{"text": "module Lib where\n\nimport qualified Numeric.LinearAlgebra as Matrix\nimport qualified Numeric.LinearAlgebra.Data as HM\n\nimport Control.Monad.Random\nimport Control.Monad.Random.Class\n\nimport Control.DeepSeq\n\nimport Control.Parallel.Strategies (parListChunk, rpar, rdeepseq, rseq, runEval, runEvalIO)\n\nimport Data.List (foldl', sort, sortBy, maximumBy, minimumBy)\n\nimport GHC.Conc (numCapabilities)\n\nimport qualified Data.ByteString.Lazy as BS (writeFile, readFile)\nimport Data.Serialize (encodeLazy, decodeLazy)\n\ndata Player = X | O deriving (Show, Ord, Eq, Enum, Read)\n\ntype Grid   = (Player, [Maybe Player])\ndata Result = Undecided | Tie | Win Player deriving Show\n\ndata Tree a = Node a [Tree a] deriving (Show)\n\nshowGrid :: Grid -> String\nshowGrid (_, xs) = \" \" ++ x00 ++ \" | \" ++ x01 ++ \" | \" ++ x02 ++ \"\\n\" ++\n                   \"-----------\" ++ \"\\n\" ++\n                   \" \" ++ x10 ++ \" | \" ++ x11 ++ \" | \" ++ x12 ++ \"\\n\" ++\n                   \"-----------\" ++ \"\\n\" ++\n                   \" \" ++ x20 ++ \" | \" ++ x21 ++ \" | \" ++ x22 ++ \"\\n\"\n    where\n        [x00, x01, x02, x10, x11, x12, x20, x21, x22] =\n            map (\\x -> case x of\n                          Nothing -> \" \"\n                          Just X  -> \"X\"\n                          Just O  -> \"O\") xs\n\nmoves :: (Grid, Result) -> [(Grid, Result)]\nmoves (g@(_, xs), Undecided) = gs\n    where\n        l  = length $ filter id $ map isNothing xs\n        gs = map (\\i -> move i g) [0..l-1]\nmoves _ = []\n\ngameTree :: (Grid, Result) -> Tree (Grid, Result)\ngameTree n = Node n fs\n    where\n        fs = map gameTree $ moves n\n\nmaxMin :: RandomGen g => Tree (Grid, Result) -> Rand g (Maybe ((Grid, Result), Int))\nmaxMin (Node _ []) = return Nothing\nmaxMin (Node n fs) = case mms of\n                        [] -> return Nothing\n                        _  -> do\n                               i <- getRandomR (0, length maxScores - 1)\n                               return (Just $ maxScores !! i)\n    where\n        mms = map minMax' fs\n        maxScore  = maximum $ map snd mms\n        maxScores = filter ((==maxScore) . snd) mms\n\nmaxMin' :: Tree (Grid, Result) -> ((Grid, Result), Int)\nmaxMin' (Node n@(_, Tie) []) = (n, 0)\nmaxMin' (Node n@(_, Win O) []) = (n, -1)\nmaxMin' (Node n@(_, Win X) []) = (n, 1)\nmaxMin' (Node (_, _) []) = error \"Undecided Leaf\"\nmaxMin' (Node n fs) = (n, snd $ maximumBy (\\(_, r1) (_, r2) -> r1 `compare` r2) $ map minMax' fs)\n\nminMax :: RandomGen g => Tree (Grid, Result) -> Rand g (Maybe ((Grid, Result), Int))\nminMax (Node _ []) = return Nothing\nminMax (Node n fs) = case mms of\n                        [] -> return Nothing\n                        _  -> do\n                               i <- getRandomR (0, length minScores - 1)\n                               return (Just $ minScores !! i)\n    where\n        mms = map maxMin' fs\n        minScore  = minimum $ map snd mms\n        minScores = filter ((==minScore) . snd) mms\n\nminMax' :: Tree (Grid, Result) -> ((Grid, Result), Int)\nminMax' (Node n@(_, Tie) []) = (n, 0)\nminMax' (Node n@(_, Win O) []) = (n, -1)\nminMax' (Node n@(_, Win X) []) = (n, 1)\nminMax' (Node (_, _) []) = error \"Undecided Leaf\"\nminMax' (Node n fs) = (n, snd $ minimumBy (\\(_, r1) (_, r2) -> r1 `compare` r2) $ map maxMin' fs)\n\nmoveMM :: RandomGen g => (Grid, Result) -> Rand g (Maybe (Grid, Result))\nmoveMM gr@((X, _), _) = fmap (fmap fst) . maxMin $ gameTree gr\nmoveMM gr@((O, _), _) = fmap (fmap fst) . minMax $ gameTree gr\n\nempty :: Grid\nempty = (X, take 9 $ repeat Nothing)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n [] = []\nchunksOf n xs = take n xs : chunksOf n (drop n xs)\n\nrows :: [a] -> [[a]]\nrows xs      = rs ++\n               map (\\i -> map (!!i) rs) [0,1,2] ++\n               pure (zipWith (!!) rs [0,1,2]) ++\n               pure (zipWith (!!) rs [2,1,0])\n    where\n        rs = chunksOf 3 xs\n                \n\nallSame :: Eq a => [a] -> (Bool, Maybe a)\nallSame []     = (True, Nothing)\nallSame (x:xs) = case all (==x) xs of\n                   True  -> (True, Just x)\n                   False -> (False, Nothing)\n\nisNothing :: Maybe a -> Bool\nisNothing Nothing = True\nisNothing _       = False\n\ngridResult :: Grid -> Result\ngridResult (_, xs)\n        | not (null winners) = Win $ head winners\n        | undecided          = Undecided\n        | otherwise          = Tie\n    where\n        rs = rows xs\n        rresults = map rowResult rs\n        winners = map (\\(Just x) -> x) $\n                  filter (not . isNothing) $\n                  map (\\res -> case res of\n                                 Win p -> Just p\n                                 _     -> Nothing)\n                  rresults\n        undecided = any (\\res -> case res of\n                                 Undecided -> True\n                                 _         -> False)\n                  rresults\n\n\nrowResult :: [Maybe Player] -> Result\nrowResult r = case any isNothing r of\n                True  -> Undecided\n                False -> case allSame r of\n                           (True, Just (Just p)) -> Win p\n                           _                     -> Tie\n\nemptyFields :: [Maybe a] -> [Int]\nemptyFields xs = map snd $\n                 filter (isNothing . fst) $\n                 zip xs [0..]\n\nmove :: Int -> Grid -> (Grid, Result)\nmove m (p, xs) = ((nextPlayer, nextGrid), res)\n    where\n        nextPlayer = case p of\n                       X -> O\n                       O -> X\n        empties = emptyFields xs\n        numEmpties = length empties\n        m' = m `mod` numEmpties\n        pos = empties !! m'\n        nextGrid = take pos xs ++ [Just p] ++ drop (pos+1) xs\n        res = gridResult (nextPlayer, nextGrid)\n\nmoveAI :: DenseData -> Grid -> (Grid, Result)\nmoveAI net g = move m g\n    where\n        l = fromGrid g\n        m = predict (net, [relu, softmax]) l\n\nbattle :: DenseData -> DenseData -> Maybe Player\nbattle pX pO = battle' pX pO empty\n\nbattle' :: DenseData -> DenseData -> Grid -> Maybe Player\nbattle' pX pO g@(p, _) = case moveAI ai g of\n                            (_, Tie)        -> Nothing\n                            (_, Win w)      -> Just w\n                            (g', Undecided) -> battle' pX pO g'\n    where\n        ai = case p of\n                X -> pX\n                O -> pO\n\nbattleMM' :: RandomGen g => (Grid, Result) -> Rand g [(Grid, Result)]\nbattleMM' g = do\n                g' <- moveMM g\n                case g' of\n                  Nothing  -> return [g]\n                  Just g'' -> fmap (g:) $ battleMM' g''\n\nbattleMM :: RandomGen g => Rand g [(Grid, Result)]\nbattleMM = battleMM' (empty, Undecided)\n\nloses :: DenseData -> DenseData -> Bool\nloses p1 p2 = case w1 of\n                Just O -> True\n                _      -> case w2 of\n                            Just X -> True\n                            _      -> False\n    where\n        w1 = battle p1 p2\n        w2 = battle p2 p1\n\nbeats :: DenseData -> DenseData -> Bool\nbeats p1 p2 = case w1 of\n                Just X -> case w2 of\n                            Nothing -> True\n                            Just O  -> True\n                            _       -> False\n                _      -> False\n    where\n        w1 = battle p1 p2\n        w2 = battle p2 p1\n\ntype Layer  = HM.Vector HM.R\ntype Bias   = HM.Vector HM.R\ntype Weight = HM.Matrix HM.R\ntype Activation = Layer -> Layer\n\ntype DenseData = [(Bias, Weight)]\ntype DenseNet  = (DenseData, [Activation])\n\ntype CrossingData = [(Bias, Bias, Weight, Weight)]\n\ntoFile :: String -> DenseData -> IO ()\ntoFile fileName net = BS.writeFile fileName $\n                      encodeLazy $\n                      fmap (\\(b, w) -> (HM.toList b, HM.toLists w)) net\n\nfromFile :: String -> IO DenseData\nfromFile fileName = fmap (fmap (\\(b, w) -> (HM.fromList b, HM.fromLists w)) . (\\(Right x) -> x) . decodeLazy) $\n                    BS.readFile fileName\n\nrandBias :: RandomGen g => Int -> Rand g Bias\nrandBias n = (pure . HM.fromList . take n) =<< getRandomRs (-1, 1)\n\nrandWeight :: RandomGen g => Int -> Int -> Rand g Weight\nrandWeight m n = (pure . (m HM.>< n)) =<< getRandomRs (-1, 1)\n\nrepeatM :: Monad m => Int -> m a -> m [a]\nrepeatM 0 m = pure []\nrepeatM n m =\n    do\n        x  <- m\n        xs <- repeatM (n-1) m\n        pure (x:xs)\n\ntoBinary :: (Num a, Ord a) => a -> a\ntoBinary x\n    | x < 0 = 0\n    | otherwise = 1\n\ninvert :: Num a => a -> a\ninvert x = 1-x\n\nrandCrossing :: RandomGen g => Rand g CrossingData\nrandCrossing =\n  do\n    ~[(b1, w01), (b2, w12)] <- randPlayer\n    let b1' = HM.cmap toBinary b1\n    let b2' = HM.cmap toBinary b2\n    let w01' = HM.cmap toBinary w01\n    let w12' = HM.cmap toBinary w12\n    return [(b1', HM.cmap invert b1', w01', HM.cmap invert w01'),\n            (b2', HM.cmap invert b2', w12', HM.cmap invert w12')]\n\nrandPlayer :: RandomGen g => Rand g DenseData\nrandPlayer =\n  do\n    b1 <- randBias 18\n    b2 <- randBias 9\n    w01 <- randWeight 18 18\n    w12 <- randWeight 9 18\n    return [(b1, w01), (b2, w12)]\n\nfromGrid :: Grid -> Layer\nfromGrid (_, xs) = HM.fromList $ lX ++ lO\n    where\n        lX = map (\\x -> case x of\n                          Just X -> 1\n                          _      -> 0)\n             xs\n        lO = map (\\x -> case x of\n                          Just O -> 1\n                          _      -> 0)\n             xs\n\ndense :: Bias -> Weight -> Activation -> Layer -> Layer\ndense b w a l = a $ b + (w Matrix.#> l)\n\nrelu :: Activation\nrelu = HM.cmap relu'\n    where\n        relu' x = if x < 0 then 0 else x\n\nsoftmax :: Activation\nsoftmax l = HM.cmap (/s) exps\n    where\n        m    = HM.maxElement l\n        exps = HM.cmap (\\x -> exp (x - m)) l\n        s    = sum $ HM.toList exps\n\nrunDenseNet :: DenseNet -> Layer -> Layer\nrunDenseNet (dat, acts) l =\n    foldl' (\\l' ((b, w), a) -> dense b w a l') l $ zip dat acts\n\npredict :: DenseNet -> Layer -> Int\npredict net = HM.maxIndex . runDenseNet net\n\nselect :: [DenseData] -> (Int, [DenseData])\nselect ps = (maximum scores,\n             take n' $\n             map fst $\n             sortBy (\\(_, score1) (_, score2) -> score2 `compare` score1) $\n             zip ps scores)\n    where\n        scores = runEval $\n                 parListChunk (n `div` numCapabilities) rdeepseq $\n                 fmap (\\x -> length $ filter not $ fmap (loses x) ps) ps\n        n = length ps\n        n' = n `div` 100\n\nbreed2' :: DenseData -> DenseData -> CrossingData -> DenseData\nbreed2' m f cd = map (\\((b, w), (b', w'), (cb, cb', cw, cw')) -> (b*cb + b' * cb', w*cw + w'*cw')) $ zip3 m f cd\n\nbreed2 :: RandomGen g => DenseData -> DenseData -> Rand g [DenseData]\nbreed2 m f =\n    do\n        cds <- repeatM 10 randCrossing\n        return $ fmap (breed2' m f) cds\n\nbreed :: RandomGen g => [DenseData] -> Rand g [DenseData]\nbreed ps = fmap concat $ sequence $ breed2 <$> ps <*> ps\n\ninitPopulation :: RandomGen g => Int -> Rand g [DenseData]\ninitPopulation n = repeatM n randPlayer\n\nsomeFunc :: IO ()\nsomeFunc = do\n            ps <- evalRandIO $ initPopulation 1000\n            go ps\n    where\n        go ps = let (score, fittest) = select ps\n                in do\n                     putStrLn $ show score ++ \"\\t(\" ++ show (length ps) ++ \")\"\n                     if score == 1000\n                       then return () >> (toFile \"weights.dat\" $ head fittest)\n                       else go =<< evalRandIO (breed fittest)\n", "meta": {"hexsha": "7ef6a6bbcccafd12c68f75a5aee1a8ea41711411", "size": 11256, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "nilsalex/genetic-ttt", "max_stars_repo_head_hexsha": "e7cbb3ea248c2925cb31d5f369979991486e3f66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "nilsalex/genetic-ttt", "max_issues_repo_head_hexsha": "e7cbb3ea248c2925cb31d5f369979991486e3f66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lib.hs", "max_forks_repo_name": "nilsalex/genetic-ttt", "max_forks_repo_head_hexsha": "e7cbb3ea248c2925cb31d5f369979991486e3f66", "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.2521489971, "max_line_length": 112, "alphanum_fraction": 0.493692253, "num_tokens": 3235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.499984820924629}}
{"text": "module Isumi.Math.MatrixUtil\n  ( imageToMatrix\n  ) where\n\nimport           Codec.Picture\nimport           Numeric.LinearAlgebra (Matrix)\nimport qualified Numeric.LinearAlgebra as LA\n\n-- | Convert image of Pixel8 to matrix\nimageToMatrix :: Image Pixel8 -> Matrix Double\nimageToMatrix =\n  LA.fromColumns . fmap (LA.fromList . fmap fromIntegral) . imageToPixels\n\n-- | Convert image to list of list of pixels, in column major order\nimageToPixels :: Pixel a => Image a -> [[a]]\nimageToPixels image =\n  fmap (\\c -> fmap (\\r -> pixelAt image c r) [0.. height - 1]) [0..width - 1]\n  where\n  width = imageWidth image\n  height = imageHeight image\n\n", "meta": {"hexsha": "1b04c289af3879d7ef67e17756df8f3a51b66aa4", "size": 638, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/lib/Isumi/Math/MatrixUtil.hs", "max_stars_repo_name": "IsumiF/fft-bruun", "max_stars_repo_head_hexsha": "93920f47a67f091d0451edcf32fd6032aceb2845", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-18T06:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-18T06:45:22.000Z", "max_issues_repo_path": "src/lib/Isumi/Math/MatrixUtil.hs", "max_issues_repo_name": "IsumiF/fft-bruun", "max_issues_repo_head_hexsha": "93920f47a67f091d0451edcf32fd6032aceb2845", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/Isumi/Math/MatrixUtil.hs", "max_forks_repo_name": "IsumiF/fft-bruun", "max_forks_repo_head_hexsha": "93920f47a67f091d0451edcf32fd6032aceb2845", "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.0, "max_line_length": 77, "alphanum_fraction": 0.697492163, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4994780062186209}}
{"text": "{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE RankNTypes          #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies        #-}\n{-# LANGUAGE TypeOperators       #-}\n\nmodule Grenade.Utils.OneHot (\n    oneHot\n  , hotMap\n  , makeHot\n  , unHot\n  , sample\n  ) where\n\nimport           Data.List                    (group, sort)\nimport           Data.Map                     (Map)\nimport qualified Data.Map                     as M\nimport           Data.Proxy\nimport           Data.Singletons.TypeLits\nimport           Data.Vector                  (Vector)\nimport qualified Data.Vector                  as V\nimport qualified Data.Vector.Storable         as VS\nimport           Numeric.LinearAlgebra        (maxIndex)\nimport           Numeric.LinearAlgebra.Devel\nimport           Numeric.LinearAlgebra.Static\nimport           System.Random.MWC            hiding (create)\n\nimport           Grenade.Core.Shape\nimport           Grenade.Types\n\n\n-- | From an int which is hot, create a 1D Shape\n--   with one index hot (1) with the rest 0.\n--   Rerurns Nothing if the hot number is larger\n--   than the length of the vector.\noneHot :: forall n. (KnownNat n)\n       => Int -> Maybe (S ('D1 n))\noneHot hot =\n  let len = fromIntegral $ natVal (Proxy :: Proxy n)\n  in if hot < len\n      then\n        fmap S1D . create $ runSTVector $ do\n        vec    <- newVector 0 len\n        writeVector vec hot 1\n        return vec\n      else Nothing\n\n-- | Create a one hot map from any enumerable.\n--   Returns a map, and the ordered list for the reverse transformation\nhotMap :: (Ord a, KnownNat n) => Proxy n -> [a] -> Either String (Map a Int, Vector a)\nhotMap n as =\n  let len  = fromIntegral $ natVal n\n      uniq = [ c | (c:_) <- group $ sort as]\n      hotl = length uniq\n  in if hotl == len\n      then\n        Right (M.fromList $ zip uniq [0..], V.fromList uniq)\n      else\n        Left (\"Couldn't create hotMap of size \" ++ show len ++ \" from vector with \" ++ show hotl ++ \" unique characters\")\n\n-- | From a map and value, create a 1D Shape\n--   with one index hot (1) with the rest 0.\n--   Rerurns Nothing if the hot number is larger\n--   than the length of the vector or the map\n--   doesn't contain the value.\nmakeHot :: forall a n. (Ord a, KnownNat n)\n        => Map a Int -> a -> Maybe (S ('D1 n))\nmakeHot m x = do\n  hot    <- M.lookup x m\n  let len = fromIntegral $ natVal (Proxy :: Proxy n)\n  if hot < len\n      then\n        fmap S1D . create $ runSTVector $ do\n        vec    <- newVector 0 len\n        writeVector vec hot 1\n        return vec\n      else Nothing\n\nunHot :: forall a n. KnownNat n\n      => Vector a -> S ('D1 n) -> Maybe a\nunHot v (S1D xs)\n  = (V.!?) v\n  $ maxIndex (extract xs)\n\nsample :: forall a n . (KnownNat n)\n       => RealNum -> Vector a -> S ('D1 n) -> IO a\nsample temperature v (S1D xs) = do\n  ix <- randFromList . zip [0..] . fmap (toRational . exp . (/ temperature) . log) . VS.toList . extract $ xs\n  return $ v V.! ix\n\n\n-- | Sample a random value from a weighted list.  The total weight of all\n-- elements must not be 0.\nrandFromList :: [(a,Rational)] -> IO a\nrandFromList [] = error \"OneHot.randFromList called with empty list\"\nrandFromList [(x,_)] = return x\nrandFromList xs | sumxs == 0 = error \"OneHot.randFromList sum of weights was 0\"\n                | otherwise = do\n                    r <- toRational <$> (withSystemRandom . asGenST $ \\gen -> uniformR (0, fromRational sumxs :: RealNum) gen)\n                    return . fst . head $ dropWhile ((< r) . snd) cs\n  where sumxs = sum (map snd xs)\n        cs = scanl1 (\\(_,q) (y,s') -> (y, s'+q)) xs -- cumulative weight\n", "meta": {"hexsha": "93ff9d9fb7be442dfc8664e301d84db19a76b73a", "size": 3687, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Utils/OneHot.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Utils/OneHot.hs", "max_issues_repo_name": "schnecki/grenade", "max_issues_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Utils/OneHot.hs", "max_forks_repo_name": "schnecki/grenade", "max_forks_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-02T01:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:08:47.000Z", "avg_line_length": 35.1142857143, "max_line_length": 126, "alphanum_fraction": 0.5809601302, "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49947798287759204}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n{-\n\nA lot of error handling needs to be added to the code. For example\n0 < hopsize < windowsize < fftsize needs to be reinforced.\nCode currently just throws exceptions. Maybe change to something like;\nhttp://www.mega-nerd.com/erikd/Blog/CodeHacking/Haskell/what_do_you_mean.html\n\n-}\n\nmodule STFT (\n\n    stft\n  , readWav\n  , writeWav\n  , stftSynth  \n  , hammingC\n\n  ) where\n\nimport System.IO (writeFile)\nimport Data.WAVE\nimport Window\nimport qualified Data.Vector.Generic as V\nimport Numeric.FFT.Vector.Invertible\nimport Data.Vector\nimport qualified Data.Complex as C\nimport Data.Bifunctor (first)\nimport Data.Vector.Split (divvy)\n\nepsilon = 2.2204460492503131e-16\n\n-- This code from the Linear.Epsilon library\n-- by Edward Kmett. There were some dependency conflicts\n-- so I just copied it in. Will fix.\nclass Num a => Epsilon a where\n  -- | Determine if a quantity is near zero.\n  nearZero :: a -> Bool\n\n-- | @'abs' a '<=' 1e-6@\ninstance Epsilon Float where\n  nearZero a = abs a <= 1e-6\n\n-- | @'abs' a '<=' 1e-12@\ninstance Epsilon Double where\n  nearZero a = abs a <= 1e-12\n\ntype MagSpect = Vector Double -- Magnitude Spectrum\n\ntype PhaseSpect = Vector Double -- Phase Spectrum\n\ntype CSignal = Vector (C.Complex Double) -- Complex Signal\n\ntype Signal = Vector Double \n\ntype FFTsz = Int -- Should be Greater than 0 and a power of 2\n\ntype Hopsz = Int -- Should be about 1/4 the fft sz\n\ntype Path = String\n\ntype Winsz = Int -- Should be an odd number and smaller than FFTsz\n\n\n-- Phase unwrapping algorithm.\n-- Converting to and from list for pattern matching is a little cumbersome.\n-- See this post for possible improvement;\n-- http://stackoverflow.com/questions/36993937/haskell-pattern-matching-on-vectors\nunwrap :: PhaseSpect -> PhaseSpect\nunwrap xs = fromList $ diff (toList xs) 0 where\n  diff (x:y:ys) accm\n    | (y+accm) - x > pi    = x: diff (y+accm-(2*pi):ys) (accm-(2*pi))\n    | (y+accm) - x < (-pi) = x: diff (y+accm+(2*pi):ys) (accm+(2*pi))\n    | otherwise             = x: diff (y+accm:ys) accm\n  diff [x] _     = [x]\n  diff []  _     = []\n\n\n-- Takes a complex signal and fftsz does zero phase windows\nzeroPhaseWindow :: CSignal -> FFTsz -> CSignal\nzeroPhaseWindow xs fftsz = let win = V.length xs\n                               hM1 = floor $ fromIntegral (win + 1) / 2\n                               hM2 = floor $ (fromIntegral win) / 2\n                               zs = V.replicate (fftsz-hM1-hM2) (c 0)\n                            in V.concat [(V.slice hM2 hM1 xs), zs, \n                                         (V.slice 0 hM2 xs)]\n\n\n-- Normalize signal to 0 Db.\nnormTo0Db :: Vector (Double,Double) -> Vector (Double, Double)\nnormTo0Db xs = V.map (first ((-) (fst $ V.maximumBy compare xs))) xs\n\n-- Next power of 2 greater than n.\npo2gtn :: Int -> Int\npo2gtn n = 2^(ceiling $ logBase 2 (fromIntegral n))\n\nisPo2 :: (Ord a, Fractional a) => a -> Bool\nisPo2 x\n  | x > 2     = isPo2 (x / 2)\n  | x == 2    = True\n  | otherwise = False\n\n-- Calculates the magnitude spectrum in Db\nmagSpect :: CSignal -> MagSpect\nmagSpect vec = V.map (dB.(near0).(C.magnitude)) vec where\n  dB x = 20 * (logBase 10 x)\n  near0 x = if nearZero x then epsilon else x\n\n-- Calculates the phase spectrum\nphaseSpect :: CSignal -> PhaseSpect\nphaseSpect vec = unwrap $ V.map ((C.phase).to0) vec where\n  to0 x = go (C.realPart x) (C.imagPart x)\n  go x y | nearZero x && nearZero y = (0 C.:+ 0)\n         | nearZero x               = (0 C.:+ y)\n         | nearZero y               = (x C.:+ 0)\n         | otherwise                = (x C.:+ y)\n\n\n-- Takes a windowed signal and FFT size returns a vector of tuples\n-- (Magnitude, Phase). Magnitude in Db, phase unwrapped, both positve\n-- half of the spectrum.\ndftAnal :: FFTsz -> CSignal -> (MagSpect, PhaseSpect)\ndftAnal fftsz winSig = (mag, phase) where\n    inputVec = zeroPhaseWindow winSig fftsz\n    hN = fftsz `div` 2 + 1\n    trsf :: Vector (C.Complex Double)\n    trsf = V.slice 0 hN (run dft inputVec)\n    mag = magSpect trsf\n    phase = phaseSpect trsf\n\n\n-- Takes an input signal, a window, an fftsize and a hop size and\n-- computes the short time Fourier transform, returning a list of\n-- (vector of magnitude, vector of phase)\nstft :: Signal -> CWindow ->\n  FFTsz -> Hopsz -> [(MagSpect, PhaseSpect)]\nstft dsig win fftsz hopsz = let sig = V.map c dsig -- Convert to complex\n                                winsz = V.length win\n                                wdiv = V.sum win\n                                w = V.map (/wdiv) win -- Normalize window function\n                                halfWin = floor $ (fromIntegral winsz) / 2\n                                zs = V.replicate halfWin (c 0)\n                                sigzs = V.concat [zs, sig, zs]\n                                splitSig = divvy winsz hopsz sigzs\n                             in fmap ((dftAnal fftsz).(V.zipWith (*) w)) splitSig\n\n\n-- Takes a vector of tuples (Magnitude, Phase) and a window size\n-- and returns the original signal\ndftSynth :: Winsz -> (MagSpect, PhaseSpect) -> Signal\ndftSynth win (magVec, phaseVec) = let vec = V.zipWith (\\x y -> (x, y)) magVec phaseVec \n                                      hN = V.length vec\n                                      n = (hN-1)*2\n                                      hM1 = floor $ fromIntegral (win+1) / 2\n                                      hM2 = floor $ fromIntegral win / 2\n                                      posFreqs = V.map f vec where\n                                        f (mag, phase) = (10**(mag/20) C.:+ 0) *\n                                                         (exp ((phase C.:+ 0) *\n                                                         (0 C.:+ 1)))\n                                      negFreqs = ((V.map f) . V.reverse) (g vec) where\n                                        g = (V.init . V.tail)\n                                        f (mag, phase) = (10**(mag/20) C.:+ 0) *\n                                                         (exp ((phase C.:+ 0) *\n                                                         (0 C.:+ (-1))))\n                                      x = (run idft (posFreqs V.++ negFreqs))\n                                  in V.map C.realPart $ V.concat [(V.slice (V.length x - hM2) hM2 x), (V.take hM1 x)]\n\n\nstftSynth :: [(MagSpect, PhaseSpect)] -> Hopsz -> Winsz -> Signal\nstftSynth magphase hopsz winsz = let hM1 = floor $ fromIntegral (winsz+1) / 2\n                                     hM2 = floor $ fromIntegral winsz / 2\n                                     signalFrames = fmap ((V.map ((fromIntegral hopsz)*)).(dftSynth winsz)) magphase\n                                     signalTuples = fmap (V.splitAt hM1) signalFrames\n                                     overlapAdd (x1, x2) (y1, y2) = (x1 V.++ (V.zipWith (+) x2 y1), y2)\n                                  in V.drop hM1 $ fst (Prelude.foldl overlapAdd\n                                        (Prelude.head signalTuples) (Prelude.tail signalTuples))  \n\n-- Takes a vector of doubles, the sample frequency, and a name\n-- and writes the audio file. Written in 32 bit.\nwriteWav :: Signal -> Int -> String -> IO ()\nwriteWav vec sf name = let samples = fmap ((:[]) . doubleToSample) (V.toList vec)\n                           header = WAVEHeader 1 sf 32 Nothing\n                       in putWAVEFile name (WAVE header samples)\n\n-- Takes a Path and returns IO (sampling frequency, Vector signal).\nreadWav :: Path -> IO (Int, Signal)\nreadWav path = do\n  audio <- getWAVEFile \"singing-female.wav\"\n  let header = waveHeader audio\n      samples = waveSamples audio\n      channels = waveNumChannels header\n      sampRate = waveFrameRate header\n  case channels of\n    1 -> let sig = fromList $ fmap (sampleToDouble.(Prelude.head)) samples\n          in return $ (sampRate, sig)\n    _ -> error \"Should be mono.\"\n\n", "meta": {"hexsha": "ffcada2d5c154eb68638c1c9baecb4ac5f4c7a8e", "size": 7845, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/STFT.hs", "max_stars_repo_name": "davlum/haskell-stft", "max_stars_repo_head_hexsha": "4e6826621427c43fb80fb03aa43fbb218d0d86bb", "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/STFT.hs", "max_issues_repo_name": "davlum/haskell-stft", "max_issues_repo_head_hexsha": "4e6826621427c43fb80fb03aa43fbb218d0d86bb", "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/STFT.hs", "max_forks_repo_name": "davlum/haskell-stft", "max_forks_repo_head_hexsha": "4e6826621427c43fb80fb03aa43fbb218d0d86bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.225, "max_line_length": 117, "alphanum_fraction": 0.5518164436, "num_tokens": 2131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4992775645990493}}
{"text": "module Numeric.Network where\nimport Data.Kind\nimport Dependent.Size\nimport Numeric.Layer\nimport Numeric.Vector.Sized\nimport Numeric.Loss\n\ninfixr 0 :~>\n\ntype family NetworkOutput (layers :: [Type]) where\n  NetworkOutput '[x] = Outputs x\n  NetworkOutput (x ': y ': rest) = NetworkOutput (y ': rest)\n\ntype family NetworkInput (layers :: [Type]) where\n  NetworkInput (x ': _) = Inputs x\n\ndata Network (layers :: [Type]) where\n  Last :: Layer x => x -> Network '[x]\n  (:~>) :: (Layer x, Outputs x ~ Inputs y) => x -> Network (y:xs) -> Network (x : y : xs)\n\ninstance (Show x) => Show (Network '[x]) where\n  showsPrec n (Last g) = showsPrec n g\ninstance (Show x, Show (Network (y:xs))) => Show (Network (x:y:xs)) where\n  showsPrec n (layer :~> net) = showsPrec n layer . showString \" :~> \" . showsPrec n net\n\ninfixr 0 :|>\ndata Tapes (layers :: [Type]) where\n  LastTape :: Layer x => Tape x -> Tapes '[x]\n  (:|>) :: (Layer x, Outputs x ~ Inputs y) => Tape x -> Tapes (y:xs) -> Tapes (x:y:xs)\n\ninstance (Show (Tape x)) => Show (Tapes '[x]) where\n  showsPrec n (LastTape g) = showsPrec n g\ninstance (Show (Tape x), Show (Tapes (y:xs))) => Show (Tapes (x:y:xs)) where\n  showsPrec n (tape :|> tapes) = showsPrec n tape . showString \" :|> \" . showsPrec n tapes\n\ninfixr 0 :<|\ndata Gradients (layers :: [Type]) where\n  LastGradient :: Layer x => Gradient x -> Gradients '[x]\n  (:<|) :: (Layer x, Outputs x ~ Inputs y) => Gradient x -> Gradients (y:xs) -> Gradients (x : y : xs)\n\ninstance (Show (Gradient x)) => Show (Gradients '[x]) where\n  showsPrec n (LastGradient g) = showsPrec n g\ninstance (Show (Gradient x), Show (Gradients (y:xs))) => Show (Gradients (x:y:xs)) where\n  showsPrec n (grad :<| grads) = showsPrec n grad . showString \" :<| \" . showsPrec n grads\n\npredict\n  :: Network layers\n  -> SizedArray (NetworkInput layers)\n  -> SizedArray (NetworkOutput layers)\npredict (Last layer ) x = fst (forward layer x)\npredict (layer:~>net) x = predict net y where y = fst (forward layer x)\n\npredict'\n  :: Network layers\n  -> SizedArray (NetworkInput layers)\n  -> (SizedArray (NetworkOutput layers), Tapes layers)\npredict' (Last layer) x = let (y, tape) = forward layer x in (y, LastTape tape)\npredict' (layer:~>net) x =\n  let (y, tape) = forward layer x\n  in  let (z, tapes) = predict' net y in (z, tape :|> tapes)\n\nbackprop\n  :: Network layers\n  -> Tapes layers\n  -> SizedArray (NetworkOutput layers)\n  -> (Gradients layers, SizedArray (NetworkInput layers))\nbackprop (Last layer) (LastTape tape) dy =\n  let (grad, dx) = backward layer tape dy in (LastGradient grad, dx)\nbackprop (layer:~>net) (tape:|>tapes) dz =\n  let (grads, dy) = backprop net tapes dz\n  in  let (grad, dx) = backward layer tape dy in (grad :<| grads, dx)\n\nbackpropagation\n  :: (Loss (NetworkOutput layers) loss)\n  => Network layers\n  -> loss\n  -> SizedArray (NetworkInput layers)\n  -> SizedArray (NetworkOutput layers)\n  -> (Gradients layers, SizedArray (NetworkInput layers))\nbackpropagation net loss x target = backprop net tapes dy\n  where\n    (y, tapes) = predict' net x\n    dy         = lossDerivative loss y target\n\nlearn :: Network layers -> Gradients layers -> Network layers\nlearn (Last layer ) (LastGradient grad) = Last (applyGradient layer grad)\nlearn (layer:~>net) (grad:<|grads     ) = applyGradient layer grad :~> learn net grads\n\ntrain\n  :: (Loss (NetworkOutput layers) loss)\n  => Network layers\n  -> loss\n  -> SizedArray (NetworkInput layers)\n  -> SizedArray (NetworkOutput layers)\n  -> Network layers\ntrain net loss x t = f $ backpropagation net loss x t\n  where f (gradients, _) = learn net gradients\n\n-- A network is a layer\ninstance Layer (Network layers) where\n  type Inputs (Network layers) = NetworkInput layers\n  type Outputs (Network layers) = NetworkOutput layers\n  type Gradient (Network layers) = Gradients layers\n  type Tape (Network layers) = Tapes layers\n  forward = predict'\n  backward = backprop\n  applyGradient = learn\n", "meta": {"hexsha": "2f913e01575a91e0adc9360a56a9517d4746984b", "size": 3913, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Network.hs", "max_stars_repo_name": "mixed-signals/mixed-signals", "max_stars_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/Network.hs", "max_issues_repo_name": "mixed-signals/mixed-signals", "max_issues_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "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/Numeric/Network.hs", "max_forks_repo_name": "mixed-signals/mixed-signals", "max_forks_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2314814815, "max_line_length": 102, "alphanum_fraction": 0.6690518784, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.499083689178397}}
{"text": "module STCR2Z2T0S0PointSetBinary where\n\nimport           Control.Arrow\nimport           Control.Monad\nimport           Data.Array.Repa         as R\nimport           Data.Binary             (encodeFile, decodeFile)\nimport           Data.Complex\nimport           Data.List               as L\nimport           DFT.Plan\nimport           Filter.Utils\nimport           FokkerPlanck.MonteCarlo\nimport           FokkerPlanck.Pinwheel\nimport           Image.Edge\nimport           Image.IO\nimport           STC\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Text.Printf\nimport           Types\nimport           Utils.Array\nimport           Utils.Parallel\n\n\nmain = do\n  args@(numPointStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:taoStr:numTrailStr:maxTrailStr:thetaFreqsStr:scaleFreqsStr:hollowRadiusStr:cutoffRadiusStr:histFilePath:filterFileFolder:numIterationStr:writeSourceFlagStr:saveEdgeDataFlagStr:loadEdgeDataFlagStr:shape2DStr:useFFTWWisdomFlagStr:fftwWisdomFileName:batchSizeStr:numThreadStr:_) <-\n    getArgs\n  print args\n  let numPoint = read numPointStr :: Int\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      maxScale = read maxScaleStr :: Double\n      tao = read taoStr :: Double\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      thetaFreq = read thetaFreqsStr :: Double\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      scaleFreq = read scaleFreqsStr :: Double\n      scaleFreqs = [-scaleFreq .. scaleFreq]\n      hollowRadius = read hollowRadiusStr :: Double\n      cutoffRadius = read cutoffRadiusStr :: Double\n      numIteration = read numIterationStr :: Int\n      writeSourceFlag = read writeSourceFlagStr :: Bool\n      saveEdgeDataFlag = read saveEdgeDataFlagStr :: Bool\n      loadEdgeDataFlag = read loadEdgeDataFlagStr :: Bool\n      shape2D@(Points _ minDist _) = read shape2DStr :: Points Shape2D\n      useFFTWWisdomFlag = read useFFTWWisdomFlagStr :: Bool\n      batchSize = read batchSizeStr :: Int\n      numThread = read numThreadStr :: Int\n      parallelParams = ParallelParams numThread batchSize\n      folderPath = \"output/test/STCR2Z2T0S0PointSetBinary\"\n      fftwWisdomFilePath = folderPath </> fftwWisdomFileName\n      filterFileName =\n        printf\n          \"Filter_%.0f_%.0f_%s\"\n          hollowRadius\n          cutoffRadius\n          (takeFileName histFilePath)\n      filterFilePath = filterFileFolder </> filterFileName\n      eigenVecFilePath = printf \"%s/EigenVec.dat\" filterFileFolder\n  createDirectoryIfMissing True folderPath\n  createDirectoryIfMissing True filterFileFolder\n  plan <-\n    makePlanBinary\n      emptyPlan\n      useFFTWWisdomFlag\n      fftwWisdomFilePath\n      (L.length thetaFreqs)\n      (L.length scaleFreqs)\n      numPoint\n      numPoint\n  filterFlag <- doesFileExist filterFilePath\n  flag <-\n    if filterFlag\n      then do\n        size <- getFileSize filterFilePath\n        return $\n          if size == 0\n            then False\n            else True\n      else return False\n  unless\n    flag\n    (do histFlag <- doesFileExist histFilePath\n        radialArr <-\n          if histFlag\n            then R.map magnitude . getNormalizedHistogramArr <$>\n                 decodeFile histFilePath\n            else do\n              putStrLn\n                \"Couldn't find a Green's function data. Start simulation...\"\n              solveMonteCarloR2Z2T0S0Radial\n                numThread\n                numTrail\n                maxTrail\n                numPoint\n                numPoint\n                thetaSigma\n                scaleSigma\n                maxScale\n                tao\n                thetaFreqs\n                thetaFreqs\n                scaleFreqs\n                scaleFreqs\n                histFilePath\n                (emptyHistogram\n                   [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n                   , L.length scaleFreqs\n                   , L.length thetaFreqs\n                   , L.length scaleFreqs\n                   , L.length thetaFreqs\n                   ]\n                   0)\n        putStrLn \"Write filter to disk...\"\n        writeDFTPinwheel \n          parallelParams\n          plan\n          radialArr\n          hollowRadius\n          cutoffRadius\n          thetaFreqs\n          scaleFreqs\n          maxScale\n          (numPoint, numPoint)\n          filterFilePath)\n  let pointSet = makeShape2D shape2D\n      points =\n        L.map (\\(x, y) -> R2S1RPPoint (x, y, 0, 1)) . getShape2DIndexList $\n        pointSet\n      bias = computeBiasR2T0S0 numPoint numPoint thetaFreqs scaleFreqs points\n      eigenVec =\n        computeInitialEigenVectorBinary\n          numPoint\n          numPoint\n          thetaFreqs\n          scaleFreqs\n          points\n  eigenVec <-\n    if loadEdgeDataFlag\n      then readRepaArray eigenVecFilePath\n      else return $\n           computeInitialEigenVectorBinary\n             numPoint\n             numPoint\n             thetaFreqs\n             scaleFreqs\n             points\n  powerMethodBinary\n    parallelParams\n    plan\n    folderPath\n    numPoint\n    numPoint\n    numOrientation\n    thetaFreqs\n    numScale\n    scaleFreqs\n    maxScale\n    filterFilePath\n    numIteration\n    writeSourceFlag\n    (printf\n       \"_%.2f_%.2f_%d_%d_%d_%d\"\n       thetaSigma\n       scaleSigma\n       (round maxScale :: Int)\n       (round tao :: Int)\n       (round thetaFreq :: Int)\n       (round scaleFreq :: Int))\n    saveEdgeDataFlag\n    eigenVecFilePath\n    bias\n    eigenVec\n", "meta": {"hexsha": "32bade955b80f08d2e9cf58b6863af26ca08d2c4", "size": 5677, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2Z2T0S0PointSetBinary/STCR2Z2T0S0PointSetBinary.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/STCR2Z2T0S0PointSetBinary/STCR2Z2T0S0PointSetBinary.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/STCR2Z2T0S0PointSetBinary/STCR2Z2T0S0PointSetBinary.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 32.0734463277, "max_line_length": 368, "alphanum_fraction": 0.6071868945, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4989219535183192}}
{"text": "-- {-# LANGUAGE AllowAmbiguousTypes                      #-}\n{-# LANGUAGE BangPatterns                             #-}\n{-# LANGUAGE DataKinds                                #-}\n{-# LANGUAGE DeriveGeneric                            #-}\n{-# LANGUAGE FlexibleContexts                         #-}\n{-# LANGUAGE FlexibleInstances                        #-}\n{-# LANGUAGE GADTs                                    #-}\n{-# LANGUAGE LambdaCase                               #-}\n{-# LANGUAGE PartialTypeSignatures                    #-}\n{-# LANGUAGE PatternSynonyms                          #-}\n{-# LANGUAGE RankNTypes                               #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE TupleSections                            #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# LANGUAGE ViewPatterns                             #-}\n{-# OPTIONS_GHC -Wno-incomplete-patterns              #-}\n{-# OPTIONS_GHC -Wno-orphans                          #-}\n{-# OPTIONS_GHC -Wno-unused-top-binds                 #-}\n{-# OPTIONS_GHC -fno-warn-orphans                     #-}\n{-# OPTIONS_GHC -fno-warn-partial-type-signatures     #-}\n{-# OPTIONS_GHC -fwarn-redundant-constraints          #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Extra.Solver    #-}\n-- {-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n-- {-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise       #-}\n\nmodule Main where\nimport           Control.DeepSeq\nimport           Control.Exception\nimport           Control.Monad\nimport           Control.Monad.IO.Class\nimport           Control.Monad.Trans.Maybe\nimport           Control.Monad.Trans.State\nimport           Data.Bitraversable\nimport           Data.Foldable\nimport           Data.IDX\nimport           Data.List.Split\nimport           Data.Maybe\nimport           Data.Proxy\nimport           Data.Time.Clock\nimport           Data.Traversable\nimport           Data.Tuple\nimport           GHC.Generics                        (Generic)\nimport           GHC.TypeLits\nimport           GHC.TypeLits.Extra\nimport           Lens.Micro                          hiding ((&))\nimport           Mnist.Internal.Convolution\nimport           Numeric.Backprop                    hiding ((:&))\nimport           Numeric.LinearAlgebra.Static.Backprop                          -- hmatrix-backprop\nimport           Numeric.LinearAlgebra.Static.Vector (vecL, vecR, lVec, rVec)\nimport           Numeric.OneLiner\nimport           Text.Printf\nimport qualified Data.Vector                         as V\nimport qualified Data.Vector.Generic                 as VG\nimport qualified Data.Vector.Storable.Sized          as SVS\nimport qualified Data.Vector.Unboxed                 as VU\nimport qualified Numeric.LinearAlgebra               as HM  -- non-backprop hmatrix\nimport qualified Numeric.LinearAlgebra.Data          as HMD\nimport qualified Numeric.LinearAlgebra.Static        as HMS -- hmatrix with type-checked operations :D\nimport qualified System.Random.MWC                   as MWC\nimport qualified System.Random.MWC.Distributions     as MWC\nimport Debug.Trace\n\ntype Model p a b = forall z. Reifies z W\n  => BVar z p\n  -> BVar z a\n  -> BVar z b\n\n-- Custom data type for a tuple with strict values\ndata a :& b = !a :& !b\n  deriving (Show, Generic)\ninfixr 2 :&\n\n-- Do we actually need this? BVar already defines a similar instance\ninstance (NFData a, NFData b) => NFData (a :& b)\n  where rnf (a :& b) = force a `seq` force b `seq` ()\n\ninstance (Num a, Num b) => Num (a :& b) where\n    (+)         = gPlus\n    (-)         = gMinus\n    (*)         = gTimes\n    negate      = gNegate\n    abs         = gAbs\n    signum      = gSignum\n    fromInteger = gFromInteger\n\ninstance (Fractional a, Fractional b) => Fractional (a :& b) where\n    (/) = gDivide\n    recip = gRecip\n    fromRational = gFromRational\n\ninstance (Backprop a, Backprop b) => Backprop (a :& b)\n\ninstance (MWC.Variate a, MWC.Variate b, Num a, Num b) => MWC.Variate (a :& b) where\n    uniform g = (:&) <$> MWC.uniform g <*> MWC.uniform g\n    uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance KnownNat n => MWC.Variate (R n) where\n    uniform g = HMS.randomVector <$> MWC.uniform g <*> pure HMS.Uniform\n    uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance (KnownNat m, KnownNat n) => MWC.Variate (L m n) where\n    uniform g = HMS.uniformSample <$> MWC.uniform g <*> pure 0 <*> pure 1\n    uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\n-- So if we have a BVar z (a :& b) (a BVar containing a tuple), then matching on (x :&& y) will give us x :: BVar z a and y :: BVar z b.\npattern (:&&) :: (Backprop a, Backprop b, Reifies z W)\n              => BVar z a -> BVar z b -> BVar z (a :& b)\npattern x :&& y <- (\\xy -> (xy ^^. t1, xy ^^. t2)->(x, y))\n  where\n    (:&&) = isoVar2 (:&) (\\case x :& y -> (x, y))\n{-# COMPLETE (:&&) #-}\n\n-- Just some lenses to help us get BVars out of the tuple\nt1 :: Lens (a :& b) (a' :& b) a a'\nt1 f (x :& y) = (:& y) <$> f x\n{-# INLINE t1 #-}\n\nt2 :: Lens (a :& b) (a :& b') b b'\nt2 f (x :& y) = (x :&) <$> f y\n{-# INLINE t2 #-}\n\nfeedForward\n    :: (KnownNat i, KnownNat o)\n    => Model (L o i :& R o) (R i) (R o)\nfeedForward (w :&& b) x = w #> x + b\n{-# INLINE feedForward #-}\n\nconvolution\n  :: ( KnownNat kernelSize\n     , KnownNat filters\n     , KnownNat stride\n     , KnownNat inputRows\n     , KnownNat inputCols\n     , KnownNat (kernelSize * kernelSize * channels)\n     , KnownNat (inputRows * channels)\n     , KnownNat (((Div (inputRows - filters) stride) + 1) * filters)\n     , KnownNat (((Div (inputCols - filters) stride) + 1))\n     )\n     -- | These proxies introduce type variables into the scope\n     --   so GHC can do type level arithmetic to infer the Model types\n     -- | Example: convolution (Proxy @3) (Proxy @12) (Proxy @1) (Proxy @28) (Proxy @28) (Proxy @1)\n     --   will return a function of type Model (L 9 12) (L 28 28) (L 204 17)\n     => Proxy kernelSize\n     -> Proxy filters\n     -> Proxy stride\n     -> Proxy inputRows\n     -> Proxy inputCols\n     -> Proxy channels\n     -> Model\n        (L (kernelSize * kernelSize * channels) filters) -- TODO: Add bias\n        (L (inputRows * channels) inputCols)\n        (L (((Div (inputRows - filters) stride) + 1) * filters) ((Div (inputCols - filters) stride) + 1))\nconvolution k' fs' st' ix' iy' cs' =\n  liftOp2 . op2 $ \\kernel input ->\n\n    -- natVal \"reflects\" the type level Nat into a term level Int.\n    -- Example: for ix' (input rows) this works because we told the type checker that the function argument ix' is a Proxy of a type\n    -- that has a KnownNat constraint. So the type level Nat is brought into scope when we pass Proxy @28 (which is sugar for Proxy :: Proxy 28)\n    -- Hyperparameters as types. Neat.\n    let ix = fromIntegral $ natVal ix'\n        iy = fromIntegral $ natVal iy'\n        kx = fromIntegral $ natVal k'\n        ky = fromIntegral $ natVal k'\n        sx = fromIntegral $ natVal st'\n        sy = fromIntegral $ natVal st'\n        ox = ((ix - (fromIntegral $ natVal fs')) `div` sx) + 1\n        oy = ((iy - (fromIntegral $ natVal fs')) `div` sx) + 1\n        ex = HMS.extract input\n        ek = HMS.extract kernel\n\n        -- Transform the 3D input matrix into a (W*H, K*K*D) matrix\n        c  = vid2col kx ky sx sy ix iy ex\n    in\n\n    (\n      -- FORWARD PASS\n      -- This is the actual \"convolution\"\n      let mt = c HM.<> ek\n          -- Stretch the image back to the output dimensions\n          r  = col2vid 1 1 1 1 ox oy mt\n      in\n          fromJust . HMS.create $ r\n\n    , -- BACKWARD PASS (see backprop ops for more info)\n      \\dzdy ->\n        let eo = HMS.extract dzdy\n\n            -- what is this actually doing?\n            -- should be taking output from forward pass and reshaping it\n            -- so we can do convolutions via matrix mult\n            vs = vid2col 1 1 1 1 ox oy eo\n\n            -- TODO: Gradient for weights -- I cannot get this to work -- WHY?\n            -- It currently only works when filters === kernelSize -- wat\n            dW = HM.tr c HM.<> vs\n\n            -- Gradient for input -- This seems to work fine\n            -- convolve (via matrix mult) output with transposed weights matrix http://soumith.ch/ex/pages/2014/08/07/why-rotate-weights-convolution-gradient/\n            dX' = vs HM.<> HM.tr ek\n            dX = col2vid kx ky sx sy ix iy dX' -- stretch back into image dimensions\n        in\n            -- trace (\"convolution backwards\") (fromJust . HMS.create $ dW, fromJust . HMS.create $ dX)\n            (fromJust . HMS.create $ dW, fromJust . HMS.create $ dX)\n    )\n{-# INLINE convolution #-}\n\nflattenLayer :: (KnownNat o, KnownNat i, KnownNat (o * i), Reifies s W) => BVar s (L o i) -> BVar s (R (o * i))\nflattenLayer = liftOp1 . op1 $ \\input ->\n  (\n    let ex = HMS.extract input\n        flattened = HMD.flatten ex\n        result = fromJust . HMS.create $ flattened\n      in\n        -- trace \"flatten forwards\" result\n        result\n  ,\n    \\dzdy ->\n      let ex = HMS.extract dzdy\n          ei = HMS.extract input\n        in\n          -- trace (\"flatten backwards\") fromJust . HMS.create $ HMD.reshape (HMD.cols ei) ex\n          fromJust . HMS.create $ HMD.reshape (HMD.cols ei) ex\n  )\n{-# INLINE flattenLayer #-}\n\n-- TODO Add type annotation?\nconvLayer k fs st ix io cs p = vmap reLU . flattenLayer . convolution k fs st ix io cs p\n{-# INLINE convLayer #-}\n\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n{-# INLINE logistic #-}\n\nfeedForwardLog\n    :: (KnownNat i, KnownNat o)\n    => Model (L o i :& R o) (R i) (R o)\nfeedForwardLog wb = logistic . feedForward wb\n{-# INLINE feedForwardLog #-}\n\nreLU :: (Num a, Ord a) => a -> a\nreLU x | x < 0     = 0\n       | otherwise = x\n{-# INLINE reLU #-}\n\nfeedForwardReLU\n    :: (KnownNat i, KnownNat o)\n    => Model (L o i :& R o) (R i) (R o)\nfeedForwardReLU wb = vmap reLU . feedForward wb\n{-# INLINE feedForwardReLU #-}\n\nsoftMax :: (KnownNat n, Reifies s W) => BVar s (R n) -> BVar s (R n)\nsoftMax x = konst (1 / sumElements expx) * expx\n   where\n      expx = exp x\n{-# INLINE softMax #-}\n\nfeedForwardSoftMax\n    :: (KnownNat i, KnownNat o)\n    => Model (L o i :& R o) (R i) (R o)\nfeedForwardSoftMax wb = softMax . feedForward wb\n{-# INLINE feedForwardSoftMax #-}\n\ncrossEntropy\n   :: (KnownNat n, Reifies s W)\n   => R n\n   -> BVar s (R n)\n   -> BVar s Double\ncrossEntropy !targ !res = -(log res <.> constVar targ)\n{-# INLINE crossEntropy #-}\n\nnetErr\n   :: forall m n o p s. (KnownNat o, Reifies s W)\n   => Model p (L m n) (R o)\n   -> L m n\n   -> R o\n   -> BVar s p\n   -> BVar s Double\nnetErr f !x !targ !p = crossEntropy targ $ f p $ auto x\n{-# INLINE netErr #-}\n\ntrainModel\n   :: forall m n o p. (KnownNat o, Backprop p, Fractional p)\n   => Double                -- ^ learning rate\n   -> Model p (L m n) (R o)\n   -> p                     -- ^ initial params\n   -> [(L m n, R o)]        -- ^ input and target pairs\n   -> p                     -- ^ trained params\ntrainModel r f = foldl' (\\p (x,y) -> p - realToFrac r * gradBP (netErr f x y) p)\n{-# INLINE trainModel #-}\n\ntestNet\n   :: forall m n o p. (KnownNat o)\n   => Model p (L m n) (R o)\n   -> p\n   -> [(L m n, R o)]\n   -> Double\ntestNet f !p !xs = sum (map (uncurry test) xs) / fromIntegral (length xs)\n   where\n      test :: L m n -> R o -> Double -- test if the max index is correct\n      -- second argument here is using ViewPatterns extension of GHC\n      test x (HMS.extract->t)\n         | HM.maxIndex t == HM.maxIndex (HMS.extract r) = 1\n         | otherwise                                    = 0\n         where\n            r :: R o\n            r = evalBP2 f p x\n\n-- Given two Models, we can define the composition of them both\n-- as long as their input/output shapes match\n(<~)\n    :: (Backprop p, Backprop q)\n    => Model  p       b c\n    -> Model       q  a b\n    -> Model (p :& q) a c\n(f <~ g) (p :&& q) = f p . g q\ninfixr 8 <~\n{-# INLINE (<~) #-}\n\n-- The type wildcard here means GHC should infer the type of the model params\n-- We could define it but then we'd have to update it manually every time we add a new \"layer\" here\n-- Each layer's parameters (weights + bias) are tupled together so we can pattern match on them (see <~ operator above)\nmodel :: Model _ (L 28 28) (R 10)\nmodel =\n   feedForwardSoftMax @100 @10\n   <~ feedForwardLog @500 @100\n   <~ feedForwardLog @2028 @500\n   <~ convLayer (Proxy @3) (Proxy @3) (Proxy @1) (Proxy @28) (Proxy @28) (Proxy @1)\n{-# INLINE model #-}\n\nmain :: IO ()\nmain = MWC.withSystemRandom $ \\g -> do\n   Just train <- loadMNIST \"data/train-images-idx3-ubyte\" \"data/train-labels-idx1-ubyte\"\n   Just test  <- loadMNIST \"data/t10k-images-idx3-ubyte\"  \"data/t10k-labels-idx1-ubyte\"\n   putStrLn \"Loaded data.\"\n\n   p0 <- MWC.uniformR (-0.5, 0.5) g\n   -- print (show $ take 10 train)\n\n   flip evalStateT p0 . forM_ [1..] $ \\e -> do\n      train' <- liftIO . fmap V.toList $ MWC.uniformShuffle (V.fromList train) g\n      liftIO $ printf \"[Epoch %d]\\n\" (e :: Int)\n\n      forM_ ([1..] `zip` chunksOf batch train') $ \\(b, chnk) -> StateT $ \\ps0 -> do\n         printf \"(Batch %d)\\n\" (b :: Int)\n\n         t0 <- getCurrentTime\n         newP <- evaluate . force $ trainModel (rate ^ fromIntegral e) model ps0 chnk\n         t1 <- getCurrentTime\n         printf \"Trained on %d points in %s.\\n\" batch (show (t1 `diffUTCTime` t0))\n\n         let trainScore = testNet model newP chnk\n             testScore  = testNet model newP test\n         printf \"Training error:   %.2f%%\\n\" ((1 - trainScore) * 100)\n         printf \"Validation error: %.2f%%\\n\" ((1 - testScore ) * 100)\n\n         -- TODO: Serialize trained params so we can save/load them\n\n         -- Because we are in the StateT monad, the next iteration of the loop\n         -- will be passed newP (the updated parameters for the model)\n         return ((), newP)\n   where\n      rate = 0.01\n      batch = 30\n\nloadMNIST\n   :: FilePath\n   -> FilePath\n   -> IO (Maybe [(L 28 28, R 10)])\nloadMNIST fpI fpL = runMaybeT $ do\n   i <- MaybeT          $ decodeIDXFile       fpI\n   l <- MaybeT          $ decodeIDXLabelsFile fpL\n   d <- MaybeT . return $ labeledIntData l i\n   r <- MaybeT . return $ for d (bitraverse mkImage mkLabel . swap)\n   liftIO . evaluate $ force r\n      where\n         mkImage :: VU.Vector Int -> Maybe (L 28 28)\n         mkImage = HMS.create . HMD.reshape 28 . VG.convert . VG.map (\\i -> fromIntegral i / 255)\n         mkLabel :: Int -> Maybe (R 10)\n         mkLabel n = HMS.create $ HM.build 10 (\\i -> if round i == n then 1 else 0)\n", "meta": {"hexsha": "7f2fbdd1584f4772e6ed39bb3d3cd4d27fe74b2b", "size": 14535, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Mnist.hs", "max_stars_repo_name": "velveteer/mnist-backprop", "max_stars_repo_head_hexsha": "5de7d5191e447835fa50853739f822ad8b574e41", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-29T16:51:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-29T16:51:38.000Z", "max_issues_repo_path": "src/Mnist.hs", "max_issues_repo_name": "velveteer/mnist-backprop", "max_issues_repo_head_hexsha": "5de7d5191e447835fa50853739f822ad8b574e41", "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/Mnist.hs", "max_forks_repo_name": "velveteer/mnist-backprop", "max_forks_repo_head_hexsha": "5de7d5191e447835fa50853739f822ad8b574e41", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1496062992, "max_line_length": 158, "alphanum_fraction": 0.5637426901, "num_tokens": 4100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49884237969427}}
{"text": "{-# LANGUAGE DeriveFunctor #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\nmodule Tests.Matrix.Types\n    (\n      Mat(..)\n    , fromMat\n    , toMat\n    ) where\n\nimport Control.Monad (join)\nimport Control.Applicative ((<$>), (<*>))\nimport Statistics.Matrix (Matrix(..), fromList)\nimport Test.QuickCheck\nimport Tests.Helpers (shrinkFixedList, small)\nimport qualified Data.Vector.Unboxed as U\n\ndata Mat a = Mat { mrows :: Int , mcols :: Int\n                 , asList :: [[a]] }\n              deriving (Eq, Ord, Show, Functor)\n\nfromMat :: Mat Double -> Matrix\nfromMat (Mat r c xs) = fromList r c (concat xs)\n\ntoMat :: Matrix -> Mat Double\ntoMat (Matrix r c _ v) = Mat r c . split . U.toList $ v\n  where split xs@(_:_) = let (h,t) = splitAt c xs\n                         in h : split t\n        split []       = []\n\ninstance (Arbitrary a) => Arbitrary (Mat a) where\n    arbitrary = small $ join (arbMat <$> arbitrary <*> arbitrary)\n    shrink (Mat r c xs) = Mat r c <$> shrinkFixedList (shrinkFixedList shrink) xs\n\narbMat :: (Arbitrary a) => Positive (Small Int) -> Positive (Small Int)\n       -> Gen (Mat a)\narbMat (Positive (Small r)) (Positive (Small c)) =\n    Mat r c <$> vectorOf r (vector c)\n\ninstance Arbitrary Matrix where\n    arbitrary = fromMat <$> arbitrary\n    -- shrink    = map fromMat . shrink . toMat\n", "meta": {"hexsha": "82e804946a667cd461cdfc1594f2d4ed21f7fcea", "size": 1305, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Tests/Matrix/Types.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "tests/Tests/Matrix/Types.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Tests/Matrix/Types.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3488372093, "max_line_length": 81, "alphanum_fraction": 0.6091954023, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.4985983492701425}}
{"text": "module Strategy.Orientation where\n\nimport Prelude hiding (Right, Left)\nimport Numeric.LinearAlgebra ((<>))\n\nimport Cube (Color, Side(..), Cube)\nimport qualified Cube as Cube\nimport Rotation (MatrixRotation)\nimport qualified Rotation as Rotation\nimport RotationPath (CubeMutation)\nimport qualified RotationPath as RotationPath\n\n{-|\n  Orienting a cube so that other strategies have an oriented cube to work with.\n\n  In the context of this module color of a side refers only to the middle field of a side.\n|-}\n\nsides :: Cube -> [(Side, Color)]\nsides = map (\\(s, _, _, c) -> (s, c)) . filter (\\(_, x, y, _) -> x == 1 && y == 1)\n\nisColorOnSide :: Color -> Side -> Cube -> Bool\nisColorOnSide color side = any (\\(s, c) -> (c == color && s == side)) . sides\n\n-- | Returning (prefix, suffix) rotations to do something with a color on top\nforColorOnTop :: Color -> Cube -> (MatrixRotation, MatrixRotation)\nforColorOnTop color cube\n  | isColorOnSide color Front cube = (Rotation.topToBack, Rotation.topToFront)\n  | isColorOnSide color Right cube = (Rotation.topToLeft, Rotation.topToRight)\n  | isColorOnSide color Back cube = (Rotation.topToFront, Rotation.topToBack)\n  | isColorOnSide color Left cube = (Rotation.topToRight, Rotation.topToLeft)\n  | isColorOnSide color Bottom cube =\n    let r = Rotation.topToFront <> Rotation.topToFront\n    in (r, r)\n  | otherwise = (Rotation.identity, Rotation.identity)\n\nputColorOnTop :: Color -> CubeMutation\nputColorOnTop color cube =\n  let (rotation, _) = forColorOnTop color cube\n  in RotationPath.rotate rotation cube\n\nwithColorOnTop :: Color -> CubeMutation -> CubeMutation\nwithColorOnTop color \u03bb cube =\n  let (prefix, suffix) = forColorOnTop color cube\n  in RotationPath.between prefix suffix \u03bb cube\n", "meta": {"hexsha": "52fd355caefb2a7ee036cde6d0c9839845408c0d", "size": 1734, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Strategy/Orientation.hs", "max_stars_repo_name": "runjak/hRubiks", "max_stars_repo_head_hexsha": "28798a2a07871c81843490ed95eb5377921c1be5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Strategy/Orientation.hs", "max_issues_repo_name": "runjak/hRubiks", "max_issues_repo_head_hexsha": "28798a2a07871c81843490ed95eb5377921c1be5", "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": "Strategy/Orientation.hs", "max_forks_repo_name": "runjak/hRubiks", "max_forks_repo_head_hexsha": "28798a2a07871c81843490ed95eb5377921c1be5", "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": 37.6956521739, "max_line_length": 90, "alphanum_fraction": 0.7289504037, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.49858009538407283}}
{"text": "module Statistics.Information.Mixed.TotalCorrelation where\n\nimport Data.Matrix\nimport qualified Statistics.Information.Continuous.Entropy as CE\nimport Statistics.Information.Continuous.MutualInfo\nimport qualified Statistics.Information.Continuous.TotalCorrelation as CTC\nimport qualified Statistics.Information.Discrete.Entropy as DE\nimport qualified Statistics.Information.Discrete.TotalCorrelation as DTC\nimport Statistics.Information.Mixed.Entropy\nimport Statistics.Information.Mixed.MutualInfo\nimport Statistics.Information.Utils.Matrix\nimport Statistics.Information.Utils.Random\nimport System.Random\n\nctcdc :: (RandomGen g, Eq a) => g -> Int -> Int -> Matrix a -> Matrix Double ->\n         Double\nctcdc g k base xs ys = sum hxs - hx where\n  hxs = [centropydc gcol k base col ys | (col, gcol) <- cols]\n  hx = centropydc g2 k base xs ys\n  (g1, g2) = split g\n  cols = (map colVector (columns xs)) `zip` (splitN (ncols xs) g1)\n\nctccd :: (RandomGen g, Eq a) => g -> Int -> Int -> Matrix Double -> Matrix a ->\n         Double\nctccd g k base xs ys = sum hxs - hx where\n  hxs = [centropycd gcol k base col ys | (col, gcol) <- cols]\n  hx = centropycd g2 k base xs ys\n  (g1, g2) = split g\n  cols = (map colVector (columns xs)) `zip` (splitN (ncols xs) g1)\n\ncorexcd_tcs :: (RandomGen g, Eq a) => g -> Int -> Int -> Matrix Double ->\n               Matrix a -> Double\ncorexcd_tcs g k base xs ys = CTC.tc g1 k base xs - ctccd g2 k base xs ys where\n  (g1, g2) = split g\n\ncorexcd_mis :: (RandomGen g, Eq a) => g -> Int -> Int -> Matrix Double ->\n               Matrix a -> Double\ncorexcd_mis g k base xs ys = sum mixs - mi_all where\n  mixs = [micd gcol k base col ys | (col, gcol) <- cols]\n  mi_all = micd g2 k base xs ys\n  (g1, g2) = split g\n  cols = (map colVector (columns xs)) `zip` (splitN (ncols xs) g1)\n\ncorexdc_tcs :: (RandomGen g, Eq a) => g -> Int -> Int -> Matrix a ->\n               Matrix Double -> Double\ncorexdc_tcs g k base xs ys = DTC.tc base xs - ctcdc g k base xs ys\n\ncorexdc_mis :: (RandomGen g, Eq a) => g -> Int -> Int -> Matrix a ->\n               Matrix Double -> Double\ncorexdc_mis g k base xs ys = sum mixs - mi_all where\n  mixs = [midc gcol k base col ys | (col, gcol) <- cols]\n  mi_all = midc g2 k base xs ys\n  (g1, g2) = split g\n  cols = (map colVector (columns xs)) `zip` (splitN (ncols xs) g1)\n", "meta": {"hexsha": "24f1a0616898f7849aa2dcd82eca282517d73cf3", "size": 2314, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Information/Mixed/TotalCorrelation.hs", "max_stars_repo_name": "eligottlieb/Shannon", "max_stars_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/Information/Mixed/TotalCorrelation.hs", "max_issues_repo_name": "eligottlieb/Shannon", "max_issues_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Information/Mixed/TotalCorrelation.hs", "max_forks_repo_name": "eligottlieb/Shannon", "max_forks_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "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": 42.0727272727, "max_line_length": 79, "alphanum_fraction": 0.668971478, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4985157395064323}}
{"text": "{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE OverlappingInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule Numeric.LinearAlgebra.Dimensional.DK.Internal \n{-\n(\n   -- * Data.Packed.Vector\n   (@>),\n   -- * Data.Packed.Matrix\n   -- ** dimension\n   cols, rows,\n   colsNT, rowsNT,\n   hasRows, hasCols,\n   -- (><),\n   trans,\n   -- reshape, flatten, fromLists, toLists, buildMatrix,\n   (@@>),\n\n   -- asRow, asColumn, fromRows, toRows, fromColumns, toColumns\n   -- fromBlocks\n   -- diagBlock,\n   -- toBlocks, toBlocksEvery, repmat, flipud, fliprl\n   -- subMatrix, takeRows, dropRows, takeColumns, dropColumns,\n   -- extractRows, diagRect, takeDiag, mapMatrix,\n   -- mapMatrixWithIndexM, mapMatrixWithIndexM_, liftMatrix,\n   -- liftMatrix2, liftMatrix2Auto, fromArray2D,\n\n   ident, -- where to put this?\n   -- * Numeric.Container\n   -- constant, linspace,\n   diag,\n   ctrans,\n   -- ** Container class\n   scalar,\n   conj,\n   scale, scaleRecip,\n   recipMat,\n   add,\n   sub,\n   mul,\n   divide,\n   equal,\n   arctan2,\n   hconcat,\n   vconcat,\n   concat,\n   konst,\n   zeroes,\n   -- build, atIndex, minIndex, maxIndex, minElement, maxElement,\n   -- sumElements, prodElements, step, cond, find, assoc, accum,\n   -- Convert\n   -- ** Product class\n   multiply,\n   -- dot, absSum, norm1, norm2, normInf,\n   -- norm1, normInf,\n   -- optimiseMult, mXm, mXv, vXm, (<.>),\n   -- (<>), (<\\>), outer, kronecker,\n   (<>),\n   -- ** Random numbers\n   -- ** Element conversion\n   -- ** Input/Output\n   -- ** Experimental\n\n   -- * Numeric.LinearAlgebra.Algorithms\n   -- | incomplete wrapper for \"Numeric.LinearAlgebra.Algorithms\"\n\n   -- ** Linear Systems\n   -- linearSolve, luSolve, cholSolve, linearSolveLS, linearSolveSVD,\n   inv,\n   PInv(pinv), \n   pinvTol,\n   det,\n   -- invlndet,\n   rank,\n   -- rcond,\n   -- ** Matrix factorizations\n\n   -- *** Singular value decomposition\n   -- *** Eigensystems\n   -- $eigs\n   --wrapEig, wrapEigOnly,\n   --EigCxt,\n   -- **** eigenvalues and eigenvectors\n   --eig,\n   --eigC,\n   --eigH,\n   --eigH',\n   --eigR,\n   --eigS,\n   --eigS',\n   --eigSH,\n   --eigSH',\n\n   -- **** eigenvalues\n   --eigOnlyC,\n   --eigOnlyH,\n   --eigOnlyR,\n   --eigOnlyS,\n   --eigenvalues,\n   --eigenvaluesSH,\n   --eigenvaluesSH',\n\n   -- *** QR\n   -- *** Cholesky\n   -- *** Hessenberg\n   -- *** Schur\n   -- *** LU \n\n   -- ** Matrix functions\n   -- sqrtm, matFunc\n   expm,\n\n   -- ** Nullspace\n   -- ** Norms\n   -- ** Misc\n   -- ** Util \n\n   -- * actually internal\n   toDM,\n   DimMat(..),\n  )\n  -}\n   where\nimport Foreign.Storable (Storable)      \nimport GHC.Exts (Constraint)\nimport Numeric.Units.Dimensional.DK.Prelude hiding (concat)\nimport qualified Prelude as P\nimport qualified Numeric.NumType.DK.Integers as N\n\n\nimport Numeric.LinearAlgebra.Dimensional.DK.Shapes as S\nimport Data.Proxy\n\nimport qualified Numeric.Matrix as M\nimport Numeric.Matrix ((<|>), (<->))\n\ndata DimMat (shape :: Shape) a where\n  DimMat :: M.Matrix a -> DimMat ('MatrixShape g rs cs) a\n  DimVec :: M.Matrix a -> DimMat ('VectorShape d ds) a -- as a column vector\n\ntype ValidElement = M.MatrixElement\n\nderiving instance (Show a, ValidElement a) => Show (DimMat s a)\n\n(@>) :: (NN.KnownNat n, KnownDimension (VectorElement ('VectorShape d ds) n), Fractional a, ValidElement a)\n     => DimMat ('VectorShape d ds) a\n     -> Proxy n\n     -> Quantity (VectorElement ('VectorShape d ds) n) a\n(DimVec v) @> n = (v `M.at` (asIntFrom1 n,1)) *~ siUnit\n\n(@@>) :: (NN.KnownNat nr, NN.KnownNat nc, KnownDimension (MatrixElement ('MatrixShape g rs cs) nr nc), Fractional a, ValidElement a)\n    => DimMat ('MatrixShape g rs cs) a\n    -> (Proxy nr, Proxy nc)\n    -> Quantity (MatrixElement ('MatrixShape g rs cs) nr nc) a\nDimMat m @@> (nr,nc) = (m `M.at` (asIntFrom1 nr, asIntFrom1 nc)) *~ siUnit\n\nasInt, asIntFrom1 :: (NN.KnownNat n) => Proxy n -> Int\nasInt = fromInteger . NN.natVal\nasIntFrom1 = (P.+ 1) . asInt\n\n{-\nnorm1 :: (sh ~ [r11 ': rs,ci], rs ~ MapConst r11 rs, ci ~ MapConst DOne ci, a ~ H.RealOf a)\n         => DimMat sh a\n         -> Quantity r11 a\nnorm1 (DimMat a) = Dimensional (H.pnorm H.PNorm1 a)\n\nnormInf :: (sh ~ [r11 ': rs,ci], rs ~ MapConst r11 rs, ci ~ MapConst DOne ci, a ~ H.RealOf a)\n           => DimMat sh a\n           -> Quantity r11 a\nnormInf (DimMat a) = Dimensional (H.pnorm H.Infinity a)\n-}\n\n{- | does H.'H.mXm' and H.'H.mXv'.\n\nvXm and vXv (called dot) might be supported in the future too\n-}\nmultiply :: (HasProduct s1 s2, ValidElement a)\n    => DimMat s1 a -> DimMat s2 a\n    -> DimMat (ShapeProduct s1 s2) a\nmultiply (DimMat a) (DimMat b) = DimMat (M.times a b)\nmultiply (DimMat a) (DimVec b) = DimVec (M.times a b)\n\ninfixl 7 <>\n(<>) :: (HasProduct s1 s2, ValidElement a)\n    => DimMat s1 a -> DimMat s2 a\n    -> DimMat (ShapeProduct s1 s2) a\n(<>) = multiply\n\ntrans :: (ValidElement a) => DimMat s a -> DimMat (ShapeTranspose s) a\ntrans (DimMat m) = DimMat $ M.transpose m\n\n{-\npinvTol :: (PInv sh sh',\n            a ~ Double,\n           sh' ~ [ri2 ': _1 , DOne ': ci2]) => Double -> DimMat sh a -> DimMat sh' a\npinvTol tol (DimMat a) = DimMat (H.pinvTol tol a)\n\n-}\n\ndet :: (Square s, KnownDimension (ShapeDeterminant s), Fractional a, ValidElement a) => DimMat s a -> Quantity (ShapeDeterminant s) a\ndet (DimMat m) = M.det m *~ siUnit\n\nexpm :: (s ~ ShapeProduct s s, HasProduct s s) => DimMat s a -> DimMat s a\nexpm = undefined\n\nscale :: (Fractional a, ValidElement a, KnownDimension d)\n         => Quantity d a -> DimMat s a -> DimMat (ShapeScale d s) a\nscale x (DimMat m) = DimMat $ M.scale m (x /~ siUnit)\nscale x (DimVec v) = DimVec $ M.scale v (x /~ siUnit)\n\nadd :: (ValidElement a) => DimMat s a -> DimMat s a -> DimMat s a\nadd (DimMat x) (DimMat y) = DimMat (M.plus x y)\n\nsub :: (ValidElement a) => DimMat s a -> DimMat s a -> DimMat s a\nsub (DimMat x) (DimMat y) = DimMat (M.minus x y)\n\nequal :: (Eq a, ValidElement a) => DimMat s a -> DimMat s a -> Bool\nequal (DimMat m1) (DimMat m2) = m1 == m2\nequal (DimVec v1) (DimVec v2) = v1 == v2\n\nhconcat :: (HorizontallyConcatenable s1 s2, ValidElement a) => DimMat s1 a -> DimMat s2 a -> DimMat (HorizontalConcatenation s1 s2) a\nhconcat (DimMat m1) (DimMat m2) = DimMat (m1 <|> m2)\nhconcat (DimMat m1) (DimVec v2) = DimMat (m1 <|> v2)\nhconcat (DimVec v1) (DimMat m2) = DimMat (v1 <|> m2)\nhconcat (DimVec v1) (DimVec v2) = DimMat (v1 <|> v2)\n\nvconcat :: (VerticallyConcatenable s1 s2, ValidElement a) => DimMat s1 a -> DimMat s2 a -> DimMat (VerticalConcatenation s1 s2) a\nvconcat (DimMat m1) (DimMat m2) = DimMat (m1 <-> m2)\nvconcat (DimMat m1) (DimVec v2) = undefined --DimMat (m1 <-> M.transpose v2)\nvconcat (DimVec v1) (DimMat m2) = undefined --DimMat (M.transpose v1 <-> m2)\nvconcat (DimVec v1) (DimVec v2) = DimMat (M.transpose v1 <-> M.transpose v2)\n\nfromRowVector :: (ValidElement a) => DimMat (VectorShape d ds) a -> DimMat (MatrixShape d '[] (MapDiv d ds)) a\nfromRowVector (DimVec v) = DimMat (M.transpose v)\n\nvconcat'  :: (ValidElement a,\n              MapMulEq ds d cs\n              )\n             => DimMat (VectorShape d ds) a\n             -> DimMat (MatrixShape g rs cs) a\n             -> DimMat (MatrixShape d ((g/d) ': (MapMul (g/d) rs)) cs) a\nvconcat' (DimVec v1) (DimMat m2) = DimMat (M.transpose v1 <-> m2)\n\n-- I can't figure out why this is needed. But I also can't make a version of vconcat' that seems to work when used with fromRowVector. I don't get it.\nvconcat'' :: (ValidElement a,\n              MapMulEq ds2 (d2/d1) ds1\n             )\n             => DimMat (VectorShape d1 ds1) a\n             -> DimMat (VectorShape d2 ds2) a\n             -> DimMat (MatrixShape d1 '[d2/d1] (MapDiv d1 ds1)) a\nvconcat'' (DimVec v1) (DimVec v2) = DimMat (M.transpose v1 <-> M.transpose v2)\n\nconcat :: (ValidElement a) => DimMat s1 a -> DimMat s2 a -> DimMat (VectorConcatenation s1 s2) a\nconcat (DimVec v1) (DimVec v2) = DimVec (v1 <-> v2)\n\n--vecSingleton :: (KnownDimension d, Fractional a, ValidElement a) => Quantity d a -> DimMat (VectorShape d '[]) a\n--vecSingleton x = DimVec . M.fromList $ [[x /~ siUnit]]\n\n--vecCons :: (KnownDimension d', Fractional a, ValidElement a) => Quantity d' a -> DimMat (VectorShape d ds) a -> DimMat (VectorShape d' (d ': ds)) a\n--vecCons x = concat (vecSingleton x)\n\nvecSingleton :: (Fractional a, ValidElement a) => Quantity d a -> DimMat (VectorShape d '[]) a\nvecSingleton x = DimVec . M.fromList $ [[12345]]\n\nvecCons :: (Fractional a, ValidElement a) => Quantity d' a -> DimMat (VectorShape d ds) a -> DimMat (VectorShape d' (d ': ds)) a\nvecCons x = concat (vecSingleton x)\n\n\nrank :: DimMat s a -> Integer\nrank = undefined\n\nrows :: forall s a.(NN.KnownNat (ShapeRows s)) => DimMat s a -> Integer\nrows _ = NN.natVal (Proxy :: Proxy (ShapeRows s))\n\ncols :: forall s a.(NN.KnownNat (ShapeCols s)) => DimMat s a -> Integer\ncols _ = NN.natVal (Proxy :: Proxy (ShapeCols s))\n\n-- TODO: add a constraint that the row exists for better error message?\nrow :: forall n s a d ds.(MatrixRow s n ~ 'VectorShape d ds) => Proxy n -> DimMat s a -> DimMat ('VectorShape d ds) a\nrow _ _ = DimVec undefined\n\n-- TODO: add a constraint that the column exists for better error message?\ncol :: forall n s a d ds.(MatrixColumn s n ~ 'VectorShape d ds) => Proxy n -> DimMat s a -> DimMat ('VectorShape d ds) a\ncol _ _ = DimVec undefined\n\n{-\nscalar :: (H.Field a,\n          sh ~ ['[u], '[DOne]]) => Quantity u a -> DimMat sh a\nscalar (Dimensional a) = DimMat (H.scalar a)\n-}\n\n{- | Numeric.Container.'H.konst', but the size is determined by the type.\n\n>>> let n = hSucc (hSucc hZero) -- 2\n>>> konst ((1::Double) *~ second) `hasRows` n `hasCols` n\n2><2 1   1  \ns    1.0 1.0\ns    1.0 1.0\n\n-}\n{-\nkonst :: forall u us ones a _1.\n    (H.Field a,\n     HNat2Integral (HLength ones),\n     HNat2Integral (HLength us),\n     ones ~ (DOne ': _1),\n     AllEq DOne _1,\n     AllEq u us)\n    => Quantity u a -> DimMat [us, ones] a\nkonst (Dimensional a) = DimMat (H.konst a\n    (hNat2Integral (proxy :: Proxy (HLength us)),\n     hNat2Integral (proxy :: Proxy (HLength ones))))\n\n-}\n\n-- | identity matrix. The size is determined by the type.\nident :: forall g rs cs s a.(s ~ 'MatrixShape g rs cs, HasIdentity s, NN.KnownNat (ShapeRows s), ValidElement a) => DimMat ('MatrixShape g rs cs) a\nident = DimMat $ M.unit $ asInt (Proxy :: Proxy (ShapeRows s))\n\n-- | zero matrix. The size and dimension is determined by the type.\nzeroes :: forall g rs cs s a.(s ~ 'MatrixShape g rs cs, NN.KnownNat (ShapeRows s), NN.KnownNat (ShapeCols s), ValidElement a) => DimMat ('MatrixShape g rs cs) a\nzeroes = DimMat $ M.matrix (r,c) (\\(i,j) -> 0)\n           where\n             r = asInt (Proxy :: Proxy (ShapeRows s))\n             c = asInt (Proxy :: Proxy (ShapeCols s))\n\ntrace :: (HasTrace s, Fractional a, ValidElement a, KnownDimension (ShapeTrace s)) => DimMat s a -> Quantity (ShapeTrace s) a\ntrace (DimMat m) = (P.sum $ M.trace m) *~ siUnit\n\nconj :: DimMat s a -> DimMat s a\nconj = undefined\n\n-- | conjugate transpose\nctrans :: DimMat s a -> DimMat (ShapeTranspose s) a\nctrans = undefined\n\n{-\n\ndiag :: (MapConst DOne v ~ c,\n        c ~ (DOne ': _1)\n        ) => DimMat '[v] t -> DimMat '[v,c] t\ndiag (DimVec a) = DimMat (H.diag a)\n-}\n\n{- $eigs\n\nThe Hmatrix eig factors A into P and D where A = P D inv(P) and D is diagonal.\n\nThe units for eigenvalues can be figured out:\n\n>               _____\n>      -1       |  c\n> P D P  = A =  |r\n>               |\n\n>       _______\n>       |   d\n> P   = |c\n>       |\n\n>       _______\n>       |   -1\n>       |  c\n>  -1   |   \n> P   = | -1\n>       |d\n\nSo we can see that the dimension labeled `d-1` in P inverse is actually the\nsame `c` in `A`. The actual units of `d` don't seem to matter because the\n`inv(d)` un-does any units that the `d` adds. So `d` can be all DOne. But\nanother choice, such as 1/c would be more appropriate, since then you can\nexpm your eigenvectors (not that that seems to be something people do)?\n\nTo get the row-units of A to match up, sometimes `D` will have units. \nThe equation ends up as D/c = r\n\nPlease ignore the type signatures on 'eig' 'eigC' etc. instead look at the type of\n'wrapEig' 'wrapEigOnly' together with the hmatrix documentation (linked).\n\nPerhaps the convenience definitions `eig m = wrapEig H.eig m` should be in\nanother module.\n-}\n\n{-\n\n-- | 'wrapEig' H.'H.eig'\neig m = wrapEig H.eig m\n-- | 'wrapEig' H.'H.eigC'\neigC m = wrapEig H.eigC m\n-- | 'wrapEig' H.'H.eigH'\neigH m = wrapEig H.eigH m\n-- | 'wrapEig' H.'H.eigH''\neigH' m = wrapEig H.eigH' m\n-- | 'wrapEig' H.'H.eigR'\neigR m = wrapEig H.eigR m\n-- | 'wrapEig' H.'H.eigS'\neigS m = wrapEig H.eigS m\n-- | 'wrapEig' H.'H.eigS''\neigS' m = wrapEig H.eigS' m\n-- | 'wrapEig' H.'H.eigSH'\neigSH m = wrapEig H.eigSH m\n-- | 'wrapEig' H.'H.eigSH''\neigSH' m = wrapEig H.eigSH' m\n\n-- | 'wrapEigOnly' H.'H.eigOnlyC'\neigOnlyC m = wrapEigOnly H.eigOnlyC m\n-- | 'wrapEigOnly' H.'H.eigOnlyH'\neigOnlyH m = wrapEigOnly H.eigOnlyH m\n-- | 'wrapEigOnly' H.'H.eigOnlyR'\neigOnlyR m = wrapEigOnly H.eigOnlyR m\n-- | 'wrapEigOnly' H.'H.eigOnlyS'\neigOnlyS m = wrapEigOnly H.eigOnlyS m\n-- | 'wrapEigOnly' H.'H.eigenvalues'\neigenvalues m = wrapEigOnly H.eigenvalues m\n-- | 'wrapEigOnly' H.'H.eigenvaluesSH'\neigenvaluesSH m = wrapEigOnly H.eigenvaluesSH m\n-- | 'wrapEigOnly' H.'H.eigenvaluesSH''\neigenvaluesSH' m = wrapEigOnly H.eigenvaluesSH' m\n\nwrapEig :: (ones ~ (DOne ': _1), EigCxt [r,c] eigVal [cinv,ones],\n    H.Field y, H.Field z)\n    => (H.Matrix x -> (H.Vector y, H.Matrix z)) ->\n    DimMat [r,c] x ->\n    (DimMat '[eigVal] y, DimMat [cinv,ones] z)\nwrapEig hmatrixFun (DimMat a) = case hmatrixFun a of\n    (e,v) -> (DimVec e, DimMat v)\n\nwrapEigOnly :: (EigCxt [r,c] eigVal '(), H.Field y)\n    => (H.Matrix x -> H.Vector y) ->\n    DimMat [r,c] x -> DimMat '[eigVal] y\nwrapEigOnly hmatrixFun (DimMat a) = case hmatrixFun a of\n    (e) -> DimVec e\n\n-}", "meta": {"hexsha": "950a1f2ad211432e27c027899cfdc2f751b40a5f", "size": 13935, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/Dimensional/DK/Internal.hs", "max_stars_repo_name": "dmcclean/dimensional-dk-linalg", "max_stars_repo_head_hexsha": "acc39b98d5422b5f5f405efc504edd472c368924", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-02-01T09:15:12.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-01T09:15:12.000Z", "max_issues_repo_path": "src/Numeric/LinearAlgebra/Dimensional/DK/Internal.hs", "max_issues_repo_name": "dmcclean/dimensional-dk-linalg", "max_issues_repo_head_hexsha": "acc39b98d5422b5f5f405efc504edd472c368924", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LinearAlgebra/Dimensional/DK/Internal.hs", "max_forks_repo_name": "dmcclean/dimensional-dk-linalg", "max_forks_repo_head_hexsha": "acc39b98d5422b5f5f405efc504edd472c368924", "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.4559819413, "max_line_length": 160, "alphanum_fraction": 0.6255471834, "num_tokens": 4704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49850943533582853}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule FEECa.Internal.Form (\n\n  -- * Generic form types\n    Dim, Form (Form, arity, dimVec, terms), split\n\n  -- * Predefined primitive constructors\n  , zeroForm, nullForm, oneForm\n\n  -- * Form operations\n  , apply, refine, refineBasis, inner, contract, trace\n  \n  ) where\n\n\nimport            Data.List ( intersect, elemIndex )\nimport            Data.Maybe ( fromJust )\nimport qualified  Numeric.LinearAlgebra.HMatrix as M\n-- import qualified Numeric.LinearAlgebra.Data as M\n\nimport            FEECa.Utility.Combinatorics\nimport            FEECa.Utility.Discrete\nimport qualified  FEECa.Utility.Print           as P  ( Pretty(..), printForm,\n                                                        text, (<>), (<+>), int )\nimport            FEECa.Utility.Utility               ( pairM, sumV, expSign, sign )\n\nimport            FEECa.Internal.Spaces     hiding    ( inner )\nimport qualified  FEECa.Internal.Spaces         as S  ( inner )\n\n-- * General form: does not depend on the underlying vector space it works on\n--   in any way.\n\ntype Dim = Int\ntype Idx = Int\ntype Prd = [Idx] -- a product of projections / indexed 1-forms\n-- type LinComb f = [(f, Prd)]\n\n\n-- | Bilinear, alternating forms over vectorspaces\ndata Form f =  -- we lose dependency on the type of vector!\n    Form  { arity   :: Dim            -- ^ For complete evaluation\n          , dimVec  :: Dim            -- ^ Of the underlying vector space\n          , terms   :: [(f, Prd)] }   -- ^ List of terms of (coeff,wedge)'s\n  deriving Eq\n\n\nsplit :: (Module w, Scalar w ~ v) => Form w -> ([w], [Form v])\nsplit (Form k n cs) = unzip $ map split' cs\n  where split' (a,b) = (a, Form k n [(mulId, b)])\n\n-- terms [(17, [1,2]), (38, [1,3])] = 17*dx1/\\dx2 + 38*dx1/\\dx3\n\n-- | Invariant for terms of a defined form: all terms have the same arity\n--   ie: each is the result of the exterior product of the same number of 1-forms\ntermsInv :: [(f, Prd)] -> Bool\ntermsInv []          = True\ntermsInv ((_,xs):ys) = all (\\(_,xs') -> length xs == length xs') ys\n\n-- NB: because of ((,) t) 's functorial nature, maybe it could make sense to\n--   rearrange our terms so as to have them be (inds,coeff) like they used to be?\n-- XXX: change so as to inspect result (in case f zeroes out a coeff?)\ninstance Functor Form where\n  fmap f (Form k n cs) = Form k n (map (pairM f id) cs)\n\ninstance Show f => Show (Form f) where\n  show (Form k n cs) = show k ++ \"-form in \" ++ show n ++ \" dimensions: \" ++\n                        show cs\n\ninstance P.Pretty f => P.Pretty (Form f) where\n  pPrint (Form k n cs) =\n    P.int k P.<> P.text \"-form in\" P.<+> P.int n P.<+> P.text \"dimensions:\"\n    P.<+> P.printForm \"dx\" \"0\" P.pPrint cs\n\n-- NB: will be (i -> i -> Ordering) once we normalise all products to be in\n--      their normal form - an increasing list\ncombineWithBy :: (a -> a -> a) -> (i -> i -> Bool)\n              -> [(a, i)] -> [(a, i)] -> [(a,i)]\ncombineWithBy f p = foldl ins\n  where ins [] x = [x]\n        ins (y:ys) x | p (snd x) (snd y) = (fst x `f` fst y, snd y) : ys\n                     | otherwise         = y : ins ys x\n\n-- XXX: have combinator\n--        aggregate f p cs1 cs2\n--      where f :: a -> a -> a (or b -> c)\n--            p :: MultiIndex -> MultiIndex -> Bool\n--            cs1, cs2 :: [(a, MultiIndex)]\n--      such that combines elements from cs2 with those in cs1 (sequentially,\n--      no repeat, or filtering those appropriate) with p defining the \"quotient\"\n--      class, f defining the transformation on coeff's\n--      OPT: also a MultiIndex transformation? or a separte combinator for it?\n\n-- | Sum of forms\n-- Shall we do: permutation simplification/identification\n(+++) :: Ring f => Form f -> Form f -> Form f\nomega +++ eta\n    | degNEq omega eta = errForm \"(+++)\" BiDegEq\n    | spaNEq omega eta = errForm \"(+++)\" BiSpaEq\n    | otherwise = Form (arity eta) (dimVec eta)\n                       (step (terms omega) (terms eta))\n  where step [] ys = ys\n        step xs [] = xs\n        step (x:xs) (y:ys)\n          | snd x == snd y = let z = add (fst x) (fst y) in\n              if fst x /= (addInv . fst) y then (z, snd x) : step xs ys\n                            else step xs ys\n          | snd x < snd y  = x : step xs (y:ys)\n          | otherwise      = y : step (x:xs) ys\n\n-- | Scaling of forms\n(***) :: Ring f => f -> Form f -> Form f\n(***) a | a == addId = \\(Form k n _) -> zeroForm k n\n        | otherwise  = fmap (mul a)\n\n-- | (Exterior) Product of forms\n(//\\\\) :: Ring f => Form f -> Form f -> Form f\nomega //\\\\ eta\n    | spaNEq omega eta = errForm \"(//\\\\\\\\)\" BiSpaEq\n    | otherwise = Form (arity omega + arity eta) (dimVec eta)\n                       (concatMap (\\d -> map (`combine` d) (dxs d)) (terms eta))\n  where dxs     (_,ys) = filter (null . intersect ys . snd) (terms omega)\n        combine (a,xs) = pairM (mul a) (xs++)\n\n-- | Forms over a 'Ring' form a 'Module'.\ninstance Ring f => Module (Form f) where\n  type Scalar (Form f) = f\n  addV = (+++)\n  sclV = (***)\n\n-- | Forms over a 'Field' form a 'VectorSpace'.\ninstance Field f => VectorSpace (Form f)\n\n-- | For 'Form's defined over a 'Ring' we associate an 'Algebra': the exterior\n-- algebra.\n-- This instance is valid this way since we do not have a restrictive typing\n-- for forms and hence addition is blind to arity *type-wise* - however,\n-- runtime errors will take place if invalid addition is attempted.\ninstance Ring f => Algebra (Form f) where\n  addA = addV\n  (/\\) = (//\\\\)\n  sclA = sclV\n\n-- | Basic abstract 1-form\noneForm :: Ring f => Dim -> Dim -> Form f\noneForm i n | i < 0 || i > n  = errForm \"oneForm\" MoProjBd\n            | otherwise       = Form 1 n [ (mulId,[i]) ]\n\n\n-- TODO: shall we have something special for these? no need to state dimension\n-- n since they will be constantly zero anyway\n\n-- | The (normalised) == 0 form\nzeroForm :: Dim -> Dim -> Form f\nzeroForm k n = Form k n []\n\n-- | The k-arity == 0 form\nnullForm :: Dim -> f -> Form f\nnullForm n f = Form 0 n [(f, [])]\n\n\n-- Necesitamos una funci\u00f3n de pinchado\n--  y as\u00ed pinchar las consecutivas componentes\n-- If the function was actually a field, this part would be simplified\ncontract :: (Ring f, Module v, Dimensioned v)\n         => (Idx -> v -> f) -> Form f -> v -> Form f\ncontract proj omega v\n    | vecNEq omega v = errForm \"contract\" MoVecEq\n    | otherwise      = foldl (+++) (zeroForm k n) $\n        map (\\c -> Form k n $ map (pinchado c) [1..arity omega])\n            (terms omega)\n        {- concatMap (\\c -> map (pinchado c) [1..arity omega]) -}\n  where k = max 0 (arity omega - 1)\n        n = dimVec omega\n        pinchado (f,[]) _ = (f, []) -- error ??\n        pinchado (f,ds) i = let (ds1,j:ds2) = splitAt (i-1) ds in\n                              (expSign i $ mul f (proj j v), ds1 ++ ds2)\n  {- TODO:  optimise\n            error handling: proj indexing beyond dimension of v -}\n\n-- list_to_index :: Integral a => a -> [a] -> a\n-- list_to_index n (l:ls)\n\n-- list_to_index' :: Integral a => a -> a -> [a] -> a\n-- list_to_index' acc n (l:ls) = list_to_index' ((acc * n) + l) n ls\n-- list_to_index' acc   _ []     = acc\n\n-- make_lookup  :: (Ring r, EuclideanSpace v, Scalar v ~ r)\n--              => Int -> Int -> [v] -> [[v]] -> Array [r]\n-- make_lookup n k ds vvs\napply :: (EuclideanSpace v, Ring w, Module w, Scalar v ~ Scalar w)\n      => [v] -> [v] -> Form w -> w\napply ds vs (Form k _ cs) = foldl addV addId (map (apply' k ds vs) cs)\n\napply' :: (EuclideanSpace v, Module w, Scalar v ~ Scalar w)\n       => Int -> [v] -> [v] -> (w,[Int]) -> w\napply' _ _  _  (p, []) = p\napply' k ds vs (p, cs) = sclV c p\n  where projections    = [toDouble $ dot (ds !! i) v | v <- vs, i <- cs]\n        c              = fromDouble $ M.det $ M.matrix k projections\n\nrefineBasis :: (EuclideanSpace v, Scalar v ~ r)\n            => [v] -> [[v]] -> [[r]]\nrefineBasis ds vvs = map (map (fromDouble . M.det)) submatrices\n  where projections = [[[toDouble $ dot d v | v <- vs] | d <- ds] | vs <- vvs]\n        matrices    = map (kSublists k) projections\n        submatrices = map (map (M.matrix k . concat)) matrices\n        k           = length (head vvs)\n\n-- | Run function for 'Form's: given (an appropriate number of) vector arguments\n--   and a 1-form basis (given as a basis-element indexing function 'proj'), it\n--   evaluates the form on those arguments\nrefine :: (Ring w, Module w, Module v, Scalar v ~ Scalar w)\n       => (Idx -> v -> Scalar w)  -- ^ The definition for the projection function\n                                  --   for the specific vector space\n       -> Form w\n       -> [v] -> w\nrefine proj (Form _ _ cs) vs = {-#SCC \"Form.refine\" #-} sumV (map (($ vs) . formify proj) cs')\n  where cs' | null cs   = [(addId,[])]\n            | otherwise = cs\n-- TODO: capture inconsistency between k and length vs here??\n-- ALSO: 0-forms... not evaluating correctly now! Cfr: formify does not accept\n--    empty cs\n-- XXX: for now proj should take care of the error... change later when settled\n\n\n-- | Helper function in evaluation: given a 1-form basis, converts a single\n--   'Form' term into an actual function on vectors\nformify :: (Ring w, Module w, Module v, Scalar w ~ Scalar v)\n        => (i -> v -> Scalar v) -> (w,[i]) -> [v] -> w\nformify _    (s, [])   _  = s\nformify proj (s, i:is) vs\n    | null is   = {-#SCC \"Form.formify\"  #-} sclV (proj i (head vs)) s\n    | otherwise = {-#SCC \"Form.formifyR\" #-}\n        foldl addV addId\n              (map (\\(w,e) -> sclV\n                                (mul (sign (w,e)) ((proj i . head) (pick' w vs)))\n                                (formify proj (s,is) (pick' e vs)))\n                   (permutationPairs (length is + 1) 1 (length is)))\n  where pick' ns = pick (differences ns)\n\n\n-- We need a basis here\ninner :: (InnerProductSpace w, EuclideanSpace v, Scalar w ~ Scalar v)\n      => (Idx -> v -> Scalar w)  -- ^ Projection function in the specific vector space\n      -> Form w -> Form w -> Scalar w\ninner proj omega eta\n    | degNEq omega eta = errForm \"inner\" BiDegEq -- TODO (??)\n    | otherwise = foldl\n          (flip $ \\vs -> add (S.inner (app omega vs) (app eta vs)))\n          addId\n          (map pick' (permutations n (arity omega)))\n  where pick' is  = pick (differences is) (map (unitVector n) [0..n-1])\n        app       = refine proj\n        n         = dimVec omega\n\ntrace :: [Int] -> Form w -> Form w\ntrace sigma (Form k n ts)\n    | k' < k    = zeroForm k' n\n    | otherwise = Form k n (map (pairM id restrict') ts')\n  where ts'       = filter (is_in_range' sigma . snd) ts\n        restrict' = map (fromJust . (`elemIndex` sigma))\n        k'        = length sigma\n        -- is_in_range' :: [Int] -> [Int] -> Bool\n        is_in_range' sigma = all (`elem` sigma)\n\n-- | Checks arity equality\ndegNEq :: Form f -> Form f -> Bool\ndegNEq omega eta = arity omega /= arity eta\n\n-- | Checks combined arity bound\ndegNBd :: Form f -> Form f -> Bool\ndegNBd  omega eta = (arity omega + arity eta) <= dimVec omega\n\n-- | Checks compatible underlying vector space dimensions between forms\nspaNEq :: Form f -> Form f -> Bool\nspaNEq omega eta = dimVec omega /= dimVec eta\n\n-- | Checks compatible underlying vector space dimensions between a form and a\n-- 'Dimensioned' type value\nvecNEq :: Dimensioned v => Form f -> v -> Bool\nvecNEq omega v = dimVec omega /= dim v\n\nerrForm :: String -> FormMust -> t\nerrForm callee obligation = error $ \"Form.\" ++ callee ++\n                                    \": forms must \" ++ show obligation\n\n\n\n-- | Kinds of enforcements to the definitions and operations between/for 'Form'\ndata FormMust = BiDegEq | BiDegBd | BiSpaEq | MoProjBd | MoVecEq\n\ninstance Show FormMust where\n  show BiDegEq  = \"be of the same degree\"\n  show BiDegBd  = \"have joint degree bounded by the working vector space dimension\"\n  show BiSpaEq  = \"act on the same vector space\"\n  show MoProjBd = \"project components of the underlying vector space\"\n  show MoVecEq  = \"act on vectors of the working vectors space\"\n", "meta": {"hexsha": "98e2f04dbc38849247bd24076680b20e744a9af4", "size": 11955, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FEECa/Internal/Form.hs", "max_stars_repo_name": "Airini/FEECa", "max_stars_repo_head_hexsha": "3ffae7177fca159d965b70e3763a20ab84cd8a8b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2016-05-18T05:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T12:51:19.000Z", "max_issues_repo_path": "src/FEECa/Internal/Form.hs", "max_issues_repo_name": "Airini/FEECa", "max_issues_repo_head_hexsha": "3ffae7177fca159d965b70e3763a20ab84cd8a8b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-10-26T13:28:34.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-08T16:37:41.000Z", "max_forks_repo_path": "src/FEECa/Internal/Form.hs", "max_forks_repo_name": "Airini/FEECa", "max_forks_repo_head_hexsha": "3ffae7177fca159d965b70e3763a20ab84cd8a8b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2016-05-18T21:33:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:33:06.000Z", "avg_line_length": 39.85, "max_line_length": 94, "alphanum_fraction": 0.5771643664, "num_tokens": 3493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49850942956048483}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE MultiWayIf #-}\n\nmodule Data.AdaptiveCoordinateDescent\n  ( adaptiveCoordinateDescent )\n  where\n\nimport Control.Monad.State.Strict\nimport Data.AdaptiveCoordinateDescent.Internal\nimport Data.Foldable\nimport Data.List ( sortBy )\nimport Data.Ord\nimport Data.Traversable\nimport Numeric.LinearAlgebra hiding ( toList )\nimport Pipes hiding ( for )\nimport qualified Pipes.Prelude as P\nimport System.Random.MWC\n\n-- | Performs adaptive coordinate descent.\nadaptiveCoordinateDescent :: (MonadIO m, Traversable f, Eq (f Double))\n                          => (f Double -> m Double)  -- ^ Cost function. Smaller cost = better model.\n                          -> f Double                -- ^ Initial parameters from which to start optimization.\n                          -> Double                  -- ^ Tolerance on how small changes are allowed.\n                                                     --   If no changes larger\n                                                     --   than this value are\n                                                     --   found, then this\n                                                     --   descent function\n                                                     --   returns. You probably\n                                                     --   want something small\n                                                     --   like 0.0000001\n                          -> Int                     -- ^ How many best N candidates to keep for PCA phase.\n                                                     --   Good values are\n                                                     --   probably around the\n                                                     --   size of number of\n                                                     --   your parameters.\n                                                     --   Maybe more if you\n                                                     --   only have like 2\n                                                     --   parameters. Probably.\n                                                     --   We don't know.\n                          -> Producer (f Double, Double) m (f Double, Double)\nadaptiveCoordinateDescent evaluate initial_params tolerance how_many_to_keep = do\n  score <- lift $ evaluate initial_params\n  yield (initial_params, score)\n\n  loop_it initial_params initial_params score (toColumns $ ident $ length $ toList initial_params) [] (replicate (length $ toList initial_params) 1.0) []\n where\n  k_succ = 2.0 :: Double\n  k_unsucc = 0.5 :: Double\n\n  loop_it original_params params score principal_components last_n_params step_sizes new_step_sizes | length last_n_params < 5 = do\n    rng <- liftIO createSystemRandom\n    items <- liftIO $ P.toListM (makePerturbed params rng 5)\n    scored_items <- lift $ for (initial_params:items) $ \\item -> (,) item <$> evaluate item\n    loop_it original_params params score principal_components scored_items step_sizes new_step_sizes\n\n  loop_it original_params params score (principal_component:principal_components) last_n_params (step_size':step_sizes) new_step_sizes = do\n    let step_size = max tolerance step_size'\n        scaled_pcomponent = cmap (*step_size) principal_component\n        top_candidate    = params `plus` fromVector scaled_pcomponent initial_params\n        bottom_candidate = params `minus` fromVector scaled_pcomponent initial_params\n\n    top_score    <- lift $ evaluate top_candidate\n    bottom_score <- lift $ evaluate bottom_candidate\n\n    yield (top_candidate, top_score)\n    yield (bottom_candidate, bottom_score)\n\n    if | top_score < score\n         -> loop_it original_params top_candidate top_score principal_components ((top_candidate, top_score):last_n_params) step_sizes (step_size*k_succ:new_step_sizes)\n       | bottom_score < score\n         -> loop_it original_params bottom_candidate bottom_score principal_components ((bottom_candidate, bottom_score):last_n_params) step_sizes (step_size*k_succ:new_step_sizes)\n       | otherwise\n         -> loop_it original_params params score principal_components last_n_params step_sizes (step_size*k_unsucc:new_step_sizes)\n\n  loop_it original_params params score [] _last_n_params _step_sizes new_step_sizes\n    | original_params == params &&\n      all (\\x -> x <= tolerance) new_step_sizes = yield (params, score) >> return (params, score)\n  loop_it _original_params params score [] last_n_params _step_sizes new_step_sizes = do\n    let num_coordinates = length (toList params)\n        sorted_items = sortBy (comparing snd) last_n_params\n        picked_items = take how_many_to_keep sorted_items\n\n        items_mat = normalize $\n                    ( (length picked_items><num_coordinates)\n                      (mconcat $ fmap (toList . fst) picked_items) )\n\n    let (_evec, mat2) = rightSV items_mat\n    loop_it params params score (toColumns mat2) picked_items (reverse new_step_sizes) []\n\n  loop_it _ _ _ _ _ _ _ = error \"adaptiveCoordinateDescent: impossible case.\"\n\n", "meta": {"hexsha": "5ef63a4f3cc55005851ab38194a2882519875f6b", "size": 5087, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/AdaptiveCoordinateDescent.hs", "max_stars_repo_name": "Noeda/adaptivecoordinatedescent", "max_stars_repo_head_hexsha": "c2121a634ba6e38999f79d4763f89319ebd88c2e", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/AdaptiveCoordinateDescent.hs", "max_issues_repo_name": "Noeda/adaptivecoordinatedescent", "max_issues_repo_head_hexsha": "c2121a634ba6e38999f79d4763f89319ebd88c2e", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/AdaptiveCoordinateDescent.hs", "max_forks_repo_name": "Noeda/adaptivecoordinatedescent", "max_forks_repo_head_hexsha": "c2121a634ba6e38999f79d4763f89319ebd88c2e", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.1170212766, "max_line_length": 180, "alphanum_fraction": 0.5974051504, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4984785633596105}}
{"text": "module ML.NN.Tests (tests) where\n\nimport ML.NN (ActivationFunction, Layer(..), Network(..), computeActivations,\n              feedForward, runNetwork)\n\nimport Numeric.LinearAlgebra ((><), konst, size, sumElements, vector)\n\nimport Test.HUnit (Assertion, (@?=))\nimport Test.Tasty (TestTree, testGroup)\nimport Test.Tasty.HUnit (testCase)\n\nidentityActivation :: ActivationFunction\nidentityActivation x = x\n\nemptyNetwork :: Network\nemptyNetwork = Network []\n\ntests :: TestTree\ntests = testGroup \"ML.NN\"\n    [\n        testCase\n        \"FeedForward_SumInputWeights_NoBias\" testFeedForward_SumInputWeights_NoBias\n    ,   testCase\n        \"RunNetwork_Empty\" testRunNetwork_Empty\n    ,   testCase\n        \"ComputeActivations_EmptyNetwork\" testComputeActivations_EmptyNetwork\n    ,   testCase\n        \"ComputeActivations_SingleLayerSingleNeuron\" testComputeActivations_SingleLayerSingleNeuron\n    ]\n\n\n-- | Test a simple layer where each neuron sums the input.\ntestFeedForward_SumInputWeights_NoBias :: Assertion\ntestFeedForward_SumInputWeights_NoBias =\n    feedForward identityActivation x sumLayer @?= expected\n    where x          = vector [1,2,3]\n          expected   = vector $ replicate numNeurons (sumElements x)\n          numNeurons = 5\n          sumLayer   = Layer (konst 0 numNeurons) (konst 1 (numNeurons, size x))\n\n-- | Test that running an empty network on an input 'x' yields 'x'.\ntestRunNetwork_Empty :: Assertion\ntestRunNetwork_Empty =\n    runNetwork emptyNetwork identityActivation x @?= x\n    where x = vector [1,2,3]\n\n-- | When there are no layers, there should be no z's and the only\n--   activation should be the input.\ntestComputeZsAndAs_EmptyNetwork :: Assertion\ntestComputeZsAndAs_EmptyNetwork =\n    computeZsAndAs identityActivation emptyNetwork x @?= ([], [x])\n    where x = vector [1,2,3]\n\n-- | When there is a single identity layer, the zs = [z] where z is the sum\n--   of the input values, and the activations are z and the input x.\n--\n--   The order of the activations is reversed from the order they appear in the\n--   network so they can easily be used by the backpropogation algorithm.\ntestComputeZsAndAs_SingleLayerSingleNeuron :: Assertion\ntestComputeZsAndAs_SingleLayerSingleNeuron =\n    computeZsAndAs identityActivation net x @?= ([z], [z,x])\n    where x = vector [1,2,3]\n          z = vector [6]\n          net = Network [Layer (vector [0]) ((1><3) [1,1,1])]\n", "meta": {"hexsha": "3ab1ed5bcfb34698b7c62aab2d2fd83af3354d29", "size": 2385, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "testsuite/tests/ML/NN/Tests.hs", "max_stars_repo_name": "m-renaud/ML", "max_stars_repo_head_hexsha": "7fb9fdac687cd76528d6b3d9080030a0723b01ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-05-15T16:13:43.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-15T16:13:43.000Z", "max_issues_repo_path": "testsuite/tests/ML/NN/Tests.hs", "max_issues_repo_name": "m-renaud/ML", "max_issues_repo_head_hexsha": "7fb9fdac687cd76528d6b3d9080030a0723b01ca", "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": "testsuite/tests/ML/NN/Tests.hs", "max_forks_repo_name": "m-renaud/ML", "max_forks_repo_head_hexsha": "7fb9fdac687cd76528d6b3d9080030a0723b01ca", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6923076923, "max_line_length": 99, "alphanum_fraction": 0.7174004193, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49820880703660425}}
{"text": "{-# LANGUAGE Rank2Types #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module     : Numeric.LinearAlgebra.Matrix.Tri\n-- Copyright  : Copyright (c) 2010, Patrick Perry <patperry@gmail.com>\n-- License    : BSD3\n-- Maintainer : Patrick Perry <patperry@gmail.com>\n-- Stability  : experimental\n--\n-- Triangular views of matrices.\n--\n\nmodule Numeric.LinearAlgebra.Matrix.Tri (\n    -- * Immutable interface\n    \n    -- ** Vector multiplication\n    triMulVector,\n    \n    -- ** Matrix multiplication\n    triMulMatrix,\n    triMulMatrixWithScale,\n\n    -- ** Vector solving\n    triSolvVector,\n    \n    -- ** Matrix solving\n    triSolvMatrix,\n    triSolvMatrixWithScale,\n\n    -- * Mutable interface\n    triCreate,\n    \n    -- ** Vector multiplication\n    triMulVectorM_,\n    \n    -- ** Matrix multiplication\n    triMulMatrixM_,\n    triMulMatrixWithScaleM_,\n\n    -- ** Vector solving\n    triSolvVectorM_,\n\n    -- ** Matrix solving\n    triSolvMatrixM_,\n    triSolvMatrixWithScaleM_,\n\n    ) where\n\nimport Control.Monad( when )\nimport Control.Monad.ST( ST, runST, unsafeIOToST )\nimport Text.Printf( printf )\n\nimport Numeric.LinearAlgebra.Vector( Vector, STVector )\nimport qualified Numeric.LinearAlgebra.Vector as V\nimport Numeric.LinearAlgebra.Matrix.Base( Matrix )\nimport Numeric.LinearAlgebra.Matrix.STBase( STMatrix, RMatrix )\nimport qualified Numeric.LinearAlgebra.Matrix.STBase as M\nimport Numeric.LinearAlgebra.Types\nimport qualified Foreign.BLAS as BLAS\n\n\n-- | A safe way to create and work with a mutable Tri Matrix before returning \n-- an immutable one for later perusal.\ntriCreate :: (Storable e)\n           => (forall s. ST s (Tri (STMatrix s) e))\n           -> Tri Matrix e\ntriCreate mt = runST $ do\n    (Tri u d ma) <- mt\n    a <- M.unsafeFreeze ma\n    return $ Tri u d a\n\n-- | @triMulVector trans a x@ returns @op(a) * x@, where @op(a)@ is\n-- determined by @trans@.\ntriMulVector :: (BLAS2 e)\n             => Trans\n             -> Tri Matrix e\n             -> Vector e\n             -> Vector e\ntriMulVector trans a x =\n    V.create $ do\n        x' <- V.newCopy x\n        triMulVectorM_ trans a x'\n        return x'\n\n-- | @triMulMatrix side a b@\n-- returns @alpha * op(a) * b@ when @side@ is @LeftSide@ and\n-- @alpha * b * op(a)@ when @side@ is @RightSide@.  Operation\n-- @op(a)@ is determined by @trans@.\ntriMulMatrix :: (BLAS3 e)\n              => Side\n              -> Trans -> Tri Matrix e\n              -> Matrix e\n              -> Matrix e\ntriMulMatrix side trans a b = \n    M.create $ do\n        b' <- M.newCopy b\n        triMulMatrixM_ side trans a b'\n        return b'\n\n-- | @triMulMatrixWithScale alpha side trans a b@\n-- returns @alpha * op(a) * b@ when @side@ is @LeftSide@ and\n-- @alpha * b * op(a)@ when @side@ is @RightSide@.  Operation\n-- @op(a)@ is determined by @trans@.\ntriMulMatrixWithScale :: (BLAS3 e)\n                       => e\n                       -> Side\n                       -> Trans -> Tri Matrix e\n                       -> Matrix e\n                       -> Matrix e\ntriMulMatrixWithScale alpha side trans a b =\n    M.create $ do\n        b' <- M.newCopy b\n        triMulMatrixWithScaleM_ alpha side trans a b'\n        return b'\n\n-- | @triMulVectorM_ a x@ sets @x := op(a) * x@, where @op(a)@ is determined\n-- by @trans@.\ntriMulVectorM_ :: (RMatrix m, BLAS2 e)\n               => Trans -> Tri m e\n               -> STVector s e\n               -> ST s ()\ntriMulVectorM_ trans (Tri uplo diag a) x = do\n    (ma,na) <- M.getDim a\n    nx <- V.getDim x\n    let n = nx\n    \n    when (ma /= na) $ error $\n        printf (\"triMulVectorM_\"\n                ++ \" _\"\n                ++ \" (Tri _ _ <matrix with dim (%d,%d)>)\"\n                ++ \" _\"\n                ++ \": matrix is not square\")\n               ma na\n               \n    when ((not . and) [ (ma,na) == (n,n)\n                      , nx == n\n                      ]) $ error $\n        printf (\"triMulVectorM_\"\n                ++ \" _\"\n                ++ \" (Tri _ _ <matrix with dim (%d,%d)>)\"\n                ++ \" <vector with dim %d>\"\n                ++ \": dimension mismatch\")\n               ma na\n               nx\n\n    unsafeIOToST $\n        M.unsafeWith a $ \\pa lda ->\n        V.unsafeWith x $ \\px ->\n            BLAS.trmv uplo trans diag n pa lda px 1\n\n\n-- | @triMulMatrixM_ side trans a b@\n-- sets @b := op(a) * b@ when @side@ is @LeftSide@ and\n-- @b := b * op(a)@ when @side@ is @RightSide@.  Operation\n-- @op(a)@ is determined by @trans@.\ntriMulMatrixM_ :: (RMatrix m, BLAS3 e)\n               => Side \n               -> Trans -> Tri m e\n               -> STMatrix s e\n               -> ST s ()\ntriMulMatrixM_ = triMulMatrixWithScaleM_ 1\n\n-- | @triMulMatrixWithScaleM_ alpha side trans a b@\n-- sets @b := alpha * op(a) * b@ when @side@ is @LeftSide@ and\n-- @b := alpha * b * op(a)@ when @side@ is @RightSide@.  Operation\n-- @op(a)@ is determined by @trans@.\ntriMulMatrixWithScaleM_ :: (RMatrix m, BLAS3 e)\n                         => e\n                         -> Side\n                         -> Trans -> Tri m e\n                         -> STMatrix s e\n                         -> ST s ()\ntriMulMatrixWithScaleM_ alpha side trans (Tri uplo diag a) b = do\n    (ma,na) <- M.getDim a\n    (mb,nb) <- M.getDim b\n    let (m,n) = (mb,nb)\n    \n    when (ma /= na) $ error $\n        printf (\"triMulMatrixWithScaleM_\"\n                ++ \" _\"\n                ++ \" _\"\n                ++ \" _\"\n                ++ \" (Tri _ _ <matrix with dim (%d,%d)>)\"\n                ++ \" _\"\n                ++ \": matrix is not square\")\n               ma na\n\n    when ((not . and) [ case side of LeftSide  -> (ma,na) == (m,m)\n                                     RightSide -> (ma,na) == (n,n)\n                      , (mb, nb ) == (m,n)\n                      ]) $ error $\n        printf (\"triMulMatrixWithScaleM_\"\n                ++ \" _\"\n                ++ \" %s\"\n                ++ \" _\"\n                ++ \" (Tri _ _ <matrix with dim (%d,%d)>)\"\n                ++ \" <matrix with dim (%d,%d)>\"\n                ++ \": dimension mismatch\")\n               (show side)\n               ma na\n               mb nb\n\n    unsafeIOToST $\n        M.unsafeWith a $ \\pa lda ->\n        M.unsafeWith b $ \\pb ldb ->\n            BLAS.trmm side uplo trans diag m n alpha pa lda pb ldb\n\n\n-- | @triSolvVector trans a x@ returns @op(a) \\\\ x@, where @op(a)@ is\n-- determined by @trans@.\ntriSolvVector :: (BLAS2 e)\n             => Trans\n             -> Tri Matrix e\n             -> Vector e\n             -> Vector e\ntriSolvVector trans a x =\n    V.create $ do\n        x' <- V.newCopy x\n        triSolvVectorM_ trans a x'\n        return x'\n\n-- | @triSolvMatrix side a b@\n-- returns @alpha * op(a) \\\\ b@ when @side@ is @LeftSide@ and\n-- @alpha * b * op(a)@ when @side@ is @RightSide@.  Operation\n-- @op(a)@ is determined by @trans@.\ntriSolvMatrix :: (BLAS3 e)\n              => Side\n              -> Trans -> Tri Matrix e\n              -> Matrix e\n              -> Matrix e\ntriSolvMatrix side trans a b = \n    M.create $ do\n        b' <- M.newCopy b\n        triSolvMatrixM_ side trans a b'\n        return b'\n\n-- | @triSolvMatrixWithScale alpha side trans a b@\n-- returns @alpha * op(a) \\\\ b@ when @side@ is @LeftSide@ and\n-- @alpha * b * op(a)@ when @side@ is @RightSide@.  Operation\n-- @op(a)@ is determined by @trans@.\ntriSolvMatrixWithScale :: (BLAS3 e)\n                       => e\n                       -> Side\n                       -> Trans -> Tri Matrix e\n                       -> Matrix e\n                       -> Matrix e\ntriSolvMatrixWithScale alpha side trans a b =\n    M.create $ do\n        b' <- M.newCopy b\n        triSolvMatrixWithScaleM_ alpha side trans a b'\n        return b'\n\n-- | @triSolvVectorM_ a x@ sets @x := op(a) \\\\ x@, where @op(a)@ is determined\n-- by @trans@.\ntriSolvVectorM_ :: (RMatrix m, BLAS2 e)\n               => Trans -> Tri m e\n               -> STVector s e\n               -> ST s ()\ntriSolvVectorM_ trans (Tri uplo diag a) x = do\n    (ma,na) <- M.getDim a\n    nx <- V.getDim x\n    let n = nx\n    \n    when (ma /= na) $ error $\n        printf (\"triSolvVectorM_\"\n                ++ \" _\"\n                ++ \" (Tri _ _ <matrix with dim (%d,%d)>)\"\n                ++ \" _\"\n                ++ \": matrix is not square\")\n               ma na\n               \n    when ((not . and) [ (ma,na) == (n,n)\n                      , nx == n\n                      ]) $ error $\n        printf (\"triSolvVectorM_\"\n                ++ \" _\"\n                ++ \" (Tri _ _ <matrix with dim (%d,%d)>)\"\n                ++ \" <vector with dim %d>\"\n                ++ \": dimension mismatch\")\n               ma na\n               nx\n\n    unsafeIOToST $\n        M.unsafeWith a $ \\pa lda ->\n        V.unsafeWith x $ \\px ->\n            BLAS.trsv uplo trans diag n pa lda px 1\n\n\n-- | @triSolvMatrixM_ side trans a b@\n-- sets @b := op(a) \\\\ b@ when @side@ is @LeftSide@ and\n-- @b := b * op(a)@ when @side@ is @RightSide@.  Operation\n-- @op(a)@ is determined by @trans@.\ntriSolvMatrixM_ :: (RMatrix m, BLAS3 e)\n               => Side \n               -> Trans -> Tri m e\n               -> STMatrix s e\n               -> ST s ()\ntriSolvMatrixM_ = triSolvMatrixWithScaleM_ 1\n\n-- | @triSolvMatrixWithScaleM_ alpha side trans a b@\n-- sets @b := alpha * op(a) \\\\ b@ when @side@ is @LeftSide@ and\n-- @b := alpha * b * op(a)@ when @side@ is @RightSide@.  Operation\n-- @op(a)@ is determined by @trans@.\ntriSolvMatrixWithScaleM_ :: (RMatrix m, BLAS3 e)\n                         => e\n                         -> Side\n                         -> Trans -> Tri m e\n                         -> STMatrix s e\n                         -> ST s ()\ntriSolvMatrixWithScaleM_ alpha side trans (Tri uplo diag a) b = do\n    (ma,na) <- M.getDim a\n    (mb,nb) <- M.getDim b\n    let (m,n) = (mb,nb)\n    \n    when (ma /= na) $ error $\n        printf (\"triSolvMatrixWithScaleM_\"\n                ++ \" _\"\n                ++ \" _\"\n                ++ \" _\"\n                ++ \" (Tri _ _ <matrix with dim (%d,%d)>)\"\n                ++ \" _\"\n                ++ \": matrix is not square\")\n               ma na\n\n    when ((not . and) [ case side of LeftSide  -> (ma,na) == (m,m)\n                                     RightSide -> (ma,na) == (n,n)\n                      , (mb, nb ) == (m,n)\n                      ]) $ error $\n        printf (\"triSolvMatrixWithScaleM_\"\n                ++ \" _\"\n                ++ \" %s\"\n                ++ \" _\"\n                ++ \" (Tri _ _ <matrix with dim (%d,%d)>)\"\n                ++ \" <matrix with dim (%d,%d)>\"\n                ++ \": dimension mismatch\")\n               (show side)\n               ma na\n               mb nb\n\n    unsafeIOToST $\n        M.unsafeWith a $ \\pa lda ->\n        M.unsafeWith b $ \\pb ldb ->\n            BLAS.trsm side uplo trans diag m n alpha pa lda pb ldb\n", "meta": {"hexsha": "dcb4fc61d68952be88db57c92b5b444114a406df", "size": 10744, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Tri.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Tri.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Tri.hs", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 31.2325581395, "max_line_length": 78, "alphanum_fraction": 0.4745904691, "num_tokens": 2974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4981662997245794}}
{"text": "{-# language ScopedTypeVariables #-}\n{-# language TypeFamilies #-}\nmodule RealMain where\n\nimport Codec.Picture\nimport Control.Monad.State\nimport Data.Word\nimport Data.Complex\nimport System.Exit (exitFailure, exitSuccess)\nimport System.Environment (getArgs)\nimport qualified Data.Vector.Storable as V\nimport qualified Data.Vector.Generic as G\n\nimport Paths_proyecto_lena\nimport ArrayPoking\nimport Algoritmo\n\nrealMain :: IO ()\nrealMain =\n  do rate : divisions : reconstruct : _ <- getArgs\n     img@(Image width height _) <- loadImage lena_path\n     let red   = V.map fromIntegral (extractColor 0 img)\n         green = V.map fromIntegral (extractColor 1 img)\n         blue  = V.map fromIntegral (extractColor 2 img)\n\n         calidad    = read rate\n         divisiones = read divisions\n         recons     = read reconstruct\n         factor     = divisiones - recons\n\n         redNew   = waveletAlgo calidad divisiones recons red\n         greenNew = waveletAlgo calidad divisiones recons green\n         blueNew  = waveletAlgo calidad divisiones recons blue\n\n     writePng \"./lena_alt.png\"\n              (nuevaImg factor width height redNew greenNew blueNew)\n\nrealMain2 :: IO ()\nrealMain2 =\n  do rate : divisions : reconstruct : _ <- getArgs\n     img@(Image width height _) <- loadImage lena_path\n     let red   = V.map fromIntegral (extractColor 0 img)\n\n         calidad    = read rate\n         divisiones = read divisions\n         recons     = read reconstruct\n         factor     = divisiones - recons\n\n         redNew   = waveletAlgo calidad divisiones recons red\n\n     writePng \"./lena_alt.png\"\n       -- Solo afecta el largo pues es 1D\n       (Image (width `div` (2^(factor - 1))) (height)\n              (V.map (round . realPart) redNew) :: Image Pixel8)\n\nloadImage :: FilePath -> IO (Image PixelRGB8)\nloadImage path =\n  do lena <- readImage path\n     img  <- either (\\s -> putStrLn s >> exitFailure) return lena\n     case img of\n       ImageRGB8 img_lena -> return img_lena\n       _                  -> exitFailure\n\nloadImageBebe :: FilePath -> IO (Image Pixel8)\nloadImageBebe path =\n  do lena <- readImage path\n     img  <- either (\\s -> putStrLn s >> exitFailure) return lena\n     case img of\n       ImageY8   img_bebe -> return img_bebe\n       _                  -> exitFailure\n\nnuevaImg :: (Complex Double ~ a)\n         => Int -> Int -> Int\n         -> V.Vector a -> V.Vector a -> V.Vector a\n         -> Image PixelRGB8\nnuevaImg factor width height red green blue =\n  let combined = combineColors red green blue\n   in Image (width `div` 2^(factor - 1)) height\n      . G.map (round . realPart) $ combined\n\nlena_path, tiny_path, bebe_path :: FilePath\nlena_path = \"/home/slack/UTFSM/2016-2/trabajo-roldan-peypo/proyecto-lena/images/Lenna.png\"\ntiny_path = \"/home/slack/UTFSM/2016-2/trabajo-roldan-peypo/proyecto-lena/images/tiny.png\"\nbebe_path = \"/home/slack/UTFSM/2016-2/trabajo-roldan-peypo/proyecto-lena/images/bebe.png\"\n", "meta": {"hexsha": "8afd2539ef3293dbc5691c6e82f65ce5fd04b909", "size": 2927, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/RealMain.hs", "max_stars_repo_name": "RubenAstudillo/proyecto-lena", "max_stars_repo_head_hexsha": "4ada23dc739cb32b6d82612784e8cd96f33a748d", "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/RealMain.hs", "max_issues_repo_name": "RubenAstudillo/proyecto-lena", "max_issues_repo_head_hexsha": "4ada23dc739cb32b6d82612784e8cd96f33a748d", "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/RealMain.hs", "max_forks_repo_name": "RubenAstudillo/proyecto-lena", "max_forks_repo_head_hexsha": "4ada23dc739cb32b6d82612784e8cd96f33a748d", "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.4352941176, "max_line_length": 90, "alphanum_fraction": 0.6617697301, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4979188082435052}}
{"text": "--\n-- Image : image data structure\n--\n\nmodule CNN.Image (\n  Image\n, Plain\n, Class\n, Trainer\n, classNumToVec\n) where\n\nimport qualified Data.Map as M\nimport Numeric.LinearAlgebra.Data\n\ntype Plain = Matrix R    -- 2D: X x Y pixels\ntype Image = [Plain]     -- n dimension\n\ntype Class = Vector R    -- teacher vector\n\ntype Trainer = (Image, Class)\n\n-- FUNCTIONS\n\nclassNumToVec :: Int -> Int -> Class\nclassNumToVec n c = fromList ls\n  where\n    ls = take n (replicate c 0.0 ++ [1.0] ++ repeat 0.0)\n", "meta": {"hexsha": "6470cab72a5e4e8f48c0c40fd4aad63750df62cc", "size": 492, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "CNN/Image.hs", "max_stars_repo_name": "eijian/deeplearning", "max_stars_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-30T01:28:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T18:58:17.000Z", "max_issues_repo_path": "CNN/Image.hs", "max_issues_repo_name": "eijian/deeplearning", "max_issues_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "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": "CNN/Image.hs", "max_forks_repo_name": "eijian/deeplearning", "max_forks_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "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": 16.9655172414, "max_line_length": 56, "alphanum_fraction": 0.6605691057, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.49785590937243546}}
{"text": "{-# LANGUAGE ScopedTypeVariables, GADTs #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Complex\nimport Data.Int\nimport Data.List\nimport Data.Mat\nimport qualified Data.Map\nimport Data.Maybe\nimport System.Environment\nimport System.Exit\nimport System.IO\n\n-- A universal datatype for MAT data.\ndata MatVal =\n    VDouble  Double\n  | VInt64   Int64\n  | VBool    Bool\n  | VChar    Char\n  | VComplex (Complex MatVal)\n  | VStruct  (Data.Map.Map String MatVal)\n  | VArray   Int [MatVal]\n  deriving (Eq, Show)\n\n-- | Transform from the types into the universal representation.\ntoMatVal :: MatData -> MatVal\ntoMatVal (MatData MatDouble d)               = VDouble d\ntoMatVal (MatData MatInt64  i)               = VInt64  i\ntoMatVal (MatData MatBool   b)               = VBool   b\ntoMatVal (MatData MatChar   c)               = VChar   c\ntoMatVal (MatData MatCell   d)               = toMatVal d\ntoMatVal (MatData (MatStruct (Known fs)) ds) = VStruct (Data.Map.fromList (zip fs (map toMatVal ds)))\ntoMatVal (MatData (MatArray t (Known d)) xs) = VArray d (map (toMatVal . MatData t) xs)\ntoMatVal (MatData (MatComplex t) (x :+ y))   = matZipWith (\\ r i -> VComplex (r :+ i)) (toMatVal (MatData t x)) (toMatVal (MatData t y))\n\n-- | Push down complex values.\nmatZipWith :: (MatVal -> MatVal -> MatVal) -> MatVal -> MatVal -> MatVal\nmatZipWith op (VStruct xs) (VStruct ys)   = VStruct (Data.Map.unionWith (matZipWith op) xs ys)\nmatZipWith op (VArray d xs) (VArray _ ys) = VArray d (zipWith (matZipWith op) xs ys)\nmatZipWith op x y = op x y\n\nmain :: IO ()\nmain = do\n  (fp:_) <- getArgs\n  -- Read an entire MAT file\n  xs :: [(String, MatData)] <- liftM Data.Map.toList (readMatFile fp)\n  putStrLn \"Variables contained in MAT file:\"\n  -- Print all the contents\n  mapM_ (\\ (n, d) -> putStr (n ++ \" ->\\n  \" ++ show (toMatVal d) ++ \"\\n\")) xs\n  exitSuccess\n", "meta": {"hexsha": "9aca8dec7a2b46e1f59c4e78dabb2bf9c6786371", "size": 1838, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/TestUniversal.hs", "max_stars_repo_name": "glutamate/matio", "max_stars_repo_head_hexsha": "c2ce4f5b8eb9be1e78ee5cbe34bd1682157a54a5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-28T03:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:20:12.000Z", "max_issues_repo_path": "test/TestUniversal.hs", "max_issues_repo_name": "glutamate/matio", "max_issues_repo_head_hexsha": "c2ce4f5b8eb9be1e78ee5cbe34bd1682157a54a5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/TestUniversal.hs", "max_forks_repo_name": "glutamate/matio", "max_forks_repo_head_hexsha": "c2ce4f5b8eb9be1e78ee5cbe34bd1682157a54a5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3461538462, "max_line_length": 136, "alphanum_fraction": 0.6588683351, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.49777433285614386}}
{"text": "{-|\nModule      : HABQTlib.MeasurementProcessing\n\nFunctions that deal with optimising and simulating measurements that take place\nduring tomography.\n-}\nmodule HABQTlib.MeasurementProcessing\n  ( PurePOVM\n  , SingleQbParam\n  , measurementProbs\n  , svToAngles\n  , blochAnglesToSV\n  , mkAntipodalPOVM\n  , productPOVM\n  , simulateMeasuremet\n  , optimiseSingleQbPOVM\n  ) where\n\nimport Control.Applicative (liftA2)\nimport Control.Newtype.Generics (unpack)\nimport Data.Complex (mkPolar, polar)\nimport Data.List (unfoldr)\nimport Data.Maybe (fromJust)\nimport qualified Data.Vector as V\nimport HABQTlib.Data\nimport HABQTlib.Data.Particle\nimport qualified Numeric.GSL as GSL\nimport Numeric.LinearAlgebra (Complex((:+)))\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified System.Random.MWC as MWC\nimport System.Random.MWC.Distributions (categorical)\n\n-- | A POVM consisting of projections onto pure states.\ntype PurePOVM = V.Vector WeighedPureStateVector\n\n-- | Spherical coordinates of a pure single qubit state on Bloch sphere.\ntype SingleQbParam = (Double, Double)\n\n-- | Probabilities to measure elements of POVM when performing the measurement\n-- over a mixed state.\nmeasurementProbs :: PurePOVM -> DensityMatrix -> V.Vector Double\nmeasurementProbs povm dm = V.map (weighedProb dm) povm\n\nweighedProb :: DensityMatrix -> WeighedPureStateVector -> Double\nweighedProb dm (WeighedPureStateVector (w, sv)) = w * pureStateLikelihood sv dm\n\nentropy :: V.Vector Double -> Double\nentropy = negate . V.sum . V.map (\\p -> p * log p)\n\npovmPointEntropy :: PurePOVM -> DensityMatrix -> Double\npovmPointEntropy povm dm = entropy (measurementProbs povm dm)\n\npovmMeanEntropy :: PurePOVM -> ParticleHierarchy -> Double\npovmMeanEntropy povm ph =\n  let meanEnt = foldOverPts (povmPointEntropy povm) (*) (+) 0\n      totalWeight = V.sum . V.map ptsWeight $ ph\n      rawEntropy = V.sum . V.map (liftA2 (*) ptsWeight meanEnt) $ ph\n   in rawEntropy / totalWeight\n\n-- | Recover a state vector from spherical coordinates.\nblochAnglesToSV :: SingleQbParam -> PureStateVector\nblochAnglesToSV (th, phi) =\n  let z = LA.fromList [1, 0]\n      o = LA.fromList [0, 1]\n   in PureStateVector . LA.fromColumns . pure $\n      LA.scalar (cos (th / 2) :+ 0) * z +\n      LA.scalar (mkPolar (sin (th / 2)) phi) * o\n\n-- | Return spherical coordinates of a single qubit pure state (on Bloch\n-- sphere).\nsvToAngles :: PureStateVector -> Maybe SingleQbParam\nsvToAngles (PureStateVector sv) =\n  let s = LA.size sv\n      (m0, ph0) = polar $ LA.atIndex sv (0, 0)\n      (_, ph1) = polar $ LA.atIndex sv (1, 0)\n      ph = ph1 - ph0\n      th = 2 * acos m0\n   in if s == (2, 1)\n        then Just (th, ph)\n        else Nothing\n\n-- | Given spherical coordinates, construct a POVM from the given vector and\n-- one orthogonal to it.\nmkAntipodalPOVM :: SingleQbParam -> PurePOVM\nmkAntipodalPOVM c@(th, phi) =\n  let sv = blochAnglesToSV c\n      sv' = blochAnglesToSV (pi - th, phi + pi)\n   in V.fromList $ WeighedPureStateVector <$> [(1, sv), (1, sv')]\n\nreshapeList :: Int -> [a] -> [[a]]\nreshapeList n =\n  unfoldr\n    (\\b ->\n       if length b < n\n         then Nothing\n         else Just (splitAt n b))\n\nlistToPairs :: [a] -> [(a, a)]\nlistToPairs = fmap (\\(a:[b]) -> (a, b)) . reshapeList 2\n\npairToList :: (a, a) -> [a]\npairToList (a, b) = [a, b]\n\n-- | Given a list of POVM measurements on sub-systems, construct a POVM over\n-- the composite system that includes all of them.\nproductPOVM :: [PurePOVM] -> PurePOVM\nproductPOVM sqbPovms =\n  let pr ::\n           WeighedPureStateVector\n        -> WeighedPureStateVector\n        -> WeighedPureStateVector\n      pr wsv0 wsv1 =\n        WeighedPureStateVector (w0 * w1, PureStateVector $ LA.kronecker sv0 sv1)\n        where\n          up = fmap unpack . unpack\n          (w0, sv0) = up wsv0\n          (w1, sv1) = up wsv1\n   in V.foldl1' (liftA2 pr) $ V.fromList sqbPovms\n\n-- | Approximate most informative separable POVM over a composite system of\n-- quantum bits, given a list of single-qubit starting points and a particle\n-- distribution.\noptimiseSingleQbPOVM ::\n     OptIter -- ^ Number of optimisation steps to perform\n  -> [PureStateVector] -- ^ single qubit initial states\n  -> ParticleHierarchy\n  -> PurePOVM\noptimiseSingleQbPOVM iter sv0s ph =\n  let nq = length sv0s\n      method = GSL.NMSimplex2\n      precision = 1e-6\n      iterations = iter\n      initialBox = replicate (2 * nq) (pi / 2)\n      estimateDM = getMixedEstimate ph\n      obj params =\n        negate $ povmPointEntropy povm estimateDM - povmMeanEntropy povm ph\n        where\n          povm = productPOVM . fmap mkAntipodalPOVM . listToPairs $ params\n      start = concatMap (pairToList . fromJust . svToAngles) sv0s\n      result = GSL.minimize method precision iterations initialBox obj start\n   in productPOVM . fmap mkAntipodalPOVM . listToPairs . fst $ result\n\n-- | Simulate a POVM over a mixed state and return the state vector on which\n-- the projection was obtained.\nsimulateMeasuremet ::\n     DensityMatrix -> PurePOVM -> MWC.GenIO -> IO PureStateVector\nsimulateMeasuremet dm povm gen = do\n  let probs = measurementProbs povm dm\n      svs = V.map (\\(WeighedPureStateVector (_, sv)) -> sv) povm\n  idx <- categorical probs gen\n  return $ svs V.! idx\n", "meta": {"hexsha": "e5cce6ad46cfba4166f9f7d744bc3751bc5ced67", "size": 5213, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HABQTlib/MeasurementProcessing.hs", "max_stars_repo_name": "Belinsky-L-V/HABQT", "max_stars_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-23T03:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T08:45:58.000Z", "max_issues_repo_path": "src/HABQTlib/MeasurementProcessing.hs", "max_issues_repo_name": "Belinsky-L-V/HABQT", "max_issues_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "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/HABQTlib/MeasurementProcessing.hs", "max_forks_repo_name": "Belinsky-L-V/HABQT", "max_forks_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "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.2960526316, "max_line_length": 80, "alphanum_fraction": 0.6932668329, "num_tokens": 1528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505966, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4976822707320871}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedLists #-}\n{-# LANGUAGE Strict #-}\n\nmodule Utils where\n\nimport qualified Graphics.GL as GLRaw\nimport qualified Graphics.Rendering.OpenGL.GL as GL\nimport           Numeric.LinearAlgebra ((><), Vector, Matrix, scale, cross, dot, tr)\nimport qualified Numeric.LinearAlgebra as L\nimport           Data.Vector.Storable ((!))\nimport qualified Numeric.LinearAlgebra.Data as LD\nimport qualified Data.Vector.Storable as VS\n\nstep :: Float\nstep = 0.02\n\nnorm :: Vector Float -> Float\nnorm = realToFrac . L.norm_2\n\nposToMatV :: Vector Float -> Vector Float\nposToMatV v =\n            [1,0,0,0\n             ,0,1,0,0\n             ,0,0,1,0\n             ,VS.unsafeIndex v 0,VS.unsafeIndex v 1, VS.unsafeIndex v 2,1]\n\nposToMat = tr . LD.reshape 4 . posToMatV\n\nglTexture :: GL.GLuint -> GLRaw.GLenum\nglTexture = (GLRaw.GL_TEXTURE0+) . fromIntegral\n\nlookAt' :: Vector Float -> Vector Float -> Vector Float -> Matrix Float\nlookAt' up eye at =\n  let zaxis = normalize $ eye - at\n      xaxis = normalize $ cross zaxis up\n      yaxis = cross xaxis zaxis\n      crd x = negate $ dot eye x\n  in (4><4) [ xaxis!0,   yaxis!0,   zaxis!0,   0\n            , xaxis!1,   yaxis!1,   zaxis!1,   0\n            , xaxis!2,   yaxis!2,   zaxis!2,   0\n            , crd xaxis, crd yaxis, crd zaxis, 1]\n\npointAt :: Vector Float -> Vector Float\npointAt sp =\n  let up =  [0,1,0]\n      eye = [0,0,0]\n      at  = sp\n      zaxis = normalize $ eye - at\n      xaxis = normalize $ cross zaxis up\n      yaxis = cross xaxis zaxis\n      crd x = negate $ dot eye x\n  in [ xaxis!0,   yaxis!0,   zaxis!0,   0\n     , xaxis!1,   yaxis!1,   zaxis!1,   0\n     , xaxis!2,   yaxis!2,   zaxis!2,   0\n     , crd xaxis, crd yaxis, crd zaxis, 1]\n\n\nlookAt :: Vector Float -> Vector Float -> Matrix Float\nlookAt = lookAt' [0,1,0]\n\n\nnormalize :: Vector Float -> Vector Float\nnormalize v =\n  let n = (1/) . norm $ v\n  in scale n v\n\nremTrans = mat3ToMat4 . mat4ToMat3\n\nmat4ToMat3 :: Matrix Float -> Matrix Float\nmat4ToMat3 = LD.takeRows 3 . LD.takeColumns 3\n\nmat3ToMat4 :: Matrix Float -> Matrix Float\nmat3ToMat4 = helper . LD.flatten\n  -- LD.fromLists . foldr (\\a -> ((a ++ [0]):)) [[0,0,0,1]] . LD.toLists\n  where\n    helper v = (4><4) [ VS.unsafeIndex v 0, VS.unsafeIndex v 1, VS.unsafeIndex v 2, 0\n                      , VS.unsafeIndex v 3, VS.unsafeIndex v 4, VS.unsafeIndex v 5, 0\n                      , VS.unsafeIndex v 6, VS.unsafeIndex v 7, VS.unsafeIndex v 8, 0\n                      ,                  0,                  0,                  0, 1]\n\nprojectionMatrix :: Matrix Float\nprojectionMatrix =\n  (4><4) [ t / as, 0,           0, 0\n         , 0,      t,           0, 0\n         , 0,      0, (f+n)/(n-f),(2*f*n)/(n-f)\n         , 0,      0,          -1, 0]\n  where\n    n = 0.1\n    f = 200\n    t = 1 / tan ((pi/3) / 2)\n    as= 1366/768\n\nmaxSpeed = 10\n\nclampSpeed :: Vector Float -> Vector Float\nclampSpeed v =\n  if norm v >= maxSpeed\n  then LD.cmap (*maxSpeed) . normalize $ v\n  else v\n", "meta": {"hexsha": "e60445b6329f66b60b7aa01dacdad40332bcd87c", "size": 2987, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Utils.hs", "max_stars_repo_name": "Antystenes/CPG", "max_stars_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils.hs", "max_issues_repo_name": "Antystenes/CPG", "max_issues_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils.hs", "max_forks_repo_name": "Antystenes/CPG", "max_forks_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5742574257, "max_line_length": 86, "alphanum_fraction": 0.573150318, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4976822659779271}}
{"text": "{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE DataKinds #-}\n{-# OPTIONS_GHC -Wno-simplifiable-class-constraints #-}\nmodule Data.Matrix.Static.LinearAlgebra.Types\n    ( Numeric(..)\n    , Matrix\n    , MMatrix\n    , SparseMatrix\n    ) where\n\nimport Data.Vector.Storable (Vector, Storable)\nimport Data.Vector.Storable.Mutable (MVector)\nimport Data.Complex (Complex)\nimport Foreign.C.Types\n\nimport qualified Data.Matrix.Static.Dense as D\nimport qualified Data.Matrix.Static.Dense.Mutable as DM\nimport qualified Data.Matrix.Static.Sparse as S\n\nclass (S.Zero a, Storable a, Num a) => Numeric a where\n    foreignType :: a -> CInt\n\ninstance Numeric Float where foreignType _ = 0\ninstance Numeric CFloat where foreignType _ = 0\ninstance Numeric Double where foreignType _ =1\ninstance Numeric (Complex Float) where foreignType _ = 2\ninstance Numeric (Complex Double) where foreignType _ = 3\n\ntype Matrix r c a = D.Matrix r c Vector a\ntype MMatrix r c s a = DM.MMatrix r c MVector s a\n\ntype SparseMatrix r c a = S.SparseMatrix r c Vector a", "meta": {"hexsha": "e3ff0ef75a12ab8f60fd5d7d51e039b75fa1b66b", "size": 1128, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Matrix/Static/LinearAlgebra/Types.hs", "max_stars_repo_name": "kaizhang/matrix-sized", "max_stars_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/Matrix/Static/LinearAlgebra/Types.hs", "max_issues_repo_name": "kaizhang/matrix-sized", "max_issues_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/Matrix/Static/LinearAlgebra/Types.hs", "max_forks_repo_name": "kaizhang/matrix-sized", "max_forks_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "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.2285714286, "max_line_length": 57, "alphanum_fraction": 0.7411347518, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.49742251621945177}}
{"text": "#!/usr/bin/env stack\n-- stack --resolver lts-15.04 runghc --package reanimate\nmodule Main where\n\nimport           Codec.Picture.Types\nimport           Control.Lens\nimport           Control.Monad\nimport           Data.List\nimport           Data.Maybe\nimport qualified Data.Text                     as T\nimport           Data.Tuple\nimport qualified Data.Vector                   as V\nimport           Linear.V2\nimport           Linear.Vector\nimport qualified Numeric.LinearAlgebra         as Matrix\nimport           Numeric.LinearAlgebra.HMatrix (Matrix, linearSolve, toLists,\n                                                (><))\nimport           Reanimate\nimport           Reanimate.Math.Common\nimport           Reanimate.Math.Polygon\n\nbgColor :: PixelRGBA8\nbgColor = PixelRGBA8 252 252 252 0xFF\n\ntype Points = V.Vector (V2 Double)\ntype Edges = [(Int, Int, Int)]\ndata Mesh = Mesh { meshPoints :: Points, meshEdges :: Edges }\ndata MeshPair = MeshPair Points Points Edges\n-- The points in a RelMesh are:\n--   relMeshStatic ++ x where Ax = B\ndata RelMesh = RelMesh\n  { relMeshStatic :: Points\n  , relMeshEdges  :: Edges\n  , relMeshA      :: Matrix Double\n  , relMeshB      :: Matrix Double\n  }\ndata RelMeshPair = RelMeshPair Points Edges (Matrix Double) (Matrix Double) (Matrix Double) (Matrix Double)\n-- Linear interpolation on RelMesh gives smooth morph.\n-- solveMesh :: RelMesh -> Mesh\n-- mkRelative :: Mesh -> RelMesh\n-- mkRelativePair :: MeshPair -> RelMeshPair\n-- triangulate :: Polygon -> Polygon -> MeshPair ?\n-- embed :: MeshPair -> MeshPair\n-- compatible :: Mesh -> Mesh -> Maybe MeshPair\n-- linearInterpolate :: MeshPair -> Double -> Mesh\n-- convexInterpolate :: RelMeshPair -> Double -> RelMesh\n\nmeshToPolygon :: Mesh -> Polygon\nmeshToPolygon mesh = pScale 2 $ mkPolygon $ V.fromList\n    [ realToFrac <$> (meshPoints mesh V.! (n-1))\n    | n <- polygonNodes ]\n  where\n    polygonNodes :: [Int]\n    polygonNodes = [5,8,9,7,4,6]\n\nmain :: IO ()\nmain = reanimate morphAnimation\n\ngenTrails :: (Double -> Mesh) -> SVG\ngenTrails mkMesh =\n    withFillOpacity 0 $\n    withStrokeWidth (defaultStrokeWidth*0.5) $\n    withStrokeColor \"black\" $\n    withStrokeDashArray [0.1,0.1] $\n    mkGroup $ map mkTrail $ transpose\n      [ V.toList $ V.map (fmap realToFrac) $ polygonPoints $ meshToPolygon mesh\n      | n <- [0..steps]\n      , let mesh = mkMesh (fromIntegral n / fromIntegral steps)\n      ]\n  where\n    steps = 100 :: Int\n    mkTrail lst =mkLinePath [ (x,y) | V2 x y <- lst ]\n\nmorphAnimation :: Animation\nmorphAnimation = playThenReverseA $ pauseAround 1 1 $ addStatic (mkBackgroundPixel bgColor) $\n  signalA (curveS 2) $ mkAnimation 5 $ \\t -> lowerTransformations $ scale 3 $ pathify $\n  mkGroup\n  [ translate (-1.5) 0 $ withFillColor \"lightgreen\" $ mkGroup\n    [ withStrokeWidth defaultStrokeWidth $\n      withStrokeColor \"black\" $\n      polygonShape $ meshToPolygon $ linearInterpolate meshPair t\n    , linearTrails\n    , polygonNumDots (meshToPolygon $ linearInterpolate meshPair t) 0\n    ]\n  , translate 1 0 $ withFillColor \"cyan\" $ mkGroup\n    [ withStrokeWidth defaultStrokeWidth $\n      withStrokeColor \"black\" $\n      polygonShape $ meshToPolygon $ solveMesh $ convexInterpolate relPair t\n    , curveTrails\n    , polygonNumDots (meshToPolygon $ solveMesh $ convexInterpolate relPair t) 0\n    ]\n  ]\n  where\n    linearTrails = genTrails (linearInterpolate meshPair)\n    curveTrails = genTrails (solveMesh . convexInterpolate relPair)\n    relPair = mkRelativePair meshPair\n    meshPair = fromJust $ compatible example1 example2\n\nmkLineP :: P -> P -> SVG\nmkLineP (V2 x1 y1) (V2 x2 y2) = mkLine (x1,y1) (x2,y2)\n\n-- FIXME: Check that the triangles are all anticlockwise.\n-- FIXME: Check that the edges connect all the points.\n-- FIXME: Check that the edgse leave no gaps.\ncompatible :: Mesh -> Mesh -> Maybe MeshPair\ncompatible a b =\n  if meshEdges a == meshEdges b && V.length (meshPoints a) == V.length (meshPoints b)\n    then Just $ MeshPair (meshPoints a) (meshPoints b) (meshEdges a)\n    else Nothing\n\nlinearInterpolate :: MeshPair -> Double -> Mesh\nlinearInterpolate (MeshPair aP bP edges) t = Mesh\n    { meshPoints = V.zipWith (lerp (1-t)) aP bP\n    , meshEdges = edges }\n\nexample1 :: Mesh\nexample1 = Mesh points edges\n  where\n    points = V.fromList\n      [ V2 1 0\n      , V2 (-1/2) (sqrt 3 / 2)\n      , V2 (-1/2) (-sqrt 3 / 2)\n      , 3 * points V.! 0 ^/ 4\n      , 3 * points V.! 1 ^/ 4\n      , 3 * points V.! 2 ^/ 4\n      , points V.! 0 ^/ 2\n      , points V.! 1 ^/ 2\n      , points V.! 2 ^/ 2\n      ]\n    edges =\n      [ (1,5,4), (1,2,5), (2,6,5), (2,3,6), (3,4,6), (3,1,4)\n      , (4,8,7), (4,5,8), (5,9,8), (5,6,9), (6,7,9), (6,4,7), (7,8,9)]\n\nexample2 :: Mesh\nexample2 = Mesh points edges\n  where\n    points = V.fromList\n      [ V2 1 0\n      , V2 (-1/2) (sqrt 3 / 2)\n      , V2 (-1/2) (-sqrt 3 / 2)\n      , 3 * points V.! 2 ^/ 4\n      , 3 * points V.! 0 ^/ 4\n      , 3 * points V.! 1 ^/ 4\n      , points V.! 1  ^/ 2\n      , points V.! 2 ^/ 2\n      , points V.! 0 ^/ 2\n      ]\n    edges = meshEdges example1\n\n-- T = (U, G)\n-- G = [Polygon]\n-- U = nub $ concat G\n\nfindStarNeighbours :: Eq a => [(a,a,a)] -> a -> [(a, a)]\nfindStarNeighbours allTrig self =\n  [ (b,c)\n  | (a,b,c) <- allTrig\n  , self == a\n  ] ++\n  [ (c,a)\n  | (a,b,c) <- allTrig\n  , self == b\n  ] ++\n  [ (a,b)\n  | (a,b,c) <- allTrig\n  , self == c\n  ]\n\nisInterior :: Eq a => [(a, a)] -> Bool\nisInterior = isJust . getExteriorPoly\n\ngetExteriorPoly :: Eq a => [(a, a)] -> Maybe [a]\ngetExteriorPoly [] = Nothing\ngetExteriorPoly ((a,b):rest) = worker [a] a b rest\n  where\n    worker acc start this [] = do\n      guard (start == this)\n      return (reverse acc)\n    worker acc start this xs =\n      case lookup this xs of\n        Just next -> worker (this:acc) start next (delete (this,next) xs)\n        Nothing   ->\n          case lookup this (map swap xs) of\n            Just next -> worker (this:acc) start next (delete (next, this) xs)\n            Nothing   -> Nothing\n\nconvexInterpolate :: RelMeshPair -> Double -> RelMesh\nconvexInterpolate (RelMeshPair static edges leftM leftB rightM rightB) t =\n  RelMesh\n  { relMeshStatic = static\n  , relMeshEdges  = edges\n  , relMeshA      = Matrix.scale (1-t) leftM +\n                    Matrix.scale t rightM\n  , relMeshB      = Matrix.scale (1-t) leftB +\n                    Matrix.scale t rightB\n  }\n\nsolveMesh :: RelMesh -> Mesh\nsolveMesh (RelMesh static edges m b) =\n  case linearSolve m b of\n    Nothing -> error \"Failed to solve mesh\"\n    Just ret ->\n      Mesh (static <> V.fromList (worker (toLists ret))) edges\n  where\n    worker []             = []\n    worker ([x]:[y]:rest) = V2 x y : worker rest\n    worker _              = error \"invalid result\"\n\nmkRelative :: Mesh -> RelMesh\nmkRelative (Mesh points edges) = RelMesh (V.fromList exteriorPoints) edges mM bM\n  where\n    mM = (s><s) (concat m)\n    bM = (s><1) b\n    (s,exterior, (m, b)) = toParameters points edges\n    exteriorPoints =\n      [ points V.! (i-1)\n      | i <- exterior\n      ]\n\nmkRelativePair :: MeshPair -> RelMeshPair\nmkRelativePair (MeshPair p1 p2 edges) =\n  let RelMesh static _ leftM leftB = mkRelative (Mesh p1 edges)\n      RelMesh _ _ rightM rightB = mkRelative (Mesh p2 edges)\n  in RelMeshPair static edges leftM leftB rightM rightB\n\ntoParameters :: (Ord b, Fractional b) => V.Vector (V2 b) -> [(Int, Int, Int)] -> (Int, [Int], ([[b]], [b]))\ntoParameters points groups = (length interior*2,exterior,unzip $ concat\n  [ let lst = [(if i == j then -1 else t)\n              | j <- interior\n              , let t = fromMaybe 0 $ lookup (i,j) lam_ij_cache\n              ]\n        pos = negate $ sum\n           [ pj ^* t\n           | j <- exterior\n           , let t = fromMaybe 0 $ lookup (i,j) lam_ij_cache\n                 pj = points V.! (j-1)\n           ]\n    in [ (dupX lst, pos ^. _x)\n       , (dupY lst, pos ^. _y)]\n  | i <- interior ])\n  where\n    lam_ij_cache = lam_ij points groups\n    dupX []     = []\n    dupX (x:xs) = x:0:dupX xs\n    dupY []     = []\n    dupY (x:xs) = 0:x:dupY xs\n    (interior, exterior) =\n      partition (isInterior . findStarNeighbours groups) [1 .. length points]\n\nlam_ij :: (Ord b, Fractional b) => V.Vector (V2 b) -> [(Int, Int, Int)] -> [((Int, Int), b)]\nlam_ij points groups =\n  [ ((i, j), t)\n  | i <- [1..V.length points]\n  , (j, t) <- lam_j points groups i\n  ]\n\nlam_j :: (Ord b, Fractional b) => V.Vector (V2 b) -> [(Int, Int, Int)] -> Int -> [(Int, b)]\nlam_j points groups p =\n  [ (nP, sum [ t | (j,_k,t) <- mu, j == nP ] / fromIntegral (length nPoints))\n  | let n = findStarNeighbours groups p\n        nPoints = fromMaybe [] $ getExteriorPoly n\n        mu = calcMu points groups p\n  , nP <- nPoints ]\n\ncalcMu :: (Ord c, Fractional c) => V.Vector (V2 c) -> [(Int, Int, Int)] -> Int -> [(Int, Int, c)]\ncalcMu points groups p = concat\n    [ [ (nP, nP, t1)\n      , (a, nP, t2)\n      , (b, nP, t3) ]\n      -- (nP, a, b)\n    | {-p <- [1..length points]-}\n      let selfVert = points V.! (p-1)\n          n = findStarNeighbours groups p\n          nPoints :: [Int]\n          nPoints = fromMaybe [] $ getExteriorPoly n\n    , nP <- nPoints\n    , let vert = points V.! (nP-1)\n    , let line = (vert, selfVert)\n    , let (a,b,aP,bP) = head $\n            [ (_a,_b,_aP,_bP)\n            | (_a,_b) <- n\n            , let _aP = points V.! (_a-1)\n                  _bP = points V.! (_b-1)\n                  segment = (points V.! (_a-1), points V.! (_b-1))\n            , case rayIntersect line segment of\n                Nothing -> False\n                Just u  -> isBetween u segment\n            , _a /= nP\n            , _b /= nP ]\n    -- , b == (nPoints ++ nPoints) !! i\n    , let (t1,t2,t3) = barycentricCoords vert aP bP selfVert\n    ]\n\ngenColor :: Int -> Int -> PixelRGBA8\ngenColor n m =\n    promotePixel $ parula (fromIntegral (n+offset) / fromIntegral (m+offset))\n  where\n    offset = 5\n\npolygonNumDots :: Polygon -> Double -> SVG\npolygonNumDots p t = mkGroup $ reverse\n    [ mkGroup\n      [ colored n $ withStrokeWidth (defaultStrokeWidth*0.5) $ withStrokeColor \"black\" $\n        translate x y $ mkCircle circR\n      , withFillColor \"black\" $\n        translate x y $ ppNum n ]\n    | n <- [0..pSize p-1]\n    , let a = realToFrac <$> pAccess p n\n          b = realToFrac <$> pAccess p (pNext p n)\n          V2 x y = lerp t b a ]\n  where\n    circR = 0.1\n    colored n =\n      let c = genColor n (pSize p-1)\n      in withFillColorPixel c\n    ppNum n = scaleToHeight (circR*1.5) $ center $ latex $ T.pack $ \"\\\\texttt{\" ++ show n ++ \"}\"\n\npolygonShape :: Polygon -> SVG\npolygonShape p = mkLinePathClosed\n  [ (x,y) | V2 x y <- map (fmap realToFrac) $ V.toList (polygonPoints p) ]\n", "meta": {"hexsha": "bf543dfe190eee809f9df020954c9684dff032e9", "size": 10598, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/morphology_point_trajectory.hs", "max_stars_repo_name": "TristanCacqueray/reanimate", "max_stars_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/morphology_point_trajectory.hs", "max_issues_repo_name": "TristanCacqueray/reanimate", "max_issues_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/morphology_point_trajectory.hs", "max_forks_repo_name": "TristanCacqueray/reanimate", "max_forks_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.015576324, "max_line_length": 107, "alphanum_fraction": 0.5832232497, "num_tokens": 3319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49731912258757494}}
{"text": "{-# LANGUAGE DeriveFunctor #-}\nmodule Net where\n\nimport Prelude hiding (id,(.))\n\nimport Numeric.LinearAlgebra hiding (range)\nimport Data.Traversable\nimport System.Random\nimport Data.Array\n\nimport Debug.Trace\nimport Control.Category\n\n--A function with a deriviative\n--a and b are assumed to be numbers, and thus their own tangent/cotangent spaces\ndata DifferentiableFunction a b =\n  DiffFunction { dfRun :: (a -> b)\n               , dfDerivative :: (a -> (a -> b))\n               }\n\n\ntype DF = DifferentiableFunction\n\ninstance Category DifferentiableFunction where\n  id = DiffFunction id (const id)\n  (DiffFunction f df) . (DiffFunction g dg) =\n    DiffFunction (f . g) (\\x -> (df (g x)) . (dg x))\n\nsimpleDiff :: (Num a) => DifferentiableFunction a b -> (a -> b)\nsimpleDiff df = (\\x -> dfDerivative df x 1)\n\n{-\ninstance Category DifferentiableFunction where\n  id = DiffFunction id id\n  (DiffFunction f df) . (DiffFunction g dg) = DiffFunction (f . g) ((f . dg)??df)\n-}\ndata Layer c = Layer\n  { layerWeights :: c\n  , layerActivation :: DifferentiableFunction Double Double\n  } deriving (Functor)\n\ninstance (Show c) => Show (Layer c) where\n  show = show . layerWeights\n\ndata Net c = Net\n  { netLayerSizes :: [Int]\n  , netContent :: [Layer c]} deriving (Functor,Show)\n\nnetParameters :: Net c -> [c]\nnetParameters = (map layerWeights) . netContent\n\ntype NetShape = Net ()\ntype DoubleNet = Net (Matrix Double)\n\n\nrunLayer :: Layer (Matrix Double) -> Vector Double -> Vector Double\nrunLayer Layer{layerWeights=inputs,layerActivation=act} v =\n  cmap (dfRun act) $ inputs #> v\n\nrunNet :: Net (Matrix Double) -> Vector Double -> Vector Double\nrunNet net input =\n  --first layer needs a fake input that's always 1\n  let realInput = vjoin [input,1.0]\n  in foldl (flip runLayer) realInput (netContent net)\n\ncreateSingle :: Int -> Int -> Double -> Vector Double\ncreateSingle n i x = assoc n 0 [(i,x)]\n\nrunAndDiffLayer :: Layer (Matrix Double) -> Vector Double -> (Vector Double,Array (Int,Int) (Vector Double),Matrix Double)\nrunAndDiffLayer Layer{layerWeights=weights,layerActivation=act} input =\n  let dact = simpleDiff act\n      linearValues = weights #> input\n      output = cmap (dfRun act) linearValues\n      (nR,nC) = size weights\n      limit = (nR-1,nC-1)\n\n      deriveArrayValue r c = (dact $ atIndex linearValues r)*(atIndex input c)\n\n      derivArray =\n        listArray ((0,0),limit) $\n        (\\(r,c) -> createSingle nR r $ deriveArrayValue r c) <$> range ((0,0),limit)\n      dactMatrix = (diag  (cmap dact linearValues))\n  in (output,derivArray,dactMatrix <> weights)\n\nrunAndDiffNet :: Net (Matrix Double) -> Vector Double -> (Vector Double,[Array (Int,Int) (Vector Double)])\nrunAndDiffNet net input =\n  let realInput = vjoin [input,1.0]\n  in foldl (\\(newIn,prevDiff) l ->\n               let (nextIn,layerDiff,layerVDiff) = (runAndDiffLayer l newIn)\n               in (nextIn,((fmap (layerVDiff #>)) <$> prevDiff) ++ [layerDiff]))\n     (realInput,[]) $ netContent net\n\nrunAndDiffWithError :: Net (Matrix Double) -> Vector Double -> DifferentiableFunction (Vector Double) Double -> (Vector Double,Double,[Matrix Double])\nrunAndDiffWithError net input errFunc =\n  let (out,grad) = runAndDiffNet net input\n      derr = dfDerivative errFunc\n  in (out,dfRun errFunc out,((fromArray2D . fmap (\\v -> (derr out v))) <$> grad))\n\nmodifyNet :: Net a -> [b] -> Net b\nmodifyNet net contents =\n  net{netContent = zipWith (\\m l -> m <$ l) contents $ netContent net}\n\nupdateNet :: Net (Matrix Double) -> [Matrix Double] -> Double -> Net (Matrix Double)\nupdateNet net grad c =\n  let param = netParameters net\n      newParams = zipWith (\\oldM gradM -> oldM + scale c gradM) param grad\n  in modifyNet net newParams\n\ntanhFunc :: DifferentiableFunction Double Double\ntanhFunc = DiffFunction f (\\y c -> c*(let z = f y in 1-z^2))\n  where\n    f :: Double -> Double\n    f = tanh\n\n--layerAsDiffFunc :: Layer (Matrix Double) -> DifferentiableFunction (Matrix Double,Vector Double) (Vector Double)\n\n--netAsDiffFunction :: Net (Matrix Double) -> DifferentiableFunction ([Matrix Double],Vector Double) (Vector Double)\n\nrandomSimpleNet :: Int -> Int -> Int -> IO (Net (Matrix Double))\nrandomSimpleNet numIn numOut internal=\n  do layer1 <- Layer <$> (scale (1/(fromIntegral (numIn+1))) <$> randn internal (numIn+1)) <*> pure tanhFunc\n\n     layer2 <- Layer <$> (scale (1/(fromIntegral internal)) <$> randn numOut internal) <*> pure tanhFunc\n\n     return $ Net [numIn,internal,numOut] [layer1,layer2]\n", "meta": {"hexsha": "62ab97ba9ceb6ff822d5c86c54eb0599ed648077", "size": 4465, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Net.hs", "max_stars_repo_name": "jkelleyy/sinenet", "max_stars_repo_head_hexsha": "367ad0dd2762578c34ef56c8532ce884768fac47", "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/Net.hs", "max_issues_repo_name": "jkelleyy/sinenet", "max_issues_repo_head_hexsha": "367ad0dd2762578c34ef56c8532ce884768fac47", "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/Net.hs", "max_forks_repo_name": "jkelleyy/sinenet", "max_forks_repo_head_hexsha": "367ad0dd2762578c34ef56c8532ce884768fac47", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4365079365, "max_line_length": 150, "alphanum_fraction": 0.6799552072, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.49710945874102924}}
{"text": "{-\n - Hacq (c) 2013 NEC Laboratories America, Inc.  All rights reserved.\n -\n - This file is part of Hacq.\n - Hacq is distributed under the 3-clause BSD license.\n - See the LICENSE file for more details.\n -}\n\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule Control.Monad.Quantum.ApproxSequence.Class (MonadApproxSequence(..), applyPrepareQubitApprox, applyGlobalPhase) where\n\nimport Control.Monad.Reader (ReaderT)\nimport Control.Monad.Trans (MonadTrans, lift)\nimport Data.Complex\n\nimport Control.Monad.Quantum.Class\n\nclass MonadQuantumBase w m => MonadApproxSequence w m | m -> w where\n  -- |@applyOneQubitUnitary a c d w@ applies unitary U to wire w, where U is given by the following matrix:\n  --\n  -- > a c*\n  -- > c d\n  applyOneQubitUnitary :: Complex Double -> Complex Double -> Complex Double -> w -> m ()\n\n-- |@applyPrepareQubitApprox a b@ prepares a qubit in a state a|0>+b|1>.\napplyPrepareQubitApprox :: MonadApproxSequence w m => Complex Double -> Complex Double -> m w\napplyPrepareQubitApprox a b = do\n    w <- ancilla\n    applyOneQubitUnitary a b (-conjugate a) w\n    return w\n{-# INLINABLE applyPrepareQubitApprox #-}\n\napplyGlobalPhase :: (MonadQuantum w m, MonadApproxSequence w m) => Double -> m ()\napplyGlobalPhase fraction =\n    handleMaybeCtrl $ \\ctrl ->\n      case ctrl of\n        Nothing -> return ()\n        Just ctrlwire ->\n          applyOneQubitUnitary 1 0 (cis (2 * pi * fraction)) ctrlwire\n{-# INLINABLE applyGlobalPhase #-}\n\n-- Instance for ReaderT\n\ninstance MonadApproxSequence w m => MonadApproxSequence w (ReaderT r m) where\n  applyOneQubitUnitary a c d w = lift $ applyOneQubitUnitary a c d w\n  {-# INLINABLE applyOneQubitUnitary #-}\n", "meta": {"hexsha": "8ee51747d41e5708a0f8d987d28c398e1afc5675", "size": 1776, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Control/Monad/Quantum/ApproxSequence/Class.hs", "max_stars_repo_name": "ti1024/hacq", "max_stars_repo_head_hexsha": "394f51890ac98f35c274d06d109929b512a14b6d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-01-16T14:50:29.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-16T14:50:29.000Z", "max_issues_repo_path": "src/Control/Monad/Quantum/ApproxSequence/Class.hs", "max_issues_repo_name": "ti1024/hacq", "max_issues_repo_head_hexsha": "394f51890ac98f35c274d06d109929b512a14b6d", "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/Control/Monad/Quantum/ApproxSequence/Class.hs", "max_forks_repo_name": "ti1024/hacq", "max_forks_repo_head_hexsha": "394f51890ac98f35c274d06d109929b512a14b6d", "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.8235294118, "max_line_length": 124, "alphanum_fraction": 0.7150900901, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.4970323181248274}}
{"text": "{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DeriveAnyClass        #-}\n{-# LANGUAGE DeriveGeneric         #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE OverloadedStrings     #-}\n{-|\nModule      : Grenade.Layers.GlobalAvgPool\nDescription : Global Average Pooling\nMaintainer  : Theo Charalambous\nLicense     : BSD2\nStability   : experimental\n\nThe layer follows the implementation as introduced in the paper:\nMin Lin, Qiang Chen, Shuicheng Yan. Network In Network\n<https://arxiv.org/abs/1312.4400>\n-}\n\nmodule Grenade.Layers.GlobalAvgPool \n  (\n  -- * Layer definition\n    GlobalAvgPool (..)\n  )\nwhere\n\nimport           Control.DeepSeq                (NFData (..))\nimport           Data.Serialize\nimport           Data.Singletons\nimport           GHC.Generics                   (Generic)\nimport           GHC.TypeLits\n\nimport qualified Numeric.LinearAlgebra.Static   as H\n\nimport           Grenade.Core\nimport           Grenade.Utils.LinearAlgebra\n\nimport           Grenade.Onnx\n\ndata GlobalAvgPool = GlobalAvgPool\n  deriving (Generic, NFData, Show)\n\ninstance UpdateLayer GlobalAvgPool where\n  type Gradient GlobalAvgPool = ()\n  runUpdate _ _ _ = GlobalAvgPool\n  reduceGradient _ = ()\n\ninstance RandomLayer GlobalAvgPool where\n  createRandomWith _ _ = return GlobalAvgPool\n\ninstance Serialize GlobalAvgPool where\n  put _ = return ()\n  get   = return GlobalAvgPool\n\n-- | Performing a global average pool on a 1d vector will take the average of the elements and\n--   return a vector of size 1\ninstance (KnownNat i) => Layer GlobalAvgPool ('D1 i) ('D1 1) where\n  type Tape GlobalAvgPool ('D1 i) ('D1 1) = S ('D1 i)\n\n  runForwards _ x = \n    let n   = fromIntegral $ natVal (Proxy :: Proxy i)\n        avg = nsum x / n\n        vec = listToVector [avg]   \n    in  (x, S1D vec)\n\n  runBackwards = undefined\n\n-- | Performing a global average pool on a 2d matrix will take the average of the elements\n--   and return a matrix of size 1x1\ninstance (KnownNat i, KnownNat j) => Layer GlobalAvgPool ('D2 i j) ('D2 1 1) where\n  type Tape GlobalAvgPool ('D2 i j) ('D2 1 1) = S ('D2 i j)\n\n  runForwards _ x =\n    let n   = fromIntegral $ natVal (Proxy :: Proxy i)\n        m   = fromIntegral $ natVal (Proxy :: Proxy j)\n        avg = nsum x / (n * m)\n        mat = H.fromList [avg]\n    in  (x, S2D mat)\n\n  runBackwards = undefined\n\n-- | Performing a global average pool on a 3d matrix with k channels will take the average of the elements\n--   channel-wise and return a 3d matrix with k channels each of size 1x1\ninstance (KnownNat i, KnownNat j, KnownNat k) => Layer GlobalAvgPool ('D3 i j k) ('D3 1 1 k) where\n\n  type Tape GlobalAvgPool ('D3 i j k) ('D3 1 1 k) = S ('D3 i j k)\n\n  runForwards _ x =\n    let n   = fromIntegral $ natVal (Proxy :: Proxy i)\n        m   = fromIntegral $ natVal (Proxy :: Proxy j)\n        cs  = splitChannels x\n        ys  = map (\\c -> nsum c / (n * m)) cs\n        mat = H.fromList ys \n    in  (x, S3D mat)\n\n  runBackwards = undefined\n\ninstance OnnxOperator GlobalAvgPool where\n  onnxOpTypeNames _ = [\"GlobalAveragePool\"]\n\ninstance OnnxLoadableActivation GlobalAvgPool where\n  activationLayer = GlobalAvgPool\n", "meta": {"hexsha": "31ae0c8caa871ba7146d1b36cf319e0053d8fbcc", "size": 3327, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/GlobalAvgPool.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/GlobalAvgPool.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/GlobalAvgPool.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3867924528, "max_line_length": 106, "alphanum_fraction": 0.6540426811, "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4970224151793786}}
{"text": "{-# LANGUAGE DataKinds, TypeFamilies #-}\n{-# OPTIONS_GHC -Wno-missing-export-lists #-}\n-- | Scalar-based implementation of fully connected neutral network\n-- for classification of MNIST digits. Sports 2 hidden layers.\nmodule HordeAd.Tool.MnistFcnnScalar where\n\nimport Prelude\n\nimport           Control.Exception (assert)\nimport           Data.Proxy (Proxy)\nimport qualified Data.Strict.Vector as Data.Vector\nimport qualified Data.Vector.Generic as V\nimport           GHC.Exts (inline)\nimport           Numeric.LinearAlgebra (Vector)\n\nimport HordeAd.Core.DualNumber\nimport HordeAd.Core.Engine\nimport HordeAd.Core.PairOfVectors (DualNumberVariables, var0)\nimport HordeAd.Tool.MnistData\n\n-- | Compute the output of a neuron, without applying activation function,\n-- from trainable inputs in @xs@ and parameters (the bias and weights)\n-- at @variables@ starting at @offset@. Useful for neurons in the middle\n-- of the network, receiving inputs from other neurons.\nsumTrainableInputs\n  :: forall d r m. DualMonad d r m\n  => Data.Vector.Vector (DualNumber d r) -> Int -> DualNumberVariables d r\n  -> m (DualNumber d r)\nsumTrainableInputs xs offset variables = do\n  let bias = var0 variables offset\n      f :: DualNumber d r -> Int -> DualNumber d r -> DualNumber d r\n      f !acc i u =\n        let v = var0 variables (offset + 1 + i)\n        in acc + u * v\n  returnLet $ V.ifoldl' f bias xs\n\n-- | Compute the output of a neuron, without applying activation function,\n-- from constant data in @xs@ and parameters (the bias and weights)\n-- at @variables@ starting at @offset@. Useful for neurons at the bottom\n-- of the network, tasked with ingesting the data.\nsumConstantData\n  :: forall d r m. DualMonad d r m\n  => Vector r -> Int -> DualNumberVariables d r -> m (DualNumber d r)\nsumConstantData xs offset variables = do\n  let bias = var0 variables offset\n      f :: DualNumber d r -> Int -> r -> DualNumber d r\n      f !acc i r =\n        let v = var0 variables (offset + 1 + i)\n        in acc + scale r v\n  returnLet $ V.ifoldl' f bias xs\n\nhiddenLayerMnist\n  :: forall d r m. DualMonad d r m\n  => (DualNumber d r -> m (DualNumber d r)) -> Vector r\n  -> DualNumberVariables d r -> Int\n  -> m (Data.Vector.Vector (DualNumber d r))\nhiddenLayerMnist factivation input variables width = do\n  let nWeightsAndBias = V.length input + 1\n      f :: Int -> m (DualNumber d r)\n      f i = do\n        outSum <- sumConstantData input (i * nWeightsAndBias) variables\n        factivation outSum\n  V.generateM width f\n\nmiddleLayerMnist\n  :: forall d r m. DualMonad d r m\n  => (DualNumber d r -> m (DualNumber d r))\n  -> Data.Vector.Vector (DualNumber d r)\n  -> Int -> DualNumberVariables d r -> Int\n  -> m (Data.Vector.Vector (DualNumber d r))\nmiddleLayerMnist factivation hiddenVec offset variables width = do\n  let nWeightsAndBias = V.length hiddenVec + 1\n      f :: Int -> m (DualNumber d r)\n      f i = do\n        outSum <- sumTrainableInputs hiddenVec\n                                     (offset + i * nWeightsAndBias)\n                                     variables\n        factivation outSum\n  V.generateM width f\n\noutputLayerMnist\n  :: forall d r m. DualMonad d r m\n  => (Data.Vector.Vector (DualNumber d r)\n      -> m (Data.Vector.Vector (DualNumber d r)))\n  -> Data.Vector.Vector (DualNumber d r) -> Int\n  -> DualNumberVariables d r -> Int\n  -> m (Data.Vector.Vector (DualNumber d r))\noutputLayerMnist factivation hiddenVec offset variables width = do\n  let nWeightsAndBias = V.length hiddenVec + 1\n      f :: Int -> m (DualNumber d r)\n      f i = sumTrainableInputs hiddenVec\n                               (offset + i * nWeightsAndBias)\n                               variables\n  vOfSums <- V.generateM width f\n  factivation vOfSums\n\nfcnnMnistLen0 :: Int -> Int -> Int\nfcnnMnistLen0 widthHidden widthHidden2 =\n  widthHidden * (sizeMnistGlyph + 1)\n  + widthHidden2 * (widthHidden + 1)\n  + sizeMnistLabel * (widthHidden2 + 1)\n\n-- | Fully connected neural network for the MNIST digit classification task.\n-- There are two hidden layers and both use the same activation function.\n-- The output layer uses a different activation function.\n-- The widths of the hidden layers are @widthHidden@ and @widthHidden2@\n-- and from these, the @fcnnMnistLen2@ function computes the number\n-- of scalar dual number parameters (variables) to be given to the program.\nfcnnMnist0 :: forall d r m. DualMonad d r m\n           => (DualNumber d r -> m (DualNumber d r))\n           -> (Data.Vector.Vector (DualNumber d r)\n               -> m (Data.Vector.Vector (DualNumber d r)))\n           -> Int\n           -> Int\n           -> Vector r\n           -> DualNumberVariables d r\n           -> m (Data.Vector.Vector (DualNumber d r))\nfcnnMnist0 factivationHidden factivationOutput widthHidden widthHidden2\n           input variables = do\n  let !_A = assert (sizeMnistGlyph == V.length input) ()\n  layer1 <- inline hiddenLayerMnist factivationHidden input\n                                    variables widthHidden\n  let offsetMiddle = widthHidden * (sizeMnistGlyph + 1)\n  layer2 <- inline middleLayerMnist factivationHidden layer1\n                                    offsetMiddle variables widthHidden2\n  let offsetOutput = offsetMiddle + widthHidden2 * (widthHidden + 1)\n  inline outputLayerMnist factivationOutput layer2\n                          offsetOutput variables sizeMnistLabel\n\n-- | The neural network applied to concrete activation functions\n-- and composed with the appropriate loss function.\nfcnnMnistLoss0\n  :: DualMonad d r m\n  => Int -> Int -> MnistData r -> DualNumberVariables d r\n  -> m (DualNumber d r)\nfcnnMnistLoss0 widthHidden widthHidden2 (input, target) variables = do\n  result <- inline fcnnMnist0 logisticAct softMaxAct\n                              widthHidden widthHidden2 input variables\n  lossCrossEntropy target result\n\n-- | A function testing the neural network given testing set of inputs\n-- and the trained parameters.\n--\n-- The proxy argument is needed only for the (spurious) SPECIALIZE pragma,\n-- becuase I can't write @SPECIALIZE fcnnMnistTest0 \\@Double@.\nfcnnMnistTest0 :: forall r. IsScalar 'DModeGradient r\n           => Proxy r -> Int -> Int -> [MnistData r] -> Domain0 r\n           -> r\nfcnnMnistTest0 _ widthHidden widthHidden2 inputs params0 =\n  let matchesLabels :: MnistData r -> Bool\n      matchesLabels (glyph, label) =\n        let nn = inline (fcnnMnist0 @'DModeGradient) logisticAct softMaxAct\n                                        widthHidden widthHidden2 glyph\n            value = V.map (\\(D r _) -> r)\n                    $ primalValueGeneral nn (params0, V.empty, V.empty, V.empty)\n        in V.maxIndex value == V.maxIndex label\n  in fromIntegral (length (filter matchesLabels inputs))\n     / fromIntegral (length inputs)\n{-# SPECIALIZE fcnnMnistTest0 :: Proxy Double -> Int -> Int -> [MnistData Double] -> Domain0 Double -> Double #-}\n", "meta": {"hexsha": "7b0bd2ea5c620da59a520a5a1ff8fc7130a4c005", "size": 6858, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Tool/MnistFcnnScalar.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HordeAd/Tool/MnistFcnnScalar.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "src/HordeAd/Tool/MnistFcnnScalar.hs", "max_forks_repo_name": "Mikolaj/horde-ad", "max_forks_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8625, "max_line_length": 113, "alphanum_fraction": 0.6684164479, "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4969606510905707}}
{"text": "{-# LANGUAGE BangPatterns          #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE TupleSections         #-}\n{-# LANGUAGE TypeFamilies          #-}\n\nimport           Codec.Picture.Bitmap\nimport           Codec.Picture.Types\nimport           Control.Monad.Random\nimport           Data.Serialize\nimport           Data.Word (Word8)\nimport           GHC.TypeLits\nimport           Grenade\nimport           Options.Applicative\nimport qualified Data.ByteString as B\nimport qualified Data.Vector.Storable as V\nimport qualified Numeric.LinearAlgebra.Static as SA\n\n\ntype ZDim      = 5\ntype TotalDim  = 2+5\ntype OutDim    = 3\ntype Hidden    = 100\n\n-- type BatchSize = 500 * 500\n\ntype CppnNet = Network '[ FullyConnected TotalDim Hidden , Tanh\n                        , FullyConnected Hidden   Hidden , Softmax\n                        , FullyConnected Hidden   Hidden , Tanh\n                        , FullyConnected Hidden   OutDim , Logit\n                        ]\n                       '[ 'D1 TotalDim\n                        , 'D1 Hidden   , 'D1 Hidden\n                        , 'D1 Hidden   , 'D1 Hidden \n                        , 'D1 Hidden   , 'D1 Hidden\n                        , 'D1 OutDim   , 'D1 OutDim\n                        ]\n\n\nrandomNet :: MonadRandom m => m CppnNet\nrandomNet = randomNetwork\n\n\nbuildInputs :: Int \n            -> Int \n            -> S ('D1 ZDim)\n            -> [ S ('D1 TotalDim) ]\nbuildInputs h w (S1D z') = vects\n  where\n    z      = V.toList (SA.unwrap z')\n    start  = -1\n    end    = 1\n    range  = end - start\n    -- TODO: Presently only works for a square.\n    step   = range / (fromIntegral w - 1)\n    pts    = [ start, start + step .. end ]\n    points = [ [x, y] ++ z | x <- pts, y <- pts ]\n\n    vects  = map (S1D . SA.vector) points\n\n\nnetForward :: CppnNet \n           -> Int \n           -> Int \n           -> IO (CppnNet, Image PixelRGB8)\nnetForward net width height = do\n\n  z <- do\n    seed <- getRandom\n    return $ S1D (SA.randomVector seed SA.Uniform :: SA.R ZDim)\n\n  let inputs       = buildInputs width height z\n      outputs      = map (runNet net) inputs\n      extractPixel = toPixel . extract\n\n      pixels :: V.Vector (PixelBaseComponent PixelRGB8)\n      pixels = V.fromList (concatMap extractPixel outputs)\n\n      img :: Image PixelRGB8\n      img = Image width height pixels\n\n  return $ (net, img)\n\n\n\ntoPixel :: (Double, Double, Double) \n        -> [Word8]\ntoPixel (r,g,b) = [ fromIntegral $ round (r * 255)\n                  , fromIntegral $ round (g * 255)\n                  , fromIntegral $ round (b * 255) ]\n\n\nextract :: S ('D1 OutDim) -> (Double, Double, Double)\nextract (S1D a) = let [r,g,b] = V.toList (SA.unwrap a)\n                    in (r,g,b)\n\n\nnetLoad :: FilePath -> IO CppnNet\nnetLoad modelPath = do\n  modelData <- B.readFile modelPath\n  either fail return $ runGet (get :: Get CppnNet) modelData\n\n\ndata CppnOpts = CppnOpts Int Int (Maybe FilePath) (Maybe FilePath)\n\n\nopts :: Parser CppnOpts\nopts =\n  CppnOpts <$> option auto (long \"width\"  <> short 'w' <> value 500)\n           <*> option auto (long \"height\" <> short 'h' <> value 500)\n           <*> optional (strOption (long \"load\"))\n           <*> optional (strOption (long \"save\"))\n\n\nmain :: IO ()\nmain = do\n  CppnOpts width height load save <- execParser (info (opts <**> helper) idm)\n\n  net0 <- case load of\n    Just loadFile -> netLoad loadFile\n    Nothing -> randomNet\n\n  (net, image) <- netForward net0 width height\n\n\n  writeBitmap \"test.png\" image\n\n  case save of\n    Just saveFile -> B.writeFile saveFile $ runPut (put net)\n    Nothing -> return ()\n\n  putStrLn $ \"Done!\"\n", "meta": {"hexsha": "536732de83a0827642b0626ddefefeb2e47deb31", "size": 3674, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "GrenadeCppn/src/Main.hs", "max_stars_repo_name": "silky/fashion", "max_stars_repo_head_hexsha": "2b01d1e5c385fe99e8e54f5828114551e9c8e309", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2018-07-10T23:35:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:39:57.000Z", "max_issues_repo_path": "GrenadeCppn/src/Main.hs", "max_issues_repo_name": "silky/fashion", "max_issues_repo_head_hexsha": "2b01d1e5c385fe99e8e54f5828114551e9c8e309", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 205, "max_issues_repo_issues_event_min_datetime": "2015-03-25T08:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T21:31:12.000Z", "max_forks_repo_path": "GrenadeCppn/src/Main.hs", "max_forks_repo_name": "silky/fashion", "max_forks_repo_head_hexsha": "2b01d1e5c385fe99e8e54f5828114551e9c8e309", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-07-10T23:38:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:53:29.000Z", "avg_line_length": 27.4179104478, "max_line_length": 77, "alphanum_fraction": 0.5579749592, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4969606487785663}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes                      #-}\n{-# LANGUAGE DataKinds                                #-}\n{-# LANGUAGE FlexibleContexts                         #-}\n{-# LANGUAGE FlexibleInstances                        #-}\n{-# LANGUAGE MultiParamTypeClasses                    #-}\n{-# LANGUAGE PatternSynonyms                          #-}\n{-# LANGUAGE RankNTypes                               #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeFamilies                             #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# LANGUAGE UndecidableInstances                     #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise       #-}\n\nmodule Backprop.Learn.Model.Neural (\n    -- * Feed-forward\n    FCp, fc, fca\n  , fcWeights, fcBias\n    -- * Recurrent\n  , fcr, fcra\n  , FCRp, fcrBias, fcrInputWeights, fcrStateWeights\n  ) where\n\n\nimport           Backprop.Learn.Model.Combinator\nimport           Backprop.Learn.Model.Regression\nimport           Backprop.Learn.Model.State\nimport           Backprop.Learn.Model.Types\nimport           Data.Tuple\nimport           GHC.TypeNats\nimport           Lens.Micro\nimport           Numeric.Backprop\nimport           Numeric.LinearAlgebra.Static.Backprop\nimport qualified Numeric.LinearAlgebra.Static          as H\n\n-- | Parameters for fully connected feed-forward layer with bias.\ntype FCp = LRp\n\nfcWeights :: Lens (FCp i o) (FCp i' o) (L o i) (L o i')\nfcWeights = lrBeta\n\nfcBias :: forall i o. Lens' (FCp i o) (R o)\nfcBias = lrAlpha\n\n-- | Fully connected feed-forward layer with bias.  Parameterized by its\n-- initialization distribution.\n--\n-- Note that this has no activation function; to use as a model with\n-- activation function, chain it with an activation function using 'RMap',\n-- ':.~', etc.; see 'FCA' for a convenient type synonym and constructor.\n--\n-- Without any activation function, this is essentially a multivariate\n-- linear regression.\n--\n-- With the logistic function as an activation function, this is\n-- essentially multivariate logistic regression. (See 'logReg')\nfc  :: (KnownNat i, KnownNat o)\n    => Model ('Just (FCp i o)) 'Nothing (R i) (R o)\nfc = linReg\n\n-- | Convenient synonym for an 'fC' post-composed with a simple\n-- parameterless activation function.\nfca :: (KnownNat i, KnownNat o)\n    => (forall z. Reifies z W => BVar z (R o) -> BVar z (R o))\n    -> Model ('Just (FCp i o)) 'Nothing (R i) (R o)\nfca f = funcD f <~ linReg\n\n-- | Fully connected recurrent layer with bias.\nfcr :: (KnownNat i, KnownNat o, KnownNat s)\n    => (forall z. Reifies z W => BVar z (R o) -> BVar z (R s))      -- ^ store\n    -> Model ('Just (FCRp s i o)) ('Just (R s)) (R i) (R o)\nfcr s = recurrent H.split (H.#) s fc\n\n-- | Convenient synonym for an 'fcr' post-composed with a simple\n-- parameterless activation function.\nfcra\n    :: (KnownNat i, KnownNat o, KnownNat s)\n    => (forall z. Reifies z W => BVar z (R o) -> BVar z (R o))\n    -> (forall z. Reifies z W => BVar z (R o) -> BVar z (R s))      -- ^ store\n    -> Model ('Just (FCRp s i o)) ('Just (R s)) (R i) (R o)\nfcra f s = funcD f <~ recurrent H.split (H.#) s fc\n\n-- | Parameter for fully connected recurrent layer.\ntype FCRp s i o = FCp (i + s) o\n\nlensIso :: (s -> (a, x)) -> ((b, x) -> t) -> Lens s t a b\nlensIso f g h x = g <$> _1 h (f x)\n\nfcrInputWeights\n    :: (KnownNat s, KnownNat i, KnownNat i', KnownNat o)\n    => Lens (FCRp s i o) (FCRp s i' o) (L o i) (L o i')\nfcrInputWeights = fcWeights\n                . lensIso H.splitCols (uncurry (H.|||))\n\nfcrStateWeights\n    :: (KnownNat s, KnownNat s', KnownNat i, KnownNat o)\n    => Lens (FCRp s i o) (FCRp s' i o) (L o s) (L o s')\nfcrStateWeights = fcWeights\n                . lensIso (swap . H.splitCols) (uncurry (H.|||) . swap)\n\nfcrBias :: forall s i o. Lens' (FCRp s i o) (R o)\nfcrBias = fcBias @(i + s) @o\n", "meta": {"hexsha": "bba8154d36aeae1f293d93da7d1a141a3031f861", "size": 3953, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Backprop/Learn/Model/Neural.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "src/Backprop/Learn/Model/Neural.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "src/Backprop/Learn/Model/Neural.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 38.0096153846, "max_line_length": 78, "alphanum_fraction": 0.5886668353, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4969606441545574}}
{"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE KindSignatures      #-}\n{-# LANGUAGE RankNTypes          #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators       #-}\n\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\nmodule Test.Hedgehog.Hmatrix where\n\nimport           GHC.Stack                    (HasCallStack,\n                                               withFrozenCallStack)\n\nimport           Data.Singletons\nimport           Data.Singletons.TypeLits\nimport           Grenade\n\nimport           GHC.TypeLits\n\nimport           Hedgehog                     (Gen, MonadTest, diff)\nimport qualified Hedgehog.Gen                 as Gen\nimport qualified Hedgehog.Range               as Range\n\nimport           Numeric.LinearAlgebra        (norm_Inf)\nimport           Numeric.LinearAlgebra.Data   hiding ((===))\nimport qualified Numeric.LinearAlgebra.Static as H\n\nimport           Test.Hedgehog.Compat\n\nrandomVector :: forall n. ( KnownNat n ) =>  Gen (H.R n)\nrandomVector = (\\s -> H.randomVector s H.Uniform * 2 - 1) <$> Gen.int Range.linearBounded\n\nrandomPositiveVector :: forall n. ( KnownNat n ) =>  Gen (H.R n)\nrandomPositiveVector = (\\s -> H.randomVector s H.Uniform) <$> Gen.int Range.linearBounded\n\nrandomVectorNormalised :: forall n. ( KnownNat n ) =>  Gen (H.R n)\nrandomVectorNormalised = (\\s -> sigmoid ((H.randomVector s H.Uniform) * 2 - 1)) <$> Gen.int Range.linearBounded\n  where\n    sigmoid :: Floating a => a -> a\n    sigmoid x = 1/(1 + exp (-x))\n\nuniformSample :: forall m n. ( KnownNat m, KnownNat n ) => Gen (H.L m n)\nuniformSample = (\\s -> H.uniformSample s (-1) 1 ) <$> Gen.int Range.linearBounded\n\n-- | Generate random data of the desired shape\ngenOfShape :: forall x. ( SingI x ) => Gen (S x)\ngenOfShape =\n  case (sing :: Sing x) of\n    D1Sing l ->\n      withKnownNat l $\n        S1D <$> randomVector\n    D2Sing r c ->\n      withKnownNat r $ withKnownNat c $\n        S2D <$> uniformSample\n    D3Sing r c d ->\n      withKnownNat r $ withKnownNat c $ withKnownNat d $\n        S3D <$> uniformSample\n    D4Sing n c h w ->\n      withKnownNat n $ withKnownNat c $ withKnownNat h $ withKnownNat w $\n        S4D <$> uniformSample\n\nnice :: S shape -> String\nnice (S1D x) = show . H.extract $ x\nnice (S2D x) = show . H.extract $ x\nnice (S3D x) = show . H.extract $ x\nnice (S4D x) = show . H.extract $ x\n\nallClose :: SingI shape => S shape -> S shape -> Bool\nallClose xs ys = case xs - ys of\n  (S1D x) -> H.norm_Inf x < 0.0001\n  (S2D x) -> H.norm_Inf x < 0.0001\n  (S3D x) -> H.norm_Inf x < 0.0001\n  (S4D x) -> H.norm_Inf x < 0.0001\n\nallCloseP :: SingI shape => S shape -> S shape -> RealNum -> Bool\nallCloseP xs ys p = case xs - ys of\n  (S1D x) -> H.norm_Inf x < p\n  (S2D x) -> H.norm_Inf x < p\n  (S3D x) -> H.norm_Inf x < p\n  (S4D x) -> H.norm_Inf x < p\n\nallCloseV :: KnownNat n => H.R n -> H.R n -> Bool\nallCloseV xs ys = H.norm_Inf (xs - ys) < 0.0001\n\n-- | generate a 2D list with random elements\ngenLists :: Int -> Int -> Gen [[RealNum]]\ngenLists height width = Gen.list (Range.singleton height) $ Gen.list (Range.singleton width) (genRealNum (Range.constant (-2.0) 2.0))\n\ngenLists3D :: Int -> Int -> Int -> Gen [[[RealNum]]]\ngenLists3D depth height width\n  = Gen.list (Range.singleton depth) $\n      Gen.list (Range.singleton height) $\n        Gen.list (Range.singleton width)\n          (genRealNum (Range.constant (-2.0) 2.0))\n\nextractVec :: KnownNat n => S ('D1 n) -> [RealNum]\nextractVec (S1D vec) = toList $ H.extract vec\n\nextractMat :: (KnownNat a, KnownNat b) => S ('D2 a b) -> [[RealNum]]\nextractMat (S2D mat) = toLists $ H.extract mat\n\nextractMat3D :: (KnownNat a, KnownNat b, KnownNat c) => S ('D3 a b c) -> [[RealNum]]\nextractMat3D (S3D mat) = toLists $ H.extract mat\n\nextractMat4D :: (KnownNat a, KnownNat b, KnownNat c, KnownNat d, KnownNat (a * b * c)) => S ('D4 a b c d) -> [[RealNum]]\nextractMat4D (S4D mat) = toLists $ H.extract mat\n\nelementsEqual :: SingI shape => S shape -> Bool\nelementsEqual m = case m of\n  S1D x -> listSameElements . toList $ H.extract x\n  S2D x -> listSameElements . concat . toLists $ H.extract x\n  S3D x -> listSameElements . concat . toLists $ H.extract x\n  S4D x -> listSameElements . concat . toLists $ H.extract x\n\nlistSameElements :: Eq a => [a] -> Bool\nlistSameElements []  = True\nlistSameElements [_] = True\nlistSameElements (x:x':xs)\n  | x == x'   = listSameElements (x':xs)\n  | otherwise = False\n\nmaxVal :: S shape -> RealNum\nmaxVal ( S1D x ) = norm_Inf x\nmaxVal ( S2D x ) = norm_Inf x\nmaxVal ( S3D x ) = norm_Inf x\nmaxVal ( S4D x ) = norm_Inf x\n\nisSimilarMatrixTo :: (MonadTest m, HasCallStack) => Matrix RealNum -> Matrix RealNum -> m ()\nisSimilarMatrixTo x y =\n  withFrozenCallStack $\n    diff x (\\a b -> norm_Inf (a - b) < precision) y\n\nisSimilarVectorTo :: (MonadTest m, HasCallStack) => Vector RealNum -> Vector RealNum -> m ()\nisSimilarVectorTo x y =\n  withFrozenCallStack $\n    diff x (\\a b -> norm_Inf (a - b) < precision) y\n", "meta": {"hexsha": "bc84fb291c7a6bb81ee4466925ced5960281bffa", "size": 5099, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Hedgehog/Hmatrix.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "test/Test/Hedgehog/Hmatrix.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Test/Hedgehog/Hmatrix.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9084507042, "max_line_length": 133, "alphanum_fraction": 0.6207099431, "num_tokens": 1552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4968099085823291}}
{"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Data.Network.Utils\n (repeatM, scanl, randomInput, rowNorm, rowNorm', (.*), (*.),\n  Differentiable, derivate, squeeze, squish, toGaussian,\n  makeBatchP, unzipP, integersP, averageP,\n  accuracy, accuracyBatch)\nwhere\n\nimport Prelude hiding (scanl, zip)\nimport Data.Bifunctor as Bf\nimport Data.Foldable as F\nimport Numeric.LinearAlgebra as LA\nimport Control.Monad.Random as R\nimport qualified Data.Vector.Storable as V\nimport Control.Applicative as A\nimport Pipes as P\nimport Pipes.Core as PC\nimport qualified Pipes.Prelude as PP\n\n\nscanl :: Foldable f => (b -> a -> b) -> b -> f a -> [b]\nscanl f b a = reverse $ foldl (\\(i:is) x -> (f i x):i:is) [b] a\n\nscanr :: Foldable f => (a -> b -> b) -> b -> f a -> [b]\nscanr f b a = foldr (\\x (i:is) -> (f x i):i:is) [b] a\n\nrandomInput :: MonadRandom m => RandDist -> Int -> m (LA.Vector Double)\nrandomInput dist i = do\n  seed :: Int <- getRandom\n  return $ LA.randomVector seed dist i\n\na .* b = LA.scale a b\na *. b = LA.scale b a\n\nrowNorm :: Matrix Double -> Vector R\nrowNorm m = squeeze $ sqrt (m**2) \n\nrowNorm' :: (Element a, Normed (Vector a)) => Matrix a -> Vector R\nrowNorm' = LA.fromList . (fmap norm_2) . toRows\n\nclass Differentiable a b c | c -> a b where\n  derivate :: c -> (a -> b)\n\nrepeatM :: Monad m => Int -> (a -> m a) -> a -> m a\nrepeatM n f i \n  | n <= 0 = return i\n  | otherwise = do\n      o <- f i\n      repeatM (n-1) f o\n\n-- flatten laterally(summing over rows)\nsqueeze :: (V.Storable a, Num a, Numeric a) => Matrix a -> Vector a\nsqueeze m = m #> (V.generate (cols m) (const 1))\n\n-- flatten vertically(summing over columns)\nsquish :: (V.Storable a, Num a, Numeric a) => Matrix a -> Vector a\nsquish m = (V.generate (rows m) (const 1)) <# m \n\n--- Pipe utils\n-----------------------------------------------------------------------------------------\n\n-- Collect chunks of values of a particular size and yields those chunks as lists\n-- Note: the elements of each list are in reverse order of arrival.\n-- Compose with (PP.map reverse) to change that.\nchunkP :: (Monad m) => Int -> Pipe a [a] m r\nchunkP n = collect n [] where\n  collect 0 xs = (yield xs) >> (collect n [])\n  collect n xs = do\n    x <- await\n    collect (n-1) (x:xs)\n\n-- transforms a stream of vectors into a stream of matrix(i.e. batch of vectors)\nmakeBatchP :: (Element a, Monad m) => Int -> Pipe (Vector a) (Matrix a) m r\nmakeBatchP n = chunkP n >-> PP.map (LA.fromRows)\n  \nunzipP :: (Monad m) => Producer (a,b) m r -> (Producer a m r, Producer b m r)\nunzipP p = (p >-> (PP.map fst), p >-> (PP.map snd))\n\nintegersP :: (Monad m, Enum a) => a -> Producer a m r\nintegersP n = yield n >> integersP (succ n)\n\nrangeP :: (Monad m, Enum a, Ord a) => a -> a -> Producer a m ()\nrangeP !a !b\n  | a < b = yield a >> rangeP (succ a) b\n  | otherwise = return ()\n\nwhileMaybe :: (Monad m) => Proxy a' a b' b m r -> Proxy a' a b' (Maybe b) m r\nwhileMaybe p = for p (respond . Just) <* respond Nothing\n\naverageP :: (Monad m, Num a, Floating a) => Producer a m r -> m (a, r)\naverageP = PP.fold' (\\x r -> bimap (+r) (+1) x) (0,0) (uncurry (/))\n  \n\n-----------------------------------------------------------------------------------\n-- Random stream transformation\n-----------------------------------------------------------------------------------\n\n\ntoGaussian :: [Double] -> [Double]\ntoGaussian (a:b:cs) = (r * cos \u03b8):(r * sin \u03b8):toGaussian cs\n  where r = sqrt (-2 * log a)\n        \u03b8 = 2*pi*b\n\n----------------------------------------\naccuracy :: [(Vector R, Vector R)] -> Double\naccuracy outs = (/ (fromIntegral $ length outs)) $ fromIntegral $ length $ filter (\\(y,y') -> (maxIndex y == maxIndex y')) outs \n\n\naccuracyBatch :: (Matrix R, Matrix R) -> Double\naccuracyBatch out = let n = fromIntegral $ rows $ fst out\n                        hits = let (idx, idx') = bimap (fmap maxIndex . toRows) (fmap maxIndex . toRows) out\n                               in fromIntegral $ length $ filter id (zipWith (==) idx idx')\n                     in  hits/n\n  \nhitBatchP :: (Floating a, Monad m) => Pipe (Matrix R, Matrix R) a m ()\nhitBatchP = do\n  (o,t) <- await\n  let (idx, idx') = bimap (fmap maxIndex . toRows) (fmap maxIndex . toRows) (o,t)\n      hits = filter id (zipWith (==) idx idx')\n  yield $ (fromIntegral $ length hits) / (fromIntegral $ rows o)\n      \n", "meta": {"hexsha": "1f9b6a085c278c7e9adbe8ad54f5d363fbf133ca", "size": 4473, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Network/Utils.hs", "max_stars_repo_name": "DrPyser/NeuralNetwork", "max_stars_repo_head_hexsha": "17ca01505dab75235af8522d9b0674639e8a4524", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-10-28T14:35:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T17:57:12.000Z", "max_issues_repo_path": "src/Data/Network/Utils.hs", "max_issues_repo_name": "DrPyser/NeuralNetwork", "max_issues_repo_head_hexsha": "17ca01505dab75235af8522d9b0674639e8a4524", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-06-18T07:52:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-02T18:00:22.000Z", "max_forks_repo_path": "src/Data/Network/Utils.hs", "max_forks_repo_name": "DrPyser/NeuralNetwork", "max_forks_repo_head_hexsha": "17ca01505dab75235af8522d9b0674639e8a4524", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-09T18:36:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-14T20:52:39.000Z", "avg_line_length": 34.9453125, "max_line_length": 128, "alphanum_fraction": 0.5763469707, "num_tokens": 1306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4968099031803123}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes, DataKinds, RankNTypes, TypeFamilies,\n             TypeOperators #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\nmodule TestMnistRNN (testTrees, shortTestForCITrees) where\n\nimport Prelude\n\nimport           Control.Monad (foldM)\nimport qualified Data.Array.DynamicS as OT\nimport           Data.Array.Internal (valueOf)\nimport           Data.List (foldl', unfoldr)\nimport           Data.Proxy (Proxy (Proxy))\nimport qualified Data.Vector.Generic as V\nimport           GHC.TypeLits (KnownNat)\nimport           Numeric.LinearAlgebra (Matrix, Vector)\nimport qualified Numeric.LinearAlgebra as HM\nimport           System.IO (hPutStrLn, stderr)\nimport           System.Random\nimport           Test.Tasty\nimport           Test.Tasty.HUnit hiding (assert)\nimport           Text.Printf\n\n-- until stylish-haskell accepts NoStarIsType\nimport qualified GHC.TypeLits\n\nimport HordeAd\nimport HordeAd.Core.OutdatedOptimizer\nimport HordeAd.Tool.MnistRnnShaped\nimport HordeAd.Tool.MnistTools\n\ntestTrees :: [TestTree]\ntestTrees = [ sinRNNTests\n            , mnistRNNTestsShort\n            , mnistRNNTestsLong\n            ]\n\nshortTestForCITrees :: [TestTree]\nshortTestForCITrees = [ sinRNNTests\n                      , mnistRNNTestsShort\n                      ]\n\n\n-- * A recurrent net and an autoregressive model for sine, following\n-- https://blog.jle.im/entry/purely-functional-typed-models-2.html\n-- and obtaining matching results\n\n-- A version written using matrices\n\nhiddenLayerSinRNN :: DualMonad d r m\n                  => r\n                  -> DualNumber d (Vector r)\n                  -> DualNumberVariables d r\n                  -> m (DualNumber d (Vector r), DualNumber d (Vector r))\nhiddenLayerSinRNN x s variables = do\n  let wX = var2 variables 0\n      wS = var2 variables 1\n      b = var1 variables 0\n  y <- returnLet $ wX #>!! V.singleton x + wS #>! s + b\n  yLogistic <- logisticAct y\n  return (y, yLogistic)\n\noutputLayerSinRNN :: DualMonad d r m\n                  => DualNumber d (Vector r)\n                  -> DualNumberVariables d r\n                  -> m (DualNumber d r)\noutputLayerSinRNN vec variables = do\n  let w = var1 variables 1\n      b = var0 variables 0\n  returnLet $ w <.>! vec + b\n\nfcfcrnn :: DualMonad d r m\n        => r\n        -> DualNumber d (Vector r)\n        -> DualNumberVariables d r\n        -> m (DualNumber d r, DualNumber d (Vector r))\nfcfcrnn x s variables = do\n  (hiddenLayer, sHiddenLayer) <- hiddenLayerSinRNN x s variables\n  outputLayer <- outputLayerSinRNN hiddenLayer variables\n  return (outputLayer, sHiddenLayer)\n\nunrollLast' :: forall d r m. DualMonad d r m\n            => (r\n                -> DualNumber d (Vector r)\n                -> DualNumberVariables d r\n                -> m (DualNumber d r, DualNumber d (Vector r)))\n            -> (Vector r\n                -> DualNumber d (Vector r)\n                -> DualNumberVariables d r\n                -> m (DualNumber d r, DualNumber d (Vector r)))\nunrollLast' f xs s0 variables =\n  let g :: (DualNumber d r, DualNumber d (Vector r)) -> r\n        -> m (DualNumber d r, DualNumber d (Vector r))\n      g (_, s) x = f x s variables\n  in V.foldM' g (undefined, s0) xs\n\nzeroState :: DualMonad d r m\n          => Int\n          -> (a\n              -> DualNumber d (Vector r)\n              -> DualNumberVariables d r\n              -> m (DualNumber d r2, DualNumber d (Vector r)))\n          -> (a\n              -> DualNumberVariables d r\n              -> m (DualNumber d r2))\nzeroState k f xs variables =\n  fst <$> f xs (constant $ HM.konst 0 k) variables\n\nnnSinRNN :: DualMonad d r m\n         => Vector r\n         -> DualNumberVariables d r\n         -> m (DualNumber d r)\nnnSinRNN = zeroState 30 (unrollLast' fcfcrnn)\n\nnnSinRNNLoss :: DualMonad d r m\n             => (Vector r, r)\n             -> DualNumberVariables d r\n             -> m (DualNumber d r)\nnnSinRNNLoss (xs, target) variables = do\n  result <- nnSinRNN xs variables\n  lossSquared target result\n\nseries :: [Double]\nseries = [sin (2 * pi * t / 25) | t <- [0 ..]]\n\nsamples :: [(Vector Double, Double)]\nsamples  = [(V.fromList $ init c, last c) | c <- chunksOf 19 series]\n\nsgdShow :: HasDelta r\n        => (a -> DualNumberVariables 'DModeGradient r -> DualMonadGradient r (DualNumber 'DModeGradient r))\n        -> [a]\n        -> Domains r\n        -> r\nsgdShow f trainData parameters =\n  let result = fst $ sgd 0.1 f trainData parameters\n  in snd $ dReverse 1 (f $ head trainData) result\n\nsgdTestCase :: String\n            -> (a\n                -> DualNumberVariables 'DModeGradient Double\n                -> DualMonadGradient Double (DualNumber 'DModeGradient Double))\n            -> (Int, [Int], [(Int, Int)], [OT.ShapeL])\n            -> IO [a]\n            -> Double\n            -> TestTree\nsgdTestCase prefix f nParameters trainDataIO expected =\n  let ((nParams0, nParams1, nParams2, _), totalParams, range, parameters0) =\n        initializerFixed 44 0.05 nParameters\n      name = prefix ++ \" \"\n             ++ unwords [ show nParams0, show nParams1, show nParams2\n                        , show totalParams, show range ]\n  in testCase name $ do\n       trainData <- trainDataIO\n       sgdShow f trainData parameters0\n         @?= expected\n\nsgdTestCaseAlt :: String\n            -> (a\n                -> DualNumberVariables 'DModeGradient Double\n                -> DualMonadGradient Double (DualNumber 'DModeGradient Double))\n            -> (Int, [Int], [(Int, Int)], [OT.ShapeL])\n            -> IO [a]\n            -> [Double]\n            -> TestTree\nsgdTestCaseAlt prefix f nParameters trainDataIO expected =\n  let ((nParams0, nParams1, nParams2, _), totalParams, range, parameters0) =\n        initializerFixed 44 0.05 nParameters\n      name = prefix ++ \" \"\n             ++ unwords [ show nParams0, show nParams1, show nParams2\n                        , show totalParams, show range ]\n  in testCase name $ do\n       trainData <- trainDataIO\n       let res = sgdShow f trainData parameters0\n       assertBool (\"wrong result: \" ++ show res ++ \" is expected to be a member of \" ++ show expected) $ res `elem` expected\n\nprime :: IsScalar 'DModeGradient r\n      => (r\n          -> DualNumber 'DModeGradient (Vector r)\n          -> DualNumberVariables 'DModeGradient r\n          -> DualMonadValue r (DualNumber 'DModeGradient r, DualNumber 'DModeGradient (Vector r)))\n      -> Domains r\n      -> Vector r\n      -> [r]\n      -> Vector r\nprime f parameters =\n  foldl' (\\s x -> primalValue (fmap snd . f x (constant s)) parameters)\n\nfeedback :: IsScalar 'DModeGradient r\n         => (r\n             -> DualNumber 'DModeGradient (Vector r)\n             -> DualNumberVariables 'DModeGradient r\n             -> DualMonadValue r (DualNumber 'DModeGradient r, DualNumber 'DModeGradient (Vector r)))\n         -> Domains r\n         -> Vector r\n         -> r\n         -> [r]\nfeedback f parameters s0 x0 =\n  let go (x, s) =\n        let (D y _, sd') = primalValueGeneral (f x s) parameters\n        in Just (x, (y, sd'))\n  in unfoldr go (x0, constant s0)\n\nfeedbackTestCase :: String\n                 -> (Double\n                     -> DualNumber 'DModeGradient (Vector Double)\n                     -> DualNumberVariables 'DModeGradient Double\n                     -> DualMonadValue Double\n                                        ( DualNumber 'DModeGradient Double\n                                        , DualNumber 'DModeGradient (Vector Double) ))\n                 -> (a\n                     -> DualNumberVariables 'DModeGradient Double\n                     -> DualMonadGradient Double (DualNumber 'DModeGradient Double))\n                 -> (Int, [Int], [(Int, Int)], [OT.ShapeL])\n                 -> [a]\n                 -> [Double]\n                 -> TestTree\nfeedbackTestCase prefix fp f nParameters trainData expected =\n  let ((nParams0, nParams1, nParams2, _), totalParams, range, parameters0) =\n        initializerFixed 44 0.05 nParameters\n      name = prefix ++ \" \"\n             ++ unwords [ show nParams0, show nParams1, show nParams2\n                        , show totalParams, show range ]\n      trained = fst $ sgd 0.1 f trainData parameters0\n      primed = prime fp trained (HM.konst 0 30) (take 19 series)\n      output = feedback fp trained primed (series !! 19)\n  in testCase name $\n       take 30 output @?= expected\n\n-- A version written using vectors\n\nhiddenLayerSinRNNV :: DualMonad d r m\n                   => r\n                   -> DualNumber d (Vector r)\n                   -> DualNumberVariables d r\n                   -> m (DualNumber d (Vector r), DualNumber d (Vector r))\nhiddenLayerSinRNNV x s variables = do\n  let wX = var1 variables 0\n      b = var1 variables 31\n  y <- returnLet\n       $ scale (HM.konst x 30) wX + sumTrainableInputsL s 1 variables 30 + b\n  yLogistic <- logisticAct y\n  return (y, yLogistic)\n\noutputLayerSinRNNV :: DualMonad d r m\n                   => DualNumber d (Vector r)\n                   -> DualNumberVariables d r\n                   -> m (DualNumber d r)\noutputLayerSinRNNV vec variables = do\n  let w = var1 variables 32\n      b = var0 variables 0\n  returnLet $ w <.>! vec + b\n\nfcfcrnnV :: DualMonad d r m\n         => r\n         -> DualNumber d (Vector r)\n         -> DualNumberVariables d r\n         -> m (DualNumber d r, DualNumber d (Vector r))\nfcfcrnnV x s variables = do\n  (hiddenLayer, sHiddenLayer) <- hiddenLayerSinRNNV x s variables\n  outputLayer <- outputLayerSinRNNV hiddenLayer variables\n  return (outputLayer, sHiddenLayer)\n\nnnSinRNNLossV :: DualMonad d r m\n              => (Vector r, r)\n              -> DualNumberVariables d r\n              -> m (DualNumber d r)\nnnSinRNNLossV (xs, target) variables = do\n  result <- zeroState 30 (unrollLast' fcfcrnnV) xs variables\n  lossSquared target result\n\n-- Autoregressive model with degree 2\n\nar2Sin :: DualMonad d r m\n       => r\n       -> DualNumber d (Vector r)\n       -> DualNumberVariables d r\n       -> m (DualNumber d r, DualNumber d (Vector r))\nar2Sin yLast s variables = do\n  let c = var0 variables 0\n      phi1 = var0 variables 1\n      phi2 = var0 variables 2\n      yLastLast = index0 s 0  -- dummy vector for compatibility\n  y <- returnLet $ c + scale yLast phi1 + phi2 * yLastLast\n  return (y, constant $ V.singleton yLast)\n\nar2SinLoss :: DualMonad d r m\n           => (Vector r, r)\n           -> DualNumberVariables d r\n           -> m (DualNumber d r)\nar2SinLoss (xs, target) variables = do\n  result <- zeroState 30 (unrollLast' ar2Sin) xs variables\n  lossSquared target result\n\nsinRNNTests :: TestTree\nsinRNNTests = testGroup \"Sine RNN tests\"\n  [ sgdTestCase \"train\" nnSinRNNLoss (1, [30, 30], [(30, 1), (30, 30)], [])\n                (return $ take 30000 samples) 5.060827754123346e-5\n  , feedbackTestCase \"feedback\" fcfcrnn nnSinRNNLoss\n                     (1, [30, 30], [(30, 1), (30, 30)], [])\n                     (take 10000 samples)\n                     [-0.9980267284282716,-0.9655322144631203,-0.8919588317267176,-0.7773331580548076,-0.6212249872512189,-0.4246885094957385,-0.19280278430361192,6.316924614971235e-2,0.3255160857644734,0.5731149496491759,0.7872840563791541,0.957217059407527,1.0815006200684472,1.1654656874016613,1.2170717188563214,1.2437913143303263,1.251142657837598,1.2423738174804864,1.2186583377053681,1.1794148708577938,1.1226117988569018,1.0450711676413071,0.9428743310020188,0.8120257428038534,0.6495453130357101,0.45507653540664667,0.23281831228915612,-6.935736916677385e-3,-0.24789484923780786,-0.4705527193222155]\n  , sgdTestCase \"trainVV\" nnSinRNNLossV (1, replicate 33 30, [], [])\n                (return $ take 30000 samples) 4.6511403967229306e-5\n      -- different random initial paramaters produce a worse result;\n      -- matrix implementation faster, because the matrices still fit in cache\n  , feedbackTestCase \"feedbackVV\" fcfcrnnV nnSinRNNLossV\n                     (1, replicate 33 30, [], [])\n                     (take 10000 samples)\n                     [-0.9980267284282716,-0.9660899403337656,-0.8930568599923028,-0.7791304201898077,-0.6245654477568863,-0.4314435277698684,-0.2058673183484546,4.0423225394292085e-2,0.29029630688547203,0.5241984159992963,0.7250013011527577,0.8820730400055012,0.9922277361823716,1.057620382863504,1.08252746840241,1.070784986731554,1.0245016946328942,0.9438848015250431,0.827868146535437,0.6753691437632174,0.48708347071773117,0.26756701680655437,2.6913747557207532e-2,-0.21912614372802072,-0.45154893423928943,-0.6525638736434227,-0.8098403108946983,-0.9180866488182939,-0.9775459850131992,-0.9910399864230198]\n  , sgdTestCase \"trainAR\" ar2SinLoss (3, [], [], [])\n                (return $ take 30000 samples) 6.327978161031336e-23\n  , feedbackTestCase \"feedbackAR\" ar2Sin ar2SinLoss\n                     (3, [], [], [])\n                     (take 10000 samples)\n                     [-0.9980267284282716,-0.9510565162972417,-0.8443279255081759,-0.6845471059406962,-0.48175367412103653,-0.24868988719256901,-3.673766846290505e-11,0.24868988711894977,0.4817536740469978,0.6845471058659982,0.8443279254326351,0.9510565162207472,0.9980267283507953,0.9822872506502898,0.9048270523889208,0.7705132427021685,0.5877852522243431,0.3681245526237731,0.12533323351198067,-0.1253332336071494,-0.36812455271766376,-0.5877852523157643,-0.7705132427900961,-0.9048270524725681,-0.9822872507291605,-0.9980267284247174,-0.9510565162898851,-0.844327925497479,-0.6845471059273313,-0.48175367410584324]\n  ]\n\n\n-- * A 1 recurrent layer net with 128 neurons for MNIST, based on\n-- https://medium.com/machine-learning-algorithms/mnist-using-recurrent-neural-network-2d070a5915a2\n-- *Not* LSTM.\n-- Doesn't train without Adam, regardless of whether mini-batch sgd\n-- is used and whether a second recurrent layer. It does train with Adam,\n-- but only after very carefully tweaking initialization. This is\n-- extremely sensitive to initial parameters, more than to anything\n-- else. Probably, gradient is vanishing if parameters are initialized\n-- with a probability distribution that doesn't have the right variance. See\n-- https://stats.stackexchange.com/questions/301285/what-is-vanishing-gradient.\n\nhiddenLayerMnistRNNL :: DualMonad d r m\n                     => Vector r\n                     -> DualNumber d (Vector r)\n                     -> DualNumberVariables d r\n                     -> m (DualNumber d (Vector r), DualNumber d (Vector r))\nhiddenLayerMnistRNNL x s variables = do\n  let wX = var2 variables 0  -- 128x28\n      wS = var2 variables 1  -- 128x128\n      b = var1 variables 0  -- 128\n      y = wX #>!! x + wS #>! s + b\n  yTanh <- tanhAct y\n  return (yTanh, yTanh)  -- tanh in both, as per https://github.com/keras-team/keras/blob/v2.8.0/keras/layers/legacy_rnn/rnn_cell_impl.py#L468\n\nmiddleLayerMnistRNNL :: DualMonad d r m\n                     => DualNumber d (Vector r)\n                     -> DualNumber d (Vector r)\n                     -> DualNumberVariables d r\n                     -> m (DualNumber d (Vector r), DualNumber d (Vector r))\nmiddleLayerMnistRNNL vec s variables = do\n  let wX = var2 variables 3  -- 128x128\n      wS = var2 variables 4  -- 128x128\n      b = var1 variables 2  -- 128\n      y = wX #>! vec + wS #>! s + b\n  yTanh <- tanhAct y\n  return (yTanh, yTanh)\n\noutputLayerMnistRNNL :: DualMonad d r m\n                     => DualNumber d (Vector r)\n                     -> DualNumberVariables d r\n                     -> m (DualNumber d (Vector r))\noutputLayerMnistRNNL vec variables = do\n  let w = var2 variables 2  -- 10x128\n      b = var1 variables 1  -- 10\n  returnLet $ w #>! vec + b  -- I assume there is no activations, as per https://www.tensorflow.org/api_docs/python/tf/compat/v1/layers/dense\n\nfcfcrnnMnistL :: DualMonad d r m\n              => Vector r\n              -> DualNumber d (Vector r)\n              -> DualNumberVariables d r\n              -> m (DualNumber d (Vector r), DualNumber d (Vector r))\nfcfcrnnMnistL = hiddenLayerMnistRNNL\n\nfcfcrnnMnistL2 :: DualMonad d r m\n               => Vector r\n               -> DualNumber d (Vector r)\n               -> DualNumberVariables d r\n               -> m (DualNumber d (Vector r), DualNumber d (Vector r))\nfcfcrnnMnistL2 x s@(D u _) variables = do\n  let len = V.length u `div` 2\n      s1 = slice1 0 len s\n      s2 = slice1 len len s\n  (vec1, s1') <- hiddenLayerMnistRNNL x s1 variables\n  (vec2, s2') <- middleLayerMnistRNNL vec1 s2 variables\n  s3 <- returnLet $ append1 s1' s2'\n  return (vec2, s3)\n\nunrollLastG :: forall d a b c m r. DualMonad d r m\n            => (a -> b -> DualNumberVariables d r -> m (c, b))\n            -> ([a] -> b -> DualNumberVariables d r -> m (c, b))\nunrollLastG f xs s0 variables =\n  let g :: (c, b) -> a -> m (c, b)\n      g (_, s) x = f x s variables\n  in foldM g (undefined, s0) xs\n\nnnMnistRNNL :: forall d r m. DualMonad d r m\n            => Int\n            -> [Vector r]\n            -> DualNumberVariables d r\n            -> m (DualNumber d (Vector r))\nnnMnistRNNL width x variables = do\n  rnnLayer <- zeroState width (unrollLastG fcfcrnnMnistL) x variables\n  outputLayerMnistRNNL rnnLayer variables\n\nnnMnistRNNL2 :: DualMonad d r m\n             => Int\n             -> [Vector r]\n             -> DualNumberVariables d r\n             -> m (DualNumber d (Vector r))\nnnMnistRNNL2 width x variables = do\n  rnnLayer <- zeroState (2 * width) (unrollLastG fcfcrnnMnistL2) x variables\n  outputLayerMnistRNNL rnnLayer variables\n\nnnMnistRNNLossL :: forall d r m. DualMonad d r m\n                => Int\n                -> ([Vector r], Vector r)\n                -> DualNumberVariables d r\n                -> m (DualNumber d r)\nnnMnistRNNLossL width (xs, target) variables = do\n  result <- nnMnistRNNL width xs variables\n  lossSoftMaxCrossEntropyV target result\n\nnnMnistRNNLossL2 :: DualMonad d r m\n                 => Int\n                 -> ([Vector r], Vector r)\n                 -> DualNumberVariables d r\n                 -> m (DualNumber d r)\nnnMnistRNNLossL2 width (xs, target) variables = do\n  result <- nnMnistRNNL2 width xs variables\n  lossSoftMaxCrossEntropyV target result\n\ntestMnistRNNL :: forall r. IsScalar 'DModeGradient r\n              => Int -> [([Vector r], Vector r)] -> Domains r -> r\ntestMnistRNNL width inputs parameters =\n  let matchesLabels :: ([Vector r], Vector r) -> Bool\n      matchesLabels (glyph, label) =\n        let nn = nnMnistRNNL width glyph\n            value = primalValue nn parameters\n        in V.maxIndex value == V.maxIndex label\n  in fromIntegral (length (filter matchesLabels inputs))\n     / fromIntegral (length inputs)\n\ntestMnistRNNL2 :: forall r. IsScalar 'DModeGradient r\n               => Int -> [([Vector r], Vector r)] -> Domains r -> r\ntestMnistRNNL2 width inputs parameters =\n  let matchesLabels :: ([Vector r], Vector r) -> Bool\n      matchesLabels (glyph, label) =\n        let nn = nnMnistRNNL2 width glyph\n            value = primalValue nn parameters\n        in V.maxIndex value == V.maxIndex label\n  in fromIntegral (length (filter matchesLabels inputs))\n     / fromIntegral (length inputs)\n\n-- A version written using vectors\n\nhiddenLayerMnistRNNV :: DualMonad d r m\n                     => Int\n                     -> Vector r\n                     -> DualNumber d (Vector r)\n                     -> DualNumberVariables d r\n                     -> m (DualNumber d (Vector r), DualNumber d (Vector r))\nhiddenLayerMnistRNNV width x s variables = do\n  let b = var1 variables (width + width)  -- 128\n      y = sumConstantDataL x 0 variables width\n          + sumTrainableInputsL s width variables width\n          + b\n  yTanh <- tanhAct y\n  return (yTanh, yTanh)\n\noutputLayerMnistRNNV :: DualMonad d r m\n                     => Int\n                     -> DualNumber d (Vector r)\n                     -> DualNumberVariables d r\n                     -> m (DualNumber d (Vector r))\noutputLayerMnistRNNV width vec variables = do\n  let b = var1 variables (width + width + 1 + 10)  -- 10\n  returnLet $ sumTrainableInputsL vec (width + width + 1) variables 10 + b\n\nfcfcrnnMnistV :: DualMonad d r m\n              => Int\n              -> Vector r\n              -> DualNumber d (Vector r)\n              -> DualNumberVariables d r\n              -> m (DualNumber d (Vector r), DualNumber d (Vector r))\nfcfcrnnMnistV = hiddenLayerMnistRNNV\n\nnnMnistRNNV :: DualMonad d r m\n            => Int\n            -> [Vector r]\n            -> DualNumberVariables d r\n            -> m (DualNumber d (Vector r))\nnnMnistRNNV width x variables = do\n  rnnLayer <- zeroState width (unrollLastG $ fcfcrnnMnistV width) x variables\n  outputLayerMnistRNNV width rnnLayer variables\n\nnnMnistRNNLossV :: DualMonad d r m\n                => Int\n                -> ([Vector r], Vector r)\n                -> DualNumberVariables d r\n                -> m (DualNumber d r)\nnnMnistRNNLossV width (xs, target) variables = do\n  result <- nnMnistRNNV width xs variables\n  lossSoftMaxCrossEntropyV target result\n\ntestMnistRNNV :: forall r. IsScalar 'DModeGradient r\n              => Int -> [([Vector r], Vector r)] -> Domains r -> r\ntestMnistRNNV width inputs parameters =\n  let matchesLabels :: ([Vector r], Vector r) -> Bool\n      matchesLabels (glyph, label) =\n        let nn = nnMnistRNNV width glyph\n            value = primalValue nn parameters\n        in V.maxIndex value == V.maxIndex label\n  in fromIntegral (length (filter matchesLabels inputs))\n     / fromIntegral (length inputs)\n\nlenMnistRNNL :: Int -> Int -> (Int, [Int], [(Int, Int)], [OT.ShapeL])\nlenMnistRNNL width nLayers =\n  ( 0\n  , [width, 10] ++ replicate (nLayers - 1) width\n  , [(width, 28), (width, width), (10, width)]\n    ++ concat (replicate (nLayers - 1) [(width, width), (width, width)])\n  , []\n  )\n\nlenMnistRNNV :: Int -> Int -> (Int, [Int], [(Int, Int)], [OT.ShapeL])\nlenMnistRNNV width nLayers =\n  ( 0\n  , replicate width 28 ++ replicate width width ++ [width]\n    ++ replicate 10 width ++ [10]\n    ++ concat (replicate (nLayers - 1)\n                (replicate width width ++ replicate width width ++ [width]))\n  , []\n  , []\n  )\n\nmnistTestCaseRNN\n  :: String\n  -> Int\n  -> Int\n  -> (Int\n      -> ([Vector Double], Vector Double)\n      -> DualNumberVariables 'DModeGradient Double\n      -> DualMonadGradient Double (DualNumber 'DModeGradient Double))\n  -> (Int -> [([Vector Double], Vector Double)] -> Domains Double -> Double)\n  -> (Int -> Int -> (Int, [Int], [(Int, Int)], [OT.ShapeL]))\n  -> Int\n  -> Int\n  -> Double\n  -> TestTree\nmnistTestCaseRNN prefix epochs maxBatches f ftest flen width nLayers\n                 expected =\n  let ((nParams0, nParams1, nParams2, _), totalParams, range, parameters0) =\n        initializerFixed 44 0.2 (flen width nLayers)\n      name = prefix ++ \": \"\n             ++ unwords [ show epochs, show maxBatches\n                        , show width, show nLayers\n                        , show nParams0, show nParams1, show nParams2\n                        , show totalParams, show range ]\n  in testCase name $ do\n       hPutStrLn stderr $ printf \"\\n%s: Epochs to run/max batches per epoch: %d/%d\"\n              prefix epochs maxBatches\n       let rws (input, target) =\n             ( map (\\k -> V.slice (k * 28) 28 input) [0 .. 27]\n             , target )\n       trainData <- map rws <$> loadMnistData trainGlyphsPath trainLabelsPath\n       testData <- map rws <$> loadMnistData testGlyphsPath testLabelsPath\n       -- There is some visual feedback, because some of these take long.\n       let runBatch :: (Domains Double, StateAdam Double)\n                    -> (Int, [([Vector Double], Vector Double)])\n                    -> IO (Domains Double, StateAdam Double)\n           runBatch (parameters@(!_, !_, !_, !_), stateAdam) (k, chunk) = do\n             let res@(parameters2, _) =\n                   sgdAdamBatch 150 (f width) chunk parameters stateAdam\n                 !trainScore = ftest width chunk parameters2\n                 !testScore = ftest width testData parameters2\n                 !lenChunk = length chunk\n             hPutStrLn stderr $ printf \"\\n%s: (Batch %d with %d points)\" prefix k lenChunk\n             hPutStrLn stderr $ printf \"%s: Training error:   %.2f%%\" prefix ((1 - trainScore) * 100)\n             hPutStrLn stderr $ printf \"%s: Validation error: %.2f%%\" prefix ((1 - testScore ) * 100)\n             return res\n           runEpoch :: Int\n                    -> (Domains Double, StateAdam Double)\n                    -> IO (Domains Double)\n           runEpoch n (params2, _) | n > epochs = return params2\n           runEpoch n paramsStateAdam = do\n             hPutStrLn stderr $ printf \"\\n%s: [Epoch %d]\" prefix n\n             let trainDataShuffled = shuffle (mkStdGen $ n + 5) trainData\n                 chunks = take maxBatches\n                          $ zip [1 ..] $ chunksOf 5000 trainDataShuffled\n             !res <- foldM runBatch paramsStateAdam chunks\n             runEpoch (succ n) res\n       res <- runEpoch 1 (parameters0, initialStateAdam parameters0)\n       let testErrorFinal = 1 - ftest width testData res\n       testErrorFinal @?= expected\n\n\n-- * A version written using matrices to express mini-batches of data\n-- and so using matrix multiplication to run the neural net\n\nhiddenLayerMnistRNNB :: DualMonad d r m\n                     => Matrix r  -- the mini-batch of data 28x150\n                     -> DualNumber d (Matrix r)  -- state for mini-batch 128x150\n                     -> DualNumberVariables d r\n                     -> m (DualNumber d (Matrix r), DualNumber d (Matrix r))\nhiddenLayerMnistRNNB x s variables = do\n  let wX = var2 variables 0  -- 128x28\n      wS = var2 variables 1  -- 128x128\n      b = var1 variables 0  -- 128\n      batchSize = HM.cols x\n      y = wX <>!! x + wS <>! s + asColumn2 b batchSize\n  yTanh <- returnLet $ tanh y\n  return (yTanh, yTanh)\n\nmiddleLayerMnistRNNB :: DualMonad d r m\n                     => DualNumber d (Matrix r)  -- 128x150\n                     -> DualNumber d (Matrix r)  -- 128x150\n                     -> DualNumberVariables d r\n                     -> m (DualNumber d (Matrix r), DualNumber d (Matrix r))\nmiddleLayerMnistRNNB batchOfVec@(D u _) s variables = do\n  let wX = var2 variables 3  -- 128x128\n      wS = var2 variables 4  -- 128x128\n      b = var1 variables 2  -- 128\n      batchSize = HM.cols u\n      y = wX <>! batchOfVec + wS <>! s + asColumn2 b batchSize\n  yTanh <- returnLet $ tanh y\n  return (yTanh, yTanh)\n\noutputLayerMnistRNNB :: DualMonad d r m\n                     => DualNumber d (Matrix r)  -- 128x150\n                     -> DualNumberVariables d r\n                     -> m (DualNumber d (Matrix r))\noutputLayerMnistRNNB batchOfVec@(D u _) variables = do\n  let w = var2 variables 2  -- 10x128\n      b = var1 variables 1  -- 10\n      batchSize = HM.cols u\n  returnLet $ w <>! batchOfVec + asColumn2 b batchSize\n\nfcfcrnnMnistB :: DualMonad d r m\n              => Matrix r\n              -> DualNumber d (Matrix r)\n              -> DualNumberVariables d r\n              -> m (DualNumber d (Matrix r), DualNumber d (Matrix r))\nfcfcrnnMnistB = hiddenLayerMnistRNNB\n\nfcfcrnnMnistB2 :: DualMonad d r m\n               => Matrix r  -- 28x150\n               -> DualNumber d (Matrix r)  -- 256x150\n               -> DualNumberVariables d r\n               -> m (DualNumber d (Matrix r), DualNumber d (Matrix r))\nfcfcrnnMnistB2 x s@(D u _) variables = do\n  let len = HM.rows u `div` 2\n      s1 = rowSlice2 0 len s\n      s2 = rowSlice2 len len s\n  (vec1, s1') <- hiddenLayerMnistRNNB x s1 variables\n  (vec2, s2') <- middleLayerMnistRNNB vec1 s2 variables\n  return (vec2, rowAppend2 s1' s2')\n\nzeroStateB :: DualMonad d r m\n           => (Int, Int)\n           -> (a\n               -> DualNumber d (Matrix r)\n               -> DualNumberVariables d r\n               -> m (DualNumber d r2, DualNumber d (Matrix r)))\n           -> (a\n               -> DualNumberVariables d r\n               -> m (DualNumber d r2))\nzeroStateB ij f xs variables =\n  fst <$> f xs (constant $ HM.konst 0 ij) variables\n\nnnMnistRNNB :: DualMonad d r m\n            => Int\n            -> [Matrix r]\n            -> DualNumberVariables d r\n            -> m (DualNumber d (Matrix r))\nnnMnistRNNB width xs variables = do\n  let batchSize = HM.cols $ head xs\n  rnnLayer <- zeroStateB (width, batchSize) (unrollLastG fcfcrnnMnistB)\n                         xs variables\n  outputLayerMnistRNNB rnnLayer variables\n\nnnMnistRNNB2 :: DualMonad d r m\n             => Int\n             -> [Matrix r]\n             -> DualNumberVariables d r\n             -> m (DualNumber d (Matrix r))\nnnMnistRNNB2 width xs variables = do\n  let batchSize = HM.cols $ head xs\n  rnnLayer <- zeroStateB (2 * width, batchSize) (unrollLastG fcfcrnnMnistB2)\n                         xs variables\n  outputLayerMnistRNNB rnnLayer variables\n\nnnMnistRNNLossB :: DualMonad d r m\n                => Int\n                -> ([Matrix r], Matrix r)\n                -> DualNumberVariables d r\n                -> m (DualNumber d r)\nnnMnistRNNLossB width (xs, target) variables = do\n  result <- nnMnistRNNB width xs variables\n  vec@(D u _) <- lossSoftMaxCrossEntropyL target result\n  returnLet $ scale (recip $ fromIntegral $ V.length u) $ sumElements0 vec\n\nnnMnistRNNLossB2 :: DualMonad d r m\n                 => Int\n                 -> ([Matrix r], Matrix r)\n                 -> DualNumberVariables d r\n                 -> m (DualNumber d r)\nnnMnistRNNLossB2 width (xs, target) variables = do\n  result <- nnMnistRNNB2 width xs variables\n  vec@(D u _) <- lossSoftMaxCrossEntropyL target result\n  returnLet $ scale (recip $ fromIntegral $ V.length u) $ sumElements0 vec\n\nmnistTestCaseRNNB\n  :: String\n  -> Int\n  -> Int\n  -> (Int\n      -> ([Matrix Double], Matrix Double)\n      -> DualNumberVariables 'DModeGradient Double\n      -> DualMonadGradient Double (DualNumber 'DModeGradient Double))\n  -> (Int -> [([Vector Double], Vector Double)] -> Domains Double -> Double)\n  -> (Int -> Int -> (Int, [Int], [(Int, Int)], [OT.ShapeL]))\n  -> Int\n  -> Int\n  -> Double\n  -> TestTree\nmnistTestCaseRNNB prefix epochs maxBatches f ftest flen width nLayers\n                  expected =\n  let ((nParams0, nParams1, nParams2, _), totalParams, range, parameters0) =\n        initializerFixed 44 0.2 (flen width nLayers)\n      name = prefix ++ \": \"\n             ++ unwords [ show epochs, show maxBatches\n                        , show width, show nLayers\n                        , show nParams0, show nParams1, show nParams2\n                        , show totalParams, show range ]\n  in testCase name $ do\n       hPutStrLn stderr $ printf \"\\n%s: Epochs to run/max batches per epoch: %d/%d\"\n              prefix epochs maxBatches\n       let rws (input, target) =\n             ( map (\\k -> V.slice (k * 28) 28 input) [0 .. 27]\n             , target )\n       trainData <- map rws <$> loadMnistData trainGlyphsPath trainLabelsPath\n       testData <- map rws <$> loadMnistData testGlyphsPath testLabelsPath\n       let packChunk :: [([Vector Double], Vector Double)]\n                     -> ([Matrix Double], Matrix Double)\n           packChunk chunk =\n             let (inputs, targets) = unzip chunk\n                 behead !acc ([] : _) = reverse acc\n                 behead !acc l = behead (HM.fromColumns (map head l) : acc)\n                                        (map tail l)\n             in (behead [] inputs, HM.fromColumns targets)\n           -- There is some visual feedback, because some of these take long.\n           runBatch :: (Domains Double, StateAdam Double)\n                    -> (Int, [([Vector Double], Vector Double)])\n                    -> IO (Domains Double, StateAdam Double)\n           runBatch (parameters@(!_, !_, !_, !_), stateAdam) (k, chunk) = do\n             let res@(parameters2, _) =\n                   sgdAdam (f width) (map packChunk $ chunksOf 150 chunk)\n                           parameters stateAdam\n                 !trainScore = ftest width chunk parameters2\n                 !testScore = ftest width testData parameters2\n                 !lenChunk = length chunk\n             hPutStrLn stderr $ printf \"\\n%s: (Batch %d with %d points)\" prefix k lenChunk\n             hPutStrLn stderr $ printf \"%s: Training error:   %.2f%%\" prefix ((1 - trainScore) * 100)\n             hPutStrLn stderr $ printf \"%s: Validation error: %.2f%%\" prefix ((1 - testScore ) * 100)\n             return res\n           runEpoch :: Int\n                    -> (Domains Double, StateAdam Double)\n                    -> IO (Domains Double)\n           runEpoch n (params2, _) | n > epochs = return params2\n           runEpoch n paramsStateAdam = do\n             hPutStrLn stderr $ printf \"\\n%s: [Epoch %d]\" prefix n\n             let trainDataShuffled = shuffle (mkStdGen $ n + 5) trainData\n                 chunks = take maxBatches\n                          $ zip [1 ..] $ chunksOf 5000 trainDataShuffled\n             !res <- foldM runBatch paramsStateAdam chunks\n             runEpoch (succ n) res\n       res <- runEpoch 1 (parameters0, initialStateAdam parameters0)\n       let testErrorFinal = 1 - ftest width testData res\n       testErrorFinal @?= expected\n\n\n-- * A version written using shaped tensors\n\nmnistTestCaseRNNS\n  :: forall out_width batch_size d r m.\n     ( KnownNat out_width, KnownNat batch_size\n     , r ~ Double, d ~ 'DModeGradient, m ~ DualMonadGradient Double )\n  => String\n  -> Int\n  -> Int\n  -> (forall out_width' batch_size'.\n      (DualMonad d r m, KnownNat out_width', KnownNat batch_size')\n      => Proxy out_width'\n      -> MnistDataBatchS batch_size' r\n      -> DualNumberVariables d r\n      -> m (DualNumber d r))\n  -> (forall out_width' batch_size'.\n      (IsScalar d r, KnownNat out_width', KnownNat batch_size')\n      => Proxy r -> Proxy out_width'\n      -> MnistDataBatchS batch_size' r\n      -> Domains r\n      -> r)\n  -> (forall out_width'. KnownNat out_width'\n      => Proxy out_width' -> (Int, [Int], [(Int, Int)], [OT.ShapeL]))\n  -> Double\n  -> TestTree\nmnistTestCaseRNNS prefix epochs maxBatches trainWithLoss ftest flen expected =\n  let proxy_out_width = Proxy @out_width\n      batch_size = valueOf @batch_size\n      ((_, _, _, nParamsX), totalParams, range, parametersInit) =\n        initializerFixed 44 0.2 (flen proxy_out_width)\n      name = prefix ++ \": \"\n             ++ unwords [ show epochs, show maxBatches\n                        , show (valueOf @out_width :: Int), show batch_size\n                        , show nParamsX, show totalParams, show range ]\n  in testCase name $ do\n    hPutStrLn stderr $ printf \"\\n%s: Epochs to run/max batches per epoch: %d/%d\"\n           prefix epochs maxBatches\n    trainData <- map shapeBatch\n                 <$> loadMnistData trainGlyphsPath trainLabelsPath\n    testData <- map shapeBatch\n                <$> loadMnistData testGlyphsPath testLabelsPath\n    let testDataS = packBatch @LengthTestData testData\n        -- There is some visual feedback, because some of these take long.\n        runBatch :: (Domains r, StateAdam r)\n                 -> (Int, [MnistDataS r])\n                 -> IO (Domains r, StateAdam r)\n        runBatch (parameters@(!_, !_, !_, !_), stateAdam) (k, chunk) = do\n          let f = trainWithLoss proxy_out_width\n              chunkS = map (packBatch @batch_size)\n                       $ filter (\\ch -> length ch >= batch_size)\n                       $ chunksOf batch_size chunk\n              res@(parameters2, _) = sgdAdam f chunkS parameters stateAdam\n              !trainScore =\n                ftest (Proxy @r) proxy_out_width\n                      (packBatch @(10 GHC.TypeLits.* batch_size) chunk)\n                      parameters2\n              !testScore = ftest (Proxy @r) proxy_out_width\n                                testDataS parameters2\n              !lenChunk = length chunk\n          hPutStrLn stderr $ printf \"\\n%s: (Batch %d with %d points)\" prefix k lenChunk\n          hPutStrLn stderr $ printf \"%s: Training error:   %.2f%%\" prefix ((1 - trainScore) * 100)\n          hPutStrLn stderr $ printf \"%s: Validation error: %.2f%%\" prefix ((1 - testScore ) * 100)\n          return res\n        runEpoch :: Int -> (Domains r, StateAdam r) -> IO (Domains r)\n        runEpoch n (params2, _) | n > epochs = return params2\n        runEpoch n paramsStateAdam = do\n          hPutStrLn stderr $ printf \"\\n%s: [Epoch %d]\" prefix n\n          let trainDataShuffled = shuffle (mkStdGen $ n + 5) trainData\n              chunks = take maxBatches\n                       $ zip [1 ..]\n                       $ chunksOf (10 * batch_size) trainDataShuffled\n          !res <- foldM runBatch paramsStateAdam chunks\n          runEpoch (succ n) res\n    res <- runEpoch 1 (parametersInit, initialStateAdam parametersInit)\n    let testErrorFinal = 1 - ftest (Proxy @r) proxy_out_width testDataS res\n    testErrorFinal @?= expected\n\nmnistRNNTestsLong :: TestTree\nmnistRNNTestsLong = testGroup \"MNIST RNN long tests\"\n  [ mnistTestCaseRNN \"99LL 1 epoch, all batches\" 1 99\n                     nnMnistRNNLossL testMnistRNNL lenMnistRNNL 128 1\n                     8.209999999999995e-2\n  , mnistTestCaseRNNB \"99BB 1 epoch, all batches\" 1 99\n                      nnMnistRNNLossB testMnistRNNL lenMnistRNNL 128 1\n                      8.209999999999995e-2\n  , mnistTestCaseRNN \"99LL2 1 epoch, all batches\" 1 99\n                     nnMnistRNNLossL2 testMnistRNNL2 lenMnistRNNL 128 2\n                     6.259999999999999e-2\n  , mnistTestCaseRNNB \"99BB2 1 epoch, all batches\" 1 99\n                      nnMnistRNNLossB2 testMnistRNNL2 lenMnistRNNL 128 2\n                      6.259999999999999e-2\n  , mnistTestCaseRNN \"99VV 1 epoch, all batches\" 1 99\n                     nnMnistRNNLossV testMnistRNNV lenMnistRNNV 128 1\n                     6.740000000000002e-2\n  , mnistTestCaseRNNS @128 @150 \"1S 1 epoch, 1 batch\" 1 1\n                      rnnMnistLossFusedS rnnMnistTestS rnnMnistLenS\n                      0.4375\n  ]\n\nmnistRNNTestsShort :: TestTree\nmnistRNNTestsShort = testGroup \"MNIST RNN short tests\"\n  [ let glyph = V.unfoldrExactN sizeMnistGlyph (uniformR (0, 1))\n        label = V.unfoldrExactN sizeMnistLabel (uniformR (0, 1))\n        rws v = map (\\k -> V.slice (k * 28) 28 v) [0 .. 27]\n        trainData = map ((\\g -> (rws (glyph g), label g)) . mkStdGen) [1 .. 140]\n    in sgdTestCaseAlt \"randomLL 140\"\n                      (nnMnistRNNLossL 128)\n                      (lenMnistRNNL 128 1)\n                      (return trainData)\n                      [39.26529871965807, 39.26529500592892]\n  , let rws (input, target) =\n          (map (\\k -> V.slice (k * 28) 28 input) [0 .. 27], target)\n    in sgdTestCase \"firstLL 100 trainset samples only\"\n                   (nnMnistRNNLossL 128)\n                   (lenMnistRNNL 128 1)\n                   (map rws . take 100\n                    <$> loadMnistData trainGlyphsPath trainLabelsPath)\n                   2.7790856895965272\n  , mnistTestCaseRNN \"1LL 1 epoch, 1 batch\" 1 1\n                     nnMnistRNNLossL testMnistRNNL lenMnistRNNL 128 1\n                     0.2845\n  , mnistTestCaseRNNB \"1BB 1 epoch, 1 batch\" 1 1\n                      nnMnistRNNLossB testMnistRNNL lenMnistRNNL 128 1\n                      0.2845\n  , let glyph = V.unfoldrExactN sizeMnistGlyph (uniformR (0, 1))\n        label = V.unfoldrExactN sizeMnistLabel (uniformR (0, 1))\n        rws v = map (\\k -> V.slice (k * 28) 28 v) [0 .. 27]\n        trainData = map ((\\g -> (rws (glyph g), label g)) . mkStdGen) [1 .. 140]\n    in sgdTestCaseAlt \"randomLL2 140\"\n                      (nnMnistRNNLossL2 128)\n                      (lenMnistRNNL 128 2)\n                      (return trainData)\n                      [30.061871495723956, 30.06187089990927]\n  , let rws (input, target) =\n          (map (\\k -> V.slice (k * 28) 28 input) [0 .. 27], target)\n    in sgdTestCase \"firstLL2 99 trainset samples only\"\n                   (nnMnistRNNLossL2 128)\n                   (lenMnistRNNL 128 2)\n                   (map rws . take 99\n                    <$> loadMnistData trainGlyphsPath trainLabelsPath)\n                   2.772595855528805\n  , mnistTestCaseRNN \"1LL2 1 epoch, 1 batch\" 1 1\n                     nnMnistRNNLossL2 testMnistRNNL2 lenMnistRNNL 128 2\n                     0.2945\n  , mnistTestCaseRNNB \"1BB2 1 epoch, 1 batch\" 1 1\n                      nnMnistRNNLossB2 testMnistRNNL2 lenMnistRNNL 128 2\n                      0.2945\n  , let glyph = V.unfoldrExactN sizeMnistGlyph (uniformR (0, 1))\n        label = V.unfoldrExactN sizeMnistLabel (uniformR (0, 1))\n        rws v = map (\\k -> V.slice (k * 28) 28 v) [0 .. 27]\n        trainData = map ((\\g -> (rws (glyph g), label g)) . mkStdGen) [1 .. 100]\n    in sgdTestCase \"randomVV 100\"\n                   (nnMnistRNNLossV 128)\n                   (lenMnistRNNV 128 1)\n                   (return trainData)\n                   48.93543453250378\n  , let rws (input, target) =\n          (map (\\k -> V.slice (k * 28) 28 input) [0 .. 27], target)\n    in sgdTestCase \"firstVV 100 trainset samples only\"\n                   (nnMnistRNNLossV 128)\n                   (lenMnistRNNV 128 1)\n                   (map rws . take 100\n                    <$> loadMnistData trainGlyphsPath trainLabelsPath)\n                   2.749410768938081\n  , mnistTestCaseRNN \"1VV 1 epoch, 1 batch\" 1 1\n                     nnMnistRNNLossV testMnistRNNV lenMnistRNNV 128 1\n                     0.3024\n  , mnistTestCaseRNNS @120 @15 \"1S 1 epoch, 1 batch\" 1 1\n                      rnnMnistLossFusedS rnnMnistTestS rnnMnistLenS\n                      0.8418\n  ]\n", "meta": {"hexsha": "3b49843db35cd2964d7b802bc953b984a0b702dc", "size": 41279, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/common/TestMnistRNN.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/common/TestMnistRNN.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "test/common/TestMnistRNN.hs", "max_forks_repo_name": "Mikolaj/horde-ad", "max_forks_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4058885384, "max_line_length": 618, "alphanum_fraction": 0.594636498, "num_tokens": 11781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.49680989777829554}}
{"text": "{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeInType                               #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\nimport           Control.DeepSeq\nimport           Control.Exception\nimport           Criterion.Main\nimport           Data.Char\nimport           Data.Complex\nimport           GHC.TypeNats\nimport           Numeric.EMD\nimport           Numeric.HHT\nimport           Statistics.Transform\nimport           Text.Printf\nimport qualified Data.Vector          as UV\nimport qualified Data.Vector.Sized    as V\nimport qualified System.Random.MWC    as MWC\n\nmain :: IO ()\nmain = do\n    g     <- MWC.initialize\n           . UV.fromList\n           . map (fromIntegral . ord)\n           $ \"hello world\"\n\n    test256    <- evaluate . force =<< generateData @8  g\n    test1024   <- evaluate . force =<< generateData @10 g\n    test4096   <- evaluate . force =<< generateData @12 g\n\n    itest256   <- evaluate . force $ emd defaultEO test256\n    itest1024  <- evaluate . force $ emd defaultEO test1024\n    itest4096  <- evaluate . force $ emd defaultEO test4096\n\n    htest256   <- evaluate . force $ hhtEmd itest256\n    htest1024  <- evaluate . force $ hhtEmd itest1024\n    htest4096  <- evaluate . force $ hhtEmd itest4096\n\n    let imfs256   = length . emdIMFs $ itest256\n        imfs1024  = length . emdIMFs $ itest1024\n        imfs4096  = length . emdIMFs $ itest4096\n\n    defaultMainWith defaultConfig [\n        bgroup \"emd\"\n          [ bench (printf \"256 (%d imfs)\"   imfs256  ) $ nf (emd defaultEO) test256\n          , bench (printf \"1024 (%d imfs)\"  imfs1024 ) $ nf (emd defaultEO) test1024\n          , bench (printf \"4096 (%d imfs)\"  imfs4096 ) $ nf (emd defaultEO) test4096\n          ]\n      , bgroup \"hhtEmd\"\n          [ bench \"256\"   $ nf hhtEmd itest256\n          , bench \"1024\"  $ nf hhtEmd itest1024\n          , bench \"4096\"  $ nf hhtEmd itest4096\n          ]\n      , bgroup \"iemd\"\n          [ bench \"256\"   $ nf iemd itest256\n          , bench \"1024\"  $ nf iemd itest1024\n          , bench \"4096\"  $ nf iemd itest4096\n          ]\n      , bgroup \"ihhtEmd\"\n          [ bench \"256\"   $ nf ihhtEmd htest256\n          , bench \"1024\"  $ nf ihhtEmd htest1024\n          , bench \"4096\"  $ nf ihhtEmd htest4096\n          ]\n      ]\n\ngenerateData\n    :: KnownNat n\n    => MWC.GenIO\n    -> IO (V.Vector (2^n) Double)\ngenerateData g = fmap (fmap realPart . ifftSized) . V.generateM $ \\i ->\n    let i' = recip . (+ 1) . fromIntegral $ i\n    in  (:+) <$> MWC.uniformR (-i', i') g\n             <*> MWC.uniformR (-i', i') g\n\nifftSized\n    :: V.Vector (2^n) (Complex Double)\n    -> V.Vector (2^n) (Complex Double)\nifftSized = V.withVectorUnsafe ifft\n", "meta": {"hexsha": "7144ec4669b6ad0a985dc38255960d6463404ae8", "size": 2817, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/bench.hs", "max_stars_repo_name": "mstksg/emd", "max_stars_repo_head_hexsha": "bc02724d861a8932b72a97745542a62dd19071d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-07-11T08:16:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T07:49:50.000Z", "max_issues_repo_path": "bench/bench.hs", "max_issues_repo_name": "mstksg/emd", "max_issues_repo_head_hexsha": "bc02724d861a8932b72a97745542a62dd19071d0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-07-26T09:36:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-22T09:24:58.000Z", "max_forks_repo_path": "bench/bench.hs", "max_forks_repo_name": "mstksg/emd", "max_forks_repo_head_hexsha": "bc02724d861a8932b72a97745542a62dd19071d0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2125, "max_line_length": 84, "alphanum_fraction": 0.5612353568, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.49645182738506205}}
{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections       #-}\n{-# LANGUAGE TypeFamilies        #-}\n{-# LANGUAGE TypeOperators       #-}\n\nimport           Control.Monad                (foldM)\nimport           Control.Monad.Random         (MonadRandom, getRandomR)\n\n#if __GLASGOW_HASKELL__ < 800\nimport           Data.List                    (unfoldr)\n#else\nimport           Data.List                    (cycle, unfoldr)\n#endif\nimport           Data.Semigroup               ((<>))\n\nimport qualified Numeric.LinearAlgebra.Static as SA\n\nimport           Options.Applicative\n\nimport           Grenade\nimport           Grenade.Recurrent\n\n-- The defininition for our simple recurrent network.\n-- This file just trains a network to generate a repeating sequence\n-- of 0 0 1.\n--\n-- The F and R types are Tagging types to ensure that the runner and\n-- creation function know how to treat the layers.\ntype R = Recurrent\n\ntype RecNet = RecurrentNetwork '[ R (LSTM 1 4), R (LSTM 4 1)]\n                               '[ 'D1 1, 'D1 4, 'D1 1 ]\n\ntype RecInput = RecurrentInputs '[ R (LSTM 1 4), R (LSTM 4 1)]\n\nrandomNet :: IO RecNet\nrandomNet = randomRecurrent\n\nnetTest :: MonadRandom m => RecNet -> RecInput -> LearningParameters -> Int -> m (RecNet, RecInput)\nnetTest net0 i0 rate iterations =\n    foldM trainIteration (net0,i0) [1..iterations]\n  where\n    trainingCycle = cycle [c 0, c 0, c 1]\n\n    trainIteration (net, io) _ = do\n      dropping <- getRandomR (0, 2)\n      count    <- getRandomR (5, 30)\n      let t     = drop dropping trainingCycle\n      let example = ((,Nothing) <$> take count t) ++ [(t !! count, Just $ t !! (count + 1))]\n      return $ trainEach net io example\n\n    trainEach !nt !io !ex = trainRecurrent rate nt io ex\n\ndata FeedForwardOpts = FeedForwardOpts Int LearningParameters\n\nfeedForward' :: Parser FeedForwardOpts\nfeedForward' = FeedForwardOpts <$> option auto (long \"examples\" <> short 'e' <> value 40000)\n                               <*> (LearningParameters\n                                    <$> option auto (long \"train_rate\" <> short 'r' <> value 0.01)\n                                    <*> option auto (long \"momentum\" <> value 0.9)\n                                    <*> option auto (long \"l2\" <> value 0.0005)\n                                    )\n\ngenerateRecurrent :: RecNet -> RecInput -> S ('D1 1) -> [Int]\ngenerateRecurrent n s i =\n  unfoldr go (s, i)\n    where\n  go (x, y) =\n    do let (_, ns, o) = runRecurrent n x y\n           o'         = heat o\n       Just (o', (ns, fromIntegral o'))\n\n  heat :: S ('D1 1) -> Int\n  heat x = case x of\n    (S1D v) -> round (SA.mean v)\n\nmain :: IO ()\nmain = do\n    FeedForwardOpts examples rate <- execParser (info (feedForward' <**> helper) idm)\n    putStrLn \"Training network...\"\n\n    net0                    <- randomNet\n    (trained, bestInput)    <- netTest net0 0 rate examples\n\n    let results = generateRecurrent trained bestInput (c 1)\n\n    print . take 50 . drop 100 $ results\n\nc :: Double -> S ('D1 1)\nc = S1D . SA.konst\n", "meta": {"hexsha": "dba014696b2ead6f8c556f14f8bc4ad72a2072bc", "size": 3126, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/recurrent.hs", "max_stars_repo_name": "koenigmaximilian/grenade", "max_stars_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/main/recurrent.hs", "max_issues_repo_name": "koenigmaximilian/grenade", "max_issues_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/main/recurrent.hs", "max_forks_repo_name": "koenigmaximilian/grenade", "max_forks_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2553191489, "max_line_length": 99, "alphanum_fraction": 0.5681381958, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236824, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4964518253087286}}
{"text": "{-# LANGUAGE RankNTypes #-}\n\nmodule Main where\n\nimport System.Random.MWC.Probability (Gen)\nimport qualified System.Random.MWC.Probability as MWC\nimport Control.Monad.Trans.State.Strict (execStateT)\n\nimport Statistics.Distribution.Poisson\nimport Statistics.Distribution.LogNormal\nimport Statistics.Distribution\n\nimport Conduit\n\nimport Data.Model\nimport Numeric.MCMC\n\n-- ~from https://hackage.haskell.org/package/declarative-0.2.1/docs/src/Numeric-MCMC.html#mcmc\n-- A Markov chain driven by an arbitrary transition operator.\n-- now using Conduit instead of Pipes\nchain\n  :: PrimMonad m\n  => Transition m b\n  -> b\n  -> Gen (PrimState m)\n  -> Producer m b\nchain transition = loop where\n  loop state prng = do\n    next <- lift (MWC.sample (execStateT transition state) prng)\n    yield next\n    loop next prng\n\n\nmain :: IO ()\nmain = withSystemRandom . asGenIO $\n        \\g -> chain (metropolis 10) c g =$ takeC 99999 =$ mapC (filter (`notElem` \"|\\\"\") . show) $$ mapM_C putStrLn\n\n    where c = Chain t (testLH initPred) initPred Nothing\n          t = Target testLH Nothing\n          testData = [1, 100, 25, 50]\n          initPred = [1, 1, 1, 1]\n          ln = logNormalDistr' 50 20\n          testLH xs = if any (<= 0) xs\n                         then log 0.0\n                         else predHistLLH testData (fmap poisson xs) + (sum $ map (logDensity ln) xs)\n", "meta": {"hexsha": "192c74832772630c4302ee40fedb3dee963bb2dc", "size": 1354, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/testMCMC.hs", "max_stars_repo_name": "cspollard/HMCMC", "max_stars_repo_head_hexsha": "292c3a3e6f0a60a71612dc45ba83f6e269b06f5e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/testMCMC.hs", "max_issues_repo_name": "cspollard/HMCMC", "max_issues_repo_head_hexsha": "292c3a3e6f0a60a71612dc45ba83f6e269b06f5e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/testMCMC.hs", "max_forks_repo_name": "cspollard/HMCMC", "max_forks_repo_head_hexsha": "292c3a3e6f0a60a71612dc45ba83f6e269b06f5e", "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.4347826087, "max_line_length": 115, "alphanum_fraction": 0.6639586411, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4963821159480646}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes     #-}\n{-# LANGUAGE ConstrainedClassMethods #-}\n{-# LANGUAGE ConstraintKinds         #-}\n{-# LANGUAGE DataKinds               #-}\n{-# LANGUAGE FlexibleContexts        #-}\n{-# LANGUAGE FlexibleInstances       #-}\n{-# LANGUAGE GADTs                   #-}\n{-# LANGUAGE InstanceSigs            #-}\n{-# LANGUAGE KindSignatures          #-}\n{-# LANGUAGE LambdaCase              #-}\n{-# LANGUAGE MultiParamTypeClasses   #-}\n{-# LANGUAGE PolyKinds               #-}\n{-# LANGUAGE RankNTypes              #-}\n{-# LANGUAGE ScopedTypeVariables     #-}\n{-# LANGUAGE StandaloneDeriving      #-}\n{-# LANGUAGE TypeApplications        #-}\n{-# LANGUAGE TypeFamilies            #-}\n{-# LANGUAGE TypeFamilyDependencies  #-}\n{-# LANGUAGE TypeInType              #-}\n{-# LANGUAGE TypeOperators           #-}\n{-# LANGUAGE UndecidableInstances    #-}\n{-# LANGUAGE ViewPatterns            #-}\n\nmodule TensorOps.Types where\n\nimport           Control.Category\nimport           Control.Monad.Primitive\nimport           Data.Finite\nimport           Data.Kind\nimport           Data.Singletons\nimport           Data.Type.Combinator\nimport           Data.Type.Length                  as TCL\nimport           Data.Type.Product                 as TCP\nimport           Data.Type.Product.Util            as TCP\nimport           Data.Type.Sing\nimport           Data.Type.Uniform\nimport           Data.Type.Vector\nimport           Prelude hiding                    ((.), id)\nimport           Statistics.Distribution\nimport           System.Random.MWC\nimport           TensorOps.NatKind\nimport           Type.Class.Higher\nimport           Type.Class.Known\nimport           Type.Class.Witness\nimport           Type.Family.List\n\n{-# RULES\n\"realToFrac/Double->Double\" realToFrac = id :: Double -> Double\n\"realToFrac/Float->Float\" realToFrac = id :: Float -> Float\n    #-}\n\nclass NatKind k => Tensor (t :: [k] -> Type) where\n    type ElemT t  :: Type\n\n    -- TODO: can we detach Vec from liftT ?\n    liftT   :: SingI o\n            => (Vec n (ElemT t) -> ElemT t)\n            -> Vec n (t o)\n            -> t o\n    gmul    :: (SingI (Reverse os ++ ns), SingI (ms ++ ns))\n            => Length ms\n            -> Length os\n            -> Length ns\n            -> t (ms         ++ os)\n            -> t (Reverse os ++ ns)\n            -> t (ms         ++ ns)\n    -- is a list really the best data structure here?\n    -- maybe Foldable f?\n    sumT    :: SingI o => [t o] -> t o\n    scaleT  :: SingI o => ElemT t -> t o -> t o\n    transp  :: (SingI ns, SingI (Reverse ns))\n            => t ns\n            -> t (Reverse ns)\n    -- sumRow  :: Remove ns n ms\n    --         -> t ns\n    --         -> t ms\n    mapRows :: SingI (ns ++ ms)\n            => Length ns\n            -> (t ms -> t ms)\n            -> t (ns ++ ms)\n            -> t (ns ++ ms)\n    sumRows :: (SingI (n ': ns), SingI ns)\n            => t (n ': ns)\n            -> t ns\n    diag    :: SingI (n ': ns)\n            => Uniform n ns\n            -> t '[n]\n            -> t (n ': ns)\n    getDiag :: SingI n\n            => Uniform n ns\n            -> t (n ': n ': ns)\n            -> t '[n]\n    genRand :: (ContGen d, PrimMonad m, SingI ns)\n            => d\n            -> Gen (PrimState m)\n            -> m (t ns)\n    generateA :: (Applicative f, SingI ns)\n              => (Prod (IndexN k) ns -> f (ElemT t))\n              -> f (t ns)\n    ixRows\n        :: (Applicative f, SingI (ms ++ os))\n        => Length ms\n        -> Length os\n        -> (Prod (IndexN k) ms -> t ns -> f (t os))\n        -> t (ms ++ ns)\n        -> f (t (ms ++ os))\n    (!) :: t ns\n        -> Prod (IndexN k) ns\n        -> ElemT t\n\n-- type TensorOp = OpPipe TOp\n\n-- | Function and gradient\ndata VFunc n\n    = VF { vfFunc :: !(forall a. RealFloat a => Vec n a -> a      )\n         , vfGrad :: !(forall a. RealFloat a => Vec n a -> Vec n a)\n         }\n\n-- -- | A kludge to get around lack of impredicative types in Haskell\n-- newtype VFunc n = VF { getVF :: forall a. RealFloat a => Vec n a -> a }\n\ndata TOp :: [[k]] -> [[k]] -> Type where\n    TOp :: { runTOp   :: !(forall t. (Tensor t, RealFloat (ElemT t)) => Prod t ns -> Prod t ms)\n           , gradTOp' :: !(forall t. (Tensor t, RealFloat (ElemT t)) => Prod t ns -> Prod t ms -> Prod t ns)\n           } -> TOp ns ms\n\ngradTOp\n    :: (Tensor t, RealFloat (ElemT t))\n    => TOp ns '[ '[] ]\n    -> Prod t ns\n    -> Prod t ns\ngradTOp o xs = gradTOp' o xs (only (getI $ generateA (\\_ -> I 1)))\n\n\ninstance Category TOp where\n    id = TOp id\n             (flip const)\n    {-# INLINE id #-}\n\n    (.) :: forall as bs cs. ()\n        => TOp bs cs\n        -> TOp as bs\n        -> TOp as cs\n    TOp f2 g2 . TOp f1 g1 = TOp f3 g3\n      where\n        f3  :: forall t. (Tensor t, RealFloat (ElemT t))\n            => Prod t as\n            -> Prod t cs\n        f3 = f2 . f1\n        {-# INLINE f3 #-}\n        g3  :: forall t. (Tensor t, RealFloat (ElemT t))\n            => Prod t as\n            -> Prod t cs\n            -> Prod t as\n        g3 xs ds = g1 xs (g2 (f1 xs) ds)\n        {-# INLINE g3 #-}\n    {-# INLINE (.) #-}\n\nidOp\n    :: forall ns. ()\n    => TOp ns ns\nidOp = id\n{-# INLINE idOp #-}\n\nfirstOp\n    :: forall os ns ms. (Known Length ns, Known Length ms)\n    => TOp ns ms\n    -> TOp (ns ++ os) (ms ++ os)\nfirstOp (TOp f g) = TOp f' g'\n  where\n    f'  :: forall t. (Tensor t, RealFloat (ElemT t))\n        => Prod t (ns ++ os)\n        -> Prod t (ms ++ os)\n    f' = overProdInit @os known f\n    {-# INLINE f' #-}\n    g'  :: forall t. (Tensor t, RealFloat (ElemT t))\n        => Prod t (ns ++ os)\n        -> Prod t (ms ++ os)\n        -> Prod t (ns ++ os)\n    g' (takeProd @os known -> xs) = overProdInit @os known (g xs)\n    {-# INLINE g' #-}\n{-# INLINE firstOp #-}\n\nsecondOp\n    :: forall os ns ms. Known Length os\n    => TOp ns ms\n    -> TOp (os ++ ns) (os ++ ms)\nsecondOp (TOp f g) = TOp f' g'\n  where\n    f'  :: forall t. (Tensor t, RealFloat (ElemT t))\n        => Prod t (os ++ ns)\n        -> Prod t (os ++ ms)\n    f' = overProdTail @os known f\n    {-# INLINE f' #-}\n    g'  :: forall t. (Tensor t, RealFloat (ElemT t))\n        => Prod t (os ++ ns)\n        -> Prod t (os ++ ms)\n        -> Prod t (os ++ ns)\n    g' (dropProd @os known -> xs) = overProdTail @os known (g xs)\n    {-# INLINE g' #-}\n{-# INLINE secondOp #-}\n\n\n(*>>)\n    :: forall as bs cs ds. (Known Length as, Known Length bs)\n    => TOp as bs\n    -> TOp (bs ++ cs) ds\n    -> TOp (as ++ cs) ds\nt1 *>> t2 = firstOp @cs t1 >>> t2\ninfixr 0 *>>\n{-# INLINE (*>>) #-}\n\n(<<*)\n    :: forall as bs cs ds. (Known Length as, Known Length bs)\n    => TOp (bs ++ cs) ds\n    -> TOp as bs\n    -> TOp (as ++ cs) ds\n(<<*) = flip ((*>>) @as @bs @cs @ds)\ninfixr 2 <<*\n{-# INLINE (<<*) #-}\n\n(***)\n    :: forall as bs cs ds. (Known Length as, Known Length cs)\n    => TOp as cs\n    -> TOp bs ds\n    -> TOp (as ++ bs) (cs ++ ds)\nTOp f1 g1 *** TOp f2 g2 = TOp f3 g3\n  where\n    f3  :: forall t. (Tensor t, RealFloat (ElemT t))\n        => Prod t (as ++ bs)\n        -> Prod t (cs ++ ds)\n    f3 = overProdSplit known f1 f2\n    {-# INLINE f3 #-}\n    g3  :: forall t. (Tensor t, RealFloat (ElemT t))\n        => Prod t (as ++ bs)\n        -> Prod t (cs ++ ds)\n        -> Prod t (as ++ bs)\n    g3 (splitProd known->(xs, ys)) = overProdSplit known (g1 xs) (g2 ys)\n    {-# INLINE g3 #-}\n{-# INLINE (***) #-}\n\n(&&&)\n    :: forall as bs cs. (Known Length bs, SingI as)\n    => TOp as bs\n    -> TOp as cs\n    -> TOp as (bs ++ cs)\nTOp f1 g1 &&& TOp f2 g2 = TOp f3 g3\n  where\n    f3  :: forall t. (Tensor t, RealFloat (ElemT t))\n        => Prod t as\n        -> Prod t (bs ++ cs)\n    f3 = TCP.append' <$> f1 <*> f2\n    {-# INLINE f3 #-}\n    g3  :: forall t. (Tensor t, RealFloat (ElemT t))\n        => Prod t as\n        -> Prod t (bs ++ cs)\n        -> Prod t as\n    g3 xs (splitProd known->(dtdys,dtdzs)) =\n        zipProdWith3 (\\s gxy gxz -> sumT [gxy,gxz] \\\\ s)\n                     (singProd sing)\n                     (g1 xs dtdys)\n                     (g2 xs dtdzs)\n    {-# INLINE g3 #-}\n{-# INLINE (&&&) #-}\n\n\n-- -- | TODO: replace with `syntactic`?\n-- data OpPipe :: ([k] -> [k] -> Type) -> [k] -> [k] -> Type where\n--     OP\u00d8   :: OpPipe f a a\n--     Pop   :: !(Sing a)\n--           -> !(Sing b)\n--           -> !(Sing d)\n--           -> !(f a b)\n--           -> !(OpPipe f (b ++ d) c)\n--           -> OpPipe f (a ++ d) c\n\n-- pappend\n--     :: forall a b c d f. ()\n--     => Sing a\n--     -> Sing b\n--     -> Sing d\n--     -> OpPipe f a b\n--     -> OpPipe f (b ++ d) c\n--     -> OpPipe f (a ++ d) c\n-- pappend _ sB sD = \\case\n--     OP\u00d8 -> id\n--     Pop (sA' :: Sing a')\n--         (sB' :: Sing b')\n--         (sD' :: Sing d')\n--         (x   :: f a' b'  )\n--         (xs  :: OpPipe f (b' ++ d') b)\n--           -> \\ys -> let lD' :: Length d'\n--                         lD' = singLength sD'\n--                     in  Pop sA' sB' (sD' %:++ sD) x (pappend (sB' %:++ sD') sB sD xs ys)\n--                           \\\\ appendAssoc (singLength sA') lD' lD\n--                           \\\\ appendAssoc (singLength sB') lD' lD\n--   where\n--     lD :: Length d\n--     lD = singLength sD\n\n-- pipe\n--     :: forall t a b. (SingI a, SingI b)\n--     => t a b\n--     -> OpPipe t a b\n-- pipe o = Pop sing sing SNil o OP\u00d8\n--            \\\\ appendNil (singLength (sing :: Sing a))\n--            \\\\ appendNil (singLength (sing :: Sing b))\n\n-- pop :: forall a b c d f. (SingI a, SingI b, SingI d)\n--     => Length d\n--     -> f a b\n--     -> OpPipe f (b ++ d) c\n--     -> OpPipe f (a ++ d) c\n-- pop _ = Pop (sing :: Sing a) (sing :: Sing b) (sing :: Sing d)\n\n-- infixr 4 ~.\n-- (~.)\n--     :: (SingI a, SingI b, SingI d)\n--     => (Length a, Length d, f a b)\n--     -> OpPipe f (b ++ d) c\n--     -> OpPipe f (a ++ d) c\n-- (_, lD, x) ~. y = pop lD x y\n\ninstance Eq1 Finite\n", "meta": {"hexsha": "b75d2448543a430821adebd54d7e2f28979b8082", "size": 9733, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/TensorOps/Types.hs", "max_stars_repo_name": "mstksg/tensor-ops", "max_stars_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2016-08-24T06:50:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T00:31:35.000Z", "max_issues_repo_path": "src/TensorOps/Types.hs", "max_issues_repo_name": "mstksg/tensor-ops", "max_issues_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-09-29T06:01:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T10:52:51.000Z", "max_forks_repo_path": "src/TensorOps/Types.hs", "max_forks_repo_name": "mstksg/tensor-ops", "max_forks_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-09-28T05:44:48.000Z", "max_forks_repo_forks_event_max_datetime": "2017-01-30T11:01:34.000Z", "avg_line_length": 29.9476923077, "max_line_length": 108, "alphanum_fraction": 0.4547416007, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6001883592602051, "lm_q1q2_score": 0.4961828055142654}}
{"text": "{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators       #-}\n\nimport           Control.DeepSeq\nimport           Control.Exception\nimport           Control.Monad\nimport           Control.Monad.IO.Class\nimport           Control.Monad.Trans.Maybe\nimport           Control.Monad.Trans.State\nimport           Data.Bifunctor\nimport           Data.Bitraversable\nimport           Data.Default\nimport           Data.Finite\nimport           Data.IDX\nimport           Data.List.Split\nimport           Data.Time.Clock\nimport           Data.Traversable\nimport           Data.Tuple\nimport           Data.Type.Product\nimport           Learn.Neural\nimport           Numeric.BLAS.HMatrix\nimport           Numeric.LinearAlgebra.Static\nimport           Text.Printf\nimport qualified Data.Vector                     as V\nimport qualified Data.Vector.Generic             as VG\nimport qualified Data.Vector.Unboxed             as VU\nimport qualified System.Random.MWC               as MWC\nimport qualified System.Random.MWC.Distributions as MWC\n\nloadMNIST\n    :: FilePath\n    -> FilePath\n    -> IO (Maybe [(HM '[784], HM '[10])])\nloadMNIST fpI fpL = runMaybeT $ do\n    i <- MaybeT          $ decodeIDXFile       fpI\n    l <- MaybeT          $ decodeIDXLabelsFile fpL\n    d <- MaybeT . return $ labeledIntData l i\n    r <- MaybeT . return $ for d (bitraverse mkImage mkLabel . swap)\n    liftIO . evaluate $ force r\n  where\n    mkImage :: VU.Vector Int -> Maybe (HM '[784])\n    mkImage = fmap HM . create . VG.convert . VG.map (\\i -> fromIntegral i / 255)\n    mkLabel :: Int -> Maybe (HM '[10])\n    mkLabel = fmap (oneHot . only) . packFinite . fromIntegral\n\nmain :: IO ()\nmain = MWC.withSystemRandom $ \\g -> do\n    Just train <- loadMNIST \"data/train-images-idx3-ubyte\" \"data/train-labels-idx1-ubyte\"\n    Just test  <- loadMNIST \"data/t10k-images-idx3-ubyte\"  \"data/t10k-labels-idx1-ubyte\"\n    putStrLn \"Loaded data.\"\n    net0 :: Network 'FeedForward HM ( '[784] :~ FullyConnected )\n                                   '[ '[300] :~ LogitMap\n                                    , '[300] :~ FullyConnected\n                                    , '[100] :~ LogitMap\n                                    , '[100] :~ FullyConnected\n                                    , '[10 ] :~ SoftMax '[10]\n                                    ]\n                                    '[10] <- initDefNet g\n    let dout = alongNet net0 $ Nothing\n                           :&% Just 0.2\n                           :&% Nothing\n                           :&% Just 0.2\n                           :&% Nothing\n                           :&% DOExt\n    flip evalStateT net0 . forM_ [1..] $ \\e -> do\n      train' <- liftIO . fmap V.toList $ MWC.uniformShuffle (V.fromList train) g\n      liftIO $ printf \"[Epoch %d]\\n\" (e :: Int)\n\n      forM_ ([1..] `zip` chunksOf batch train') $ \\(b, chnk) -> StateT $ \\n0 -> do\n        printf \"(Batch %d)\\n\" (b :: Int)\n\n        t0 <- getCurrentTime\n        -- n' <- evaluate $ optimizeList_ (bimap only_ only_ <$> chnk) n0\n        --                                -- (sgdOptimizer rate netOpPure crossEntropy)\n        --                                (adamOptimizer def netOpPure crossEntropy)\n        n' <- optimizeListM_ (bimap only_ only_ <$> chnk) n0\n                             (adamOptimizerM def (netOpDOPure dout g) crossEntropy)\n        t1 <- getCurrentTime\n        printf \"Trained on %d points in %s.\\n\" batch (show (t1 `diffUTCTime` t0))\n\n        let trainScore = testNetList maxTest (someNet n') chnk\n            testScore  = testNetList maxTest (someNet n') test\n        printf \"Training error:   %.2f%%\\n\" ((1 - trainScore) * 100)\n        printf \"Validation error: %.2f%%\\n\" ((1 - testScore ) * 100)\n\n        return ((), n')\n  where\n    -- rate :: Double\n    -- rate  = 0.02\n    batch :: Int\n    batch = 2500\n", "meta": {"hexsha": "909131c57c6918594ecb84b1dd6c8f6d043d2e26", "size": 3852, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "old/app/MNIST.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "old/app/MNIST.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "old/app/MNIST.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 41.4193548387, "max_line_length": 89, "alphanum_fraction": 0.5244029076, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4961469096579945}}
{"text": "module SampleWeight\n    ( Weight\n    , Bias\n    , SampleWeight\n    , createBinarySW\n    , loadSW\n    ) where\n\nimport Control.Applicative ((<$>))\nimport Control.Monad\nimport Numeric.LinearAlgebra\nimport qualified Data.ByteString.Lazy as BL\nimport qualified Codec.Compression.GZip as GZ (compress, decompress)\nimport Data.Binary (encode, decode)\nimport Text.Parsec\n\ntype Weight = Matrix R\ntype Bias = Vector R\ntype SampleWeight = ([Weight], [Bias])\n\nassetsDir = \"assets\"\nweightFiles = [ \"sample-weight-w1\"\n              , \"sample-weight-w2\"\n              , \"sample-weight-w3\"\n              , \"sample-weight-b1\"\n              , \"sample-weight-b2\"\n              , \"sample-weight-b3\"\n              ]\n\ngeneratePath :: String -> String\ngeneratePath p = assetsDir ++ \"/\" ++ p\n\ncreateBinary :: String -> IO ()\ncreateBinary p = do\n    let bp = generatePath p\n\n    ws <- readFile $ bp ++ \".csv\"\n    case parseCSV ws of\n      Left e -> print e\n      Right w -> do\n        putStrLn $ \"Creating binary Matrix file: \" ++ bp\n        let wm = fromLists $ fmap (read :: String -> Double) <$> w\n        createPickle (bp ++ \".dat\") wm\n        putStrLn \"Done\"\n\ncreateBinarySW :: IO ()\ncreateBinarySW = forM_ weightFiles createBinary\n\ncsvStruct = endBy line eol\nline = sepBy cell $ char ','\ncell = many $ noneOf \",\\n\"\neol = char '\\n'\n\nparseCSV :: String -> Either ParseError [[String]]\nparseCSV = parse csvStruct \"* ParseError *\"\n\ncreatePickle :: String -> Matrix R -> IO ()\ncreatePickle p w = BL.writeFile p $ (GZ.compress . encode) w\n\nloadPickle :: String -> IO (Matrix R)\nloadPickle p = do\n    esw <- BL.readFile $ generatePath p ++ \".dat\"\n    return $ (decode . GZ.decompress) esw\n\nloadSW :: IO SampleWeight\nloadSW = do\n    sw <- forM weightFiles loadPickle\n    let (w,b) = splitAt 3 sw\n    return (w, fmap flatten b)\n", "meta": {"hexsha": "f5485a643be779ce6a4abff0d16abab3157b9bfe", "size": 1800, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SampleWeight.hs", "max_stars_repo_name": "ku00/deep-learning-practice", "max_stars_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-03T05:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T05:32:58.000Z", "max_issues_repo_path": "src/SampleWeight.hs", "max_issues_repo_name": "ku00/deep-learning-practice", "max_issues_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "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/SampleWeight.hs", "max_forks_repo_name": "ku00/deep-learning-practice", "max_forks_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7142857143, "max_line_length": 68, "alphanum_fraction": 0.6272222222, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.4960919922641956}}
{"text": "{-# LANGUAGE TemplateHaskell #-}\n\nmodule Types where\n\nimport Lens.Micro.TH\nimport Lens.Micro\nimport qualified Statistics.Distribution.Normal as Stat\nimport qualified Statistics.Distribution as Stat\n\ndata Bandit d = Bandit d\n\ninstance (Stat.Mean d, Stat.Variance d) => Show (Bandit d) where\n  show (Bandit d) = \"Bandit {mean = \" ++ show (Stat.mean d) ++ \", stdDev = \" ++ show (Stat.stdDev d) ++ \"}\"\n\ndistLens :: Lens' (Bandit d) d\ndistLens = lens (\\(Bandit d) -> d) (\\_ d -> Bandit d)\n\nmeanLens :: Lens' Stat.NormalDistribution Double\nmeanLens = lens (\\d -> Stat.mean d) (\\d m -> Stat.normalDistr m (Stat.stdDev d))\n\n-- Statistics about a given bandit.\ndata BanditStats = BanditStats { _totalReward :: Double\n                               , _timesPulled :: Int\n                               } deriving (Eq, Show)\n\nmakeLenses ''BanditStats\n\ninstance Monoid BanditStats where\n  a `mappend` b = BanditStats (a ^. totalReward + b ^. totalReward) (a ^. timesPulled + b ^. timesPulled)\n  mempty = BanditStats 0.0 0\n\ntype BanditDist = Stat.NormalDistribution\n\ndata SimState = SimState { _bandits :: [(BanditStats, Bandit BanditDist)] -- ^ The bandits and associated statistics\n                         , _roundsCount :: Int -- ^ Number of rounds so far\n                         , _regretHist :: [Double]\n                         }\n\nmakeLenses ''SimState\n\ninstance Show SimState where\n  show (SimState b count regretHist_) = \"SimState { bandits = \" ++ show b ++ \", n = \" ++ show count ++ \", regret = \"++ show regretHist_ ++\"}\"\n\ntype BanditState = (BanditStats, Bandit BanditDist)\n", "meta": {"hexsha": "0447d5d26fb0e6c3e62723e01d80314df5ab2993", "size": 1573, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Types.hs", "max_stars_repo_name": "beala/bandits", "max_stars_repo_head_hexsha": "e0847e3cb4446483c250333b38aa6d6215e52b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Types.hs", "max_issues_repo_name": "beala/bandits", "max_issues_repo_head_hexsha": "e0847e3cb4446483c250333b38aa6d6215e52b29", "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/Types.hs", "max_forks_repo_name": "beala/bandits", "max_forks_repo_head_hexsha": "e0847e3cb4446483c250333b38aa6d6215e52b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9555555556, "max_line_length": 141, "alphanum_fraction": 0.6363636364, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.49609198440227326}}
{"text": "-- |\n-- Module      : Streamly.Statistics\n-- Copyright   : (c) 2020 Composewell Technologies\n-- License     : Apache-2.0\n-- Maintainer  : streamly@composewell.com\n-- Stability   : experimental\n-- Portability : GHC\n--\n-- Statistical measures over a stream of data. All operations use numerically\n-- stable floating point arithmetic.\n--\n-- Measurements can be performed over the entire input stream or on a sliding\n-- window of fixed or variable size.  Where possible, measures are computed\n-- online without buffering the input stream.\n--\n-- Currently there is no overflow detection.\n--\n-- References:\n--\n-- * https://en.wikipedia.org/wiki/Statistics\n-- * https://mathworld.wolfram.com/topics/ProbabilityandStatistics.html\n\n-- Resources:\n--\n-- This may be another useful resource for incremental (non-windowed)\n-- computation:\n--\n-- https://www.researchgate.net/publication/287152055_Incremental_Statistical_Measures\n--\n-- Sample Statistics\n--\n-- Terms\n--\n-- Population: the complete data set from which statistical samples are taken.\n--\n-- Sample: a subset of the population.\n--\n-- https://en.wikipedia.org/wiki/Sample_(statistics)\n--\n-- Estimator:\n--\n-- Statistical measures can be computed either from the actual population\n-- or from samples. Statistical measures computed from the samples provide an\n-- estimate of the actual measures of the entire population. Measures computed\n-- from samples may not truly reflect the actual measures and may have to be\n-- adjusted for biases or errors.\n--\n-- An \"estimator\" is a method or function to compute a statistical measure from\n-- sampled data. For example, the sample variance is an esitmator of the\n-- population variance.\n--\n-- https://en.wikipedia.org/wiki/Estimator\n--\n-- Bias:\n--\n-- The result computed by an estimator may not be centered at the true value as\n-- determined by computing the measure for the actual population. Such an\n-- estimator is called a biased estimator.  For example, notice how\n-- 'sampleVariance' is adjusted for bias.\n--\n-- https://en.wikipedia.org/wiki/Bias_of_an_estimator\n--\n-- Consistency:\n--\n-- https://en.wikipedia.org/wiki/Consistent_estimator\n\n{-# LANGUAGE ScopedTypeVariables #-}\nmodule Streamly.Statistics\n    (\n    -- * Incremental Folds\n    -- | Folds of type @Fold m (a, Maybe a) b@ are incremental sliding window\n    -- folds. An input of type @(a, Nothing)@ indicates that the input element\n    -- @a@ is being inserted in the window without ejecting an old value\n    -- increasing the window size by 1. An input of type @(a, Just a)@\n    -- indicates that the first element is being inserted in the window and the\n    -- second element is being removed from the window, the window size remains\n    -- the same. The window size can only increase and never decrease.\n    --\n    -- You can compute the statistics over the entire stream using sliding\n    -- window folds by keeping the second element of the input tuple as\n    -- @Nothing@.\n    --\n      Window.lmap\n    , Window.cumulative\n\n    -- * Summary Statistics\n    -- | See https://en.wikipedia.org/wiki/Summary_statistics .\n\n    -- ** Sums\n    , Window.length\n    , Window.sum\n    , Window.sumInt\n    , Window.powerSum\n\n    -- ** Location\n    -- | See https://en.wikipedia.org/wiki/Location_parameter .\n    --\n    -- See https://en.wikipedia.org/wiki/Central_tendency .\n    , Window.minimum\n    , Window.maximum\n    , rawMoment\n    , rawMomentFrac\n\n    -- Pythagorean means (https://en.wikipedia.org/wiki/Pythagorean_means)\n    , mean\n    , welfordMean\n    , geometricMean\n    , harmonicMean\n\n    , quadraticMean\n\n    -- Generalized mean\n    , powerMean\n    , powerMeanFrac\n\n    -- ** Weighted Means\n    -- | Exponential Smoothing.\n    , ewma\n    , ewmaAfterMean\n    , ewmaRampUpSmoothing\n\n    -- ** Spread\n    -- | Second order central moment is a statistical measure of dispersion.\n    -- The \\(k\\)th moment about the mean (or \\(k\\)th central moment) is defined\n    -- as:\n    --\n    -- \\(\\mu_k = \\frac{1}{n}\\sum_{i=1}^n {(x_{i}-\\mu)}^k\\)\n    --\n    -- See https://mathworld.wolfram.com/CentralMoment.html .\n    --\n    -- See https://en.wikipedia.org/wiki/Statistical_dispersion .\n    , Window.range\n    , md\n    , variance\n    , stdDev\n\n    -- ** Shape\n    -- | Third and fourth order central moments are a measure of shape.\n    --\n    -- See https://en.wikipedia.org/wiki/Shape_parameter .\n    --\n    -- See https://en.wikipedia.org/wiki/Standardized_moment .\n    , skewness\n    , kurtosis\n\n    -- XXX Move to Statistics.Sample or Statistics.Estimation module?\n    -- ** Estimation\n    , sampleVariance\n    , sampleStdDev\n    , stdErrMean\n\n    -- ** Resampling\n    , resample\n    , foldResamples\n    , jackKnifeMean\n    , jackKnifeVariance\n    , jackKnifeStdDev\n\n    -- ** Probability Distribution\n    , frequency\n    , mode\n\n    -- Histograms\n    , HistBin (..)\n    , binOffsetSize\n    , binFromSizeN\n    , binFromToN\n    , binBoundaries\n    , histogram\n\n    -- * Transforms\n    , fft\n    )\nwhere\n\nimport Control.Exception (assert)\nimport Control.Monad (when)\nimport Control.Monad.IO.Class (MonadIO(..))\nimport Data.Functor.Identity (runIdentity, Identity)\nimport Data.Bits (Bits(complement, shiftL, shiftR, (.&.), (.|.)))\nimport Data.Complex (Complex ((:+)))\nimport Data.Map.Strict (Map, foldrWithKey)\nimport Foreign.Storable (Storable)\nimport Streamly.Data.Fold.Tee(Tee(..), toFold)\nimport Streamly.Internal.Control.Concurrent (MonadAsync)\nimport Streamly.Internal.Data.Array.Foreign.Type\n    (Array, length, toStream, unsafeIndexIO)\nimport Streamly.Internal.Data.Fold.Type (Fold(..), Step(..))\nimport Streamly.Internal.Data.Stream.IsStream (SerialT)\nimport Streamly.Internal.Data.Stream.StreamD.Step (Step(..))\nimport Streamly.Internal.Data.Tuple.Strict (Tuple'(..))\nimport Streamly.Internal.Data.Unfold.Type (Unfold(..))\nimport System.Random.MWC (createSystemRandom, uniformRM)\n\nimport qualified Streamly.Internal.Data.Array.Foreign as Array\nimport qualified Streamly.Internal.Data.Array.Foreign.Mut as MA\nimport qualified Streamly.Internal.Data.Fold as Fold\nimport qualified Streamly.Internal.Data.Fold.Window as Window\nimport qualified Streamly.Internal.Data.Stream.IsStream as Stream\nimport qualified Streamly.Internal.Data.Unfold as Unfold\n\nimport Prelude hiding (length, sum, minimum, maximum)\n\n-- TODO: Overflow checks. Would be good if we can directly replace the\n-- operations with overflow checked operations.\n--\n-- See https://hackage.haskell.org/package/safe-numeric\n-- See https://hackage.haskell.org/package/safeint\n--\n-- TODO We have many of these functions in Streamly.Data.Fold as well. Need to\n-- think about deduplication.\n\n-------------------------------------------------------------------------------\n-- Transforms\n-------------------------------------------------------------------------------\n\n-- XXX These utility functions can be moved to streamly-numeric\n\n-- | Test if the given integer value is a power of 2.\n{-# INLINE isPower2 #-}\nisPower2 :: Int -> Bool\nisPower2 n = n .&. (n - 1) == 0\n\n-- | Create a power of 2\n--\n-- Argument must be less than 64 assuming 64-bit Int size.\n--\n{-# INLINE _power2 #-}\n_power2 :: Int -> Int\n_power2 n = shiftL 1 n\n\n-- | Create a bit mask with lower n bits 0 and the rest as 1.\n--\n-- Argument must be less than 64 assuming 64-bit Int size.\n--\n{-# INLINE maskLowerN #-}\nmaskLowerN :: Int -> Int\nmaskLowerN n = complement (shiftL 1 n - 1)\n\n-- | Compute the base 2 logarithm of the given value.\n--\n-- Assumes the Int size to be 64-bit.\n--\n{-# INLINE logBase2 #-}\nlogBase2 :: Int -> Int\nlogBase2 v0\n    | v0 <= 0   = error $ \"logBase2: input must be greater than 0 \" ++ show v0\n    | otherwise = go 32 0 v0\n\n    where\n\n    go !bits !result !v\n        | bits == 0 = result\n        | v .&. maskLowerN bits /= 0 =\n             go (bits `shiftR` 1) (result .|. bits) (v `shiftR` bits)\n        | otherwise = go (bits `shiftR` 1) result v\n\n-- Algo translated from the statistics library.\n--\n-- XXX We can use a wrapper API that takes an array of Double input instead of\n-- array of Complex.\n--\n-- | Compute fast fourier transform of an array of 'Complex' values.\n--\n-- Array length must be power of 2.\n--\n{-# INLINE fft #-}\nfft :: MonadIO m => MA.Array (Complex Double) -> m ()\nfft marr\n    | isPower2 len = bitReverse 0 0\n    | otherwise  = error \"fft: Array length must be power of 2\"\n\n    where\n\n    len = MA.length marr\n\n    halve x = x `shiftR` 1\n\n    twice x = x `shiftL` 1\n\n    inner i j k\n        | k <= j  = inner i (j - k) (halve k)\n        | otherwise = bitReverse (i + 1) (j + k)\n\n    bitReverse i j\n        | i == len - 1 = stage 0 1\n        | otherwise = do\n            when (i < j) $ MA.unsafeSwapIndices i j marr\n            inner i j (halve len)\n\n    log2len = logBase2 len\n\n    stage l !l1\n        | l == log2len = return ()\n        | otherwise = do\n            let !l2 = twice l1\n                !e  = -6.283185307179586/fromIntegral l2\n                flight j !a | j == l1   = stage (l + 1) l2\n                            | otherwise = do\n                    let butterfly i | i >= len  = flight (j + 1) (a + e)\n                                    | otherwise = do\n                            let i1 = i + l1\n                            xi1 :+ yi1 <- MA.getIndexUnsafe i1 marr\n                            let !c = cos a\n                                !s = sin a\n                                d  = (c * xi1 - s * yi1) :+ (s * xi1 + c * yi1)\n                            ci <- MA.getIndexUnsafe i marr\n                            MA.putIndexUnsafe  i1 (ci - d) marr\n                            MA.putIndexUnsafe  i (ci + d) marr\n                            butterfly (i + l2)\n                    butterfly j\n            flight 0 0\n\n-------------------------------------------------------------------------------\n-- Mean\n-------------------------------------------------------------------------------\n\n-- | Arithmetic mean of elements in a sliding window:\n--\n-- \\(\\mu = \\frac{\\sum_{i=1}^n x_{i}}{n}\\)\n--\n-- This is also known as the Simple Moving Average (SMA) when used in the\n-- sliding window and Cumulative Moving Avergae (CMA) when used on the entire\n-- stream.\n--\n-- Mean is the same as the first raw moment.\n--\n-- \\(\\mu = \\mu'_1\\)\n--\n-- >>> mean = rawMoment 1\n-- >>> mean = powerMean 1\n-- >>> mean = Fold.teeWith (/) sum length\n--\n-- /Space/: \\(\\mathcal{O}(1)\\)\n--\n-- /Time/: \\(\\mathcal{O}(n)\\)\n{-# INLINE mean #-}\nmean :: forall m a. (Monad m, Fractional a) => Fold m (a, Maybe a) a\nmean = Window.mean\n\n-- | Recompute mean from old mean when an item is removed from the sample.\n{-# INLINE _meanSubtract #-}\n_meanSubtract :: Fractional a => Int -> a -> a -> a\n_meanSubtract n oldMean oldItem =\n    let delta = (oldItem - oldMean) / fromIntegral (n - 1)\n     in oldMean - delta\n\n-- | Recompute mean from old mean when an item is added to the sample.\n{-# INLINE meanAdd #-}\nmeanAdd :: Fractional a => Int -> a -> a -> a\nmeanAdd n oldMean newItem =\n    let delta = (newItem - oldMean) / fromIntegral (n + 1)\n     in oldMean + delta\n\n-- We do not carry rounding errors, therefore, this would be less numerically\n-- stable than the kbn mean.\n--\n-- | Recompute mean from old mean when an item in the sample is replaced.\n{-# INLINE meanReplace #-}\nmeanReplace :: Fractional a => Int -> a -> a -> a -> a\nmeanReplace n oldMean oldItem newItem =\n    let n1 = fromIntegral n\n        -- Compute two deltas instead of a single (newItem - oldItem) because\n        -- the latter would be too small causing rounding errors.\n        delta1 = (newItem - oldMean) / n1\n        delta2 = (oldItem - oldMean) / n1\n     in (oldMean + delta1) - delta2\n\n-- | Same as 'mean' but uses Welford's algorithm to compute the mean\n-- incrementally.\n--\n-- It maintains a running mean instead of a running sum and adjusts the mean\n-- based on a new value.  This is slower than 'mean' because of using the\n-- division operation on each step and it is numerically unstable (as of now).\n-- The advantage over 'mean' could be no overflow if the numbers are large,\n-- because we do not maintain a sum, but that is a highly unlikely corner case.\n--\n-- /Internal/\n{-# INLINE welfordMean #-}\nwelfordMean :: forall m a. (Monad m, Fractional a) => Fold m (a, Maybe a) a\nwelfordMean = Fold step initial extract\n\n    where\n\n    initial =\n        return\n            $ Partial\n            $ Tuple'\n                (0 :: a)   -- running mean\n                (0 :: Int) -- count of items in the window\n\n    step (Tuple' oldMean w) (new, mOld) =\n        return\n            $ Partial\n            $ case mOld of\n                Nothing -> Tuple' (meanAdd w oldMean new) (w + 1)\n                Just old -> Tuple' (meanReplace w oldMean old new) w\n\n    extract (Tuple' x _) = return x\n\n-------------------------------------------------------------------------------\n-- Moments\n-------------------------------------------------------------------------------\n\n-- XXX We may have chances of overflow if the powers are high or the numbers\n-- are large. A limited mitigation could be to use welford style avg\n-- computation. Do we need an overflow detection?\n--\n-- | Raw moment is the moment about 0. The \\(k\\)th raw moment is defined as:\n--\n-- \\(\\mu'_k = \\frac{\\sum_{i=1}^n x_{i}^k}{n}\\)\n--\n-- >>> rawMoment k = Fold.teeWith (/) (powerSum p) length\n--\n-- See https://en.wikipedia.org/wiki/Moment_(mathematics) .\n--\n-- /Space/: \\(\\mathcal{O}(1)\\)\n--\n-- /Time/: \\(\\mathcal{O}(n)\\)\n{-# INLINE rawMoment #-}\nrawMoment :: (Monad m, Fractional a) => Int -> Fold m (a, Maybe a) a\nrawMoment k = Fold.teeWith (/) (Window.powerSum k) Window.length\n\n-- | Like 'rawMoment' but powers can be negative or fractional. This is\n-- slower than 'rawMoment' for positive intergal powers.\n--\n-- >>> rawMomentFrac p = Fold.teeWith (/) (powerSumFrac p) length\n--\n{-# INLINE rawMomentFrac #-}\nrawMomentFrac :: (Monad m, Floating a) => a -> Fold m (a, Maybe a) a\nrawMomentFrac k = Fold.teeWith (/) (Window.powerSumFrac k) Window.length\n\n-- XXX Overflow can happen when large powers or large numbers are used. We can\n-- keep a running mean instead of running sum but that won't mitigate the\n-- overflow possibility by much. The overflow can still happen when computing\n-- the mean incrementally.\n\n-- | The \\(k\\)th power mean of numbers \\(x_1, x_2, \\ldots, x_n\\) is:\n--\n-- \\(M_k = \\left( \\frac{1}{n} \\sum_{i=1}^n x_i^k \\right)^{\\frac{1}{k}}\\)\n--\n-- \\(powerMean(k) = (rawMoment(k))^\\frac{1}{k}\\)\n--\n-- >>> powerMean k = (** (1 / fromIntegral k)) <$> rawMoment k\n--\n-- All other means can be expressed in terms of power mean. It is also known as\n-- the generalized mean.\n--\n-- See https://en.wikipedia.org/wiki/Generalized_mean\n--\n{-# INLINE powerMean #-}\npowerMean :: (Monad m, Floating a) => Int -> Fold m (a, Maybe a) a\npowerMean k = (** (1 / fromIntegral k)) <$> rawMoment k\n\n-- | Like 'powerMean' but powers can be negative or fractional. This is\n-- slower than 'powerMean' for positive intergal powers.\n--\n-- >>> powerMeanFrac k = (** (1 / k)) <$> rawMomentFrac k\n--\n{-# INLINE powerMeanFrac #-}\npowerMeanFrac :: (Monad m, Floating a) => a -> Fold m (a, Maybe a) a\npowerMeanFrac k = (** (1 / k)) <$> rawMomentFrac k\n\n-- | The harmonic mean of the positive numbers \\(x_1, x_2, \\ldots, x_n\\) is\n-- defined as:\n--\n-- \\(HM = \\frac{n}{\\frac1{x_1} + \\frac1{x_2} + \\cdots + \\frac1{x_n}}\\)\n--\n-- \\(HM = \\left(\\frac{\\sum\\limits_{i=1}^n x_i^{-1}}{n}\\right)^{-1}\\)\n--\n-- >>> harmonicMean = Fold.teeWith (/) length (lmap recip sum)\n-- >>> harmonicMean = powerMeanFrac (-1)\n--\n-- See https://en.wikipedia.org/wiki/Harmonic_mean .\n--\n{-# INLINE harmonicMean #-}\nharmonicMean :: (Monad m, Fractional a) => Fold m (a, Maybe a) a\nharmonicMean = Fold.teeWith (/) Window.length (Window.lmap recip Window.sum)\n\n-- | Geometric mean, defined as:\n--\n-- \\(GM = \\sqrt[n]{x_1 x_2 \\cdots x_n}\\)\n--\n-- \\(GM = \\left(\\prod_{i=1}^n x_i\\right)^\\frac{1}{n}\\)\n--\n-- or, equivalently, as the arithmetic mean in log space:\n--\n-- \\(GM = e ^{{\\frac{\\sum_{i=1}^{n}\\ln a_i}{n}}}\\)\n--\n-- >>> geometricMean = exp <$> lmap log mean\n--\n-- See https://en.wikipedia.org/wiki/Geometric_mean .\n{-# INLINE geometricMean #-}\ngeometricMean :: (Monad m, Floating a) => Fold m (a, Maybe a) a\ngeometricMean = exp <$> Window.lmap log mean\n\n-- | The quadratic mean or root mean square (rms) of the numbers\n-- \\(x_1, x_2, \\ldots, x_n\\) is defined as:\n--\n-- \\(RMS = \\sqrt{ \\frac{1}{n} \\left( x_1^2 + x_2^2 + \\cdots + x_n^2 \\right) }.\\)\n--\n-- >>> quadraticMean = powerMean 2\n--\n-- See https://en.wikipedia.org/wiki/Root_mean_square .\n--\n{-# INLINE quadraticMean #-}\nquadraticMean :: (Monad m, Floating a) => Fold m (a, Maybe a) a\nquadraticMean = powerMean 2\n\n-------------------------------------------------------------------------------\n-- Weighted Means\n-------------------------------------------------------------------------------\n\n-- XXX Is this numerically stable? We can use the kbn summation here.\n-- | ewmaStep smoothing-factor old-value new-value\n{-# INLINE ewmaStep #-}\newmaStep :: Double -> Double -> Double -> Double\newmaStep k x0 x1 = (1 - k) * x0 + k * x1\n\n-- XXX Compute this in a sliding window?\n--\n-- | @ewma smoothingFactor@.\n--\n-- @ewma@ of an empty stream is 0.\n--\n-- Exponential weighted moving average, \\(s_n\\), of \\(n\\) values,\n-- \\(x_1,\\ldots,x_n\\), is defined recursively as:\n--\n-- \\(\\begin{align} s_0& = x_0\\\\ s_n & = \\alpha x_{n} + (1-\\alpha)s_{n-1},\\quad n>0 \\end{align}\\)\n--\n-- If we expand the recursive term it becomes an exponential series:\n--\n-- \\(s_n = \\alpha \\left[x_n + (1-\\alpha)x_{n-1} + (1-\\alpha)^2 x_{n-2} + \\cdots + (1-\\alpha)^{n-1} x_1 \\right] + (1-\\alpha)^n x_0\\)\n--\n-- where \\(\\alpha\\), the smoothing factor, is in the range \\(0 <\\alpha < 1\\).\n-- More the value of \\(\\alpha\\), the more weight is given to newer values.  As\n-- a special case if it is 0 then the weighted sum would always be the same as\n-- the oldest value, if it is 1 then the sum would always be the same as the\n-- newest value.\n--\n-- See https://en.wikipedia.org/wiki/Moving_average\n--\n-- See https://en.wikipedia.org/wiki/Exponential_smoothing\n--\n{-# INLINE ewma #-}\newma :: Monad m => Double -> Fold m Double Double\newma k = extract <$> Fold.foldl' step (Tuple' 0 1)\n\n    where\n\n    step (Tuple' x0 k1) x = Tuple' (ewmaStep k1 x0 x) k\n\n    extract (Tuple' x _) = x\n\n-- XXX It can perhaps perform better if implemented as a custom fold?\n--\n-- | @ewma n k@ is like 'ewma' but uses the mean of the first @n@ values and\n-- then uses that as the initial value for the @ewma@ of the rest of the\n-- values.\n--\n-- This can be used to reduce the effect of volatility of the initial value\n-- when k is too small.\n--\n{-# INLINE ewmaAfterMean #-}\newmaAfterMean :: Monad m => Int -> Double -> Fold m Double Double\newmaAfterMean n k =\n    Fold.concatMap (\\i -> (Fold.foldl' (ewmaStep k) i)) (Fold.take n Fold.mean)\n\n-- | @ewma n k@ is like 'ewma' but uses 1 as the initial smoothing factor and\n-- then exponentially smooths it to @k@ using @n@ as the smoothing factor.\n--\n-- This is significantly faster than 'ewmaAfterMean'.\n--\n{-# INLINE ewmaRampUpSmoothing #-}\newmaRampUpSmoothing :: Monad m => Double -> Double -> Fold m Double Double\newmaRampUpSmoothing n k1 = extract <$> Fold.foldl' step initial\n\n    where\n\n    initial = Tuple' 0 1\n\n    step (Tuple' x0 k0) x1 =\n        let x = ewmaStep k0 x0 x1\n            k = ewmaStep n k0 k1\n        in Tuple' x k\n\n    extract (Tuple' x _) = x\n\n-------------------------------------------------------------------------------\n-- Spread/Dispersion\n-------------------------------------------------------------------------------\n\n-- | @md n@ computes the mean absolute deviation (or mean deviation) in a\n-- sliding window of last @n@ elements in the stream.\n--\n-- The mean absolute deviation of the numbers \\(x_1, x_2, \\ldots, x_n\\) is:\n--\n-- \\(MD = \\frac{1}{n}\\sum_{i=1}^n |x_i-\\mu|\\)\n--\n-- Note: It is expensive to compute MD in a sliding window. We need to\n-- maintain a ring buffer of last n elements and maintain a running mean, when\n-- the result is extracted we need to compute the difference of all elements\n-- from the mean and get the average. Using standard deviation may be\n-- computationally cheaper.\n--\n-- See https://en.wikipedia.org/wiki/Average_absolute_deviation .\n--\n-- /Pre-release/\n{-# INLINE md #-}\nmd ::  MonadIO m => Fold m ((Double, Maybe Double), m (MA.Array Double)) Double\nmd =\n    Fold.rmapM computeMD\n        $ Fold.tee (Fold.lmap fst mean) (Fold.lmap snd Fold.last)\n\n    where\n\n    computeMD (mn, rng) =\n        case rng of\n            Just action -> do\n                arr <- action\n                Stream.fold Fold.mean\n                    $ Stream.map (\\a -> abs (mn - a))\n                    $ Stream.unfold MA.read arr\n            Nothing -> return 0.0\n\n-- | The variance \\(\\sigma^2\\) of a population of \\(n\\) equally likely values\n-- is defined as the average of the squares of deviations from the mean\n-- \\(\\mu\\). In other words, second moment about the mean:\n--\n-- \\(\\sigma^2 = \\frac{1}{n}\\sum_{i=1}^n {(x_{i}-\\mu)}^2\\)\n--\n-- \\(\\sigma^2 = rawMoment(2) - \\mu^2\\)\n--\n-- \\(\\mu_2 = -(\\mu'_1)^2 + \\mu'_2\\)\n--\n-- Note that the variance would be biased if applied to estimate the population\n-- variance from a sample of the population. See 'sampleVariance'.\n--\n-- See https://en.wikipedia.org/wiki/Variance.\n--\n-- /Space/: \\(\\mathcal{O}(1)\\)\n--\n-- /Time/: \\(\\mathcal{O}(n)\\)\n{-# INLINE variance #-}\nvariance :: (Monad m, Fractional a) => Fold m (a, Maybe a) a\nvariance = Fold.teeWith (\\p2 m -> p2 - m ^ (2 :: Int)) (rawMoment 2) mean\n\n-- | Standard deviation \\(\\sigma\\) is the square root of 'variance'.\n--\n-- This is the population standard deviation or uncorrected sample standard\n-- deviation.\n--\n-- >>> stdDev = sqrt <$> variance\n--\n-- See https://en.wikipedia.org/wiki/Standard_deviation .\n--\n-- /Space/: \\(\\mathcal{O}(1)\\)\n--\n-- /Time/: \\(\\mathcal{O}(n)\\)\n{-# INLINE stdDev #-}\nstdDev :: (Monad m, Floating a) => Fold m (a, Maybe a) a\nstdDev = sqrt <$> variance\n\n-- | Skewness \\(\\gamma\\) is the standardized third central moment defined as:\n--\n-- \\(\\tilde{\\mu}_3 = \\frac{\\mu_3}{\\sigma^3}\\)\n--\n-- The third central moment can be computed in terms of raw moments:\n--\n-- \\(\\mu_3 = 2(\\mu'_1)^3 - 3\\mu'_1\\mu'_2 + \\mu'_3\\)\n--\n-- Substituting \\(\\mu'_1 = \\mu\\), and \\(\\mu'_2 = \\mu^2 + \\sigma^2\\):\n--\n-- \\(\\mu_3 = -\\mu^3 - 3\\mu\\sigma^2 + \\mu'_3\\)\n--\n-- Skewness is a measure of symmetry of the probability distribution. It is 0\n-- for a symmetric distribution, negative for a distribution that is skewed\n-- towards left, positive for a distribution skewed towards right.\n--\n-- For a normal like distribution the median can be found around\n-- \\(\\mu - \\frac{\\gamma\\sigma}{6}\\) and the mode can be found around\n-- \\(\\mu - \\frac{\\gamma \\sigma}{2}\\).\n--\n-- See https://en.wikipedia.org/wiki/Skewness .\n--\n{-# INLINE skewness #-}\nskewness :: (Monad m, Floating a) => Fold m (a, Maybe a) a\nskewness =\n    toFold\n        $ (\\rm3 sd mu ->\n            rm3 / sd ^ (3 :: Int) - 3 * (mu / sd) - (mu / sd) ^ (3 :: Int)\n          )\n        <$> Tee (rawMoment 3)\n        <*> Tee stdDev\n        <*> Tee mean\n\n-- XXX We can compute the 2nd, 3rd, 4th raw moments by repeatedly multiplying\n-- instead of computing the powers every time.\n--\n-- | Kurtosis \\(\\kappa\\) is the standardized fourth central moment, defined as:\n--\n-- \\(\\tilde{\\mu}_4 = \\frac{\\mu_4}{\\sigma^4}\\)\n--\n-- The fourth central moment can be computed in terms of raw moments:\n--\n-- \\(\\mu_4 = -3(\\mu'_1)^4 + 6(\\mu'_1)^2\\mu'_2 - 4\\mu'_1\\mu'_3\\ + \\mu'_4\\)\n--\n-- Substituting \\(\\mu'_1 = \\mu\\), and \\(\\mu'_2 = \\mu^2 + \\sigma^2\\):\n--\n-- \\(\\mu_4 = 3\\mu^4 + 6\\mu^2\\sigma^2 - 4\\mu\\mu'_3 + \\mu'_4\\)\n--\n-- It is always non-negative. It is 0 for a point distribution, low for light\n-- tailed (platykurtic) distributions and high for heavy tailed (leptokurtic)\n-- distributions.\n--\n-- \\(\\kappa >= \\gamma^2 + 1\\)\n--\n-- For a normal distribution \\(\\kappa = 3\\sigma^4\\).\n--\n-- See https://en.wikipedia.org/wiki/Kurtosis .\n--\n{-# INLINE kurtosis #-}\nkurtosis :: (Monad m, Floating a) => Fold m (a, Maybe a) a\nkurtosis =\n    toFold\n        $ (\\rm4 rm3 sd mu ->\n             ( 3 * mu ^ (4 :: Int)\n            + 6 * mu ^ (2 :: Int) * sd ^ (2 :: Int)\n            - 4 * mu * rm3\n            + rm4) / (sd ^ (4 :: Int))\n          )\n        <$> Tee (rawMoment 4)\n        <*> Tee (rawMoment 3)\n        <*> Tee stdDev\n        <*> Tee mean\n\n-------------------------------------------------------------------------------\n-- Estimation\n-------------------------------------------------------------------------------\n\n-- | Unbiased sample variance i.e. the variance of a sample corrected to\n-- better estimate the variance of the population, defined as:\n--\n-- \\(s^2 = \\frac{1}{n - 1}\\sum_{i=1}^n {(x_{i}-\\mu)}^2\\)\n--\n-- \\(s^2 = \\frac{n}{n - 1} \\times \\sigma^2\\).\n--\n-- See https://en.wikipedia.org/wiki/Bessel%27s_correction.\n--\n{-# INLINE sampleVariance #-}\nsampleVariance :: (Monad m, Fractional a) => Fold m (a, Maybe a) a\nsampleVariance = Fold.teeWith (\\n s2 -> n * s2 / (n - 1)) Window.length variance\n\n-- | Sample standard deviation:\n--\n-- \\(s = \\sqrt{sampleVariance}\\)\n--\n-- >>> sampleStdDev = sqrt <$> sampleVariance\n--\n-- See https://en.wikipedia.org/wiki/Unbiased_estimation_of_standard_deviation\n-- .\n--\n{-# INLINE sampleStdDev #-}\nsampleStdDev :: (Monad m, Floating a) => Fold m (a, Maybe a) a\nsampleStdDev = sqrt <$> sampleVariance\n\n-- | Standard error of the sample mean (SEM), defined as:\n--\n-- \\( SEM = \\frac{sampleStdDev}{\\sqrt{n}} \\)\n--\n-- See https://en.wikipedia.org/wiki/Standard_error .\n--\n-- /Space/: \\(\\mathcal{O}(1)\\)\n--\n-- /Time/: \\(\\mathcal{O}(n)\\)\n{-# INLINE stdErrMean #-}\nstdErrMean :: (Monad m, Floating a) => Fold m (a, Maybe a) a\nstdErrMean = Fold.teeWith (\\sd n -> sd / sqrt n) sampleStdDev Window.length\n\n-------------------------------------------------------------------------------\n-- Resampling\n-------------------------------------------------------------------------------\n\n{-# INLINE foldArray #-}\nfoldArray :: Storable a => Fold Identity a b -> Array a -> b\nfoldArray f = runIdentity . Stream.fold f . toStream\n\n-- XXX Is this numerically stable? Should we keep the rounding error in the sum\n-- and take it into account when subtracting?\n--\n-- | Given an array of @n@ items, compute mean of @(n - 1)@ items at a time,\n-- producing a stream of all possible mean values omitting a different item\n-- every time.\n--\n{-# INLINE jackKnifeMean #-}\njackKnifeMean :: (Monad m, Fractional a, Storable a) => Array a -> SerialT m a\njackKnifeMean arr = do\n    let len = fromIntegral (length arr - 1)\n        s = foldArray Fold.sum arr\n     in Stream.map (\\b -> (s - b) / len) $ toStream arr\n\n-- | Given an array of @n@ items, compute variance of @(n - 1)@ items at a time,\n-- producing a stream of all possible variance values omitting a different item\n-- every time.\n--\n{-# INLINE jackKnifeVariance #-}\njackKnifeVariance :: (Monad m, Fractional a, Storable a) =>\n    Array a -> SerialT m a\njackKnifeVariance arr = do\n    let len = fromIntegral $ length arr - 1\n        foldSums (s, s2) x = (s + x, s2 + x ^ (2 :: Int))\n        (sum, sum2) = foldArray (Fold.foldl' foldSums (0.0, 0.0)) arr\n        var x = (sum2 - x ^ (2 :: Int)) / len -  ((sum - x) / len) ^ (2::Int)\n     in Stream.map var $ toStream arr\n\n-- | Standard deviation computed from 'jackKnifeVariance'.\n--\n{-# INLINE jackKnifeStdDev #-}\njackKnifeStdDev :: (Monad m, Storable a, Floating a) =>\n    Array a -> SerialT m a\njackKnifeStdDev = Stream.map sqrt . jackKnifeVariance\n\n-- XXX This can be made more modular if the replicateM unfold can take count\n-- from the seed.\n--\n-- | Randomly select elements from an array, with replacement, producing\n-- a stream of the same size as the original array.\n{-# INLINE resample #-}\nresample :: (MonadIO m, Storable a) => Unfold m (Array a) a\nresample = Unfold step inject\n\n    where\n\n    inject arr = liftIO $ do\n        g <- createSystemRandom\n        return $ (g, arr, length arr, 0)\n\n    chooseOne g arr len = do\n        i <- uniformRM (0, len - 1) g\n        unsafeIndexIO i arr\n\n    step (g, arr, len, idx) = liftIO $ do\n        if idx >= len\n        then return Stop\n        else do\n            e <- chooseOne g arr len\n            return $ Yield e (g, arr, len, idx + 1)\n\n-- | Resample an array multiple times and run the supplied fold on each\n-- resampled stream, producing a stream of fold results. The fold is usually an\n-- estimator fold.\n{-# INLINE foldResamples #-}\nfoldResamples :: (MonadAsync m, Storable a) =>\n       Int          -- ^ Number of resamples to compute.\n    -> Array a      -- ^ Original sample.\n    -> Fold m a b   -- ^ Estimator fold\n    -> SerialT m b\nfoldResamples n arr fld =\n    Stream.replicateM n (Unfold.fold fld resample arr)\n\n-------------------------------------------------------------------------------\n-- Probability Distribution\n-------------------------------------------------------------------------------\n\n-- | Determine the frequency of each element in the stream.\n--\n{-# INLINE frequency #-}\nfrequency :: (Monad m, Ord a) => Fold m a (Map a Int)\nfrequency = Fold.classifyWith id Fold.length\n\n-- | Find out the most frequently ocurring element in the stream and its\n-- frequency.\n--\n{-# INLINE mode #-}\nmode :: (Monad m, Ord a) => Fold m a (Maybe (a, Int))\nmode = Fold.rmapM findMax frequency\n\n    where\n\n    fmax k v Nothing = Just (k, v)\n    fmax k v old@(Just (_, v1))\n        | v > v1 = Just (k, v)\n        | otherwise = old\n\n    findMax = return . foldrWithKey fmax Nothing\n\n-------------------------------------------------------------------------------\n-- Histograms\n-------------------------------------------------------------------------------\n\n-- | @binOffsetSize offset binSize input@. Given an integral input value,\n-- return its bin index provided that each bin contains @binSize@ items and the\n-- bins are aligned such that the 0 index bin starts at @offset@ from 0. If\n-- offset = 0 then the bin with index 0 would have values from 0 to binSize -\n-- 1.\n--\n-- This API does not put a bound on the number of bins, therefore, the number\n-- of bins could be potentially large depending on the range of values.\n--\n{-# INLINE binOffsetSize #-}\nbinOffsetSize :: Integral a => a -> a -> a -> a\nbinOffsetSize offset binSize x = (x - offset) `div` binSize\n\ndata HistBin a = BelowRange | InRange a | AboveRange deriving (Eq, Show)\n\ninstance (Eq a, Ord a) => Ord (HistBin a) where\n    compare BelowRange BelowRange = EQ\n    compare BelowRange (InRange _) = LT\n    compare BelowRange AboveRange = LT\n\n    compare (InRange _) BelowRange = GT\n    compare (InRange x) (InRange y)= x `compare` y\n    compare (InRange _) AboveRange = LT\n\n    compare AboveRange BelowRange = GT\n    compare AboveRange (InRange _) = GT\n    compare AboveRange AboveRange = EQ\n\n-- | @binFromSizeN low binSize nbins input@. Classify @input@ into bins\n-- specified by a @low@ limit, @binSize@ and @nbins@. Inputs below the lower\n-- limit are classified into 'BelowRange' and inputs above the highest bin are\n-- classified into 'AboveRange'. 'InRange' inputs are classified into bins\n-- starting from bin index 0.\n--\n{-# INLINE binFromSizeN #-}\nbinFromSizeN :: Integral a => a -> a -> a -> a -> HistBin a\nbinFromSizeN low binSize nbins x =\n    let high = low + binSize * nbins\n     in if x < low\n        then BelowRange\n        else if x >= high\n             then AboveRange\n             else InRange ((x - low) `div` binSize)\n\n-- | @binFromToN low high nbins input@. Like @binFromSizeN@ except that a range\n-- of lower and higher limit is specified. @binSize@ is computed using the\n-- range and @nbins@. @nbins@ is rounded to the range @0 < nbins < (high - low\n-- + 1)@. @high >= low@ must hold.\n--\n{-# INLINE binFromToN #-}\nbinFromToN :: Integral a => a -> a -> a -> a -> HistBin a\nbinFromToN low high n x =\n    let count = high - low + 1\n        n1 = max n 1\n        n2 = min n1 count\n        binSize = count `div` n2\n        nbins =\n            if binSize * n2 < count\n            then n2 + 1\n            else n2\n     in assert (high >= low) (binFromSizeN low binSize nbins x)\n\n-- Use binary search to find the bin\n--\n-- | Classify an input value to bins using the bin boundaries specified in an\n-- array.\n--\n-- /Unimplemented/\n--\n{-# INLINE binBoundaries #-}\nbinBoundaries :: -- Integral a =>\n    Array.Array a -> a -> HistBin a\nbinBoundaries = undefined\n\n-- | Given a bin classifier function and a stream of values, generate a\n-- histogram map from indices of bins to the number of items in the bin.\n--\n-- >>> Stream.fold (histogram (binOffsetSize 0 3)) $ Stream.fromList [1..15]\n-- fromList [(0,2),(1,3),(2,3),(3,3),(4,3),(5,1)]\n--\n{-# INLINE histogram #-}\nhistogram :: (Monad m, Ord k) => (a -> k) -> Fold m a (Map k Int)\nhistogram bin = Fold.classifyWith bin Fold.length\n", "meta": {"hexsha": "499dccbb84c7488d52fa314c1ae6450a88d98267", "size": 32624, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Streamly/Statistics.hs", "max_stars_repo_name": "composewell/streamly-statistics", "max_stars_repo_head_hexsha": "e190e70e5317416ddc6019be02a99f69c0a434a7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-26T03:25:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T07:47:51.000Z", "max_issues_repo_path": "src/Streamly/Statistics.hs", "max_issues_repo_name": "composewell/streamly-statistics", "max_issues_repo_head_hexsha": "e190e70e5317416ddc6019be02a99f69c0a434a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2021-12-25T02:24:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:42:34.000Z", "max_forks_repo_path": "src/Streamly/Statistics.hs", "max_forks_repo_name": "composewell/streamly-statistics", "max_forks_repo_head_hexsha": "e190e70e5317416ddc6019be02a99f69c0a434a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4948665298, "max_line_length": 131, "alphanum_fraction": 0.6051679745, "num_tokens": 8954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.49583520490646266}}
{"text": "{-# LANGUAGE BangPatterns #-}\nmodule MnistData (loadDataWrapper) where\n\nimport           Codec.Compression.GZip (decompress)\nimport qualified Data.ByteString.Lazy   as BL\nimport qualified Numeric.LinearAlgebra  as H\n\n\nloadDataWrapper :: IO ([(H.Vector H.R, H.Vector H.R)], [(H.Vector H.R, Int)], [(H.Vector H.R, Int)])\nloadDataWrapper = do\n  (_, _, testImage) <- loadImage \"data/t10k-images-idx3-ubyte.gz\"\n  (_, testLabel) <- loadLabel \"data/t10k-labels-idx1-ubyte.gz\"\n  (_, _, trainImage) <- loadImage \"data/train-images-idx3-ubyte.gz\"\n  (_, trainLabel) <- loadLabel \"data/train-labels-idx1-ubyte.gz\"\n  let !testData = zip testImage testLabel\n  let (!trainData', !validateDate) = splitAt 50000 $ zip trainImage trainLabel\n  let trainData = map (\\(a, b)-> (a, labelToVec b)) trainData'\n  return (trainData, validateDate, testData)\n\nlabelToVec :: Int -> H.Vector H.R\nlabelToVec n = H.fromList $ replicate n 0 ++ [1.0] ++ replicate (9-n) 0\n\nloadLabel :: FilePath -> IO (Int, [Int])\nloadLabel fp = do\n  content <- decompress <$> BL.readFile fp\n  let (hd, dat) = BL.splitAt 8 content\n  let (magic, size) = BL.splitAt 4 hd\n  case BL.unpack magic of\n    [0, 0, 8, 1] -> return (readInt size, take (readInt size) (parseData dat))\n    _            -> return (0, [])\n\nloadImage :: FilePath -> IO (Int, (Int, Int), [H.Vector H.R])\nloadImage fp = do\n  content <- decompress <$> BL.readFile fp\n  let (hd, dat) = BL.splitAt 16 content\n  let (magic, tl) = BL.splitAt 4 hd\n  let (size, xy) =  BL.splitAt 4 tl\n  let (rowW, colW) = BL.splitAt 4 xy\n  let (row, col) = (readInt rowW, readInt colW)\n  let images = map (H.fromList . map ((/256.0). fromIntegral)) (every (row * col) $ BL.unpack dat)\n  case BL.unpack magic of\n    [0, 0, 8, 3] -> return (readInt size, (row, col), images)\n    _            -> return (0, (0, 0), images)\n\nparseData :: BL.ByteString -> [Int]\nparseData = map fromIntegral . BL.unpack\n\nreadInt :: Integral a => BL.ByteString -> a\nreadInt bs = foldl (\\a b -> a * 256 + b) 0 $ map fromIntegral $ BL.unpack bs\n\nevery :: Int -> [a] -> [[a]]\nevery n xs = hd : every n tl\n  where\n    (hd, tl) = splitAt n xs\n", "meta": {"hexsha": "6fef579217cc5eddab0d8a44707a3564d6ef39c9", "size": 2108, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MnistData.hs", "max_stars_repo_name": "fujiisat/nnadl-haskell-study", "max_stars_repo_head_hexsha": "81542691a584da4f08ad861568b414dab796230e", "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/MnistData.hs", "max_issues_repo_name": "fujiisat/nnadl-haskell-study", "max_issues_repo_head_hexsha": "81542691a584da4f08ad861568b414dab796230e", "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/MnistData.hs", "max_forks_repo_name": "fujiisat/nnadl-haskell-study", "max_forks_repo_head_hexsha": "81542691a584da4f08ad861568b414dab796230e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3272727273, "max_line_length": 100, "alphanum_fraction": 0.6437381404, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4955121944961517}}
{"text": "module Raytracer.Camera where\n\nimport Numeric.LinearAlgebra.Data (Vector, (|>), toList)\nimport Raytracer.Geometry (Ray(Ray), (|*), intersection)\nimport Numeric.LinearAlgebra (cross)\nimport Data.Array (listArray)\nimport Data.Monoid (mappend)\nimport Data.Tuple (swap)\nimport Data.Ix (range, Ix, index, inRange)\nimport Data.Function (on)\n\n-- This is a camera. It's got a bunch of crap\n-- So, first are settings. They're size of the surface in our units (w h) then resolution of the surface (w h).\n-- Then the next two are the position of the camera, and the vector it's pointing in\n-- The maybe is Focal Distance. If it's Nothing, then we do an orthographic representation\n--   If it's a number, then it's the number of units back that the focal point is.\n-- We assume for now that the camera is always level relative to (1, 0, 1) (No roll)\ndata Camera = Camera Double Double Int Int (Maybe Double) (Vector Double) (Vector Double) deriving Show\n\ndata Point = Point Int Int deriving (Eq, Show)\n\ninstance Ord Point where\n\tcompare (Point a b) (Point c d) = mappend (compare b d) (compare a c)\n\ninstance Ix Point where\n\trange ((Point a b), (Point c d)) = (range (b, d)) >>= (\\y -> (range (a, c)) >>= (\\x -> return $ Point x y))\n\tindex ((Point a b), (Point c d)) (Point e f) = (((c - a) + 1) * (f - b)) + (e - a)\n\tinRange ((Point a b), (Point c d)) (Point e f) = (inRange (a, c) e) && (inRange (b, d) f)\n\nnorm :: Vector Double -> Double\nnorm = sqrt.sum.(map (^2)).toList\n\nunitize :: Vector Double -> Vector Double\nunitize v = (1/(norm v)) |* v\n\n-- This camera is currently orthographic, rather than perspective\ncalculate_ray (Camera width height wres hres focus pos direction) = (\\pos -> Ray (ray_direction pos) pos) . ray_pos\n\twhere\n\t-- This gives me the width axis of my image\n\t-- It is acheived by a cross product of my looking direction and a vertical axis\n\twidth_axis = unitize $ cross (3 |>  [0, 1, 0]) direction\n\t-- This gives me the height axis of my image\n\theight_axis = unitize $ cross direction width_axis\n\t-- This function computes a vector based on progress along a vector\n\tpartial_vector vec steps current_step = (on (/) fromIntegral current_step steps) |* vec\n\t-- This function computes the position of a ray given its place in the matrix\n\tray_pos (Point x y) = (partial_vector (width |* width_axis) wres x) + (partial_vector (height |* height_axis) hres y) + pos + (3 |> [-width / 2, -height/2, 0])\n\t-- This function takes in the point and returns the direction of the ray at that point\n\t-- If it's perspective it involves subtracting from the focal point. If it's orthographic it's just always direction.\n\tray_direction = maybe (const direction) (\\len -> (flip (-)) $ pos - (len |* direction)) focus\n\n-- This function, finally, generates an array of wres and hres full of the proper ray at each point\ncalculate_rays camera = build_array (calculate_ray camera) (Point 1 1, Point wres hres)\n\twhere\n\t(Camera _ _ wres hres _ _ _) = camera\n\t-- This function takes a function expecting (x,y) and bounds and builds an array by calling the function at each point\n\tbuild_array func bounds = listArray bounds $ map func $ range bounds\n\nfire_ray mesh ray = intersection ray mesh\nfire_rays rays mesh = fmap (fire_ray mesh) rays\n", "meta": {"hexsha": "791b419b230a6631523c8b2458c2b90e224a6608", "size": 3225, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Raytracer/Camera.hs", "max_stars_repo_name": "psycotica0/ray-tracer", "max_stars_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Raytracer/Camera.hs", "max_issues_repo_name": "psycotica0/ray-tracer", "max_issues_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Raytracer/Camera.hs", "max_forks_repo_name": "psycotica0/ray-tracer", "max_forks_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.868852459, "max_line_length": 160, "alphanum_fraction": 0.7103875969, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4953867531747}}
{"text": "module Main where\n\nimport Lib\nimport Types\nimport Numeric.Vector\nimport Wavefront.Wavefront\n\ncam :: Camera\ncam = Camera { c_getPos = vec3 3 2 (-5)\n             , c_getForward = vec3 0 0 (1)\n             , c_getUp = vec3 0 1 0\n             , c_getRight = vec3 1 0 0\n             , c_getFOV = 90\n             }\n\ncheckerShader :: BRDF\ncheckerShader = let spacing = VecConst 1 1 1\n                    quarterSpacing = VecMath VDiv spacing (VecConst 4 4 4)\n                    cs = VecMath\n                           VSub\n                           (VecConst 1 1 1)\n                           (VecMath\n                             VMul\n                             (VecConst 2 2 2) \n                             (VecMath\n                               VDiv\n                               (VecMath\n                                 VMod\n                                 (VecMath\n                                   VAdd\n                                   quarterSpacing\n                                   (VecMath VAbs (VecMath VAdd UV quarterSpacing) (VecConst 0 0 0))\n                                 )\n                                 spacing\n                               )\n                               spacing\n                             )\n                           )\n                    lt = ValMath LessThan (ValMath Mul (SeparateX cs) (SeparateY cs)) (ValConst 0)\n                    value = ValMath Add (ValConst 0.7) (ValMath Mul (ValConst 0.3) lt)\n                    color = CombineRGB value value value\n                in Diffuse color\n\nshader :: BRDF\nshader = Diffuse $ ColConst 0.8 0.8 0.8\n\nsun :: Light\nsun = Directional { l_getAngle = 2.5\n                  , l_getStrength = 1\n                  , l_getDirection = normalized $ vec3 0.5 (-1) (-0.4)\n                  , l_getColor = vec3 1 1 1\n                  }\n\nscene :: Scene\nscene = Scene { s_getCamera = cam\n              , s_getObjects = []\n              , s_getLights = [sun]\n              , s_getSkyColor = vec3 0.6 0.7 0.9\n              , s_getWidth = 640\n              , s_getHeight = 480\n              , s_getSeed = 1\n              , s_getSamples = 128\n              , s_getBounces = 2\n              }\n\nmain :: IO ()\nmain = do\n  maybeCube <- readObj \"cube.obj\" <$> readFile \"/home/craig/haskell/raytracer/app/cube.obj\"\n  case maybeCube of\n    Left e -> print e\n    Right cube -> do\n      -- print cube\n      let scene' = scene { s_getObjects = [Object cube shader] }\n      writeImg \"testimg.png\" $ parRender scene'\n", "meta": {"hexsha": "78459761d8f2caf25593d9b224ae1dcb63a8295c", "size": 2489, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "craigmc08/haskell-raytracer", "max_stars_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "craigmc08/haskell-raytracer", "max_issues_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "craigmc08/haskell-raytracer", "max_forks_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1866666667, "max_line_length": 99, "alphanum_fraction": 0.4218561671, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915959134569, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4953091157515127}}
{"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}\n\n{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE ConstraintKinds     #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE KindSignatures      #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell     #-}\n{-# LANGUAGE TypeOperators       #-}\nmodule Test.Grenade.Layers.BatchNorm where\n\nimport           Control.Monad\nimport           Data.List                         (zipWith5)\nimport           Data.Proxy\nimport           GHC.TypeLits\n\nimport           Numeric.LinearAlgebra.Static      (L, R)\nimport qualified Numeric.LinearAlgebra.Static      as H\n\nimport           Hedgehog\n\nimport           Test.Hedgehog.Compat\nimport           Test.Hedgehog.Hmatrix\n\nimport           Grenade.Core\nimport           Grenade.Layers.BatchNormalisation\nimport           Grenade.Utils.LinearAlgebra\nimport           Grenade.Utils.ListStore\n\nbatchnorm :: forall channels rows columns momentum.\n  (KnownNat channels, KnownNat rows, KnownNat columns, KnownNat momentum)\n  => Bool -> R channels -> R channels -> R channels -> R channels -> BatchNorm channels rows columns momentum\nbatchnorm training gamma beta mean var =\n  let \u03b5      = 0.00001\n  in BatchNorm training (BatchNormParams gamma beta) mean var \u03b5 mkListStore\n\nprop_batchnorm_train_behaves_as_reference :: Property\nprop_batchnorm_train_behaves_as_reference = property $ do\n  height   :: Int <- forAll $ choose 2 100\n  width    :: Int <- forAll $ choose 2 100\n  channels :: Int <- forAll $ choose 1 100\n\n  case (someNatVal (fromIntegral height), someNatVal (fromIntegral width), someNatVal (fromIntegral channels), channels) of\n    (Just (SomeNat (Proxy :: Proxy h)), Just (SomeNat (Proxy :: Proxy w)), _, 1) -> do\n      inp :: S ('D2 h w) <- forAll genOfShape\n      guard . not $ elementsEqual inp\n      g :: R 1 <- forAll randomVector\n      b :: R 1 <- forAll randomVector\n      m :: R 1 <- forAll randomVector\n      v :: R 1 <- forAll randomPositiveVector\n\n      let layer   = batchnorm False g b m v :: BatchNorm 1 h w 90\n          S2D out = snd $ runForwards layer inp :: S ('D2 h w)\n          S2D ref = run2DBatchNorm layer inp :: S ('D2 h w)\n      H.extract out === H.extract ref\n\n    (Just (SomeNat (Proxy :: Proxy h)), Just (SomeNat (Proxy :: Proxy w)), Just (SomeNat (Proxy :: Proxy c)), _) -> do\n      inp :: S ('D3 h w c) <- forAll genOfShape\n      g :: R c <- forAll randomVector\n      b :: R c <- forAll randomVector\n      m :: R c <- forAll randomVector\n      v :: R c <- forAll randomPositiveVector\n\n      let layer   = batchnorm False g b m v :: BatchNorm c h w 90\n          S3D out = snd $ runForwards layer inp :: S ('D3 h w c)\n          S3D ref = run3DBatchNorm layer inp    :: S ('D3 h w c)\n      H.extract out === H.extract ref\n\nprop_batchnorm_1D_forward_same_as_torch :: Property\nprop_batchnorm_1D_forward_same_as_torch = withTests 1 $ property $ do\n    let g = H.fromList weight :: R 10\n        b = H.fromList bias   :: R 10\n        m = H.fromList mean   :: R 10\n        v = H.fromList var    :: R 10\n\n        bn = batchnorm False g b m v :: BatchNorm 10 4 4 90\n\n        mat    = H.fromList . concat . concat $ input :: L 40 4\n        x      = S3D mat :: S ('D3 4 4 10)\n        y      = snd $ runForwards bn x :: S ('D3 4 4 10)\n\n        mat' = H.fromList . concat . concat $ ref_out :: L 40 4\n\n    assert $ allClose y (S3D mat')\n  where\n    weight = [ -0.9323,  1.0161,  0.1728,  0.3656, -0.6816,  0.0334,  0.8494, -0.6669, -0.1527, -0.7004 ]\n    bias   = [  0.7582,  1.0068, -0.2532, -1.5240, -1.0370,  0.8442,  0.5867, -1.2567,  0.4283, -0.0001 ]\n    mean   = [ -0.4507,  0.9090, -1.4717,  0.5009,  0.8931, -0.4792,  0.0432,  0.4649, -0.6547, -1.3197 ]\n    var    = [  1.2303,  1.4775,  0.8372,  0.1644,  0.9392,  0.2103,  0.4951,  0.2482,  0.7559,  0.3686 ]\n\n    input  = [ [ [ -0.70681204, -0.20616523, -0.33806887, -1.52378976   ]\n               , [ 0.056113367, -0.51263034, -0.28884589, -2.64030218   ]\n               , [ -1.19894597, -1.16714501, -0.19816216, -1.13361239   ]\n               , [ -0.81997509, -1.05715847,  0.59198695,  0.51939314   ] ]\n             , [ [ -0.18338945, -1.08975303,  0.30558434,  0.85780441   ]\n               , [ -0.47586514,  0.16499641,  2.18205571, -0.11155529   ]\n               , [ 1.090167402,  0.92460924,  0.42982020,  1.30098605   ]\n               , [ 0.286766794, -1.90825951, -0.91737461, -1.11035680   ] ]\n             , [ [ 1.042808533,  0.08287286, -0.92343962, -0.49747768   ]\n               , [ -0.21943949,  0.61554014, -2.25771808, -0.04292159   ]\n               , [ 1.290057424, -1.07323992, -1.00024509,  1.30155622   ]\n               , [ 0.472014425, -0.96431374,  0.77593171, -1.19090688   ] ]\n             , [ [ 0.993361895,  0.82586401, -1.64278686,  1.25544464   ]\n               , [ 0.239656539, -0.81472164,  1.32814168,  0.78350490   ]\n               , [ -0.16597847,  0.74175131, -1.29834091, -1.28858852   ]\n               , [ 1.307537318,  0.55525642, -0.04312540,  0.24699424   ] ]\n             , [ [ 0.391699581, -0.09803850, -0.41061267,  0.34999904   ]\n               , [ -2.22257169,  0.43748092, -1.21343314,  0.39576068   ]\n               , [ 0.003147978, -1.00396716,  1.27623140,  1.17001295   ]\n               , [ -0.58247902, -0.15453417, -0.37016496,  0.04613848   ] ]\n             , [ [ 0.521356827,  0.94643139,  1.11394095,  0.60162323   ]\n               , [ -0.90214585, -0.75316292,  2.20823979, -1.63446676   ]\n               , [ 0.668517357,  0.62832462,  0.31174039, -0.04457542   ]\n               , [ -0.24607617,  0.12855675, -1.62831199, -0.23100854   ] ]\n             , [ [ -0.43619379, -0.41219231,  0.07910434, -0.20312546   ]\n               , [ 1.670419093, -0.26496240, -1.53759109,  1.00907373   ]\n               , [ -1.04028647, -1.37309467, -0.79040497, -0.15661381   ]\n               , [ 0.009049783, -0.05525103,  1.44492578,  0.44786781   ] ]\n             , [ [ 1.431640263, -0.12869687,  1.25025844,  0.07864278   ]\n               , [ -1.69032764, -0.07707843,  0.11284181, -0.00826502   ]\n               , [ -0.92387816, -0.83121442,  0.42292186, -0.49128937   ]\n               , [ -1.62631051,  0.98236626, -1.69256067, -0.66552013   ] ]\n             , [ [ 0.154654814,  0.59295737,  0.48604089,  0.46829459   ]\n               , [ 0.624001921,  2.11190581, -1.80008912,  0.26847255   ]\n               , [ -0.36086676,  0.94211035,  0.19112136, -0.04113261   ]\n               , [ -0.94438538, -0.38932472, -0.29867526,  0.34307864   ] ]\n             , [ [ 1.016388653, -0.41974341, -0.94618958,  0.22629515   ]\n               , [ -2.04437517, -1.14956784,  0.38054388,  0.82105201   ]\n               , [ 0.054255251,  1.03682625,  0.29021424, -0.42736151   ]\n               , [ -0.00021907,  0.98816186,  0.23878140, -0.17728853   ] ] ]\n    \n    ref_out = [ [ [ 0.9734674096107483, 0.5526634454727173, 0.6635311841964722, 1.660154104232788]\n                , [0.3322128653526306, 0.8102537393569946, 0.6221582293510437, 2.5986058712005615]\n                , [1.3871161937713623, 1.360386848449707, 0.5459367036819458, 1.3322019577026367]\n                , [1.068583369255066, 1.267940878868103, -0.11819997429847717, -0.05718337371945381] ]\n              , [ [0.0936361625790596, -0.66402268409729, 0.5023852586746216, 0.9640040397644043]\n                , [-0.15085376799106598, 0.3848632574081421, 2.070988893508911, 0.15368467569351196]\n                , [1.1582437753677368, 1.019848346710205, 0.606238067150116, 1.334473967552185]\n                , [0.4866550862789154, -1.3482388257980347, -0.5199258923530579, -0.6812460422515869] ]\n              , [ [0.22167539596557617, 0.04038754478096962, -0.14965875446796417, -0.06921406835317612]\n                , [-0.016705399379134178, 0.14098398387432098, -0.4016427993774414, 0.016630740836262703]\n                , [0.2683693766593933, -0.17794916033744812, -0.16416378319263458, 0.2705409526824951]\n                , [0.11387854814529419, -0.15737800300121307, 0.1712745875120163, -0.20017105340957642] ]\n              , [ [-1.0799674987792969, -1.230993390083313, -3.456873655319214, -0.8436583876609802]\n                , [-1.7595523595809937, -2.7102415561676025, -0.7781105041503906, -1.2691868543624878]\n                , [-2.1252965927124023, -1.30683434009552, -3.146301031112671, -3.137507677078247]\n                , [-0.7966886162757874, -1.4749890565872192, -2.0145251750946045, -1.7529363632202148] ]\n              , [ [-0.6843588948249817, -0.3399200439453125, -0.1200828030705452, -0.655030369758606]\n                , [1.1542901992797852, -0.7165574431419373, 0.44455069303512573, -0.6872150897979736]\n                , [-0.41108575463294983, 0.29723069071769714, -1.306460976600647, -1.2317562103271484]\n                , [0.0007928922423161566, -0.3001859486103058, -0.14853018522262573, -0.4413214921951294] ]\n              , [ [0.9170715808868408, 0.9480301737785339, 0.9602301120758057, 0.9229174852371216]\n                , [0.8133963942527771, 0.8242470026016235, 1.0399290323257446, 0.760060727596283]\n                , [0.9277894496917725, 0.9248621463775635, 0.9018049836158752, 0.8758541345596313]\n                , [0.8611786365509033, 0.88846355676651, 0.7605089545249939, 0.862276017665863] ]\n              , [ [0.007999604567885399, 0.036973003298044205, 0.6300419569015503, 0.28934815526008606]\n                , [2.5509982109069824, 0.21470165252685547, -1.3215526342391968, 1.7526549100875854]\n                , [-0.7212311029434204, -1.1229807138442993, -0.4195865988731384, 0.34549471735954285]\n                , [0.5454756021499634, 0.4678548276424408, 2.278794050216675, 1.0751949548721313] ]\n              , [ [-2.550779104232788, -0.4621109068393707, -2.307981491088867, -0.7396559119224548]\n                , [1.628288984298706, -0.5312073826789856, -0.7854347229003906, -0.6233210563659668]\n                , [0.6023192405700684, 0.4782795310020447, -1.2005081176757812, 0.023255640640854836]\n                , [1.542595624923706, -1.9493807554244995, 1.631278157234192, 0.2564810514450073] ]\n              , [ [0.28615128993988037, 0.20917125046253204, 0.22794923186302185, 0.2310660481452942]\n                , [0.20371884107589722, -0.05760492384433746, 0.6294671297073364, 0.2661612331867218]\n                , [0.3766934275627136, 0.14784877002239227, 0.2797465920448303, 0.32053783535957336]\n                , [0.4791780710220337, 0.381691575050354, 0.3657706081867218, 0.25305798649787903] ]\n              , [ [-2.6950571537017822, -1.0383073091506958, -0.4309888482093811, -1.7835899591445923]\n                , [0.8358993530273438, -0.19636774063110352, -1.9615343809127808, -2.469712972640991]\n                , [-1.5851213932037354, -2.7186343669891357, -1.8573282957077026, -1.029518961906433]\n                , [-1.5222787857055664, -2.66249418258667, -1.7979943752288818, -1.3180080652236938] ] ]\n\n\ntests :: IO Bool\ntests = checkParallel $$(discover)\n\n\n-- REFERENCE FUNCTIONS\n\nrun2DBatchNorm :: forall h w m.\n                  (KnownNat h, KnownNat w, KnownNat m)\n               => BatchNorm 1 h w m -> S ('D2 h w) ->  S ('D2 h w)\nrun2DBatchNorm (BatchNorm False (BatchNormParams gamma beta) runningMean runningVar \u03b5 _) (S2D x)\n  = let [m]    = vectorToList runningMean\n        [v]    = vectorToList runningVar\n        [g]    = vectorToList gamma\n        [b]    = vectorToList beta\n        std    = sqrt $ v + \u03b5\n        x_norm = H.dmmap (\\a -> (a - m) / std) x\n        out    = H.dmmap (\\a -> g * a + b) x_norm\n    in S2D out\n\nrun3DBatchNorm :: forall h w m c.\n                  (KnownNat h, KnownNat w, KnownNat m, KnownNat c)\n               => BatchNorm c h w m -> S ('D3 h w c) ->  S ('D3 h w c)\nrun3DBatchNorm (BatchNorm False (BatchNormParams gamma beta) runningMean runningVar \u03b5 _) inp\n  = let ms     = vectorToList runningMean\n        vs     = vectorToList runningVar\n        gs     = vectorToList gamma\n        bs     = vectorToList beta\n\n        cs     = splitChannels inp :: [S ('D2 h w)]\n\n        f c g b m v = let gs' = listToVector [g] :: R 1\n                          bs' = listToVector [b] :: R 1\n                          ms' = listToVector [m] :: R 1\n                          vs' = listToVector [v] :: R 1\n                          bn' = BatchNorm False (BatchNormParams gs' bs') ms' vs' \u03b5 undefined :: BatchNorm 1 h w m\n                      in  run2DBatchNorm bn' c\n      in combineChannels $ zipWith5 f cs gs bs ms vs\n", "meta": {"hexsha": "99f1bbaafa0665529e9a4f7b4480f383dcbe944d", "size": 12533, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Layers/BatchNorm.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "test/Test/Grenade/Layers/BatchNorm.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Test/Grenade/Layers/BatchNorm.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.5654205607, "max_line_length": 123, "alphanum_fraction": 0.5906806032, "num_tokens": 4738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4952427946821758}}
{"text": "{-# LANGUAGE Arrows #-}\n\n-- | Compute the value of pi by generating random number. Using o Storable vector thanks to Dunai MSF that can handle IO.\nmodule Main where\n\nimport Data.Bool (bool)\nimport Data.Complex\nimport Data.Vector.Storable.Mutable\nimport Data.Word\nimport Dunai.Gloss\nimport Prelude hiding (read, replicate)\n\nmain :: IO ()\nmain = do\n  bitmap <- replicate (s * s * 4) 255\n  field <- generate (s * s) init\n  field2 <- replicate (s * s) 0\n  playDunaiIO (InWindow \"Random Pi\" (s, s) (100, 100)) white 30 (network field field2 bitmap)\n  where\n    init :: Int -> Complex Double\n    init i =\n      let x' = mod i s\n          x = fromIntegral x' * dx\n          y' = div i s\n          y = fromIntegral y' * dx\n          x0 = l / 5\n          y0 = l / 2\n          kx = l\n          ky = 0\n          r = l / 20\n       in mkPolar (exp (- ((x - x0) ^ 2 + (y - y0) ^ 2) / r)) (kx * x + ky * y)\n\ns :: Int\ns = 200\n\nl, dx, dt :: Double\nl = 10\ndx = l / fromIntegral s\ndt = 3e-3\n\nii :: Complex Double\nii = 0 :+ 1\n\ntoRGBA ptr = bitmapOfForeignPtr s s (BitmapFormat TopToBottom PxRGBA) ptr False\n\nnetwork field field2 bitmap = proc (upd, _) -> do\n  if upd > 0\n    then do\n      i <- count -< ()\n      let (cur, nex) = if odd i then (field, field2) else (field2, field)\n      arrM (uncurry update) -< (cur, nex)\n      arrM (`render` bitmap) -< nex\n    else returnA -< ()\n  returnA -< img\n  where\n    img = toRGBA . fst $ unsafeToForeignPtr0 bitmap\n\nupdate field nfield = go 0\n  where\n    dir x y\n      | x < 0 = dir 0 y\n      | x >= s = dir (s -1) y\n      | y < 0 = dir x 0\n      | y >= s = dir x (s -1)\n      | otherwise = x + s * y\n    go i\n      | i >= s * s = return ()\n      | otherwise = do\n        let x = mod i s\n            y = div i s\n        c <- read field i\n        cu <- read field (dir x (y -1))\n        cd <- read field (dir x (y + 1))\n        cl <- read field (dir (x -1) y)\n        cr <- read field (dir (x + 1) y)\n        let v = c + (dt :+ 0) * hv x y c cu cd cl cr\n        write nfield i v\n        go (i + 1)\n\nhv :: Int -> Int -> Complex Double -> Complex Double -> Complex Double -> Complex Double -> Complex Double -> Complex Double\nhv x y c cu cd cl cr = - ii * (- a * (cu + cd + cl + cr -4 * c))\n  where\n    a = 1 / dx * dx :+ 0\n\nrender field bitmap = go 0\n  where\n    go i\n      | i >= s * s = return ()\n      | otherwise = do\n        c <- read field i\n        let (re :+ im) = 255 * (c + (1.5 :+ 1.5)) / 3\n            r = floor re\n            g = 0\n            b = floor im\n        write bitmap (i * 4) r\n        write bitmap (i * 4 + 1) g\n        write bitmap (i * 4 + 2) b\n        go (i + 1)\n", "meta": {"hexsha": "c412ab9f8e0808619836b1aaf8f7215b561f74c4", "size": 2611, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/quantum/Quantum.hs", "max_stars_repo_name": "xayon40-12/dunai-gloss", "max_stars_repo_head_hexsha": "4d7dac1a21b5315afe87664dd51abab479d71d51", "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": "examples/quantum/Quantum.hs", "max_issues_repo_name": "xayon40-12/dunai-gloss", "max_issues_repo_head_hexsha": "4d7dac1a21b5315afe87664dd51abab479d71d51", "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/quantum/Quantum.hs", "max_forks_repo_name": "xayon40-12/dunai-gloss", "max_forks_repo_head_hexsha": "4d7dac1a21b5315afe87664dd51abab479d71d51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3737373737, "max_line_length": 124, "alphanum_fraction": 0.509766373, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49451021102258585}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE Arrows, FlexibleContexts #-}\n\nmodule Examples.SingleTargetTracking where\n\nimport Control.Arrow (returnA)\nimport Control.Monad.Trans (liftIO, lift)\nimport Control.Monad.Bayes.Class (MonadSample)\nimport Control.Monad.Bayes.Sampler (SamplerIO, sampleIO)\n\nimport Data.Aeson (encode)\nimport Data.Maybe (fromJust)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (putStrLn)\n\nimport Numeric.LinearAlgebra.Static\n\nimport Inference (zdsparticles, zunheap, zparticles)\nimport DelayedSampling (DelayedInfer, Result (..))\nimport qualified SymbolicDistr as DS (sample, mvNormal)\nimport DSProg (DeepForce (..), Expr' (..), Expr, marginal, zdeepForce, deepForce', zdeepForce')\nimport Util.ZStream (ZStream)\nimport qualified Util.ZStream as ZS\nimport Util.Ref (MonadState, Heap)\n\nimport qualified Metaprob as MP\n\nmodel :: MonadState Heap m => MonadSample m => Bool -> ZStream (MP.Gen m) () (Expr (R 6), Expr (R 3))\nmodel delay = ZS.fromStep step initPosVel\n  where\n  initPosVel :: Expr (R 6)\n  initPosVel = Const (konst 0 :: R 6)\n  step posvel () = do\n    posvel' <- lift (force (DS.sample (DS.mvNormal (MVMul (Const motionMatrix) posvel) motionCov)))\n    observation <- \"obs\" MP.~~ (MP.dsPrim (DS.mvNormal (MVMul (Const posFromPosVel) posvel') (10 * sym eye)))\n    return (posvel', (posvel', observation))\n\n  force = if delay then id else (>>= deepForce')\n  -- Constants\n  posCov = 0.01 * sym eye\n  velCov = 0.1 * sym eye\n  tdiff = 1\n  motionCov :: Sym 6\n  motionCov =\n    sym $ konst tdiff * ((unSym posCov ||| (konst 0 :: Sq 3))\n          ===\n          ((konst 0 :: Sq 3) ||| unSym velCov))\n  motionMatrix :: Sq 6\n  motionMatrix =\n      ((eye :: Sq 3) ||| (konst tdiff * eye :: Sq 3))\n                    ===\n      ((konst 0 :: Sq 3) ||| (eye :: Sq 3))\n  posFromPosVel :: L 3 6\n  posFromPosVel = (eye :: Sq 3) ||| (konst 0 :: Sq 3)\n\nprocessObservationStream :: DelayedInfer m => Bool -> ZStream m (R 3) (Result (R 6))\nprocessObservationStream delay = proc observations -> do\n  (posvel, _) <- MP.zobserving (model delay) -< ((), \"obs\" MP.|-> MP.obs observations)\n  ZS.run -< fromJust <$> marginal posvel\n\nrunInference :: Bool -> Int -> ZStream SamplerIO () (R 6, [Result (R 6)], R 3)\nrunInference delay numParticles = proc () -> do\n  (groundTruth, obs) <- simulate (model True) -< ()\n  particles <- zdsparticles numParticles (processObservationStream delay) -< obs\n  returnA -< (groundTruth, particles, obs)\n\nrunExample :: Bool -> Int -> IO ()\nrunExample delay n = sampleIO $ ZS.runStream (liftIO . BS.putStrLn . encode . f) (runInference delay n)\n  where f (gt, particles, obs) = ([(0 :: Int, gt)], map (\\x -> [(0 :: Int, x)]) particles, [obs])\n\nsimulate = zdeepForce . ZS.liftM MP.sim", "meta": {"hexsha": "db7f1a0471dc5dc99409ba05f94ed6243f619f27", "size": 2714, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/src/Examples/SingleTargetTracking.hs", "max_stars_repo_name": "psg-mit/probzelus-haskell", "max_stars_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-26T13:13:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T19:11:41.000Z", "max_issues_repo_path": "haskell/src/Examples/SingleTargetTracking.hs", "max_issues_repo_name": "psg-mit/probzelus-haskell", "max_issues_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "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": "haskell/src/Examples/SingleTargetTracking.hs", "max_forks_repo_name": "psg-mit/probzelus-haskell", "max_forks_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2253521127, "max_line_length": 109, "alphanum_fraction": 0.6639646279, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4944828802377565}}
{"text": "{-# LANGUAGE UnicodeSyntax, DataKinds, TypeOperators, KindSignatures,\n             TypeInType, GADTs, MultiParamTypeClasses, FunctionalDependencies,\n             TypeFamilies, AllowAmbiguousTypes, FlexibleInstances,\n             UndecidableInstances, InstanceSigs, TypeApplications, \n             ScopedTypeVariables, EmptyCase, FlexibleContexts, \n             RankNTypes, LambdaCase\n#-}\n\n-- Implementation of density matrix interpretation of quantum computation\nmodule LinTrans2 where\n\nimport Prelim\n\nimport qualified Data.Complex as C \nimport Data.Complex (Complex(..))\nimport Control.Monad.State.Lazy\nimport Data.Singletons\nimport Data.Maybe (fromJust)\n--import Data.Tuple hiding (swap)\nimport Unsafe.Coerce\nimport Data.Constraint (Dict(..))\nimport Data.List ( (\\\\) )\nimport qualified Debug.Trace as Tr\n\n\n-- I don't like the show instance for \u2102\nnewtype \u2102 = \u2102 (Complex Double)\n\nliftC :: (Complex Double -> Complex Double) -> \u2102 -> \u2102\nliftC f (\u2102 c) = \u2102 $ f c\n\ni :: \u2102\ni = \u2102 $ 0 :+ 1\nconjugate = liftC C.conjugate\ninstance Num \u2102 where\n  \u2102 m + \u2102 n = \u2102 $ m + n\n  \u2102 m - \u2102 n = \u2102 $ m - n\n  \u2102 m * \u2102 n = \u2102 $ m * n\n  abs = liftC abs\n  signum = liftC signum\n  fromInteger = \u2102 . fromInteger \ninstance Fractional \u2102 where\n  fromRational = \u2102 . fromRational\n  \u2102 m / \u2102 n    = \u2102 $ m / n\ninstance Floating \u2102 where\n  pi    = \u2102 $ pi\n  exp   = liftC exp\n  log   = liftC log\n  sin   = liftC sin\n  cos   = liftC cos\n  asin  = liftC asin\n  acos  = liftC acos\n  atan  = liftC atan\n  sinh  = liftC sinh\n  cosh  = liftC cosh\n  asinh = liftC asinh\n  acosh = liftC acosh\n  atanh = liftC atanh\ninstance Show \u2102 where\n  show (\u2102 (\u03b1 :+ \u03b2)) =   if \u03b2 == 0 then show \u03b1 \n                        else if \u03b1 == 0 then show \u03b2 ++ \"i\"\n                        else show \u03b1 ++ \" + \" ++ show \u03b2 ++ \"i\"\n\n\n--------------\n-- Matrices --\n--------------\n\n-- A matrix Matrix (m,n) f of dimension 2^m \u00d7 2^n is a function f from pairs of\n-- nats to \u2102\ndata Matrix = Matrix { dim :: (Int,Int)\n                     , idx :: (Int, Int) -> \u2102\n                     }\ndom :: Matrix -> [Int]\ndom (Matrix (m,_) _) = [0..(2^m)-1]\n\ncod :: Matrix -> [Int]\ncod (Matrix (_,n) _) = [0..(2^n)-1]\n\nmkMatrix :: (Int,Int) -> [[\u2102]] -> Matrix\nmkMatrix (m,n) ls = Matrix (m,n) $ \\(i,j) -> (ls !! i) !! j\n\n--------------\n-- Printing --\n--------------\n\nrows :: Matrix -> [[\u2102]]\nrows mat = f <$> dom mat\n  where\n    f i = (\\j -> idx mat (i,j)) <$> cod mat\nshowRows :: Matrix -> [String]\nshowRows mat = show <$> rows mat\ninstance Show Matrix where\n  show mat = unlines $ showRows mat\n\n\n---------------------------------------\n-- Primitive matrices and operations --\n---------------------------------------\n\nident :: Int -> Matrix\nident n = Matrix (n,n) $ \\(i,j) -> if i == j then 1 else 0\n\ntranspose :: Matrix -> Matrix\ntranspose (Matrix (m,n) f) = Matrix (n,m) $ \\(i,j) -> f (j,i)\n\ndot :: Matrix -> Matrix -> \u2102\ndot v1 v2 | snd (dim v1) == fst (dim v2) =\n            foldl (+) 0 $ (\\x -> idx v1 (0,x) * idx v2 (x,0)) <$> dom v2\n          | otherwise = error \"Mismatched dimensions when taking dot product\"\n\nrow :: Int -> Matrix -> Matrix\nrow i (Matrix (_,n) f) = Matrix (0,n) $ \\(_,j) -> f(i,j)\n\ncol :: Int -> Matrix -> Matrix\ncol j (Matrix (m,_) f) = Matrix (m,0) $ \\(i,_) -> f(i,j)\n\nplusM :: Matrix -> Matrix -> Matrix\nplusM (Matrix dim1 f1) (Matrix dim2 f2) | dim1 == dim2 = \n       Matrix dim1 $ \\(i,j) -> f1(i,j) + f2(i,j)\nplusM _ _ | otherwise    = error \"Mismatched dimensions when adding matrices\"\n\nmultM :: Matrix -> Matrix -> Matrix\nmultM mat1 mat2 | n1 == m2 = \n    Matrix (m1,n2) $ \\(i,j) -> dot (row i mat1) (col j mat2)\n  where\n    (m1,n1) = dim mat1\n    (m2,n2) = dim mat2\nmultM _ _ | otherwise = error \"Mismatched dimensions when multiplying matrices\"\n\nkron :: Matrix -> Matrix -> Matrix\nkron (Matrix (m1,n1) f1) (Matrix (m2,n2) f2) =\n    Matrix (m1*n1, m2*n2) $ \\(i,j) -> \n           f1 (i `div` 2^m2, j `div` 2^n2) * f2 (i `mod` 2^m2, j `mod` 2^n2)\n\nzero n = Matrix (n,n) $ \\_ -> 0\n\nscale :: \u2102 -> Matrix -> Matrix\nscale c (Matrix (m,n) f) = Matrix (m,n) $ \\(i,j) -> c * f(i,j)\n\n\n----------------------\n-- Quantum Matrices --\n----------------------\n\nket0 = mkMatrix (1,0) [[1],[0]]\nket1 = mkMatrix (1,0) [[0],[1]]\ndensity0 = ket0 * transpose ket0\ndensity1 = ket1 * transpose ket1\nnewD True  = density1\nnewD False = density0\n\nhadamard = mkMatrix (1,1) [[1/sqrt 2, 1/sqrt 2]\n                          ,[1/sqrt 2, -1/sqrt 2]]\n\npauliX = mkMatrix (1,1) [[0,1]\n                       ,[1,0]]\npauliY = mkMatrix (1,1) [[0,-1]\n                       ,[i,0]]\npauliZ = mkMatrix (1,1) [[1,0]\n                       ,[0,-1]]\n\ncnot = mkMatrix (2,2) [[1,0,0,0]\n                      ,[0,1,0,0]\n                      ,[0,0,0,1]\n                      ,[0,0,1,0]]\n\n\n\n\n\n------------------\n-- Permutations --\n------------------\n\n-- encode and decode modulo a key k\nencode :: Int -> [Int] -> Int\nencode k [] = 0\nencode k (i : ls) = i + k * encode k ls\n\ndecode :: Int -> Int -> [Int]\ndecode k i | i == 0 = []\ndecode k i | otherwise = i `mod` k : decode k (i `div` k)\n\nfromAssocList :: [(Int,Int)] -> Int -> Int\nfromAssocList []           = id\nfromAssocList ((a,b) : ls) = assocFun a b . fromAssocList ls\n  where\n    assocFun a b i = if i == a then b else i\n\n-- Check if two lists are equal up to the permutation specified, i.e.\n-- if permuting ls1 by f is equal to ls2\nisPermutation :: Eq a => (Int -> Int) -> [a] -> [a] -> Bool\nisPermutation f ls1 ls2 = all (\\i -> ls1 !! i == ls2 !! f i) [0..len]\n  where\n    len = length ls1\n    \n\nswapFun :: Int -> (Int -> Int) -> Matrix\nswapFun k f = Matrix (k,k) $ \\(i,j) -> \n    if isPermutation f (decode k i) (decode k j) then 1 else 0\n\n-- swap takes a list of qubit/bit variables and produces a matrix that permutes\n-- those qubits.\n-- i.e. swap ls |\u03c6_0 \u22ef \u03c6_n\u27e9 = |\u03c6_f(0) \u22ef \u03c1_f(n)\u27e9 \n-- where f = fromAssocList ls\nswap :: Int -> [Int] -> Matrix\nswap k ls = swapFun k $ fromAssocList $ zip [0..] ls\n\n\n\n-------------------\n-- Density Monad --\n-------------------\n\n-- A density monad is a nondeterminism state monad:\n-- Density -> [Density]\n-- An element op of type DensityMonad corresponds to the superoperator\n-- \\\u03c1 -> \u2211 (op \u03c1)\ntype DensityMonad = StateT Matrix []\n\nnewM :: Bool -> DensityMonad Int\nnewM b = do\n    \u03c1 \u2190 get\n    put $ \u03c1 `kron` newD b\n    return $ fst (dim \u03c1)\n\n-- runQ applies the superoperator to the identity density matrix of size 1.\nrunQ :: DensityMonad a -> [(a,Matrix)]\nrunQ m = runStateT m (ident 0)\n\n-- getDensity combines the result of runQ into a single density matrix\ngetDensity :: DensityMonad a -> Matrix\ngetDensity m = foldr f (zero n) ls\n  where\n    ls = runQ m\n    n = fst . dim . snd $ head ls\n    f (_,\u03c1) \u03c10 = \u03c1 + \u03c10\n\n\n\n-----------------\n-- Application --\n-----------------\n\n\nsuper :: Matrix -> DensityMonad ()\nsuper mat = do \u03c1 \u2190 get\n               put $ mat * \u03c1 * transpose mat\n\napplyMatrix :: Matrix -> [Int] -> DensityMonad ()\napplyMatrix mat ls = do super $ swap n ls  -- moves the relevant qubits to the front\n                        super mat -- applies operation\n                        super . transpose $ swap n ls -- moves the qubits back to where they were\n  where\n    (n,_) = dim mat\n\nbranch :: DensityMonad a -> DensityMonad a -> DensityMonad a\nbranch m0 m1 = StateT $ \\\u03c1 -> [runStateT m0 \u03c1, runStateT m1 \u03c1] >>= id\n\nmeasM :: Int -> DensityMonad Bool\nmeasM i = branch (applyMatrix density0 [i] >> return False) (applyMatrix density1 [i] >> return True)\n\n\n------------------\n-- Num instance --\n------------------\n\ninstance Num Matrix where\n  (+) = plusM\n  mat1 - mat2 = mat1 `plusM` scale (-1) mat2\n  (*) = multM\n  abs = undefined\n  signum mat = undefined -- trace?\n  fromInteger n = ident $ fromInteger n\n\n-------------------\n-- Show Instance --\n-------------------\n\ninstance Show (DensityMonad a) where\n  show = show . getDensity\n\n{-\n\n\n------------------\n-- Num instance --\n------------------\n\ninstance (SingI m, SingI n) => Num (Matrix m n) where\n  (+) mat1 mat2 (i,j) = mat1(i,j) + mat2(i,j)\n  (-) mat1 mat2 (i,j) = mat1(i,j) - mat2(i,j)\n  (*) mat1 mat2 (i,j) = mat1(i,j) * mat2(i,j)\n  abs mat (i,j) = abs $ mat(i,j)\n  signum mat = undefined -- trace mat\n  fromInteger n = matrix . repeat $ fromIntegral n\ninstance Num Density where\n  Density n1 mat1 + Density n2 mat2 = \n    withSingI (two `raiseToSNat` n1) $\n    withSingI (two `raiseToSNat` n2) $\n    case eqSNat n1 n2 of \n      Left Dict -> Density n1 $ mat1 + mat2\n      Right _   -> error $ \"Cannot add mismatched matrices \" \n                            ++ show mat1 ++ \" and \" ++ show mat2\n  _ - _ = undefined\n  _ * _ = undefined\n  abs _ = undefined\n  signum = undefined\n  fromInteger n = undefined\n\n\n\n\n-- Debugging help\nm0 = square @Two [1,0,0,0\n                 ,0,1,0,0\n                 ,0,0,0,1\n                 ,0,0,1,0]\nrho = Density three $ \\case\n  (0,0) -> -0.5\n  (0,2) ->  0.5\n  (3,0) -> -0.5\n  (3,2) ->  0.5\n  (_,_) -> 0\n\n\n\n-}\n", "meta": {"hexsha": "d8a2c0c4ba7111d4f278daf5bdd9a110159bb200", "size": 8789, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/examples/LinTrans2.hs", "max_stars_repo_name": "jpaykin/LNLHaskell", "max_stars_repo_head_hexsha": "7c3e3880d2702b5456326870ba4863f27a8606b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2016-10-23T18:46:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T06:00:45.000Z", "max_issues_repo_path": "src/examples/LinTrans2.hs", "max_issues_repo_name": "jpaykin/LNLHaskell", "max_issues_repo_head_hexsha": "7c3e3880d2702b5456326870ba4863f27a8606b4", "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/examples/LinTrans2.hs", "max_forks_repo_name": "jpaykin/LNLHaskell", "max_forks_repo_head_hexsha": "7c3e3880d2702b5456326870ba4863f27a8606b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-29T12:57:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-29T14:22:00.000Z", "avg_line_length": 26.6333333333, "max_line_length": 101, "alphanum_fraction": 0.5500056889, "num_tokens": 2841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.49423564996338337}}
{"text": "{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE RankNTypes          #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Pendulum.Model (\n  Pendulum(..),\n  mkPendlumSystem,\n  stepPendulum\n  ) where\n\nimport qualified Data.Vector.Sized as V\nimport           GHC.TypeLits (KnownNat)\nimport           Numeric.Hamilton\nimport           Numeric.LinearAlgebra.Static\n\ndata Pendulum n = Pendulum\n  { _lengthes :: V.Vector n Double\n  , _masses   :: V.Vector n Double\n  , _config   :: Config n\n  }\n\ngravity :: Floating a => a\ngravity = 9.8\n\ntoFloating :: Floating a => Double -> a\ntoFloating = fromRational . toRational\n\nduplicate :: [a] -> [a]\nduplicate = concatMap (\\x -> [x, x])\n\nmerge :: [a] -> [a] -> [a]\nmerge []     ys     = ys\nmerge xs     []     = xs\nmerge (x:xs) (y:ys) = x : y : merge xs ys\n\nevenElems :: [a] -> [a]\nevenElems []       = []\nevenElems (_:[])   = []\nevenElems (_:x:xs) = x : evenElems xs\n\ntoVector :: forall a m. KnownNat m => [a] -> V.Vector m a\ntoVector = (\\(Just x) -> x) . V.fromList\n\nmkPendlumSystem :: forall m n. (KnownNat m, KnownNat n) => Pendulum n -> System m n\nmkPendlumSystem p =\n  let lengthes = V.toList (_lengthes p)\n      masses   = V.toList (_masses p)\n      masses' :: R m\n      masses' = vector (duplicate masses)\n      coordinates :: Floating a => V.Vector n a -> V.Vector m a\n      coordinates v =\n        let ths = V.toList v\n            ls = map toFloating lengthes\n            xs =                scanl1 (+) (zipWith (*) ls (map sin ths))\n            ys = (* (-1.0)) <$> scanl1 (+) (zipWith (*) ls (map cos ths))\n         in toVector (merge xs ys)\n      potential :: Floating a => V.Vector m a -> a\n      potential v =\n        let ys = evenElems (V.toList v)\n            ms = map toFloating masses\n         in gravity * foldl1 (+) (zipWith (*) ms ys)\n   in mkSystem' masses' coordinates potential\n\nstepPendulum :: forall m n. (KnownNat m, KnownNat n) => Double -> System m n -> Pendulum n -> Pendulum n\nstepPendulum dt system pd =\n  let phase  = toPhase system (_config pd)\n      phase' = stepHam dt system phase\n   in pd {_config = fromPhase system phase'}\n\n", "meta": {"hexsha": "bf93e320696113eecf50d1a42b4ab4a75d12b1fc", "size": 2097, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Pendulum/Model.hs", "max_stars_repo_name": "lotz84/hamilton-gloss-multi-pendulum", "max_stars_repo_head_hexsha": "779b7f524772b367b45abca531664b8ac4ca4cec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-05-29T16:13:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-20T02:46:26.000Z", "max_issues_repo_path": "src/Pendulum/Model.hs", "max_issues_repo_name": "lotz84/hamilton-gloss-multi-pendulum", "max_issues_repo_head_hexsha": "779b7f524772b367b45abca531664b8ac4ca4cec", "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/Pendulum/Model.hs", "max_forks_repo_name": "lotz84/hamilton-gloss-multi-pendulum", "max_forks_repo_head_hexsha": "779b7f524772b367b45abca531664b8ac4ca4cec", "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.9571428571, "max_line_length": 104, "alphanum_fraction": 0.5851216023, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49390236053832887}}
{"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Statistics.Distribution.Random.Normal (normal) where\n\nimport Control.Monad\nimport Data.Bits\nimport Data.Word\nimport qualified Data.Vector.Unboxed as I\nimport Random.CRI\nimport Statistics.Distribution.Random.Uniform\n\n-- Copied from mwc-random.\n\ndata T = T {-# UNPACK #-} !Double {-# UNPACK #-} !Double\n\n-- | Generate a normally distributed random variate.\n--\n-- The implementation uses Doornik's modified ziggurat algorithm.\n-- Compared to the ziggurat algorithm usually used, this is slower,\n-- but generates more independent variates that pass stringent tests\n-- of randomness.\nnormal :: (Source m g Double, Source m g Word32) => g m -> m Double\nnormal gen = loop\n  where\n    loop = do\n      u  <- (subtract 1 . (*2)) `liftM` uniform gen\n      ri <- uniform gen\n      let i  = fromIntegral ((ri :: Word32) .&. 127)\n          bi = I.unsafeIndex blocks i\n          bj = I.unsafeIndex blocks (i+1)\n      if abs u < I.unsafeIndex ratios i\n        then return $! u * bi\n        else if i == 0\n        then normalTail (u < 0)\n        else do\n          let x  = u * bi\n              xx = x * x\n              d  = exp (-0.5 * (bi * bi - xx))\n              e  = exp (-0.5 * (bj * bj - xx))\n          c <- uniform gen\n          if e + c * (d - e) < 1\n            then return x\n            else loop\n    blocks = let f = exp (-0.5 * r * r)\n             in (`I.snoc` 0) . I.cons (v/f) . I.cons r .\n                I.unfoldrN 126 go $! T r f\n      where\n        go (T b g)   = let !u = T h (exp (-0.5 * h * h))\n                           h  = sqrt (-2 * log (v / b + g))\n                       in Just (h, u)\n        v            = 9.91256303526217e-3\n    {-# NOINLINE blocks #-}\n    r                = 3.442619855899\n    ratios           = I.zipWith (/) (I.tail blocks) blocks\n    {-# NOINLINE ratios #-}\n    normalTail neg  = tailing\n      where tailing  = do\n              x <- ((/r) . log) `liftM` uniform gen\n              y <- log          `liftM` uniform gen\n              if y * (-2) < x * x\n                then tailing\n                else return $! if neg then x - r else r - x\n{-# INLINE normal #-}\n\n\n", "meta": {"hexsha": "990be42dd97594cbee661bd252429c825aaa5ef0", "size": 2202, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Random/Normal.hs", "max_stars_repo_name": "finlay/random-dist", "max_stars_repo_head_hexsha": "26a12396c61762565ef12c47313d5ab71302af62", "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": "Statistics/Distribution/Random/Normal.hs", "max_issues_repo_name": "finlay/random-dist", "max_issues_repo_head_hexsha": "26a12396c61762565ef12c47313d5ab71302af62", "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": "Statistics/Distribution/Random/Normal.hs", "max_forks_repo_name": "finlay/random-dist", "max_forks_repo_head_hexsha": "26a12396c61762565ef12c47313d5ab71302af62", "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.8656716418, "max_line_length": 68, "alphanum_fraction": 0.5227066303, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4938836594682285}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport qualified Statistics.Distribution as Stat\nimport qualified Statistics.Distribution.Normal as Stat\nimport qualified Statistics.Distribution.Uniform as Stat\nimport Control.Monad.Primitive\nimport qualified System.Random.MWC as Rand\nimport Control.Monad.State.Strict\nimport Control.Monad.Reader\nimport Lens.Micro\nimport Types\nimport qualified Data.List as List\nimport Options.Generic\n\n-- Contraints that allow for random number generation\ntype BanditM m = (MonadIO m, MonadReader (Rand.Gen (PrimState IO)) m)\n\n-- |Generate a list of random bandits using dist to generate their parameters.\nrandomBandits ::\n  (BanditM m, Stat.ContGen d1, Stat.ContGen d2)\n  => Int\n  -> d1\n  -> d2\n  -> m [Bandit BanditDist]\nrandomBandits count avgDist stdDevDist =\n  replicateM count randomBandit\n  where \n    randomBandit = do\n      gen <- ask\n      mean <- liftIO $ Stat.genContVar avgDist gen\n      stdDev <- liftIO $ Stat.genContVar stdDevDist gen\n      return $ Bandit (Stat.normalDistr mean (abs stdDev))\n\n-- |Pulls the handle and returns the reward\npullArm ::\n  (BanditM m, Stat.ContGen d)\n  => Bandit d\n  -> m BanditStats\npullArm (Bandit d) = do\n  gen <- ask\n  reward <- liftIO $ Stat.genContVar d gen\n  return $ BanditStats reward 1\n\nsimulate ::\n  BanditM m\n  => SimState -- ^ Starting state\n  -> Int      -- ^ Number of rounds\n  -> (SimState -> m Int) -- ^ Choosing function\n  -> m SimState\nsimulate simState 0 _ = return simState\nsimulate simState rounds f = do\n  chosenIndex <- f simState\n  let Just (chosenStat, chosenBandit) = simState ^? bandits. ix chosenIndex -- Pick a bandit\n  newStat <- pullArm chosenBandit\n  let newState = simState\n                 & (bandits . ix chosenIndex) . _1 .~ (chosenStat `mappend` newStat) -- Update stats\n                 & roundsCount %~ (+1) -- Update rounds count\n                 & regretHist %~ (\\t -> (regret simState) : t)\n  simulate newState (rounds - 1) f\n\n-- | Initialize the state but creating the specified number of bandits and pulling each\n-- | one once.\ninitState ::\n  BanditM m\n  => Int -- Number of bandits\n  -> m SimState\ninitState count = do\n  initBandits <- randomBandits count (Stat.uniformDistr 0 50) (Stat.normalDistr 0 5)\n  let initStats = replicate count mempty\n  return $ SimState (zip initStats initBandits) 0 []\n\nregret :: SimState -> Double\nregret simState =\n  let allTimesPulled = fromIntegral <$> (simState ^.. bandits . each . _1 . timesPulled)\n      allMeans = simState ^.. bandits . each . _2 . distLens . meanLens\n      actualExpectedReturn = sum (zipWith (*) allTimesPulled allMeans)\n      maxMean = maximum (simState ^.. bandits . each . _2 . distLens . meanLens)\n      rounds = fromIntegral $ simState ^. roundsCount\n      maxExpectedReturn = maxMean * rounds\n  in\n    maxExpectedReturn - actualExpectedReturn\n\ntype Concrete a = (ReaderT (Rand.Gen (PrimState IO)) IO) a\n\nrun ::\n  Int\n  -> Int\n  -> (SimState -> Concrete Int)\n  -> Concrete SimState\nrun rounds count f = do\n  startingState <- initState count\n  simulate startingState rounds f\n\n-- | Return the index of the largest item as determined by the function\nargMaxIndex :: (Ord b, Num b) => [a] -> (a -> b) -> Maybe Int\nargMaxIndex as f =\n  let magnitudes = f <$> as\n      indexAndMagnitude = zip [0..] magnitudes\n      biggestToSmallest = (List.sortOn (negative . snd) indexAndMagnitude)\n  in biggestToSmallest ^? _head . _1\n  where \n    negative x = -x -- Swap the sign, so it's sorted biggest to smallest.\n\n-- | Choose the bandit with the highest Upper Confidence Bound\nchoose :: SimState -> Int\nchoose simState =\n  let banditStats = simState ^.. bandits . each . _1\n      curRound = simState ^. roundsCount\n      Just maxIndex = argMaxIndex banditStats (ucb curRound)\n  in maxIndex\n\nucb :: Int -> BanditStats -> Double\nucb curRound banditStats =\n  let totalTimesPulled = fromIntegral (banditStats ^. timesPulled)\n      empiricalMean = (banditStats ^. totalReward) / totalTimesPulled\n      t = fromIntegral curRound\n      confidence = sqrt ((2.0 * log (1 + (t * ((log t) ^ 2)))) / totalTimesPulled)\n      in\n    if totalTimesPulled /= 0 then empiricalMean + confidence else maxDouble\n  where\n    maxDouble = 100000000 -- TODO: What's the actual max double?\n\n-- | Choose a random bandit.\nchooseRandom :: BanditM m => SimState -> m Int\nchooseRandom simState = do\n    let count = fromIntegral $ length $ simState ^. bandits\n    let d = Stat.uniformDistr 0 (count - 1)\n    gen <- ask\n    rand <- liftIO $ Stat.genContVar d gen\n    return $ truncate rand\n\n-- | Pick the bandit with the best empirical mean.\nchooseBestMean :: SimState -> Int\nchooseBestMean simState =\n  let banditStats = simState ^.. bandits . each . _1\n      Just maxIndex = argMaxIndex banditStats avgReturn\n  in\n    maxIndex\n\n-- | Pick the bandit with the highest mean reward.\ngodMode :: SimState -> Int\ngodMode simState =\n  let bandits_ = simState ^.. bandits . each . _2\n      Just maxIndex = argMaxIndex bandits_ (\\(Bandit d) -> Stat.mean d)\n  in\n    maxIndex\n\navgReturn :: BanditStats -> Double\navgReturn (BanditStats reward pulled) = reward / (fromIntegral pulled)\n\nmain :: IO ()\nmain = do\n  (opts :: BanditOpts Unwrapped) <-unwrapRecord \"Multi-armed bandit simulator.\"\n  rand <- Rand.createSystemRandom\n  finalState <- runReaderT (run (optRounds opts) (optBandits opts) (return . godMode)) rand\n  _ <- traverse (putStrLn . show) (reverse (finalState ^. regretHist))\n  return ()\n  \n\ndata BanditOpts w =\n  BanditOpts { optRounds :: w ::: Int <?> \"Number of rounds to simulate.\"\n             , optBandits :: w ::: Int <?> \"Number of bandits.\"\n             -- , optMeanMean :: w ::: Double <?> \"Mean of the mean.\"\n             -- , optStdDevMean :: w ::: Double <?> \"StdDev of the mean.\"\n             -- , optMeanStdDev :: w ::: Double <?> \"Mean of the StdDev.\"\n             -- , optStdDevStdDev :: w ::: Double <?> \"StdDev of the StdDev.\"\n             } deriving (Generic)\n\ninstance ParseRecord (BanditOpts Wrapped)\n", "meta": {"hexsha": "2006bc8bb625e916748aac3285f2c3792634fefd", "size": 6263, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "beala/bandits", "max_stars_repo_head_hexsha": "e0847e3cb4446483c250333b38aa6d6215e52b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "beala/bandits", "max_issues_repo_head_hexsha": "e0847e3cb4446483c250333b38aa6d6215e52b29", "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": "app/Main.hs", "max_forks_repo_name": "beala/bandits", "max_forks_repo_head_hexsha": "e0847e3cb4446483c250333b38aa6d6215e52b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6022099448, "max_line_length": 100, "alphanum_fraction": 0.6803448826, "num_tokens": 1696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4938836545616781}}
{"text": "module Grammar where\n\nimport Data.Complex\nimport Data.Matrix\n\ndata Command =\n  --  let a =              [1, 0]\n  InitQ { qName :: String, qVal :: QBit} |\n  InitG { gName :: String, gVal :: Gate} |\n  Measure QBit |\n  Return QBit\n\ndata QBit =\n  QRef String | QArr [Complex Float] | App Gate QBit \n\ndata Gate =\n  GRef String | GMatrix (Matrix (Complex Float)) | Tensor Gate Gate | Product Gate Gate\n", "meta": {"hexsha": "98871bf23354cebf5d0bbeae6e7a16222033d0fd", "size": 396, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grammar.hs", "max_stars_repo_name": "lukasberglund/quami", "max_stars_repo_head_hexsha": "3afceefd7e6570eef819be890e9a899e05239526", "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/Grammar.hs", "max_issues_repo_name": "lukasberglund/quami", "max_issues_repo_head_hexsha": "3afceefd7e6570eef819be890e9a899e05239526", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-20T17:00:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-21T11:50:01.000Z", "max_forks_repo_path": "src/Grammar.hs", "max_forks_repo_name": "lukasberglund/quami", "max_forks_repo_head_hexsha": "3afceefd7e6570eef819be890e9a899e05239526", "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": 22.0, "max_line_length": 87, "alphanum_fraction": 0.6414141414, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49376400312538204}}
{"text": "-- file: Astro/Benchmarks.hs\n-- Benchmarks for some of the functions\n\nmodule Astro.Benchmarks\n\twhere\n\nimport Astro.Stumpff\nimport Astro.Kepler\nimport Astro.Elements\n\nimport Numeric.GSL\nimport Numeric.LinearAlgebra\nimport Control.Monad\n\nkeplerPropagateBM :: Int -> IO ()\nkeplerPropagateBM nsteps = step 0 (rv,vv) \n\twhere\n\t(rv, vv) \t= (3|>[1,0,0], 3|>[0,0.1,0])\n\toe \t\t= posvelToOrbel rv vv\n\th  \t\t= 10*2*pi/(fromIntegral nsteps::Double)\n\tstep n (r,v) = do\n\t\tputStrLn $ (show r)\n\t\t(when (n < nsteps) $ step (n+1) newS)\n\t\twhere \n\t\tnewS = keplerPropagate r v h (1e-15,100)\n", "meta": {"hexsha": "69faf97c39547fa0fbd1c0da0d475a677279decb", "size": 567, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Benchmarks.hs", "max_stars_repo_name": "sageh/AstroHaskell", "max_stars_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Benchmarks.hs", "max_issues_repo_name": "sageh/AstroHaskell", "max_issues_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "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": "Benchmarks.hs", "max_forks_repo_name": "sageh/AstroHaskell", "max_forks_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "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": 21.8076923077, "max_line_length": 45, "alphanum_fraction": 0.6878306878, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.49375925798401316}}
{"text": "-- This file is part of Quipper. Copyright (C) 2011-2014. Please see the\n-- file COPYRIGHT for a list of authors, copyright holders, licensing,\n-- and other details. All rights reserved.\n-- \n-- ======================================================================\n\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\n\n-- | This module contains an implementation of the oracle and its\n-- automatic lifting to quantum circuits using Template Haskell.\nmodule Algorithms.QLS.TemplateOracle where\n\nimport Data.Complex\nimport Libraries.Auxiliary\n\nimport Control.Monad\n\nimport QuipperLib.Arith hiding (template_symb_plus_)\nimport Algorithms.QLS.Utils\nimport Algorithms.QLS.QDouble\nimport Algorithms.QLS.RealFunc\nimport Algorithms.QLS.QSignedInt\nimport Algorithms.QLS.CircLiftingImport\n\nimport Quipper\nimport Quipper.CircLifting\n\n-- | Lifted version of @'any'@ (local version).\nbuild_circuit\nlocal_any :: (a -> Bool) -> [a] -> Bool\nlocal_any f l = case l of\n            []    -> False\n            (h:t) -> if (f h) then True else local_any f t\n\n \n\n-- | Auxiliary function.\nbuild_circuit\nitoxy :: Int -> Int -> Int -> (Int, Int)\nitoxy i nx ny = \n   if (i <= 0) then (0,0)\n   else if (i > (nx-1)*ny + nx*(ny-1)) then (0,0)\n   else ((mod (i - 1) (2*nx - 1)) + 1, ceiling ((fromIntegral i)/(2.0*(fromIntegral nx)-1.0)))\n\n\n-- | The function sin /x/ \\/ /x/.\nbuild_circuit\nsinc :: Double -> Double\nsinc x = if (x /= 0.0) then (sin x) / x else 1.0\n\n\n-- | Auxiliary function.\nbuild_circuit\nedgetoxy :: Int -> Int -> Int -> (Double, Double)\nedgetoxy e nx ny = \n  let (ex,ey) = itoxy e nx ny in\n     if (ex < nx) then ((fromIntegral ex) + 0.5, fromIntegral ey)\n     else (fromIntegral (ex - nx + 1), (fromIntegral ey) + 0.5)\n\n\n-- | Auxiliary function. The inputs are:\n-- \n-- * /y1/ :: 'Int' - Global edge index of row index of desired matrix element;\n-- \n-- * /y2/ :: 'Int' - Global edge index of column index of desired matrix element;\n-- \n-- * /nx/ :: 'Int' - Number of vertices left to right;\n-- \n-- * /ny/ :: 'Int' - Number of vertices top to bottom;\n-- \n-- * /lx/ :: 'Double' - Length of horizontal edges (distance between vertices in /x/ direction);\n-- \n-- * /ly/ :: 'Double' - Length of vertical edges (distance between vertices in /y/ direction);\n-- \n-- * /k/ :: 'Double' - Plane wave wavenumber.\n-- \n-- The output is the matrix element /A/(/y1/, /y2/).\nbuild_circuit\ncalcmatrixelement :: --\n\t-- Inputs\n\tInt \t-- int y1 - Global edge index of row index of desired matrix element  \n\t-> Int \t-- int y2 - Global edge index of column index of desired matrix element\n\t-> Int \t-- int nx - Number of vertices left to right\n\t-> Int\t-- int ny - Number of vertices top to bottom\n\t-> Double -- float lx - Length of horizontal edges (distance between vertices in x direction)\n\t-> Double -- float ly - Length of vertical edges (distance between vertices in y direction)\n\t-> Double -- float k - Plane wave wavenumber\t\n\t-- Outputs\n\t-> Complex Double -- float A - Matrix element A(y1,y2)\ncalcmatrixelement y1 y2 nx ny lx ly k = \n\tlet (xg1, yg1) = itoxy y1 nx ny in\n        let (xg2, yg2) = itoxy y2 nx ny in\n        let b = if ( (y1==y2) && (xg1 >= nx) ) then ly/lx - k*k*lx*ly/3.0\n                -- B11 and B22\n                else if ( (y1==y2) && (xg1<nx) ) then lx/ly - k*k*lx*ly/3.0\n                -- B12 and B21\n                else if ( (abs(yg1-yg2) == 1) && (abs(xg1-xg2) == 0) && (xg1<nx) ) then -lx/ly + k*k*lx*ly/12.0\n                -- B34 and B43\n                else if ( (abs(yg1-yg2)==0) && (abs(xg1-xg2) == 1) && (xg1>=nx) ) then -ly/lx + k*k*lx*ly/12.0\n                -- B13\n                else if ( (yg1==(yg2+1)) && (xg1==(xg2-nx+1)) && (xg2>=nx) ) then -1.0\n                -- B31\n                else if ( (yg2==(yg1+1)) && (xg2==(xg1-nx+1)) && (xg1>=nx) ) then -1.0\n                -- B14\n                else if ( (yg1==(yg2+1)) && (xg1==(xg2-nx)) && (xg1<nx) ) then 1.0\n                -- B41\n                else if ( (yg2==(yg1+1)) && (xg2==(xg1-nx)) && (xg2<nx) ) then 1.0\n                -- B42\n                else if ( (yg1==yg2) && (xg1==(xg2+nx)) && (xg1>=nx) ) then -1.0\n                -- B24\n                else if ( (yg2==yg1) && (xg2==(xg1+nx)) && (xg2>=nx) ) then -1.0\n                -- B32\n                else if ( (yg1==yg2) && (xg1==(xg2+nx-1)) && (xg2<nx) ) then 1.0\n                -- B23\n                else if ( (yg2==yg1) && (xg2==(xg1+nx-1)) && (xg1<nx) ) then 1.0\n                else -1.0\n        in \n        let c = if ( (y1==y2) && ( (xg1==nx) || (xg1==(2*nx-1)) ) ) then 0.0 :+ (k*ly)\n                else if  ( (y1==y2) && ( ((yg1==1) && (xg1<nx)) || ((yg1==ny) && (xg1<nx)) ) ) then 0.0 :+ (k*lx)\n                else 0.0 :+ 0.0\n\tin (b :+ 0.0) + c\n\n\n-- | Auxiliary function.\nbuild_circuit\nget_edges l = case l of\n                [] -> []\n                (x:tt) -> case tt of\n                   [] -> []\n                   (y:t) -> (x,y):(get_edges (y:t))\n\n-- | Auxiliary function.\nbuild_circuit\ncheckedge :: Int -> [(Double,Double)] -> Int -> Int -> Bool\ncheckedge e scatteringnodes nx ny = \n     let (xi,yi) = edgetoxy e nx ny in\n     let test_elt ((x1,y1),(x2, y2)) = xi >= x1 && yi >= y1 && xi <= x2 && yi <= y2 in\n     let half = take_half scatteringnodes in\n     let test_list = local_any test_elt (get_edges half) in (not test_list)\n\n\n\n\n-- | Oracle /r/.\nbuild_circuit\ncalcRweights :: Int -> Int -> Int -> Double -> Double -> Double -> Double -> Double -> Complex Double\ncalcRweights y nx ny lx ly k theta phi =\n     let (xc',yc') = edgetoxy y nx ny in\n     let xc = (xc'-1.0)*lx - ((fromIntegral nx)-1.0)*lx/2.0 in\n     let yc = (yc'-1.0)*ly - ((fromIntegral ny)-1.0)*ly/2.0 in\n     let (xg,yg) = itoxy y nx ny in\n     \n     if (xg == nx) then\n         \n         let i = (mkPolar ly (k*xc*(cos phi)))*\n                 (mkPolar 1.0 (k*yc*(sin phi)))*\n                 ((sinc (k*ly*(sin phi)/2.0)) :+ 0.0) in\n             \n         let r = ( cos(phi) :+ k*lx )*((cos (theta - phi))/lx :+ 0.0) in i * r\n \n     else if (xg==2*nx-1) then\n         \n         let i = (mkPolar ly (k*xc*cos(phi)))*\n                 (mkPolar 1.0 (k*yc*sin(phi)))*\n                 ((sinc (k*ly*sin(phi)/2.0)) :+ 0.0) in\n             \n         let r = ( cos(phi) :+ (- k*lx))*((cos (theta - phi))/lx :+ 0.0) in i * r\n     \n         \n     else if ( (yg==1) && (xg<nx) ) then \n         \n         let i = (mkPolar lx (k*yc*sin(phi)))*\n                 (mkPolar 1.0 (k*xc*cos(phi)))*\n                 ((sinc (k*lx*(cos phi)/2.0)) :+ 0.0) in\n             \n         let r = ( (- sin phi) :+ k*ly )*((cos(theta - phi))/ly :+ 0.0) in i * r\n     \n         \n     else if ( (yg==ny) && (xg<nx) ) then \n         \n         let i = (mkPolar lx (k*yc*sin(phi)))*\n                 (mkPolar 1.0 (k*xc*cos(phi)))*\n                 ((sinc (k*lx*(cos phi)/2.0)) :+ 0.0) in\n             \n         let r = ( (- sin phi) :+ (- k*ly) )*((cos(theta - phi)/ly) :+ 0.0) in i * r\n     \n     else 0.0 :+ 0.0\n\n\n\n-- | Auxiliary function for oracle /A/.\nbuild_circuit\nconvertband :: Int -> Int -> Int -> Int -> Int\nconvertband y b nx ny = \n let nedges = (nx - 1)*ny + nx*(ny - 1) in\n let (ex,ey) = itoxy y nx ny in \n let x = if ( (ex < nx) && (ey /= 1) ) then\n           case b of\n                1 -> y-2*nx+1\n                2 -> y-nx\n                3 -> y-nx+1\n                5 -> y\n                7 -> y+nx-1\n                8 -> y+nx \n                9 -> y+2*nx-1\n                _ -> -1\n         else if ( (ex < nx) && (ey == 1) ) then \n           case b of\n                5 -> y\n                7 -> y+nx-1\n                8 -> y+nx\n                9 -> y+2*nx-1\n                _ -> -1\n         else if ( (ex >= nx) && (ex /= nx) && (ex /= 2*nx-1) ) then\n           case b of\n                    2 -> y-nx\n                    3 -> y-nx+1\n                    4 -> y-1\n                    5 -> y\n                    6 -> y+1\n                    7 -> y+nx-1\n                    8 -> y+nx\n                    _ -> -1\n         else if ( (ex >= nx) && (ex == nx) ) then\n                 case b of\n                    3 -> y-nx+1\n                    5 -> y\n                    6 -> y+1\n                    8 -> y+nx\n                    _ -> -1\n         else if ( (ex >= nx) && (ex == 2*nx-1) ) then\n                case b of\n                    2 -> y-nx \n                    4 -> y-1\n                    5 -> y\n                    7 -> y+nx-1\n                    _ -> -1\n         else -1\n in if ( (x < 1) || (x > nedges) ) then -1 else x\n\n\n\n\n-- | Oracle /A/. It is equivalent to the Matlab function\n-- 'getBandNodeValues'.\n--\n-- 'getNodeValuesMoreOutputs v b ...'  outputs the node of the edge\n-- connected to vertex v in band b, and a real number parameterized by\n-- the 'BoolParam' parameter: the magnitude (PFalse) or the phase\n-- (PTrue) of the complex value at the corresponding place in the matrix A.\nbuild_circuit\ngetNodeValuesMoreOutputs :: \n    Int -> Int -> Int -> Int -> [(Double,Double)] -> Double -> Double -> Double -> BoolParam \n    -> Int -> (Int, Double)\ngetNodeValuesMoreOutputs v' b' nx ny scatteringnodes lx ly k argflag maxConnectivity =\n   let maxC = getIntFromParam maxConnectivity in\n   let b = getIntFromParam b' in\n   let nedges = (nx - 1)*ny + nx*(ny - 1) in\n   let flag = v' <= nedges in\n   let v = (if flag then v' else (v' - nedges)) in\n   let nodeDefault = (if flag then v + nedges else v) in\n   let valueDefault = 0.0 in\n   let indicesDefault = (-1, -1) in\n   let isvalid = checkedge v scatteringnodes nx ny \n   in \n   if ( (not isvalid) && b == 5 ) then\n \n     let indices = (if flag then (v, v + nedges) else (v + nedges, v)) in\n     case argflag of\n        PTrue  -> (nodeDefault, valueDefault)\n        PFalse -> (nodeDefault, 1.0)\n \n   else if ( (not isvalid) && b /= 5) then (nodeDefault, valueDefault)\n \n   else if ((b > maxC + 2) || (b <= 0)) then (nodeDefault, valueDefault)\n \n   else\n \n   let x = convertband v b' nx ny in\n \n   if (x == -1) then (nodeDefault, valueDefault)\n   else\n \n   let isvalid = checkedge x scatteringnodes nx ny in\n \n   if isvalid then\n \n     let ax = calcmatrixelement v x nx ny lx ly k in\n     let (node, indices) = if flag then (x + nedges, (v, x + nedges)) \n                           else (x, (v+nedges,x)) in\n     let value = case argflag of\n                   PTrue -> atan2  (imagPart ax) (realPart ax)\n                   PFalse -> magnitude ax\n     in (node, value)\n     \n   else\n     (nodeDefault, valueDefault)\n\n\n\n\n-- | Auxiliary function for oracle /b/. The inputs are:\n-- \n-- * /y/ :: 'Int' - Global edge index.  Note this is the unmarked /y/\n-- coordinate, i.e. the coordinate without scattering regions removed;\n-- \n-- * /nx/ :: 'Int' - Number of vertices left to right;\n-- \n-- * /ny/ :: 'Int' - Number of vertices top to bottom;\n-- \n-- * /lx/ :: 'Double' - Length of horizontal edges (distance between vertices in /x/ direction);\n-- \n-- * /ly/ :: 'Double' - Length of vertical edges (distance between vertices in /y/ direction);\n-- \n-- * /k/ :: 'Double' - Plane wave wavenumber;\n-- \n-- * \u03b8 :: 'Double' - Direction of wave propagation;\n-- \n-- * /E0/ :: 'Double' - Magnitude of incident plane wave.\n-- \n-- The output is the magnitude of the electric field on edge /y/.\nbuild_circuit\ncalcincidentfield :: --\n\t-- Inputs\n\t\tInt -- int y - Global edge index.  Note this is the unmarked y coordinate, \n\t\t\t-- i.e. the coordinate without scattering regions removed.\n\t-> Int -- int nx - Number of vertices left to right\n\t-> Int --  int ny - Number of vertices top to bottom\n\t-> Double -- float lx - Length of horizontal edges (distance between vertices in x direction)\n\t-> Double -- float ly - Length of vertical edges (distance between vertices in y direction)\n\t-> Double -- float k - Plane wave wavenumber\n\t-> Double -- float theta - Direction of wave propagation\n\t-> Double -- float E0 - Magnitude of incident plane wave\n\t-- Outputs\n\t-> Complex Double -- complex float e - Magnitude of electric field on edge y\ncalcincidentfield y nx ny lx ly k theta e0 = \n        let (xg, yg) = itoxy y nx ny in\n        --Determine whether edge is horizontal or vertical\n        let isvertical = xg >= nx in\n        let (xvalueTmp, yvalueTmp) = edgetoxy y nx ny in\n        let xvalue = xvalueTmp * lx in\n        let yvalue = yvalueTmp * ly in\n        -- Convert x and y edge coordinates to x and y values and caluculate field\n        if isvertical then\n          mkPolar (-cos(theta)*e0) ( -k*(xvalue*cos(theta)+yvalue*sin(theta)))\n        else\n          mkPolar (sin(theta)*e0) ( -k*(xvalue*cos(theta)+yvalue*sin(theta)))\n\n\n-- | Auxiliary function for oracle /b/.\nbuild_circuit\ngetconnection :: Int -> Int -> Int -> Int -> Int -> Int\ngetconnection y i' nx ny maxConnectivity =\n  let i = getIntFromParam i' in\n  let maxC = getIntFromParam maxConnectivity in\n  let (ex,ey) = itoxy y nx ny in\n  let x = if ( (ex < nx) && (ey /= 1) ) then \n            case i' of \n                1 -> y-2*nx+1\n                2 -> y-nx\n                3 -> y-nx+1\n                4 -> y\n                5 -> y+nx-1\n                6 -> y+nx\n                7 -> y+2*nx-1\n                _ -> -1\n          else if ( (ex < nx) && (ey == 1) ) then\n            case i' of\n                1 -> y\n                2 -> y+nx-1\n                3 -> y+nx\n                4 -> y+2*nx-1\n                _ -> -1\n          else if ( (ex >= nx) && (ex /= nx) && (ex /= 2*nx-1) ) then \n             case i' of \n                1 -> y-nx\n                2 -> y-nx+1\n                3 -> y-1\n                4 -> y\n                5 -> y+1\n                6 -> y+nx-1\n                7 -> y+nx\n                _ -> -1\n          else if ( (ex >= nx) && (ex == nx) ) then\n             case i' of\n                1 -> y-nx+1\n                2 -> y\n                3 -> y+1\n                4 -> y+nx\n                _ -> -1\n          else if ( (ex >= nx) && (ex == 2*nx-1) ) then\n             case i' of\n                1 -> y-nx\n                2 -> y-1\n                3 -> y\n                4 -> y+nx-1\n                _ -> -1\n          else -1\n  in\n  if (i > maxC) then -1\n  else if (x > nx*(ny-1)+ny*(nx-1)) then -1 \n  else x\n\n\n\n-- | Auxiliary function to @'template_paramZero'@.\nbuild_circuit\nlocal_loop_with_index_aux :: Int -> Int -> t -> (Int -> t -> t) -> t\nlocal_loop_with_index_aux i n x f = \n   case paramMinus n i of\n     0 -> x\n     _ -> local_loop_with_index_aux (paramSucc i) n (f i x) f\n\n\n-- | Local version of @'loop_with_index'@, for lifting.\nbuild_circuit\nlocal_loop_with_index :: Int -> t -> (Int -> t -> t) -> t\nlocal_loop_with_index n x f = local_loop_with_index_aux paramZero n x f\n\n\n-- | Oracle /b/.\nbuild_circuit\ngetKnownWeights :: Int -> Int -> Int -> [(Double,Double)] -> Double -> Double -> Double -> Double -> Double -> Int -> Complex Double\ngetKnownWeights y nx ny scatteringnodes lx ly k theta e0 maxConnectivity =\n   let makeConnections i connections = let x = getconnection y (paramSucc i) nx ny maxConnectivity in\n                                       let t = not $ checkedge x scatteringnodes nx ny in \n                                       (x,t):connections\n   in\n   let calcTang b (c,t) = if t \n                          then let matElt = calcmatrixelement y c nx ny lx ly k in\n                               let incField = calcincidentfield c nx ny lx ly k theta e0\n                               in b - matElt * incField\n                          else b\n   in\n   let connections = local_loop_with_index maxConnectivity [] makeConnections in\n   if (not $ checkedge y scatteringnodes nx ny) then 0.0 :+ 0.0\n   else foldl calcTang (0.0 :+ 0.0) connections\n\n\n\n\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n-- Testing functions\n\ntest_template_sinc = do\n      f <- template_sinc\n      r <- qinit (0 :: FDouble)\n      f r\n      return ()\n\ntest_template_itoxy = do\n      f <- template_itoxy\n      x <- qinit (0 :: FSignedInt)\n      y <- qinit (0 :: FSignedInt)\n      z <- qinit (0 :: FSignedInt)\n      g <- f x\n      h <- g y\n      k <- h z\n      return ()\n\ntest_template_edgetoxy = do\n      f <- template_edgetoxy\n      x <- qinit (0 :: FSignedInt)\n      y <- qinit (0 :: FSignedInt)\n      z <- qinit (0 :: FSignedInt)\n      g <- f x\n      h <- g y\n      k <- h z\n      return ()\n\ntest_template_calcRweights = do\n      f <- template_calcRweights\n      n1 <- qinit (0 :: FSignedInt)\n      n2 <- qinit (0 :: FSignedInt)\n      n3 <- qinit (0 :: FSignedInt)\n      x1 <- qinit (0 :: FDouble)\n      x2 <- qinit (0 :: FDouble)\n      x3 <- qinit (0 :: FDouble)\n      x4 <- qinit (0 :: FDouble)\n      x5 <- qinit (0 :: FDouble)\n      f1 <- f n1\n      f2 <- f1 n2\n      f3 <- f2 n3\n      g1 <- f3 x1\n      g2 <- g1 x2\n      g3 <- g2 x3\n      g4 <- g3 x4\n      g5 <- g4 x5\n      return ()\n\ntest_template_calcincidentfield = do\n   y' <- qinit (0 :: FSignedInt)\n   nx' <- qinit (0 :: FSignedInt)\n   ny' <- qinit (0 :: FSignedInt)\n   lx' <- qinit (0 :: FDouble)\n   ly' <- qinit (0 :: FDouble)\n   k' <- qinit (0 :: FDouble)\n   theta' <- qinit (0 :: FDouble)\n   e0' <- qinit (0 :: FDouble)\n   f <- template_calcincidentfield \n   f1 <- f y'\n   f2 <- f1 nx'\n   f3 <- f2 ny'\n   f4 <- f3 lx'\n   f5 <- f4 ly'\n   f6 <- f5 k'\n   f7 <- f6 theta'\n   f8 <- f7 e0'\n   return ()\n\ntest_template_calcmatrixelement = do\n   y1 <- qinit (0 :: FSignedInt)\n   y2 <- qinit (0 :: FSignedInt)\n   nx <- qinit (0 :: FSignedInt)\n   ny <- qinit (0 :: FSignedInt)\n   lx <- qinit (0 :: FDouble)\n   ly <- qinit (0 :: FDouble)\n   k  <- qinit (0 :: FDouble)\n   f <- template_calcmatrixelement\n   f1 <- f y1\n   f2 <- f1 y2\n   f3 <- f2 nx\n   f4 <- f3 ny\n   f5 <- f4 lx\n   f6 <- f5 ly\n   f7 <- f6 k\n   return ()\n\ntest_template_getconnection = do\n   y <- qinit (0 :: FSignedInt)\n   nx <- qinit (0 :: FSignedInt)\n   ny <- qinit (0 :: FSignedInt)\n   f <- template_getconnection\n   f1 <- f y\n   f2 <- f1 6\n   f3 <- f2 nx\n   f4 <- f3 ny\n   f5 <- f4 7\n   return ()\n\ntest_template_checkedge = do\n   y <- qinit (0 :: FSignedInt)\n   nx <- qinit (0 :: FSignedInt)\n   ny <- qinit (0 :: FSignedInt)\n   s <- qinit [(0 :: FDouble,0 :: FDouble),(0 :: FDouble,0 :: FDouble)]\n   f <- template_checkedge\n   f1 <- f y\n   f2 <- f1 s\n   f3 <- f2 nx\n   f4 <- f3 ny\n   return ()\n\n", "meta": {"hexsha": "6e96c3f10cc561db76868433ccacdb0e1426e4f4", "size": 18141, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Algorithms/QLS/TemplateOracle.hs", "max_stars_repo_name": "fritzo/quipper", "max_stars_repo_head_hexsha": "b1f1e49cede91c4869b4d849a263aa6acacc55c2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 81, "max_stars_repo_stars_event_min_datetime": "2015-03-04T00:30:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T18:00:04.000Z", "max_issues_repo_path": "Algorithms/QLS/TemplateOracle.hs", "max_issues_repo_name": "fritzo/quipper", "max_issues_repo_head_hexsha": "b1f1e49cede91c4869b4d849a263aa6acacc55c2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-06-17T17:39:28.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-11T18:44:16.000Z", "max_forks_repo_path": "Algorithms/QLS/TemplateOracle.hs", "max_forks_repo_name": "fritzo/quipper", "max_forks_repo_head_hexsha": "b1f1e49cede91c4869b4d849a263aa6acacc55c2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2015-11-29T03:46:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T02:27:40.000Z", "avg_line_length": 32.6276978417, "max_line_length": 132, "alphanum_fraction": 0.5023978832, "num_tokens": 5840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936377487305, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.49366558990991155}}
{"text": "-- An abstract data type for performing multiple linear regression, \n-- using HMatrix as the backend for matrix computations.\n--\n-- types:\n--   Matrix a (2D-array)\n--   Vector a (vector from the standard vector package)\n--\n-- Both types are dense, immutable, and strict in all elements and are \n-- manipulated as whole blocks.\n--\n-- matrix product is a <> b, where a and b are matrices\n-- matrix-vector product is a #> x, where a is a matrix and x a vector\n-- vector-vector dot product is x <.> y\n-- the (conjugate) transpose is trans a, where a is a matrix or vector\n-- the general linear system solver is <\\>\n--\n-- to construct a 4 by 3 matrix: \n-- let a = (4><3) [1,2,3,4,5,6,7,8,9,10,11,12] :: Matrix R\n--\n-- to construct a vector of double-precision floating points:\n-- let x = vector [1,2,3]\n--\n-- to multiply vectors:\n-- x * y\n--\n-- to add two vectors elementwise: \n-- x + y\n--\n-- to compute vector dot product:\n-- x <.> y\n--\n-- to perform matrix-vector product:\n-- m  #> x\n--\n-- to perform matrix-matrix product\n-- m <> n\n--\n-- to sum elements of a vector or matrix:\n-- sumelements m\n--\n\nmodule Regression.HMatrix (\n    model_features,\n    model_outputs,\n    model_weights,\n    model_predictions,\n    model_rss,\n    create_model,\n    create_features,\n    create_weights,\n    predict,\n    powers,\n    normalize,\n    newtons_method,\n    newtons_method_with_norm,\n    cross_validate,\n    gradient_descent\n) where\n\nimport Numeric.LinearAlgebra hiding (magnitude)\nimport Numeric.LinearAlgebra.HMatrix hiding (magnitude)\nimport Data.List hiding (transpose)\nimport Data.Maybe (fromJust)\nimport Debug.Trace (trace)\nimport Stat (range, mean, stdev)\nimport qualified Data.Vector as V\n\n-- A model is:\n-- * a feature matrix with n rows and d columns\n-- * a vector of length n representing the observed output\n-- * a weight vector containing the calculated vector of optimized weights\n-- * the predicted outputs using the optimized weights\n-- * the \ndata Model = MO {\n    model_features    :: FeatureMatrix,\n    model_outputs     :: FeatureVector,\n    model_weights     :: WeightVector,\n    model_predictions :: FeatureVector,\n    model_rss         :: Double\n} deriving (Show)\n\n\n-- A two-dimensional matrix whose columns contain feature values. \ndata FeatureMatrix = FM {\n    fm_name_indexes:: [(String, Int)],\n    fm_values :: Matrix Double\n} deriving (Show)\n\n\n-- A vector of values for a named feature.\ndata FeatureVector = FV {\n    fv_name :: String,\n    fv_values :: Vector Double\n}\ninstance Show FeatureVector where\n    show (FV name values) =\n        name ++ \" = \" ++ show (toList values)\n\n\ntype Feature a = (String, a -> Double)\n\ntype Output a = (String, a -> Double)\n\ntype Optimizer = FeatureMatrix -> FeatureVector -> WeightVector\n\n\n-- A vector of weights.  Each weight corresponds to a feature in the\n-- feature matrix used to calculate the weights.\ndata WeightVector = WV {\n    wv_name_indexes :: [(String, Int)],\n    wv_values :: Vector Double\n}\n\n\ninstance Show WeightVector where\n    show (WV name_indexes values) =\n        concatMap showWeight (zip name_indexes (toList values))\n        where showWeight ((name, i), value) = name ++ \" = \" ++ show value ++ \"\\n\"\n\n\n-- Creates a model from a list of records, a list of features, and the output\n-- accessor function.  This computes the weight vector as well.  This function\n-- does not scale the features nor does it add an intercept feature (a feature\n-- whose values are all 1). \ncreate_model :: [a] -> [Feature a] -> Output a -> Optimizer -> Model\ncreate_model rows features (output_name, output) optimizer = \n    let fmat         = create_features features rows\n        nn           = length rows\n        observations = FV output_name (fromList (Data.List.map output rows))\n        weights      = optimizer fmat observations \n        predictions  = predict fmat weights\n        residuals    = rss observations predictions\n    in MO fmat observations weights predictions residuals\n\n\n-- Multiplies a feature matrix by a weights vector to obtain a prediction of\n-- output.\npredict :: FeatureMatrix -> WeightVector -> FeatureVector\npredict (FM _ h) (WV _ w) = FV \"\" (h #> w)\n\n\n-- Generates the feature matrix, usually denoted as H, with N rows and\n-- D features where D is the length of the feature list.\ncreate_features :: [Feature a] -> [a] -> FeatureMatrix\ncreate_features hs inputs = \n    let n = length inputs\n        d = length hs\n        names = (Data.List.map fst hs)\n        name_indexes = Prelude.zip names [0..]\n        dat = [h(row) | row <- inputs, (_,h) <- hs]\n        h = (n><d) dat \n    in FM name_indexes h\n\n\n-- Computes the residual sum of squares from the observed output and\n-- the predicted output. \nrss :: (Num a) => FeatureVector -> FeatureVector -> Double\nrss (FV _ v1) (FV _ v2) = rss' v1 v2\n\n\nrss' :: Vector Double -> Vector Double -> Double\nrss' v1 v2 = diff <.> diff\n    where diff = v1 - v2\n\n\n-- Takes a list of numbers and turns them into a vector of weights.\ncreate_weights :: FeatureMatrix -> [Double] -> WeightVector\ncreate_weights (FM name_indexes h) weights = WV name_indexes (vector weights)\n\n\nnewtons_method :: Optimizer\nnewtons_method h y = newtons_method_with_norm 0 h y\n\n\nnewtons_method_with_norm :: Matrix Double -> Optimizer\nnewtons_method_with_norm l (FM n h) (FV o y) = WV n w\n    where w = newtons_method_with_norm' l h y\n\n\n-- Performs newtons method, finding an estimate of the minimum.  This method\n-- uses the formula:\n-- w_hat = (H^t * H - lambda*I)^-1 * H^T * y\nnewtons_method_with_norm' :: Matrix Double -> Matrix Double -> Vector Double -> Vector Double\nnewtons_method_with_norm' l h y = ((inv (hth - mod)) <> th) #> y\n    where th = tr h\n          hth = th <> h\n          (d,_) = size hth\n          mod = l * (ident d) :: Matrix Double\n\n\n\n-- Performs gradient descent, updating the weights until the residual\n-- sum of squares is less than the epsilon value e, at which point the\n-- weight matrix is returned.  n is the step size.\ngradient_descent :: Double -> Double -> WeightVector -> Optimizer\ngradient_descent e n (WV name w) (FM _ f) (FV _ o) =\n    let ft      = tr f\n        weights = gradient_descent' e n w f ft o\n    in WV name weights\n\n\ngradient_descent' :: Double -> Double -> Vector Double -> Matrix Double ->\n    Matrix Double -> Vector Double -> Vector Double\ngradient_descent' e n w h ht y =\n    let grad = gradient h ht y w -- (-2H^t(y-Hw))\n        grad_len = magnitude grad  -- grad RSS(w) == ||2H^t(y-HW)||\n    --in if grad_len < e\n    in if (trace (\"gradient = \" ++ show grad_len) grad_len) < e\n        then w\n        else let delta = cmap (*(-n)) grad -- (2nH^t(y-Hw))\n                 w' = w + delta\n             in gradient_descent' e n w' h ht y\n\n\n-- Compute the magnitude of the given vector.\nmagnitude :: Vector Double -> Double\nmagnitude vec = sumElements $ cmap (\\y -> y^2) vec\n\n-- Calculates the gradient of the residual sum of squares (-2H^t(y-Hw)).\n-- This is used to compute the magnitude of the gradient, to see if the \n-- function is minimized.  It is also used to update the weights of the\n-- features.\ngradient :: Matrix Double -> Matrix Double -> Vector Double ->\n    Vector Double -> Vector Double\ngradient h ht y w =\n    let yhat = h #> w\n        err = y - yhat\n        prod = ht #> err\n        grad = cmap (*(-2)) prod\n    in grad\n\n\n-- Given a feature, computes polynomial powers of that feature from \n-- 1 (the original feature) up to and including n. \npowers :: Feature a -> Int -> [Feature a]\npowers (name, f) n = Data.List.map  (\\i -> (name ++ (show i), (\\a -> (f a)^i))) [1..n]\n\n\n-- given a list of values and a feature, return a normalized version of that\n-- feature where the mean of the feature is subtracted from each feature and\n-- the result is divided by the standard deviation of the feature.\nnormalize :: [a] -> (a -> Double) -> a -> Double\nnormalize xs f = (/sdxs) . (+(-meanxs)) . f\n    where meanxs = mean (Data.List.map f xs)\n          sdxs = stdev (Data.List.map f xs)\n\n\n-- Compute the average k-fold cross-validation error for a given L2 penalty and\n-- a given split size k.\n-- Note that the rows should be shuffled before they are provided.\ncross_validate :: Int -> [a] -> [Feature a] -> Output a  -> Optimizer -> Double\ncross_validate k rows features o@(output_name, output) optimizer = kmean\n    where ksplits         = ksplit k rows\n          training_data   = map fst ksplits\n          valid_data      = map snd ksplits\n          trained_models  = map (\\rows -> create_model rows features o optimizer) training_data\n          trained_weights = map model_weights trained_models\n          valid_features  = map (create_features features) valid_data \n          predictions     = zipWith (\\h w -> predict h w) valid_features trained_weights\n          observations    = map (\\dat -> FV output_name (fromList (Data.List.map output dat))) valid_data\n          valid_rss       = zipWith (\\o p -> rss o p) observations predictions\n          kmean           = mean valid_rss\n\n\n-- prepare splits of the data for k-means where k is the number of\n-- clusters and the number of values in the test set (the second list\n-- in the pair) is n/k where n is the size of the input list.\nksplit :: Int -> [a] -> [([a], [a])]\nksplit k xs = map (ksplit' k xs) [0..k-1]\n\n\n-- prepare a k split ([a], [a]) for the chunk at index i with list xs\n-- and with number of chunks k\nksplit' :: Int -> [a] -> Int -> ([a], [a])\nksplit' k xs i = ((take (sz*i) xs) ++ (drop (sz*(i+1)) xs), take sz (drop (sz*i) xs))\n    where sz = length xs `div` k\n", "meta": {"hexsha": "097875806b07abcc2929aa3e9e1ba975b6da69f2", "size": 9482, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Regression/HMatrix.hs", "max_stars_repo_name": "markrgrant/regression", "max_stars_repo_head_hexsha": "8530b3a1c9c44fbf30940b8fbba29bc33f7bff76", "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/Regression/HMatrix.hs", "max_issues_repo_name": "markrgrant/regression", "max_issues_repo_head_hexsha": "8530b3a1c9c44fbf30940b8fbba29bc33f7bff76", "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/Regression/HMatrix.hs", "max_forks_repo_name": "markrgrant/regression", "max_forks_repo_head_hexsha": "8530b3a1c9c44fbf30940b8fbba29bc33f7bff76", "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.2310469314, "max_line_length": 105, "alphanum_fraction": 0.6605146594, "num_tokens": 2456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4935829899343473}}
{"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}\n\n{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE ConstraintKinds     #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE KindSignatures      #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell     #-}\n{-# LANGUAGE TypeApplications    #-}\n{-# LANGUAGE TypeOperators       #-}\n\nmodule Test.Grenade.Layers.Mul where\n\nimport           System.Random.MWC\n\nimport           Data.Proxy\n\nimport           GHC.TypeLits\n\nimport           Grenade.Core\nimport           Grenade.Layers.Mul\nimport qualified Numeric.LinearAlgebra        as LA\nimport           Numeric.LinearAlgebra.Static (L, R)\nimport qualified Numeric.LinearAlgebra.Static as H\n\nimport           Hedgehog\nimport qualified Hedgehog.Range               as Range\n\nimport           Test.Hedgehog.Compat\nimport           Test.Hedgehog.Hmatrix\n\nimport           Data.Either\nimport           Data.Serialize\n\nprop_mul_scalar_one_does_nothing = property $ do\n  height   :: Int <- forAll $ choose 2 100\n  width    :: Int <- forAll $ choose 2 100\n  channels :: Int <- forAll $ choose 2 100\n\n  case (someNatVal (fromIntegral height), someNatVal (fromIntegral width), someNatVal (fromIntegral channels)) of\n    (Just (SomeNat (Proxy :: Proxy h)), Just (SomeNat (Proxy :: Proxy w)), Just (SomeNat (Proxy :: Proxy c))) -> do\n      input :: S ('D3 h w c) <- forAll genOfShape\n\n      let layer    = initMul :: Mul 1 1 1\n          S3D out  = snd $ runForwards layer input :: S ('D3 h w c)\n          S3D inp' = input :: S ('D3 h w c)\n\n      H.extract inp' === H.extract out\n\nprop_mul_random_scalar_as_expected = property $ do\n  height   :: Int <- forAll $ choose 2 100\n  width    :: Int <- forAll $ choose 2 100\n  channels :: Int <- forAll $ choose 2 100\n\n  scalar :: R 1 <- forAll randomVector\n  let scale = H.extract scalar LA.! 0\n\n  case (someNatVal (fromIntegral height), someNatVal (fromIntegral width), someNatVal (fromIntegral channels)) of\n    (Just (SomeNat (Proxy :: Proxy h)), Just (SomeNat (Proxy :: Proxy w)), Just (SomeNat (Proxy :: Proxy c))) -> do\n      input :: S ('D3 h w c) <- forAll genOfShape\n\n      let layer    = Mul scalar :: Mul 1 1 1\n          S3D out  = snd $ runForwards layer input :: S ('D3 h w c)\n          inp' = (\\(S3D x) -> H.dmmap (* scale) x) input :: L (h * c) w\n\n      H.extract inp' === H.extract out\n\nprop_mul_has_show = withTests 1 $ property $ do\n  gen <- evalIO create\n  mul :: Mul 1 1 1 <- evalIO $ createRandomWith UniformInit gen\n  show mul `seq` success\n\nprop_mul_can_update = withTests 1 $ property $ do\n  gen <- evalIO create\n  mul :: Mul 1 1 1 <- evalIO $ createRandomWith UniformInit gen\n  runUpdate defSGD mul () `seq` success\n  runUpdate defAdam mul () `seq` success\n\nprop_mul_can_be_used_with_batch = withTests 1 $ property $ do\n  reduceGradient @(Mul 1 1 1) [()] `seq` success\n\nprop_mul_can_be_serialized = withTests 1 $ property $ do\n  s <- forAll $ genRealNum $ Range.constant 1 10\n  let mul :: Mul 1 1 1 = Mul (H.fromList [s])\n      bs = encode mul\n      dec = decode bs :: Either String (Mul 1 1 1)\n  assert $ isRight dec\n  let Right mul' = dec\n      (Mul scalarMat)  = mul\n      (Mul scalarMat') = mul'\n  (H.extract scalarMat) === (H.extract scalarMat')\n\nprop_mul_fails_serialize_with_incorrect_size = withTests 1 $ property $ do\n  s <- forAll $ genRealNum $ Range.constant 1 10\n  let mul :: Mul 1 1 1 = Mul (H.fromList [s])\n  let bs = encode mul\n  let dec = decode bs :: Either String (Mul 1 2 1)\n  assert $ isLeft dec\n\ntests :: IO Bool\ntests = checkParallel $$(discover)\n", "meta": {"hexsha": "db52e9f2999032f02524286da86e2637f0c5a77d", "size": 3684, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Layers/Mul.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "test/Test/Grenade/Layers/Mul.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Test/Grenade/Layers/Mul.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0857142857, "max_line_length": 115, "alphanum_fraction": 0.6359934853, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.49343346860588494}}
{"text": "{-# LANGUAGE ForeignFunctionInterface, GeneralizedNewtypeDeriving #-}\n\nmodule Numerical.HBLAS.BLAS.FFI.Level3  where\n\nimport Foreign.Ptr\nimport Foreign()\nimport Foreign.C.Types\nimport Data.Complex\nimport Numerical.HBLAS.BLAS.FFI\n\n--------------------------------------------------------------------------------\n------------------------------ | BLAS LEVEL 3 ROUTINES\n--------------------------------------------------------------------------------\n-----------------------  |  Level 3 ops are faster than Levels 1 or 2\n--------------------------------------------------------------------------------\n\n\n--void cblas_sgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const blasint M, const blasint N, const blasint K,\n--         const float alpha, const float *A, const blasint lda, const float *B, const blasint ldb, const float beta, float *C, const blasint ldc);\n\n--void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const blasint M, const blasint N, const blasint K,\n--         const double alpha, const double *A, const blasint lda, const double *B, const blasint ldb, const double beta, double *C, const blasint ldc);\n--void cblas_cgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const blasint M, const blasint N, const blasint K,\n--         const float *alpha, const float *A, const blasint lda, const float *B, const blasint ldb, const float *beta, float *C, const blasint ldc);\n--void cblas_zgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const blasint M, const blasint N, const blasint K,\n--         const double *alpha, const double *A, const blasint lda, const double *B, const blasint ldb, const double *beta, double *C, const blasint ldc);\n\n-- |  Matrix mult for general dense matrices\ntype GemmFunFFI scale el = CBLAS_ORDERT ->   CBLAS_TRANSPOSET -> CBLAS_TRANSPOSET->\n        CInt -> CInt -> CInt -> {- scal A * B -} scale  -> {- Matrix A-} Ptr el  -> CInt -> {- B -}  Ptr el -> CInt->\n            scale -> {- C -}  Ptr el -> CInt -> IO ()\n\n{- C := alpha*op( A )*op( B ) + beta*C ,  -}\n\n-- matrix mult!\nforeign import ccall unsafe \"cblas_sgemm\"\n    cblas_sgemm_unsafe :: GemmFunFFI Float Float\n\nforeign import ccall unsafe \"cblas_dgemm\"\n    cblas_dgemm_unsafe :: GemmFunFFI Double Double\n\nforeign import ccall unsafe \"cblas_cgemm\"\n    cblas_cgemm_unsafe :: GemmFunFFI (Ptr(Complex Float)) (Complex Float)\n\nforeign import ccall unsafe \"cblas_zgemm\"\n    cblas_zgemm_unsafe :: GemmFunFFI (Ptr (Complex Double)) (Complex Double)\n\n-- safe ffi variant for large inputs\nforeign import ccall \"cblas_sgemm\"\n    cblas_sgemm_safe :: GemmFunFFI Float Float\n\nforeign import ccall \"cblas_dgemm\"\n    cblas_dgemm_safe :: GemmFunFFI Double Double\n\nforeign import ccall \"cblas_cgemm\"\n    cblas_cgemm_safe :: GemmFunFFI (Ptr(Complex Float)) (Complex Float)\n\nforeign import ccall \"cblas_zgemm\"\n    cblas_zgemm_safe :: GemmFunFFI (Ptr (Complex Double)) (Complex Double)\n\n-----------------------------------------\n----- |  Matrix mult for Symmetric Matrices\n-----------------------------------------\n\n\n--void cblas_ssymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const blasint M, const blasint N,\n--                 const float alpha, const float *A, const blasint lda, const float *B, const blasint ldb, const float beta, float *C, const blasint ldc);\n--void cblas_dsymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const blasint M, const blasint N,\n--                 const double alpha, const double *A, const blasint lda, const double *B, const blasint ldb, const double beta, double *C, const blasint ldc);\n--void cblas_csymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const blasint M, const blasint N,\n--                 const float *alpha, const float *A, const blasint lda, const float *B, const blasint ldb, const float *beta, float *C, const blasint ldc);\n--void cblas_zsymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const blasint M, const blasint N,\n--                 const double *alpha, const double *A, const blasint lda, const double *B, const blasint ldb, const double *beta, double *C, const blasint ldc);\n\ntype SymmFunFFI scale el = CBLAS_ORDERT -> CBLAS_SIDET -> CBLAS_UPLOT ->\n     CInt->CInt -> scale -> Ptr el -> CInt -> Ptr el -> CInt -> scale ->Ptr el -> CInt -> IO ()\n\nforeign import ccall unsafe \"cblas_ssymm\"\n    cblas_ssymm_unsafe :: SymmFunFFI Float Float\n\nforeign import ccall unsafe \"cblas_dsymm\"\n    cblas_dsymm_unsafe :: SymmFunFFI Double Double\n\nforeign import ccall unsafe \"cblas_csymm\"\n    cblas_csymm_unsafe :: SymmFunFFI (Ptr (Complex Float )) (Complex Float)\n\nforeign import ccall unsafe \"cblas_zsymm\"\n    cblas_zsymm_unsafe :: SymmFunFFI (Ptr (Complex Double)) (Complex Double)\n\n-- safe ffi variant,\nforeign import ccall  \"cblas_ssymm\"\n    cblas_ssymm_safe :: SymmFunFFI Float Float\n\nforeign import ccall  \"cblas_dsymm\"\n    cblas_dsymm_safe :: SymmFunFFI Double Double\n\nforeign import ccall  \"cblas_csymm\"\n    cblas_csymm_safe :: SymmFunFFI (Ptr (Complex Float )) (Complex Float)\n\nforeign import ccall  \"cblas_zsymm\"\n    cblas_zsymm_safe :: SymmFunFFI (Ptr (Complex Double)) (Complex Double)\n\n\n-----------------------------------\n--- |  symmetric rank k  matrix update, C := alpha*A*A' + beta*C\n--- or C = alpha*A'*A + beta*C\n------------------------------------\n\n\n--void cblas_ssyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans,\n--         const blasint N, const blasint K, const float alpha, const float *A, const blasint lda, const float beta, float *C, const blasint ldc);\n--void cblas_dsyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans,\n--         const blasint N, const blasint K, const double alpha, const double *A, const blasint lda, const double beta, double *C, const blasint ldc);\n--void cblas_csyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans,\n--         const blasint N, const blasint K, const float *alpha, const float *A, const blasint lda, const float *beta, float *C, const blasint ldc);\n--void cblas_zsyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans,\n--         const blasint N, const blasint K, const double *alpha, const double *A, const blasint lda, const double *beta, double *C, const blasint ldc);\n\ntype SyrkFunFFI scale el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET ->\n     CInt -> CInt  -> scale -> Ptr el -> CInt -> scale -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_ssyrk\"\n    cblas_ssyrk_unsafe :: SyrkFunFFI Float Float\nforeign import ccall unsafe \"cblas_dsyrk\"\n    cblas_dsyrk_unsafe :: SyrkFunFFI Double Double\nforeign import ccall unsafe \"cblas_csyrk\"\n    cblas_csyrk_unsafe :: SyrkFunFFI (Ptr(Complex Float)) (Complex Float)\nforeign import ccall unsafe \"cblas_zsyrk\"\n    cblas_zsyrk_unsafe :: SyrkFunFFI (Ptr(Complex Double)) (Complex Double)\n\nforeign import ccall safe \"cblas_ssyrk\"\n    cblas_ssyrk_safe :: SyrkFunFFI Float Float\nforeign import ccall safe \"cblas_dsyrk\"\n    cblas_dsyrk_safe :: SyrkFunFFI Double Double\nforeign import ccall safe \"cblas_csyrk\"\n    cblas_csyrk_safe :: SyrkFunFFI (Ptr(Complex Float)) (Complex Float)\nforeign import ccall safe \"cblas_zsyrk\"\n    cblas_zsyrk_safe :: SyrkFunFFI (Ptr(Complex Double)) (Complex Double)\n----------------------\n----- | Symmetric Rank 2k matrix update, C= alpha* A*B' + alpha* B*A' + beta * C\n----- or C= alpha* A'*B + alpha* B'*A + beta * C\n-------------------\n\n\n--void cblas_ssyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans,\n--          const blasint N, const blasint K, const float alpha, const float *A, const blasint lda, const float *B, const blasint ldb, const float beta, float *C, const blasint ldc);\n--void cblas_dsyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans,\n--          const blasint N, const blasint K, const double alpha, const double *A, const blasint lda, const double *B, const blasint ldb, const double beta, double *C, const blasint ldc);\n--void cblas_csyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans,\n--          const blasint N, const blasint K, const float *alpha, const float *A, const blasint lda, const float *B, const blasint ldb, const float *beta, float *C, const blasint ldc);\n--void cblas_zsyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans,\n         --const blasint N, const blasint K, const double *alpha, const double *A, const blasint lda, const double *B, const blasint ldb, const double *beta, double *C, const blasint ldc);\n\ntype Syr2kFunFFI scale el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET  ->\n     CInt->CInt -> scale -> Ptr el -> CInt -> Ptr el -> CInt ->\n     scale ->Ptr el -> CInt -> IO ()\n\nforeign  import ccall unsafe \"cblas_ssyr2k\"\n    cblas_ssyr2k_unsafe :: Syr2kFunFFI Float Float\nforeign import ccall unsafe \"cblas_dsyr2k\"\n    cblas_dsyr2k_unsafe :: Syr2kFunFFI Double Double\nforeign  import ccall unsafe \"cblas_csyr2k\"\n    cblas_csyr2k_unsafe :: Syr2kFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign  import ccall unsafe \"cblas_zsyr2k\"\n    cblas_zsyr2k_unsafe :: Syr2kFunFFI (Ptr (Complex Double)) (Complex Double)\n\nforeign  import ccall safe \"cblas_ssyr2k\"\n    cblas_ssyr2k_safe :: Syr2kFunFFI Float Float\nforeign import ccall safe \"cblas_dsyr2k\"\n    cblas_dsyr2k_safe :: Syr2kFunFFI Double Double\nforeign  import ccall safe \"cblas_csyr2k\"\n    cblas_csyr2k_safe :: Syr2kFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign  import ccall safe \"cblas_zsyr2k\"\n    cblas_zsyr2k_safe :: Syr2kFunFFI (Ptr (Complex Double)) (Complex Double)\n\n-------------------------------\n--------  |  matrix matrix product for triangular matrices\n------------------------------\n\ntype TrmmFunFFI scale el = CBLAS_ORDERT -> CBLAS_SIDET -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->\n     CInt -> CInt -> scale -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign  import ccall unsafe \"cblas_strmm\"\n    cblas_strmm_unsafe :: TrmmFunFFI Float Float\nforeign  import ccall unsafe \"cblas_dtrmm\"\n    cblas_dtrmm_unsafe :: TrmmFunFFI Double Double\nforeign  import ccall unsafe \"cblas_ctrmm\"\n    cblas_ctrmm_unsafe :: TrmmFunFFI (Ptr (Complex Float )) (Complex Float)\nforeign  import ccall unsafe \"cblas_ztrmm\"\n    cblas_ztrmm_unsafe :: TrmmFunFFI (Ptr (Complex Double )) (Complex Double)\n\nforeign  import ccall safe \"cblas_strmm\"\n    cblas_strmm_safe :: TrmmFunFFI Float Float\nforeign  import ccall safe \"cblas_dtrmm\"\n    cblas_dtrmm_safe :: TrmmFunFFI Double Double\nforeign  import ccall safe \"cblas_ctrmm\"\n    cblas_ctrmm_safe :: TrmmFunFFI (Ptr (Complex Float )) (Complex Float)\nforeign  import ccall safe \"cblas_ztrmm\"\n    cblas_ztrmm_safe :: TrmmFunFFI (Ptr (Complex Double )) (Complex Double)\n--void cblas_strmm(  enum CBLAS_ORDER Order,   enum CBLAS_SIDE Side,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE TransA,\n--                   enum CBLAS_DIAG Diag,   CInt M,   CInt N,   Float alpha,   Float *A,   CInt lda, Float *B,   CInt ldb);\n--void cblas_dtrmm(  enum CBLAS_ORDER Order,   enum CBLAS_SIDE Side,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE TransA,\n--                   enum CBLAS_DIAG Diag,   CInt M,   CInt N,   Double alpha,   Double *A,   CInt lda, Double *B,   CInt ldb);\n--void cblas_ctrmm(  enum CBLAS_ORDER Order,   enum CBLAS_SIDE Side,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE TransA,\n--                   enum CBLAS_DIAG Diag,   CInt M,   CInt N,   Float *alpha,   Float *A,   CInt lda, Float *B,   CInt ldb);\n--void cblas_ztrmm(  enum CBLAS_ORDER Order,   enum CBLAS_SIDE Side,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE TransA,\n--                   enum CBLAS_DIAG Diag,   CInt M,   CInt N,   Double *alpha,   Double *A,   CInt lda, Double *B,   CInt ldb);\n\n------------------------\n--  |  triangular solvers\n-----------------------\n\n\n--\n--TRSM solves  op(A)*X = alpha*B or  X*op(A) = alpha*B\n--op(A) is one of op(A) = A, or op(A) = A', or op(A) = conjg(A').\n-- A is a unit, or non-unit, upper or lower triangular matrix\n----\ntype TrsmFunFFI scale el = CBLAS_ORDERT -> CBLAS_SIDET -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->\n     CInt -> CInt -> scale -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign  import ccall unsafe \"cblas_strsm\"\n    cblas_strsm_unsafe :: TrsmFunFFI Float Float\nforeign  import ccall unsafe \"cblas_dtrsm\"\n    cblas_dtrsm_unsafe :: TrsmFunFFI Double Double\nforeign  import ccall unsafe \"cblas_ctrsm\"\n    cblas_ctrsm_unsafe :: TrsmFunFFI (Ptr (Complex Float )) (Complex Float)\nforeign  import ccall unsafe \"cblas_ztrsm\"\n    cblas_ztrsm_unsafe :: TrsmFunFFI (Ptr (Complex Double )) (Complex Double)\n\nforeign  import ccall safe \"cblas_strsm\"\n    cblas_strsm_safe :: TrsmFunFFI Float Float\nforeign  import ccall safe \"cblas_dtrsm\"\n    cblas_dtrsm_safe :: TrsmFunFFI Double Double\nforeign  import ccall safe \"cblas_ctrsm\"\n    cblas_ctrsm_safe :: TrsmFunFFI (Ptr (Complex Float )) (Complex Float)\nforeign  import ccall safe \"cblas_ztrsm\"\n    cblas_ztrsm_safe :: TrsmFunFFI (Ptr (Complex Double )) (Complex Double)\n--void cblas_strsm(  enum CBLAS_ORDER Order,   enum CBLAS_SIDE Side,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE TransA,\n--                   enum CBLAS_DIAG Diag,   CInt M,   CInt N,   Float alpha,   Float *A,   CInt lda, Float *B,   CInt ldb);\n--void cblas_dtrsm(  enum CBLAS_ORDER Order,   enum CBLAS_SIDE Side,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE TransA,\n--                   enum CBLAS_DIAG Diag,   CInt M,   CInt N,   Double alpha,   Double *A,   CInt lda, Double *B,   CInt ldb);\n--void cblas_ctrsm(  enum CBLAS_ORDER Order,   enum CBLAS_SIDE Side,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE TransA,\n--                   enum CBLAS_DIAG Diag,   CInt M,   CInt N,   Float *alpha,   Float *A,   CInt lda, Float *B,   CInt ldb);\n--void cblas_ztrsm(  enum CBLAS_ORDER Order,   enum CBLAS_SIDE Side,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE TransA,\n--                   enum CBLAS_DIAG Diag,   CInt M,   CInt N,   Double *alpha,   Double *A,   CInt lda, Double *B,   CInt ldb);\n\n-------------------------\n-- | hermitian matrix mult\n------------------------\n\ntype HemmFunFFI  el = CBLAS_ORDERT -> CBLAS_SIDET -> CBLAS_UPLOT ->\n     CInt -> CInt -> Ptr el -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> Ptr el -> CInt -> IO ()\n\nforeign  import ccall unsafe \"cblas_chemm\"\n    cblas_chemm_unsafe :: HemmFunFFI (Complex Float)\nforeign  import ccall unsafe \"cblas_zhemm\"\n    cblas_zhemm_unsafe :: HemmFunFFI  (Complex Double)\n\nforeign  import ccall safe \"cblas_chemm\"\n    cblas_chemm_safe :: HemmFunFFI (Complex Float)\nforeign  import ccall safe \"cblas_zhemm\"\n    cblas_zhemm_safe :: HemmFunFFI  (Complex Double)\n\n--void cblas_chemm(  enum CBLAS_ORDER Order,   enum CBLAS_SIDE Side,   enum CBLAS_UPLO Uplo,   CInt M,   CInt N,\n--                   Float *alpha,   Float *A,   CInt lda,   Float *B,   CInt ldb,   Float *beta, Float *C,   CInt ldc);\n--void cblas_zhemm(  enum CBLAS_ORDER Order,   enum CBLAS_SIDE Side,   enum CBLAS_UPLO Uplo,   CInt M,   CInt N,\n--                   Double *alpha,   Double *A,   CInt lda,   Double *B,   CInt ldb,   Double *beta, Double *C,   CInt ldc);\n\ntype HerkFunFFI scale el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET ->\n     CInt -> CInt -> scale -> Ptr el -> CInt -> scale -> Ptr el -> CInt -> IO ()\n\nforeign  import ccall unsafe \"cblas_cherk\"\n    cblas_cherk_unsafe :: HerkFunFFI Float (Complex Float)\nforeign  import ccall unsafe \"cblas_zherk\"\n    cblas_zherk_unsafe :: HerkFunFFI Double (Complex Double)\n\nforeign  import ccall safe \"cblas_cherk\"\n    cblas_cherk_safe :: HerkFunFFI Float (Complex Float)\nforeign  import ccall safe \"cblas_zherk\"\n    cblas_zherk_safe :: HerkFunFFI Double (Complex Double)\n--void cblas_cherk(  enum CBLAS_ORDER Order,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE Trans,   CInt N,   CInt K,\n--                   Float alpha,   Float *A,   CInt lda,   Float beta, Float *C,   CInt ldc);\n--void cblas_zherk(  enum CBLAS_ORDER Order,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE Trans,   CInt N,   CInt K,\n--                   Double alpha,   Double *A,   CInt lda,   Double beta, Double *C,   CInt ldc);\n\ntype Her2kFunFFI scale el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET ->\n     CInt -> CInt -> Ptr el  -> Ptr el -> CInt -> Ptr el -> CInt -> scale ->Ptr el -> CInt -> IO ()\n\nforeign  import ccall unsafe \"cblas_cher2k\"\n    cblas_cher2k_unsafe :: Her2kFunFFI  Float  (Complex Float)\nforeign  import ccall unsafe \"cblas_zher2k\"\n    cblas_zher2k_unsafe :: Her2kFunFFI  Double  (Complex Double)\n\nforeign  import ccall safe \"cblas_cher2k\"\n    cblas_cher2k_safe :: Her2kFunFFI Float (Complex Float)\nforeign  import ccall safe \"cblas_zher2k\"\n    cblas_zher2k_safe :: Her2kFunFFI Double (Complex Double)\n--void cblas_cher2k(  enum CBLAS_ORDER Order,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE Trans,   CInt N,   CInt K,\n--                    Float *alpha,   Float *A,   CInt lda,   Float *B,   CInt ldb,   Float beta, Float *C,   CInt ldc);\n--void cblas_zher2k(  enum CBLAS_ORDER Order,   enum CBLAS_UPLO Uplo,   enum CBLAS_TRANSPOSE Trans,   CInt N,   CInt K,\n--                    Double *alpha,   Double *A,   CInt lda,   Double *B,   CInt ldb,   Double beta, Double *C,   CInt ldc);\n\n----void cblas_xerbla(CInt p, char *rout, char *form, ...);\n", "meta": {"hexsha": "281f7654db22d46396cf6ae6dea3646ee28edffb", "size": 17725, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numerical/HBLAS/BLAS/FFI/Level3.hs", "max_stars_repo_name": "schnecki/hblas", "max_stars_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-05-03T23:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-17T22:58:54.000Z", "max_issues_repo_path": "src/Numerical/HBLAS/BLAS/FFI/Level3.hs", "max_issues_repo_name": "schnecki/hblas", "max_issues_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-01-24T13:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T22:15:09.000Z", "max_forks_repo_path": "src/Numerical/HBLAS/BLAS/FFI/Level3.hs", "max_forks_repo_name": "schnecki/hblas", "max_forks_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-01-09T12:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:37:37.000Z", "avg_line_length": 58.6920529801, "max_line_length": 188, "alphanum_fraction": 0.6847954866, "num_tokens": 5417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6261241632752916, "lm_q1q2_score": 0.49334276059040755}}
{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections       #-}\n{-# LANGUAGE TypeFamilies        #-}\n{-# LANGUAGE TypeOperators       #-}\n\nmodule Main where\nimport           Debug.Trace\nimport           Control.Monad\nimport qualified Data.ByteString              as B\nimport qualified Data.ByteString.Lazy         as L\nimport           Data.List\nimport           Data.Serialize               (decodeLazy, encodeLazy)\nimport qualified Data.Vector.Storable         as V\nimport           Grenade\nimport           Numeric.LinearAlgebra        (maxIndex)\nimport qualified Numeric.LinearAlgebra.Static as S\nimport           System.Random\nimport           Graphics.Image              as I hiding (map)\nimport           Graphics.Image.Interface    as I hiding (map)\nimport           Graphics.Image.Processing   as I hiding (map)\nimport qualified Numeric.LinearAlgebra as NLA\nimport qualified Numeric.LinearAlgebra.Static as NLA\nimport qualified Numeric.LinearAlgebra.Data as NLA\n\nreadF::FilePath->IO (S ('D3 100 100 3))\nreadF path =do\n     Right x<- (fmap (resize Bilinear Edge (100,100)))<$>readImage path::IO (Either String (Image VS RGB Double))\n     let Just res=fromStorable $V.concatMap (\\(PixelRGB r g b) -> V.fromList [r,g,b]) $ toVector x\n     return res\n\nscons a !b = V.cons a b\n\nelemAt = (V.!)\n\ntoImg::S ('D3 100 100 3)->Image VS RGB Double\ntoImg x = fromVector (100,100) $groupRGB $ext x\n          where groupRGB v= if V.null v then V.empty else (PixelRGB (v `elemAt` 0) (v `elemAt` 1) (v `elemAt` 2)) `scons` groupRGB (V.drop 3 v)\n                ext::S ('D3 100 100 3)->V.Vector Double\n                ext (S3D m) = NLA.flatten$NLA.extract m\n\n type FE\n  = Network\n    '[ Convolution 3 24 5 5 1 1,  Relu, Pooling 2 2 2 2\n     , Reshape\n     , FullyConnected 55296 1024, Logit\n     , FullyConnected 1024 55296, Relu\n     , Reshape\n     , Deconvolution 24 3 6 6 2 2, Logit\n     ]\n    '[ 'D3 100 100 3, 'D3 96 96 24, 'D3 96 96 24, 'D3 48 48 24 \n     , 'D1 55296\n     , 'D1 1024, 'D1 1024\n     , 'D1 55296, 'D1 55296\n     , 'D3 48 48 24\n     , 'D3 100 100 3,'D3 100 100 3]\n\n\ntrainOne::LearningParameters->FE->S ('D3 100 100 3)->FE\ntrainOne rate !net i=\n  train rate net i i\n\ntrainT::FE->Int->S ('D3 100 100 3)->FE\ntrainT !net x img= \n    let lp = LearningParameters 0.0001 0.9 0.0005\n    in  foldl' (\\n i -> \n      trace (show i) $trainOne (lp{ learningRate = learningRate lp *(0.999 ^ i)}) n img)\n      net [0..x]\n\nmain' = do\n  i<-readF \"image/n11669921_50878.JPEG\"\n  writeImage \"newimg.jpg\" $ toImg i\n\nmain = do\n  i<-readF \"image/n11669921_50878.JPEG\"\n  x<-Prelude.read<$>getLine\n  net<-randomNetwork::IO FE\n  let net'=trainT net x i\n  writeImage \"newimg.jpg\" $ toImg $runNet net' i\n", "meta": {"hexsha": "9b2b9ae529ad49d14f5e37cf3d80aa8e57cdb474", "size": 2807, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "AutoEncoder.hs", "max_stars_repo_name": "xsuler/ADS_IR", "max_stars_repo_head_hexsha": "ba6642f37494186d5f8a9f5beda75a3a933b21ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AutoEncoder.hs", "max_issues_repo_name": "xsuler/ADS_IR", "max_issues_repo_head_hexsha": "ba6642f37494186d5f8a9f5beda75a3a933b21ca", "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": "AutoEncoder.hs", "max_forks_repo_name": "xsuler/ADS_IR", "max_forks_repo_head_hexsha": "ba6642f37494186d5f8a9f5beda75a3a933b21ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2317073171, "max_line_length": 143, "alphanum_fraction": 0.6234413965, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4931705313371806}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{- |\nThis module provides a simple way to train\nthe transition matrix and initial probability vector\nusing simple patterns of state sequences.\n\nYou may create a trained model using semigroup combinators like this:\n\n> let a = atom $ HMM.state 0\n>     b = atom $ HMM.state 1\n>     distr =\n>        Distr.DiscreteTrained $ Map.fromList $\n>        ('a', Vector.fromList [1,2]) :\n>        ('b', Vector.fromList [4,3]) :\n>        ('c', Vector.fromList [0,1]) :\n>        []\n> in  finish 2 distr $ replicate 5 $ replicate 10 a <> replicate 20 b\n-}\nmodule Math.HiddenMarkovModel.Pattern (\n   T,\n   atom,\n   append,\n   replicate,\n   finish,\n   ) where\n\nimport qualified Math.HiddenMarkovModel.Distribution as Distr\nimport qualified Math.HiddenMarkovModel as HMM\nimport Math.HiddenMarkovModel.Private (Trained(..))\nimport Math.HiddenMarkovModel.Distribution (State(State))\n\nimport qualified Numeric.LinearAlgebra.Algorithms as Algo\nimport qualified Numeric.Container as NC\nimport qualified Data.Packed.Vector as Vector\nimport Data.Packed.Matrix (Matrix)\nimport Data.Packed.Vector (Vector)\n\nimport qualified Data.Map as Map\nimport Data.Semigroup (Semigroup, (<>), stimes)\n\nimport Prelude hiding (replicate)\n\n\nnewtype T prob = Cons (Int -> (State, Matrix prob, State))\n\natom ::\n   (NC.Container Vector prob) =>\n   State -> T prob\natom s = Cons $ \\n -> (s, NC.konst 0 (n,n), s)\n\n\ninstance (Algo.Field prob) => Semigroup (T prob) where\n   (<>) = append\n   stimes k = replicate $ fromIntegral k\n\n\ninfixl 5 `append`\n\nappend ::\n   (NC.Container Vector prob) =>\n   T prob -> T prob -> T prob\nappend (Cons f) (Cons g) =\n   Cons $ \\n ->\n      case (f n, g n) of\n         ((sai, ma, sao), (sbi, mb, sbo)) ->\n            (sai, increment (sbi,sao) 1 $ NC.add ma mb, sbo)\n\nreplicate ::\n   (NC.Container Vector prob) =>\n   Int -> T prob -> T prob\nreplicate ki (Cons f) =\n   Cons $ \\n ->\n      case f n of\n         (si, m, so) ->\n            let k = fromIntegral ki\n            in  (si, increment (si,so) (k-1) $ NC.scale k m, so)\n\nincrement ::\n   (NC.Container Vector a) =>\n   (State, State) -> a -> Matrix a -> Matrix a\nincrement (State i, State j) x m  =  NC.accum m (+) [((i,j), x)]\n\n\nfinish ::\n   (NC.Container Vector prob) =>\n   Int -> tdistr -> T prob -> Trained tdistr prob\nfinish n tdistr (Cons f) =\n   case f n of\n      (State si, m, _so) ->\n         Trained {\n            trainedInitial = NC.assoc n 0 [(si,1)],\n            trainedTransition = m,\n            trainedDistribution = tdistr\n         }\n\n\n_example :: HMM.DiscreteTrained Double Char\n_example =\n   let a = atom $ HMM.state 0\n       b = atom $ HMM.state 1\n       distr =\n          Distr.DiscreteTrained $ Map.fromList $\n          ('a', Vector.fromList [1,2]) :\n          ('b', Vector.fromList [4,3]) :\n          ('c', Vector.fromList [0,1]) :\n          []\n   in  finish 2 distr $ replicate 5 $ replicate 10 a <> replicate 20 b\n", "meta": {"hexsha": "fb59acce9f12cd33e47444ed08356bf14945684c", "size": 2935, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/HiddenMarkovModel/Pattern.hs", "max_stars_repo_name": "rybern/hmm-hmatrix", "max_stars_repo_head_hexsha": "3f1c44aa630e0c7a662c1abe100ea8e783e3c44e", "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/Math/HiddenMarkovModel/Pattern.hs", "max_issues_repo_name": "rybern/hmm-hmatrix", "max_issues_repo_head_hexsha": "3f1c44aa630e0c7a662c1abe100ea8e783e3c44e", "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/Math/HiddenMarkovModel/Pattern.hs", "max_forks_repo_name": "rybern/hmm-hmatrix", "max_forks_repo_head_hexsha": "3f1c44aa630e0c7a662c1abe100ea8e783e3c44e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9266055046, "max_line_length": 70, "alphanum_fraction": 0.6136286201, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49307831129874624}}
{"text": "{-# LANGUAGE RankNTypes #-}\n\nmodule Test.Grenade.Layers.Internal.Reference where\n\nimport           Grenade.Types\nimport           Numeric.LinearAlgebra\nimport qualified Numeric.LinearAlgebra.Static as H\nimport           GHC.TypeLits\n\nim2col :: Int -> Int -> Int -> Int -> Matrix RealNum -> Matrix RealNum\nim2col nrows ncols srows scols m =\n  let starts = fittingStarts (rows m) nrows srows (cols m) ncols scols\n  in  im2colFit starts nrows ncols m\n\nvid2col :: Int -> Int -> Int -> Int -> Int -> Int -> [Matrix RealNum] -> Matrix RealNum\nvid2col nrows ncols srows scols inputrows inputcols ms =\n  let starts = fittingStarts inputrows nrows srows inputcols ncols scols\n      subs   = fmap (im2colFit starts nrows ncols) ms\n  in  foldl1 (|||) subs\n\nim2colFit :: [(Int,Int)] -> Int -> Int -> Matrix RealNum -> Matrix RealNum\nim2colFit starts nrows ncols m =\n  let imRows = fmap (\\start -> flatten $ subMatrix start (nrows, ncols) m) starts\n  in  fromRows imRows\n\ncol2vid :: Int -> Int -> Int -> Int -> Int -> Int -> Matrix RealNum -> [Matrix RealNum]\ncol2vid nrows ncols srows scols drows dcols m =\n  let starts = fittingStart (cols m) (nrows * ncols) (nrows * ncols)\n      r      = rows m\n      mats   = fmap (\\s -> subMatrix (0,s) (r, nrows * ncols) m) starts\n      colSts = fittingStarts drows nrows srows dcols ncols scols\n  in  fmap (col2imfit colSts nrows ncols drows dcols) mats\n\ncol2im :: Int -> Int -> Int -> Int -> Int -> Int -> Matrix RealNum -> Matrix RealNum\ncol2im krows kcols srows scols drows dcols m =\n  let rs       = map toList $ toColumns m \n      rs'      = zip [0..] rs\n      indicies = (\\[a,b] -> (a,b)) <$> sequence [[0..(krows-1)], [0..(kcols-1)]]\n      accums   = concatMap (\\(offset, column) -> zipWith (comb offset) indicies column) rs'\n  in accum (konst 0 (drows, dcols)) (+) accums\n  where     \n    comb o (i, j) x = let w = (div (dcols - kcols) scols) + 1\n                          (a, b) = divMod o w\n                      in  ((i + srows * a, j + scols * b), x)\n\ncol2imfit :: [(Int,Int)] -> Int -> Int -> Int -> Int -> Matrix RealNum -> Matrix RealNum\ncol2imfit starts krows kcols drows dcols m =\n  let indicies   = (\\[a,b] -> (a,b)) <$> sequence [[0..(krows-1)], [0..(kcols-1)]]\n      convs      = fmap (zip indicies . toList) . toRows $ m\n      pairs      = zip convs starts\n      accums     = concatMap (\\(conv',(stx',sty')) -> fmap (\\((ix,iy), val) -> ((ix + stx', iy + sty'), val)) conv') pairs\n  in  accum (konst 0 (drows, dcols)) (+) accums\n\npoolForward :: Int -> Int -> Int -> Int -> Int -> Int -> Matrix RealNum -> Matrix RealNum\npoolForward nrows ncols srows scols outputRows outputCols m =\n  let starts = fittingStarts (rows m) nrows srows (cols m) ncols scols\n  in  poolForwardFit starts nrows ncols outputRows outputCols m\n\npoolForwardList :: Functor f => Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> f (Matrix RealNum) -> f (Matrix RealNum)\npoolForwardList nrows ncols srows scols inRows inCols outputRows outputCols ms =\n  let starts = fittingStarts inRows nrows srows inCols ncols scols\n  in  poolForwardFit starts nrows ncols outputRows outputCols <$> ms\n\npoolForwardFit :: [(Int,Int)] -> Int -> Int -> Int -> Int -> Matrix RealNum -> Matrix RealNum\npoolForwardFit starts nrows ncols _ outputCols m =\n  let els    = fmap (\\start -> maxElement $ subMatrix start (nrows, ncols) m) starts\n  in  matrix outputCols els\n\npoolBackward :: Int -> Int -> Int -> Int -> Matrix RealNum -> Matrix RealNum -> Matrix RealNum\npoolBackward krows kcols srows scols inputMatrix gradientMatrix =\n  let inRows     = rows inputMatrix\n      inCols     = cols inputMatrix\n      starts     = fittingStarts inRows krows srows inCols kcols scols\n  in  poolBackwardFit starts krows kcols inputMatrix gradientMatrix\n\npoolBackwardList :: Functor f => Int -> Int -> Int -> Int -> Int -> Int -> f (Matrix RealNum, Matrix RealNum) -> f (Matrix RealNum)\npoolBackwardList krows kcols srows scols inRows inCols inputMatrices =\n  let starts     = fittingStarts inRows krows srows inCols kcols scols\n  in  uncurry (poolBackwardFit starts krows kcols) <$> inputMatrices\n\npoolBackwardFit :: [(Int,Int)] -> Int -> Int -> Matrix RealNum -> Matrix RealNum -> Matrix RealNum\npoolBackwardFit starts krows kcols inputMatrix gradientMatrix =\n  let inRows     = rows inputMatrix\n      inCols     = cols inputMatrix\n      inds       = fmap (\\start -> maxIndex $ subMatrix start (krows, kcols) inputMatrix) starts\n      grads      = toList $ flatten gradientMatrix\n      grads'     = zip3 starts grads inds\n      accums     = fmap (\\((stx',sty'),grad,(inx, iny)) -> ((stx' + inx, sty' + iny), grad)) grads'\n  in  accum (konst 0 (inRows, inCols)) (+) accums\n\n-- | These functions are not even remotely safe, but it's only called from the statically typed\n--   commands, so we should be good ?!?!?\n--   Returns the starting sub matrix locations which fit inside the larger matrix for the\n--   convolution. Takes into account the stride and kernel size.\nfittingStarts :: Int -> Int -> Int -> Int -> Int -> Int -> [(Int,Int)]\nfittingStarts nrows kernelrows steprows ncols kernelcols stepcolsh =\n  let rs = fittingStart nrows kernelrows steprows\n      cs = fittingStart ncols kernelcols stepcolsh\n      ls = sequence [rs, cs]\n  in  fmap (\\[a,b] -> (a,b)) ls\n\n-- | Returns the starting sub vector which fit inside the larger vector for the\n--   convolution. Takes into account the stride and kernel size.\nfittingStart :: Int -> Int -> Int -> [Int]\nfittingStart width kernel steps =\n  let go left | left + kernel < width\n              = left : go (left + steps)\n              | left + kernel == width\n              = [left]\n              | otherwise\n              = []\n  in go 0\n\nconvBackProp :: Matrix RealNum -> Int -> Int -> Int \n             -> Matrix RealNum -> Int -> Int -> Int \n             -> Matrix RealNum -> Int -> Int\n             -> Int -> Int \n             -> (Matrix RealNum, Matrix RealNum)\nconvBackProp input channels inRows inCols kernel filters kernelRows kernelCols dout outRows outCols strideRows strideCols =\n  let fs       = [0..filters-1]\n      hs       = [let h_start = h * strideRows in (h, h_start) | h <- [0..outRows - 1]]\n      ws       = [let w_start = w * strideCols in (w, w_start) | w <- [0..outCols - 1]]\n      fhws     = [(f, h, w) | f <- fs, h <- hs, w <- ws]\n      dX_accum = concatMap dxLoop fhws\n      dX       = accum (konst 0 (channels * inRows, inCols)) (+) dX_accum\n      dW_accum = concatMap dwLoop fhws\n      dW       = accum (konst 0 (kernelRows * kernelCols * channels, filters)) (+) dW_accum\n  in (dX, dW)\n  where \n    dxLoop (f, (h, h_start), (w, w_start)) \n      = [ ((c * inRows + h_start + i, w_start + j), (indexAtdOut f h w) * (indexAtKernel f c i j)) | i <- [0..kernelRows-1], j <- [0..kernelCols-1], c <- [0..channels-1]]\n    \n    dwLoop (f, (h, h_start), (w, w_start))\n      = [ ((c * kernelRows * kernelCols + i * kernelCols + j, f), (indexAtdOut f h w) * (indexAtIn c (h_start + i) (w_start + j))) | i <- [0..kernelRows-1], j <- [0..kernelCols-1], c <- [0..channels-1]]\n\n    indexAtIn       c x y = input `atIndex` (c * inRows + x, y)\n    indexAtdOut     c x y = dout `atIndex` (c * outRows + x, y)\n    indexAtKernel f c x y = kernel `atIndex` (c * kernelRows * kernelCols + x * kernelCols + y, f)\n\nconvForwards :: Matrix RealNum -> Int -> Int -> Int \n             -> Matrix RealNum -> Int -> Int -> Int \n             -> Int -> Int\n             -> Int -> Int \n             -> Matrix RealNum\nconvForwards input channels inRows inCols kernel filters kernelRows kernelCols outRows outCols strideRows strideCols =\n  let fs     = [0..filters-1]\n      hs     = [(h, h * strideRows) | h <- [0..outRows - 1], h * strideRows + kernelRows - 1 < inRows]\n      ws     = [(w, w * strideCols) | w <- [0..outCols - 1], w * strideCols + kernelCols - 1 < inCols]\n      fhws   = [(f, h, w) | f <- fs, h <- hs, w <- ws]\n      accums = map loopIter fhws\n  in accum (konst 0 (filters * outRows, outCols)) (+) accums\n  where \n    loopIter (f, (h, h_start), (w, w_start)) \n      = ((f * outRows + h, w), sum [ (indexAtKernel f c i j) * (indexAtIn c (h_start + i) (w_start + j)) | i <- [0..kernelRows-1], j <- [0..kernelCols-1], c <- [0..channels-1]])\n    \n    indexAtIn c x y = input `atIndex` (c * inRows + x, y)\n    indexAtKernel f c x y = kernel `atIndex` (c * kernelRows * kernelCols + x * kernelCols + y, f)\n\nconvForwardsWithPadding :: Matrix RealNum -> Int -> Int -> Int \n                        -> Matrix RealNum -> Int -> Int -> Int \n                        -> Int -> Int\n                        -> Int -> Int\n                        -> Int -> Int -> Int -> Int  \n                        -> Matrix RealNum\nconvForwardsWithPadding input channels inRows inCols kernel filters kernelRows kernelCols outRows outCols strideRows strideCols padl padt padr padb =\n  let accums      = [((c * padded_r + x + padt, y + padl), input `atIndex` (c * inRows + x, y)) | x <- [0..inRows-1], y <- [0..inCols-1], c <- [0..channels-1]]\n      padded_r    = inRows + padt + padb\n      padded_c    = inCols + padl + padr\n      paddedInput = accum (konst 0 (channels * padded_r, padded_c)) (+) accums\n  in convForwards paddedInput channels padded_r padded_c kernel filters kernelRows kernelCols outRows outCols strideRows strideCols \n\nconvBackPropWithPadding :: Matrix RealNum -> Int -> Int -> Int \n                        -> Matrix RealNum -> Int -> Int -> Int \n                        -> Matrix RealNum -> Int -> Int\n                        -> Int -> Int \n                        -> Int -> Int -> Int -> Int  \n                        -> (Matrix RealNum, Matrix RealNum)\nconvBackPropWithPadding input channels inRows inCols kernel filters kernelRows kernelCols dout outRows outCols strideRows strideCols padl padt padr padb =\n  let accums      = [((c * padded_r + x + padt, y + padl), input `atIndex` (c * inRows + x, y)) | x <- [0..inRows-1], y <- [0..inCols-1], c <- [0..channels-1]]\n      padded_r    = inRows + padt + padb\n      padded_c    = inCols + padl + padr\n      paddedInput = accum (konst 0 (channels * padded_r, padded_c)) (+) accums\n      (dX', dW)   = convBackProp paddedInput channels padded_r padded_c kernel filters kernelRows kernelCols dout outRows outCols strideRows strideCols \n      accums'     = [((c * inRows + x, y), dX' `atIndex` (c * padded_r + x + padt, y + padl)) | x <- [0..inRows-1], y <- [0..inCols-1], c <- [0..channels-1]]\n      dX          = accum (konst 0 (channels * inRows, inCols)) (+) accums'\n  in  (dX, dW)\n\nbiasConvForwards :: Matrix RealNum -> Int -> Int -> Int \n                 -> Matrix RealNum -> Int -> Int -> Int \n                 -> Vector RealNum\n                 -> Int -> Int\n                 -> Int -> Int \n                 -> Matrix RealNum\nbiasConvForwards input channels inRows inCols kernel filters kernelRows kernelCols bias outRows outCols strideRows strideCols =\n  let fs     = [0..filters-1]\n      hs     = [(h, h * strideRows) | h <- [0..outRows - 1], h * strideRows + kernelRows - 1 < inRows]\n      ws     = [(w, w * strideCols) | w <- [0..outCols - 1], w * strideCols + kernelCols - 1 < inCols]\n      fhws   = [(f, h, w) | f <- fs, h <- hs, w <- ws]\n      accums = map loopIter fhws\n  in accum (konst 0 (filters * outRows, outCols)) (+) accums\n  where \n    loopIter (f, (h, h_start), (w, w_start)) \n      = ((f * outRows + h, w), indexAtBias f + sum [ (indexAtKernel f c i j) * (indexAtIn c (h_start + i) (w_start + j)) | i <- [0..kernelRows-1], j <- [0..kernelCols-1], c <- [0..channels-1]])\n    \n    indexAtBias i = bias `atIndex` i\n    indexAtIn c x y = input `atIndex` (c * inRows + x, y)\n    indexAtKernel f c x y = kernel `atIndex` (c * kernelRows * kernelCols + x * kernelCols + y, f)\n\nbiasConvForwardsWithPadding :: Matrix RealNum -> Int -> Int -> Int \n                        -> Matrix RealNum -> Int -> Int -> Int \n                        -> Vector RealNum\n                        -> Int -> Int\n                        -> Int -> Int\n                        -> Int -> Int -> Int -> Int  \n                        -> Matrix RealNum\nbiasConvForwardsWithPadding input channels inRows inCols kernel filters kernelRows kernelCols bias outRows outCols strideRows strideCols padl padt padr padb =\n  let accums      = [((c * padded_r + x + padt, y + padl), input `atIndex` (c * inRows + x, y)) | x <- [0..inRows-1], y <- [0..inCols-1], c <- [0..channels-1]]\n      padded_r    = inRows + padt + padb\n      padded_c    = inCols + padl + padr\n      paddedInput = accum (konst 0 (channels * padded_r, padded_c)) (+) accums\n  in biasConvForwards paddedInput channels padded_r padded_c kernel filters kernelRows kernelCols bias outRows outCols strideRows strideCols \n\nbiasConvBackProp :: Matrix RealNum -> Int -> Int -> Int \n                 -> Matrix RealNum -> Int -> Int -> Int \n                 -> Matrix RealNum -> Int -> Int\n                 -> Int -> Int \n                 -> (Matrix RealNum, Matrix RealNum, Vector RealNum)\nbiasConvBackProp input channels inRows inCols kernel filters kernelRows kernelCols dout outRows outCols strideRows strideCols =\n  let (dX, dW)  = convBackProp input channels inRows inCols kernel filters kernelRows kernelCols dout outRows outCols strideRows strideCols\n      db_accums = [ (f, sum [ indexAtdOut f i j | i <- [0..outRows-1], j <- [0..outCols-1]]) | f <- [0..filters-1]]\n      db        = accum (konst 0 filters) (+) db_accums\n  in (dX, dW, db)\n  where \n    indexAtdOut     c x y = dout `atIndex` (c * outRows + x, y)\n\nbiasConvBackPropWithPadding :: Matrix RealNum -> Int -> Int -> Int \n                            -> Matrix RealNum -> Int -> Int -> Int \n                            -> Matrix RealNum -> Int -> Int\n                            -> Int -> Int \n                            -> Int -> Int -> Int -> Int  \n                            -> (Matrix RealNum, Matrix RealNum, Vector RealNum)\nbiasConvBackPropWithPadding input channels inRows inCols kernel filters kernelRows kernelCols dout outRows outCols strideRows strideCols padl padt padr padb =\n  let accums        = [((c * padded_r + x + padt, y + padl), input `atIndex` (c * inRows + x, y)) | x <- [0..inRows-1], y <- [0..inCols-1], c <- [0..channels-1]]\n      padded_r      = inRows + padt + padb\n      padded_c      = inCols + padl + padr\n      paddedInput   = accum (konst 0 (channels * padded_r, padded_c)) (+) accums\n      (dX', dW, db) = biasConvBackProp paddedInput channels padded_r padded_c kernel filters kernelRows kernelCols dout outRows outCols strideRows strideCols \n      accums'       = [((c * inRows + x, y), dX' `atIndex` (c * padded_r + x + padt, y + padl)) | x <- [0..inRows-1], y <- [0..inCols-1], c <- [0..channels-1]]\n      dX            = accum (konst 0 (channels * inRows, inCols)) (+) accums'\n  in  (dX, dW, db)\n\nnaiveFullyConnectedRunForwards :: forall i o. (KnownNat i, KnownNat o) \n                               => H.L o i       -- Weights\n                               -> H.R o         -- Biases\n                               -> H.R i         -- Input\n                               -> (H.R i, H.R o)  -- (Tape, Output)\nnaiveFullyConnectedRunForwards w b i = (i, b + (w H.#> i))\n\nnaiveFullyConnectedBackprop :: forall i o. (KnownNat i, KnownNat o) \n                            => H.L o i             -- Weights\n                            -> (H.R i, H.R o)        -- (Tape, Output)\n                            -> (H.L o i, H.R o, H.R i) -- (NablaW, NablaB, derivatives)\nnaiveFullyConnectedBackprop w (tape, out) = (w', b', d)\n  where\n    b' = out\n    w' = H.outer out tape\n    d  = (H.tr w) H.#> out\n\n-- Implementation reference: https://papers.nips.cc/paper/2012/file/c399862d3b9d6b76c8436e924a68c45b-Paper.pdf\nnaiveLRNForwards :: RealNum -> RealNum -> RealNum -> Int -> [[[RealNum]]] -> [[[RealNum]]]\nnaiveLRNForwards a b k n values = [\n    [[ g ch ro co | co <- [0..length (values!!ch!!ro) - 1] ] | ro <- [0..length (values!!ch) - 1]] | ch <- [0..cs-1]\n  ]\n  where\n    cs = length values\n    f ch ro co = values!!ch!!ro!!co\n    g ch ro co = (f ch ro co) / den\n      where\n        den  = den' ** b\n        sub = floor ((fromIntegral n) / 2     :: RealNum)\n        add = floor ((fromIntegral n - 1) / 2 :: RealNum)\n        lower = maximum [0, ch - sub]\n        upper = minimum [cs - 1, ch + add]\n        summation = sum [ (f j ro co) ** 2 | j <- [lower..upper]]\n        den' = k + a * summation\n\nnaiveLRNBackwards :: RealNum         -- a\n                    -> RealNum       -- b\n                    -> RealNum       -- k\n                    -> Int          -- n\n                    -> [[[RealNum]]] -- inputs\n                    -> [[[RealNum]]] -- backpropagated error\n                    -> [[[RealNum]]] -- error to propagate further\nnaiveLRNBackwards a b k n values errs = [\n    [[ ng ch ro co | co <- [0..length (values!!ch!!ro) - 1] ] | ro <- [0..length (values!!ch) - 1]] | ch <- [0..cs-1]\n  ]\n  where\n    cs = length values\n    f  ch ro co = values!!ch!!ro!!co\n    nf ch ro co = errs!!ch!!ro!!co\n    c ch ro co = den\n      where\n        sub = floor ((fromIntegral n) / 2     :: RealNum)\n        add = floor ((fromIntegral n - 1) / 2 :: RealNum)\n        lower = maximum [0, ch - sub]\n        upper = minimum [cs - 1, ch + add]\n        summation = sum [ (f j ro co) ** 2 | j <- [lower..upper]]\n        den = k + a * summation\n    ng ch ro co = t1 - t2\n      where\n        t1 = (c ch ro co) ** (-b) * (nf ch ro co)\n        t2 = 2 * b * a * (f ch ro co) * (c ch ro co) ** (-b - 1) * s\n        s  = sum [(f q ro co) * (nf q ro co) | q <- [lower..upper]]\n\n        sub = floor ((fromIntegral n) / 2     :: RealNum)\n        add = floor ((fromIntegral n - 1) / 2 :: RealNum)\n        lower = maximum [0, ch - sub]\n        upper = minimum [cs - 1, ch + add]\n", "meta": {"hexsha": "ac8738e6b6f046c4529a0fb4c09ec54eefa043d0", "size": 17679, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Layers/Internal/Reference.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "test/Test/Grenade/Layers/Internal/Reference.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Test/Grenade/Layers/Internal/Reference.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.4200626959, "max_line_length": 202, "alphanum_fraction": 0.5727699531, "num_tokens": 5291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4925531601666521}}
{"text": "{-# LANGUAGE BangPatterns          #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE QuantifiedConstraints #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TupleSections         #-}\nmodule Q.Stochastic.Process\n        where\nimport           Control.Monad\nimport           Control.Monad.State\nimport           Data.List             (foldl')\nimport           Data.RVar\nimport           Data.Random\nimport           Numeric.LinearAlgebra\n\nrwalkState :: RVarT (State Double) Double\nrwalkState = do\n    prev <- lift get\n    change  <- rvarT StdNormal\n\n    let new = prev + change\n    lift (put new)\n    return new\n\ntype Time = Double\n\n-- Dont know why this wasn't done.\n-- Is there an easier way to do this where we either lift or return?\ninstance (Num a) => Num (RVarT m a) where\n  (+) = liftM2 (+)\n  (-) = liftM2 (-)\n  (*) = liftM2 (*)\n  abs = liftM abs\n  signum = liftM signum\n  fromInteger x = return $ fromInteger x\n\n\n\n-- |Discretization of stochastic process over given interval\nclass (Num b) => Discretize d b where\n  -- |Discretization of the drift process.\n  dDrift  :: (StochasticProcess a b) => a -> d -> (Time, b) -> RVar b\n  -- |Discretization of the diffusion process.\n  dDiff   :: (StochasticProcess a b) => a -> d -> (Time, b) -> RVar b\n  -- |dt used.\n  dDt     :: (StochasticProcess a b) => a -> d -> (Time, b) -> Time\n\n\n-- |A stochastic process of the form \\(dX_t = \\mu(X_t, t)dt + \\sigma(S_t, t)dB_t \\)\nclass (Num b) => StochasticProcess a b where\n  -- |The process drift.\n  pDrift  :: a -> (Time, b) -> RVar b\n  -- |The process diffusion.\n  pDiff   :: a -> (Time, b) -> RVar b\n\n  -- |Evolve a process from a given state to a given time.\n  pEvolve :: (Discretize d b) => a         -- ^The process\n                             -> d         -- ^Discretization scheme\n                             -> (Time, b) -- ^Initial state\n                             -> Time      -- ^Target time t.\n                             -> RVar b    -- ^\\(dB_i\\).\n                             -> RVar b    -- ^\\(X(t)\\).\n  pEvolve p disc s0@(t0, x0) t dw = do\n    if t0 >= t then return x0 else do\n      s'@(t', b') <- pEvolve' p disc s0 dw\n      if t' >= t then return b' else pEvolve p disc s' t dw\n\n  -- |Similar to evolve, but evolves the process with the discretization scheme \\(dt\\).\n  pEvolve' :: (Discretize d b, Num b) => a -> d -> (Time, b) -> RVar b -> RVar (Time, b)\n  pEvolve' process discr s@(t, b) dw = do\n    let !newT = t + dDt process discr s\n        !newX = do\n               drift <- dDrift process discr s\n               diff  <- dDiff process discr s\n               dw' <- dw\n               return $ b + drift + diff * dw'\n        newX :: RVar b\n\n    (newT,) <$>  newX\n\n-- |Geometric Brownian motion\ndata GeometricBrownian = GeometricBrownian {\n    gbDrift :: Double -- ^Drift\n  , gbDiff  :: Double -- ^Vol\n} deriving (Show)\n\n\ninstance StochasticProcess GeometricBrownian Double where\n--  pDrift :: GeometricBrownian -> (Time, Double) -> RVar Double\n  pDrift p (_, x) = return $ gbDrift p * x -- drift is prpotional to the spot.\n  pDiff  p (_, x) = return $ gbDiff p  * x -- diffisuion is also prportional to the spot.\n\n\n-- | Ito process\ndata ItoProcess = ItoProcess {\n        ipDrift :: (Time, Double) -> Double,\n        ipDiff  :: (Time, Double) -> Double\n}\n", "meta": {"hexsha": "4c5b236daf7e2969c2c37a18499eb5332f993658", "size": 3286, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Q/Stochastic/Process.hs", "max_stars_repo_name": "ghais/lowq", "max_stars_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-01T17:50:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T18:06:22.000Z", "max_issues_repo_path": "src/Q/Stochastic/Process.hs", "max_issues_repo_name": "ghais/lowq", "max_issues_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "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/Q/Stochastic/Process.hs", "max_forks_repo_name": "ghais/lowq", "max_forks_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5306122449, "max_line_length": 89, "alphanum_fraction": 0.5651247718, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4924981882887363}}
{"text": "-- |\n-- Module      : Tiler.hs\n-- Description : \n-- Copyright   : (c) Jonatan H Sundqvist, 2015\n-- License     : MIT\n-- Maintainer  : Jonatan H Sundqvist\n-- Stability   : experimental|stable\n-- Portability : POSIX (not sure)\n-- \n\n-- Created July 9 2015\n\n-- TODO | - \n--        - \n\n-- SPEC | -\n--        -\n\n\n\nmodule Tiler (renderPathWithJoints) where \n\n\n\n---------------------------------------------------------------------------------------------------\n-- We'll need these\n---------------------------------------------------------------------------------------------------\nimport Control.Monad (mapM_, forM_)\nimport Data.Complex\n\nimport qualified Graphics.Rendering.Cairo as Cairo\n\nimport qualified Southpaw.Picasso.Palette as Palette\nimport Southpaw.Utilities.Utilities (pairwise)\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Data\n---------------------------------------------------------------------------------------------------\n\u03c0 = pi\n\u03c4 = 2*\u03c0\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Types\n---------------------------------------------------------------------------------------------------\ntype Path = [Complex Double]\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Functions\n---------------------------------------------------------------------------------------------------\nrenderPathWithJoints :: Palette.Colour -> Palette.Colour -> Double -> Double -> Path -> Cairo.Render ()\nrenderPathWithJoints line joint radius thickness path = do\n\t\n\t-- Render the lines\n\tCairo.setLineWidth thickness\n\tforM_ (pairwise $ path ++ [head path]) $ \\ (fr, to) -> do\n\t\tPalette.choose line\n\t\tCairo.moveTo (realPart fr) (imagPart fr)\n\t\tCairo.lineTo (realPart to) (imagPart to)\n\t\tCairo.stroke\n\n\t-- Render the 'joints'\n\tforM_ path $ \\ (x:+y) -> do\n\t\tPalette.choose joint\n\t\tCairo.arc x y radius 0 \u03c4\n\t\tCairo.fill", "meta": {"hexsha": "956231844d53928222dafbe2ed7d67668818db59", "size": 1980, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Tiler.hs", "max_stars_repo_name": "SwiftsNamesake/Leopardy", "max_stars_repo_head_hexsha": "27de74fe64fa3b131c35b8a6a6ddfb2d60db658b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Tiler.hs", "max_issues_repo_name": "SwiftsNamesake/Leopardy", "max_issues_repo_head_hexsha": "27de74fe64fa3b131c35b8a6a6ddfb2d60db658b", "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/Tiler.hs", "max_forks_repo_name": "SwiftsNamesake/Leopardy", "max_forks_repo_head_hexsha": "27de74fe64fa3b131c35b8a6a6ddfb2d60db658b", "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": 27.8873239437, "max_line_length": 103, "alphanum_fraction": 0.4, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49249592649806645}}
{"text": "{-# language TypeFamilies #-}\n{-# language ScopedTypeVariables #-}\n{-# language RankNTypes #-}\n\n-- | A <https://en.wikipedia.org/wiki/Monus commutative monoid with monus>\n-- is a 'Monoid' equipped with a subtraction operator.\nmodule Data.Monoid.Monus\n  ( Monus(..)\n  , (-)\n  ) where\n\nimport Prelude hiding ((-))\nimport Data.Set (Set)\nimport Data.Complex (Complex(..))\nimport Data.Monoid (Any(..),All(..),Sum(..), Endo(..))\nimport Control.Applicative (liftA2)\nimport Numeric.Natural (Natural)\nimport Data.Foldable\nimport Data.Coerce\n\nimport qualified Prelude as P\nimport qualified Data.Set as S\n\ninfixl 6 -\n\n-- | A commutative monoid that supports subtraction. The following\n-- laws must hold:\n--\n-- > x <> (y - x) = y <> (x - y)\n-- > (x - y) - z = x - (y <> z)\n-- > x - x = mempty\n-- > mempty - x = mempty\nclass Monoid a => Monus a where\n  monus :: a -> a -> a\n\n-- | An infix synonym for 'subtraction'.\n(-) :: Monus a => a -> a -> a\n(-) = monus\n{-# INLINE (-) #-}\n\ninstance Ord a => Monus (Set a) where\n  monus = S.difference\n  {-# INLINE monus #-}\n\n-- | Unlike the subtraction provided by the 'Num' instance of\n-- 'Natural', this subtraction is total.\ninstance (a ~ Natural) => Monus (Sum a) where\n  monus (Sum x) (Sum y) = Sum (if x > y then x P.- y else 0)\n  {-# INLINE monus #-}\n\n-- | Defined as @P - Q = P \u2227 \u00acQ@\ninstance Monus Any where\n  monus (Any x) (Any y) = case x of\n    False -> Any False\n    True -> Any (not y)\n  {-# INLINE monus #-}\n\n-- | Defined as @P - Q = P \u2228 \u00acQ@\ninstance Monus All where\n  monus (All x) (All y) = case x of\n    False -> All (not y)\n    True -> All True\n  {-# INLINE monus #-}\n\ninstance forall a. Monus a => Monus (Endo a) where\n  monus = coerce (liftA2 monus :: (a -> a) -> (a -> a) -> (a -> a))\n  {-# INLINE monus #-}\n\ninstance Monus () where\n  monus _ _ = ()\n  {-# INLINE monus #-}\n\ninstance (Monus a, Monus b) => Monus (a,b) where\n  monus (a1,b1) (a2,b2) = (monus a1 a2,monus b1 b2)\n  {-# INLINE monus #-}\n\ninstance (Monus a, Monus b, Monus c) => Monus (a,b,c) where\n  monus (a1,b1,c1) (a2,b2,c2) = (monus a1 a2,monus b1 b2,monus c1 c2)\n  {-# INLINE monus #-}\n\ninstance (Monus a, Monus b, Monus c,Monus d) => Monus (a,b,c,d) where\n  monus (a1,b1,c1,d1) (a2,b2,c2,d2) =\n    (monus a1 a2,monus b1 b2,monus c1 c2,monus d1 d2)\n  {-# INLINE monus #-}\n\ninstance (Monus a, Monus b, Monus c,Monus d,Monus e) => Monus (a,b,c,d,e) where\n  monus (a1,b1,c1,d1,e1) (a2,b2,c2,d2,e2) = \n    (monus a1 a2,monus b1 b2,monus c1 c2,monus d1 d2,monus e1 e2)\n  {-# INLINE monus #-}\n\ninstance Monus b => Monus (a -> b) where\n  monus = liftA2 monus\n  {-# INLINE monus #-}\n\ninstance Monus a => Monus (IO a) where\n  monus = liftA2 monus\n  {-# INLINE monus #-}\n\ninstance Monus a => Monus [a] where\n  monus [] _ = []\n  monus x [] = x\n  monus (x:xs) (y:ys) = monus x y : monus xs ys\n\ninstance Monus a => Monus (Maybe a) where\n  monus = liftA2 monus\n  {-# INLINE monus #-}", "meta": {"hexsha": "bd6dd86f94ae2e0b16ceb5d86e73404b3a462874", "size": 2882, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Monoid/Monus.hs", "max_stars_repo_name": "andrewthad/monus", "max_stars_repo_head_hexsha": "6903fec25182dbaad88ed08717209c7227f85ec3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-05-27T00:13:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-12T19:49:40.000Z", "max_issues_repo_path": "src/Data/Monoid/Monus.hs", "max_issues_repo_name": "andrewthad/monus", "max_issues_repo_head_hexsha": "6903fec25182dbaad88ed08717209c7227f85ec3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-05-27T16:00:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-19T23:55:01.000Z", "max_forks_repo_path": "src/Data/Monoid/Monus.hs", "max_forks_repo_name": "andrewthad/monus", "max_forks_repo_head_hexsha": "6903fec25182dbaad88ed08717209c7227f85ec3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1886792453, "max_line_length": 79, "alphanum_fraction": 0.6034004164, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4923376642688862}}
{"text": "{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE OverloadedStrings     #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE PolyKinds             #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE TypeApplications      #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE AllowAmbiguousTypes   #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-# LANGUAGE ConstraintKinds #-}\nmodule Frames.VegaLite.Regression\n  (\n    Frame2DRegressionScatterFit (..)\n  , frameScatterWithFit\n  , keyedLayeredFrameScatterWithFit\n  , scatterWithFit\n  , FitToPlot (..)\n  , regressionCoefficientPlot\n  , regressionCoefficientPlotMany\n  ) where\n\nimport qualified Frames.VegaLite.Utils as FV\nimport qualified Frames.Transform as FT\nimport qualified Frames.Regression as FR\nimport qualified Math.Regression.Regression as RE \n\nimport qualified Control.Foldl          as FL\nimport qualified Data.Text              as T\nimport qualified Data.Vinyl             as V\nimport qualified Data.Vinyl.Functor     as V\nimport qualified Data.Vinyl.TypeLevel   as V\nimport qualified Frames                 as F\nimport qualified Frames.Melt            as F\nimport qualified Graphics.Vega.VegaLite as GV\nimport qualified Data.List              as List\nimport Text.Printf (printf)\n\nimport qualified Statistics.Types               as S\n\n\n#if MIN_VERSION_hvega(0,4,0)\ngvTitle :: Text -> GV.PropertySpec\ngvTitle x = GV.title x []\n#else\ngvTitle :: Text -> (GV.VLProperty, GV.VLSpec)\ngvTitle = GV.title\n#endif\n\n  \n-- | Plot regression coefficents with error bars\n-- | Flex version handles a foldable of results so we can, e.g., \n-- | 1. Compare across time or other variable in the data\n-- | 2. Compare different fitting methods for the same data\n\n-- TODO: Fix replicated y-axis ticks.  There since we need the difference between them (trailing \"'\"s) to provide y-offset\n-- to the different results.  Otherwise they would overlap in y.  Maybe fix by switching to layers and only having Y-axis labels\n-- on 0th?\n\n-- TODO: Make this typed?  Using a regression result with typed parameters?  Power-to-weight? \n\nregressionCoefficientPlot :: T.Text -> [T.Text] -> RE.RegressionResult Double -> S.CL Double -> GV.VegaLite\nregressionCoefficientPlot title names r cl = regressionCoefficientPlotFlex False id title names (V.Identity (\"\",r)) cl\n\nregressionCoefficientPlotMany :: Foldable f\n                              => (k -> T.Text) -> T.Text -> [T.Text] -> f (k, RE.RegressionResult Double) -> S.CL Double -> GV.VegaLite\nregressionCoefficientPlotMany = regressionCoefficientPlotFlex True \n\nregressionCoefficientPlotFlex :: Foldable f\n                              => Bool -> (k -> Text) -> T.Text -> [T.Text] -> f (k, RE.RegressionResult Double) -> S.CL Double -> GV.VegaLite\nregressionCoefficientPlotFlex haveLegend printKey title names results cl =\n  let toRow m (RE.NamedEstimate n e eci _) = [(\"Parameter\",GV.Str (n <> T.replicate m \"'\")), (\"Estimate\",GV.Number e), (\"Confidence\",GV.Number eci)]\n      addKey k l = (\"Key\", GV.Str $ printKey k) : l\n      dataRowFold = FL.Fold (\\(l,n) (k,regRes) -> (l ++ fmap (flip GV.dataRow [] . addKey k . toRow n) (RE.namedEstimates names regRes cl), n+1)) ([],0) (GV.dataFromRows [] . List.concat . fst)\n      dat = FL.fold dataRowFold results\n      xLabel = \"Estimate (with \" <> T.pack (printf \"%2.0f\" (100 * S.confidenceLevel cl)) <> \"% confidence error bars)\"\n      estimateXEnc = GV.position GV.X [GV.PName \"Estimate\", GV.PmType GV.Quantitative, GV.PAxis [GV.AxTitle xLabel]]\n      estimateYEnc = GV.position GV.Y [GV.PName \"Parameter\", GV.PmType GV.Ordinal]\n      handleLegend l = if haveLegend then l else GV.MLegend [] : l\n      estimateColorEnc = GV.color $ handleLegend  [GV.MName \"Key\", GV.MmType GV.Nominal]\n      estimateEnc = estimateXEnc . estimateYEnc . estimateColorEnc\n      estLoCalc = \"datum.Estimate - datum.Confidence/2\"\n      estHiCalc = \"datum.Estimate + datum.Confidence/2\"\n      calcEstConf = GV.calculateAs estLoCalc \"estLo\" . GV.calculateAs estHiCalc \"estHi\"\n      estConfLoEnc = GV.position GV.X [GV.PName \"estLo\", GV.PmType GV.Quantitative, GV.PAxis [GV.AxTitle \"\"]]\n      estConfHiEnc = GV.position GV.X2 [GV.PName \"estHi\", GV.PmType GV.Quantitative, GV.PAxis [GV.AxTitle \"\"]]\n      estConfEnc = estConfLoEnc . estConfHiEnc . estimateYEnc . estimateColorEnc\n      estSpec = GV.asSpec [(GV.encoding . estimateEnc) [], GV.mark GV.Point []]\n      confSpec = GV.asSpec [(GV.encoding . estConfEnc) [], GV.mark GV.Rule []]\n      configuration = GV.configure\n        . GV.configuration (GV.ViewStyle [GV.ViewContinuousWidth 800, GV.ViewContinuousHeight 400]) . GV.configuration (GV.PaddingStyle $ GV.PSize 50)\n      vl = GV.toVegaLite\n        [\n          gvTitle title\n        , (GV.transform . calcEstConf) []\n        , GV.layer [estSpec, confSpec]\n        , dat\n        , configuration []\n        ]\n  in vl \n\n--\n{-\ntype family WeightElemOf (rs :: [(Symbol, Type)]) (w :: (Symbol, Type)) :: Constraint where\n  WeightElemOf _ FR.Unweighted = ()\n  WeightElemOf rs w  = F.ElemOf rs w\n-}\n\nframeRegressionError :: forall y wc as w rs. FR.FrameRegressionResult y wc as w rs -> Error rs\nframeRegressionError (FR.FrameUnweightedRegressionResult _) = const 0\nframeRegressionError (FR.FrameWeightedRegressionResult wf _) = (\\r -> 1/(wf $ F.rgetField @w r))\n\n\ntype ScatterFitConstraints x y = ( F.ColumnHeaders '[x]\n                                 , F.ColumnHeaders '[y]\n                                 , FV.ToVLDataValue (F.ElField x)\n                                 , FV.ToVLDataValue (F.ElField y)\n                                 , V.KnownField y\n                                 , Real (V.Snd y)\n                                 )\n\ntype ScatterFitC1 rs x y = ( F.ElemOf (rs V.++ [YError,YFit,YFitError]) x\n                           , F.ElemOf (rs V.++ [YError,YFit,YFitError]) y\n                           , F.ElemOf (rs V.++ [YError,YFit,YFitError]) YError\n                           , F.ElemOf (rs V.++ [YError,YFit,YFitError]) YFit\n                           , F.ElemOf (rs V.++ [YError,YFit,YFitError]) YFitError)\n                           \nclass Frame2DRegressionScatterFit rs a where\n  regressionResultToError :: a -> Error rs\n  regressionResultToFit :: Maybe T.Text -> a -> S.CL Double -> FitToPlot rs\n--  scatterPlot :: (Foldable f, Functor f) => T.Text -> Maybe T.Text -> a -> Double -> f (F.Record rs) -> GV.VegaLite\n  scatterPlotSpec :: (Foldable f, Functor f) => Maybe T.Text -> a -> S.CL Double -> f (F.Record rs) -> GV.VLSpec\n\nframeScatterWithFit :: (Frame2DRegressionScatterFit rs a, Foldable f, Functor f)\n                    => T.Text -> Maybe T.Text -> a -> S.CL Double -> f (F.Record rs) -> GV.VegaLite\nframeScatterWithFit title fitNameM frr cl frame =\n  let configuration = GV.configure\n        . GV.configuration (GV.ViewStyle [GV.ViewContinuousWidth 800, GV.ViewContinuousHeight 400]) . GV.configuration (GV.PaddingStyle $ GV.PSize 50)\n      swfSpec = GV.layer [scatterPlotSpec fitNameM frr cl frame]\n  in GV.toVegaLite [configuration [], swfSpec, gvTitle title]\n\nkeyedLayeredFrameScatterWithFit :: (Frame2DRegressionScatterFit rs a, Foldable f, Functor f, Foldable g, Functor g) \n  => T.Text -> (k -> T.Text) -> g (k, a) -> S.CL Double -> f (F.Record rs) -> GV.VegaLite\nkeyedLayeredFrameScatterWithFit title keyText keyedFits cl dat =\n  let toSpec (k, a) = scatterPlotSpec (Just $ keyText k) a cl dat\n      specs = FL.fold FL.list (fmap toSpec keyedFits)\n      configuration = GV.configure\n        . GV.configuration (GV.ViewStyle [GV.ViewContinuousWidth 800, GV.ViewContinuousHeight 400]) . GV.configuration (GV.PaddingStyle $ GV.PSize 50)\n  in GV.toVegaLite [configuration [], GV.layer specs, gvTitle title]\n\ninstance ( V.KnownField x\n         , Real (V.Snd x)\n         , ScatterFitConstraints x y\n         , ScatterFitC1 rs x y\n         , F.ElemOf (rs V.++ [YError,YFit,YFitError]) x\n         , F.ElemOf (rs V.++ [YError,YFit,YFitError]) y\n         , F.ElemOf rs x\n         , F.ElemOf rs y\n         , V.KnownField w\n         , rs F.\u2286 rs\n         ) => Frame2DRegressionScatterFit rs (FR.FrameRegressionResult y 'True '[x] w rs) where\n  regressionResultToError = frameRegressionError\n  regressionResultToFit fitNameM frr cl =\n    let label = fromMaybe \"fit\" fitNameM\n        dof = RE.degreesOfFreedom (FR.regressionResult frr)\n        predF = RE.predictFromEstimateAtConfidence dof frr cl        \n    in FitToPlot label predF\n\n--  scatterPlot title fitNameM frr ci frame = \n--    scatterWithFit @x @y @rs @rs (regressionResultToError frr) (regressionResultToFit fitNameM frr ci) Nothing title frame\n    \n  scatterPlotSpec fitNameM frr cl frame = \n      scatterWithFitSpec @x @y @rs @rs (regressionResultToError frr) (regressionResultToFit fitNameM frr cl) Nothing frame\n\n\n-- in this case we have y = a(x1) + b(x2) so we plot (y/x1) vs (a + b(x1/x2))\ntype YOverX1 = \"y_over_x1\" F.:-> Double\ntype X2OverX1 = \"x2_over_x1\" F.:-> Double\n\ninstance ( F.ElemOf rs x1\n         , F.ElemOf rs x2\n         , F.ElemOf rs y\n         , V.KnownField y         \n         , V.KnownField x1\n         , V.KnownField x2\n         , V.KnownField w\n         , Real (V.Snd x1)\n         , Real (V.Snd x2)\n         , Real (V.Snd y)\n         , F.ElemOf [x1,x2] x1\n         , F.ElemOf [x1,x2] x2\n         , F.ElemOf (rs V.++ [YOverX1, X2OverX1]) x1\n         , F.ElemOf (rs V.++ [YOverX1, X2OverX1]) x2\n         , F.ElemOf (rs V.++ [YOverX1, X2OverX1]) y\n         , F.ElemOf (rs V.++ [YOverX1, X2OverX1]) X2OverX1\n         , F.ElemOf (rs V.++ [YOverX1, X2OverX1]) YOverX1\n         , rs F.\u2286 (rs V.++  [YOverX1, X2OverX1])\n         , ScatterFitC1 (rs V.++ [YOverX1, X2OverX1]) YOverX1 X2OverX1\n         ) => Frame2DRegressionScatterFit rs (FR.FrameRegressionResult y 'False '[x1,x2] w rs) where\n  regressionResultToError frr =\n    let x1 = realToFrac . F.rgetField @x1\n    in (\\r -> frameRegressionError frr r/x1 r)\n  \n  regressionResultToFit fitNameM frr cl =\n    let label = fromMaybe \"fit\" fitNameM\n        dof = RE.degreesOfFreedom (FR.regressionResult frr)\n        predF r =\n          let x1 = realToFrac $ F.rgetField @x1 r\n              (y,dy) = RE.predictFromEstimateAtConfidence dof frr cl r\n          in (y/x1, dy/x1)\n    in FitToPlot label predF    \n\n  scatterPlotSpec fitNameM frr cl frame =\n    let mut :: F.Record rs -> F.Record [YOverX1, X2OverX1]\n        mut r =\n          let y = F.rgetField @y r\n              x1 = F.rgetField @x1 r\n              x2 = F.rgetField @x2 r\n          in (realToFrac y/realToFrac x1) F.&: (realToFrac x2/realToFrac x1) F.&: V.RNil\n        mutData = fmap (FT.mutate mut) frame\n        yName = FV.colName @y\n        x1Name = FV.colName @x1\n        x2Name = FV.colName @x2\n        xLabel = x2Name <> \"/\" <> x1Name\n        yLabel = yName <> \"/\" <> x1Name\n    in scatterWithFitSpec @X2OverX1 @YOverX1 @(rs V.++ [YOverX1,X2OverX1]) @rs (regressionResultToError @rs frr) (regressionResultToFit @rs fitNameM frr cl) (Just (xLabel,yLabel)) mutData\n\n{-    \nframe2DRegressionScatter :: forall x y rs a f. (Foldable f, Frame2DRegressionScatterFit rs x y a)\n  => T.Text -> Maybe T.Text -> a -> Double -> f (F.Record rs) -> GV.VegaLite    \nframe2DRegressionScatter title fitNameM frr ci frame =\n-}\n\n--\ntype YError = \"yError\" F.:-> Double\ntype YFit = \"yFit\" F.:-> Double\ntype YFitError = \"yFitError\" F.:->Double\n\ntype Error rs = (F.Record rs -> Double)\ndata FitToPlot rs = FitToPlot { fitLabel :: T.Text, fitFunction :: F.Record rs -> (Double, Double) }\n\n-- | 2D Scatter of Data with calculated error and fit function.  \n-- | Use TypeApplications to specify x and y columns for scatter and then provide calculated error and fit.\n-- | Since both calculations use the record itself as the domain, you can put the error and fit into the record and just use\n-- | field selection.  But this allows more flexibility and doesn't require adding things to the input frame record just for the plot.\n\nscatterWithFit :: forall x y rs as f. ( ScatterFitConstraints x y\n                                      , as F.\u2286 rs\n                                      , ScatterFitC1 rs x y\n                                      , Foldable f)\n               => Error as -> FitToPlot as -> Maybe (T.Text, T.Text) -> Text -> f (F.Record rs) -> GV.VegaLite\nscatterWithFit err fit axisLabelsM title frame =\n  let configuration = GV.configure\n        . GV.configuration (GV.ViewStyle [GV.ViewContinuousWidth 800, GV.ViewContinuousHeight 400]) . GV.configuration (GV.PaddingStyle $ GV.PSize 50)\n      swfSpec = GV.specification $ scatterWithFitSpec @x @y @rs @as @f err fit axisLabelsM frame\n  in GV.toVegaLite [configuration [], swfSpec, gvTitle title]\n  \nscatterWithFitSpec :: forall x y rs as f. ( ScatterFitConstraints x y\n                                          , as F.\u2286 rs\n                                          , ScatterFitC1 rs x y\n                                          , Foldable f)\n               => Error as -> FitToPlot as -> Maybe (T.Text, T.Text) -> f (F.Record rs) -> GV.VLSpec\nscatterWithFitSpec err fit axisLabelsM frame =  \n  let mut :: F.Record rs -> F.Record '[YError, YFit, YFitError]\n      mut r =\n        let a = F.rcast r\n            (f,fe) = fitFunction fit a\n        in err a F.&: f F.&: fe F.&: V.RNil\n      vegaDat = FV.recordsToVLData (F.rcast @[x,y,YError,YFit,YFitError] . FT.mutate mut) frame\n  in scatterWithFitSpec' @x @y @YError @YFit @YFitError axisLabelsM (fitLabel fit) vegaDat\n\n{-\nscatterWithFit' :: forall x y ye fy fye. ( F.ColumnHeaders '[x]\n                                         , F.ColumnHeaders '[y]\n                                         , F.ColumnHeaders '[ye]\n                                         , F.ColumnHeaders '[fy]\n                                         , F.ColumnHeaders '[fye])\n  => Maybe (T.Text, T.Text) -> Text -> Text -> GV.Data -> GV.VegaLite\nscatterWithFit' axisLabelsM title fitLbl dat =\n  let configuration = GV.configure\n        . GV.configuration (GV.ViewStyle [GV.ViewContinuousWidth 800, GV.ViewContinuousHeight 400]) . GV.configuration (GV.PaddingStyle $ GV.PSize 50)\n      swfSpec = GV.specification $ scatterWithFitSpec' @x @y @ye @fy @fye axisLabelsM fitLbl dat\n  in GV.toVegaLite [configuration [], swfSpec, gvTitle title]\n-}\n-- TODO: Add xErrors as well, in scatter and in fit\nscatterWithFitSpec' :: forall x y ye fy fye. ( F.ColumnHeaders '[x]\n                                             , F.ColumnHeaders '[y]\n                                             , F.ColumnHeaders '[ye]\n                                             , F.ColumnHeaders '[fy]\n                                             , F.ColumnHeaders '[fye])\n  => Maybe (T.Text, T.Text) -> Text -> GV.Data -> GV.VLSpec\nscatterWithFitSpec' axisLabelsM fitLbl dat =\n-- create 4 new cols so we can use rules/areas for errors\n  let yLoCalc yName yErrName = \"datum.\" <> yName <> \" - (datum.\" <> yErrName <> \")/2\"\n      yHiCalc yName yErrName = \"datum.\" <> yName <> \" + (datum.\" <> yErrName <> \")/2\"\n      calcs = GV.calculateAs (yLoCalc (FV.colName @y) (FV.colName @ye)) \"yLo\"\n              . GV.calculateAs (yHiCalc (FV.colName @y) (FV.colName @ye)) \"yHi\"\n              . GV.calculateAs (yLoCalc (FV.colName @fy) (FV.colName @fye)) \"fyLo\"\n              . GV.calculateAs (yHiCalc (FV.colName @fy) (FV.colName @fye)) \"fyHi\"\n              . GV.calculateAs (\"\\\"\" <> fitLbl <> \"\\\"\")  \"fitLabel\"\n      xLabel = maybe (FV.colName @x) fst axisLabelsM\n      yLabel = maybe (FV.colName @y) snd axisLabelsM\n      xEnc = GV.position GV.X [FV.pName @x, GV.PmType GV.Quantitative, GV.PAxis [GV.AxTitle xLabel]]\n      yEnc = GV.position GV.Y [FV.pName @y, GV.PmType GV.Quantitative, GV.PAxis [GV.AxTitle yLabel]]\n      yLEnc = GV.position GV.Y [GV.PName \"yLo\", GV.PmType GV.Quantitative]\n      yHEnc = GV.position GV.Y2 [GV.PName \"yHi\", GV.PmType GV.Quantitative]\n--      yErrorEnc = GV.position GV.YError [FV.pName @ye, GV.PmType GV.Quantitative]\n      yFitEnc t = GV.position GV.Y [FV.pName @fy, GV.PmType GV.Quantitative, GV.PAxis [GV.AxTitle t]]\n      yFitLEnc = GV.position GV.Y [GV.PName \"fyLo\", GV.PmType GV.Quantitative]\n      yFitHEnc = GV.position GV.Y2 [GV.PName \"fyHi\", GV.PmType GV.Quantitative]\n      colorEnc = GV.color [GV.MName \"fitLabel\", GV.MmType GV.Nominal]\n  --    yFitErrorEnc = GV.position GV.YError [FV.pName @fye, GV.PmType GV.Quantitative]\n      scatterEnc = xEnc . yEnc \n      scatterBarEnc = xEnc . yLEnc . yHEnc\n      fitEnc t = xEnc . yFitEnc t . colorEnc\n      fitBandEnc = xEnc . yFitLEnc . yFitHEnc . colorEnc \n                  \n      selectScalesS = GV.select (\"scalesS\" <> fitLbl) GV.Interval [GV.BindScales]\n      selectScalesSE = GV.select(\"scalesSE\" <> fitLbl) GV.Interval [GV.BindScales]\n      selectScalesF = GV.select (\"scalesF\" <> fitLbl) GV.Interval [GV.BindScales]\n      selectScalesFE = GV.select (\"scalesFE\" <> fitLbl) GV.Interval [GV.BindScales]\n      scatterSpec = GV.asSpec\n        [\n          (GV.encoding . scatterEnc) []\n        , GV.mark GV.Point []\n        , (GV.selection . selectScalesS) []\n        ]\n      scatterBarSpec = GV.asSpec\n        [\n          (GV.encoding . scatterBarEnc) []\n        , GV.mark GV.Rule []\n        , (GV.selection . selectScalesSE) []\n        ]\n      fitLineSpec = GV.asSpec\n        [\n          (GV.encoding . fitEnc fitLbl) []\n        , GV.mark GV.Line []\n        , (GV.selection . selectScalesF) []\n        ]        \n      fitBandSpec = GV.asSpec\n        [\n          (GV.encoding . fitBandEnc) []\n        , GV.mark GV.Area [GV.MOpacity 0.5, GV.MFillOpacity 0.3]\n        , (GV.selection . selectScalesFE) []\n        ]\n      layers = GV.layer [ scatterSpec, scatterBarSpec, fitLineSpec, fitBandSpec]\n      configuration = GV.configure\n        . GV.configuration (GV.ViewStyle [GV.ViewContinuousWidth 800, GV.ViewContinuousHeight 400]) . GV.configuration (GV.PaddingStyle $ GV.PSize 50)\n      spec =\n        GV.asSpec\n        [\n          (GV.transform . calcs) []\n        , layers\n        , dat\n        , configuration []\n        ]\n  in spec\n\n\n\n", "meta": {"hexsha": "e1675caf480b2ba6ad2f00d3284fce89754af02f", "size": 18075, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Frames/VegaLite/Regression.hs", "max_stars_repo_name": "teto/Frames-utils", "max_stars_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-01-17T21:51:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T08:20:19.000Z", "max_issues_repo_path": "src/Frames/VegaLite/Regression.hs", "max_issues_repo_name": "teto/Frames-utils", "max_issues_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-22T13:50:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T13:50:50.000Z", "max_forks_repo_path": "src/Frames/VegaLite/Regression.hs", "max_forks_repo_name": "teto/Frames-utils", "max_forks_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-04T12:49:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T11:25:11.000Z", "avg_line_length": 49.5205479452, "max_line_length": 193, "alphanum_fraction": 0.6170954357, "num_tokens": 5128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4920729734539147}}
{"text": "module Cas.Internal.Utils\n    ( module Cas.Internal.Utils\n    , module Cas.Internal.Def.Interface\n    , module Cas.Internal.Instances.TFunctor\n    , module Cas.Internal.Instances.TFoldable ) where\n\nimport           PreludeCustom\n\nimport           Cas.Internal.Def.Interface\nimport           Cas.Internal.Instances.TFunctor\nimport           Cas.Internal.Instances.TFoldable\nimport           Data.Ratio\nimport           Data.Complex.Generic\nimport           Cas.Misc\n\nisNegative :: T -> Bool\nisNegative = isF   ?>>> (<0) . tF\n         ||> isMul ?>>- uniqueOnDepth 1 ((&&) <$> isF <*> (<0) . tF)\n         ||>            False\n\n\nselectCs, selectFs, selectXs, selectNonFs  :: T   -> [T]\nlengthCs, lengthFs, lengthXs, lengthNonFs, lengthOpers :: T   -> Int\nselectCs = select isC\nselectFs = select isF\nselectXs = select isX\nselectNonFs = select (not . isF)\nselectNonFLeafs = select isNonFLeaf\nlengthCs = tLength isC\nlengthFs = tLength isF\nlengthXs = tLength isX\nlengthNonFs = tLength (not . isF)\nlengthNonFLeafs = tLength isNonFLeaf\nlengthLeafs = tLength isLeaf\nlengthChilds = tLengthOnDepth 1 (const True)\nlengthOpers = tLength isOper\nlengthNonFlats = tLength (not . isFlat)\nlengthAddChilds = length . concatMap tAddTs . select isAdd\nlengthMulChilds = length . concatMap tMulTs . select isMul\nlengthNotPowAddChilds = length\n                         . concatMap tAddTs\n                         . filter isAdd\n                         . ((:) <$> id\n                                <*> concatMap tToListChilds\n                                  . select (not . isPow) )\nlengthLns = tLength isLn\nlengthNonOpers = tLength (not . isOper)\n\nsubTsAdd :: Add -> [[T]]\nsubTsAdd Add {..} = fmap (\\case (TMul (Mul {..})) -> mulTs; t -> [t]) addTs\n\nsubTsMul :: Mul -> [[T]]\nsubTsMul Mul {..} = fmap (\\case (TAdd (Add {..})) -> addTs; t -> [t]) mulTs\n\n\nsubTs :: T   -> [[T]]\nsubTs TAdd {..}  = subTsAdd tAdd\nsubTs TMul {..}  = subTsMul tMul\nsubTs _          = error \"subTs called on non Add or Mul term\"\n\naddElems, mulElems :: T -> [T]\naddElems = isAdd ?>>> tAddTs ||> return\nmulElems = isMul ?>>> tMulTs ||> return\n\naddFBin, mulFBin :: F -> F -> F\naddFBin w0 w1 = w0+w1\n\nmulFBin w0 w1 = w0*w1\n\naddF, mulF :: [F] -> F\naddF = foldr addFBin zeroF\nmulF = foldr mulFBin oneF\n\nfilterF = fmap tF . filter isF\nfilterNotF = filter (not . isF)\n\naddCollapse, mulCollapse :: [T] -> T\naddCollapse = add\n         . filter (not . isZero)\n         . ((:) <$> TF .  addF . filterF\n                <*> filterNotF)\n\n\nmulCollapse = any isZero ?>>> const zero\n                          ||> mul\n                            . filter (not . isOne)\n                            . ((:) <$> TF . mulF . filterF\n                                   <*> filterNotF)\n\naddBinCollapse, mulBinCollapse, powCollapse :: T -> T -> T\naddBinCollapse x y = addCollapse $ addElems x <> addElems y\nmulBinCollapse x y = mulCollapse $ mulElems x <> mulElems y\n\npowCollapse _    (TF 0)  = one\npowCollapse (TF 0) _     = zero\npowCollapse (TF 1) _     = one\npowCollapse x    (TF 1)  = x\npowCollapse (TF z) (TF w) | imagPart w == 0 && denominator (realPart w) == 1 = f $ z^^(numerator $ realPart w)\npowCollapse x    y           = pow x y\n\n\n\nmulParts :: T -> (F,T)\nmulParts = isF    ?>>>  (,) <$> tF\n                            <*> const one\n       ||> isMul  ?>>> ((,) <$> mulF . filterF\n                            <*> mul . filterNotF ) . tMulTs\n       ||>              (,) <$> const oneF\n                            <*> id\n\npowParts :: T -> (T,T)\npowParts = ((&&) <$> isPow\n                 <*> isF . tPowE) ?>>> (,) <$> tPowE <*> tPowB\n                                   ||> (,) <$> const one <*> id\n-- powParts =  isPow ?>>> (,) <$> tPowE <*> tPowB\n--                                    ||> (,) <$> const one <*> id\n\n", "meta": {"hexsha": "1927be7bffdccda7a5355e572a94250c555079c1", "size": 3751, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Cas/Internal/Utils.hs", "max_stars_repo_name": "vcanadi/cas", "max_stars_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-20T22:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-20T22:42:53.000Z", "max_issues_repo_path": "src/Cas/Internal/Utils.hs", "max_issues_repo_name": "vcanadi/cas", "max_issues_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "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/Cas/Internal/Utils.hs", "max_forks_repo_name": "vcanadi/cas", "max_forks_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "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.7881355932, "max_line_length": 110, "alphanum_fraction": 0.5393228472, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.492007178760272}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RecordWildCards  #-}\n\nmodule AI.Layer\n( LayerDefinition(..)\n, Layer(..)\n, Connectivity\n, RandomTransform\n, Randomization\n\n, showableToLayer\n\n, createLayer\n, scaleLayer\n, randomizeFully\n, randomizeLocally\n, connectFully\n, connectLocally\n\n, randomList\n, boxMuller\n, normals\n, uniforms\n, boundedUniforms\n) where\n\nimport           Data.Binary           (Binary (..), decode, encode)\nimport           AI.Neuron\nimport           Numeric.LinearAlgebra\nimport           System.Random\n\n-- | The LayerDefinition type is an intermediate type initialized by the\n--   library user to define the different layers of the network.\ndata LayerDefinition g = LayerDefinition { neuronDef   :: Neuron\n                                         , neuronCount :: Int\n                                         , connect     :: Connectivity\n                                         , randomize   :: Randomization g\n                                         }\n\n-- | The Layer type, which stores the weight matrix, the bias matrix, and\n--   a neuron type.\ndata Layer = Layer { weightMatrix :: Matrix Double\n                   , biasVector   :: Vector Double\n                   , neuron       :: Neuron\n                   } deriving Show\n\ninstance Binary Layer where\n  put Layer{..} = do put weightMatrix; put biasVector\n  get = do weightMatrix <- get; biasVector <- get; return Layer{..}\n\n-- | Connectivity is the type alias for a function that defines the connective\n--   matrix for two layers (fully connected, convolutionally connected, etc.)\n--   and takes in the number of output and input neurons\ntype Connectivity = Int -> Int -> Matrix Double\n\n-- | Randomiation is the type alias for a function that defines\n--   the initial random values for the weight matrix and bias vector\n--   for two layers and takes in a random transformation on an infinite\n--   stream of uniformly generated numbers, a source of entropy,\n--   the number of output neurons, and the number of input neurons\ntype Randomization g = g -> RandomTransform -> Int -> Int -> (Matrix Double, Vector Double)\n\n-- | ConvolutionalSettings is a type alias for the receptive field size,\n--   stride, zero-padding, the number of filters, the number of dimensions,\n--   the weight and height of the input and output fields\ntype ConvolutionalSettings = Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int\n\n-- | A random transformation type alias. It is a transformation defined on an\n--   infinite list of uniformly distributed random numbers, and returns a list\n--   distributed on the transforming distribution.\ntype RandomTransform = [Double] -> [Double]\n\n-- | The createLayer function takes in a random transformation on an infinite\n--   stream of uniformly generated numbers, a source of entropy, and two\n--   layer definitions, one for the previous layer and one for the next layer.\n--   It returns a layer defined by the Layer type -- a weight matrix, a bias\n--   vector, and a neuron type.\ncreateLayer :: (RandomGen g)\n  => RandomTransform -> g -> LayerDefinition g -> LayerDefinition g -> Layer\ncreateLayer t g layerDef layerDef' =\n  Layer (randomMatrix * connectivity i j)\n        (randomVector * bias)\n        (neuronDef layerDef)\n  where (randomMatrix, randomVector) = randomize layerDef' g t i j\n        i = neuronCount layerDef'\n        j = neuronCount layerDef\n        connectivity = connect layerDef'\n        bias = i |> repeat 1 -- bias connectivity (full)\n\nscaleLayer :: Double -> Layer -> Layer\nscaleLayer factor l =\n  Layer (factor `scale` weightMatrix l) (factor `scale` biasVector l) (neuron l)\n\n-- | The randomizeFully function takes in a source of entropy, the number of output\n--   neurons, and the number of input neurons, and returns a tuple of the \n--   a fully random matrix, and a fully random vector\nrandomizeFully :: (RandomGen g) => Randomization g\nrandomizeFully g t i j = (randomMatrix, randomVector)\n  where randomMatrix = (i >< j) (randomList t g')\n        randomVector = i |> randomList t g''\n        (g', g'') = split g\n\n-- | The randomizeLocally function takes in ConvolutionalSettings a source\n--   of entropy, a random transform, the number of output and input neurons.\n--   It returns a tuple with a random matrix and a random vector\nrandomizeLocally :: (RandomGen g) => Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Randomization g\nrandomizeLocally f s p k d w1 h1 w2 h2 g t i j = (randomMatrix, randomVector)\n  where randomMatrix = fromLists (locallyRandomList f s p k d w1 h1 w2 h2 g' t i j) :: Matrix Double\n        randomVector = i |> randomList t g''\n        (g', g'') = split g\n\n-- | The locallyRandomList function takes in ConvolutionalSettings a source\n--   of entropy, a random transform, the number of output and input neurons.\n--   It returns a list of lists of locally random numbers\nlocallyRandomList :: (RandomGen g) => Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> g -> RandomTransform -> Int -> Int -> [[Double]]\nlocallyRandomList f s p k d w1 h1 w2 h2 g t i j =\n  if k == 0 then []\n  else filterValues ++ nextFilterValues\n    where filterValues = [replicate (rowZeroOffset + colZeroOffset) 0\n                          ++ take (j - rowZeroOffset - colZeroOffset) (randomList t g')\n                          | n <- [0..div i k-1],\n                          let rowSize = w1 + 2 * p,\n                          let postsynPerFilter = rem n (div i k),\n                          let rowZeroOffset = (1 + s) * quot postsynPerFilter w2 * rowSize,\n                          let colZeroOffset = (1 + s) * mod n w2]\n          nextFilterValues = locallyRandomList f s p (k - 1) k w1 h1 w2 h2 g'' t (i - div i k) j\n          (g', g'') = split g\n\n-- | The connectFully function takes the number of input neurons for a layer, i,\n--   and the number of output neurons of a layer, j, and returns an i x j\n--   connectivity matrix for a fully connected network.\nconnectFully :: Connectivity\nconnectFully i j = (i >< j) (repeat 1)\n\n-- | The connectLocally function takes in ConvolutionalSettings and the number\n--   of output and input neurons\nconnectLocally :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Connectivity\nconnectLocally f s p k d w1 h1 w2 h2 i j =\n  repmat (fromLists conn :: Matrix Double) k d\n  where conn = [replicate rowZeroOffset 0\n                ++ take (f * rowSize) (cycle fieldArea)\n                ++ replicate (rowSize * colSize - rowSize * f - rowZeroOffset) 0\n                | n <- [0.. quot i k-1],\n                  let rowSize = w1 + 2 * p,\n                  let colSize = h1 + 2 * p,\n                  let rowZeroOffset = (1 + s) * quot n w2 * rowSize,\n                  let fieldAreaZeroOffset = (1 + s) * mod n w2,\n                  let fieldArea = replicate fieldAreaZeroOffset 0\n                                   ++ replicate f 1\n                                   ++ replicate (rowSize - f - fieldAreaZeroOffset) 0]\n\n-- | To go from a showable to a layer, we also need a neuron type,\n--   which is an unfortunate restriction owed to Haskell's inability to\n--   serialize functions.\nshowableToLayer :: (RandomGen g) => (Layer, LayerDefinition g) -> Layer\nshowableToLayer (s, d) = Layer (weightMatrix s) (biasVector s) (neuronDef d)\n\n-- | Initialize an infinite random list given a random transform and a source\n--   of entroy.\nrandomList :: RandomGen g => RandomTransform -> g -> [Double]\nrandomList transform = transform . randoms\n\n-- | Define a transformation on the uniform distribution to generate\n--   normally distributed numbers in Haskell (the Box-Muller transform)\nboxMuller :: Double -> Double -> (Double, Double)\nboxMuller x1 x2 = (z1, z2)\n  where z1 = sqrt ((-2) * log x1) * cos (2 * pi * x2)\n        z2 = sqrt ((-2) * log x1) * sin (2 * pi * x2)\n\n-- | This is a function of type RandomTransform that transforms a list of\n--   uniformly distributed numbers to a list of normally distributed numbers.\nnormals :: RandomTransform\nnormals (x1:x2:xs) = z1:z2:normals xs\n  where (z1, z2) = boxMuller x1 x2\nnormals _ = []\n\n-- | A non-transformation to return a list of uniformly distributed numbers\n--   from a list of uniformly distributed numbers. It's really a matter of\n--   naming consistency. It generates numbers on the range (0, 1]\nuniforms :: RandomTransform\nuniforms xs = xs\n\n-- | An affine transformation to return a list of uniforms on the range\n--   (a, b]\nboundedUniforms :: (Double, Double) -> [Double] -> [Double]\nboundedUniforms (lower, upper) = map affine\n  where affine x = lower + x * (upper - lower)\n", "meta": {"hexsha": "93e76161fda0f9f21b2ebabf3da3889a40d1c9cd", "size": 8548, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "AI/Layer.hs", "max_stars_repo_name": "jbarrow/LambdaNet", "max_stars_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 308, "max_stars_repo_stars_event_min_datetime": "2015-01-01T01:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:03:18.000Z", "max_issues_repo_path": "AI/Layer.hs", "max_issues_repo_name": "jbarrow/LambdaNet", "max_issues_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2015-05-23T20:39:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-29T17:04:47.000Z", "max_forks_repo_path": "AI/Layer.hs", "max_forks_repo_name": "jbarrow/LambdaNet", "max_forks_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2015-01-01T07:14:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:33:41.000Z", "avg_line_length": 45.4680851064, "max_line_length": 149, "alphanum_fraction": 0.6477538606, "num_tokens": 2128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.49199879232299243}}
{"text": "{-# LANGUAGE DataKinds, TypeFamilies #-}\n{-# OPTIONS_GHC -Wno-missing-export-lists #-}\n-- | Vector-based (meaning that dual numbers for gradient computation\n-- consider vectors, not scalars, as the primitive differentiable type)\n-- implementation of fully connected neutral network for classification\n-- of MNIST digits. Sports 2 hidden layers.\nmodule HordeAd.Tool.MnistFcnnVector where\n\nimport Prelude\n\nimport           Control.Exception (assert)\nimport qualified Data.Array.DynamicS as OT\nimport qualified Data.Vector.Generic as V\nimport           GHC.Exts (inline)\nimport           Numeric.LinearAlgebra (Vector)\n\nimport HordeAd.Core.DualNumber\nimport HordeAd.Core.Engine\nimport HordeAd.Core.PairOfVectors (DualNumberVariables, var1)\nimport HordeAd.Tool.MnistData\n\nsumTrainableInputsV\n  :: IsScalar d r\n  => DualNumber d (Vector r) -> Int -> DualNumberVariables d r -> DualNumber d r\nsumTrainableInputsV x offset variables =\n  let v = var1 variables offset\n  in v <.>! x\n\nsumTrainableInputsL\n  :: forall d r. IsScalar d r\n  => DualNumber d (Vector r) -> Int -> DualNumberVariables d r -> Int\n  -> DualNumber d (Vector r)\nsumTrainableInputsL x offset variables width =\n  let f :: Int -> DualNumber d r\n      f i = sumTrainableInputsV x (offset + i) variables\n  in seq1 $ V.generate width f\n\nsumConstantDataV\n  :: IsScalar d r\n  => Vector r -> Int -> DualNumberVariables d r -> DualNumber d r\nsumConstantDataV x offset variables =\n  let v = var1 variables offset\n  in v <.>!! x\n\nsumConstantDataL\n  :: forall d r. IsScalar d r\n  => Vector r -> Int -> DualNumberVariables d r -> Int\n  -> DualNumber d (Vector r)\nsumConstantDataL x offset variables width =\n  let f :: Int -> DualNumber d r\n      f i = sumConstantDataV x (offset + i) variables\n  in seq1 $ V.generate width f\n\nfcnnMnistLen1 :: Int -> Int -> (Int, [Int], [(Int, Int)], [OT.ShapeL])\nfcnnMnistLen1 widthHidden widthHidden2 =\n  ( 0\n  , replicate widthHidden sizeMnistGlyph ++ [widthHidden]\n    ++ replicate widthHidden2 widthHidden ++ [widthHidden2]\n    ++ replicate sizeMnistLabel widthHidden2 ++ [sizeMnistLabel]\n  , []\n  , []\n  )\n\n-- | Fully connected neural network for the MNIST digit classification task.\n-- There are two hidden layers and both use the same activation function.\n-- The output layer uses a different activation function.\n-- The widths of the hidden layers are @widthHidden@ and @widthHidden2@\n-- and from these, the @len*@ functions compute the number and dimensions\n-- of scalars (none in this case) and vectors of dual number parameters\n-- (variables) to be given to the program.\nfcnnMnist1 :: forall d r m. DualMonad d r m\n           => (DualNumber d (Vector r) -> m (DualNumber d (Vector r)))\n           -> (DualNumber d (Vector r) -> m (DualNumber d (Vector r)))\n           -> Int\n           -> Int\n           -> Vector r\n           -> DualNumberVariables d r\n           -> m (DualNumber d (Vector r))\nfcnnMnist1 factivationHidden factivationOutput widthHidden widthHidden2\n          input variables = do\n  let !_A = assert (sizeMnistGlyph == V.length input) ()\n  let hiddenLayer1 = sumConstantDataL input 0 variables widthHidden\n                     + var1 variables widthHidden  -- bias\n  nonlinearLayer1 <- factivationHidden hiddenLayer1\n  let offsetMiddle = widthHidden + 1\n      hiddenLayer2 = sumTrainableInputsL nonlinearLayer1 offsetMiddle\n                                         variables widthHidden2\n                     + var1 variables (offsetMiddle + widthHidden2)  -- bias\n  nonlinearLayer2 <- factivationHidden hiddenLayer2\n  let offsetOutput = offsetMiddle + widthHidden2 + 1\n      outputLayer = sumTrainableInputsL nonlinearLayer2 offsetOutput\n                                        variables sizeMnistLabel\n                    + var1 variables (offsetOutput + sizeMnistLabel)  -- bias\n  factivationOutput outputLayer\n\n-- | The neural network applied to concrete activation functions\n-- and composed with the appropriate loss function.\nfcnnMnistLoss1\n  :: DualMonad d r m\n  => Int -> Int -> MnistData r -> DualNumberVariables d r\n  -> m (DualNumber d r)\nfcnnMnistLoss1 widthHidden widthHidden2 (input, target) variables = do\n  result <- inline fcnnMnist1 logisticAct softMaxActV\n                              widthHidden widthHidden2 input variables\n  lossCrossEntropyV target result\n\n-- | A function testing the neural network given testing set of inputs\n-- and the trained parameters.\nfcnnMnistTest1\n  :: forall r. IsScalar 'DModeGradient r\n  => Int -> Int -> [MnistData r] -> (Domain0 r, Domain1 r) -> r\nfcnnMnistTest1 widthHidden widthHidden2 inputs (params0, params1) =\n  let matchesLabels :: MnistData r -> Bool\n      matchesLabels (glyph, label) =\n        let nn = inline fcnnMnist1 logisticAct softMaxActV\n                                        widthHidden widthHidden2 glyph\n            value = primalValue nn (params0, params1, V.empty, V.empty)\n        in V.maxIndex value == V.maxIndex label\n  in fromIntegral (length (filter matchesLabels inputs))\n     / fromIntegral (length inputs)\n", "meta": {"hexsha": "56024d9cff407ef959ef269940dfad6932a5cdb2", "size": 5005, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Tool/MnistFcnnVector.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HordeAd/Tool/MnistFcnnVector.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "src/HordeAd/Tool/MnistFcnnVector.hs", "max_forks_repo_name": "Mikolaj/horde-ad", "max_forks_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3636363636, "max_line_length": 80, "alphanum_fraction": 0.6921078921, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.49199879232299243}}
{"text": "{-# LANGUAGE BangPatterns #-}\nmodule LogFourierSeries where\n\nimport           Data.Array.Repa     as R\nimport           Data.Complex\nimport           Data.List           as L\nimport           Data.Vector.Unboxed as VU\nimport           Image.IO\nimport           System.Environment\nimport           System.FilePath\nimport           Utils.Parallel hiding ((.|))\nimport Control.DeepSeq\nimport Data.Conduit\nimport Data.Conduit.List as CL\nimport Control.Monad.Trans.Resource\nimport Control.Monad\nimport           FokkerPlanck.MonteCarlo\nimport Utils.Array\nimport            STC.Utils\n\n\n\n{-# INLINE gaussian #-}\ngaussian :: Double -> Double -> Double -> Double\ngaussian !mu !sigma !x =\n  (exp $ (x - mu) ^ 2 / (-2 * sigma ^ 2)) / (sqrt $ 2 * pi) / sigma\n  \nsink ::\n     ParallelParams -> (VU.Vector (Complex Double))\n  -> ConduitT (VU.Vector (Complex Double)) Void (ResourceT IO) (VU.Vector Double)\nsink !parallelParams !vec = do\n  xs <- CL.take . batchSize $ parallelParams\n  if (L.null xs)\n    then return . VU.map magnitude $ vec\n    else sink parallelParams (L.foldl' (VU.zipWith (+)) vec xs)\n  -- case x of\n  --   Nothing -> return . VU.map magnitude $ vec\n  --   Just y -> sink (VU.zipWith (+) vec y)\n\nmain = do\n  args@(numPointStr:maxThetaFreqStr:maxRFreqStr:deltaStr:maxRStr:stdStr:scaleFactorStr:batchSizeStr:numThreadStr:_) <-\n    getArgs\n  print args\n  let maxThetaFreq = read maxThetaFreqStr :: Double\n      maxRFreq = read maxRFreqStr :: Double\n      delta = read deltaStr :: Double\n      thetaFreqs = [-maxThetaFreq .. maxThetaFreq]\n      rFreqs = [-maxRFreq .. maxRFreq]\n      phiFreqs = [0] -- thetaFreqs\n      muR = 16\n      sigmaR = 8\n      muTheta = 0\n      sigmaTheta = 0.5\n      muPhi = pi\n      sigmaPhi = 0.5\n      deltaPhi = 2 * pi / fromIntegral numOrientation\n      alpha = 1\n      scaleFactor = read scaleFactorStr :: Double\n      numPoint = read numPointStr :: Int\n      numOrientation = 72 :: Int\n      maxR = read maxRStr :: Double\n      std = read stdStr :: Double\n      batchSize = read batchSizeStr :: Int\n      numThread = read numThreadStr :: Int\n      center = div numPoint 2\n      folderPath = \"output/test/LogFourierSeries\"\n      gaussianFunc theta r phi =\n        (gaussian muTheta sigmaTheta theta) * (gaussian muR sigmaR r) *\n        (gaussian muPhi sigmaPhi phi)\n      centerArr =\n        fromFunction (Z :. (1 :: Int) :. numPoint :. numPoint) $ \\(Z :. _ :. i :. j) ->\n          if i == center && j == center\n            then 1\n            else 0\n  plotImageRepa (folderPath </> \"Center.png\") . ImageRepa 8 . computeS $\n    centerArr\n  -- originalArray <-\n  --   computeUnboxedP . fromFunction (Z :. numPoint :. numPoint :. numOrientation) $ \\(Z :. i :. j :. k) ->\n  --     let !x = (fromIntegral $ i)\n  --         !y = (fromIntegral $ j - center)\n  --         !theta = atan2 y x\n  --         !r = sqrt $ x ^ 2 + y ^ 2\n  --         !phi = fromIntegral k * deltaPhi\n  --     in gaussianFunc theta r phi\n  arrG <-\n    solveMonteCarloR2S1\n      numThread\n      1000000\n      1000000\n      numPoint\n      numPoint\n      numOrientation\n      0.1\n      100\n      64\n      1\n      \"\"\n  print . extent $ arrG\n  let originalArray =\n        extend (Z :. All :. All :. (1 :: Int)) . sumS $ rotate3D arrG\n  plotImageRepa (folderPath </> \"Greens3DNorm_1.png\") .\n    ImageRepa 8 .\n    computeS .\n    reduceContrast 10 . extend (Z :. (1 :: Int) :. All :. All) . R.sumS $\n    originalArray\n  plotImageRepa (folderPath </> \"Greens3D_1.png\") .\n    ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) . R.sumS $\n    originalArray\n  recon <-\n    runConduitRes $\n    CL.sourceList\n      [ (rFreq, thetaFreq, phiFreq)\n      | rFreq <- rFreqs\n      , thetaFreq <- thetaFreqs\n      , phiFreq <- phiFreqs\n      ] .|\n    parConduit\n      (ParallelParams numThread batchSize)\n      (\\(rFreq, thetaFreq, phiFreq) ->\n         let !c =\n               sumAllS .\n               R.zipWith (\\a b -> (a :+ 0) * b) originalArray .\n               fromFunction (Z :. numPoint :. numPoint :. (1 :: Int)) $ \\(Z :. i :. j :. k) ->\n                 let !x = delta * (fromIntegral $ i - center)\n                     !y = delta * (fromIntegral $ j - center)\n                     !theta = atan2 y x\n                     !r = (sqrt $ x ^ 2 + y ^ 2)\n                     !phi = fromIntegral k * deltaPhi\n                 in if (x ^ 2 + y ^ 2) == 0  -- || r >= maxR -- || pi * r <  (abs thetaFreq)\n                      then 0\n                           -- exp $ (log r) * (alpha - 1) :+ ((-thetaFreq) * theta - rFreq * (log r))\n                      else exp $ (log r) * (-1 + alpha) :+ ((-thetaFreq) * theta - rFreq * (log r) -- * pi / (log maxR)\n                                                              )\n                           -- cis ((-thetaFreq) * theta - rFreq * (log r) * pi / (log maxR) )\n                           -- (x :+ y) ** ((-thetaFreq) :+ 0) *\n                           -- ((x ^ 2 + y ^ 2) :+ 0) **\n                           -- (((thetaFreq - 2 + alpha) :+ (-rFreq)) / 2)\n                           -- (x :+ y) ** ((-thetaFreq) :+ 0) *\n                           -- ((x ^ 2 + y ^ 2) :+ 0) **\n                           -- (((thetaFreq) :+ (-pi * rFreq / (log maxR))) / 2)\n         in toUnboxed .\n            computeS .\n            -- R.map (* c) .\n            R.map\n              (* (c *\n                  ((exp $ (-thetaFreq ^ 2 - rFreq ^ 2) / (2 * std ^ 2)) :+ 0))) .\n            fromFunction (Z :. numPoint :. numPoint :. (1 :: Int)) $ \\(Z :. i :. j :. k) ->\n              let !x = (fromIntegral $ i - center)\n                  !y = (fromIntegral $ j - center)\n                  !theta = atan2 y x\n                  !r = delta * (sqrt $ x ^ 2 + y ^ 2)\n                  !phi = fromIntegral k * deltaPhi\n              in if r <= 0 -- || pi * r < (abs thetaFreq)\n                   then 0\n                        \n                   else exp $ (log r) * (-alpha) :+ (thetaFreq * theta + rFreq * (log r) -- * pi / (log maxR)\n                                                  )\n                        -- cis (thetaFreq * theta + rFreq * (log r) * pi / (log maxR))\n                        -- exp $ (log r) * (-alpha) :+ (thetaFreq * theta + rFreq * (log r))\n                        -- (x :+ y) ** (thetaFreq :+ 0) *\n                        -- ((x ^ 2 + y ^ 2) :+ 0) **\n                        -- (((-thetaFreq - alpha) :+ rFreq) / 2)\n                        -- (x :+ y) ** (thetaFreq :+ 0) *\n                        -- ((x ^ 2 + y ^ 2) :+ 0) **\n                        -- (((-thetaFreq) :+ (pi * rFreq / (log maxR))) / 2)\n       ) .|\n    sink\n      (ParallelParams numThread batchSize)\n      (VU.replicate (numPoint ^ 2 * 1) 0)\n  -- let\n      -- !recon =\n      --   VU.map magnitude .\n      --   L.foldl1' (VU.zipWith (+)) .\n      --   parMap\n      --     rdeepseq\n      --     (\\(rFreq, thetaFreq, phiFreq) ->\n      --        let !c =\n      --              sumAllS .\n      --              fromFunction (Z :. numPoint :. numPoint :. numPoint) $ \\(Z :. i :. j :. k) ->\n      --                let !x = delta * (fromIntegral $ i - center)\n      --                    !y = delta * (fromIntegral $ j - center)\n      --                    !theta = atan2 y x\n      --                    !r = sqrt $ x ^ 2 + y ^ 2\n      --                    !phi = fromIntegral k * deltaPhi\n      --                in if r < 1 / maxR || r >= maxR\n      --                     then 0\n      --                     else (gaussianFunc theta r phi :+ 0) *\n      --                          (cis $\n      --                           (-1) * thetaFreq * theta -\n      --                           phiFreq * (phi - theta) -\n      --                           pi * rFreq * (r) / (maxR))\n      --        in toUnboxed .\n      --           computeS .\n      --           R.map (* c) .\n      --           fromFunction (Z :. numPoint :. numPoint :. numPoint) $ \\(Z :. i :. j :. k) ->\n      --             let !x = fromIntegral $ i - center\n      --                 !y = fromIntegral $ j - center\n      --                 !theta = atan2 y x\n      --                 !r = sqrt $ x ^ 2 + y ^ 2\n      --                 !phi = fromIntegral k * deltaPhi\n      --             in if r == 0\n      --                  then 0\n      --                  else cis $\n      --                       thetaFreq * theta + phiFreq * (phi - theta) +\n      --                       pi * rFreq * (r) / (maxR)) $\n      --   [ (rFreq, thetaFreq, phiFreq)\n      --   | rFreq <- rFreqs\n      --   , thetaFreq <- thetaFreqs\n      --   , phiFreq <- phiFreqs\n      --   ]\n  plotImageRepa (folderPath </> \"Greens3DRecon_2.png\") .\n    ImageRepa 8 .\n    computeS .\n    extend (Z :. (1 :: Int) :. All :. All) .\n    sumS . fromUnboxed (Z :. numPoint :. numPoint :. (1 :: Int)) $\n    recon\n  plotImageRepa (folderPath </> \"Greens3DReconNorm_2.png\") .\n    ImageRepa 8 .\n    computeS .\n    reduceContrast 10 .\n    extend (Z :. (1 :: Int) :. All :. All) .\n    sumS . fromUnboxed (Z :. numPoint :. numPoint :. (1 :: Int)) $\n    recon\n", "meta": {"hexsha": "25f3cdb6172cbe76ba7e5e4acbe38e4b4697164f", "size": 8983, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/LogFourierSeries/LogFourierSeries.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/LogFourierSeries/LogFourierSeries.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/LogFourierSeries/LogFourierSeries.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 40.1026785714, "max_line_length": 119, "alphanum_fraction": 0.4443949683, "num_tokens": 2642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245617, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.49174895105686894}}
{"text": "{-# LANGUAGE DeriveFunctor, GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DataKinds, TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts, FlexibleInstances #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ConstraintKinds #-}\n\nmodule DelayedSampling where\n\nimport Prelude hiding ((<>))\n\nimport Control.Exception.Base (assert)\nimport Control.Monad (forM_, when)\nimport Control.Monad.State (get, put)\nimport Control.Monad.Trans (MonadIO, liftIO)\nimport Control.Monad.Bayes.Class (MonadSample, MonadCond, MonadInfer)\nimport Control.Monad.Bayes.Weighted\nimport Control.Monad.Bayes.Sampler\n\nimport Data.Aeson (ToJSON (..), object, (.=))\nimport Data.List (delete)\nimport Data.Maybe (isJust)\nimport Data.Proxy\nimport Data.Random hiding (normal)\n\nimport Debug.Trace\n\nimport GHC.TypeLits\n\nimport Numeric.AD\nimport Numeric.AD.Rank1.Tower (Tower)\n\nimport Numeric.LinearAlgebra.Static hiding (M)\n\nimport Unsafe.Coerce (unsafeCoerce)\n\nimport Distributions\nimport MVDistributions\nimport Inference\nimport Util.Ref\n\ndata MarginalT = MGaussianT | MBetaT | MBernoulliT | forall (n :: Nat). MMVGaussianT (Proxy n)\n\ntype DelayedSampling = MonadState Heap\ntype DelayedSample m = (MonadState Heap m, MonadSample m)\ntype DelayedInfer m = (MonadState Heap m, MonadInfer m)\n\ndata SMarginalT (m :: MarginalT) where\n  SMGaussianT :: SMarginalT MGaussianT\n  SMBetaT :: SMarginalT MBetaT\n  SMBernoulliT :: SMarginalT MBernoulliT\n  SMMVGaussianT :: forall (n :: Nat) (p :: Proxy n). SMarginalT (MMVGaussianT p)\n\n\ntype family MType (m :: MarginalT) where\n  MType MGaussianT = Double\n  MType MBetaT = Double\n  MType MBernoulliT = Bool\n  MType (MMVGaussianT (p :: Proxy n)) = R n\n\n\ndata MDistr (m :: MarginalT) where\n  MGaussian :: !Double -> !Double -> MDistr MGaussianT\n  MBeta :: !Double -> !Double -> MDistr MBetaT\n  MBernoulli :: !Double -> MDistr MBernoulliT\n  MMVGaussian :: forall (n :: Nat) (p :: Proxy n). KnownNat n => !(R n) -> !(Sym n) -> MDistr (MMVGaussianT p)\n\nderiving instance Show (MDistr m)\n\ninstance ToJSON (MDistr a) where\n  toJSON (MMVGaussian mu cov) = object [\"mean\" .= mu, \"cov\" .= cov]\n  toJSON (MGaussian mu cov) = object [\"mean\" .= mu, \"cov\" .= cov]\n  toJSON (MBeta a b) = object [\"alpha\" .= a, \"beta\" .= b]\n  toJSON (MBernoulli p) = object [\"p\" .= p]\n\n\ndata CDistr (m :: MarginalT) (m' :: MarginalT) where\n  AffineMeanGaussian :: !Double -> !Double -> !Double -> CDistr MGaussianT MGaussianT\n  CBernoulli :: CDistr MBetaT MBernoulliT\n  MVAffineMeanGaussian :: forall (n :: Nat) (m :: Nat) (pn :: Proxy n) (pm :: Proxy m).\n    (KnownNat n, KnownNat m) => (L m n) -> (R m) -> (Sym m) -> CDistr (MMVGaussianT pn) (MMVGaussianT pm)\n\ndata Result a where\n  RConst :: a -> Result a\n  RMarginal :: MDistr a -> Result (MType a)\n\nderiving instance Show a => Show (Result a)\n\ngaussianConditioning :: Double -> Double -> Double -> Double -> (Double, Double)\ngaussianConditioning mu var obs obsvar = (mu', var')\n  where\n  ivar = recip var\n  iobsvar = recip obsvar\n  inf = ivar + iobsvar\n  var' = recip inf\n  mu' = (ivar * mu + iobsvar * obs) / inf\n\ngaussianMeanGaussian :: Double -> CDistr MGaussianT MGaussianT\ngaussianMeanGaussian = AffineMeanGaussian 1 0\n\nascend1 :: Floating d => d -> (d -> d) -> Int -> d -> d\nascend1 lr diff = go where\n  go 0 x = x\n  go n x = let d = diff x in go (n - 1) (x + (lr * d))\n\n-- XXX: not sure that the factor amount is good\nsolveLaplaceGaussian :: MDistr MGaussianT\n  -> (forall s. AD s (Tower Double) -> AD s (Tower Double))\n  -> Double\n  -> Int\n  -> (MDistr MGaussianT, Double)\nsolveLaplaceGaussian (MGaussian mu var) likelihood learningRate numIters =\n  (MGaussian mu' var', factorAmt - originalFactorAmt)\n  where\n  fmu' : _ : f''mu' : _ = diffs0 f mu'\n  originalFactorAmt = log $ sqrt (pi / var) * exp (gaussian_ll' mu var mu)\n  factorAmt = log $ sqrt (- 2 * pi / f''mu') * exp fmu'\n  var' :: Double\n  var' = -2 / f''mu'\n  mu' ::  Double\n  mu' = ascend1 learningRate ((!! 1) . diffs0 f) numIters mu\n  f :: forall s. AD s (Tower Double) -> AD s (Tower Double)\n  f x = gaussian_ll' (auto mu) (auto var) x + likelihood x\n\nmdistrToDistr :: MDistr a -> Distr (MType a)\nmdistrToDistr (MGaussian mu var) = normal mu var\nmdistrToDistr (MMVGaussian mu var) = mvNormal mu var\nmdistrToDistr (MBeta a b) = beta a b\nmdistrToDistr (MBernoulli p) = bernoulli p\n\ncdistrToDistr :: CDistr m m' -> MType m -> MDistr m'\ncdistrToDistr (AffineMeanGaussian m b obsvar) mu = MGaussian (m * mu + b) obsvar\ncdistrToDistr (MVAffineMeanGaussian f b obsvar) mu = MMVGaussian (f #> mu + b) obsvar\ncdistrToDistr CBernoulli p = MBernoulli p\n\nmakeMarginal :: MDistr a -> CDistr a b -> MDistr b\nmakeMarginal (MGaussian mu var) (AffineMeanGaussian m b obsvar) =\n  MGaussian (m * mu + b) (m^2 * var + obsvar)\nmakeMarginal (MMVGaussian mu var) (MVAffineMeanGaussian f b obsvar) =\n  MMVGaussian (f #> mu + b) (conjugate f var + obsvar)\nmakeMarginal (MBeta a b) CBernoulli = MBernoulli (a / (a + b))\nmakeMarginal (MBernoulli _) _ = error \"impossible\"\n\nmakeConditional :: MDistr a -> CDistr a b -> MType b -> MDistr a\nmakeConditional (MGaussian mu var) (AffineMeanGaussian m b obsvar) obs =\n  MGaussian mu' var'\n  where (mu', var') = gaussianConditioning mu var ((obs - b) / m) (obsvar / m^2)\nmakeConditional (MMVGaussian mu var) (MVAffineMeanGaussian f b obsvar) obs =\n  MMVGaussian mu' var'\n  where (mu', var') = fst (kalmanUpdate obs f obsvar (mu, var))\nmakeConditional (MBeta a b) CBernoulli tf =\n  if tf then MBeta (a + 1) b else MBeta a (b + 1)\nmakeConditional (MBernoulli _) _ _ = error \"impossible\"\n\ndata State b where\n  Initialized :: State b\n  Marginalized :: MDistr b -> State b\n\nderiving instance Show (State MGaussianT)\nderiving instance Show (State MBetaT)\n\nisMarginalized :: State b -> Bool\nisMarginalized (Marginalized _) = True\nisMarginalized _ = False\n\ndata DSDistr a b where\n   UDistr :: !(MDistr b) -> DSDistr a b\n   CDistr :: !(Ref (Node z a)) -> !(CDistr a b) -> DSDistr a b\n\ntypeOfMDistr :: MDistr b -> SMarginalT b\ntypeOfMDistr (MGaussian _ _) = SMGaussianT\ntypeOfMDistr (MBeta _ _) = SMBetaT\ntypeOfMDistr (MBernoulli _) = SMBernoulliT\ntypeOfMDistr (MMVGaussian _ _) = SMMVGaussianT\n\ntypeOfCDistr :: CDistr m m' -> SMarginalT m'\ntypeOfCDistr (AffineMeanGaussian _ _ _) = SMGaussianT\ntypeOfCDistr CBernoulli = SMBernoulliT\ntypeOfCDistr (MVAffineMeanGaussian _ _ _) = SMMVGaussianT\n\ntypeOfDSDistr :: DSDistr a b -> SMarginalT b\ntypeOfDSDistr (UDistr d) = typeOfMDistr d\ntypeOfDSDistr (CDistr _ c) = typeOfCDistr c\n\n\ndata Node a b = Node\n  { name :: !String\n  , children :: [RefNodeFrom b]\n  , state :: !(State b)\n  , distr :: !(DSDistr a b)\n  }\n  | RealizedNode (MType b)\n\ndata RefNode a b where\n  RefNode :: !(Ref (Node a b)) -> RefNode a b\n\ndata SomeRefNode where\n  SomeRefNode :: !(Ref (Node a b)) -> SomeRefNode\n\ninstance Eq SomeRefNode where\n  SomeRefNode x == SomeRefNode y = x == unsafeCoerce y\n\ndata Path e (a :: MarginalT) (b :: MarginalT) where\n  PNil :: Path e a a\n  PSnoc :: e b c -> Path e a b -> Path e a c\n\ndata PathTo e b where\n  PathTo :: !(Path e a b) -> PathTo e b\n\ndata RefNodeTo b where\n  RefNodeTo :: !(Ref (Node a b)) -> RefNodeTo b\n\ndata RefNodeFrom a where\n  RefNodeFrom :: !(Ref (Node a b)) -> RefNodeFrom a\n\ninstance Eq (RefNodeFrom a) where\n  RefNodeFrom x == RefNodeFrom y = x == unsafeCoerce y\n\ninstance Eq (RefNodeTo a) where\n  RefNodeTo x == RefNodeTo y = x == unsafeCoerce y\n\nancestry :: DelayedSampling m => Node a b -> m (PathTo RefNode a)\nancestry n = case distr n of\n  UDistr _ -> pure $ PathTo PNil\n  CDistr par cdistr -> do\n    PathTo ancestors <- ancestry =<< readRef par\n    pure (PathTo (PSnoc (RefNode par) ancestors))\n\npath_all :: Applicative f => (forall a b. e a b -> f Bool) -> Path e a b -> f Bool\npath_all f PNil = pure True\npath_all f (PSnoc e es) = (&&) <$> f e <*> path_all f es\n\nisTerminal :: DelayedSampling m =>Node a b -> m Bool\nisTerminal n = do\n  PathTo ancestors <- ancestry n\n  ancestors_all_marginalized <- path_all (\\(RefNode n) -> isMarginalized . state <$> readRef n) ancestors\n  pure $ isMarginalized (state n) && ancestors_all_marginalized\n\n-- initialize without parent node\nconstant' :: String -> MDistr a -> Node z a\nconstant' n d = Node\n  { name = n\n  , children = []\n  , state = Initialized\n  , distr = UDistr d\n  }\n\nassumeConstant :: DelayedSampling m => String -> MDistr a -> m (Ref (Node z a))\nassumeConstant n d = newRef (constant' n d)\n\n-- initialize with parent node\nnewConditional' :: DelayedSampling m => String -> Ref (Node a b) -> CDistr b c -> m (Ref (Node b c))\nnewConditional' str par cdistr = do\n  childRef <- newRef child\n  modifyRef' par $ \\n -> n { children = (RefNodeFrom childRef) : children n }\n  --childRef' <- mkWeakRef childRef $ putStrLn (\"deleted \" ++ str)\n  pure childRef\n  where\n  child = Node\n    { name = str\n    , children = []\n    , state = Initialized\n    , distr = CDistr par cdistr }\n\nassumeConditional :: DelayedSampling m => String -> Ref (Node a b) -> CDistr b c -> m (Ref (Node b c))\nassumeConditional str par cdistr = newConditional' str par cdistr\n\nupdater :: DelayedSampling m => (a -> m a) -> Ref a -> m ()\nupdater f ref = do\n  x <- readRef ref\n  y <- f x\n  writeRef ref y\n\n\nmarginalize :: DelayedSampling m => MDistr a -> Ref (Node a b) -> m (MDistr b)\nmarginalize parMarginal nref = do\n  n <- readRef nref\n  writeLog (\"marginalize \" ++ name n)\n  case (state n, distr n) of\n    (Initialized, CDistr par cdistr) -> do\n      let marginal' = makeMarginal parMarginal cdistr\n      writeRef nref $ n { state = Marginalized marginal' }\n      pure marginal'\n    (state, _) -> error $  \"marginalize': \" ++ name n\n\nmarginalize2' :: MType a -> Node a b -> Node a b\nmarginalize2' value n =\n  case (state n, distr n) of\n    (Initialized, CDistr _ cdistr) ->\n      let marg = cdistrToDistr cdistr value in\n      n { state = Initialized, distr = UDistr marg }\n    _ -> error \"marginalize2'\"\n\nmarginalize2 :: DelayedSampling m => MType a -> Ref (Node a b) -> m ()\nmarginalize2 a = updater (pure . marginalize2' a)\n\nsample :: DelayedSampling m => MonadSample m => Ref (Node a b) -> m ()\nsample nref = do\n  n <- readRef nref\n  ioAssert (isTerminal n)\n  writeLog (\"sample \" ++ name n)\n  case state n of\n    Marginalized m -> do\n      x <- Distributions.sample (mdistrToDistr m)\n      realize x nref\n    _ -> error \"sample\"\n\nupdateParent :: DelayedSampling m => Node b c -> (forall a. CDistr b c -> Node a b -> m (Node a b)) -> m ()\nupdateParent n f = case distr n of\n  UDistr _ -> pure ()\n  CDistr p cdistr -> updater (f cdistr) p\n\nfirstSatisfying :: Monad m => (a -> m Bool) -> [a] -> m (Maybe a)\nfirstSatisfying p [] = pure Nothing\nfirstSatisfying p (x : xs) = do\n  px <- p x\n  if px then pure (Just x) else firstSatisfying p xs\n\n-- Invariant 2: A node always has at most one marginal Child\nmarginalChild :: DelayedSampling m => Node a b -> m (Maybe (RefNodeFrom b))\nmarginalChild n = firstSatisfying (\\(RefNodeFrom x) -> isMarginalized . state <$> readRef x) (children n)\n\nioAssert :: Applicative m => m Bool -> m ()\nioAssert x = pure () -- do {b <- x; assert b (pure ())}\n\nwriteLog :: Applicative m => String -> m ()\nwriteLog = const $ pure () -- putStrLn\n\nrealize :: DelayedSampling m => MType b -> Ref (Node a b) -> m ()\nrealize val nref = do\n  n <- readRef nref\n  writeLog (\"realize \" ++ name n)\n  ioAssert (isTerminal n)\n  updateParent n $ \\cdistr p -> do\n    let Marginalized marg = state p\n    let marg' = makeConditional marg cdistr val\n    pure $ p { state = Marginalized marg', children = delete (RefNodeFrom nref) (children p) }\n  forM_ (children n) $ \\(RefNodeFrom c) -> do\n    marginalize2 val c\n  writeRef nref $ RealizedNode val\n\nscore' :: DelayedSampling m => MonadCond m => MType b -> Ref (Node a b) -> m Double\nscore' x nref = do\n  n <- readRef nref\n  ioAssert (isTerminal n)\n  writeLog (\"observe \" ++ name n)\n  pure $ case state n of\n    Marginalized marg -> Distributions.score (mdistrToDistr marg) x\n    _ -> error \"observe'\"\n\nobserve :: DelayedSampling m => MonadCond m => MType b -> Ref (Node a b) -> m ()\nobserve x nref = do\n  ll <- score' x nref\n  factor ll\n  realize x nref\n\nprune :: DelayedSampling m => MonadSample m => Ref (Node a b) -> m ()\nprune nref = do\n  n <- readRef nref\n  writeLog (\"prune \" ++ name n)\n  assert (isMarginalized (state n)) $ do\n    maybeChild <- marginalChild n\n    forM_ maybeChild $ \\(RefNodeFrom c) ->\n      prune c\n    DelayedSampling.sample nref\n\n-- turns `nref` into a terminal node\ngraft :: DelayedSampling m => MonadSample m => Ref (Node a b) -> m (MDistr b)\ngraft nref = do\n  n <- readRef nref\n  writeLog (\"graft \" ++ name n)\n  case state n of\n    Marginalized _ -> do\n      maybeChild <- marginalChild n\n      forM_ maybeChild $ \\(RefNodeFrom c) -> prune c\n      n'  <- readRef nref\n      pure $ case state n' of\n        Marginalized m -> m\n        _ -> error \"graft\"\n    Initialized -> case distr n of\n      UDistr d -> do\n        writeRef nref $ n { state = Marginalized d }\n        pure d\n      CDistr par cdistr -> do\n        parMarg <- graft par\n        marginalize parMarg nref\n\nobs :: DelayedSampling m => MonadInfer m => MType b -> Ref (Node a b) -> m ()\nobs x n = do\n  graft n\n  DelayedSampling.observe x n\n\nscore :: DelayedSampling m => MonadInfer m => MType b -> Ref (Node a b) -> m Double\nscore x n = withoutModifying $ do\n  graft n\n  score' x n\n\nwithoutModifying :: MonadState s m => m a -> m a\nwithoutModifying f = do\n  s <- get\n  x <- f\n  put s\n  return x\n\n\ngetValue :: DelayedSampling m => MonadSample m => Ref (Node a b) -> m (MType b)\ngetValue nref = do\n  n <- readRef nref\n  case n of\n    RealizedNode x -> pure x\n    _ -> do\n      graft nref\n      DelayedSampling.sample nref\n      getValue nref\n\nprintValue :: Show (MType b) => DelayedSampling m => MonadSample m => MonadIO m => Ref (Node a b) -> m ()\nprintValue n = do\n  x <- getValue n\n  liftIO $ print x\n\nprintState :: Show (State b) => DelayedSampling m => MonadIO m => Ref (Node a b) -> m ()\nprintState nref = do\n  n <- readRef nref\n  liftIO $ print (state n)\n\nforget :: DelayedSampling m => Ref (Node a b) -> m ()\nforget nref = do\n  n <- readRef nref\n  case n of\n    RealizedNode _ -> pure ()\n    _ -> case state n of\n      Initialized -> error \"forget\"\n      Marginalized marg -> do\n        forM_ (children n) $ \\(RefNodeFrom cref) -> do\n          modifyRef' cref $ \\c ->\n            c { distr = case distr c of\n              UDistr d -> UDistr d\n              CDistr _ _ -> case state c of\n                Marginalized marg -> UDistr marg\n                _ -> error \"forget\" }\n        case distr n of\n          UDistr d -> pure ()\n          CDistr par cdistr -> do\n            isStale <- stale par\n            if isStale\n              then error \"can't forget: information to incorporate\"\n              else updateParent n $ \\cdistr p -> pure $ p { children = delete (RefNodeFrom nref) (children p) }\n        writeRef nref $ n { distr = UDistr marg }\n  modifyRef' nref $ \\n' -> n' { children = [] }\n  freeRef nref\n\n-- sweep :: [SomeRefNode] -> M ()\n-- sweep liveVars = mapM_ (\\(SomeRefNode n) -> forgetRelated n) liveVars where\n--   forgetRelated :: Ref (Node a b) -> M ()\n--   forgetRelated nref = undefined\n--   forgettable :: Ref (Node a b) -> M Bool\n--   forgettable nref =\n--     if SomeRefNode nref `elem` liveVars\n--       then pure False\n--       else case state n of\n\nstale :: DelayedSampling m => Ref (Node a b) -> m Bool\nstale nref = do\n  n <- readRef nref\n  case n of\n    RealizedNode _ -> pure False\n    _ -> case state n of\n      Initialized -> case distr n of\n        UDistr _ -> pure False\n        CDistr par _ -> stale par\n      Marginalized d -> isJust <$> marginalChild n\n\n\n-- Examples\n\ndelay_triplet :: DelayedInfer m => MonadIO m => Double -> m ()\ndelay_triplet zobs = do\n  x <- assumeConstant \"x\" (MGaussian 0 1)\n  writeLog \"x created\"\n  y <- assumeConditional \"y\"  x (gaussianMeanGaussian 1)\n  writeLog \"y created\"\n  z <- assumeConditional \"z\" y (gaussianMeanGaussian 1)\n  writeLog \"z created\"\n  obs zobs z\n  writeLog \"z observed\"\n  printValue z\n  printValue x\n  printValue y\n\nobserveConditional :: DelayedInfer m => String -> Ref (Node a b) -> CDistr b c -> MType c -> m ()\nobserveConditional str nref cdistr observation = do\n  y <- assumeConditional str nref cdistr\n  obs observation y\n  freeRef y\n\nscoreConditional :: DelayedInfer m => String -> Ref (Node a b) -> CDistr b c -> MType c -> m Double\nscoreConditional str nref cdistr observation = do\n  y <- assumeConditional str nref cdistr\n  ll <- DelayedSampling.score observation y\n  modifyRef' nref $ \\n -> n { children = tail (children n) }\n  freeRef y\n  pure ll\n\n-- For some reason, likelihoods aren't exactly  the same\ndelay_iidADF :: DelayedInfer m => MonadIO m => Bool -> [Double] -> m ()\ndelay_iidADF useADF yobs = do\n  x <- assumeConstant \"x\" (MGaussian 0 1)\n  forM_ (zip [1..] yobs) $ \\(t, obsyt) -> do\n    if useADF\n      then observeGeneric x $ \\d -> solveLaplaceGaussian d (\\mu -> gaussian_ll' mu 1 (auto obsyt)) 0.05 10000\n      else observeConditional (\"y\" ++ show t) x (gaussianMeanGaussian 1) obsyt  -- normal(x, 1)\n    printState x\n  printValue x\n\nobserveGeneric :: DelayedInfer m => Ref (Node a b) -> (MDistr b -> (MDistr b, Double)) -> m ()\nobserveGeneric nref f = do\n  graft nref\n  n <- readRef nref\n  case n of\n    RealizedNode x -> error \"observeGeneric: RealizedNode impossible\"\n    _ -> case state n of\n      Marginalized d -> do\n        let (d', factorAmt) = f d\n        factor factorAmt\n        writeRef nref $ n { state = Marginalized d' }\n      _ -> error \"observeGeneric\"\n\ndelay_kalman :: DelayedInfer m => MonadIO m =>\n  Bool -> Double -> Double -> [Double] -> m ()\ndelay_kalman shouldForget m b yobs = do\n  x1 <- assumeConstant \"x1\" (MGaussian 0 1)\n  observeConditional \"y1\" x1 (gaussianMeanGaussian 1) (head yobs)\n  loop 2 x1 (tail yobs)\n  where\n  loop :: DelayedInfer m => MonadIO m =>\n    Integer -> Ref (Node a MGaussianT) -> [Double] -> m ()\n  loop t xpredt [] = pure ()\n  loop t xpredt (y : ys) = do\n    xt <- assumeConditional (\"x\" ++ show t) xpredt (AffineMeanGaussian m b 1)\n    observeConditional (\"y\" ++ show t) xt (gaussianMeanGaussian 1) y\n    when (t `mod` 100 == 0) $ do\n      liftIO $ putStrLn (\"t = \" ++ show t)\n      printState xt\n    when shouldForget $ forget xpredt\n    loop (t + 1) xt ys\n", "meta": {"hexsha": "1e421a42276e32ee28c7e00144cdd08342f84028", "size": 18157, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/src/DelayedSampling.hs", "max_stars_repo_name": "psg-mit/probzelus-haskell", "max_stars_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-26T13:13:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T19:11:41.000Z", "max_issues_repo_path": "haskell/src/DelayedSampling.hs", "max_issues_repo_name": "psg-mit/probzelus-haskell", "max_issues_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "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": "haskell/src/DelayedSampling.hs", "max_forks_repo_name": "psg-mit/probzelus-haskell", "max_forks_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3155963303, "max_line_length": 111, "alphanum_fraction": 0.6554496888, "num_tokens": 5754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4917489442836073}}
{"text": "{-# LANGUAGE RankNTypes, BangPatterns, GADTs #-}\n{-# OPTIONS -Wall #-}\n\nmodule Language.Hakaru.Distribution where\n\nimport Control.Monad\nimport Control.Monad.Primitive\nimport Control.Monad.Loops\nimport qualified System.Random.MWC as MWC\nimport Language.Hakaru.Mixture\nimport Language.Hakaru.Types\nimport Data.Ix\nimport Data.Maybe (fromMaybe)\nimport Data.List (findIndex, foldl')\nimport Numeric.SpecFunctions\nimport qualified Data.Map.Strict as M\nimport qualified Data.Number.LogFloat as LF\n\nmapFst :: (t -> s) -> (t, u) -> (s, u)\nmapFst f (a,b) = (f a, b)\n\ndirac :: (Eq a) => a -> Dist a\ndirac theta = Dist {logDensity = (\\ (Discrete x) -> if x == theta then 0 else log 0),\n                    distSample = (\\ _ -> return $ Discrete theta)}\n\nbern :: Double -> Dist Bool\nbern p = Dist {logDensity = (\\ (Discrete x) -> log (if x then p else 1 - p)),\n               distSample = (\\ g -> do t <- MWC.uniformR (0,1) g\n                                       return $ Discrete (t <= p))}\n\nuniform :: Double -> Double -> Dist Double\nuniform lo hi =\n    let uniformLogDensity lo' hi' x | lo' <= x && x <= hi' = log (recip (hi' - lo'))\n        uniformLogDensity _ _ _ = log 0\n    in Dist {logDensity = (\\ (Lebesgue x) -> uniformLogDensity lo hi x),\n             distSample = (\\ g -> liftM Lebesgue $ MWC.uniformR (lo, hi) g)}\n\nuniformD :: (Ix a, MWC.Variate a) => a -> a -> Dist a\nuniformD lo hi =\n    let uniformLogDensity lo' hi' x | lo' <= x && x <= hi' = log density\n        uniformLogDensity _ _ _ = log 0\n        density = recip (fromInteger (toInteger (rangeSize (lo,hi))))\n    in Dist {logDensity = (\\ (Discrete x) -> uniformLogDensity lo hi x),\n             distSample = (\\ g -> liftM Discrete $ MWC.uniformR (lo, hi) g)}\n\nmarsaglia :: (MWC.Variate a, Ord a, Floating a, PrimMonad m) => PRNG m -> m (a, a)\nmarsaglia g = do -- \"Marsaglia polar method\"\n  x <- MWC.uniformR (-1,1) g\n  y <- MWC.uniformR (-1,1) g\n  let s = x * x + y * y\n      q = sqrt ((-2) * log s / s)\n  if 1 >= s && s > 0 then return (x * q, y * q) else marsaglia g\n\nchoose :: (PrimMonad m) => Mixture k -> PRNG m -> m (k, Prob)\nchoose (Mixture m) g = do\n  let peak = maximum (M.elems m)\n      unMix = M.map (LF.fromLogFloat . (/peak)) m\n      total = M.foldl' (+) (0::Double) unMix\n  p <- MWC.uniformR (0, total) g\n  let f !k !v b !p0 = let p1 = p0 + v in if p <= p1 then k else b p1\n      err p0 = error (\"choose: failure p0=\" ++ show p0 ++\n                      \" total=\" ++ show total ++\n                      \" size=\" ++ show (M.size m))\n  return $ (M.foldrWithKey f err unMix 0, LF.logFloat total * peak)\n\nchooseIndex :: (PrimMonad m) => [Double] -> PRNG m -> m Int\nchooseIndex probs g = do\n  p <- MWC.uniform g\n  return $ fromMaybe (error (\"chooseIndex: failure p=\" ++ show p))\n           (findIndex (p <=) (scanl1 (+) probs))\n\nnormal_rng :: (Real a, Floating a, MWC.Variate a, PrimMonad m) =>\n              a -> a -> PRNG m -> m a\nnormal_rng mu sd g | sd > 0 = do (x, _) <- marsaglia g\n                                 return (mu + sd * x)\nnormal_rng _ _ _ = error \"normal: invalid parameters\"\n\nnormalLogDensity :: Floating a => a -> a -> a -> a\nnormalLogDensity mu sd x = (-tau * square (x - mu)\n                            + log (tau / pi / 2)) / 2\n  where square y = y * y\n        tau = 1 / square sd\n\nnormal :: Double -> Double -> Dist Double \nnormal mu sd = Dist {logDensity = normalLogDensity mu sd . fromLebesgue,\n                     distSample = (\\g -> liftM Lebesgue $ normal_rng mu sd g)}\n\ncategoricalLogDensity :: (Eq b, Floating a) => [(b, a)] -> b -> a\ncategoricalLogDensity list x = log $ fromMaybe 0 (lookup x list)\n\ncategoricalSample :: (Num b, Ord b, PrimMonad m, MWC.Variate b) =>\n    [(t,b)] -> PRNG m -> m t\ncategoricalSample list g = do\n  let total = sum $ map snd list\n  p <- MWC.uniformR (0, total) g\n  let sumList = scanl1 (\\acc (a, b) -> (a, b + snd(acc))) list\n      elem' = fst $ head $ filter (\\(_,p0) -> p <= p0) sumList\n  return elem'\n\ncategorical :: Eq a => [(a,Double)] -> Dist a\ncategorical list = Dist {logDensity = categoricalLogDensity list . fromDiscrete,\n                         distSample = (\\g -> liftM Discrete $ categoricalSample list g)}\n\nlnFact :: Int -> Double\nlnFact = logFactorial\n\n-- Makes use of Atkinson's algorithm as described in:\n-- Monte Carlo Statistical Methods pg. 55\n--\n-- Further discussion at:\n-- http://www.johndcook.com/blog/2010/06/14/generating-poisson-random-values/\npoisson_rng :: (PrimMonad m) => Double -> PRNG m -> m Int\npoisson_rng lambda g' = make_poisson g'\n   where smu = sqrt lambda\n         b  = 0.931 + 2.53*smu\n         a  = -0.059 + 0.02483*b\n         vr = 0.9277 - 3.6224/(b - 2)\n         arep  = 1.1239 + 1.1368/(b-3.4)\n         lnlam = log lambda\n\n         make_poisson :: (PrimMonad m) => PRNG m -> m Int\n         make_poisson g = do u <- MWC.uniformR (-0.5,0.5) g\n                             v <- MWC.uniformR (0,1) g\n                             let us = 0.5 - abs u\n                                 k = floor $ (2*a / us + b)*u + lambda + 0.43\n                             case () of\n                               () | us >= 0.07 && v <= vr -> return k\n                               () | k < 0 -> make_poisson g\n                               () | us <= 0.013 && v > us -> make_poisson g\n                               () | accept_region us v k -> return k\n                               _  -> make_poisson g\n\n         accept_region :: Double -> Double -> Int -> Bool\n         accept_region us v k = log (v * arep / (a/(us*us)+b)) <=\n                                -lambda + (fromIntegral k)*lnlam - lnFact k\n\npoisson :: Double -> Dist Int\npoisson l =\n    let poissonLogDensity l' x | l' > 0 && x> 0 = (fromIntegral x)*(log l') - lnFact x - l'\n        poissonLogDensity l' x | x==0 = -l'\n        poissonLogDensity _ _ = log 0\n    in Dist {logDensity = poissonLogDensity l . fromDiscrete,\n             distSample = (\\g -> liftM Discrete $ poisson_rng l g)}\n\n-- Direct implementation of  \"A Simple Method for Generating Gamma Variables\"\n-- by George Marsaglia and Wai Wan Tsang.\ngamma_rng :: (PrimMonad m) => Double -> Double -> PRNG m -> m Double\ngamma_rng shape _   _ | shape <= 0.0  = error \"gamma: got a negative shape paramater\"\ngamma_rng _     scl _ | scl <= 0.0  = error \"gamma: got a negative scale paramater\"\ngamma_rng shape scl g | shape <  1.0  = do gvar1 <- gamma_rng (shape + 1) scl g\n                                           w <- MWC.uniformR (0,1) g\n                                           return $ scl * gvar1 * (w ** recip shape)\ngamma_rng shape scl g = do\n    let d = shape - 1/3\n        c = recip $ sqrt $ 9*d\n        -- Algorithm recommends inlining normal generator\n        -- n = normal_rng 1 c\n    v <- iterateUntil (> 0.0) $ normal_rng 1 c g\n        -- (v, g2) = until (\\y -> fst y > 0.0) (\\ (_, g') -> normal_rng 1 c g') (n g)\n    let x = (v - 1) / c\n        sqr = x * x\n        v3 = v * v * v\n    u <- MWC.uniformR (0.0, 1.0) g\n    let accept = u < 1.0 - 0.0331*(sqr*sqr) || log u < 0.5*sqr + d*(1.0 - v3 + log v3)\n    case accept of\n      True -> return $ scl*d*v3\n      False -> gamma_rng shape scl g\n\ngammaLogDensity :: Double -> Double -> Double -> Double\ngammaLogDensity shape scl x | x>= 0 && shape > 0 && scl > 0 =\n     scl * log shape - scl * x + (shape - 1) * log x - logGamma shape\ngammaLogDensity _ _ _ = log 0\n\ngamma :: Double -> Double -> Dist Double\ngamma shape scl = Dist {logDensity = gammaLogDensity shape scl . fromLebesgue,\n                        distSample = (\\g -> liftM Lebesgue $ gamma_rng shape scl g)}\n\nbeta_rng :: (PrimMonad m) => Double -> Double -> PRNG m -> m Double\nbeta_rng a b g | a <= 1.0 && b <= 1.0 = do\n                 u <- MWC.uniformR (0.0, 1.0) g\n                 v <- MWC.uniformR (0.0, 1.0) g\n                 let x = u ** (recip a)\n                     y = v ** (recip b)\n                 case (x+y) <= 1.0 of\n                   True -> return $ x / (x + y)\n                   False -> beta_rng a b g\nbeta_rng a b g = do ga <- gamma_rng a 1 g\n                    gb <- gamma_rng b 1 g\n                    return $ ga / (ga + gb)\n\nbetaLogDensity :: Double -> Double -> Double -> Double\nbetaLogDensity _ _ x | x < 0 || x > 1 = error \"beta: value must be between 0 and 1\"\nbetaLogDensity a b _ | a <= 0 || b <= 0 = error \"beta: parameters must be positve\" \nbetaLogDensity a b x = (logGamma (a + b)\n                        - logGamma a\n                        - logGamma b\n                        + (a - 1) * log x\n                        + (b - 1) * log (1 - x))\n\nbeta :: Double -> Double -> Dist Double\nbeta a b = Dist {logDensity = betaLogDensity a b . fromLebesgue,\n                 distSample = (\\g -> liftM Lebesgue $ beta_rng a b g)}\n\nlaplace_rng :: (PrimMonad m) => Double -> Double -> PRNG m -> m Double\nlaplace_rng mu sd g = MWC.uniformR (0.0, 1.0) g >>= sample\n   where sample u = return $ case u < 0.5 of\n                               True  -> mu + sd * log (u + u)\n                               False -> mu - sd * log (2.0 - u - u)\n\nlaplaceLogDensity :: Floating a => a -> a -> a -> a\nlaplaceLogDensity mu sd x = - log (2 * sd) - abs (x - mu) / sd\n\nlaplace :: Double -> Double -> Dist Double\nlaplace mu sd = Dist {logDensity = laplaceLogDensity mu sd . fromLebesgue,\n                      distSample = (\\g -> liftM Lebesgue $ laplace_rng mu sd g)}\n\n-- Consider having dirichlet return Vector\n-- Note: This is actually symmetric dirichlet\ndirichlet_rng :: (PrimMonad m) => Int ->  Double -> PRNG m -> m [Double]\ndirichlet_rng n' a g' = liftM normalize $ gammas g' n'\n  where gammas _ 0 = return ([], 0)\n        gammas g n = do (xs, total) <- gammas g (n-1)\n                        x <- gamma_rng a 1 g\n                        return ((x : xs), x+total)\n        normalize (b, total) = map (/ total) b\n\ndirichletLogDensity :: [Double] -> [Double] -> Double\ndirichletLogDensity a x | all (> 0) x = sum' (zipWith logTerm a x) + logGamma (sum a)\n  where sum' = foldl' (+) 0\n        logTerm b y = (b-1) * log y - logGamma b\ndirichletLogDensity _ _ = error \"dirichlet: all values must be between 0 and 1\"\n\n", "meta": {"hexsha": "170fe4e3292519c23fd7dd4d4a21a97b95924d05", "size": 10044, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Language/Hakaru/Distribution.hs", "max_stars_repo_name": "SamuelSchlesinger/hakaru", "max_stars_repo_head_hexsha": "214c251535925bd5789fad49f438b1de9dae0e65", "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": "Language/Hakaru/Distribution.hs", "max_issues_repo_name": "SamuelSchlesinger/hakaru", "max_issues_repo_head_hexsha": "214c251535925bd5789fad49f438b1de9dae0e65", "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": "Language/Hakaru/Distribution.hs", "max_forks_repo_name": "SamuelSchlesinger/hakaru", "max_forks_repo_head_hexsha": "214c251535925bd5789fad49f438b1de9dae0e65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1072961373, "max_line_length": 91, "alphanum_fraction": 0.5424133811, "num_tokens": 3070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49173642072417206}}
{"text": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Char\nimport Data.List\nimport Debug.Trace\nimport Numeric.LinearAlgebra hiding (Matrix, Vector)\nimport qualified Numeric.LinearAlgebra as LA\nimport System.Random.Mersenne\n\ntype FpType = Double\ntype Vector = LA.Vector FpType\ntype Matrix = LA.Matrix FpType\n\n-- Initializer\n\ninitVector :: MTGen -> Int -> IO (Vector)\ninitVector rng n = do\n    rs <- randoms rng\n    let v = fromList (take n rs)\n    return v\n\ninitMatrix :: MTGen -> Int -> Int -> IO (Matrix)\ninitMatrix rng n m = do\n    rs <- randoms rng :: IO [FpType]\n    let v = (n><m) $ take (n*m) rs\n    return v\n\ninitConnections :: MTGen -> (Layer, Layer) -> IO (WeightMatrix)\ninitConnections rng (l\u2081,l\u2082) = do\n    w <- initMatrix rng (neurons l\u2082) (neurons l\u2081)\n    return w\n\ninitMlp :: MTGen -> [Layer] -> IO (Network)\ninitMlp rng ls = do\n    ws <- mapM (initConnections rng) $ zip ls (tail ls)\n    let net = mlp ls ws\n    return net\n\n-- Helper\n\nvecToStr :: Vector -> String\nvecToStr v = \"[ \" ++ intercalate \"  \" (map show (toList v)) ++ \" ]\"\n\nvecsToStr :: [Vector] -> String\nvecsToStr vs = intercalate \"\\n\" (map vecToStr vs)\n\ndatasetToStr :: Dataset -> String\ndatasetToStr d = \"dataset: \" ++ show l ++ \" elements, \" ++ show u ++ \" targets\\n\"\n    where u = nub (map snd d)\n          l = length d\n\n-- Layers\n\n--TODO: allow 2d tensors for activation as well to facilitate softmax\ndata Layer = Layer {\n    \u03d5         :: FpType -> FpType,\n    \u03d5'        :: FpType -> FpType,\n    neurons   :: Int,\n    layerType :: String\n}\n\ninstance Show Layer where\n    show (Layer { neurons = n, layerType = t }) = t ++ \", \" ++ show n ++ \" neurons\"\n\nlinearLayer :: Int -> Layer\nlinearLayer n = Layer {\n    \u03d5         = id,\n    \u03d5'        = id,\n    neurons   = n,\n    layerType = \"linear\"\n}\n\nhyperbolicLayer :: Int -> Layer\nhyperbolicLayer n = Layer {\n    \u03d5         = tanh,\n    \u03d5'        = \\x -> 1 - tanh\u00b2 x,\n    neurons   = n,\n    layerType = \"tanh\"\n} where tanh\u00b2 = tanh . tanh\n\nsigmoidLayer :: Int -> Layer\nsigmoidLayer n = Layer {\n    \u03d5         = sigmoid,\n    \u03d5'        = \\x -> sigmoid x * (1 - sigmoid x),\n    neurons   = n,\n    layerType = \"sigmoid\"\n} where sigmoid x = 0.5 * (1 + tanh (0.5 * x))\n\n-- Networks\n\ndata Network = Network {\n    layers  :: [Layer],\n    weights :: [WeightMatrix],\n    netType :: String\n}\n\ntype WeightMatrix = Matrix\n\n--TODO: It would be nicer to enforce #layers == #weights+1 by zipping.\nmlp :: [Layer] -> [WeightMatrix] -> Network\nmlp ls ws = debug Network { layers = ls, weights = ws, netType = \"mlp\" }\n    where text  = map (\\x -> \"Layer \" ++ show (fst x) ++ \": \" ++ show (snd x)) (zip [1..] ls)\n          debug = trace $ \"Creating MLP\\n\" ++ intercalate \"\\n\" text ++ \"\\n\"\n\nforward :: Vector -> (Layer, WeightMatrix) -> Vector\nforward x (l,w) = mapVector (\u03d5 l) $ w <> x\n\nactivate :: Network -> Vector -> [Vector]\nactivate (Network { layers = ls, weights = ws }) x = debug result\n    where result = scanl forward \u03d5x $ zip (tail ls) ws\n          \u03d5x     = mapVector \u03d5\u2081 x\n          \u03d5\u2081     = \u03d5 (head ls)\n          debug  = trace (\"activate input\\n\" ++ vecToStr x ++ \"\\n\\nactivate output\\n\" ++ vecsToStr result ++ \"\\n\")\n\n-- Datasets\n\n--TODO: decouple classification/regression datasets properly, add bias s.t. it works flawlessly in all usages\ntype Dataset = [(Vector, Vector)]\n\n-- Training\n\ndata Trainer = Trainer {\n    \u03b7         :: FpType,\n    terminate :: TrainState -> Bool\n}\n\ndata TrainState = TrainState {\n    nEpochs :: Int,\n    \u03b4s      :: [FpType]\n} deriving (Show)\n\ntype Error = FpType\n\n--TODO: more useful termination criteria\nnEpochTrainer :: FpType -> Int -> Trainer\nnEpochTrainer lr n = debug Trainer { \u03b7 = lr, terminate = (> n) . nEpochs }\n    where debug = trace (\"Creating nEpochTrainer\\n\" ++ \"\u03b7 = \" ++ show lr ++ \"\\nmaxEpochs = \" ++ show n ++ \"\\n\")\n\n--TODO: actually perform epoch inside ST monad, put actual result\nepoch :: Dataset -> Network -> Trainer -> (Network, Error)\nepoch d net t = (net, 0)\n\n_train :: TrainState -> Dataset -> Network -> Trainer -> Network\n_train s d net t = do\n    let (net',\u03b4') = epoch d net t\n    let s' = update s where update s = TrainState { nEpochs = 1 + (nEpochs s), \u03b4s = \u03b4s s ++ [\u03b4'] }\n    let statusMessage = \"\u03b4_\" ++ show (nEpochs s') ++ \" = \" ++ show \u03b4' ++ \"\\n\" ++ show s' ++ \"\\n\"\n\n    if (terminate t) s'\n        then trace (\"Finished Training.\\n\") net'\n        else trace statusMessage $ _train s' d net' t\n\n--TODO: support testing set/cross validation\ntrain :: Dataset -> Network -> Trainer -> Network\ntrain = _train s\u2080 where s\u2080 = TrainState { nEpochs = 0, \u03b4s = [] }\n\n-- Evaluation\n\n--TODO\n\n-- Testing\n\nmain :: IO()\nmain = do\n    rng <- newMTGen Nothing\n\n    let l\u2081 = linearLayer 5\n    let l\u2082 = sigmoidLayer 3\n    let l\u2083 = linearLayer 5\n    let layers = [l\u2081,l\u2082,l\u2083]\n\n    !net <- initMlp rng layers\n    xs <- mapM (initVector rng) (take 100 $ repeat 5)\n\n    let ys = xs\n    let dataset = zip xs ys\n    let trainer = nEpochTrainer 0.1 5\n    let !trainedNet = train dataset net trainer\n\n    putStrLn $ \"Done!\\n\"\n", "meta": {"hexsha": "31037fe88784047daf76dc2492d707da055338dc", "size": 4960, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/mlp.hs", "max_stars_repo_name": "mkraemer67/haskell-ml", "max_stars_repo_head_hexsha": "2a760ca5638980100d6bcdd173c8a1727d8d4e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-03-19T07:47:59.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-25T04:12:26.000Z", "max_issues_repo_path": "src/mlp.hs", "max_issues_repo_name": "mkraemer67/haskell-ml", "max_issues_repo_head_hexsha": "2a760ca5638980100d6bcdd173c8a1727d8d4e51", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlp.hs", "max_forks_repo_name": "mkraemer67/haskell-ml", "max_forks_repo_head_hexsha": "2a760ca5638980100d6bcdd173c8a1727d8d4e51", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4033149171, "max_line_length": 114, "alphanum_fraction": 0.602016129, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49173641557919057}}
{"text": "--------------------------------------------------------------------------------\n--\n--  Copyright (c) 2010 - 2013 Tad Doxsee\n--  All rights reserved.\n--\n--  Author: Tad Doxsee\n--\n--------------------------------------------------------------------------------\n\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE  FlexibleInstances    #-}\n\n-- * base\nimport Foreign           (ForeignPtr, Storable)\nimport Foreign.C.Types   (CDouble, CInt, CSize)\n\n-- * vector\nimport qualified Data.Vector.Storable.Mutable as V\n\n-- * cholmod\nimport Numeric.LinearAlgebra.CHOLMOD.CholmodXFaceLow\nimport Numeric.LinearAlgebra.CHOLMOD.CholmodXFace\n\n--------------------------------------------------------------------------------\n\nmain :: IO ()\nmain = do\n\n  c <- allocCommon :: IO (ForeignPtr Common)\n  startC c \n\n  let n = 5                  :: CSize\n      nz = (n+1) * n `div` 2 :: CSize\n      nn = fromIntegral n    :: CSize\n\n\n  at <-allocTriplet n n nz stSquareSymmetricLower xtReal c\n       :: IO (Matrix Triplet)\n\n  atNRow  <- getNRow  at :: IO CSize\n  atNCol  <- getNCol  at :: IO CSize\n  atNZMax <- getNZMax at :: IO CSize\n\n  putStrLn \"\"\n  putStrLn $ \"at: (\" ++ show atNRow\n                     ++ \" x \" ++ show atNCol ++ \")\"\n  putStrLn $ \"nzmax: \" ++ show atNZMax\n\n  iv <- tripletGetRowIndices at :: IO (V.IOVector CInt)\n  jv <- tripletGetColIndices at :: IO (V.IOVector CInt)\n  xt  <- tripletGetX at\n\n\n  let nni = fromIntegral nn\n\n  let ij      = [(i, j) | i <- [0 .. nni-1], j <- [0 .. i]] :: [(CInt, CInt)]\n      (ia,ja) = unzip ij                                    :: ([CInt], [CInt])\n      \n      -- the elements of the matrix are (lower half)\n      --\n      --  11.0\n      --  21.0  22.0\n      --  31.0  32.0  33.0\n      --  41.0  42.0  43.0  44.0\n      --  51.0  52.0  53.0  54.0  55.0\n      \n      xp = [11, 21, 22, 31, 32, 33, 41, 42, 43, 44, 51, 52, 53, 54, 55]\n           :: [CDouble]\n\n  writev iv ia\n  writev jv ja\n  writev xt xp\n\n  let nnz = fromIntegral $ Prelude.length xp :: CSize\n\n  tripletSetNNZ at nnz\n\n\n  as <- tripletToSparse at c :: IO (Matrix Sparse)\n  b  <- ones n 1 xtReal c    :: IO (Matrix Dense)\n  l  <- analyze as c         :: IO (ForeignPtr Factor)\n  factorize as l c\n  x  <- solve stA l b c      :: IO (Matrix Dense)\n\n  xNRow <- getNRow x\n  xNCol <- getNCol x\n\n  xv <- getX x :: IO (V.IOVector CDouble)\n\n  putStrLn \"\"\n  putStrLn $ \"xv: (\" ++ show xNRow\n                     ++ \" x \" ++ show xNCol ++ \")\"\n\n  xl <- readv xv\n  mapM_ (putStrLn . show) xl\n\n\n  r <- denseCopy b c\n\n  let oneL = [1, 0] :: [CDouble]\n      m1L = [-1, 0] :: [CDouble]\n\n  _ <- sdMult as noTranspose m1L oneL x r c\n\n  norm <- denseNorm r infNorm c :: IO CDouble\n\n  putStrLn $ \"norm: \" ++ show norm\n\n  putStrLn \"done\"\n\n\n\nwritev :: (Storable a) => V.IOVector a -> [a] -> IO ()\n\nwritev v xs =\n  sequence_ [V.write v i x | (i, x) <- zip [0 .. (Prelude.length xs - 1)] xs]\n\n\nreadv :: (Storable a) => V.IOVector a -> IO [a]\nreadv v = sequence [V.read v i | i <- [0 .. (V.length v) - 1]]\n", "meta": {"hexsha": "83fcb882e75a41e325e46042b985ee6fcdfdba89", "size": 2972, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/example1.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": "examples/example1.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": "examples/example1.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": 24.5619834711, "max_line_length": 80, "alphanum_fraction": 0.5023553163, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.49171753888722186}}
{"text": "module LatticeSymmetries.ComplexRational\n  ( ComplexRational (..),\n    ConvertibleToComplexDouble (..),\n    realPart,\n    imagPart,\n    conjugate,\n    magnitudeSquared,\n    Cscalar,\n  )\nwhere\n\nimport Data.Complex (Complex (..))\nimport Foreign.C.Types (CDouble (..))\nimport Text.PrettyPrint.ANSI.Leijen (Pretty (..))\nimport qualified Text.PrettyPrint.ANSI.Leijen as Pretty\n\ndata ComplexRational = ComplexRational {-# UNPACK #-} !Rational {-# UNPACK #-} !Rational\n  deriving stock (Eq, Show)\n\nprettyRational :: Rational -> Pretty.Doc\nprettyRational x\n  | realToFrac (fromRational x :: Double) == x = Pretty.double (fromRational x :: Double)\n  | otherwise = Pretty.rational x\n\ninstance Pretty ComplexRational where\n  pretty (ComplexRational r i)\n    | i == 0 = prettyRational r\n    | otherwise = Pretty.parens $ prettyRational r <> Pretty.text \" + \" <> prettyRational i <> \"\ud835\udd5a\"\n\nrealPart :: ComplexRational -> Rational\nrealPart (ComplexRational r _) = r\n{-# INLINE realPart #-}\n\nimagPart :: ComplexRational -> Rational\nimagPart (ComplexRational _ i) = i\n{-# INLINE imagPart #-}\n\nconjugate :: ComplexRational -> ComplexRational\nconjugate (ComplexRational r i) = (ComplexRational r (-i))\n{-# INLINE conjugate #-}\n\nmagnitudeSquared :: ComplexRational -> Rational\nmagnitudeSquared (ComplexRational r i) = r * r + i * i\n{-# INLINE magnitudeSquared #-}\n\ninstance Num ComplexRational where\n  {-# INLINE (+) #-}\n  {-# INLINE (-) #-}\n  {-# INLINE (*) #-}\n  {-# INLINE fromInteger #-}\n  (ComplexRational r i) + (ComplexRational r' i') = ComplexRational (r + r') (i + i')\n  (ComplexRational r i) - (ComplexRational r' i') = ComplexRational (r - r') (i - i')\n  (ComplexRational r i) * (ComplexRational r' i') = ComplexRational (r * r' - i * i') (r * i' + i * r')\n  negate (ComplexRational r i) = ComplexRational (-r) (-i)\n  abs _ = error \"Num instance of ComplexRational does not implement abs\"\n  signum _ = error \"Num instance of ComplexRational does not implement signum\"\n  fromInteger n = ComplexRational (fromInteger n) 0\n\ninstance Fractional ComplexRational where\n  {-# INLINE (/) #-}\n  {-# INLINE fromRational #-}\n  (ComplexRational r i) / (ComplexRational r' i') =\n    ComplexRational ((r * r' + i * i') / d) ((-r * i' + i * r') / d)\n    where\n      d = r' * r' + i' * i'\n  fromRational a = ComplexRational a 0\n\n-- class Fractional a => ComplexFloating a where\n--   toComplexDouble :: a -> Complex Double\n--   fromComplexDouble :: Complex Double -> a\n\ntype Cscalar = Complex CDouble\n\nclass Fractional a => ConvertibleToComplexDouble a where\n  toComplexDouble :: a -> Cscalar\n  fromComplexDouble :: Cscalar -> a\n\ninstance ConvertibleToComplexDouble ComplexRational where\n  toComplexDouble (ComplexRational r i) = (fromRational r) :+ (fromRational i)\n  fromComplexDouble (r :+ i) = ComplexRational (toRational r) (toRational i)\n\ninstance ConvertibleToComplexDouble (Complex CDouble) where\n  toComplexDouble = id\n  fromComplexDouble = id\n\ninstance ConvertibleToComplexDouble (Complex Double) where\n  toComplexDouble = coerce\n  fromComplexDouble = coerce\n", "meta": {"hexsha": "e52fc0b98363f1a40a87ab7fcde8e92f47df837d", "size": 3042, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/LatticeSymmetries/ComplexRational.hs", "max_stars_repo_name": "twesterhout/lattice-symmetries-haskell", "max_stars_repo_head_hexsha": "812bf24d400d727a217a450171915c216c45c88e", "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/LatticeSymmetries/ComplexRational.hs", "max_issues_repo_name": "twesterhout/lattice-symmetries-haskell", "max_issues_repo_head_hexsha": "812bf24d400d727a217a450171915c216c45c88e", "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/LatticeSymmetries/ComplexRational.hs", "max_forks_repo_name": "twesterhout/lattice-symmetries-haskell", "max_forks_repo_head_hexsha": "812bf24d400d727a217a450171915c216c45c88e", "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.1797752809, "max_line_length": 103, "alphanum_fraction": 0.6939513478, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.49127096829425426}}
{"text": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\n\nmodule Lib\n    ( someFunc\n    ) where\n\n\nimport Numeric.GSL.Fitting\nimport Numeric.LinearAlgebra\nimport Numeric.AD\nimport Numeric.AD.Internal.Reverse\nimport Data.Reflection\n\nsomeFunc :: IO ()\nsomeFunc = putStrLn \"someFunc\"\n\n\ntype FitRes = ([(Double, Double)], Matrix Double)\ntype FitData = [([Double],([Double],Double))]\n\n-- type ManualJacob = ([Double] -> [Double] -> [[Double]]) \n\ndata JacobType = AutoJacob | ManualJacob ([Double] -> [Double] -> [[Double]])\n\ndata FitParams = FitParams { jacob :: JacobType\n                           , guess :: [Double]\n                           , iter :: Int \n                           , absTol :: Double  \n                           , relTol :: Double                                 \n                           }  \n\ndefaultParams = FitParams { jacob = AutoJacob,\n                            guess = repeat 1,\n                            iter = 1000,\n                            absTol = 1E-20,\n                            relTol = 1E-20 }\n\n     -- ([Double] -> [Double] -> [Double]) model\n     -- ([Double] -> [Double] -> [[Double]]) model der\n-- Only Doubles since hmatrix requires it\nfit :: [Double]\n     -> [Double]\n     -> [Double]\n     -> (forall a . Floating a => [a]->[a]->[a])\n     -> JacobType\n     -> [Double]->  Maybe FitRes\n\n\n\nfit xs ys sigma model jacobian guess\n    | xeqy && ( seqx || seqone)  = Just $ fitModelScaled 1E-20 1E-20 500 (model, sanitizedJacob jacobian) fitdata guess\n    | otherwise  = Nothing\n    where \n    lx = length xs\n    ly = length ys\n    ls = length sigma\n    xeqy = lx == ly\n    seqx = ls == lx\n    seqone = ls == 1\n    fitdata = unsafeFormatData xs ys sigma\n    sanitizedJacob jacob = case jacob of AutoJacob -> mkJac model\n                                         ManualJacob f -> f\n\n\n{-\nfit :: [Double]\n     -> [Double]\n     -> [Double]\n     -> (forall a . Floating a => [a]->[a]->[a])\n     -> ([Double] -> [Double] -> [[Double]])\n     -> [Double]->  Maybe FitRes\n\n\n\nfit xs ys sigma model jacobian guess\n    | xeqy && ( seqx || seqone)  = Just $ fitModelScaled 1E-20 1E-20 500 (model, mkJac model) fitdata guess\n    | otherwise  = Nothing\n    where \n    lx = length xs\n    ly = length ys\n    ls = length sigma\n    xeqy = lx == ly\n    seqx = ls == lx\n    seqone = ls == 1\n    fitdata = unsafeFormatData xs ys sigma\n-}\n\n{-\nfit :: [Double]\n     -> [Double]\n     -> [Double]\n     -> ([Double] -> [Double] -> [Double])\n     -> ([Double] -> [Double] -> [[Double]])\n     -> [Double]->  Maybe FitRes\n\n\n\nfit xs ys sigma model jacobian guess\n    | xeqy && ( seqx || seqone)  = Just $ fitModelScaled 1E-20 1E-20 500 (model, jacobian) fitdata guess\n    | otherwise  = Nothing\n    where \n    lx = length xs\n    ly = length ys\n    ls = length sigma\n    xeqy = lx == ly\n    seqx = ls == lx\n    seqone = ls == 1\n    fitdata = unsafeFormatData xs ys sigma -}\n\n\nunsafeFormatData :: [Double] -> [Double] -> [Double] -> FitData\nunsafeFormatData xs ys sigma\n    |  length sigma == length xs = zip (return <$> xs) $ zip (return <$> ys) sigma\n    |  length sigma == 1 = zip (return <$> xs) $ zip (return <$> ys) (repeat (head sigma))\n\n\n\n--jac :: (Num a, Traversable f, Functor g) =>\n  --     (forall s. Reifies s Tape => f (Reverse s a) -> [Reverse s a] -> g (Reverse s a))\n    --   -> f a\n      -- -> g (f a)\n\njac2 :: (Num a, Traversable f1, Traversable f2, Functor g) =>\n       (forall s. Reifies s Tape => f1 (Reverse s a) -> f2 (Reverse s a) -> g (Reverse s a))\n       -> f1 a\n       -> f2 a\n       \n       -> g (f1 a)\n\njac2 f p x = jacobian ((flip f) (fmap auto x)) p\n\njac3 :: (Floating a, Traversable f1, Traversable f2, Functor g) =>\n       (forall s. Reifies s Tape => f1 (Reverse s a) -> f2 (Reverse s a) -> g (Reverse s a))\n       -> f1 a\n       -> f2 a\n       \n       -> g (f1 a)\n \njac3 f p x = jacobian ((flip f) (fmap auto x)) p\n\n\nmkJac :: (Num a) => (forall s. Reifies s Tape => [Reverse s a] -> [Reverse s a] -> [Reverse s a])\n       -> [a]\n       -> [a]\n       \n       -> [[a]]\n\nmkJac f p x = jacobian ((flip f) (fmap auto x)) p\n\n-- to fit data\nexpModel [a,lambda,b] [t] = [a * exp (-lambda * t)+b]\n\nexpModelDer [a,lambda,b] [t] = [[exp (-lambda * t), -t * a * exp(-lambda*t) , 1]]\n\n-- to generate data\nexpModel2 [a,lambda,b] t = a * exp (-lambda * t)+b\n\nexpModelDer2 [a,lambda,b] t = [[exp (-lambda * t), -t * a * exp(-lambda*t) , 1]]\n-- to go from unbox to box:\n-- a = (\\p -> \\x -> return (expModel2 p (x !! 0)))::Floating a => [a] -> [a] -> [a]\n\nxs = [a | a <- [0..100]]\nsigma = [0.1]\nys = (map (expModel2 [5,0.1,1]) xs)\n\n\n\n\n", "meta": {"hexsha": "0ce7649c5468861d73bdd1b210958ed8c2613c87", "size": 4568, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "Magalame/Spinell", "max_stars_repo_head_hexsha": "03e819e4164f6e0361b9b320002a34f123d47ecd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "Magalame/Spinell", "max_issues_repo_head_hexsha": "03e819e4164f6e0361b9b320002a34f123d47ecd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lib.hs", "max_forks_repo_name": "Magalame/Spinell", "max_forks_repo_head_hexsha": "03e819e4164f6e0361b9b320002a34f123d47ecd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7134502924, "max_line_length": 119, "alphanum_fraction": 0.5190455342, "num_tokens": 1404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4910326900429601}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE InstanceSigs           #-}\n{-# LANGUAGE MultiParamTypeClasses  #-}\n{-# LANGUAGE NamedFieldPuns         #-}\n{-# LANGUAGE QuantifiedConstraints  #-}\n{-# LANGUAGE RecordWildCards        #-}\n{-# LANGUAGE ScopedTypeVariables    #-}\n\nmodule Q.MonteCarlo where\nimport           Control.Monad.State\nimport           Data.RVar\nimport           Q.Stochastic.Discretize\nimport           Q.Stochastic.Process\nimport           Control.Monad\nimport           Q.ContingentClaim\nimport Data.Random\nimport Q.Time\nimport Data.Time\nimport Statistics.Distribution (cumulative)\nimport Statistics.Distribution.Normal (standard)\nimport Q.ContingentClaim.Options\nimport Q.Types\n\ntype Path b = [(Time, b)]\n\n-- |Summary type class aggregates all priced values of paths\nclass (PathPricer p)  => Summary m p | m->p where\n  -- | Updates summary with given priced pathes\n  sSummarize      :: m -> [p] -> m\n\n  -- | Defines a metric, i.e. calculate distance between 2 summaries\n  sNorm           :: m -> m -> Double\n\n-- | Path generator is a stochastic path generator\nclass PathGenerator m where\n  pgMkNew         :: m->IO m\n  pgGenerate      :: Integer -> m -> Path b\n\n-- | Path pricer provides a price for given path\nclass PathPricer m where\n  ppPrice :: m -> Path b -> m\n\n\ntype MonteCarlo s a = StateT [(Time, s)] RVar a\n\n\n-- | Generate a single trajectory stopping at each provided time.\ntrajectory :: forall a b d. (StochasticProcess a b, Discretize d b) =>\n             d        -- ^ Discretization scheme\n           -> a        -- ^ The stochastic process\n           -> b        -- ^ \\(S(0)\\)\n           -> [Time]   -- ^ Stopping points \\(\\{t_i\\}_i^n \\) where \\(t_i > 0\\)\n           -> [RVar b] -- ^ \\(dW\\)s. One for each stopping point.\n           -> RVar [b] -- ^ \\(S(0) \\cup \\{S(t_i)\\}_i^n \\) \ntrajectory disc p s0 times dws = reverse <$> evalStateT (onePath times dws) initState' where\n  initState' :: [(Time, b)]\n  initState' = [(0, s0)]\n\n  onePath :: [Time] -> [RVar b] -> MonteCarlo b [b]\n  onePath [] _ = do\n    s <- get\n    return $ map snd s\n  onePath (t1:tn) (dw1:dws) = do\n    s <- get\n    let t0 = head s\n    b <- lift $ pEvolve p disc t0 t1 dw1\n    put $ (t1, b) : s\n    onePath tn dws\n\n-- | Generate multiple trajectories. See 'trajectory'\ntrajectories:: forall a b d. (StochasticProcess a b, Discretize d b) =>\n             Int        -- ^Num of trajectories\n           -> d          -- ^Discretization scheme\n           -> a          -- ^The stochastic process\n           -> b          -- ^\\(S(0)\\)\n           -> [Time]     -- ^Stopping points \\(\\{t_i\\}_i^n \\) where \\(t_i > 0\\)\n           -> [RVar b]   -- ^\\(dW\\)s. One for each stopping point.\n           -> RVar [[b]] -- ^\\(S(0) \\cup \\{S(t_i)\\}_i^n \\) \ntrajectories n disc p initState times dws = replicateM n $ trajectory disc p initState times dws\n\nobservationTimes :: ContingentClaim a -> [Day]\nobservationTimes = undefined\n\nclass Model a b | a -> b where\n  discountFactor :: a -> YearFrac -> YearFrac -> RVar Rate\n  evolve   :: a -> YearFrac -> StateT (YearFrac, b) RVar Double\n", "meta": {"hexsha": "c322dc7a4f1dcf42374c1adc589f56e558087562", "size": 3114, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Q/MonteCarlo.hs", "max_stars_repo_name": "ghais/lowq", "max_stars_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-01T17:50:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T18:06:22.000Z", "max_issues_repo_path": "src/Q/MonteCarlo.hs", "max_issues_repo_name": "ghais/lowq", "max_issues_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "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/Q/MonteCarlo.hs", "max_forks_repo_name": "ghais/lowq", "max_forks_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3863636364, "max_line_length": 96, "alphanum_fraction": 0.5944123314, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.49098332300858116}}
{"text": "-- | see examples/\nmodule DimMat (\n\n   -- * Quasiquotes\n   matD,\n   blockD,\n \n\n   -- * Data.Packed.Vector\n   (@>),\n   -- * Data.Packed.Matrix\n   -- ** dimension\n   cols, rows,\n   colsNT, rowsNT,\n   hasRows, hasCols,\n   -- (><),\n   trans,\n   -- reshape, flatten, fromLists, toLists, buildMatrix,\n   -- broken\n   ToHLists(toHLists), toHList, FromHLists(fromHLists), fromHList,\n   (@@>),\n\n   -- asRow, asColumn, fromRows, toRows, fromColumns, toColumns\n   -- fromBlocks\n#if MIN_VERSION_hmatrix(0,15,0)\n   diagBlock,\n#endif\n   -- toBlocks, toBlocksEvery, repmat, flipud, fliprl\n   -- subMatrix, takeRows, dropRows, takeColumns, dropColumns,\n   -- extractRows, diagRect, takeDiag, mapMatrix,\n   -- mapMatrixWithIndexM, mapMatrixWithIndexM_, liftMatrix,\n   -- liftMatrix2, liftMatrix2Auto, fromArray2D,\n\n   ident, -- where to put this?\n   -- * Numeric.Container\n   -- constant, linspace,\n   diag,\n   ctrans,\n   -- ** Container class\n   scalar,\n   conj,\n   scale, scaleRecip,\n   recipMat,\n   addConstant,\n   add,\n   sub,\n   mulMat, mulVec,\n   divideMat, divideVec,\n   equal,\n   arctan2,\n   hconcat,\n   vconcat,\n   cmap,\n   konst,\n   zeroes,\n   -- build, atIndex, minIndex, maxIndex, minElement, maxElement,\n   -- sumElements, prodElements, step, cond, find, assoc, accum,\n   -- Convert\n   -- ** Product class\n   Dot(..), \n   -- absSum, norm1, norm2, normInf,\n   -- norm1, normInf,\n   pnorm,\n   -- optimiseMult, mXm, mXv, vXm, (<.>),\n   -- (<>), (<\\>), outer, kronecker,\n   -- ** Random numbers\n   -- ** Element conversion\n   -- ** Input/Output\n   -- ** Experimental\n\n   -- * Numeric.LinearAlgebra.Algorithms\n   -- | incomplete wrapper for \"Numeric.LinearAlgebra.Algorithms\"\n\n   -- ** Linear Systems\n   -- linearSolve, luSolve, cholSolve, linearSolveLS, linearSolveSVD,\n   inv,\n   PInv(pinv), \n   pinvTol,\n   det,\n   -- invlndet,\n   rank,\n   -- rcond,\n   -- ** Matrix factorizations\n\n   -- *** Singular value decomposition\n   -- *** Eigensystems\n   -- eigs\n   {-\n   wrapEig, wrapEigOnly,\n   EigV, EigE,\n   -- **** eigenvalues and eigenvectors\n   eig,\n   eigC,\n   eigH,\n   eigH',\n   eigR,\n   eigS,\n   eigS',\n   eigSH,\n   eigSH',\n\n   -- **** eigenvalues\n   eigOnlyC,\n   eigOnlyH,\n   eigOnlyR,\n   eigOnlyS,\n   eigenvalues,\n   eigenvaluesSH,\n   eigenvaluesSH',\n   -}\n\n   -- *** QR\n   -- *** Cholesky\n   -- *** Hessenberg\n   -- *** Schur\n   -- *** LU \n\n   -- ** Matrix functions\n   -- sqrtm, matFunc\n   expm,\n\n   -- ** Nullspace\n   -- ** Norms\n   -- ** Misc\n   -- ** Util \n\n   -- * Automatic Differentiation\n   -- ad\n#ifdef WITH_Ad\n   diff,\n#endif\n\n\n    -- * todo arrange\n    DotS,\n    MultEq,\n\n    -- * to keep types looking ok\n    D,\n    module Data.HList.CommonMain,\n    Complex, \n\n    -- ** \"Numeric.NumType\"\n    Pos, Neg, Succ, Zero, Neg1,\n    ) where\n    \nimport Numeric.NumType\nimport DimMat.Internal\nimport DimMat.QQ\nimport Data.HList.CommonMain\nimport Data.Complex\n", "meta": {"hexsha": "3afe39f54d72626695796279e6d48a2cad22e5e5", "size": 2861, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "DimMat.hs", "max_stars_repo_name": "aavogt/DimMat", "max_stars_repo_head_hexsha": "2d53043f6e2e7d06b3ce662e3d289635ceddc1b7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-11-15T11:11:55.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-15T11:11:55.000Z", "max_issues_repo_path": "DimMat.hs", "max_issues_repo_name": "aavogt/DimMat", "max_issues_repo_head_hexsha": "2d53043f6e2e7d06b3ce662e3d289635ceddc1b7", "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": "DimMat.hs", "max_forks_repo_name": "aavogt/DimMat", "max_forks_repo_head_hexsha": "2d53043f6e2e7d06b3ce662e3d289635ceddc1b7", "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": 18.8223684211, "max_line_length": 69, "alphanum_fraction": 0.5997902831, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49091644436187615}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Statistics.Distribution.Hypergeometric.GenVar.Test where\n\nimport Data.Word\nimport Data.Int\n\nimport Statistics.Distribution.Hypergeometric.GenVar\n\nimport System.Random.MWC (initialize, GenIO)\n\nimport Data.Vector (fromList)\n\nimport Test.QuickCheck\nimport Test.QuickCheck.All\nimport Test.QuickCheck.Monadic\n\nimport Distribution.TestSuite.QuickCheck\n\ntestArbitraryRandom :: (GenIO -> IO Bool) -> [Word32] -> Property\ntestArbitraryRandom f a = monadicIO $ do\n  b <- run $ initialize (fromList a) >>= f\n  assert b \n\ntests :: IO [Test]\ntests = return\n\n  [ testGroup \"identities\"\n\n    [ testGroup \"small\"\n\n      [ testProperty \"draw nil\" $ \\p -> testArbitraryRandom $ \\g -> do\n        let i = (getSmall . getPositive) p :: Int64\n        v <- genVar (0, i, i) g\n        return $ v == 0\n\n      , testProperty \"draw all\" $ \\p -> testArbitraryRandom $ \\g -> do\n        let i = (getSmall . getPositive) p :: Int64\n        v <- genVar (i, i, i) g\n        return $ v == i\n\n      ]\n\n    , testGroup \"large\"\n\n      [ testProperty \"draw nil\" $ \\p -> testArbitraryRandom $ \\g -> do\n        let i = (getLarge . getPositive) p :: Int64\n        v <- genVar (0, i, i) g\n        return $ v == 0\n\n      , testProperty \"draw all\" $ \\p -> testArbitraryRandom $ \\g -> do\n        let i = (getLarge . getPositive) p :: Int64\n        v <- genVar (i, i, i) g\n        return $ v == i\n\n      ]\n\n    ]\n\n  ]\n", "meta": {"hexsha": "f626ebfcb56f760272383b4ef87130f3a13b3459", "size": 1417, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Distribution/Hypergeometric/GenVar/Test.hs", "max_stars_repo_name": "srijs/statistics-hypergeometric-gen", "max_stars_repo_head_hexsha": "2fa15add0571a0308535dea0914ed03613266d8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-03-26T15:05:49.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-07T15:32:44.000Z", "max_issues_repo_path": "src/Statistics/Distribution/Hypergeometric/GenVar/Test.hs", "max_issues_repo_name": "srijs/statistics-hypergeometric-gen", "max_issues_repo_head_hexsha": "2fa15add0571a0308535dea0914ed03613266d8d", "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/Statistics/Distribution/Hypergeometric/GenVar/Test.hs", "max_forks_repo_name": "srijs/statistics-hypergeometric-gen", "max_forks_repo_head_hexsha": "2fa15add0571a0308535dea0914ed03613266d8d", "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": 23.2295081967, "max_line_length": 70, "alphanum_fraction": 0.6083274524, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49073580633130787}}
{"text": "{-# LANGUAGE NamedFieldPuns, TemplateHaskell #-}\n\nmodule School.Train.Test.GradientDescent\n( gradientDescentTest ) where\n\nimport Conduit ((.|), liftIO, runConduit, sinkNull, yield, yieldMany)\nimport Data.Either (isLeft)\nimport Numeric.LinearAlgebra ((><))\nimport School.TestUtils (addClasses, assertRight, empty, isSorted,\n                         randomAffineParams, randomNNInts, randomMatrix,\n                         unitCorrect, weight1)\nimport School.FileIO.AppIO (runAppIO)\nimport School.FileIO.FileType (FileType, toExtension)\nimport School.FileIO.FileHeader (FileHeader(..))\nimport School.FileIO.MatrixSink (matrixIntSink)\nimport School.Train.AppTrain (AppTrain)\nimport School.Train.GradientDescent\nimport School.Train.SimpleDescentUpdate (simpleDescentUpdate)\nimport School.Train.StoppingCondition (maxIterations)\nimport School.Train.IterationHandler (storeCost)\nimport School.Train.TrainState (TrainState(..), HandlerStore(..), def)\nimport School.Types.PingPong (pingPongSingleton)\nimport School.Types.DataType (DataType(..))\nimport School.Types.Error (Error)\nimport School.Types.FloatEq ((~=))\nimport School.Unit.CostFunction (CostFunction)\nimport School.Unit.Affine (affine)\nimport School.Unit.MultiNoulli (multiNoulli)\nimport School.Unit.RecLin (recLin)\nimport School.Unit.UnitParams (UnitParams(..))\nimport System.Directory (removeFile)\nimport Test.Tasty (TestTree)\nimport Test.Tasty.QuickCheck hiding ((><))\nimport Test.Tasty.TH\nimport Test.QuickCheck.Monadic (assert, monadicIO)\n\nprop_no_units :: Property\nprop_no_units = monadicIO $ do\n  result <- liftIO $ gradientDescent (yield empty)\n                                     []\n                                     weight1\n                                     simpleDescentUpdate\n                                     mempty\n                                     mempty\n                                     def\n  assert $ isLeft result\n\nprop_iterations :: Positive Int -> Positive Int -> Positive Int -> Property\nprop_iterations (Positive n) (Positive b) (Positive f) = monadicIO $ do\n  input <- liftIO $ randomMatrix b f\n  let source =  yieldMany . repeat $ input\n  result <- liftIO $ gradientDescent source\n                                    [recLin]\n                                    weight1\n                                    simpleDescentUpdate\n                                    (maxIterations n)\n                                    mempty\n                                    def\n  assertRight ((== n) . iterationCount) result\n\nprop_cost_decline :: Positive Int -> Positive Int -> Positive Int -> Property\nprop_cost_decline (Positive b) (Positive f) (Positive o) = monadicIO $ do\n  input <- liftIO $ randomMatrix b f\n  let source =  yieldMany . repeat $ input\n  paramList <- liftIO $ pingPongSingleton <$> randomAffineParams f o\n  let initState = def { handlerStore = CostList []\n                                  , learningRate = 1e-2\n                                  , paramList\n                                  }\n  result <- liftIO $ gradientDescent source\n                                     [affine]\n                                     weight1\n                                     simpleDescentUpdate\n                                     (maxIterations 5)\n                                     storeCost\n                                     initState\n  assertRight ((\\(CostList c) -> isSorted c) . handlerStore)\n              result\n\nmultiSingle :: CostFunction Double (AppTrain a)\nmultiSingle = multiNoulli Nothing Nothing\n\nprop_multinoulli_single_file :: Positive Int -> Positive Int -> Property\nprop_multinoulli_single_file (Positive c) (Positive b) = monadicIO $ do\n  activation <- liftIO $ randomMatrix b c\n  classes <- liftIO $ randomNNInts (c - 1) b\n  let input = addClasses classes activation\n  let source =  yieldMany . repeat $ input\n  let initState = def { handlerStore = CostList []\n                      , paramList = pingPongSingleton EmptyParams\n                      }\n  result <- liftIO $ gradientDescent source\n                                     [unitCorrect classes]\n                                     multiSingle\n                                     simpleDescentUpdate\n                                     (maxIterations 5)\n                                     storeCost\n                                     initState\n  let check = CostList $ replicate 5 (-1)\n  assertRight ((~= check) . handlerStore) result\n\nmultiTwo :: [Int]\n         -> Int\n         -> FileType\n         -> IO ( Either Error ( FilePath\n                              , CostFunction Double (AppTrain a)))\nmultiTwo classes iterations fType = do\n  let fName = \"test.\" ++ (toExtension fType)\n  let cols = 1\n  let nClasses = length classes\n  let rows = iterations * nClasses\n  let header = FileHeader { dataType = INT32B, cols, rows }\n  let matrix = (rows >< cols) . concat . (replicate iterations)\n             . (map fromIntegral) $ classes\n  writeRes <- runAppIO . runConduit $ yield matrix\n                                   .| matrixIntSink fType header fName\n                                   .| sinkNull\n  let multi = multiNoulli (Just fName) (Just $ header { rows = nClasses })\n  either (return . Left)\n         (return . pure . Right $ (fName, multi))\n         writeRes\n\nprop_multinoulli_two_files :: Positive Int -> Positive Int -> FileType -> Property\nprop_multinoulli_two_files (Positive c) (Positive b) fType = monadicIO $ do\n  activation <- liftIO $ randomMatrix b c\n  classes <- liftIO $ randomNNInts (c - 1) b\n  let input = addClasses classes activation\n  let source =  yieldMany . repeat $ input\n  let initState = def { handlerStore = CostList []\n                      , paramList = pingPongSingleton EmptyParams\n                      }\n  let iterations = 5\n  multiResult <- liftIO $ multiTwo classes iterations fType\n  either (\\e -> do\n            liftIO . putStrLn $ \"ERROR \" ++ e\n            assert False)\n         (\\(fName, multi) -> do\n            result <- liftIO $ gradientDescent source\n                                               [unitCorrect classes]\n                                               multi\n                                               simpleDescentUpdate\n                                               (maxIterations iterations)\n                                               storeCost\n                                               initState\n            let check = CostList $ replicate iterations (-1)\n            liftIO $ removeFile fName\n            assertRight ((~= check) . handlerStore) result\n          )\n          multiResult\n\ngradientDescentTest :: TestTree\ngradientDescentTest = $(testGroupGenerator)\n", "meta": {"hexsha": "b1c6ee7433fab24e310b6afabddf07d6473ef90d", "size": 6632, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/School/Train/Test/GradientDescent.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/School/Train/Test/GradientDescent.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/School/Train/Test/GradientDescent.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3464052288, "max_line_length": 82, "alphanum_fraction": 0.5651387214, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4903808551390132}}
{"text": "{-# LANGUAGE TemplateHaskell #-}\n\nmodule RBM where\n\nimport           Control.Lens          hiding ((<.>), (|>))\nimport           Control.Monad.State\nimport           Data.Foldable\nimport           Numeric.LinearAlgebra\nimport           System.Random\n\n\ntype Input = Vector R\n\ntoBool :: Functor f => f Double -> f Bool\ntoBool = fmap (> 0.5)\n\nsign :: (Ord a, Num a, Num t) => a -> t\nsign x\n  | x >= 0 = 1\n  | otherwise = -1\n\nsign01 :: (Ord a, Num a, Num t) => a -> t\nsign01 x\n  | x >= 0 = 1\n  | otherwise = 0\n\ndata RBM = RBM { _weights :: Matrix R, _vbias :: Vector R, _hbias :: Vector R } deriving (Show)\nmakeLenses ''RBM\n\nnrVisible :: Getter RBM Int\nnrVisible = to (rows . view weights)\n\nnrHidden :: Getter RBM Int\nnrHidden = to (cols . view weights)\n\nnullrbm :: Int -> Int -> RBM\nnullrbm visible hidden = RBM ((hidden >< visible) zeros) (visible |> zeros) (hidden |> zeros)\n  where\n    zeros = repeat 0.0\n\n\n-- rngrbm :: Int -> Int -> Double -> State StdGen RBM\nrngrbm visible hidden rnghi = do\n  let nulled = nullrbm visible hidden\n      addv = flip addUniformNoise  rnghi\n      addm = flip addUniformNoiseM rnghi\n  vis <- addv $ nulled ^. vbias\n  hid <- addv $ nulled ^. hbias\n  wei <- addm $ nulled ^. weights\n  return $ nulled & vbias .~ vis & hbias .~ hid & weights .~ wei\n\n\n\nsigmoid :: Double -> Double\nsigmoid x = 1.0 / (1.0 + exp(-x))\n\nsigmoidvec :: Vector R -> Vector R\nsigmoidvec x = 1 / (1 + cmap exp (-x))\n\nnRandoms :: Int -> State StdGen [Double]\nnRandoms n = do\n  replicateM n getone\n  where\n    getone = do\n      rng <- get\n      let (nr, rng') = randomR (0.0, 1.0) rng\n      put rng'\n      return nr\n\nenergy :: RBM -> Vector Double -> Vector Double -> Double\nenergy rbm v h = - a - b - c\n  where\n    a = v <.> (rbm ^. vbias)\n    b = h <.> (rbm ^. hbias)\n    c = (h <# (rbm ^. weights)) <.> v\n\n-- | Requires binary data, i.e. v binary, for mathematical correctness\nfreeEnergyBin :: RBM -> Vector Double -> Double\nfreeEnergyBin rbm v = let\n  b = rbm ^. vbias\n  c = rbm ^. hbias\n  w = rbm ^. weights\n  lhs = b <.> v\n  rhs = sumElements $ 1 + exp (c + w #> v)\n  in -lhs -rhs\n\naddUniformNoise :: Vector R -> R -> State StdGen (Vector R)\naddUniformNoise v hi = do\n  rngs <- nRandoms $ size v\n  let rngv = (size v |> rngs) * 2 - 1\n  return $ scalar hi * rngv + v\n\naddUniformNoiseM :: Matrix R -> R -> State StdGen (Matrix R)\naddUniformNoiseM m hi = do\n  let (i,j) = size m\n  rngs <- nRandoms $ i * j\n  let rngm = ((i><j) rngs) * 2 - 1\n  return $ scalar hi * rngm + m\n\n-- | random parameters that deeplearning.net used for initializing weights\ngoodNoiseParam :: Floating a => RBM -> a\ngoodNoiseParam rbm = 4 * sqrt (6 / fromIntegral (rbm ^. nrHidden + rbm ^. nrVisible))\n\n-- | Probability of hidden nodes firing given sample v\npHid :: RBM -> Input -> Vector R\npHid rbm v = sigmoidvec $ b' + (w #> v)\n  where\n    b' = rbm ^. hbias\n    w = rbm ^. weights\n\n-- | Probability of visible nodes firing given sample h\npVis :: RBM -> Vector R -> Vector R\npVis rbm h = sigmoidvec $ v' + (h <# w)\n  where\n    v' = rbm ^. vbias\n    w = rbm ^. weights\n\ntestfire :: Vector R -> State StdGen (Vector R)\ntestfire probs = do\n  rngs <- nRandoms $ size probs\n  return $ cmap sign01 $ probs - vector rngs\n\ninpbook :: [Input]\ninpbook = vector <$>\n  [[1,1,1,0,0,0],[1,0,1,0,0,0],[1,1,1,0,0,0],[0,0,1,1,1,0], [0,0,1,1,0,0],[0,0,1,1,1,0]]\n\n-- | The algorithm part of the book is sort of half on-line, just\n-- generally broken and using weeird notation if they actually mean\n-- something that would end up as something like a weight. The code,\n-- instead, does a full batch thingy without a single mention of it,\n-- since the code would work either way. Anyhow, a weight update\n-- scheme that might work for one-input-at-a-time is available at\n-- http://image.diku.dk/igel/paper/AItRBM-proof.pdf , which this\n-- follows. All three weight diffs for this one input, as (pos - neg),\n-- is returned.  I.e: dw (Matrix), dv (vector), dh (vector). No\n-- assumptions on h, but that algo seems to imply that it maybe should\n-- stay as a probability, and not as sampled. v' is newer than v, etc.\n-- Should probably divide this by number of inputs (?).\ncompCDs :: Vector R -> Vector R -> Vector R -> Vector R -> (Matrix R, Vector R, Vector R)\ncompCDs v h v' h' = (dw, dv, dh)\n  where\n    dw = h `outer` v - h' `outer` v'\n    dv = v - v'\n    dh = h - h'\n\n-- | gibbs starting on v, h from input unused (structured this way for ease of folding)\ngibbsv :: RBM -> (Vector R, Vector R) -> State StdGen (Vector R, Vector R)\ngibbsv rbm (v, _) = do\n  h' <- testfire $ pHid rbm v\n  v' <- testfire $ pVis rbm h'\n  return (v', h')\n\ngetDiffs :: RBM -> Input -> State StdGen (Matrix R, Vector R, Vector R)\ngetDiffs rbm inp = do\n  let v = inp\n  h <- testfire $ pHid rbm v\n  (v', h') <- foldM (\\vh _ -> gibbsv rbm vh) (v, h) [1..1]\n  return $ compCDs v h v' h'\n\ntrain :: R -> RBM -> [Input] -> State StdGen RBM\ntrain eta rbm inputs = do\n  diffs <- mapM (getDiffs rbm) inputs\n  let (dw, dv, dh) = foldr (\\(a, b, c) (a', b', c') -> (a+a', b+b', c+c')) (0,0,0) diffs\n      dims = fromIntegral $ length inputs\n      scale = eta / dims\n      newrbm = rbm & weights %~ (+ (dw * scalar scale))\n                   & vbias %~ (+ (dv * scalar scale))\n                   & hbias %~ (+ (dh * scalar scale))\n  return newrbm\n\nfwd :: RBM -> Input -> State StdGen (Vector R)\nfwd rbm inp = do\n  -- (v', h') <- gibbsv rbm (inp, inp)\n  h' <- testfire $ pHid rbm inp\n  return $ pVis rbm h'\n\n\ntest :: IO ()\ntest = do\n  rng <- newStdGen\n  let tren = train 0.01\n      test = vector [0,0,0,1,1,0]\n  print . flip evalState rng $ do\n      t0 <- rngrbm 6 4 0.01\n\n      t1 <- tren t0 inpbook\n      t2 <- foldM tren t1 (replicate 4000 inpbook)\n      t3 <- tren t2 inpbook\n      out <- fwd t3 (head inpbook)\n      outtest <- fwd t3 test\n      return (out, outtest)\n\n\n-- | We can see in the output of test that the probabilities after\n-- forwarding the test vector on the one where it is active is very high,\n-- often >0.7, which is completely unlike for (head inpbook), where\n-- they are <0.2 (positions 4,5, that is). Similarly the first of the\n-- training inputs fires higher probabilities on its activations, and\n-- all this very consistently. If we keep gibbs-ing, the probabilities\n-- tend towards the relative presence in the training set, which\n-- asserts the generative-ness of it. Pos 3 is ~1 and pos 6 ~0 in all\n-- cases, which is reasonable for our data.\n--\n-- Doing it batch-wise would probably be faster, doing persistent CD\n-- likewise. Absolutely none of the improvements from hinton's very\n-- reasonable practical guide are implemented, and it would improve\n-- everything manyfold. (Also, the fold is pointless on the singleton\n-- list, but it really seems to be the case that sampling once\n-- performs the best)\n--\n-- As it is though, it seems to do some kind of learning!\n", "meta": {"hexsha": "9977f9ae7f60216f1c8f4c6cb1f96987b8564d53", "size": 6815, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/rbm/src/RBM.hs", "max_stars_repo_name": "fizzoo/kod", "max_stars_repo_head_hexsha": "79a4b415729e7cadbe9466fbdea9fe73a44485d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "haskell/rbm/src/RBM.hs", "max_issues_repo_name": "fizzoo/kod", "max_issues_repo_head_hexsha": "79a4b415729e7cadbe9466fbdea9fe73a44485d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "haskell/rbm/src/RBM.hs", "max_forks_repo_name": "fizzoo/kod", "max_forks_repo_head_hexsha": "79a4b415729e7cadbe9466fbdea9fe73a44485d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1462264151, "max_line_length": 95, "alphanum_fraction": 0.6247982392, "num_tokens": 2191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49009240732997567}}
{"text": "--\n-- PoolLayer : pooling layer\n--\n\nmodule CNN.PoolLayer (\n  poolMax\n, depoolMax\n, reversePooling\n) where\n\nimport Numeric.LinearAlgebra\n\nimport CNN.Algebra\nimport CNN.Image\nimport CNN.LayerType\n\ntype Pix = (Double, Double)\n\n{- |\npoolMax\n\n  In : pooling size (x = y)\n       image\n\n  OUT: updated image\n       position of max values\n\n>>> let im = [fromLists [[1.0,2.0,3.0,4.0],[8.0,7.0,6.0,5.0],[1.0,3.0,5.0,7.0],[2.0,4.0,6.0,8.0]], fromLists [[1.0,2.0,3.0,4.0],[2.0,2.0,3.0,4.0],[3.0,3.0,3.0,4.0],[4.0,4.0,4.0,4.0]]]\n>>> poolMax 2 im\n[[(2><2)\n [ 8.0, 6.0\n , 4.0, 8.0 ],(2><2)\n [ 2.0, 4.0\n , 4.0, 4.0 ]],[(2><2)\n [ 2.0, 2.0\n , 3.0, 3.0 ],(2><2)\n [ 1.0, 1.0\n , 2.0, 1.0 ]]]\n\n-}\n\npoolMax :: Int -> Image -> [Image]\npoolMax s im = [os, is] \n  where\n    pl = head im\n    x  = cols pl `div` s\n    y  = rows pl `div` s\n    ps = [(i*s, j*s) | i <- [0..(x-1)], j <- [0..(y-1)]]\n    (os, is) = unzip $ map (toPlain x y . maxPix s ps) im\n\ntoPlain :: Int -> Int -> [Pix] -> (Plain, Plain)\ntoPlain x y pls = ((x><y) op, (x><y) ip)\n  where\n    (op, ip) = unzip pls\n\nmaxPix :: Int -> [(Int, Int)] -> Plain -> [Pix]\nmaxPix s ps is = map (max' . toPix) ps\n  where\n    toPix :: (Int, Int) -> [Pix]\n    toPix p = zip (concat $ toLists $ subMatrix p (s, s) is) [0.0..]\n\nmax' :: [Pix] -> Pix\nmax' [] = error \"empty list!\"\nmax' [x] = x\nmax' (x:xs) = maximum' x (max' xs)\n\nmaximum' :: Pix -> Pix -> Pix\nmaximum' a@(v1, _) b@(v2, _) = if v1 < v2 then b else a\n\n-- back prop\n\n{- |\ndepoolMax\n\n>>> let im = [fromLists [[0.0,2.0],[3.0,1.0]]]\n>>> let dl = [fromLists [[0.1,0.2],[0.3,0.4]]]\n>>> depoolMax 2 im dl\n([(4><4)\n [ 0.1, 0.0, 0.0, 0.0\n , 0.0, 0.0, 0.2, 0.0\n , 0.0, 0.0, 0.0, 0.4\n , 0.0, 0.3, 0.0, 0.0 ]],Nothing)\n\n-}\n\ndepoolMax :: Int -> Image -> Delta -> (Delta, Maybe Layer)\ndepoolMax s im d = (zipWith (concatWith (expand s 0.0)) im d, Nothing)\n  where\n    concatWith :: (Double -> Double -> Matrix R) ->  Matrix R -> Matrix R\n               -> Matrix R\n    concatWith f i d = fromBlocks $ zipWith (zipWith f) is ds\n      where\n        is = toLists i\n        ds = toLists d\n\n{- |\nexpand\n\n  IN : size of pooling\n       filling value\n       positions\n       delta values\n\n>>> expand 2 0.0 0 3\n(2><2)\n [ 3.0, 0.0\n , 0.0, 0.0 ]\n>>> expand 2 0.0 2 4\n(2><2)\n [ 0.0, 0.0\n , 4.0, 0.0 ]\n>>> expand 3 0.0 5 3\n(3><3)\n [ 0.0, 0.0, 0.0\n , 0.0, 0.0, 3.0\n , 0.0, 0.0, 0.0 ]\n>>> expand 3 0.0 8 3\n(3><3)\n [ 0.0, 0.0, 0.0\n , 0.0, 0.0, 0.0\n , 0.0, 0.0, 3.0 ]\n\n-}\n\nexpand :: Int -> Double -> Double -> Double -> Matrix R\nexpand s r p d = (s><s) $ (replicate p1 r ++ [d] ++ replicate p2 r)\n  where\n    p1 = truncate p\n    p2 = max 0 (s * s - p1 - 1)\n\n-- reverse\n\nreversePooling :: Int -> Layer\nreversePooling = MaxPoolLayer\n\n\n", "meta": {"hexsha": "58e14924f28c61bd3630d28953023f1992d7b967", "size": 2686, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "CNN/PoolLayer.hs", "max_stars_repo_name": "eijian/deeplearning", "max_stars_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-30T01:28:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T18:58:17.000Z", "max_issues_repo_path": "CNN/PoolLayer.hs", "max_issues_repo_name": "eijian/deeplearning", "max_issues_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "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": "CNN/PoolLayer.hs", "max_forks_repo_name": "eijian/deeplearning", "max_forks_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "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": 19.6058394161, "max_line_length": 183, "alphanum_fraction": 0.5130305287, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4900438961095615}}
{"text": "module Main where\n\nimport Statistics.Quantile.Bench\nimport Statistics.Quantile.Exact\nimport Statistics.Quantile.Util\nimport Statistics.Quantile.Types\n\nimport System.IO\n\nmain :: IO ()\nmain = do\n  hSetBuffering stdin LineBuffering\n  hSetBuffering stdout LineBuffering\n  selectFromHandle median external stdin >>= print\n\n", "meta": {"hexsha": "f075a57bed9e522c6bdf4730d1849f2bb71a3f87", "size": 318, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "2015-08-26-fp-syd-approx-quantiles/approx-quantile/main/quantile.hs", "max_stars_repo_name": "fractalcat/slides", "max_stars_repo_head_hexsha": "338db16c6998dc4add9d1ebd511b3faf3a4420dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2015-08-26-fp-syd-approx-quantiles/approx-quantile/main/quantile.hs", "max_issues_repo_name": "fractalcat/slides", "max_issues_repo_head_hexsha": "338db16c6998dc4add9d1ebd511b3faf3a4420dc", "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": "2015-08-26-fp-syd-approx-quantiles/approx-quantile/main/quantile.hs", "max_forks_repo_name": "fractalcat/slides", "max_forks_repo_head_hexsha": "338db16c6998dc4add9d1ebd511b3faf3a4420dc", "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": 19.875, "max_line_length": 50, "alphanum_fraction": 0.8144654088, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.49003024431938574}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE Strict           #-}\n{-# LANGUAGE StrictData       #-}\nmodule Pinwheel.Transform where\n\nimport           Control.DeepSeq\nimport           Data.Array.IArray          as IA\nimport           Data.Complex\nimport           Data.List                  as L\nimport           Data.Vector.Generic        as VG\nimport           Data.Vector.Unboxed        as VU\nimport           FokkerPlanck.FourierSeries (getHarmonics)\nimport           FokkerPlanck.Histogram\nimport           Pinwheel.List\nimport           Sparse.Vector              as SV\nimport           Utils.List\nimport           Utils.Parallel             hiding (dot)\n\ndata PinwheelTransformData a b =\n  PinwheelTransformData a\n                        a\n                        b\n\ninstance (NFData a, NFData b) => NFData (PinwheelTransformData a b) where\n  rnf (PinwheelTransformData x y z) = x `seq` y `seq` z `seq` ()\n\n{-# INLINE projectVec #-}\nprojectVec ::\n     ( VG.Vector vector e\n     , VG.Vector vector (Complex e)\n     , VG.Vector vector Int\n     , Num e\n     , RealFloat e\n     )\n  => Int\n  -> Int\n  -> e\n  -> vector (Complex e)\n  -> PinwheelTransformData e (SparseVector vector (Complex e))\n  -> Complex e\nprojectVec angularFreq radialFreq sigma pinwheel (PinwheelTransformData logR theta sparseVec) =\n  ((exp ((sigma - 1) * logR)) :+ 0) *\n  (cis $\n   (-1) * (theta * fromIntegral angularFreq + logR * fromIntegral radialFreq)) *\n  (sparseVec `dot` pinwheel)\n\n{-# INLINE pinwheelTransform #-}\npinwheelTransform ::\n     ( VG.Vector vector e\n     , VG.Vector vector (Complex e)\n     , VG.Vector vector Int\n     , NFData e\n     , RealFloat e\n     , Unbox e\n     )\n  => Int\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> IA.Array (Int, Int) (vector (Complex e))\n  -> [PinwheelTransformData e (SparseVector vector (Complex e))]\n  -> Histogram (Complex e)\npinwheelTransform numThread maxPhiFreq maxRhoFreq maxThetaFreq maxRFreq sigma pinwheelArr xs =\n  let coef =\n        parMapChunk\n          (ParallelParams numThread undefined)\n          rdeepseq\n          (\\(rFreq, thetaFreq, rhoFreq, phiFreq) ->\n             let pinwheel =\n                   getHarmonics\n                     pinwheelArr\n                     (fromIntegral phiFreq)\n                     (fromIntegral rhoFreq)\n                     (fromIntegral thetaFreq)\n                     (fromIntegral rFreq)\n             in L.foldl'\n                  (\\s x -> s + projectVec thetaFreq rFreq sigma pinwheel x)\n                  0\n                  xs) $\n        [ (rFreq, thetaFreq, rhoFreq, phiFreq)\n        | rFreq <- [-maxRFreq .. maxRFreq]\n        , thetaFreq <- [-maxThetaFreq .. maxThetaFreq]\n        , rhoFreq <- [-maxRhoFreq .. maxRhoFreq]\n        , phiFreq <- [-maxPhiFreq .. maxPhiFreq]\n        ]\n  in Histogram\n       [ 2 * maxPhiFreq + 1\n       , 2 * maxRhoFreq + 1\n       , 2 * maxThetaFreq + 1\n       , 2 * maxRFreq + 1\n       ]\n       1 .\n     VU.fromList $\n     coef\n", "meta": {"hexsha": "7aa7c8a1fdd34fc8758eab6cbd0a7544adba5112", "size": 2945, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Pinwheel/Transform.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Pinwheel/Transform.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/Pinwheel/Transform.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 30.3608247423, "max_line_length": 95, "alphanum_fraction": 0.5531409168, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4899644731945312}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n\nimport           AI.Layer\nimport           AI.Neuron\n\nimport           AI.Network\nimport           AI.Network.FeedForwardNetwork\n\nimport           AI.Trainer\nimport           AI.Trainer.BackpropTrainer\n\n--import Network.Visualizations\nimport           Numeric.LinearAlgebra\nimport           System.IO\nimport           System.Random\n\nmain :: IO ()\nmain = do\n\n  g <- newStdGen\n  let l = LayerDefinition sigmoidNeuron 2 connectFully randomizeFully\n  let l' = LayerDefinition sigmoidNeuron 2 connectFully randomizeFully\n  let l'' = LayerDefinition sigmoidNeuron 1 connectFully randomizeFully\n\n  let n = createNetwork normals g [l, l', l'']\n\n  let t = BackpropTrainer (3 :: Double) quadraticCost quadraticCost'\n  let dat = [(fromList [0, 1], fromList [1]), (fromList [1, 1], fromList [0]), (fromList [1, 0], fromList [1]), (fromList [0, 0], fromList [0])]\n\n  let n' = trainNTimes g n t online dat 1000\n\n  putStrLn \"==> XOR predictions: \"\n  print $ predict (fromList [0, 0]) n'\n  print $ predict (fromList [1, 0]) n'\n  print $ predict (fromList [0, 1]) n'\n  print $ predict (fromList [1, 1]) n'\n\n  saveFeedForwardNetwork \"xor.ann\" n'\n\n  putStrLn \"==> Network saved and reloaded: \"\n  n'' <- loadFeedForwardNetwork \"xor.ann\" [l, l', l'']\n\n  print $ predict (fromList [0, 0]) n''\n  print $ predict (fromList [1, 0]) n''\n  print $ predict (fromList [0, 1]) n''\n  print $ predict (fromList [1, 1]) n''\n\n  --networkHistogram \"weights.png\" weightList n''\n  --networkHistogram \"biases.png\" biasList n''\n", "meta": {"hexsha": "0e42b48af3899cf437cd7df23d4e8350727660c5", "size": 1524, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/XOR.hs", "max_stars_repo_name": "jbarrow/LambdaNet", "max_stars_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 308, "max_stars_repo_stars_event_min_datetime": "2015-01-01T01:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:03:18.000Z", "max_issues_repo_path": "examples/XOR.hs", "max_issues_repo_name": "jbarrow/LambdaNet", "max_issues_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2015-05-23T20:39:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-29T17:04:47.000Z", "max_forks_repo_path": "examples/XOR.hs", "max_forks_repo_name": "jbarrow/LambdaNet", "max_forks_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2015-01-01T07:14:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:33:41.000Z", "avg_line_length": 30.48, "max_line_length": 144, "alphanum_fraction": 0.6496062992, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48996446813379513}}
{"text": "module QLib\n    ( quantumRun\n    ) where\n\nimport Data.Complex\nimport Data.Bits\nimport qualified Data.List as L\nimport Text.Printf\nimport Numeric.LinearAlgebra\n\nquantumRun :: IO ()\nquantumRun = do putStrLn \"Some Func\"\n                let a = newRegister 4\n                putStrLn $ show a\n--                putStrLn $ printf \"%b\" (3 :: Int)\n--                let c = Qubit $ fromList [1 :+ 0, 0]\n--                putStrLn $ show c\n--                let d = sauliX c\n--                putStrLn $ show d\n--                let e = Register $ take 5 $ repeat (Qubit $ fromList [1, 0])\n--                --let e = sauliZ d\n--                putStrLn $ show e\n\n--data Qubit = Qubit (Double, Int)\ndata Qubit = Qubit { probability :: Double, qubit :: Int }\n\ninstance Eq Qubit where\n    x == y = qubit x == qubit y\n\ninstance Ord Qubit where\n    x <= y = qubit x <= qubit y\n\ninstance Show Qubit where\n    show x = (show . probability $ x) ++ \" |\" ++ (show . qubit $ x) ++ \">\"\n\ndata Register = Register { nStates :: Int, qubits :: [Qubit] }\n\ninstance Show Register where\n    --show (Register a x) = (show a) (show x) ++ \">\"\n    show x = concatMap ((flip (++) \"\\n\") . show) $ qubits x\n\ninstance Eq Register where\n    x == y = qubits x == qubits y \n\nnewRegister :: Int -> Register\nnewRegister n = Register { nStates = n, qubits = [blankQubit (x-1) | x <- [1..2^n] ] }\n                where blankQubit 0 = Qubit { probability = 1.0, qubit = 0 }\n                      blankQubit y = Qubit { probability = 0.0, qubit = y }\n\nsauliX :: Register -> Int -> Register\nsauliX xs pos = map (\\x -> x `xor` pos) xs\n\n--newRegister :: Int -> QuantumRegister\n--newRegister 0 = QuantumRegister 0 []\n--newRegister 1 = QuantumRegister 1 [ (Register 0 [Zero]), (Register 0 [One]) ]\n--newRegister x = QuantumRegister x [ \n\n\n--sauliX :: Qubit -> Qubit\n--sauliX (Qubit x) = Qubit (xgate #> x)\n--                where xgate = (2><2)[0, 1, 1, 0] :: Matrix C\n--\n--sauliY :: Qubit -> Qubit\n--sauliY (Qubit x) = Qubit (ygate #> x)\n--                where ygate = (2><2)[0:+1, 0, 0, 0:+1] :: Matrix C\n--\n--sauliZ :: Qubit -> Qubit\n--sauliZ (Qubit x) = Qubit (zgate #> x)\n--                where zgate = (2><2)[1, 0, 0, -1] :: Matrix C\n                \n\n--data Bit = Zero | One deriving Eq\n--\n--instance Show Bit where\n--    show Zero = \"|0>\"\n--    show One  = \"|1>\"\n--\n--data Qubit a = Qubit (Complex a) (Complex a) deriving Show\n--\n--sauliX :: Qubit a -> Qubit a\n--sauliX (Qubit x y) = Qubit y x\n--\n--sauliY :: (Fractional a, RealFloat a) => Qubit a -> Qubit a\n--sauliY (Qubit x y) = Qubit rotY rotX\n--        where i = 0 :+ 1\n--              rotY = -y*i\n--              rotX = x*i\n--\n--sauliZ :: (RealFloat a) => Qubit a -> Qubit a\n--sauliZ (Qubit x y) = Qubit x (-y)\n\n\n\n--data Qubit a = Qubit (Vector a)\n--\n---- Show the Qubit using Ket notation\n--instance (Show a, Numeric a) => Show (Qubit a) where\n--    show (Qubit x) = '(':(show first) ++ \")|0> + (\" ++ (show second) ++ \")|1>\"\n--                    where first = (fromList [1, 0]) <.> x\n--                          second = fromList [0, 1] <.> x\n--\n--notGate :: Qubit R -> Qubit R\n--notGate (Qubit x) = let invertMatrix = (2><2) [-1, 0, 0, -1] in\n--                        Qubit (invertMatrix #> x)\n", "meta": {"hexsha": "3cf79f0cb3fe43c81720b63f4811723d73a09be5", "size": 3216, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/src/QLib.hs", "max_stars_repo_name": "byronwasti/Quantum-Computer-Simulation", "max_stars_repo_head_hexsha": "3c5f5ce7c90b7cc529f3af0fff6bd46cff3ecc0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-12-01T16:34:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-21T03:00:12.000Z", "max_issues_repo_path": "haskell/src/QLib.hs", "max_issues_repo_name": "byronwasti/Quantum-Computer-Simulation", "max_issues_repo_head_hexsha": "3c5f5ce7c90b7cc529f3af0fff6bd46cff3ecc0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "haskell/src/QLib.hs", "max_forks_repo_name": "byronwasti/Quantum-Computer-Simulation", "max_forks_repo_head_hexsha": "3c5f5ce7c90b7cc529f3af0fff6bd46cff3ecc0c", "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": 30.6285714286, "max_line_length": 86, "alphanum_fraction": 0.5282960199, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4898816696015692}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE PolyKinds #-}\n\nmodule Main where\n\nimport Data.Array\nimport Data.Complex\nimport qualified Data.IntMap.Strict as IM\nimport Data.List (intercalate)\nimport Data.Map (empty, fromList, union)\nimport Data.Maybe (fromJust)\nimport Data.STRef.Strict\nimport qualified Data.Set as Set\nimport HashedExpression.Derivative.Partial\nimport Graphics.EasyPlot\nimport HashedExpression\nimport HashedExpression.Derivative\nimport HashedExpression.Interp\nimport HashedExpression.Operation\nimport qualified HashedExpression.Operation\nimport HashedExpression.Prettify\nimport Data.String.Interpolate\nimport Prelude hiding ((^))\n\nmain :: IO ()\nmain = do\n  let x = variable \"x\"\n  let y = variable \"y\"\n  let f = sum [x^2 , 2*x , 1] * (x^2 + 2 * y + 1)\n  print $ allEntries f\n", "meta": {"hexsha": "ba28450ce9b24bd89695eba4b61d7ce112487208", "size": 785, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "Turboscient/HashedExpression", "max_stars_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-30T00:10:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T21:31:19.000Z", "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "Turboscient/HashedExpression", "max_issues_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-23T19:22:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-26T18:47:55.000Z", "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "Turboscient/HashedExpression", "max_forks_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-05-25T00:27:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T00:37:36.000Z", "avg_line_length": 25.3225806452, "max_line_length": 49, "alphanum_fraction": 0.7694267516, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4893996344918333}}
{"text": "{-# LANGUAGE BangPatterns, LambdaCase #-}\n\nmodule Main where\n\nimport           Help\nimport           Input\nimport           Fractals\nimport           Colors\nimport           Data.Complex\nimport qualified Graphics.Image                as I\nimport qualified Graphics.Image.Interface      as I\nimport           System.IO\nimport           Data.Word\nimport           System.Environment\nimport           System.Directory\nimport           Data.Time\n\n-- Entry point for program\nmain :: IO ()\nmain = do\n   args <- getArgs\n   if not (length args == 0) &&\n      (  head args == \"h\"\n      || head args == \"-h\"\n      || head args == \"help\"\n      || head args == \"-help\"\n      || head args == \"?\"\n      || head args == \"-?\"\n      )\n     then do\n        putStrLn $ help args\n        hFlush stdout\n     else do\n        let options = processArgs args\n        putStrLn $ pPrintOptions options\n        hFlush stdout\n        fractal args options\n\nfractal :: [String] -> Options -> IO ()\nfractal args options@(Options fractalType (numRows, numColumns) (centerReal :+ centerImag)\n                      range iterations power aaIn normalization color animation\n                      cValue setColor framesIn startingFrame)\n   = do\n      currentDir <- getCurrentDirectory\n      {- Path is generated by finding the current date/time, replacing colons (an invalid character in\n       Windows paths) with an alternate Unicode colon, and removing the last 12 digits (which contain\n       the fractional part of the seconds and the \"UTC\" code) -}\n      path  <- fmap\n         ( ((currentDir ++ \"\\\\Generated Fractals\\\\\") ++)\n         . reverse . drop 12 . reverse\n         . map (\\case ':' -> '\\xA789'; x -> x)\n         . show\n         )\n         getCurrentTime\n      createDirectoryIfMissing True path\n      setCurrentDirectory path\n      writeFile \"data.txt\" $ (pPrintOptions options) ++ '\\n' : \"Arguments:       \" ++ (unwords args)\n      putStr $ (show $ startingFrame - 1) ++ '/' : (show $ floor frames)\n      hFlush stdout\n      mapM_\n         (\\frame -> do\n            I.writeImageExact (I.PNG) []\n                  (path ++ '\\\\' : (take ((countDigits $ floor frames) - (countDigits $ frame)) $ repeat '0')\n                   ++ show (frame) ++ \".png\") $\n                  I.toManifest $ I.toWord8I $ I.makeImageR I.RPS\n                                       (numRows, numColumns)\n                                       (\\point -> colorFunc $ fractalFunction frame point)\n            putStr $ '\\r' : (show $ frame + 1) ++ '/' : (show $ floor frames)\n            hFlush stdout\n         )\n         [startingFrame - 1 .. (truncate frames) - 1]\n      putStrLn \"\"\n where\n   frames = case animation of\n      NoAnimation -> 1\n      otherwise   -> fromIntegral framesIn\n   colorFunc =\n      case color of\n            Greyscale                  -> colorGrey setColor\n            Hue                        -> colorHue setColor\n            Gradient isCircular colors -> colorGrad setColor isCircular colors\n         . fmap\n            (case normalization of\n               Linear               -> normLinear iterations\n               Sigmoid center power -> normSigmoid center power\n               Periodic period      -> normPeriodic period\n               Sine     period      -> normSine period\n            )\n   aa = case aaIn of\n      AAEnabled  -> True\n      AADisabled -> False\n   animVals = map\n      (case animation of\n         Zoom final _ -> ((exp $ (log (final / range)) / (frames - 1)) **)\n         Grid rIni rFnl _ _ rNum _ ->\n            interpolate rIni rFnl . (/ (fromIntegral rNum - 1)) . fromIntegral . (`mod` rNum) . floor\n         otherwise ->\n            case animation of\n                NoAnimation      -> \\x -> 1\n                Power final      -> interpolate power final\n                Iterations final -> interpolate (fromIntegral iterations) (fromIntegral final)\n                Theta final _    -> interpolate (phase cValue) (final * pi / 180)\n                LinearC final    -> interpolate (realPart cValue) (realPart final)\n            . if frames /= 1 then (/ (frames - 1)) else id\n      )\n      [fromIntegral startingFrame - 1 .. frames - 1]\n   altAnimVals = map\n      (case animation of\n         Grid _ _ iIni iFnl rNum iNum ->\n            interpolate iIni iFnl . (/ (fromIntegral iNum - 1)) . fromIntegral . (`div` rNum) . floor\n         otherwise ->\n            case animation of\n                Zoom _ (Just finalIter) -> interpolate (fromIntegral iterations) (fromIntegral finalIter)\n                Zoom _ Nothing          -> \\x -> fromIntegral iterations\n                Theta _ (Just final)    -> interpolate (magnitude cValue) final\n                Theta _ Nothing         -> \\x -> magnitude cValue\n                LinearC final           -> interpolate (imagPart cValue) (imagPart final)\n            . if frames /= 1 then (/ (frames - 1)) else id\n      )\n      [fromIntegral startingFrame - 1 .. frames - 1]\n   fractalFunction :: Int -> (Int, Int) -> Maybe Double\n   fractalFunction frame (r, c) = case (fractalType, animation) of\n      -- Mandelbrot animation functions\n      (Mandelbrot, NoAnimation) ->\n         pMandelbrot aa pixelSize iterations power $ pairToComplex (r, c)\n      (Mandelbrot, Power _) ->\n         pMandelbrot aa pixelSize iterations value $ pairToComplex (r, c)\n      (Mandelbrot, Zoom _ _) ->\n         pMandelbrot aa (pixelSize * value) (round $ altValue) power $ pairToComplexZ (r, c) value\n      (Mandelbrot, Iterations _) ->\n         pMandelbrot aa pixelSize (round value) power $ pairToComplex (r, c)\n      (Mandelbrot, Theta _ _) ->\n         error \"Theta animations can only be generated for Julia fractals\"\n      (Mandelbrot, LinearC _) ->\n         error \"Linear C-Value animations can only be generated for Julia fractals\"\n      (Mandelbrot, Grid _ _ _ _ _ _) ->\n         error \"Grided c-values can only be generated for Julia fractals\"\n      -- Julia animation functions\n      (Julia, NoAnimation) ->\n         pJulia aa pixelSize iterations power cValue $ pairToComplex (r, c)\n      (Julia, Power _) ->\n         pJulia aa pixelSize iterations value cValue $ pairToComplex (r, c)\n      (Julia, Zoom _ _) ->\n         pJulia aa (pixelSize * value) (round $ altValue) power cValue $ pairToComplexZ (r, c) value\n      (Julia, Iterations _) ->\n         pJulia aa pixelSize (round value) power cValue $ pairToComplex (r, c)\n      (Julia, Theta _ _) ->\n         pJulia aa pixelSize iterations power (mkPolar altValue value) $ pairToComplex (r, c)\n      (Julia, LinearC _) ->\n         pJulia aa pixelSize iterations power (value :+ altValue) $ pairToComplex (r, c)\n      (Julia, Grid _ _ _ _ _ _) ->\n         pJulia aa pixelSize iterations power (value :+ altValue) $ pairToComplex (r, c)\n      where\n         -- The value being animated\n         value     = animVals !! frame\n         altValue  = altAnimVals !! frame\n         -- Other values\n         pixelSize = (2 * range) / (fromIntegral $ numColumns - 1)\n         halfV     = 0.5 * fromIntegral numRows\n         halfH     = 0.5 * fromIntegral numColumns\n         -- Function to get a complex point from a pixel coordinate pair\n         pairToComplex (r, c) =\n            (centerReal - range + fromIntegral c * pixelSize)\n               :+ (centerImag + (pixelSize * (fromIntegral (numRows - 1) / 2)) - fromIntegral r * pixelSize)\n         -- Same as above but for zoom animations\n         pairToComplexZ (r, c) zoomFactor =\n            ((fromIntegral c - halfH) * pixelSize * zoomFactor + centerReal)\n               :+ ((fromIntegral r - halfV) * pixelSize * zoomFactor - centerImag)\n\n-- Helper function for interpolating from the start to the end of an animation's value range\ninterpolate :: RealFloat a => a -> a -> a -> a\ninterpolate i f = (i +) . (*) (f - i)\n\n-- Helper funtion to count the number of digits in an integer when expressed in base 10\ncountDigits :: Integral a => a -> a\ncountDigits = (+ 1) . floor . logBase 10 . fromIntegral\n", "meta": {"hexsha": "7cd8ae25706c35383d1efa2ece88e48d1eda7abb", "size": 7934, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "MaygeKyatt/Fractals", "max_stars_repo_head_hexsha": "e5f2102fd74c02e6290dc75d138f8962850ebd26", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "MaygeKyatt/Fractals", "max_issues_repo_head_hexsha": "e5f2102fd74c02e6290dc75d138f8962850ebd26", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "MaygeKyatt/Fractals", "max_forks_repo_head_hexsha": "e5f2102fd74c02e6290dc75d138f8962850ebd26", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8248587571, "max_line_length": 108, "alphanum_fraction": 0.5729770608, "num_tokens": 1953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4892930501997894}}
{"text": "module AI.GeneticAlgorithm\n    ( Genome\n    , Individual\n    , Population\n    , individualGenome\n    , individualFitness\n    , mutate\n    , proportionalSelection\n    , getBasePopulation\n    , evolve\n    , evolves\n    , bestAverageWorst ) where\n\nimport           AI.NeuralNetwork            as NN\nimport           Control.Lens\nimport           Control.Monad.State\nimport           Control.Parallel.Strategies\nimport           Data.Function\nimport           Data.Functor.Identity\nimport           Data.Maybe\nimport           Data.Random.Normal\nimport qualified Data.Vector                 as V\nimport qualified Data.Vector.Generic         as VG\nimport           Numeric.LinearAlgebra\nimport           System.Random\n\ntype Genome       = NN.Network\n-- An individual with a genome and fitness\ndata Individual a = Individual Genome a\n    deriving (Eq, Show)\ntype Population a = V.Vector (Individual a)\n\nmut :: Double -> Double -> Double -> State StdGen Double\nmut rate amount val = do\n    rRate <- state random\n    if rRate < rate\n       then fmap (\\x -> val + x * amount) (state normal)\n       else return val\n\ntoIndividual :: (Genome -> a) -> Genome -> Individual a\ntoIndividual fitfunc genome = Individual genome (fitfunc genome)\n\ntoPopulation :: (Genome -> a) -> V.Vector Genome -> V.Vector (Individual a)\ntoPopulation fitfunc genomes = let pop = V.map (toIndividual fitfunc) genomes\n                                in pop `using` parTraversable rseq\n\nindividualGenome :: Individual a -> Genome\nindividualGenome (Individual g _) = g\n\nindividualFitness :: Individual a -> a\nindividualFitness (Individual _ f) = f\n\nmutate :: Double -> Double -> Genome -> State StdGen Genome\nmutate rate amount genome = do\n    let cmut = mut rate amount\n    newBiases  <- mapM (VG.mapM    cmut) (genome^.biases)\n    newWeights <- mapM (mapMatrixM cmut) (genome^.weights)\n    let newNN = execState (biases .= newBiases >> weights .= newWeights) genome\n    return newNN\n\nproportionalSelection :: (Random a, Ord a, Num a, NFData a) =>\n    Population a -> State StdGen (Population a)\nproportionalSelection pop =\n    let fitness  = individualFitness <$> pop\n        accFit   = V.scanl1 (+) fitness\n        choose p = snd $ fromJust $ V.find (\\t -> p <= fst t) (V.zip accFit pop)\n     in forM pop $ \\_ -> do\n         p <- state $ randomR (0, V.last accFit)\n         return $ choose p\n\ngetBasePopulation :: (Genome -> a) -> State StdGen Genome ->\n    Int -> State StdGen (Population a)\ngetBasePopulation fitfunc genomeGen popSize =\n    toPopulation fitfunc <$> V.replicateM popSize genomeGen\n\nevolve :: (Genome -> Double) -> (Genome -> State StdGen Genome) ->\n    Population Double -> State StdGen (Population Double)\nevolve fitfunc mutfunc pop = do\n    selected <- proportionalSelection pop\n    mutated  <- mapM (\\(Individual g _) -> mutfunc g) selected\n    return $ toPopulation fitfunc mutated\n\nevolves :: Int -> Int -> State StdGen Genome ->\n    (Genome -> Double) -> (Genome -> State StdGen Genome) ->\n        State StdGen [Population Double]\nevolves generations popSize genomeGen fitfunc mutfunc = do\n    basePop <- getBasePopulation fitfunc genomeGen popSize\n    let evofunc = evolve fitfunc mutfunc\n    evolutions <- V.iterateNM generations evofunc basePop\n    return $ V.toList evolutions\n\nbestAverageWorst :: (Fractional a, Ord a) =>\n    [Population a] -> [(Individual a, a, Individual a)]\nbestAverageWorst = reverse . foldl (\\acc pop ->\n        let fitness = individualFitness <$> pop\n            best = V.maximumBy (compare `on` individualFitness) pop\n            avgFit = sum fitness / fromIntegral (V.length fitness)\n            worst = V.minimumBy (compare `on` individualFitness) pop\n         in (best, avgFit, worst) : acc) []\n\nmapMatrixM :: (Element a, Element b, Monad m) =>\n    (a -> m b) -> Matrix a -> m (Matrix b)\nmapMatrixM f m = let ll  = toLists m\n                     mmM = mapM . mapM\n                  in fromLists <$> mmM f ll\n", "meta": {"hexsha": "dc79a58e2688281c7257c5ac8a197d36274a62a3", "size": 3929, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/GeneticAlgorithm.hs", "max_stars_repo_name": "cornelius-sevald/neurocar", "max_stars_repo_head_hexsha": "9a8529ab2007b98ab20b6ce0b7e29ec7cbe085bb", "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/AI/GeneticAlgorithm.hs", "max_issues_repo_name": "cornelius-sevald/neurocar", "max_issues_repo_head_hexsha": "9a8529ab2007b98ab20b6ce0b7e29ec7cbe085bb", "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/AI/GeneticAlgorithm.hs", "max_forks_repo_name": "cornelius-sevald/neurocar", "max_forks_repo_head_hexsha": "9a8529ab2007b98ab20b6ce0b7e29ec7cbe085bb", "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.0660377358, "max_line_length": 80, "alphanum_fraction": 0.6500381777, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.488842381877019}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes       #-}\n{-# LANGUAGE DataKinds                 #-}\n{-# LANGUAGE FlexibleContexts          #-}\n{-# LANGUAGE GADTs                     #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE OverloadedStrings         #-}\n{-# LANGUAGE ScopedTypeVariables       #-}\n{-# LANGUAGE TypeApplications          #-}\n{-# LANGUAGE TypeOperators             #-}\n{-# LANGUAGE QuasiQuotes               #-}\n{-# LANGUAGE PartialTypeSignatures #-}\nmodule Main where\n\nimport qualified Control.Foldl                as FL\nimport           Control.Monad.IO.Class (MonadIO (..))\nimport qualified Data.List                    as List\nimport           Data.Maybe                   (fromMaybe)\nimport qualified Data.Map                     as M\nimport qualified Data.Text                    as T\nimport qualified Data.Text.IO                 as T\nimport qualified Data.Text.Lazy               as TL\nimport qualified Data.Vector.Storable         as V\nimport qualified Data.Vinyl                   as V\nimport qualified Frames                       as F\n\nimport qualified Numeric.LinearAlgebra        as LA\nimport           Numeric.LinearAlgebra        (R, Matrix)\n\nimport qualified Frames.Regression            as FR\nimport qualified Frames.VegaLite               as FV\n\nimport qualified Text.Blaze.Html5              as H\nimport qualified Text.Blaze.Html5.Attributes   as HA\nimport           Text.Blaze.Html              ((!))\nimport qualified Text.Blaze.Html.Renderer.Text as BH\n\nimport qualified Statistics.Types             as S\n\nimport qualified Knit.Report                  as K\nimport qualified Knit.Report.Other.Blaze      as KB\n\n{-\nimport qualified Polysemy                      as P\nimport qualified Knit.Effects.Logger           as Log\nimport qualified Knit.Effects.Pandoc           as PE\nimport qualified Knit.Effects.PandocMonad           as PM\nimport qualified Knit.Report.Blaze             as RB\nimport qualified Knit.Report.Pandoc           as PR\n-}\n\nimport Data.String.Here\n\ntemplateVars = M.fromList\n  [\n    (\"lang\", \"English\")\n  , (\"author\", \"Adam Conner-Sax\")\n  , (\"pagetitle\", \"Frame Regression Examples\")\n--  , (\"tufte\",\"True\")\n  ]\n\nregressionNotesMD\n  = [here|\n## Regression Algorithm Comparison\n* To get data for testing we choose xs evenly spaced between -0.5 and 0.5.  Then we compute ys via $y=1 + 2.2x$.  Then we add Gaussian noise to the ys.  We can optionally add Gaussian noise to the observed xs as well (that is, the ys are still calculated from the exact xs but we add noise to the xs before we regress) and add weights to the (x,y) pairs.\n* For unweighted data we use ordinary least squares (OLS) and total least square (TLS).\n* For weighted data we use weighted least squares (WOLS) and weighted total least squares (WTLS).\n* Both TLS and WTLS are computed via the Singular Value Decomposition.\n* For each comparison we vary the level of noise on the ys and/or xs, regress, then show the results of each regression in tabular form, a plot of the fits and prediction intervals together with a scatter of the noisy data, and a plot of the coefficients and confidence intervals. The shaded regions in each plot are the \"prediction intervals\" which take into account the uncertainty of the coefficients as well as the remainining noise in the data.\n* The F-stat is computed for each fit via comparision to the model of intercept-only.  So the p-value of the overall fit is the probability that the data are better explained as noise around their (weighted) mean value than by the fit.\n|]\n\nmain :: IO ()\nmain = asPandoc\n  \nasPandoc :: IO ()\nasPandoc = do\n  let pandocWriterConfig = K.PandocWriterConfig (Just \"pandoc-templates/minWithVega-pandoc.html\")  templateVars K.mindocOptionsF\n  htmlAsTextE <- K.knitHtml (Just \"FrameRegressions.Main\") K.logAll pandocWriterConfig $ do\n    K.addMarkDown regressionNotesMD\n    testMany\n  case htmlAsTextE of\n    Right htmlAsText -> T.writeFile \"examples/html/FrameRegressions.html\" $ TL.toStrict  $ htmlAsText\n    Left err -> putStrLn $ \"pandoc error: \" ++ show err\n\n{-\nasBlaze :: IO ()\nasBlaze = do\n  let runAllP = FR.runPandocAndLoggingToIO Log.logAll . Log.wrapPrefix \"Main\" . blazeToText \n  htmlAsTextE <- runAllP $ do    \n    regressionNotesBlaze <- P.markDownTextToBlazeFragment regressionNotesMD\n    blaze $ H.makeReportHtml \"Frame Regression Examples\" $ do\n      H.placeTextSection $ regressionNotesBlaze  \n    testMany\n  case htmlAsTextE of\n    Right htmlAsText -> T.writeFile \"examples/html/FrameRegressions.html\" $ TL.toStrict  $ htmlAsText\n    Left err -> putStrLn $ \"pandoc error: \" ++ show err\n-}\n\n-- regression tests\n\n-- build some data for testing\n-- uniformly distributed measurements, normally distributed noise.  Separate noise amplitudes for xs and ys\n-- also allow building heteroscedastic data\n\ntype Y = \"y\" F.:-> Double\ntype X = \"x\" F.:-> Double\n--type X2 = \"x2\" F.:-> Double\ntype Weight = \"weight\" F.:-> Double\n\nbuildRegressable :: [Double] -> Maybe (LA.Vector R) -> Double -> LA.Vector R -> Double -> IO (LA.Vector R, LA.Matrix R)\nbuildRegressable variances offsetsM noiseObs coeffs noiseMeas = do\n  -- generate random measurements\n  let d = LA.size coeffs\n      nObs = List.length variances\n      xsO = LA.asColumn (LA.fromList (List.replicate nObs 1)) LA.<> LA.asRow (fromMaybe (LA.fromList $ List.replicate (d-1) 0) offsetsM)\n--  xs0 <- LA.cmap (\\x-> x - 0.5) <$> LA.rand nObs (d-1) -- 0 centered uniformly distributed random numbers\n  let xs0 :: Matrix R = LA.asColumn $ LA.fromList $ [-0.5 + (realToFrac i/realToFrac nObs) | i <- [0..(nObs-1)]]\n  xNoise <- LA.randn nObs (d-1) -- 0 centered normally (sigma=1) distributed random numbers\n  let xsC = 1 LA.||| (xs0 + xsO)\n      xsN = 1 LA.||| (xs0 + xsO + LA.scale noiseMeas xNoise)\n  let ys0 = xsC LA.<> LA.asColumn coeffs\n  yNoise <- fmap (List.head . LA.toColumns) (LA.randn nObs 1) -- 0 centered normally (sigma=1) distributed random numbers\n  let ys = ys0 + LA.asColumn (LA.scale noiseObs (V.zipWith (*) yNoise (LA.cmap sqrt (LA.fromList variances))))\n  return (List.head (LA.toColumns ys), xsN)\n\ntype AllCols = [Y,X,Weight]\n\nmakeFrame :: [Double] -> (LA.Vector R, LA.Matrix R) -> IO (F.FrameRec AllCols)\nmakeFrame vars (ys, xs) = do\n  if snd (LA.size xs) /= 2 then error (\"Matrix of xs wrong size (\" ++ show (LA.size xs) ++ \") for makeFrame\") else return ()\n  let rows = LA.size ys\n      rowIndex = [0..(rows - 1)]\n      makeRecord :: Int -> F.Record AllCols\n      makeRecord n = ys `LA.atIndex` n F.&: xs `LA.atIndex` (n,1) F.&: vars List.!! n F.&: V.RNil -- skip bias column\n  return $ F.toFrame $ makeRecord <$> rowIndex\n\n\nunweighted :: Int -> [Double]\nunweighted n = List.replicate n (1.0)\n\nconeWeighted :: Int -> Double -> Double -> [Double]\nconeWeighted n base increment =\n  let w0 = [base + (realToFrac i) * increment | i <- [1..n]]\n      s = realToFrac n/FL.fold FL.sum w0\n  in fmap (*s) w0\n\nshowText :: Show a => a -> T.Text\nshowText = T.pack . show\n\ncoeffs :: LA.Vector R = LA.fromList [1.0, 2.2]\noffsets :: LA.Vector R = LA.fromList [1]\nvars = coneWeighted 100 1 0.1\nvarListToWeights = LA.cmap (\\x -> 1/sqrt x) . LA.fromList\nwgts = varListToWeights vars\n\ntestRegressions :: ( F.ColumnHeaders '[w]\n                   , FR.BoolVal (FR.NonVoidField w)\n                   , V.KnownField w\n                   , Traversable f\n                   , Foldable f\n                   , K.Member K.ToPandoc effs\n                   , K.PandocEffects effs\n                   , MonadIO (K.Sem effs))\n                => Double\n                -> Double\n                -> Bool\n                -> Bool\n                -> T.Text\n                -> f (T.Text, (F.FrameRec AllCols -> K.Sem effs (FR.FrameRegressionResult Y True '[X] w AllCols)))\n                -> K.Sem effs ()\ntestRegressions  yNoise xNoise weighted offset vizId keyedFs = do\n  let title = \"Sy=\" <> showText yNoise <> \" gaussian noise added to ys & \"\n               <> \"Sx=\" <> showText xNoise <> \" gaussian noise added to xs\"\n               <> \" (\" <> (if weighted then \"cone weights\" else \"unweighted\") <> (if offset then \", w/offsets\" else \"\") <> \")\"\n      vars = if weighted then coneWeighted 100 1 0.1 else unweighted 100\n      wgts = varListToWeights vars\n      offsetM = if offset then (Just offsets) else Nothing\n      doOne dat (key, f) = do\n        result <- f dat\n        return (key, result)\n  frame <- liftIO (buildRegressable vars offsetM yNoise coeffs xNoise >>= makeFrame vars)\n  results <- traverse (doOne frame) keyedFs\n  let header _ _ = title\n  K.addMarkDown $ \"\\n## \" <> title \n  K.addBlaze $ do\n    H.div ! HA.style \"display: block-inline\" $ do\n      FR.prettyPrintRegressionResults id results S.cl95 FR.prettyPrintRegressionResultBlaze mempty\n      KB.placeVisualization (vizId <> \"_fits\") $ FV.keyedLayeredFrameScatterWithFit title id results S.cl95 frame\n      KB.placeVisualization (vizId <> \"_regresssionCoeffs\") $ FV.regressionCoefficientPlotMany id \"Parameters\" [\"intercept\",\"x\"] (fmap (\\(k,frr) -> (k, FR.regressionResult frr)) results) S.cl95\n\n-- I can't test the weighted and unweighted on the same things because those algos return different types in their results.  Which, maybe, is a good point.\ntestMany :: ( K.Member K.ToPandoc effs\n            , K.PandocEffects effs\n            , MonadIO (K.Sem effs)) =>  K.Sem effs ()\ntestMany = K.wrapPrefix \"Many\" $ do\n  let toTestUW :: _ -- that this is required is suspicious\n      toTestUW =\n        [\n          (\"OLS\", FR.ordinaryLeastSquares)\n        , (\"TLS\", FR.totalLeastSquares)\n        ]\n      toTestW :: _ -- that this is required is suspicious\n      toTestW =\n        [\n          (\"WOLS\", FR.weightedLeastSquares)\n        , (\"WTLS\", FR.weightedTLS)\n        ]\n  testRegressions 0.0 0.0 False False \"many1\" toTestUW\n  testRegressions 0.3 0.0 False False \"many2\" toTestUW\n  testRegressions 0.5 0.0 False False \"many3\" toTestUW\n  testRegressions 0.3 0.1 False False \"many4\" toTestUW\n  testRegressions 3 0.0 False False \"many9\" toTestUW\n  testRegressions @Weight 0.3 0.0 True False \"many6\" toTestW\n  testRegressions @Weight 0.5 0.0 True False \"many7\" toTestW\n  testRegressions @Weight 0.3 0.1 True False \"many8\" toTestW\n\n", "meta": {"hexsha": "f892a3e24af5d29a1bacdf2be552f317b5d2ff06", "size": 10128, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/FrameRegressions.hs", "max_stars_repo_name": "teto/Frames-utils", "max_stars_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-01-17T21:51:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T08:20:19.000Z", "max_issues_repo_path": "examples/FrameRegressions.hs", "max_issues_repo_name": "teto/Frames-utils", "max_issues_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-22T13:50:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T13:50:50.000Z", "max_forks_repo_path": "examples/FrameRegressions.hs", "max_forks_repo_name": "teto/Frames-utils", "max_forks_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-04T12:49:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T11:25:11.000Z", "avg_line_length": 46.6728110599, "max_line_length": 449, "alphanum_fraction": 0.6522511848, "num_tokens": 2747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.48873085832459884}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes                      #-}\n{-# LANGUAGE DataKinds                                #-}\n{-# LANGUAGE FlexibleContexts                         #-}\n{-# LANGUAGE GADTs                                    #-}\n{-# LANGUAGE PartialTypeSignatures                    #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE TupleSections                            #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# OPTIONS_GHC -fno-warn-partial-type-signatures     #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise       #-}\n\nimport           Backprop.Learn\nimport           Control.DeepSeq\nimport           Control.Exception\nimport           Control.Monad\nimport           Control.Monad.IO.Class\nimport           Control.Monad.Trans.Class\nimport           Control.Monad.Trans.State\nimport           Data.Char\nimport           Data.Conduit\nimport           Data.Default\nimport           Data.Foldable\nimport           Data.Proxy\nimport           Data.Time\nimport           Data.Type.Equality\nimport           Data.Type.Tuple\nimport           GHC.TypeNats\nimport           Numeric.LinearAlgebra.Static.Backprop\nimport           Numeric.LinearAlgebra.Static.Vector\nimport           Numeric.Opto\nimport           System.Environment\nimport           Text.Printf\nimport qualified Conduit                               as C\nimport qualified Data.Conduit.Combinators              as C\nimport qualified Data.Set                              as S\nimport qualified Data.Text                             as T\nimport qualified Data.Vector.Sized                     as SV\nimport qualified Data.Vector.Storable.Sized            as SVS\nimport qualified System.Random.MWC                     as MWC\nimport qualified System.Random.MWC.Distributions       as MWC\n\n-- | TODO: replace with 'LModel'\ncharRNN\n    :: forall n h1 h2. (KnownNat n, KnownNat h1, KnownNat h2)\n    => LModel _ _ (R n) (R n)\ncharRNN = fca softMax\n       #: dropout @h2 0.25\n       #: lstm\n       #: dropout @h1 0.25\n       #: lstm\n       #: nilLM\n\noneHotChar\n    :: KnownNat n\n    => S.Set Char\n    -> Char\n    -> R n\noneHotChar cs = oneHotR . fromIntegral . (`S.findIndex` cs)\n\nmain :: IO ()\nmain = MWC.withSystemRandom @IO $ \\g -> do\n    sourceFile:_  <- getArgs\n    charMap <- S.fromList <$> readFile sourceFile\n    SomeNat (Proxy :: Proxy n) <- pure $ someNatVal (fromIntegral (length charMap))\n    SomeNat (Proxy :: Proxy n') <- pure $ someNatVal (fromIntegral (length charMap - 1))\n    Just Refl <- pure $ sameNat (Proxy @(n' + 1)) (Proxy @n)\n\n    printf \"%d characters found.\\n\" (natVal (Proxy @n))\n\n    let model0 = charRNN @n @100 @50\n        model  = trainState . unrollFinal @(SV.Vector 15) $ model0\n\n    p0 <- initParamNormal model 0.2 g\n\n    let report n b = do\n          liftIO $ printf \"(Batch %d)\\n\" (b :: Int)\n          t0 <- liftIO getCurrentTime\n          C.drop (n - 1)\n          mp <- mapM (liftIO . evaluate . force) =<< await\n          t1 <- liftIO getCurrentTime\n          case mp of\n            Nothing -> liftIO $ putStrLn \"Done!\"\n            Just p@(p' :# s') -> do\n              chnk <- lift . state $ (,[])\n              liftIO $ do\n                printf \"Trained on %d points in %s.\\n\"\n                  (length chnk)\n                  (show (t1 `diffUTCTime` t0))\n                let trainScore = testModelAll maxIxTest model (TJust p) chnk\n                printf \"Training error:   %.3f%%\\n\" ((1 - trainScore) * 100)\n\n                forM_ (take 15 chnk) $ \\(x,y) -> do\n                  let primed = primeModel model0 (TJust p') x (TJust s')\n                  testOut <- fmap reverse . flip execStateT [] $\n                      iterateModelM ( fmap (oneHotR . fromIntegral)\n                                    . (>>= \\r -> r <$ modify (r:))    -- trace\n                                    . (`MWC.categorical` g)\n                                    . SVS.fromSized\n                                    . rVec\n                                    )\n                            100 model0 (TJust p') y primed\n                  printf \"%s|%s\\n\"\n                    (sanitize . (`S.elemAt` charMap) . fromIntegral . maxIndexR <$> (toList x ++ [y]))\n                    (sanitize . (`S.elemAt` charMap) <$> testOut)\n              report n (b + 1)\n\n    C.runResourceT . flip evalStateT []\n        . runConduit\n        $ forever ( C.sourceFile sourceFile\n                 .| C.decodeUtf8\n                 .| C.concatMap T.unpack\n                 .| C.map (oneHotChar charMap)\n                 .| leadings\n                  )\n       .| skipSampling 0.02 g\n       .| C.iterM (modify . (:))\n       .| optoConduit\n            def\n            p0\n            (adam def (modelGradStoch crossEntropy noReg model g))\n       .| report 2500 0\n       .| C.sinkNull\n\n\nsanitize :: Char -> Char\nsanitize c | isPrint c = c\n           | otherwise = '#'\n", "meta": {"hexsha": "7060a940074f81adc4ff276ab8694abea80e49f5", "size": 4987, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/char-rnn.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "app/char-rnn.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "app/char-rnn.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 38.3615384615, "max_line_length": 102, "alphanum_fraction": 0.5005013034, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4884339931226331}}
{"text": "{-# LANGUAGE GADTs #-}\n{-# LANGUAGE QuasiQuotes #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TemplateHaskell #-}\n\nimport Frames\nimport Frames.CSV (rowGen, RowGen(..), readTableOpt)\nimport Pipes (Producer)\nimport qualified Data.Foldable as F\nimport qualified Numeric.LinearAlgebra.HMatrix as H\n\nimport Numeric.BMML.RVMC\n\n\ntableTypes'\n    rowGen\n    { rowTypeName = \"Iris\"\n    , columnNames = [ \"sepal length\"\n                    , \"sepal width\"\n                    , \"petal length\"\n                    , \"petal width\"\n                    , \"iris name\"]\n    }\n    \"data/iris.csv\"\n\nirisStream :: Producer Iris IO ()\nirisStream = readTableOpt irisParser \"data/iris.csv\"\n\nloadIris :: IO (Frame Iris)\nloadIris = inCoreAoS irisStream\n\nrestructureIris :: ( CanDelete IrisName rs\n                   , rs' ~ RDelete IrisName rs\n                   , AllAre Double (UnColumn rs')\n                   , AsVinyl rs') => Record rs -> Record (IrisName ': rs')\nrestructureIris r = frameCons (rget' irisName' r) (rdel [pr|IrisName|] r)\n\nsplitXY :: (AllAre Double (UnColumn rs), AsVinyl rs)\n        => Record (s :-> Text ': rs) -> (Text, [Double])\nsplitXY (recUncons -> (h, t)) = (h, recToList t)\n\nloadDataSet :: IO ([Text], [[Double]])\nloadDataSet =\n    loadIris >>=\n    \\ds ->\n         return $ unzip $ F.foldMap ((: []) . splitXY . restructureIris) ds\n\n\nsplitTrainTest :: [[Double]]\n               -> [Text]\n               -> (([[Double]], [Double]), ([[Double]], [Double]))\nsplitTrainTest x y =\n    splitTT\n        (takeN\n             (foldr\n                  (\\(xi,yi) ((x1,y1),(x0,y0)) ->\n                        if yi == \"Iris-setosa\"\n                            then ((x1 ++ [xi], y1 ++ [1]), (x0, y0))\n                            else ((x1, y1), (x0 ++ [xi], y0 ++ [0])))\n                  (([], []), ([], []))\n                  (zip x y)))\n  where\n    takeN ((x1,y1),(x0,y0)) = ((take n x1, take n y1), (take n x0, take n y0))\n      where\n        n = min (length y1) (length y0)\n    splitTT ((x1,y1),(x0,y0)) = ((x1Train ++ x0Train, y1Train ++ y0Train), (x1Test ++ x0Test, y1Test ++ y0Test))\n      where\n        n = length y1\n        m = floor (0.7 * fromIntegral n)\n        (x1Train,x1Test) = splitAt m x1\n        (y1Train,y1Test) = splitAt m y1\n        (x0Train,x0Test) = splitAt m x0\n        (y0Train,y0Test) = splitAt m y0\n\nmain :: IO ()\nmain = do\n    (y,x) <- loadDataSet\n    let ((xTrain,yTrain),(xTest,yTest)) = splitTrainTest x y\n        c = fit (H.fromLists xTrain) (H.fromList yTrain)\n    mapM_\n        (\\(x,y) ->\n              print\n                  (\"Real: \" ++\n                   show y ++\n                   \"probability of class 1: \" ++\n                   show (predict c (H.fromList x))))\n        (zip xTest yTest)\n", "meta": {"hexsha": "f6ec25b23bf3c738dc9ee2913a6f8319e77f2a23", "size": 2851, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "demo/Classifier.hs", "max_stars_repo_name": "DbIHbKA/BMML", "max_stars_repo_head_hexsha": "1ed44258bacf91a1319a34f50d0ebcc6e5bbaef9", "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": "demo/Classifier.hs", "max_issues_repo_name": "DbIHbKA/BMML", "max_issues_repo_head_hexsha": "1ed44258bacf91a1319a34f50d0ebcc6e5bbaef9", "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": "demo/Classifier.hs", "max_forks_repo_name": "DbIHbKA/BMML", "max_forks_repo_head_hexsha": "1ed44258bacf91a1319a34f50d0ebcc6e5bbaef9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9891304348, "max_line_length": 112, "alphanum_fraction": 0.5138547878, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733955639775, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.488139943732376}}
{"text": "{-# LANGUAGE ConstraintKinds  #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Poisson1D\nwhere\n\nimport qualified Basis\nimport           Data.List\nimport           Element               as E\nimport           Mesh\nimport           Numeric.LinearAlgebra\nimport           Quadrature            (integrate)\nimport qualified ShapeFcns\n\n-- Synonym for numeric/fractional constraints\ntype FrElNuFi a = (Fractional a,Element a,Numeric a,Field a)\n\n-- Element stiffness integrand\nstiffnessIntegrand :: (E.Element e,ShapeFcns.ShapeFcn s,Basis.Basis b,FrElNuFi a) => e a -> s b -> [a] -> Matrix a\nstiffnessIntegrand elem shpFcn xi = fromLists [[]]\n\n-- Element mass integrand\nmassIntegrand :: (E.Element e,ShapeFcns.ShapeFcn s,Basis.Basis b,FrElNuFi a) => e a -> s b -> [a] -> Matrix a\nmassIntegrand elem shpFcn xi = fromLists [[]]\n\n-- Element mass and stiffness matrices\n-- Must multiply by the determinant of the Jacobian here!!!\nelemMatrices :: (E.Element e,ShapeFcns.ShapeFcn s,Basis.Basis b,FrElNuFi a) => e a -> s b -> Int -> (Matrix a,Matrix a)\nelemMatrices elem shpFcn ngpts = (stiffnessMat, massMat)\n  where\n    stiffnessMat = integrate 1 ngpts (stiffnessIntegrand elem shpFcn)\n    massMat      = integrate 1 ngpts (massIntegrand elem shpFcn)\n\nassembleSubMatrix :: FrElNuFi a => \n\n-- Function which assembles the global stiffness and mass matrices\nassembleGlobalMatrices :: (E.Element e, ShapeFcns.ShapeFcn s,Basis.Basis b, FrElNuFi a) => Mesh e a -> s b -> Int -> a -> [[((Int,Int),a)]]\nassembleGlobalMatrices grid shpFcn ngpts advSpd = [globalK, globalM, globalF]\n  where\n    globalK = []\n    globalM = []\n    globalF = []\n\n-- Function for applying boundary conditions\napplyBCs _ = []\n", "meta": {"hexsha": "88252c4e133369d44e73d4ca7ffa3a0ba98b2127", "size": 1679, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Poisson1D.hs", "max_stars_repo_name": "jgrisham4/hfem", "max_stars_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "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/Poisson1D.hs", "max_issues_repo_name": "jgrisham4/hfem", "max_issues_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "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/Poisson1D.hs", "max_forks_repo_name": "jgrisham4/hfem", "max_forks_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5, "max_line_length": 139, "alphanum_fraction": 0.6938653961, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4880591407467426}}
{"text": "{- |\nModule      :  Numeric.GSL.ODE\nCopyright   :  (c) Alberto Ruiz 2010\nLicense     :  GPL\n\nMaintainer  :  Alberto Ruiz (aruiz at um dot es)\nStability   :  provisional\nPortability :  uses ffi\n\nSolution of ordinary differential equation (ODE) initial value problems.\n\n<http://www.gnu.org/software/gsl/manual/html_node/Ordinary-Differential-Equations.html>\n\nA simple example:\n\n@import Numeric.GSL\nimport Numeric.LinearAlgebra\nimport Graphics.Plot\n\nxdot t [x,v] = [v, -0.95*x - 0.1*v]\n\nts = linspace 100 (0,20 :: Double)\n\nsol = odeSolve xdot [10,0] ts\n\nmain = mplot (ts : toColumns sol)@\n\n-}\n-----------------------------------------------------------------------------\n\nmodule Numeric.GSL.ODE (\n    odeSolve, odeSolveV, ODEMethod(..), Jacobian\n) where\n\nimport Data.Packed.Internal\nimport Numeric.GSL.Internal\n\nimport Foreign.Ptr(FunPtr, nullFunPtr, freeHaskellFunPtr)\nimport Foreign.C.Types\nimport System.IO.Unsafe(unsafePerformIO)\n\n-------------------------------------------------------------------------\n\ntype Jacobian = Double -> Vector Double -> Matrix Double\n\n-- | Stepping functions\ndata ODEMethod = RK2 -- ^ Embedded Runge-Kutta (2, 3) method.\n               | RK4 -- ^ 4th order (classical) Runge-Kutta. The error estimate is obtained by halving the step-size. For more efficient estimate of the error, use the embedded methods.\n               | RKf45 -- ^ Embedded Runge-Kutta-Fehlberg (4, 5) method. This method is a good general-purpose integrator.\n               | RKck -- ^ Embedded Runge-Kutta Cash-Karp (4, 5) method.\n               | RK8pd -- ^ Embedded Runge-Kutta Prince-Dormand (8,9) method.\n               | RK2imp Jacobian -- ^ Implicit 2nd order Runge-Kutta at Gaussian points.\n               | RK4imp Jacobian -- ^ Implicit 4th order Runge-Kutta at Gaussian points.\n               | BSimp Jacobian -- ^ Implicit Bulirsch-Stoer method of Bader and Deuflhard. The method is generally suitable for stiff problems.\n               | RK1imp Jacobian -- ^ Implicit Gaussian first order Runge-Kutta. Also known as implicit Euler or backward Euler method. Error estimation is carried out by the step doubling method.\n               | MSAdams -- ^ A variable-coefficient linear multistep Adams method in Nordsieck form. This stepper uses explicit Adams-Bashforth (predictor) and implicit Adams-Moulton (corrector) methods in P(EC)^m functional iteration mode. Method order varies dynamically between 1 and 12. \n               | MSBDF Jacobian -- ^ A variable-coefficient linear multistep backward differentiation formula (BDF) method in Nordsieck form. This stepper uses the explicit BDF formula as predictor and implicit BDF formula as corrector. A modified Newton iteration method is used to solve the system of non-linear equations. Method order varies dynamically between 1 and 5. The method is generally suitable for stiff problems.\n\n\n-- | A version of 'odeSolveV' with reasonable default parameters and system of equations defined using lists.\nodeSolve\n    :: (Double -> [Double] -> [Double])        -- ^ xdot(t,x)\n    -> [Double]        -- ^ initial conditions\n    -> Vector Double   -- ^ desired solution times\n    -> Matrix Double   -- ^ solution\nodeSolve xdot xi ts = odeSolveV RKf45 hi epsAbs epsRel (l2v xdot) (fromList xi) ts\n    where hi = (ts@>1 - ts@>0)/100\n          epsAbs = 1.49012e-08\n          epsRel = 1.49012e-08\n          l2v f = \\t -> fromList  . f t . toList\n\n-- | Evolution of the system with adaptive step-size control.\nodeSolveV\n    :: ODEMethod\n    -> Double -- ^ initial step size\n    -> Double -- ^ absolute tolerance for the state vector\n    -> Double -- ^ relative tolerance for the state vector\n    -> (Double -> Vector Double -> Vector Double)   -- ^ xdot(t,x)\n    -> Vector Double     -- ^ initial conditions\n    -> Vector Double     -- ^ desired solution times\n    -> Matrix Double     -- ^ solution\nodeSolveV RK2 = odeSolveV' 0 Nothing\nodeSolveV RK4 = odeSolveV' 1 Nothing\nodeSolveV RKf45 = odeSolveV' 2 Nothing\nodeSolveV RKck = odeSolveV' 3 Nothing\nodeSolveV RK8pd = odeSolveV' 4 Nothing\nodeSolveV (RK2imp jac) = odeSolveV' 5 (Just jac)\nodeSolveV (RK4imp jac) = odeSolveV' 6 (Just jac)\nodeSolveV (BSimp jac) = odeSolveV' 7 (Just jac)\nodeSolveV (RK1imp jac) = odeSolveV' 8 (Just jac)\nodeSolveV MSAdams = odeSolveV' 9 Nothing\nodeSolveV (MSBDF jac) = odeSolveV' 10 (Just jac)\n\n\nodeSolveV'\n    :: CInt\n    -> Maybe (Double -> Vector Double -> Matrix Double)   -- ^ optional jacobian\n    -> Double -- ^ initial step size\n    -> Double -- ^ absolute tolerance for the state vector\n    -> Double -- ^ relative tolerance for the state vector\n    -> (Double -> Vector Double -> Vector Double)   -- ^ xdot(t,x)\n    -> Vector Double     -- ^ initial conditions\n    -> Vector Double     -- ^ desired solution times\n    -> Matrix Double     -- ^ solution\nodeSolveV' method mbjac h epsAbs epsRel f  xiv ts = unsafePerformIO $ do\n    let n   = dim xiv\n    fp <- mkDoubleVecVecfun (\\t -> aux_vTov (checkdim1 n . f t))\n    jp <- case mbjac of\n        Just jac -> mkDoubleVecMatfun (\\t -> aux_vTom (checkdim2 n . jac t))\n        Nothing  -> return nullFunPtr\n    sol <- vec xiv $ \\xiv' ->\n            vec (checkTimes ts) $ \\ts' ->\n             createMIO (dim ts) n\n              (ode_c (method) h epsAbs epsRel fp jp // xiv' // ts' )\n              \"ode\"\n    freeHaskellFunPtr fp\n    return sol\n\nforeign import ccall safe \"ode\"\n    ode_c :: CInt -> Double -> Double -> Double -> FunPtr (Double -> TVV) -> FunPtr (Double -> TVM) -> TVVM\n\n-------------------------------------------------------\n\ncheckdim1 n v\n    | dim v == n = v\n    | otherwise = error $ \"Error: \"++ show n\n                        ++ \" components expected in the result of the function supplied to odeSolve\"\n\ncheckdim2 n m\n    | rows m == n && cols m == n = m\n    | otherwise = error $ \"Error: \"++ show n ++ \"x\" ++ show n\n                        ++ \" Jacobian expected in odeSolve\"\n\ncheckTimes ts | dim ts > 1 && all (>0) (zipWith subtract ts' (tail ts')) = ts\n              | otherwise = error \"odeSolve requires increasing times\"\n    where ts' = toList ts\n", "meta": {"hexsha": "ab037bd37ee46e216d388efc18521766e16ba8ec", "size": 6059, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/ODE.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/ODE.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/ODE.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": 44.2262773723, "max_line_length": 426, "alphanum_fraction": 0.6360785608, "num_tokens": 1647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48801751963770784}}
{"text": "{-# LANGUAGE DeriveGeneric #-}\n\n{-|\nModule      : HABQTlib.Data\n\nThis module contains data types and helper functions for working with quantum\nstate vectors and density matrices.\n-}\nmodule HABQTlib.Data\n  ( Dim\n  , Rank\n  , NumberOfParticles\n  , QBitNum\n  , Weight\n  , MHMCiter\n  , OptIter\n  , OutputVerb(..)\n  , DensityMatrix(..)\n  , truncateRank\n  , PureStateVector(..)\n  , pureStateLikelihood\n  , svToDM\n  , WeighedDensityMatrix(..)\n  , mkWDM\n  , mkWDM1\n  , WeighedPureStateVector(..)\n  , (<+>)\n  , fidelity\n  , fidelityDM\n  , validSV\n  , validDM\n  , validPartNum\n  , validRank\n  , validMHMCiter\n  , validOptIter\n  , validQBitN\n  ) where\n\nimport Control.Newtype.Generics (Newtype, unpack)\nimport Data.Bool.HT (select)\nimport Data.Complex\nimport Data.Validation\nimport GHC.Generics (Generic)\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra (Matrix)\n\n-- | Dimension of Hilbert space.\ntype Dim = Int\n\n-- | Rank of mixed state.\ntype Rank = Int\n\n-- | Number of particles per rank.\ntype NumberOfParticles = Int\n\n-- | Number of quantum bits.\ntype QBitNum = Int\n\n-- | Number of MHMC iterations to perform when resampling.\ntype MHMCiter = Int\n\n-- | Number of optimisation steps to perform when searching for optimal\n-- measurment.\ntype OptIter = Int\n\n-- | Weight associated with a particle.\ntype Weight = Double\n\n-- | Output verbosity settings.\ndata OutputVerb\n  = NoOutput -- ^ No stdout output\n  | FidOutput -- ^ Only output fidelities and weights of hierarchical mean estimates\n  | FullOutput -- ^ Full output, including resampling diagnostic information\n  deriving (Eq, Show, Ord)\n\n-- | Density matrix are stored as hmatrix matrices of complex doubles.\nnewtype DensityMatrix = DensityMatrix\n  { getDensityMatrix :: Matrix (Complex Double)\n  } deriving (Eq, Show, Generic)\n\n-- | Pure state vectors are stored as hmatrix matrices of complex doubles.\n-- Such matrices only have one column.\nnewtype PureStateVector = PureStateVector\n  { getStateVector :: Matrix (Complex Double)\n  } deriving (Eq, Show, Generic)\n\ninstance Newtype DensityMatrix\n\ninstance Newtype PureStateVector\n\n-- | Check whether a pure state vector is properly normed.\nvalidSV :: PureStateVector -> Validation [String] PureStateVector\nvalidSV =\n  validate\n    [\"State vector must have unit norm.\"]\n    (\\x -> abs (1 - LA.norm_2 (unpack x)) < 1e-12)\n\n-- | Verify that density matrix is Hermitian and has trace 1.\nvalidDM :: DensityMatrix -> Validation [String] DensityMatrix\nvalidDM =\n  let traceU :: LA.Matrix (Complex Double) -> Bool\n      traceU dm =\n        (abs (1 - (magnitude . LA.sumElements . LA.takeDiag) dm) < 1e-12)\n      hermU dm = (LA.norm_2 (dm - LA.tr dm) < 1e-6)\n      both = ((&&) <$> traceU <*> hermU) . unpack\n      dmM = [\"Density matrix must be Hermitian and have trace of 1.\"]\n   in validate dmM both\n\nqnM :: [String]\nqnM = [\"Number of quantum bits must be a positive integer.\"]\n\n-- | Verify that number of quantum bits is positive.\nvalidQBitN :: QBitNum -> Validation [String] QBitNum\nvalidQBitN = validate qnM (> 0)\n\nmiM :: [String]\nmiM = [\"Number of MHMC iterations must be a positive integer.\"]\n\n-- | Verify that number of MHMC iterations is a positive integer.\nvalidMHMCiter :: MHMCiter -> Validation [String] MHMCiter\nvalidMHMCiter = validate miM (> 0)\n\npnM :: [String]\npnM = [\"Number of particles per rank must be a positive integer.\"]\n\n-- | Verify that particle number is a positive integer.\nvalidPartNum :: NumberOfParticles -> Validation [String] NumberOfParticles\nvalidPartNum = validate pnM (> 0)\n\nrM :: [String]\nrM = [\"Rank must be a positive integer.\"]\n\n-- | Verify that rank is a positive integer. Setting rank to be higher than\n-- the dimension of space creates poinless performance overhead, but isn't\n-- prevented by validation.\nvalidRank :: Rank -> Validation [String] Rank\nvalidRank = validate rM (> 0)\n\noiM :: [String]\noiM = [\"Number of POVM optimisation iterations must be a positive integer.\"]\n\n-- | Verify that number of POVM optimisation iterations is positive.\nvalidOptIter :: OptIter -> Validation [String] OptIter\nvalidOptIter = validate oiM (> 0)\n\n-- | Weighed density matrix where weight is stored separately as first\n-- coordinate of a tuple.\nnewtype WeighedDensityMatrix = WeighedDensityMatrix\n  { getWDM :: (Weight, DensityMatrix)\n  } deriving (Eq, Show, Generic)\n\n-- | A shorter alias for curried 'WeighedDensityMatrix' constructor.\nmkWDM :: Weight -> DensityMatrix -> WeighedDensityMatrix\nmkWDM w dm = WeighedDensityMatrix (w, dm)\n\n-- | Alias for @'mkWDM' 1@.\nmkWDM1 :: DensityMatrix -> WeighedDensityMatrix\nmkWDM1 = mkWDM 1\n\n-- | Weighed state vector where weight is stored separately as first coordinate\n-- of a tuple.\nnewtype WeighedPureStateVector = WeighedPureStateVector\n  { getWSV :: (Weight, PureStateVector)\n  } deriving (Eq, Show, Generic)\n\ninstance Newtype WeighedDensityMatrix\n\ninstance Newtype WeighedPureStateVector\n\n-- | Fidelity (probability of measurement) between pure states.\nfidelity :: PureStateVector -> PureStateVector -> Double\nfidelity (PureStateVector sv1) (PureStateVector sv2) =\n  let ips = magnitude (LA.atIndex (LA.tr sv1 LA.<> sv2) (0, 0)) ^ (2 :: Int)\n   in select ips [(ips < 0, 0), (ips > 1, 1)]\n\n-- | Fidelity (probability of measurement) between mixed states.\nfidelityDM :: DensityMatrix -> DensityMatrix -> Double\nfidelityDM (DensityMatrix dm1) (DensityMatrix dm2) =\n  let (u1, s1) = LA.leftSV dm1\n      (u2, s2) = LA.leftSV dm2\n      ss1 = LA.cmap (\\x -> sqrt x :+ 0) s1\n      ss2 = LA.cmap (\\x -> sqrt x :+ 0) s2\n   in LA.norm_nuclear\n        (u1 LA.<> LA.diag ss1 LA.<> LA.tr u1 LA.<> u2 LA.<> LA.diag ss2 LA.<>\n         LA.tr u2) ^\n      (2 :: Int)\n\n-- | Calculate the density matrix of a given pure state.\nsvToDM :: PureStateVector -> DensityMatrix\nsvToDM (PureStateVector sv) = DensityMatrix $ sv LA.<> LA.tr sv\n\ninfix 8 <+>\n\n-- | Given two weighed density matrixes, compute their mixture. Associative\n-- operation.\n(<+>) :: WeighedDensityMatrix -> WeighedDensityMatrix -> WeighedDensityMatrix\nwdm0 <+> wdm1 =\n  WeighedDensityMatrix\n    (w0 + w1, DensityMatrix $ LA.scale c0 dm0 + LA.scale c1 dm1)\n  where\n    up = fmap unpack . unpack\n    (w0, dm0) = up wdm0\n    (w1, dm1) = up wdm1\n    cs = LA.fromList [w0 :+ 0, w1 :+ 0]\n    csn = LA.scale (1 / LA.sumElements cs) cs\n    c0 = csn LA.! 0\n    c1 = csn LA.! 1\n\n-- | Probability of obtaining a measurement result when projecting a system in\n-- mixed state determined by a density matrix onto a pure state.\npureStateLikelihood :: PureStateVector -> DensityMatrix -> Double\npureStateLikelihood (PureStateVector sv) (DensityMatrix dm) =\n  let p =\n        LA.magnitude . LA.sumElements . LA.takeDiag $ LA.tr sv LA.<> dm LA.<> sv\n   in select p [(p < 0, 0), (p > 1, 1)]\n\n-- | Set smallest eigenvalues of a weighed density matrix to zero until\n-- specified rank is reached.\ntruncateRank :: Rank -> WeighedDensityMatrix -> WeighedDensityMatrix\ntruncateRank targetRank (WeighedDensityMatrix (w, DensityMatrix dm)) =\n  let (u, s, _) = LA.svd dm\n      st = LA.real $ LA.subVector 0 targetRank s\n      ut = u LA.\u00bf [0 .. (targetRank - 1)]\n      stn = LA.scale (1 / LA.sumElements st) st\n   in WeighedDensityMatrix\n        (w, DensityMatrix $ ut LA.<> LA.diag stn LA.<> LA.tr ut)\n", "meta": {"hexsha": "76a6a766b5a958509aaee732c2b5b1301eee5ff4", "size": 7205, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HABQTlib/Data.hs", "max_stars_repo_name": "Belinsky-L-V/HABQT", "max_stars_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-23T03:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T08:45:58.000Z", "max_issues_repo_path": "src/HABQTlib/Data.hs", "max_issues_repo_name": "Belinsky-L-V/HABQT", "max_issues_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "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/HABQTlib/Data.hs", "max_forks_repo_name": "Belinsky-L-V/HABQT", "max_forks_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "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.7400881057, "max_line_length": 84, "alphanum_fraction": 0.7003469813, "num_tokens": 2053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4880175196377078}}
{"text": "{-# LANGUAGE FlexibleContexts       #-}\n{-# LANGUAGE FlexibleInstances      #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses  #-}\n{-# LANGUAGE OverloadedStrings      #-}\n{-# LANGUAGE TemplateHaskell        #-}\n\nmodule DBPnet.ReadCount\n    ( readCount\n    , ReadCountOpt\n    , binSize\n    , pValue\n    , chromSize\n    , varFilter\n    ) where\n\nimport           Bio.Data.Bed\nimport Bio.Data.Bed.Utils\nimport           Bio.Utils.Misc                    (readDouble, readInt)\nimport           Conduit\nimport Lens.Micro ((.~), (^.))\nimport Lens.Micro.TH (makeFields)\nimport           Control.Monad                     (forM, forM_)\nimport           Control.Monad.Base                (liftBase)\nimport           Control.Monad.Morph               (hoist)\nimport qualified Data.ByteString.Char8             as B\nimport qualified Data.Conduit.Zlib                 as Zlib\nimport           Data.Default\nimport           Data.Double.Conversion.ByteString (toFixed)\nimport           Data.Int                          (Int32)\nimport           Data.List\nimport qualified Data.Matrix.Unboxed               as MU\nimport qualified Data.Text                         as T\nimport qualified Data.Vector.Unboxed               as U\nimport           Shelly                            hiding (FilePath, withTmpDir)\nimport           Statistics.Distribution           (complCumulative)\nimport           Statistics.Distribution.Poisson   (poisson)\nimport           Statistics.Sample\nimport           System.IO\n\nimport           DBPnet.Type\nimport           DBPnet.Utils\n\ndata ReadCountOpt = ReadCountOpt\n    { readCountOptBinSize   :: !Int\n    , readCountOptPValue    :: !Double\n    , readCountOptChromSize :: ![(B.ByteString, Int)]\n    , readCountOptVarFilter :: !Double   -- ^ remove constant signal\n    } deriving (Show, Read)\n\nmakeFields ''ReadCountOpt\n\ninstance Default ReadCountOpt where\n    def = ReadCountOpt\n        { readCountOptBinSize = 1000\n        , readCountOptPValue = 1e-2\n        , readCountOptChromSize = []\n        , readCountOptVarFilter  = 0.1\n        }\n\nreadCount :: [Experiment] -> FilePath -> ReadCountOpt -> IO [(String, FilePath)]\nreadCount es outDir opt = withTmpDir outDir $ \\tmp -> do\n    -- count reads for each experiment\n    rs <- forM es $ \\e -> do\n        let fls = e^.files\n            targetName = e^.eid\n            output = tmp ++ \"/\" ++ targetName\n        shelly $ mkdir_p $ fromText $ T.pack output\n        rc fls output\n        return (targetName, output)\n\n    combineAndFilter rs outDir\n  where\n    rc inputs output = do\n        readcounts <- forM inputs $ \\input -> do\n            let fl = input^.location\n                fileFormat = input^.format\n            case fileFormat of\n                Bed -> runResourceT $ runConduit $ streamBed fl .| countTagsBinBed (opt^.binSize) regions\n                BedGZip -> runResourceT $ runConduit $ streamBedGzip fl .| countTagsBinBed (opt^.binSize) regions\n                _ -> undefined\n\n        forM_ (zip (opt^.chromSize) $ merge readcounts) $ \\((chr,_), v) -> do\n            let outFile = output ++ \"/\" ++ B.unpack chr\n                l = U.length v\n                bg_glob = estimateBG v\n            withFile outFile WriteMode $ \\handle ->\n                forM_ [0..l-1] $ \\i -> do\n                    let getBG x = let len = x `div` 2\n                                      vec = U.map (v U.!) $ U.fromList $\n                                            filter (\\x -> x >= 0 && x < l) $\n                                            [i-len..i-1] ++ [i+1,i+len]\n                                  in estimateBG vec\n                        bg_local = maximum $ bg_glob : map getBG [14, 24]\n                        c = v U.! i\n                    case () of\n                        _ | c == 0 -> B.hPutStrLn handle \"0\"\n                          | complCumulative (poisson bg_local) c <= (opt^.pValue) ->\n                                B.hPutStrLn handle $ toFixed 4 $ c / bg_local\n                          | otherwise -> B.hPutStrLn handle \"0\"\n      where\n        regions = map (\\(chr,s) -> BED3 chr 0 s) $ opt^.chromSize\n        estimateBG xs = let (m, var) = meanVarianceUnb xs\n                        in mean $ U.filter (< (m + 2 * sqrt var)) xs\n        merge rs = map f $ transpose counts\n          where\n            f = foldl1' (\\acc x -> U.zipWith (+) acc x)\n            counts = flip map rs $ \\(values, _) ->\n                     map (U.map (fromIntegral :: Int32 -> Double)) values\n-- we do not need to normalize or average because we don't use input/control\n--            n = fromIntegral $ length rs\n\n    combineAndFilter xs output = do\n        shelly $ mkdir_p $ fromText $ T.pack output\n        let (ids, dirs)  = unzip xs\n\n        dat <- forM (opt^.chromSize) $ \\(chr', _) -> do\n            let chr = B.unpack chr'\n            rs <- forM dirs $ \\dir -> do\n                c <- B.readFile $ dir ++ \"/\" ++ chr\n                return $ U.fromList $ map readDouble $ B.lines c\n            let (idx, rc) = unzip $ filter (highCV . snd) $\n                            zip [0, opt^.binSize ..] $\n                            MU.toRows $ MU.fromColumns rs\n            return (zip (repeat chr') idx, rc)\n\n        let idx = concat $ fst $ unzip dat\n            dat' = MU.fromColumns $ concat $ snd $ unzip dat\n        forM (zip ids $ MU.toRows dat') $ \\(i, v) -> do\n            let outFile = output ++ \"/\" ++ i ++ \".bed\"\n            writeBed outFile $ zipWith toBed idx $ U.toList v\n            return (i, outFile)\n      where\n        highCV v = let (_,var) = meanVarianceUnb v in sqrt var >= opt^.varFilter\n        toBed (chr,i) x = BEDGraph chr i (i+(opt^.binSize)) x\n", "meta": {"hexsha": "0de15d4d1eb9ad0c239131a4fc0e8bed2d4a5684", "size": 5659, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/DBPnet/ReadCount.hs", "max_stars_repo_name": "kaizhang/DBPnet", "max_stars_repo_head_hexsha": "e0372a8641c14ffd71f718af0d7fc761f66898bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-08-24T11:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T11:12:52.000Z", "max_issues_repo_path": "src/DBPnet/ReadCount.hs", "max_issues_repo_name": "kaizhang/DBPnet", "max_issues_repo_head_hexsha": "e0372a8641c14ffd71f718af0d7fc761f66898bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-12-02T04:36:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T03:25:34.000Z", "max_forks_repo_path": "src/DBPnet/ReadCount.hs", "max_forks_repo_name": "kaizhang/DBPnet", "max_forks_repo_head_hexsha": "e0372a8641c14ffd71f718af0d7fc761f66898bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-20T23:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-20T23:51:57.000Z", "avg_line_length": 41.6102941176, "max_line_length": 113, "alphanum_fraction": 0.5181127408, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4875791776990873}}
{"text": "module Seed\n  ( Seed\n  , createSeed\n  , arrowsAt\n  , drawSeed\n  )\nwhere\n\nimport           Arrow                          ( Arrow\n                                                , arrange\n                                                , endpoint\n                                                , updateArrow\n                                                )\nimport qualified Fourier\nimport           Data.Complex\nimport           Graphics.Gloss\n\n-- A seed represents an initial state of arrow frequencies, directions, and magnitudes\n-- Any complex function can be traced out by changing this initial state.\n-- It also contains some drawing and scaling information.\ndata Seed = Seed { _arrows :: [(Arrow, Integer)], _spaceScale :: Float, _timeScale :: Float, _trailLength :: Float }\n\ncreateSeed :: (Float -> Complex Float) -> Int -> Float -> Float -> Float -> Seed\ncreateSeed f n spaceScale timeScale trailLength = Seed\n  { _arrows      = arrows\n  , _spaceScale  = spaceScale\n  , _timeScale   = timeScale\n  -- measure trail length by percentage of a time-scaled second\n  , _trailLength = trailLength\n  }\n where\n  -- order arrow frequencies 0, 1, -1, 2, -2, 3, -3, etc.\n  freqs             = take n (0 : concat [ [x, -x] | x <- [1 ..] ])\n  startingPositions = map (Fourier.coefficient f) freqs\n  arrows            = zip startingPositions freqs\n\narrowsAt :: Seed -> Float -> [Arrow]\narrowsAt seed t = map (\\(arr, freq) -> updateArrow arr freq t) (_arrows seed)\n\ndrawSeed :: Seed -> Float -> Picture\ndrawSeed seed seconds = scale s s $ Pictures [vectors, tip, trail]\n where\n  s         = _spaceScale seed\n  t         = _timeScale seed * seconds\n  positions = arrange $ arrowsAt seed t\n  (x, y)    = last positions\n  -- draw stuff\n  vectors   = color (light aquamarine) . line $ positions\n  tip       = color red . translate x y $ circleSolid (5 / _spaceScale seed)\n  trail     = color white . line $ map (endpoint . arrowsAt seed) ts\n  -- the trail draws through points with a step size of 1/1000 of a (time-scaled) second\n  tf        = truncateTo 3 t\n  ti        = max 0 (tf - _trailLength seed)\n  ts        = [ti, ti + 0.001 .. t]\n\n-- truncate a real number to the given number of decimal places\ntruncateTo :: (RealFrac a) => Integer -> a -> a\ntruncateTo n = (/ 10 ^ n) . fromIntegral . truncate . (* 10 ^ n)\n", "meta": {"hexsha": "7fa381cc19952438ac3594af2d0ebd540158f38e", "size": 2307, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Seed.hs", "max_stars_repo_name": "juliagracedefoor/fourier-visualizer", "max_stars_repo_head_hexsha": "c690aa6ebd9a32ae885e61478cd29a6aa20e889c", "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/Seed.hs", "max_issues_repo_name": "juliagracedefoor/fourier-visualizer", "max_issues_repo_head_hexsha": "c690aa6ebd9a32ae885e61478cd29a6aa20e889c", "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/Seed.hs", "max_forks_repo_name": "juliagracedefoor/fourier-visualizer", "max_forks_repo_head_hexsha": "c690aa6ebd9a32ae885e61478cd29a6aa20e889c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1016949153, "max_line_length": 116, "alphanum_fraction": 0.5877763329, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48717556320583105}}
{"text": "module PatternRecogn.Lina(\n\tMatrix, Vector,\n\tMatrixOf, VectorOf,\n\tmodule Lina\n) where\n\n\nimport Numeric.LinearAlgebra as Lina hiding( Matrix, Vector )\nimport qualified Numeric.LinearAlgebra as LinaIntern\n\ntype Matrix = LinaIntern.Matrix Double\ntype Vector = LinaIntern.Vector Double\n\ntype MatrixOf = LinaIntern.Matrix\ntype VectorOf = LinaIntern.Vector\n", "meta": {"hexsha": "0a147b9974a4513adf78ca85077de481e13477b1", "size": 351, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PatternRecogn/Lina.hs", "max_stars_repo_name": "EsGeh/pattern-recognition", "max_stars_repo_head_hexsha": "3d2512775cb7e999e8b0a142ea72ec3c9fedcc02", "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/PatternRecogn/Lina.hs", "max_issues_repo_name": "EsGeh/pattern-recognition", "max_issues_repo_head_hexsha": "3d2512775cb7e999e8b0a142ea72ec3c9fedcc02", "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/PatternRecogn/Lina.hs", "max_forks_repo_name": "EsGeh/pattern-recognition", "max_forks_repo_head_hexsha": "3d2512775cb7e999e8b0a142ea72ec3c9fedcc02", "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": 21.9375, "max_line_length": 61, "alphanum_fraction": 0.8062678063, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.4871755522428329}}
{"text": "\n-- | Internal utilities.\n\nmodule Math.Probably.Utils where\n\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport qualified Data.Vector.Storable as V\nimport Math.Probably.Types\nimport Numeric.LinearAlgebra\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal\n\nlookupDefault  :: Ord k => a -> k -> Map k a -> a\nlookupDefault d k m = fromMaybe d (Map.lookup k m)\n\n-- | A spherical Gaussian distribution.\nsphereGauss :: ContinuousParams -> ContinuousParams -> Double -> Double\nsphereGauss xs m sd = product $ zipWith density normalDists xsAsList where\n  xsAsList    = toList xs\n  meanAsList  = toList m\n  normalDists = map (`normalDistr` sd) meanAsList\n\n-- | Scalar-vector multiplication.\n(.*) :: Double -> ContinuousParams -> ContinuousParams\nz .* xs = mapVector (* z) xs\n\n-- | Scalar-vector subtraction.\n(.-) :: ContinuousParams -> ContinuousParams -> ContinuousParams\nxs .- ys = zipVectorWith (-) xs ys\n\n-- | Scalar-vector addition.\n(.+) :: ContinuousParams -> ContinuousParams -> ContinuousParams\nxs .+ ys = zipVectorWith (+) xs ys\n\n-- | The leapfrog integrator.\nleapfrog :: Gradient -> Particle -> Double -> Particle\nleapfrog glTarget (q, r) e = (qf, rf) where \n  rm = adjustMomentum glTarget e (q, r)\n  qf = adjustPosition e (rm, q)\n  rf = adjustMomentum glTarget e (qf, rm)\n\n-- | Adjust momentum according to a half-leapfrog step.\nadjustMomentum :: Gradient -> Double -> Particle -> ContinuousParams\nadjustMomentum glTarget e (t, r) = r .+ ((e / 2) .* glTarget t)\n\n-- | Adjust position according to a half-leapfrog step.\nadjustPosition :: Double -> Particle -> ContinuousParams\nadjustPosition e (r, t) = t .+ (e .* r)\n\n-- | A target augmented by momentum auxilliary variables.\nauxilliaryTarget :: (ContinuousParams -> Double) -> Particle -> Double\nauxilliaryTarget lTarget (t, r) =\n  lTarget t - 0.5 * innerProduct r r\n\ninnerProduct :: ContinuousParams -> ContinuousParams -> Double\ninnerProduct xs ys = V.sum $ V.zipWith (*) xs ys\n\nindicate :: Integral a => Bool -> a\nindicate True  = 1\nindicate False = 0\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\n\n", "meta": {"hexsha": "67e84bbc1338f378e42ccd631ba4911c3a1d1452", "size": 2110, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Probably/Utils.hs", "max_stars_repo_name": "glutamate/probably-baysig", "max_stars_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-02-12T05:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:37.000Z", "max_issues_repo_path": "src/Math/Probably/Utils.hs", "max_issues_repo_name": "silky/probably-baysig", "max_issues_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/Probably/Utils.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 31.4925373134, "max_line_length": 74, "alphanum_fraction": 0.7090047393, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.48714332639668684}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule Legacy.QuantumCircuit where\n\nimport Data.Complex\nimport Data.Either\nimport Data.List\nimport Data.Function\nimport System.Random\nimport Control.Monad.IO.Class\n\nimport Helper\n\nimport Tensor\n\n\n\n-- applyGate :: (QuantumRegister q Num RealFloat, RealFloat a) => q (Complex a) -- ^ Gate tensor\n--   -> Int -- ^ Index\n--   -> q (Complex a) -- ^ State vector\n--   -> Either String (q (Complex a))\n-- applyGate x i y\n--     | not (isSquare x) = Left \"Invalid Gate Tensor\"\n--     | not (isSquare y) = Left \"Invalid Statevector\"\n--     | i < 0 || i >= rank y = Left \"Index out of bounds\"\n--     | otherwise = Right $ norm $ build (rank y) [(i, x)] pauliId * y\n\n\n-- applyGateAll :: (QuantumRegister q Num RealFloat, RealFloat a) => q (Complex a) -> q (Complex a) -> Either String (q (Complex a))\n-- applyGateAll x y\n--     | not (isSquare x) = Left \"Invalid Gate Tensor\"\n--     | not (isSquare y) = Left \"Invalid Statevector\"\n--     | otherwise = Right $ norm $ build (rank y) [] x * y\n\n\n-- applyControl :: (QuantumRegister q, RealFloat a) => q (Complex a) -- ^ Gate tensor\n--   -> Int -- ^ Control qubit index\n--   -> Int -- ^ Apply qubit index\n--   -> q (Complex a) -- ^ State vector\n--   -> Either String (q (Complex a))\n-- applyControl x ctl i y\n--     | not (isSquare x) = Left \"Invalid gate tensor\"\n--     | not (isSquare y) = Left \"Invalid state vector\"\n--     | i < 0 || i >= rank y = Left \"Application qubit index out of bounds\"\n--     | ctl < 0 || ctl >= rank y = Left \"Control qubit index out of bounds\"\n--     | ctl == i = Left \"Control and application qubit cannot be the same\"\n--     | otherwise = Right $ norm $ (build (rank y) [(ctl, mask0)] pauliId\n--         + build (rank y) (sortBy (compare `on` fst) [(ctl, mask1), (i, x)]) pauliId) * y\n\n-- collapse :: (RealFloat a, QuantumRegister q) => Int -- ^ Index of the qubit\n--         -> Bool -- ^ Collapsed State\n--         -> q (Complex a) -- ^ Qubits to collapse\n--         -> Either String (q (Complex a)) -- ^ Resulting Tensor\n-- collapse i state q\n--     | i < 0 || i >= rank q = Left \"Index out of bounds\"\n--     | not (isSquare q) = Left \"Invalid state vector\"\n--     | state = norm <$> applyGate mask1 i q\n--     | otherwise = norm <$> applyGate mask0 i q\n\n\n-- measure i v = do\n--     a <- randomRIO (0.0, 1.0)\n--     if a < fst p then\n--         return $ fmap (\\x -> (False, x)) (collapse i False =<< v)\n--     else\n--         return $ fmap (\\x -> (True, x)) (collapse i True =<< v)\n--     where\n--         prob = getProb i =<< v\n--         p = fromRight (0.0, 0.0) prob", "meta": {"hexsha": "f1019ee1d41a8a50dd895aaf15a4025b990e2578", "size": 2572, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Legacy/QuantumCircuit.hs", "max_stars_repo_name": "w41g87/Qaskell", "max_stars_repo_head_hexsha": "40bfa73d1e4b6ab59921129cd84190d7440eba7c", "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/Legacy/QuantumCircuit.hs", "max_issues_repo_name": "w41g87/Qaskell", "max_issues_repo_head_hexsha": "40bfa73d1e4b6ab59921129cd84190d7440eba7c", "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/Legacy/QuantumCircuit.hs", "max_forks_repo_name": "w41g87/Qaskell", "max_forks_repo_head_hexsha": "40bfa73d1e4b6ab59921129cd84190d7440eba7c", "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.8235294118, "max_line_length": 132, "alphanum_fraction": 0.5808709176, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.486911078183637}}
{"text": "{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module    : Statistics.Distribution.Gamma\n-- Copyright : (c) 2009, 2011 Bryan O'Sullivan\n-- License   : BSD3\n--\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : portable\n--\n-- The gamma distribution.  This is a continuous probability\n-- distribution with two parameters, /k/ and &#977;. If /k/ is\n-- integral, the distribution represents the sum of /k/ independent\n-- exponentially distributed random variables, each of which has a\n-- mean of &#977;.\n\nmodule Statistics.Distribution.Gamma\n    (\n      GammaDistribution\n    -- * Constructors\n    , gammaDistr\n    , improperGammaDistr\n    -- * Accessors\n    , gdShape\n    , gdScale\n    ) where\n\nimport Data.Aeson (FromJSON, ToJSON)\nimport Control.Applicative ((<$>), (<*>))\nimport Data.Binary (Binary)\nimport Data.Binary (put, get)\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.MathFunctions.Constants (m_pos_inf, m_NaN, m_neg_inf)\nimport Numeric.SpecFunctions (incompleteGamma, invIncompleteGamma, logGamma, digamma)\nimport Statistics.Distribution.Poisson.Internal as Poisson\nimport qualified Statistics.Distribution as D\nimport qualified System.Random.MWC.Distributions as MWC\n\n-- | The gamma distribution.\ndata GammaDistribution = GD {\n      gdShape :: {-# UNPACK #-} !Double -- ^ Shape parameter, /k/.\n    , gdScale :: {-# UNPACK #-} !Double -- ^ Scale parameter, &#977;.\n    } deriving (Eq, Read, Show, Typeable, Data, Generic)\n\ninstance FromJSON GammaDistribution\ninstance ToJSON GammaDistribution\n\ninstance Binary GammaDistribution where\n    put (GD x y) = put x >> put y\n    get = GD <$> get <*> get\n\n-- | Create gamma distribution. Both shape and scale parameters must\n-- be positive.\ngammaDistr :: Double            -- ^ Shape parameter. /k/\n           -> Double            -- ^ Scale parameter, &#977;.\n           -> GammaDistribution\ngammaDistr k theta\n  | k     <= 0 = error $ msg ++ \"shape must be positive. Got \" ++ show k\n  | theta <= 0 = error $ msg ++ \"scale must be positive. Got \" ++ show theta\n  | otherwise  = improperGammaDistr k theta\n    where msg = \"Statistics.Distribution.Gamma.gammaDistr: \"\n\n-- | Create gamma distribution. This constructor do not check whether\n--   parameters are valid\nimproperGammaDistr :: Double            -- ^ Shape parameter. /k/\n                   -> Double            -- ^ Scale parameter, &#977;.\n                   -> GammaDistribution\nimproperGammaDistr = GD\n\ninstance D.Distribution GammaDistribution where\n    cumulative = cumulative\n\ninstance D.ContDistr GammaDistribution where\n    density    = density\n    logDensity (GD k theta) x\n      | x <= 0    = m_neg_inf\n      | otherwise = log x * (k - 1) - (x / theta) - logGamma k - log theta * k\n    quantile   = quantile\n\ninstance D.Variance GammaDistribution where\n    variance (GD a l) = a * l * l\n\ninstance D.Mean GammaDistribution where\n    mean (GD a l) = a * l\n\ninstance D.MaybeMean GammaDistribution where\n    maybeMean = Just . D.mean\n\ninstance D.MaybeVariance GammaDistribution where\n    maybeStdDev   = Just . D.stdDev\n    maybeVariance = Just . D.variance\n\ninstance D.MaybeEntropy GammaDistribution where\n  maybeEntropy (GD a l)\n    | a > 0 && l > 0 =\n      Just $\n      a\n      + log l\n      + logGamma a\n      + (1-a) * digamma a\n    | otherwise = Nothing\n\ninstance D.ContGen GammaDistribution where\n    genContVar (GD a l) = MWC.gamma a l\n\n\ndensity :: GammaDistribution -> Double -> Double\ndensity (GD a l) x\n  | a < 0 || l <= 0   = m_NaN\n  | x <= 0            = 0\n  | a == 0            = if x == 0 then m_pos_inf else 0\n  | x == 0            = if a < 1 then m_pos_inf else if a > 1 then 0 else 1/l\n  | a < 1             = Poisson.probability (x/l) a * a / x\n  | otherwise         = Poisson.probability (x/l) (a-1) / l\n\ncumulative :: GammaDistribution -> Double -> Double\ncumulative (GD k l) x\n  | x <= 0    = 0\n  | otherwise = incompleteGamma k (x/l)\n\nquantile :: GammaDistribution -> Double -> Double\nquantile (GD k l) p\n  | p == 0         = 0\n  | p == 1         = 1/0\n  | p > 0 && p < 1 = l * invIncompleteGamma k p\n  | otherwise      =\n    error $ \"Statistics.Distribution.Gamma.quantile: p must be in [0,1] range. Got: \"++show p\n", "meta": {"hexsha": "d2cee28a4a037ecd9ba1ec78ebaa6f354f1f9ece", "size": 4231, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Gamma.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "Statistics/Distribution/Gamma.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Distribution/Gamma.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7984496124, "max_line_length": 93, "alphanum_fraction": 0.6428740251, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4865856168248099}}
{"text": "{-# LANGUAGE NoImplicitPrelude #-}\nmodule LinearRegression1 where\n\nimport Protolude\nimport Data.Vector as V\nimport Numeric.LinearAlgebra as H\n", "meta": {"hexsha": "345a56c80e954762118760eabbd44b27e78f1774", "size": 142, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/LinearRegression1.hs", "max_stars_repo_name": "DataHaskell/data-haskell-examples", "max_stars_repo_head_hexsha": "fc0c0ef14787af577c38ce82fe051cc9b785c41b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2017-02-01T21:12:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T22:25:01.000Z", "max_issues_repo_path": "examples/LinearRegression1.hs", "max_issues_repo_name": "DataHaskell/data-haskell-examples", "max_issues_repo_head_hexsha": "fc0c0ef14787af577c38ce82fe051cc9b785c41b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-02-01T17:41:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-26T16:05:02.000Z", "max_forks_repo_path": "examples/LinearRegression1.hs", "max_forks_repo_name": "DataHaskell/data-haskell-examples", "max_forks_repo_head_hexsha": "fc0c0ef14787af577c38ce82fe051cc9b785c41b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-02-04T01:39:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:29:35.000Z", "avg_line_length": 20.2857142857, "max_line_length": 34, "alphanum_fraction": 0.8169014085, "num_tokens": 32, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48655104583354364}}
{"text": "-- {-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE DataKinds, GADTs, TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables  #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FunctionalDependencies #-}\n\nmodule HBLAS.BLAS.Level3Spec(main, spec) where\n\nimport Data.Complex\n\nimport Numerical.HBLAS.MatrixTypes as Matrix\nimport Numerical.HBLAS.BLAS.Level3 as BLAS\n\nimport Test.Hspec\n\n\nmain :: IO ()\nmain = hspec spec\n\nspec :: Spec\nspec = do\n  gemmSpec\n  hemmSpec\n  herkSpec\n  her2kSpec\n  symmSpec\n  syrkSpec\n  syr2kSpec\n  trmmSpec\n  trsmSpec\n\ngemmSpec :: Spec\ngemmSpec =\n  context \"?GEMM\" $ do\n    describe \"SGEMM\" $ do\n      it \"2x2 all 1's\" $ do\n        matmatTest1SGEMM\n    describe \"DGEMM\" $ do\n      it \"2x2 all 1's\" $ do\n        matmatTest1DGEMM Matrix.SRow\n      it \"3x2 and 5x3 all 1's\" $ do\n        matmatTest2DGEMM Matrix.SRow\n      it \"2x3^T and 5x3 all 1's\" $ do\n        matmatTest3DGEMM Matrix.SRow\n      it \"2x3 and 2x3^T all 1's\" $ do\n        matmatTest3aDGEMM Matrix.SRow\n      it \"3x2 and 3x5^T all 1's\" $ do\n        matmatTest4DGEMM Matrix.SRow\n      it \"2x3^T and 3x5^T all 1's\" $ do\n        matmatTest5DGEMM Matrix.SRow\n      it \"3x2^T and 3x2 all 1's\" $ do\n        matmatTest6DGEMM Matrix.SRow\n      it \"2x64^T and 2x64 all 1's\" $ do\n        matmatTest7DGEMM Matrix.SRow\n      it \"2x9^T and 2x9 all 1's\" $ do\n        matmatTest8DGEMM Matrix.SRow\n      it \"2x2 all 1's (column oriented)\" $ do\n        matmatTest1DGEMM Matrix.SColumn\n      it \"3x2 and 5x3 all 1's (column oriented)\" $ do\n        matmatTest2DGEMM Matrix.SColumn\n      it \"2x3^T and 5x3 all 1's (column oriented)\" $ do\n        matmatTest3DGEMM Matrix.SColumn\n      it \"2x3 and 2x3^T all 1's (column oriented)\" $ do\n        matmatTest3aDGEMM Matrix.SColumn\n      it \"3x2 and 3x5^T all 1's (column oriented)\" $ do\n        matmatTest4DGEMM Matrix.SColumn\n      it \"2x3^T and 3x5^T all 1's (column oriented)\" $ do\n        matmatTest5DGEMM Matrix.SColumn\n      it \"3x2^T and 3x2 all 1's (column oriented)\" $ do\n        matmatTest6DGEMM Matrix.SColumn\n      it \"2x64^T and 2x64 all 1's (column oriented)\" $ do\n        matmatTest7DGEMM Matrix.SColumn\n      it \"2x9^T and 2x9 all 1's (column oriented)\" $ do\n        matmatTest8DGEMM Matrix.SColumn\n    describe \"CGEMM\" $ do\n      it \"2x2 all 1's \" $ do\n        matmatTest1CGEMM\n    describe \"ZGEMM\" $ do\n      it \"2x2 all 1's \" $ do\n        matmatTest1ZGEMM\n    \n\n\nmatmatTest1SGEMM:: IO ()\nmatmatTest1SGEMM = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const (1.0 :: Float))\n    right <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const (1.0 :: Float))\n    res   <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const (0.0 :: Float))\n    BLAS.sgemm Matrix.NoTranspose Matrix.NoTranspose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` [2,2,2,2]\n\nmatmatTest1DGEMM :: Matrix.SOrientation x -> IO ()\nmatmatTest1DGEMM or = do\n    left  <- Matrix.generateMutableDenseMatrix or (2,2) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix or (2,2) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or (2,2) (const 0.0)\n    BLAS.dgemm Matrix.NoTranspose Matrix.NoTranspose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` [2.0,2.0,2.0,2.0]\n\nmatmatTest2DGEMM :: Matrix.SOrientation x -> IO ()\nmatmatTest2DGEMM or = do\n    left  <- Matrix.generateMutableDenseMatrix or (3,2) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix or (5,3) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or (5,2) (const 0.0)\n    BLAS.dgemm Matrix.NoTranspose Matrix.NoTranspose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` replicate 10 3\n\nmatmatTest3DGEMM :: Matrix.SOrientation x -> IO ()\nmatmatTest3DGEMM or = do\n    left  <- Matrix.generateMutableDenseMatrix or (2,3) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix or (5,3) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or (5,2) (const 0.0)\n    BLAS.dgemm Matrix.Transpose Matrix.NoTranspose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` replicate 10 3\n\nmatmatTest3aDGEMM :: Matrix.SOrientation x -> IO ()\nmatmatTest3aDGEMM or = do\n    left  <- Matrix.generateMutableDenseMatrix or (2,3) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix or (2,3) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or (3,3) (const 0.0)\n    BLAS.dgemm Matrix.NoTranspose Matrix.Transpose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` replicate 9 2\n\nmatmatTest4DGEMM :: Matrix.SOrientation x -> IO ()\nmatmatTest4DGEMM or = do\n    left  <- Matrix.generateMutableDenseMatrix or (3,2) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix or (3,5) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or (5,2) (const 0.0)\n    BLAS.dgemm Matrix.NoTranspose Matrix.Transpose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` replicate 10 3\n\nmatmatTest5DGEMM :: Matrix.SOrientation x -> IO ()\nmatmatTest5DGEMM or = do\n    left  <- Matrix.generateMutableDenseMatrix or  (2,3) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix or  (3,5) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or  (5,2) (const 0.0)\n    BLAS.dgemm Matrix.Transpose Matrix.Transpose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` replicate 10 3\n\nmatmatTest6DGEMM :: Matrix.SOrientation x -> IO ()\nmatmatTest6DGEMM or = do\n    left  <- Matrix.generateMutableDenseMatrix or (3,2) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix or (3,2) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or (3,3) (const 0.0)\n    BLAS.dgemm Matrix.Transpose Matrix.NoTranspose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` replicate 9 2\n\nmatmatTest7DGEMM :: Matrix.SOrientation x -> IO ()\nmatmatTest7DGEMM or = do\n    left  <- Matrix.generateMutableDenseMatrix or (2,64) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix or (2,64) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or (2,2) (const 0.0)\n    BLAS.dgemm Matrix.Transpose Matrix.NoTranspose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` replicate 4 64\n\nmatmatTest8DGEMM :: Matrix.SOrientation x -> IO ()\nmatmatTest8DGEMM or = do\n    left  <- Matrix.generateMutableDenseMatrix or (2,9) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix or (2,9) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or (2,2) (const 0.0)\n    BLAS.dgemm Matrix.Transpose Matrix.NoTranspose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` replicate 4 9\n\nmatmatTest1CGEMM:: IO ()\nmatmatTest1CGEMM = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const 0.0)\n    BLAS.cgemm Matrix.NoTranspose Matrix.NoTranspose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` [2.0,2.0,2.0,2.0]\n\nmatmatTest1ZGEMM:: IO ()\nmatmatTest1ZGEMM = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const 0.0)\n    BLAS.zgemm Matrix.NoTranspose Matrix.NoTranspose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` [2.0,2.0,2.0,2.0]\n\nhemmSpec :: Spec\nhemmSpec =\n  context \"?HEMM\" $ do\n    describe \"CHEMM\" $ do\n      it \"3x3 and 2x3 with leftside upper (row oriented)\" $ do\n        matmatTest1CHEMM\n    describe \"ZHEMM\" $ do\n      it \"3x3 and 3x2 with rightside lower (column oriented)\" $ do\n        matmatTest1ZHEMM\n\n-- [1:+0    1:+1    1:+1]   [1 1]   [3:+2    3:+2   ]\n-- [1:+(-1) 1:+0    2:+2] * [1 1] = [4:+1    4:+1   ]\n-- [1:+(-1) 2:+(-2) 1:+0]   [1 1]   [4:+(-3) 4:+(-3)]\nmatmatTest1CHEMM :: IO ()\nmatmatTest1CHEMM = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3,3) (\\(x, y) -> [1:+0, 1:+1, 1:+1, 0:+0, 1:+0, 2:+2, 0:+0, 0:+0, 1:+0] !! (x + y * 3))\n    right <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,3) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,3) (const 0.0)\n    BLAS.chemm Matrix.LeftSide Matrix.MatUpper 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` [3:+2, 3:+2, 4:+1, 4:+1, 4:+(-3), 4:+(-3)]\n\n-- [1 1 1]   [1:+0 1:+(-1) 1:+(-1)]    [3:+2 4:+1 4:+(-3)]\n-- [1 1 1] * [1:+1 1:+0    2:+(-2)]  = [3:+2 4:+1 4:+(-3)]\n--           [1:+1 2:+2    1:+0   ]\nmatmatTest1ZHEMM :: IO ()\nmatmatTest1ZHEMM = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,3) (\\(x, y) -> [1:+0, 0:+0, 0:+0, 1:+1, 1:+0, 0:+0, 1:+1, 2:+2, 1:+0] !! (x + y * 3))\n    right <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,2) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,2) (const 0.0)\n    BLAS.zhemm Matrix.RightSide Matrix.MatLower 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` [3:+2, 3:+2, 4:+1, 4:+1, 4:+(-3), 4:+(-3)]\n\nherkSpec :: Spec\nherkSpec = do\n  context \"?HERK\" $ do\n    describe \"CHERK\" $ do\n      it \"3x3 and 2x3 with upper no transpose (row oriented)\" $ do\n        matmatTest1CHERK\n    describe \"ZHERK\" $ do\n      it \"3x3 and 3x2 with lower conjtranspose (column oriented)\" $ do\n        matmatTest1ZHERK\n    \n\n-- [1 2]   [1 3 5]   [1:+0    1:+1    1:+1]   [6:+0 12:+1 18:+1]\n-- [3 4] * [2 4 6] + [1:+(-1) 1:+0    2:+2] = [0:+0 26:+0 41:+2]\n-- [5 6]             [1:+(-1) 2:+(-2) 1:+0]   [0:+0 0:+0  62:+0]\nmatmatTest1CHERK :: IO ()\nmatmatTest1CHERK = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,3) (\\(x, y) -> [1, 2, 3, 4, 5, 6] !! (x + y * 2))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3,3) (\\(x, y) -> [1:+0, 1:+1, 1:+1, 0:+0, 1:+0, 2:+2, 0:+0, 0:+0, 1:+0] !! (x + y * 3))\n    BLAS.cherk Matrix.MatUpper Matrix.NoTranspose 1.0 1.0 a c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [6:+0, 12:+1, 18:+1, 0:+0, 26:+0, 41:+2, 0:+0, 0:+0, 62:+0]\n\n-- [1:-1 2]   [1:+1 3 5]   [1:+0 1:+(-1) 1:+(-1)]   [7:+0  0:+0  0:+0]\n-- [3    4] * [2    4 6] + [1:+1 1:+0    2:+(-2)] = [12:+4 26:+0 0:+0]\n-- [5    6]                [1:+1 2:+2    1:+0   ]   [18:+6 41:+2 62:+0]\nmatmatTest1ZHERK :: IO ()\nmatmatTest1ZHERK = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,2) (\\(x, y) -> [1:+1, 3, 5, 2, 4, 6] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,3) (\\(x, y) -> [1:+0, 0:+0, 0:+0, 1:+1, 1:+0, 0:+0, 1:+1, 2:+2, 1:+0] !! (x + y * 3))\n    BLAS.zherk Matrix.MatLower Matrix.ConjTranspose 1.0 1.0 a c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [7:+0, 12:+4, 18:+6, 0:+0, 26:+0, 41:+2, 0:+0, 0:+0, 62:+0]\n\nher2kSpec :: Spec\nher2kSpec = \n  context \"?HER2K\" $ do\n    describe \"CHER2K\" $ do\n      it \"3x3 and 2x3 with upper no transpose (row oriented)\" $ do\n        matmatTest1CHER2K\n    describe \"ZHER2k\" $ do\n      it \"3x3 and 3x2 with lower conjtranspose (column oriented)\" $ do\n        matmatTest1ZHER2K\n\n-- [1 2]   [1 3 5]       [1:+0    1:+1    1:+1]   [11:+0 23:+1  35:+1]\n-- [3 4] * [2 4 6] * 2 + [1:+(-1) 1:+0    2:+2] = [0:+0  51:+0  80:+2]\n-- [5 6]                 [1:+(-1) 2:+(-2) 1:+0]   [0:+0  0:+0  123:+0]\nmatmatTest1CHER2K :: IO ()\nmatmatTest1CHER2K = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,3) (\\(x, y) -> [1, 2, 3, 4, 5, 6] !! (x + y * 2))\n    b <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,3) (\\(x, y) -> [1, 2, 3, 4, 5, 6] !! (x + y * 2))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3,3) (\\(x, y) -> [1:+0, 1:+1, 1:+1, 0:+0, 1:+0, 2:+2, 0:+0, 0:+0, 1:+0] !! (x + y * 3))\n    BLAS.cher2k Matrix.MatUpper Matrix.NoTranspose 1.0 1.0 a b c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [11:+0, 23:+1, 35:+1, 0:+0, 51:+0, 80:+2, 0:+0, 0:+0, 123:+0]\n\n-- [1:-1 2]   [1:+1 3 5]       [1:+0 1:+(-1) 1:+(-1)]   [13:+0  0:+0    0:+0]\n-- [3    4] * [2    4 6] * 2 + [1:+1 1:+0    2:+(-2)] = [23:+7  51:+0   0:+0]\n-- [5    6]                    [1:+1 2:+2    1:+0   ]   [35:+11 80:+2 123:+0]\nmatmatTest1ZHER2K :: IO ()\nmatmatTest1ZHER2K = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,2) (\\(x, y) -> [1:+1, 3, 5, 2, 4, 6] !! (x + y * 3))\n    b <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,2) (\\(x, y) -> [1:+1, 3, 5, 2, 4, 6] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,3) (\\(x, y) -> [1:+0, 0:+0, 0:+0, 1:+1, 1:+0, 0:+0, 1:+1, 2:+2, 1:+0] !! (x + y * 3))\n    BLAS.zher2k Matrix.MatLower Matrix.ConjTranspose 1.0 1.0 a b c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [13:+0, 23:+7, 35:+11, 0:+0, 51:+0, 80:+2, 0:+0, 0:+0, 123:+0]\n\nsymmSpec :: Spec\nsymmSpec = \n  context \"?SYMM\" $ do\n    describe \"SSYMM\" $ do\n      it \"2x2 upper all 1's\" $ do\n        matmatTest1SSYMM\n    describe \"DSYMM\" $ do\n      it \"2x2 upper all 1's\" $ do\n        matmatTest1DSYMM Matrix.SRow Matrix.MatUpper\n      it \"2x2 and 3x2 upper all 1's\" $ do\n        matmatTest2DSYMM Matrix.SRow Matrix.MatUpper\n      it \"2x5 and 2x2 upper all 1's\" $ do\n        matmatTest3DSYMM Matrix.SRow Matrix.MatUpper\n      it \"2x2 lower all 1's\" $ do\n        matmatTest1DSYMM Matrix.SRow Matrix.MatLower\n      it \"2x2 and 3x2 lower all 1's\" $ do\n        matmatTest2DSYMM Matrix.SRow Matrix.MatLower\n      it \"2x5 and 2x2 lower all 1's\" $ do\n        matmatTest3DSYMM Matrix.SRow Matrix.MatLower\n      it \"2x2 upper all 1's (column oriented)\" $ do\n        matmatTest1DSYMM Matrix.SColumn Matrix.MatUpper\n      it \"2x2 and 3x2 upper all 1's (column oriented)\" $ do\n        matmatTest2DSYMM Matrix.SColumn Matrix.MatUpper\n      it \"2x5 and 2x2 upper all 1's (column oriented)\" $ do\n        matmatTest3DSYMM Matrix.SColumn Matrix.MatUpper\n      it \"2x2 lower all 1's (column oriented)\" $ do\n        matmatTest1DSYMM Matrix.SColumn Matrix.MatLower\n      it \"2x2 and 3x2 lower all 1's (column oriented)\" $ do\n        matmatTest2DSYMM Matrix.SColumn Matrix.MatLower\n      it \"2x5 and 2x2 lower all 1's (column oriented)\" $ do\n        matmatTest3DSYMM Matrix.SColumn Matrix.MatLower\n    describe \"CSYMM\" $ do\n      it \"2x2 all 1's\" $ do\n        matmatTest1CSYMM\n    describe \"ZSYMM\" $ do\n      it \"2x2 all 1's\" $ do\n        matmatTest1ZSYMM\n\n\nmatmatTest1SSYMM:: IO ()\nmatmatTest1SSYMM = do\n    left  <- Matrix.generateMutableUpperTriangular (Matrix.SRow)  (2,2) (const (1.0 :: Float))\n    right <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const (1.0 :: Float))\n    res   <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const (0.0 :: Float))\n    BLAS.ssymm Matrix.LeftSide Matrix.MatUpper 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` [2,2,2,2]\n\nmatmatTest1DSYMM :: Matrix.SOrientation x -> Matrix.MatUpLo -> IO ()\nmatmatTest1DSYMM or uplo = do\n    left  <- (if uplo == Matrix.MatUpper then Matrix.generateMutableUpperTriangular or (2,2) (const 1.0)\n                else Matrix.generateMutableLowerTriangular or (2,2) (const 1.0))\n    right <- Matrix.generateMutableDenseMatrix or (2,2) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or (2,2) (const 0.0)\n    BLAS.dsymm Matrix.LeftSide uplo 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` [2.0,2.0,2.0,2.0]\n\nmatmatTest2DSYMM :: Matrix.SOrientation x -> Matrix.MatUpLo -> IO ()\nmatmatTest2DSYMM or uplo = do\n    left  <- (if uplo == Matrix.MatUpper then Matrix.generateMutableUpperTriangular or (2,2) (const 1.0)\n                else Matrix.generateMutableLowerTriangular or (2,2) (const 1.0))\n    right <- Matrix.generateMutableDenseMatrix or (3,2) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or (3,2) (const 0.0)\n    BLAS.dsymm Matrix.LeftSide uplo 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` [2.0,2.0,2.0,2.0,2.0,2.0]\n\nmatmatTest3DSYMM :: Matrix.SOrientation x -> Matrix.MatUpLo -> IO ()\nmatmatTest3DSYMM or uplo = do\n    left  <- (if uplo == Matrix.MatUpper then Matrix.generateMutableUpperTriangular or (2,2) (const 1.0)\n                else Matrix.generateMutableLowerTriangular or (2,2) (const 1.0))\n    right <- Matrix.generateMutableDenseMatrix or (2,5) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix or (2,5) (const 0.0)\n    BLAS.dsymm Matrix.RightSide uplo 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` replicate 10 2\n\nmatmatTest1CSYMM:: IO ()\nmatmatTest1CSYMM = do\n    left  <- Matrix.generateMutableUpperTriangular (Matrix.SRow)  (2,2) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const 0.0)\n    BLAS.csymm Matrix.LeftSide Matrix.MatUpper 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` [2.0,2.0,2.0,2.0]\n\nmatmatTest1ZSYMM:: IO ()\nmatmatTest1ZSYMM = do\n    left  <- Matrix.generateMutableUpperTriangular (Matrix.SRow)  (2,2) (const 1.0)\n    right <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const 1.0)\n    res   <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (const 0.0)\n    BLAS.zsymm Matrix.LeftSide Matrix.MatUpper 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n    resList `shouldBe` [2.0,2.0,2.0,2.0]\n\nsyrkSpec :: Spec\nsyrkSpec =\n  context \"?SYRK\" $ do\n    describe \"SSYRK\" $ do\n      it \"3x3 and 2x3 with upper no transpose (row oriented)\" $ do\n        matmatTest1SSYRK\n    describe \"DSYRK\" $ do\n      it \"3x3 and 3x2 with lower transpose (column oriented)\" $ do\n        matmatTest1DSYRK\n    describe \"CSYRK\" $ do\n      it \"3x3 and 2x3 with upper no transpose (row oriented)\" $ do\n        matmatTest1CSYRK\n    describe \"ZSYRK\" $ do\n      it \"3x3 and 3x2 with lower transpose (column oriented)\" $ do\n        matmatTest1ZSYRK\n    \n-- [1 2]   [1 3 5]   [1 1 1]   [6 12 18]\n-- [3 4] * [2 4 6] + [1 1 2] = [0 26 41]\n-- [5 6]             [1 2 1]   [0 0  62]\nmatmatTest1SSYRK :: IO ()\nmatmatTest1SSYRK = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,3) (\\(x, y) -> [1, 2, 3, 4, 5, 6] !! (x + y * 2))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3,3) (\\(x, y) -> [1, 1, 1, 0, 1, 2, 0, 0, 1] !! (x + y * 3))\n    BLAS.ssyrk Matrix.MatUpper Matrix.NoTranspose 1.0 1.0 a c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [6, 12, 18, 0, 26, 41, 0, 0, 62]\n\n-- [1 2]   [1 3 5]   [1 1 1]   [6  0  0 ]\n-- [3 4] * [2 4 6] + [1 1 2] = [12 26 0 ]\n-- [5 6]             [1 2 1]   [18 41 62]\nmatmatTest1DSYRK :: IO ()\nmatmatTest1DSYRK = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,2) (\\(x, y) -> [1, 3, 5, 2, 4, 6] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,3) (\\(x, y) -> [1, 0, 0, 1, 1, 0, 1, 2, 1] !! (x + y * 3))\n    BLAS.dsyrk Matrix.MatLower Matrix.Transpose 1.0 1.0 a c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [6, 12, 18, 0, 26, 41, 0, 0, 62]\n\n-- [1 2]   [1 3 5]   [1:+0 1:+1 1:+1]   [6:+0 12:+1 18:+1]\n-- [3 4] * [2 4 6] + [1:+1 1:+0 2:+2] = [0:+0 26:+0 41:+2]\n-- [5 6]             [1:+1 2:+2 1:+0]   [0:+0 0:+0  62:+0]\nmatmatTest1CSYRK :: IO ()\nmatmatTest1CSYRK = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,3) (\\(x, y) -> [1, 2, 3, 4, 5, 6] !! (x + y * 2))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3,3) (\\(x, y) -> [1:+0, 1:+1, 1:+1, 0:+0, 1:+0, 2:+2, 0:+0, 0:+0, 1:+0] !! (x + y * 3))\n    BLAS.csyrk Matrix.MatUpper Matrix.NoTranspose 1.0 1.0 a c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [6:+0, 12:+1, 18:+1, 0:+0, 26:+0, 41:+2, 0:+0, 0:+0, 62:+0]\n\n-- [1:+1 2]   [1:+1 3 5]   [1:+0 1:+1 1:+1]   [6:+0  0:+0  0:+0]\n-- [3    4] * [2    4 6] + [1:+1 1:+0 2:+2] = [12:+1 26:+0 0:+0]\n-- [5    6]                [1:+1 2:+2 1:+0]   [18:+1 41:+2 62:+0]\nmatmatTest1ZSYRK :: IO ()\nmatmatTest1ZSYRK = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,2) (\\(x, y) -> [1:+1, 3, 5, 2, 4, 6] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,3) (\\(x, y) -> [1:+0, 0:+0, 0:+0, 1:+1, 1:+0, 0:+0, 1:+1, 2:+2, 1:+0] !! (x + y * 3))\n    BLAS.zsyrk Matrix.MatLower Matrix.Transpose 1.0 1.0 a c -- TODO: Matrix.ConjTranspose is invalid to pass to cblas_zsyrk\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [5:+2, 12:+4, 18:+6, 0:+0, 26:+0, 41:+2, 0:+0, 0:+0, 62:+0]\n\n\nsyr2kSpec :: Spec\nsyr2kSpec =\n  context \"?SYR2K\" $ do\n    describe \"SSYR2K\" $ do\n      it \"3x3 and 2x3 with upper no transpose (row oriented)\" $ do\n        matmatTest1SSYR2K\n    describe \"DSYR2K\" $ do\n      it \"3x3 and 3x2 with lower transpose (column oriented)\" $ do\n        matmatTest1DSYR2K\n    describe \"CSYR2K\" $ do\n      it \"3x3 and 2x3 with upper no transpose (row oriented)\" $ do\n        matmatTest1CSYR2K\n    describe \"ZSYR2K\" $ do\n      it \"3x3 and 3x2 with lower conjtranspose (column oriented)\" $ do\n        matmatTest1ZSYR2K\n\n\n-- [1 2]   [1 3 5]       [1 1 1]   [11 23  35]\n-- [3 4] * [2 4 6] * 2 + [1 1 2] = [0  51  80]\n-- [5 6]                 [1 2 1]   [0  0  123]\nmatmatTest1SSYR2K :: IO ()\nmatmatTest1SSYR2K = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,3) (\\(x, y) -> [1, 2, 3, 4, 5, 6] !! (x + y * 2))\n    b <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,3) (\\(x, y) -> [1, 2, 3, 4, 5, 6] !! (x + y * 2))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3,3) (\\(x, y) -> [1, 1, 1, 0, 1, 2, 0, 0, 1] !! (x + y * 3))\n    BLAS.ssyr2k Matrix.MatUpper Matrix.NoTranspose 1.0 1.0 a b c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [11, 23, 35, 0, 51, 80, 0, 0, 123]\n\n-- [1 2]   [1 3 5]       [1 1 1]   [11 0  0  ]\n-- [3 4] * [2 4 6] * 2 + [1 1 2] = [23 51 0  ]\n-- [5 6]                 [1 2 1]   [35 80 123]\nmatmatTest1DSYR2K :: IO ()\nmatmatTest1DSYR2K = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,2) (\\(x, y) -> [1, 3, 5, 2, 4, 6] !! (x + y * 3))\n    b <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,2) (\\(x, y) -> [1, 3, 5, 2, 4, 6] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,3) (\\(x, y) -> [1, 0, 0, 1, 1, 0, 1, 2, 1] !! (x + y * 3))\n    BLAS.dsyr2k Matrix.MatLower Matrix.Transpose 1.0 1.0 a b c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [11, 23, 35, 0, 51, 80, 0, 0, 123]\n\n-- [1 2]   [1 3 5]       [1:+0 1:+1 1:+1]   [11:+0 23:+1 35:+1 ]\n-- [3 4] * [2 4 6] * 2 + [1:+1 1:+0 2:+2] = [0:+0  51:+0 80:+2 ]\n-- [5 6]                 [1:+1 2:+2 1:+0]   [0:+0  0:+0  123:+0]\nmatmatTest1CSYR2K :: IO ()\nmatmatTest1CSYR2K = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,3) (\\(x, y) -> [1, 2, 3, 4, 5, 6] !! (x + y * 2))\n    b <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,3) (\\(x, y) -> [1, 2, 3, 4, 5, 6] !! (x + y * 2))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3,3) (\\(x, y) -> [1:+0, 1:+1, 1:+1, 0:+0, 1:+0, 2:+2, 0:+0, 0:+0, 1:+0] !! (x + y * 3))\n    BLAS.csyr2k Matrix.MatUpper Matrix.NoTranspose 1.0 1.0 a b c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [11:+0, 23:+1, 35:+1, 0:+0, 51:+0, 80:+2, 0:+0, 0:+0, 123:+0]\n\n-- [1:+1 2]   [1:+1 3 5]       [1:+0 1:+1 1:+1]   [9:+4   0:+0  0:+0  ]\n-- [3    4] * [2    4 6] * 2 + [1:+1 1:+0 2:+2] = [23:+7  51:+0 0:+0  ]\n-- [5    6]                    [1:+1 2:+2 1:+0]   [35:+11 80:+2 123:+0]\nmatmatTest1ZSYR2K :: IO ()\nmatmatTest1ZSYR2K = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,2) (\\(x, y) -> [1:+1, 3, 5, 2, 4, 6] !! (x + y * 3))\n    b <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,2) (\\(x, y) -> [1:+1, 3, 5, 2, 4, 6] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3,3) (\\(x, y) -> [1:+0, 0:+0, 0:+0, 1:+1, 1:+0, 0:+0, 1:+1, 2:+2, 1:+0] !! (x + y * 3))\n    BLAS.zsyr2k Matrix.MatLower Matrix.Transpose 1.0 1.0 a b c -- TODO: Matrix.ConjTranspose is invalid to pass to cblas_zsyr2k\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [9:+4, 23:+7, 35:+11, 0:+0, 51:+0, 80:+2, 0:+0, 0:+0, 123:+0]\n\ntrmmSpec :: Spec\ntrmmSpec =\n  context \"?TRMM\" $ do\n    describe \"STRMM\" $ do\n      it \"3x3 and 2x3 with upper no transpose (row oriented)\" $ do\n        matmatTest1STRMM\n    describe \"DTRMM\" $ do\n      it \"3x3 and 3x2 with lower transpose (column oriented)\" $ do\n        matmatTest1DTRMM\n    describe \"CTRMM\" $ do\n      it \"3x3 and 2x3 with upper no transpose (row oriented)\" $ do\n        matmatTest1CTRMM\n    describe \"ZTRMM\" $ do\n      it \"3x3 and 3x2 with lower conjtranspose (column oriented)\" $ do\n        matmatTest1ZTRMM\n\n-- [1 1 1]   [1 4]   [6 15]\n-- [0 1 2] * [2 5] = [8 17]\n-- [0 0 1]   [3 6]   [3 6 ]\nmatmatTest1STRMM :: IO ()\nmatmatTest1STRMM = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3, 3) (\\(x, y) -> [1, 1, 1, 0, 1, 2, 0, 0, 1] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2, 3) (\\(x, y) -> [1, 4, 2, 5, 3, 6] !! (x + y * 2))\n    BLAS.strmm Matrix.LeftSide Matrix.MatUpper Matrix.NoTranspose Matrix.MatUnit 1.0 a c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [6, 15, 8, 17, 3, 6]\n\n-- [1 2 3]   [2 1 1]   [2 5  11]\n-- [4 5 6] * [0 2 2] = [8 14 26]\n--           [0 0 2]\nmatmatTest1DTRMM :: IO ()\nmatmatTest1DTRMM = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3, 3) (\\(x, y) -> [2, 0, 0, 1, 2, 0, 1, 2, 2] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3, 2) (\\(x, y) -> [1, 2, 3, 4, 5, 6] !! (x + y * 3))\n    BLAS.dtrmm Matrix.RightSide Matrix.MatLower Matrix.Transpose Matrix.MatNonUnit 1.0 a c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [2, 8, 5, 14, 11, 26]\n\n-- [1:+0 1:+1 1:+1]   [1 2]   [9:+8   12:+10]\n-- [0:+0 1:+0 2:+2] * [3 4] = [13:+10 16:+12]\n-- [0:+0 0:+0 1:+0]   [5 6]   [5:+0   6:+0  ]\nmatmatTest1CTRMM :: IO ()\nmatmatTest1CTRMM = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3, 3) (\\(x, y) -> [1:+0, 1:+1, 1:+1, 0:+0, 1:+0, 2:+2, 0:+0, 0:+0, 1:+0] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2, 3) (\\(x, y) -> [1, 2, 3, 4, 5, 6] !! (x + y * 2))\n    BLAS.ctrmm Matrix.LeftSide Matrix.MatUpper Matrix.NoTranspose Matrix.MatUnit 1.0 a c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [9:+8, 12:+10, 13:+10, 16:+12, 5:+0, 6:+0]\n\n-- [1:+1 3 5]   [1:+0 1:+1 1:+1]   [1:+1 3:+2 11:+8 ]\n-- [2    4 6] + [0:+0 1:+0 2:+2] = [2:+0 6:+2 16:+10]\n--              [0:+0 0:+0 1:+0]\nmatmatTest1ZTRMM :: IO ()\nmatmatTest1ZTRMM = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3, 3) (\\(x, y) -> [1:+0, 0:+0, 0:+0, 1:+(-1), 1:+0, 0:+0, 1:+(-1), 2:+(-2), 1:+0] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3, 2) (\\(x, y) -> [1:+1, 3, 5, 2, 4, 6] !! (x + y * 3))\n    BLAS.ztrmm Matrix.RightSide Matrix.MatLower Matrix.ConjTranspose Matrix.MatNonUnit 1.0 a c -- TODO: Matrix.ConjTranspose is invalid to pass to cblas_zsyr2k\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [1:+1, 2:+0, 3:+2, 6:+2, 11:+8, 16:+10]\n\ntrsmSpec :: Spec\ntrsmSpec =\n  context \"?TRSM\" $ do\n    describe \"STRSM\" $ do\n      it \"3x3 and 2x3 with upper no transpose (row oriented)\" $ do\n        matmatTest1STRSM\n    describe \"DTRSM\" $ do\n      it \"3x3 and 3x2 with lower transpose (column oriented)\" $ do\n        matmatTest1DTRSM\n    describe \"CTRSM\" $ do\n      it \"3x3 and 2x3 with upper no transpose (row oriented)\" $ do\n        matmatTest1CTRSM\n    describe \"ZTRSM\" $ do\n      it \"3x3 and 3x2 with lower conjtranspose (column oriented)\" $ do\n        matmatTest1ZTRSM\n\n-- [1 1 1]   [1 4]   [6 15]\n-- [0 1 2] * [2 5] = [8 17]\n-- [0 0 1]   [3 6]   [3 6 ]\nmatmatTest1STRSM :: IO ()\nmatmatTest1STRSM = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3, 3) (\\(x, y) -> [1, 1, 1, 0, 1, 2, 0, 0, 1] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2, 3) (\\(x, y) -> [6, 15, 8, 17, 3, 6] !! (x + y * 2))\n    BLAS.strsm Matrix.LeftSide Matrix.MatUpper Matrix.NoTranspose Matrix.MatUnit 1.0 a c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [1, 4, 2, 5, 3, 6]\n\n-- [1 2 3]   [2 1 1]   [2 5  11]\n-- [4 5 6] * [0 2 2] = [8 14 26]\n--           [0 0 2]\nmatmatTest1DTRSM :: IO ()\nmatmatTest1DTRSM = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3, 3) (\\(x, y) -> [2, 0, 0, 1, 2, 0, 1, 2, 2] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3, 2) (\\(x, y) -> [2, 5, 11, 8, 14, 26] !! (x + y * 3))\n    BLAS.dtrsm Matrix.RightSide Matrix.MatLower Matrix.Transpose Matrix.MatNonUnit 1.0 a c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [1, 4, 2, 5, 3, 6]\n\n-- [1:+0 1:+1 1:+1]   [1 2]   [9:+8   12:+10]\n-- [0:+0 1:+0 2:+2] * [3 4] = [13:+10 16:+12]\n-- [0:+0 0:+0 1:+0]   [5 6]   [5:+0   6:+0  ]\nmatmatTest1CTRSM :: IO ()\nmatmatTest1CTRSM = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3, 3) (\\(x, y) -> [1:+0, 1:+1, 1:+1, 0:+0, 1:+0, 2:+2, 0:+0, 0:+0, 1:+0] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2, 3) (\\(x, y) -> [9:+8, 12:+10, 13:+10, 16:+12, 5:+0, 6:+0] !! (x + y * 2))\n    BLAS.ctrsm Matrix.LeftSide Matrix.MatUpper Matrix.NoTranspose Matrix.MatUnit 1.0 a c\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [1, 2, 3, 4, 5, 6]\n\n-- [1:+1 3 5]   [1:+0 1:+1 1:+1]   [1:+1 3:+2 11:+8 ]\n-- [2    4 6] + [0:+0 1:+0 2:+2] = [2:+0 6:+2 16:+10]\n--              [0:+0 0:+0 1:+0]\nmatmatTest1ZTRSM :: IO ()\nmatmatTest1ZTRSM = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3, 3) (\\(x, y) -> [1:+0, 0:+0, 0:+0, 1:+(-1), 1:+0, 0:+0, 1:+(-1), 2:+(-2), 1:+0] !! (x + y * 3))\n    c <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3, 2) (\\(x, y) -> [1:+1, 3:+2, 11:+8, 2:+0, 6:+2, 16:+10] !! (x + y * 3))\n    BLAS.ztrsm Matrix.RightSide Matrix.MatLower Matrix.ConjTranspose Matrix.MatNonUnit 1.0 a c -- TODO: Matrix.ConjTranspose is invalid to pass to cblas_zsyr2k\n    resList <- Matrix.mutableVectorToList $ _bufferDenMutMat c\n    resList `shouldBe` [1:+1, 2, 3, 4, 5, 6]\n", "meta": {"hexsha": "a2379a6062bde7fc810c07d54a946061ec7f8434", "size": 31283, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/HBLAS/BLAS/Level3Spec.hs", "max_stars_repo_name": "schnecki/hblas", "max_stars_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-05-03T23:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-17T22:58:54.000Z", "max_issues_repo_path": "tests/HBLAS/BLAS/Level3Spec.hs", "max_issues_repo_name": "schnecki/hblas", "max_issues_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-01-24T13:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T22:15:09.000Z", "max_forks_repo_path": "tests/HBLAS/BLAS/Level3Spec.hs", "max_forks_repo_name": "schnecki/hblas", "max_forks_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-01-09T12:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:37:37.000Z", "avg_line_length": 49.2645669291, "max_line_length": 159, "alphanum_fraction": 0.6046734648, "num_tokens": 13060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4865510400534719}}
{"text": "-- | Interface to the FFTW routine\n--\n-- Ubuntu installation of C library:\n--\n--     sudo apt-get install libfftw3-dev\n--\n-- Basic usage:\n-- <http://www.fftw.org/fftw3_doc/Complex-One_002dDimensional-DFTs.html#Complex-One_002dDimensional-DFTs>\n--\n-- Linker flags:\n--\n--     cc file.c -lm -lfftw3\n\nmodule FFTW where\n\n\n\nimport qualified Prelude as P\n\nimport qualified Data.Complex as Complex\n\nimport qualified Test.QuickCheck as QC\nimport qualified Test.QuickCheck.Monadic as QC\n\nimport Language.Embedded.Expression (varExp)\n  -- `varExp` can be used to make named constants in expressions\n\nimport Feldspar.Run\nimport Feldspar.Data.Vector\n\nimport DFT\nimport FFT_bench (printTime_def)\n\n\n\n-- | Wrapper for the FFTW routine\n--\n-- This wrapper is mainly used for testing. It's not suitable for real code\n-- because it constructs a plan every time it's called, and it silently\n-- allocates an array for the output.\nfftw :: DManifest (Complex Double) -> Run (DManifest (Complex Double))\nfftw inp = do\n    addInclude \"<fftw3.h>\"\n    out  <- newArr (length inp)\n    plan <- newObject \"fftw_plan\" False\n    callProcAssign plan \"fftw_plan_dft_1d\"\n      [ valArg (length inp)\n      , iarrArg inp\n      , arrArg out\n      , valArg (varExp \"FFTW_FORWARD\"  :: Data Word32)\n      , valArg (varExp \"FFTW_ESTIMATE\" :: Data Word32)\n      ]\n    callProc \"fftw_execute\" [objArg plan]\n    freezeArr out\n\n\n\nalmostEq a b\n    =    Complex.magnitude d P.< 1e-7\n    P.&& Complex.phase d     P.< 1e-7\n  where\n    d = abs (a-b)\n\na ~= b = P.and $ P.zipWith almostEq a b\n\nprop_fft_dft dft' fft' = QC.monadicIO $ do\n    n   :: Int              <- QC.pick $ QC.choose (2,5)\n    inp :: [Complex Double] <- QC.pick $ QC.vector (2 P.^ n)\n    outd <- QC.run $ dft' inp\n    outf <- QC.run $ fft' inp\n    QC.assert (outd ~= outf)\n\n-- | Compare 'fftw' against 'dft'\ntestFFTW =\n    marshalledM (return . dft) $ \\dft'  ->\n    marshalledM fftw           $ \\fftw' ->\n      QC.quickCheck $ prop_fft_dft dft' fftw'\n  where\n    marshalledM = marshalled' def def\n      { externalFlagsPre  = [\"-Wno-incompatible-pointer-types\"]\n      , externalFlagsPost = [\"-lm -lfftw3\"]\n      }\n\n\n\nsizeOf_fftw_complex :: Data Length\nsizeOf_fftw_complex = 16\n  -- Checked on an x86_64 system\n\n-- | Measure the time for 100 runs of 'fftw' (excluding initialization) for\n-- arrays of the given size\nbenchmark n = do\n    addInclude \"<stdio.h>\"\n    addInclude \"<string.h>\"\n    addInclude \"<time.h>\"\n    addInclude \"<fftw3.h>\"\n\n    addDefinition printTime_def\n\n    inp  <- newObject \"fftw_complex\" True\n    out  <- newObject \"fftw_complex\" True\n    plan <- newObject \"fftw_plan\" False\n\n    callProcAssign inp \"fftw_malloc\" [valArg (n*sizeOf_fftw_complex)]\n    callProcAssign out \"fftw_malloc\" [valArg (n*sizeOf_fftw_complex)]\n    callProc \"memset\"\n      [ objArg inp\n      , valArg (0 :: Data Index)\n      , valArg (n*sizeOf_fftw_complex)\n      ]\n\n    callProcAssign plan \"fftw_plan_dft_1d\"\n      [ valArg (n :: Data Word32)\n      , objArg inp\n      , objArg out\n      , valArg (varExp \"FFTW_FORWARD\"  :: Data Word32)\n      , valArg (varExp \"FFTW_ESTIMATE\" :: Data Word32)\n          -- Change to `FFTW_MEASURE` to enable tuning\n      ]\n\n    start <- newObject \"clock_t\" False\n    end   <- newObject \"clock_t\" False\n    callProcAssign start \"clock\" []\n\n    for (0,1,Excl 100) $ \\(_ :: Data Index) ->\n      callProc \"fftw_execute\" [objArg plan]\n\n    callProcAssign end \"clock\" []\n    callProc \"printTime\" [objArg start, objArg end]\n\n    callProc \"fftw_destroy_plan\" [objArg plan]\n    callProc \"fftw_free\" [objArg inp]\n    callProc \"fftw_free\" [objArg out]\n\nrunBenchmark n = runCompiled'\n    def\n    def {externalFlagsPre = [\"-O3\"], externalFlagsPost = [\"-lm\",\"-lfftw3\"]}\n    (benchmark n)\n\n", "meta": {"hexsha": "52c3cf18c2b259377a8f68c218a76e9b709d69b8", "size": 3717, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/FFTW.hs", "max_stars_repo_name": "Abhiroop/mu-feldspar", "max_stars_repo_head_hexsha": "2a3afd53ea9d0139a4f33f0015321f84fddb5159", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2016-08-26T11:04:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T11:30:01.000Z", "max_issues_repo_path": "examples/FFTW.hs", "max_issues_repo_name": "Abhiroop/mu-feldspar", "max_issues_repo_head_hexsha": "2a3afd53ea9d0139a4f33f0015321f84fddb5159", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-08-29T10:28:39.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-29T10:28:39.000Z", "max_forks_repo_path": "examples/FFTW.hs", "max_forks_repo_name": "Abhiroop/mu-feldspar", "max_forks_repo_head_hexsha": "2a3afd53ea9d0139a4f33f0015321f84fddb5159", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-08-29T10:16:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-14T02:22:32.000Z", "avg_line_length": 26.55, "max_line_length": 105, "alphanum_fraction": 0.6540220608, "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4865510342734001}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE Strict #-}\nmodule STC.CompletionField where\n\nimport           Control.Monad.Parallel as MP\nimport           Data.Array.Repa        as R\nimport           Data.Complex\nimport           Data.List              as L\nimport           Data.Vector.Storable   as VS\nimport           DFT.Plan\nimport           Filter.Utils\nimport           STC.Convolution\nimport           STC.DFTArray\nimport           STC.Plan\nimport           Utils.Array\nimport           Utils.Parallel\n\n{-# INLINE completionField #-}\ncompletionField :: DFTPlan -> DFTArray -> DFTArray -> IO DFTArray\ncompletionField plan source@(DFTArray rows cols thetaFreqs rFreqs _) sink = do\n  let numThetaFreq = L.length thetaFreqs\n      numRFreq = L.length rFreqs\n      sourceFilter =\n        VS.convert .\n        toUnboxed .\n        computeUnboxedS .\n        R.backpermute\n          (Z :. numRFreq :. numThetaFreq :. cols :. rows)\n          (\\(Z :. a :. b :. c :. d) ->\n             (Z :. (makeFilterHelper numRFreq a) :.\n              (makeFilterHelper numThetaFreq b) :.\n              c :.\n              d)) .\n        pad [rows, cols, numThetaFreq, numRFreq] 0 . \n        dftArrayToRepa $\n        source\n      dftID = DFTPlanID DFT1DG [numRFreq, numThetaFreq, cols, rows] [0, 1]\n  dftSource <- dftExecute plan dftID sourceFilter\n  dftSink <- dftExecute plan dftID . VS.concat . getDFTArrayVector $ sink\n  arr <-\n    fmap\n      (fromUnboxed (Z :. numRFreq :. numThetaFreq :. cols :. rows) . VS.convert) .\n    dftExecute\n      plan\n      (DFTPlanID IDFT1DG [numRFreq, numThetaFreq, cols, rows] [0, 1]) .\n    VS.zipWith (*) dftSource $\n    dftSink\n  return $ repaToDFTArray thetaFreqs rFreqs $ arr\n\n{-# INLINE completionField' #-}\ncompletionField' :: DFTPlan -> DFTArray -> DFTArray -> IO DFTArray\ncompletionField' plan source@(DFTArray rows cols thetaFreqs rFreqs _) sink = do\n  let numThetaFreq = L.length thetaFreqs\n      sourceFilter =\n        VS.convert .\n        toUnboxed .\n        computeUnboxedS .\n        R.backpermute\n          (Z :. (1 :: Int) :. numThetaFreq :. cols :. rows)\n          (\\(Z :. _ :. b :. c :. d) ->\n             (Z :. (0 :: Int) :. (makeFilterHelper numThetaFreq b) :. c :. d)) .\n        dftArrayToRepa $\n        source\n      dftID = DFTPlanID DFT1DG [1, numThetaFreq, cols, rows] [0, 1]\n  dftSource <- dftExecute plan dftID sourceFilter\n  dftSink <- dftExecute plan dftID . VS.concat . getDFTArrayVector $ sink\n  arr <-\n    fmap\n      (fromUnboxed (Z :. (1 :: Int) :. numThetaFreq :. cols :. rows) .\n       VS.convert) .\n    dftExecute plan (DFTPlanID IDFT1DG [1, numThetaFreq, cols, rows] [0, 1]) .\n    VS.zipWith (*) dftSource $\n    dftSink\n  return $ repaToDFTArray thetaFreqs rFreqs $ arr\n  \n\n{-# INLINE completionFieldRepa #-}\ncompletionFieldRepa ::\n     (R.Source s1 (Complex Double), R.Source s2 (Complex Double))\n  => DFTPlan\n  -> R.Array s1 DIM4 (Complex Double)\n  -> R.Array s2 DIM4 (Complex Double)\n  -> IO (R.Array U DIM4 (Complex Double))\ncompletionFieldRepa plan source sink = do\n  print . extent $ source\n  let (Z :. numRFreq :. numThetaFreq :. cols :. rows) = extent source\n      dftID = DFTPlanID DFT1DG [numRFreq, numThetaFreq, cols, rows] [0, 1]\n  sourceFilter <-\n    fmap (VS.convert . toUnboxed) .\n    computeUnboxedP .\n    R.backpermute\n      (extent source)\n      (\\(Z :. a :. b :. c :. d) ->\n         Z :. makeFilterHelper numRFreq a :. makeFilterHelper numThetaFreq b :.\n          c :.\n          d) $\n    source\n  dftSource <- dftExecute plan dftID sourceFilter\n  sinkU <- computeUnboxedP . delay $ sink\n  dftSink <- dftExecute plan dftID . VS.convert . toUnboxed $ sinkU\n  fmap (fromUnboxed (extent source) . VS.convert) .\n    dftExecute\n      plan\n      (DFTPlanID IDFT1DG [numRFreq, numThetaFreq, cols, rows] [0, 1]) .\n    VS.zipWith (*) dftSource $\n    dftSink\n  \n\n\n-- {-# INLINE completionField #-}\n-- completionField :: DFTPlan -> DFTArray -> DFTArray -> IO DFTArray\n-- completionField plan source@(DFTArray rows cols thetaFreqs rFreqs _) sink = do\n--   let numThetaFreq = L.length thetaFreqs\n--       numRFreq = L.length rFreqs\n--       sourceFilter =\n--         VS.convert .\n--         toUnboxed .\n--         computeUnboxedS .\n--         R.backpermute\n--           (Z :. numRFreq :. numThetaFreq :. cols :. rows)\n--           (\\(Z :. a :. b :. c :. d) ->\n--              (Z :. (makeFilterHelper numRFreq a) :.\n--               (makeFilterHelper numThetaFreq b) :.\n--               c :.\n--               d)) .\n--         dftArrayToRepa $\n--         source\n--       dftID = DFTPlanID DFT1DG [numRFreq, numThetaFreq, cols, rows] [0, 1]\n--   dftSource <- dftExecute plan dftID $ sourceFilter\n--   dftSink <- dftExecute plan dftID . VS.concat . getDFTArrayVector $ sink\n--   arr <-\n--     fmap\n--       (fromUnboxed (Z :. numRFreq :. numThetaFreq :. cols :. rows) . VS.convert) .\n--     dftExecute\n--       plan\n--       (DFTPlanID IDFT1DG [numRFreq, numThetaFreq, cols, rows] [0, 1]) .\n--     VS.zipWith (*) dftSource $\n--     dftSink\n--   return $ repaToDFTArray thetaFreqs rFreqs $ arr\n", "meta": {"hexsha": "afdc4d4e915db164f4f71980b6d72d500ccea773", "size": 5044, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/STC/CompletionField.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/STC/CompletionField.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/STC/CompletionField.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 36.0285714286, "max_line_length": 85, "alphanum_fraction": 0.594369548, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4865469252001073}}
{"text": "#!/usr/bin/env stack\n-- stack --resolver lts-15.04 runghc --package reanimate\n{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\n\nimport           Codec.Picture.Types\nimport           Control.Lens                  ()\nimport           Control.Monad\nimport           Data.Function\nimport           Data.List\nimport           Data.List.NonEmpty            (NonEmpty)\nimport qualified Data.List.NonEmpty            as NE\nimport           Data.Maybe\nimport           Data.Ratio\nimport qualified Data.Text                     as T\nimport           Data.Tuple\nimport qualified Data.Vector                   as V\nimport           Debug.Trace\nimport           Linear.Matrix                 hiding (trace)\nimport           Linear.Metric\nimport           Linear.V2\nimport           Linear.V3\nimport           Linear.Vector\nimport           Numeric.LinearAlgebra         hiding (polar, scale, (<>))\nimport qualified Numeric.LinearAlgebra         as Matrix\nimport           Numeric.LinearAlgebra.HMatrix hiding (polar, scale, (<>))\nimport           Reanimate\nimport           Reanimate.Animation\nimport           Reanimate.Math.Balloon\nimport           Reanimate.Math.Common\nimport           Reanimate.Math.Triangulate\nimport           Reanimate.Math.Polygon\nimport           Reanimate.Math.EarClip\nimport           Reanimate.Math.SSSP\nimport           Reanimate.Math.Render\nimport           Reanimate.Math.Visibility\nimport           Reanimate.Math.Compatible\nimport           Reanimate.Morph.Common\nimport           Reanimate.PolyShape           (svgToPolygons)\n\np1 = pScale 2 $ pAtCenter $ pAddPoints (0+2) (pSetOffset shape13 0)\n-- p1 = pSetOffset (addPoints 2 shape13) 0\n-- p2 = pScale 0.5 $ centerPolygon shape20\n-- p1 = centerPolygon shape2\np2 = pScale 2 $ pAtCenter $ pAddPoints 0 (pSetOffset shape14 0)\n\nmain :: IO ()\nmain = reanimate $ sceneAnimation $ do\n  bg <- newSpriteSVG $ mkBackground \"black\"\n  spriteZ bg (-1)\n  -- play $ drawVisibleFrom triangle\n  -- play $ drawVisibleFrom shape1\n  -- play $ drawVisibleFrom shape2\n  -- play $ drawVisibleFrom shape3\n  -- play $ drawVisibleFrom shape4\n  -- play $ drawVisibleFrom shape5\n  -- play $ drawVisibleFrom shape6\n  -- play $ drawOverlap shape20\n  -- play $ drawSSSP triangle naive\n  -- play $ drawSSSPFast shape5\n  -- fork $ play $ mapA (translate (-3) 0) $ drawSSSPVisibilityFast shape2\n  -- fork $ play $ mapA (translate (3) 0) $ drawSSSPVisibilityFast shape7\n  -- play $ drawOverlap $ fst $ split1Link (fst (split1Link shape7 3 7)) 0 2\n  -- fork $ play $ mapA (translate (-4) 0) $ drawSSSPVisibilityFast $ pSetOffset (addPoints 0 shape14) 0\n  -- fork $ play $ mapA (translate (4) 0) $ drawSSSPVisibilityFast $ pSetOffset (addPoints 2 shape13) 0\n  fork $ play $ staticFrame 1 $ \n    translate (4) 0 $ mkGroup\n    [ withFillColor \"grey\" $ polygonShape p1\n    , polygonNumDots p1 ]\n  fork $ play $ staticFrame 1 $\n    let -- pOrigin = (addPoints 10 $ pSetOffset shape14 0)\n        pOrigin = pScale 2 $ pAtCenter $ pAddPoints (0+2) (pSetOffset shape13 0)\n        --pOrigin = (addPoints 2 shape13)\n        p1 = pScale 1 $ pSetOffset pOrigin 0\n        p2 = snd $ split1Link p1 1 11 0\n        p3 = fst $ split1Link p2 0 2 1\n        -- p4 = fst $ split2Link p3 2 5\n        p4 = snd $ split1Link p3 0 9 1\n        p5 = fst $ split1Link p4 1 3 0\n        p6 = fst $ split2Link p5 0 2\n        p7 = fst $ split1Link p6 1 3 0\n        p8 = fst $ split2Link p7 0 2\n        p9 = fst $ split1Link p7 1 3 0\n        p = p4\n    in mkGroup\n    [ withFillColor \"grey\" $ polygonShape p\n    , polygonNumDots p ]\n  -- newSpriteSVG $\n  --   let p1 = pSetOffset shape14 0\n  --       V2 x y = realToFrac <$> steiner2Link p1 2 6\n  --   in translate (-4) 0 $\n  --     translate x y $ withFillColor \"red\" $\n  --     mkCircle 0.1\n  -- newSpriteSVG $\n  --   let p1 = pSetOffset shape14 0\n  --   in translate (-4) 0 $\n  --     mkGroup\n  --     [ mkGroup\n  --       [ withStrokeColor \"purple\" $\n  --         mkLinePath [(x1,y1),(x2,y2)]\n  --       , translate x2 y2 $ withFillColor \"red\" $ mkCircle 0.1 ]\n  --     | (eA, eB) <- take 1 $ steiner2Edges p1 4 11\n  --     , let V2 x1 y1 = realToFrac <$> eA\n  --           V2 x2 y2 = realToFrac <$> eB\n  --     ]\n  -- play $ staticFrame 1 $\n  --   let p1 = pSetOffset shape14 0\n  --   in mkGroup\n  --   [ withFillColor \"grey\" $ polygonShape p1\n  --   , polygonNumDots p1\n  --   , drawWindowOverlap p1 1 6\n  --   -- , withStrokeColor \"red\" $ drawWindow (pSetOffset p1 2)\n  --   -- , withStrokeColor \"blue\" $ drawWindow (pSetOffset p1 6)\n  --   ]\n  -- play $ drawCompatible (pSetOffset (addPoints 2 shape13) 0) (pSetOffset shape14 0)\n\n  -- play $ drawSSSP shape2 naive\n  -- play $ drawSSSP shape3 naive\n  -- play $ drawSSSP shape4 naive\n  -- play $ drawSSSP shape5 naive\n  -- play $ drawSSSP (pScale 0.5 $ winding 10) (\\p -> sssp p (dual (earClip p)))\n  -- play $ drawSSSP shape1 (\\p -> sssp p (dual (earClip p)))\n  -- play $ drawTriangulation (pCycle shape5 0.2910962834555265) earClip'\n  -- play $ drawTriangulation shape5 earClip'\n  -- play $ mkAnimation 1 $ \\t ->\n  --   let p = shape4\n  --   in polygonNumDots (pCycle p t)\n  -- play $ setDuration 20 $ drawSSSPVisibility $ pScale 1 $ shape7\n  -- let shapeI = head $ svgToPolygons 0.1 $ scale 8 $ center $ latex \"I\"\n  -- play $ animate $ \\_ -> withFillColor \"grey\" $ polygonNumDots shapeI\n  -- play $ drawTriangulation (pScale 0.5 $ winding 10) earClip'\n  -- play $ staticFrame 1 $\n  --   mkGroup\n  --   [ withFillColor \"grey\" $ polygonShape shape13\n  --   , withFillColor \"grey\" $ polygonDots shape13 ]\n  -- let p = balloonP origin\n  --     origin = centerPolygon $ pScale 1 $ shiftLongestDiameter shapeI\n  --     mkB = balloon (scale 8 $ center $ latex \"C\")\n  --     inf = unsafeSVGToPolygon 0.1 $ (scale 8 $ center $ latex \"$\\\\infty$\")\n  --     cShape = shiftLongestDiameter $ unsafeSVGToPolygon 0.01 $ (scale 8 $ center $ latex \"C\")\n  -- _ <- newSpriteSVG $\n  --   translate (0) (3) $ withFillColor \"white\" $\n  --   center $ latex $ T.pack $ show (isSimple inf)\n  -- play $ pauseAtEnd 1 $ mkAnimation 3 $ \\t ->\n  --   let inflated = p t in\n  --   translate (0) (0) $ withFillColor \"white\" $ withStrokeColor \"red\" $\n  --   withStrokeWidth (defaultStrokeWidth*0) $\n    -- polygonShape inf\n    -- renderTriangulation inf (earClip inf)\n    -- mkB t\n    -- scale 3 $ -- translate (-2.2) (-1) $\n    -- mkGroup\n    -- [ mkGroup []\n    -- , withStrokeWidth (defaultStrokeWidth*0.05) $\n    --   renderDual (pRing shape22) (dual (polygonOffset shape22) $ polygonTriangulation shape22)\n    -- , polygonNumDots shape22\n    --   -- renderTriangulation cShape (polygonTriangulation cShape)\n    -- ]\n    -- mkGroup\n    -- [ -- translate (-2) 0 $ withFillColor \"white\" $ polygonShape $ balloonP (min 1 $ t+0.1) origin\n    --   if False then mkGroup [] else translate (0) 0 $ mkGroup\n    --   [ withFillColor \"white\" $ polygonShape inflated\n    --   -- , polygonNumDots inflated\n    --   ]\n    -- -- , translate (2) 0 $ mkGroup\n    -- --   [ withFillColor \"grey\" $ polygonShape origin\n    -- --   , polygonNumDots origin\n    -- --   ]\n    -- ]\n  -- play $ mapA (withStrokeWidth (defaultStrokeWidth*0.2)) $ drawTriangulation cShape earClip'\n  -- play $ staticFrame 1 $ renderTriangulation shape3 earClip\n  -- play $ staticFrame 1 $ renderTriangulation shape4 earClip\n  -- play $ staticFrame 1 $ renderTriangulation shape5 earClip\n  -- play $ staticFrame 1 $ renderTriangulation shape6 earClip\n  -- let p = deoverlapPolygon shape23\n  -- newSpriteSVG $ translate (-3) 0 $ scale 2 $ center $ mkGroup\n  --   [ withFillColor \"grey\" $ polygonShape p\n  --   , polygonNumDots p\n  --   ]\n  -- wait 1\n  -- play $ mapA (scale 2 . withStrokeWidth (defaultStrokeWidth*0.2)) $\n  --   drawTriangulation p (earClip')\n  return ()\n\ndrawVisibility :: Polygon -> Animation\ndrawVisibility p' = mkAnimation 5 $ \\t ->\n  let p = pCycle p' (t::Double) in\n  centerUsing (polygonShape p) $\n  mkGroup\n  [ withFillColor \"grey\" $ polygonShape p\n  , withFillColor \"grey\" $ polygonDots p\n  , withFillColor \"white\" $ mkLinePathClosed\n    [ (x,y) | V2 x y <- visibility (map (fmap realToFrac) $ V.toList $ polygonPoints p) ]\n  , let V2 x y = fmap realToFrac $ pAccess p 0 in\n    translate x y $ withFillColor \"red\" $ mkCircle 0.1\n  -- , withFillColor \"blue\" $ latex $ T.pack $ show (t)\n  ]\n\ndrawSSSPVisibility :: Polygon -> Animation\ndrawSSSPVisibility p' = mkAnimation 5 $ \\t ->\n  let p = pSetOffset p' (round $ t*(fromIntegral $ pSize p'-1))\n      vis = ssspVisibility p in\n  centerUsing (polygonShape p) $\n  mkGroup\n  [ withFillColor \"grey\" $ polygonShape p\n  -- , withFillColor \"grey\" $ polygonDots p\n  -- , withFillColor \"white\" $ polygonShape vis\n  , let V2 x y = fmap realToFrac $ pAccess p 0 in\n    translate x y $ withFillColor \"red\" $ mkCircle 0.1\n  -- , withFillColor \"blue\" $ latex $ T.pack $ show (t)\n  ]\n\ndrawSSSPVisibilityFast :: Polygon -> Animation\ndrawSSSPVisibilityFast p' = mkAnimation 5 $ \\t ->\n  let root = min (pSize p-1) $ (floor $ t*(fromIntegral $ pSize p))\n      p = pSetOffset p' root\n      vis = ssspVisibility p in\n  -- centerUsing (polygonShape p) $\n  mkGroup\n  [ withFillColor \"grey\" $ polygonShape p\n  , withFillColor \"white\" $ polygonShape vis\n  , withFillColor \"grey\" $ polygonNumDots p\n  , let V2 x y = fmap realToFrac $ pAccess p 0 in\n    translate x y $ withFillColor \"red\" $ mkCircle 0.09\n  -- , withFillColor \"blue\" $ latex $ T.pack $ show (t)\n  ]\n\ndrawCompatible :: Polygon -> Polygon -> Animation\ndrawCompatible a b = sceneAnimation $ do\n  newSpriteSVG $ translate (-3) 0 $ mkGroup\n    [ withFillColor \"grey\" $ polygonShape a\n    , withFillColor \"grey\" $ polygonNumDots a\n    ]\n  newSpriteSVG $ translate (3) 0 $ mkGroup\n    [ withFillColor \"grey\" $ polygonShape b\n    , withFillColor \"grey\" $ polygonNumDots b\n    ]\n  let compat = compatiblyTriangulateP a b\n  forM_ compat $ \\(l, r) -> do\n    fork $ play $ staticFrame 1 $\n      translate (-3) 0 $ withStrokeColor \"white\" $ withStrokeWidth (defaultStrokeWidth*0.2) $\n      withFillOpacity 0 $ polygonShape l\n    fork $ play $ staticFrame 1 $\n      translate (3) 0 $ withStrokeColor \"white\" $ withStrokeWidth (defaultStrokeWidth*0.2) $\n      withFillOpacity 0 $ polygonShape r\n  -- forM_ compat $ \\(l, r) -> waitOn $ do\n  --   fork $ play $ staticFrame 1 $\n  --     translate (-3) 0 $\n  --     withFillColor \"white\" $ polygonShape l\n  --   fork $ play $ staticFrame 1 $\n  --     translate (3) 0 $\n  --     withFillColor \"white\" $ polygonShape r\n\ndrawOverlap :: Polygon -> Animation\ndrawOverlap p' = mkAnimation 5 $ \\t ->\n  let p = pCycle p' (t::Double)\n      vis = ssspVisibility p\n      vis' = ssspVisibility p'\n      mWins = ssspWindows p\n      oWins = ssspWindows p'\n      -- (left, right) = split1Link p' 0 3\n      -- (left, right) = split2Link p' 0 2\n      -- (left, right) = splitNLink p' 0 [(TwoLink,2),(OneLink,3)]\n      -- (left, right) = splitNLink p' 0 [(OneLink,5),(TwoLink,3)]\n      -- sPoly = if t < 0.5 then left else right\n      in\n  centerUsing (polygonShape p) $\n  mkGroup\n  [ withFillColor \"grey\" $ polygonShape p\n  -- , withFillColor \"grey\" $ polygonDots p\n  , withFillOpacity 0.5 $ withFillColor \"lightgreen\" $ polygonShape vis\n  -- , withFillOpacity 0.5 $ withFillColor \"cyan\" $ polygonShape vis'\n  , let V2 x y = fmap realToFrac $ pAccess p 0 in\n    translate x y $ withFillColor \"red\" $ mkCircle 0.1\n  , let V2 x y = fmap realToFrac $ pAccess p' 0 in\n    translate x y $ withFillColor \"red\" $ mkCircle 0.1\n  -- , withFillColor \"blue\" $ latex $ T.pack $ show (t)\n  , mkGroup\n    [ withStrokeColor \"red\" $\n      mkLine (x1,y1) (x2,y2)\n    | (a,b) <- mWins\n    , let V2 x1 y1 = realToFrac <$> a\n          V2 x2 y2 = realToFrac <$> b\n    ]\n  -- , mkGroup\n  --   [ withStrokeColor \"blue\" $\n  --     mkLine (x1,y1) (x2,y2)\n  --   | (a,b) <- oWins\n  --   , let V2 x1 y1 = realToFrac <$> a\n  --         V2 x2 y2 = realToFrac <$> b\n  --   ]\n  , mkGroup\n    [ withStrokeColor \"green\" $mkGroup\n      [ mkLine (x1,y1) (x2,y2)\n      , mkLine (x1',y1') (x2',y2') ]\n    | (a,b) <- mWins\n    , (i,j) <- oWins\n    , a == i || a == j || b == i || b == j\n    , not (sort [a,b] == sort [i,j])\n    , let V2 x1 y1 = realToFrac <$> a\n          V2 x2 y2 = realToFrac <$> b\n          V2 x1' y1' = realToFrac <$> i\n          V2 x2' y2' = realToFrac <$> j\n    ]\n  -- , mkGroup\n  --   [ let V2 x y = realToFrac <$> link in\n  --     translate x y $\n  --     withFillColor \"red\" $\n  --     mkCircle 0.1\n  --   | link <- [steiner2Link p' 0 2, steiner2Link p' 5 3] ]\n  -- , withFillColor \"blue\" $ polygonShape sPoly\n  ]\n\ndrawWindow :: Polygon -> SVG\ndrawWindow p =\n  let mWins = ssspWindows p\n      in\n  mkGroup\n  [ mkGroup\n    [ mkLine (x1,y1) (x2,y2)\n    | (a,b) <- mWins\n    , let V2 x1 y1 = realToFrac <$> a\n          V2 x2 y2 = realToFrac <$> b\n    ]\n  ]\n\ndrawWindowOverlap :: Polygon -> Int -> Int -> SVG\ndrawWindowOverlap p a b =\n  let aWins = ssspWindows (pAdjustOffset p a)\n      bWins = ssspWindows (pAdjustOffset p b)\n      in\n  mkGroup\n  [ mkGroup $\n    [ withStrokeColor \"green\" $mkGroup\n      [ mkLine (x1,y1) (x2,y2)\n      , mkLine (x1',y1') (x2',y2') ]\n    | (a,b) <- aWins\n    , (i,j) <- bWins\n    , a == i || a == j || b == i || b == j\n    , not (sort [a,b] == sort [i,j])\n    , let V2 x1 y1 = realToFrac <$> a\n          V2 x2 y2 = realToFrac <$> b\n          V2 x1' y1' = realToFrac <$> i\n          V2 x2' y2' = realToFrac <$> j\n    ]\n  ]\n\ndrawSSSP :: Polygon -> (Polygon -> SSSP) -> Animation\ndrawSSSP p gen = mkAnimation 5 $ \\t -> centerUsing outline $\n  let p' = pCycles p !! (round $ t*(fromIntegral $ pSize p-1)) in\n  mkGroup\n  [ outline\n  , renderSSSP p' (gen p')\n  -- , let V2 x y = fmap realToFrac $ pAccess (pCycle p t) 0 in\n  --   translate x y $ withFillColor \"red\" $ mkCircle 0.1\n  , withFillColor \"grey\" $ polygonNumDots $ p'\n  ]\n  where\n    outline =\n      withFillColor \"grey\" $ mkLinePathClosed\n        [ (x,y) | V2 x y <- map (fmap realToFrac) (V.toList (polygonPoints p)  ++ [pAccess p 0]) ]\n\n{-# INLINE drawSSSPFast #-}\ndrawSSSPFast :: Polygon -> Animation\ndrawSSSPFast p = mkAnimation 5 $ \\t -> centerUsing outline $\n  let root = (round $ t*(fromIntegral $ pSize p-1))\n      d = dual root triangulation\n      sTree = sssp (pRing p) d in\n  mkGroup\n  [ outline\n  , renderSSSP p sTree\n  -- , let V2 x y = fmap realToFrac $ pAccess (pCycle p t) 0 in\n  --   translate x y $ withFillColor \"red\" $ mkCircle 0.1\n  , withFillColor \"grey\" $ polygonNumDots $ p\n  ]\n  where\n    triangulation = earClip $ pRing p\n    outline =\n      withFillColor \"grey\" $ mkLinePathClosed\n        [ (x,y) | V2 x y <- map (fmap realToFrac) (V.toList (polygonPoints p) ++ [pAccess p 0]) ]\n\ndrawVisibleFrom :: Polygon -> Animation\ndrawVisibleFrom p = mkAnimation 5 $ \\t -> centerUsing (polygonShape p) $ mkGroup\n  [ withFillColor \"grey\" $ polygonShape p\n  , withFillColor \"grey\" $ polygonDots p\n  , renderVisibleFrom (pCycle p t)\n  , let V2 x y = fmap realToFrac $ pAccess (pCycle p t) 0 in\n    translate x y $ withFillColor \"red\" $ mkCircle 0.1\n  ]\n\n\nrenderVisibleFrom :: Polygon -> SVG\nrenderVisibleFrom p = withStrokeColor \"white\" $ withFillColor \"white\" $ mkGroup\n  [ mkGroup\n    [ mkLine (ax,ay) (bx,by)\n    , translate bx by $ mkCircle 0.1 ]\n  | i <- visibilityArray (pRing p) V.! 0\n  , let V2 ax ay = fmap realToFrac $ pAccess p 0\n        V2 bx by = fmap realToFrac $ pAccess p i ]\n\ndrawTriangulation :: Polygon -> (Ring Rational -> [Triangulation]) -> Animation\ndrawTriangulation p gen = sceneAnimation $ do\n  forM_ (gen $ pRing p) $ \\t -> play $ staticFrame 1 $ renderTriangulation p t\n\nrenderDual :: Ring Rational -> Dual -> SVG\nrenderDual ring d = case d of\n    Dual (a,b,c) l r -> mkGroup\n      [ withFillColor \"blue\" $ mkTrig a b c\n      , worker c a l\n      , worker b c r\n      ]\n  where\n    mkTrig a b c =\n      let V2 x1 y1 = realToFrac <$> ringAccess ring a\n          V2 x2 y2 = realToFrac <$> ringAccess ring b\n          V2 x3 y3 = realToFrac <$> ringAccess ring c\n      in mkLinePathClosed [ (x1, y1), (x2,y2), (x3,y3) ]\n    worker p1 p2 EmptyDual = mkGroup []\n    worker p1 p2 (NodeDual x l r) = mkGroup\n      [ mkTrig p1 p2 x\n      , worker x p2 l\n      , worker p1 x r\n      ]\n-- data Dual = Dual (Int,Int,Int) -- (a,b,c)\n--                   DualTree -- borders ca\n--                   DualTree -- borders bc\n--   deriving (Show)\n--\n-- data DualTree\n--   = EmptyDual\n--   | NodeDual Int -- axb triangle, a and b are from parent.\n--       DualTree -- borders xb\n--       DualTree -- borders ax\n--   deriving (Show)\n", "meta": {"hexsha": "30b3d5e8d28995457dc5c32001c836538af2fe8a", "size": 16394, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "videos/morph/vis.hs", "max_stars_repo_name": "TristanCacqueray/reanimate", "max_stars_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "videos/morph/vis.hs", "max_issues_repo_name": "TristanCacqueray/reanimate", "max_issues_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "videos/morph/vis.hs", "max_forks_repo_name": "TristanCacqueray/reanimate", "max_forks_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6873563218, "max_line_length": 104, "alphanum_fraction": 0.6090642918, "num_tokens": 5338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4864607887890416}}
{"text": "{-# LANGUAGE CPP                        #-}\n{-# LANGUAGE DataKinds                  #-}\n{-# LANGUAGE EmptyDataDecls             #-}\n{-# LANGUAGE FlexibleContexts           #-}\n{-# LANGUAGE FlexibleInstances          #-}\n{-# LANGUAGE FunctionalDependencies     #-}\n{-# LANGUAGE GADTs                      #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE KindSignatures             #-}\n{-# LANGUAGE MultiParamTypeClasses      #-}\n{-# LANGUAGE Rank2Types                 #-}\n{-# LANGUAGE ScopedTypeVariables        #-}\n{-# LANGUAGE TypeFamilies               #-}\n{-# LANGUAGE TypeOperators              #-}\n{-# LANGUAGE ViewPatterns               #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\n{- |\nModule      :  Numeric.LinearAlgebra.Static\nCopyright   :  (c) Alberto Ruiz 2014\nLicense     :  BSD3\nStability   :  experimental\n\nExperimental interface with statically checked dimensions.\n\nSee code examples at http://dis.um.es/~alberto/hmatrix/static.html.\n\n-}\n\nmodule Numeric.LinearAlgebra.Static(\n    -- * Vector\n       \u211d, R,\n    vec2, vec3, vec4, (&), (#), split, headTail,\n    vector,\n    linspace, range, dim,\n    -- * Matrix\n    L, Sq, build,\n    row, col, (|||),(===), splitRows, splitCols,\n    unrow, uncol,\n    tr,\n    eye,\n    diag,\n    blockAt,\n    matrix,\n    -- * Complex\n    \u2102, C, M, Her, her, \ud835\udc56,\n    toComplex,\n    fromComplex,\n    complex,\n    real,\n    imag,\n    sqMagnitude,\n    magnitude,\n    -- * Products\n    (<>),(#>),(<.>),\n    -- * Linear Systems\n    linSolve, (<\\>),\n    -- * Factorizations\n    svd, withCompactSVD, svdTall, svdFlat, Eigen(..),\n    withNullspace, withOrth, qr, chol,\n    -- * Norms\n    Normed(..),\n    -- * Random arrays\n    Seed, RandDist(..),\n    randomVector, rand, randn, gaussianSample, uniformSample,\n    -- * Misc\n    mean, meanCov,\n    Disp(..), Domain(..),\n    withVector, withMatrix, exactLength, exactDims,\n    toRows, toColumns, withRows, withColumns,\n    Sized(..), Diag(..), Sym, sym, mTm, unSym, (<\u00b7>)\n) where\n\n\nimport           Control.Arrow               ((***))\nimport qualified Data.Bifunctor              as BF (first)\nimport           Data.Proxy                  (Proxy (..))\nimport           Data.Type.Equality          ((:~:) (Refl))\nimport           GHC.TypeLits\nimport           Internal.Static\nimport           Numeric.LinearAlgebra       hiding (C, Konst (..), R, build, chol, col,\n                                              complex, diag, disp, dot, eig, eigSH,\n                                              eigenvalues, eigenvaluesSH, fromComplex,\n                                              fromList, gaussianSample, linspace, mTm,\n                                              magnitude, matrix, meanCov, qr, rand, randn,\n                                              randomVector, range, real, row, size, svd,\n                                              sym, takeDiag, toColumns, toComplex, toRows,\n                                              unSym, uniformSample, vector, ( #> ), (<.>),\n                                              (<>), (<\\>), (===), (|||))\nimport qualified Numeric.LinearAlgebra       as LA\nimport qualified Numeric.LinearAlgebra.Devel as LA\nimport           Text.Printf\n#if MIN_VERSION_base(4,11,0)\nimport           Prelude                     hiding ((<>))\n#endif\n\nud1 :: R n -> Vector \u211d\nud1 (R (Dim v)) = v\n\n\ninfixl 4 &\n(&) :: forall n . KnownNat n\n    => R n -> \u211d -> R (n+1)\nu & x = u # (konst x :: R 1)\n\ninfixl 4 #\n(#) :: forall n m . (KnownNat n, KnownNat m)\n    => R n -> R m -> R (n+m)\n(R u) # (R v) = R (vconcat u v)\n\n\nvec2 :: \u211d -> \u211d -> R 2\nvec2 a b = R (gvec2 a b)\n\nvec3 :: \u211d -> \u211d -> \u211d -> R 3\nvec3 a b c = R (gvec3 a b c)\n\n\nvec4 :: \u211d -> \u211d -> \u211d -> \u211d -> R 4\nvec4 a b c d = R (gvec4 a b c d)\n\nvector :: KnownNat n => [\u211d] -> R n\nvector = fromList\n\nmatrix :: (KnownNat m, KnownNat n) => [\u211d] -> L m n\nmatrix = fromList\n\nlinspace :: forall n . KnownNat n => (\u211d,\u211d) -> R n\nlinspace (a,b) = v\n  where\n    v = mkR (LA.linspace (size v) (a,b))\n\nrange :: forall n . KnownNat n => R n\nrange = v\n  where\n    v = mkR (LA.linspace d (1,fromIntegral d))\n    d = size v\n\ndim :: forall n . KnownNat n => R n\ndim = v\n  where\n    v = mkR (scalar (fromIntegral $ size v))\n\n--------------------------------------------------------------------------------\n\n\nud2 :: L m n -> Matrix \u211d\nud2 (L (Dim (Dim x))) = x\n\n\n--------------------------------------------------------------------------------\n\ndiag :: KnownNat n => R n -> Sq n\ndiag = diagR 0\n\neye :: KnownNat n => Sq n\neye = diag 1\n\n--------------------------------------------------------------------------------\n\nblockAt :: forall m n . (KnownNat m, KnownNat n) =>  \u211d -> Int -> Int -> Matrix Float -> L m n\nblockAt x r c a = res\n  where\n    z = scalar x\n    z1 = LA.konst x (r,c)\n    z2 = LA.konst x (max 0 (m'-(ra+r)), max 0 (n'-(ca+c)))\n    ra = min (rows a) . max 0 $ m'-r\n    ca = min (cols a) . max 0 $ n'-c\n    sa = subMatrix (0,0) (ra, ca) a\n    (m',n') = size res\n    res = mkL $ fromBlocks [[z1,z,z],[z,sa,z],[z,z,z2]]\n\n--------------------------------------------------------------------------------\n\n\nrow :: R n -> L 1 n\nrow = mkL . asRow . ud1\n\n--col :: R n -> L n 1\ncol v = tr . row $ v\n\nunrow :: L 1 n -> R n\nunrow = mkR . head . LA.toRows . ud2\n\n--uncol :: L n 1 -> R n\nuncol v = unrow . tr $ v\n\n\ninfixl 2 ===\n(===) :: (KnownNat r1, KnownNat r2, KnownNat c) => L r1 c -> L r2 c -> L (r1+r2) c\na === b = mkL (extract a LA.=== extract b)\n\n\ninfixl 3 |||\n-- (|||) :: (KnownNat r, KnownNat c1, KnownNat c2) => L r c1 -> L r c2 -> L r (c1+c2)\na ||| b = tr (tr a === tr b)\n\n\ntype Sq n  = L n n\n--type CSq n = CL n n\n\n\ntype GL = forall n m . (KnownNat n, KnownNat m) => L m n\ntype GSq = forall n . KnownNat n => Sq n\n\nisKonst :: forall m n . (KnownNat m, KnownNat n) => L m n -> Maybe (\u211d,(Int,Int))\nisKonst s@(unwrap -> x)\n    | singleM x = Just (x `atIndex` (0,0), (size s))\n    | otherwise = Nothing\n\n\nisKonstC :: forall m n . (KnownNat m, KnownNat n) => M m n -> Maybe (\u2102,(Int,Int))\nisKonstC s@(unwrap -> x)\n    | singleM x = Just (x `atIndex` (0,0), (size s))\n    | otherwise = Nothing\n\n\ninfixr 8 <>\n(<>) :: forall m k n. (KnownNat m, KnownNat k, KnownNat n) => L m k -> L k n -> L m n\n(<>) = mulR\n\n\ninfixr 8 #>\n(#>) :: (KnownNat m, KnownNat n) => L m n -> R n -> R m\n(#>) = appR\n\n\ninfixr 8 <\u00b7>\n(<\u00b7>) :: KnownNat n => R n -> R n -> \u211d\n(<\u00b7>) = dotR\n\ninfixr 8 <.>\n(<.>) :: KnownNat n => R n -> R n -> \u211d\n(<.>) = dotR\n\n--------------------------------------------------------------------------------\n\nclass Diag m d | m -> d\n  where\n    takeDiag :: m -> d\n\n\ninstance KnownNat n => Diag (L n n) (R n)\n  where\n    takeDiag x = mkR (LA.takeDiag (extract x))\n\n\ninstance KnownNat n => Diag (M n n) (C n)\n  where\n    takeDiag x = mkC (LA.takeDiag (extract x))\n\n--------------------------------------------------------------------------------\n\n\ntoComplex :: KnownNat n => (R n, R n) -> C n\ntoComplex (r,i) = mkC $ LA.toComplex (ud1 r, ud1 i)\n\nfromComplex :: KnownNat n => C n -> (R n, R n)\nfromComplex (C (Dim v)) = let (r,i) = LA.fromComplex v in (mkR r, mkR i)\n\ncomplex :: KnownNat n => R n -> C n\ncomplex r = mkC $ LA.toComplex (ud1 r, LA.konst 0 (size r))\n\nreal :: KnownNat n => C n -> R n\nreal = fst . fromComplex\n\nimag :: KnownNat n => C n -> R n\nimag = snd . fromComplex\n\nsqMagnitude :: KnownNat n => C n -> R n\nsqMagnitude c = let (r,i) = fromComplex c in r**2 + i**2\n\nmagnitude :: KnownNat n => C n -> R n\nmagnitude = sqrt . sqMagnitude\n\n--------------------------------------------------------------------------------\n\nlinSolve :: (KnownNat m, KnownNat n) => L m m -> L m n -> Maybe (L m n)\nlinSolve (extract -> a) (extract -> b) = fmap mkL (LA.linearSolve a b)\n\n(<\\>) :: (KnownNat m, KnownNat n, KnownNat r) => L m n -> L m r -> L n r\n(extract -> a) <\\> (extract -> b) = mkL (a LA.<\\> b)\n\nsvd :: (KnownNat m, KnownNat n) => L m n -> (L m m, R n, L n n)\nsvd (extract -> m) = (mkL u, mkR s', mkL v)\n  where\n    (u,s,v) = LA.svd m\n    s' = vjoin [s, z]\n    z = LA.konst 0 (max 0 (cols m - LA.size s))\n\n\nsvdTall :: (KnownNat m, KnownNat n, n <= m) => L m n -> (L m n, R n, L n n)\nsvdTall (extract -> m) = (mkL u, mkR s, mkL v)\n  where\n    (u,s,v) = LA.thinSVD m\n\n\nsvdFlat :: (KnownNat m, KnownNat n, m <= n) => L m n -> (L m m, R m, L n m)\nsvdFlat (extract -> m) = (mkL u, mkR s, mkL v)\n  where\n    (u,s,v) = LA.thinSVD m\n\n--------------------------------------------------------------------------------\n\nclass Eigen m l v | m -> l, m -> v\n  where\n    eigensystem :: m -> (l,v)\n    eigenvalues :: m -> l\n\nnewtype Sym n = Sym (Sq n) deriving Show\n\n\nsym :: KnownNat n => Sq n -> Sym n\nsym m = Sym $ (m + tr m)/2\n\nmTm :: (KnownNat m, KnownNat n) => L m n -> Sym n\nmTm x = Sym (tr x <> x)\n\nunSym :: Sym n -> Sq n\nunSym (Sym x) = x\n\n\n\ud835\udc56 :: Sized \u2102 s c => s\n\ud835\udc56 = konst iC\n\nnewtype Her n = Her (M n n)\n\nher :: KnownNat n => M n n -> Her n\nher m = Her $ (m + LA.tr m)/2\n\n\ninstance (KnownNat n) => Disp (Sym n)\n  where\n    disp n (Sym x) = do\n        let a = extract x\n        let su = LA.dispf n a\n        printf \"Sym %d\" (cols a) >> putStr (dropWhile (/='\\n') $ su)\n\ninstance (KnownNat n) => Disp (Her n)\n  where\n    disp n (Her x) = do\n        let a = extract x\n        let su = LA.dispcf n a\n        printf \"Her %d\" (cols a) >> putStr (dropWhile (/='\\n') $ su)\n\n\ninstance KnownNat n => Eigen (Sym n) (R n) (L n n)\n  where\n    eigenvalues (Sym (extract -> m)) =  mkR . LA.eigenvaluesSH . LA.trustSym $ m\n    eigensystem (Sym (extract -> m)) = (mkR l, mkL v)\n      where\n        (l,v) = LA.eigSH . LA.trustSym $ m\n\ninstance KnownNat n => Eigen (Sq n) (C n) (M n n)\n  where\n    eigenvalues (extract -> m) = mkC . LA.eigenvalues $ m\n    eigensystem (extract -> m) = (mkC l, mkM v)\n      where\n        (l,v) = LA.eig m\n\nchol :: KnownNat n => Sym n -> Sq n\nchol (extract . unSym -> m) = mkL $ LA.chol $ LA.trustSym m\n\n--------------------------------------------------------------------------------\n\nwithNullspace\n    :: forall m n z . (KnownNat m, KnownNat n)\n    => L m n\n    -> (forall k . (KnownNat k) => L n k -> z)\n    -> z\nwithNullspace (LA.nullspace . extract -> a) f =\n    case someNatVal $ fromIntegral $ cols a of\n       Nothing                       -> error \"static/dynamic mismatch\"\n       Just (SomeNat (_ :: Proxy k)) -> f (mkL a :: L n k)\n\nwithOrth\n    :: forall m n z . (KnownNat m, KnownNat n)\n    => L m n\n    -> (forall k. (KnownNat k) => L n k -> z)\n    -> z\nwithOrth (LA.orth . extract -> a) f =\n    case someNatVal $ fromIntegral $ cols a of\n       Nothing                       -> error \"static/dynamic mismatch\"\n       Just (SomeNat (_ :: Proxy k)) -> f (mkL a :: L n k)\n\nwithCompactSVD\n    :: forall m n z . (KnownNat m, KnownNat n)\n    => L m n\n    -> (forall k . (KnownNat k) => (L m k, R k, L n k) -> z)\n    -> z\nwithCompactSVD (LA.compactSVD . extract -> (u,s,v)) f =\n    case someNatVal $ fromIntegral $ LA.size s of\n       Nothing                       -> error \"static/dynamic mismatch\"\n       Just (SomeNat (_ :: Proxy k)) -> f (mkL u :: L m k, mkR s :: R k, mkL v :: L n k)\n\n--------------------------------------------------------------------------------\n\nqr :: (KnownNat m, KnownNat n) => L m n -> (L m m, L m n)\nqr (extract -> x) = (mkL q, mkL r)\n  where\n    (q,r) = LA.qr x\n\n-- use qrRaw?\n\n--------------------------------------------------------------------------------\n\nsplit :: forall p n . (KnownNat p, KnownNat n, p<=n) => R n -> (R p, R (n-p))\nsplit (extract -> v) = ( mkR (subVector 0 p' v) ,\n                         mkR (subVector p' (LA.size v - p') v) )\n  where\n    p' = fromIntegral . natVal $ (undefined :: Proxy p) :: Int\n\n\nheadTail :: (KnownNat n, 1<=n) => R n -> (\u211d, R (n-1))\nheadTail = ((!0) . extract *** id) . split\n\n\nsplitRows :: forall p m n . (KnownNat p, KnownNat m, KnownNat n, p<=m) => L m n -> (L p n, L (m-p) n)\nsplitRows (extract -> x) = ( mkL (takeRows p' x) ,\n                             mkL (dropRows p' x) )\n  where\n    p' = fromIntegral . natVal $ (undefined :: Proxy p) :: Int\n\nsplitCols :: forall p m n. (KnownNat p, KnownNat m, KnownNat n, KnownNat (n-p), p<=n) => L m n -> (L m p, L m (n-p))\nsplitCols = (tr *** tr) . splitRows . tr\n\n\ntoRows :: forall m n . (KnownNat m, KnownNat n) => L m n -> [R n]\ntoRows (LA.toRows . extract -> vs) = map mkR vs\n\nwithRows\n    :: forall n z . KnownNat n\n    => [R n]\n    -> (forall m . KnownNat m => L m n -> z)\n    -> z\nwithRows (LA.fromRows . map extract -> m) f =\n    case someNatVal $ fromIntegral $ LA.rows m of\n       Nothing                       -> error \"static/dynamic mismatch\"\n       Just (SomeNat (_ :: Proxy m)) -> f (mkL m :: L m n)\n\ntoColumns :: forall m n . (KnownNat m, KnownNat n) => L m n -> [R m]\ntoColumns (LA.toColumns . extract -> vs) = map mkR vs\n\nwithColumns\n    :: forall m z . KnownNat m\n    => [R m]\n    -> (forall n . KnownNat n => L m n -> z)\n    -> z\nwithColumns (LA.fromColumns . map extract -> m) f =\n    case someNatVal $ fromIntegral $ LA.cols m of\n       Nothing                       -> error \"static/dynamic mismatch\"\n       Just (SomeNat (_ :: Proxy n)) -> f (mkL m :: L m n)\n\n\n--------------------------------------------------------------------------------\n\nbuild\n  :: forall m n . (KnownNat n, KnownNat m)\n    => (\u211d -> \u211d -> \u211d)\n    -> L m n\nbuild f = r\n  where\n    r = mkL $ LA.build (size r) f\n\n--------------------------------------------------------------------------------\n\nwithVector\n    :: forall z\n     . Vector \u211d\n    -> (forall n . (KnownNat n) => R n -> z)\n    -> z\nwithVector v f =\n    case someNatVal $ fromIntegral $ LA.size v of\n       Nothing                       -> error \"static/dynamic mismatch\"\n       Just (SomeNat (_ :: Proxy m)) -> f (mkR v :: R m)\n\n-- | Useful for constraining two dependently typed vectors to match each\n-- other in length when they are unknown at compile-time.\nexactLength\n    :: forall n m . (KnownNat n, KnownNat m)\n    => R m\n    -> Maybe (R n)\nexactLength v = do\n    Refl <- sameNat (Proxy :: Proxy n) (Proxy :: Proxy m)\n    return $ mkR (unwrap v)\n\nwithMatrix\n    :: forall z\n     . Matrix \u211d\n    -> (forall m n . (KnownNat m, KnownNat n) => L m n -> z)\n    -> z\nwithMatrix a f =\n    case someNatVal $ fromIntegral $ rows a of\n       Nothing -> error \"static/dynamic mismatch\"\n       Just (SomeNat (_ :: Proxy m)) ->\n           case someNatVal $ fromIntegral $ cols a of\n               Nothing -> error \"static/dynamic mismatch\"\n               Just (SomeNat (_ :: Proxy n)) ->\n                  f (mkL a :: L m n)\n\n-- | Useful for constraining two dependently typed matrices to match each\n-- other in dimensions when they are unknown at compile-time.\nexactDims\n    :: forall n m j k . (KnownNat n, KnownNat m, KnownNat j, KnownNat k)\n    => L m n\n    -> Maybe (L j k)\nexactDims m = do\n    Refl <- sameNat (Proxy :: Proxy m) (Proxy :: Proxy j)\n    Refl <- sameNat (Proxy :: Proxy n) (Proxy :: Proxy k)\n    return $ mkL (unwrap m)\n\nrandomVector\n    :: forall n . KnownNat n\n    => Seed\n    -> RandDist\n    -> R n\nrandomVector s d = mkR (LA.randomVector s d\n                          (fromInteger (natVal (Proxy :: Proxy n)))\n                       )\n\nrand\n    :: forall m n . (KnownNat m, KnownNat n)\n    => IO (L m n)\nrand = mkL <$> LA.rand (fromInteger (natVal (Proxy :: Proxy m)))\n                       (fromInteger (natVal (Proxy :: Proxy n)))\n\nrandn\n    :: forall m n . (KnownNat m, KnownNat n)\n    => IO (L m n)\nrandn = mkL <$> LA.randn (fromInteger (natVal (Proxy :: Proxy m)))\n                         (fromInteger (natVal (Proxy :: Proxy n)))\n\ngaussianSample\n    :: forall m n . (KnownNat m, KnownNat n)\n    => Seed\n    -> R n\n    -> Sym n\n    -> L m n\ngaussianSample s (extract -> mu) (Sym (extract -> sigma)) =\n    mkL $ LA.gaussianSample s (fromInteger (natVal (Proxy :: Proxy m)))\n                            mu (LA.trustSym sigma)\n\nuniformSample\n    :: forall m n . (KnownNat m, KnownNat n)\n    => Seed\n    -> R n    -- ^ minimums of each row\n    -> R n    -- ^ maximums of each row\n    -> L m n\nuniformSample s (extract -> mins) (extract -> maxs) =\n    mkL $ LA.uniformSample s (fromInteger (natVal (Proxy :: Proxy m)))\n                           (zip (LA.toList mins) (LA.toList maxs))\n\nmeanCov\n    :: forall m n . (KnownNat m, KnownNat n, 1 <= m)\n    => L m n\n    -> (R n, Sym n)\nmeanCov (extract -> vs) = mkR *** (Sym . mkL . LA.unSym) $ LA.meanCov vs\n\n--------------------------------------------------------------------------------\n\nclass Domain field vec mat | mat -> vec field, vec -> mat field, field -> mat vec\n  where\n    mul :: forall m k n. (KnownNat m, KnownNat k, KnownNat n) => mat m k -> mat k n -> mat m n\n    app :: forall m n . (KnownNat m, KnownNat n) => mat m n -> vec n -> vec m\n    dot :: forall n . (KnownNat n) => vec n -> vec n -> field\n    cross :: vec 3 -> vec 3 -> vec 3\n    diagR ::  forall m n k . (KnownNat m, KnownNat n, KnownNat k) => field -> vec k -> mat m n\n    dvmap :: forall n. KnownNat n => (field -> field) -> vec n -> vec n\n    dmmap :: forall n m. (KnownNat m, KnownNat n) => (field -> field) -> mat n m -> mat n m\n    outer :: forall n m. (KnownNat m, KnownNat n) => vec n -> vec m -> mat n m\n    zipWithVector :: forall n. KnownNat n => (field -> field -> field) -> vec n -> vec n -> vec n\n    det :: forall n. KnownNat n => mat n n -> field\n    invlndet :: forall n. KnownNat n => mat n n -> (mat n n, (field, field))\n    expm :: forall n. KnownNat n => mat n n -> mat n n\n    sqrtm :: forall n. KnownNat n => mat n n -> mat n n\n    inv :: forall n. KnownNat n => mat n n -> mat n n\n\n\ninstance Domain \u211d R L\n  where\n    mul = mulR\n    app = appR\n    dot = dotR\n    cross = crossR\n    diagR = diagRectR\n    dvmap = mapR\n    dmmap = mapL\n    outer = outerR\n    zipWithVector = zipWithR\n    det = detL\n    invlndet = invlndetL\n    expm = expmL\n    sqrtm = sqrtmL\n    inv = invL\n\ninstance Domain \u2102 C M\n  where\n    mul = mulC\n    app = appC\n    dot = dotC\n    cross = crossC\n    diagR = diagRectC\n    dvmap = mapC\n    dmmap = mapM'\n    outer = outerC\n    zipWithVector = zipWithC\n    det = detM\n    invlndet = invlndetM\n    expm = expmM\n    sqrtm = sqrtmM\n    inv = invM\n\n--------------------------------------------------------------------------------\n\nmulR :: forall m k n. (KnownNat m, KnownNat k, KnownNat n) => L m k -> L k n -> L m n\n\nmulR (isKonst -> Just (a,(_,k))) (isKonst -> Just (b,_)) = konst (a * b * fromIntegral k)\n\nmulR (isDiag -> Just (0,a,_)) (isDiag -> Just (0,b,_)) = diagR 0 (mkR v :: R k)\n  where\n    v = a' * b'\n    n = min (LA.size a) (LA.size b)\n    a' = subVector 0 n a\n    b' = subVector 0 n b\n\nmulR (isDiag -> Just (0,a,_)) (extract -> b) = mkL (asColumn a * takeRows (LA.size a) b)\n\nmulR (extract -> a) (isDiag -> Just (0,b,_)) = mkL (takeColumns (LA.size b) a * asRow b)\n\nmulR a b = mkL (extract a LA.<> extract b)\n\n\nappR :: (KnownNat m, KnownNat n) => L m n -> R n -> R m\nappR (isDiag -> Just (0, w, _)) v = mkR (w * subVector 0 (LA.size w) (extract v))\nappR m v                          = mkR (extract m LA.#> extract v)\n\n\ndotR :: KnownNat n => R n -> R n -> \u211d\ndotR (extract -> u) (extract -> v) = LA.dot u v\n\n\ncrossR :: R 3 -> R 3 -> R 3\ncrossR (extract -> x) (extract -> y) = vec3 z1 z2 z3\n  where\n    z1 = x!1*y!2-x!2*y!1\n    z2 = x!2*y!0-x!0*y!2\n    z3 = x!0*y!1-x!1*y!0\n\nouterR :: (KnownNat m, KnownNat n) => R n -> R m -> L n m\nouterR (extract -> x) (extract -> y) = mkL (LA.outer x y)\n\nmapR :: KnownNat n => (\u211d -> \u211d) -> R n -> R n\nmapR f (unwrap -> v) = mkR (LA.cmap f v)\n\nzipWithR :: KnownNat n => (\u211d -> \u211d -> \u211d) -> R n -> R n -> R n\nzipWithR f (extract -> x) (extract -> y) = mkR (LA.zipVectorWith f x y)\n\nmapL :: (KnownNat n, KnownNat m) => (\u211d -> \u211d) -> L n m -> L n m\nmapL f = overMatL' (LA.cmap f)\n\ndetL :: KnownNat n => Sq n -> \u211d\ndetL = LA.det . unwrap\n\ninvlndetL :: KnownNat n => Sq n -> (L n n, (\u211d, \u211d))\ninvlndetL = BF.first mkL . LA.invlndet . unwrap\n\nexpmL :: KnownNat n => Sq n -> Sq n\nexpmL = overMatL' LA.expm\n\nsqrtmL :: KnownNat n => Sq n -> Sq n\nsqrtmL = overMatL' LA.sqrtm\n\ninvL :: KnownNat n => Sq n -> Sq n\ninvL = overMatL' LA.inv\n\n--------------------------------------------------------------------------------\n\nmulC :: forall m k n. (KnownNat m, KnownNat k, KnownNat n) => M m k -> M k n -> M m n\n\nmulC (isKonstC -> Just (a,(_,k))) (isKonstC -> Just (b,_)) = konst (a * b * fromIntegral k)\n\nmulC (isDiagC -> Just (0,a,_)) (isDiagC -> Just (0,b,_)) = diagR 0 (mkC v :: C k)\n  where\n    v = a' * b'\n    n = min (LA.size a) (LA.size b)\n    a' = subVector 0 n a\n    b' = subVector 0 n b\n\nmulC (isDiagC -> Just (0,a,_)) (extract -> b) = mkM (asColumn a * takeRows (LA.size a) b)\n\nmulC (extract -> a) (isDiagC -> Just (0,b,_)) = mkM (takeColumns (LA.size b) a * asRow b)\n\nmulC a b = mkM (extract a LA.<> extract b)\n\n\nappC :: (KnownNat m, KnownNat n) => M m n -> C n -> C m\nappC (isDiagC -> Just (0, w, _)) v = mkC (w * subVector 0 (LA.size w) (extract v))\nappC m v                           = mkC (extract m LA.#> extract v)\n\n\ndotC :: KnownNat n => C n -> C n -> \u2102\ndotC (extract -> u) (extract -> v) = LA.dot u v\n\n\ncrossC :: C 3 -> C 3 -> C 3\ncrossC (extract -> x) (extract -> y) = mkC (LA.fromList [z1, z2, z3])\n  where\n    z1 = x!1*y!2-x!2*y!1\n    z2 = x!2*y!0-x!0*y!2\n    z3 = x!0*y!1-x!1*y!0\n\nouterC :: (KnownNat m, KnownNat n) => C n -> C m -> M n m\nouterC (extract -> x) (extract -> y) = mkM (LA.outer x y)\n\nmapC :: KnownNat n => (\u2102 -> \u2102) -> C n -> C n\nmapC f (unwrap -> v) = mkC (LA.cmap f v)\n\nzipWithC :: KnownNat n => (\u2102 -> \u2102 -> \u2102) -> C n -> C n -> C n\nzipWithC f (extract -> x) (extract -> y) = mkC (LA.zipVectorWith f x y)\n\nmapM' :: (KnownNat n, KnownNat m) => (\u2102 -> \u2102) -> M n m -> M n m\nmapM' f = overMatM' (LA.cmap f)\n\ndetM :: KnownNat n => M n n -> \u2102\ndetM = LA.det . unwrap\n\ninvlndetM :: KnownNat n => M n n -> (M n n, (\u2102, \u2102))\ninvlndetM = BF.first mkM . LA.invlndet . unwrap\n\nexpmM :: KnownNat n => M n n -> M n n\nexpmM = overMatM' LA.expm\n\nsqrtmM :: KnownNat n => M n n -> M n n\nsqrtmM = overMatM' LA.sqrtm\n\ninvM :: KnownNat n => M n n -> M n n\ninvM = overMatM' LA.inv\n\n--------------------------------------------------------------------------------\n\ndiagRectR :: forall m n k . (KnownNat m, KnownNat n, KnownNat k) => \u211d -> R k -> L m n\ndiagRectR x v\n    | m' == 1 = mkL (LA.diagRect x ev m' n')\n    | m'*n' > 0 = r\n    | otherwise = matrix []\n  where\n    r = mkL (asRow (vjoin [scalar x, ev, zeros]))\n    ev = extract v\n    zeros = LA.konst x (max 0 ((min m' n') - LA.size ev))\n    (m',n') = size r\n\n\ndiagRectC :: forall m n k . (KnownNat m, KnownNat n, KnownNat k) => \u2102 -> C k -> M m n\ndiagRectC x v\n    | m' == 1 = mkM (LA.diagRect x ev m' n')\n    | m'*n' > 0 = r\n    | otherwise = fromList []\n  where\n    r = mkM (asRow (vjoin [scalar x, ev, zeros]))\n    ev = extract v\n    zeros = LA.konst x (max 0 ((min m' n') - LA.size ev))\n    (m',n') = size r\n\n--------------------------------------------------------------------------------\n\nmean :: (KnownNat n, 1<=n) => R n -> \u211d\nmean v = v <\u00b7> (1/dim)\n\ntest :: (Bool, IO ())\ntest = (ok,info)\n  where\n    ok =   extract (eye :: Sq 5) == ident 5\n           && (unwrap .unSym) (mTm sm :: Sym 3) == tr ((3><3)[1..]) LA.<> (3><3)[1..]\n           && unwrap (tm :: L 3 5) == LA.matrix 5 [1..15]\n           && thingS == thingD\n           && precS == precD\n           && withVector (LA.vector [1..15]) sumV == sumElements (LA.fromList [1..15])\n\n    info = do\n        print $ u\n        print $ v\n        print (eye :: Sq 3)\n        print $ ((u & 5) + 1) <\u00b7> v\n        print (tm :: L 2 5)\n        print (tm <> sm :: L 2 3)\n        print thingS\n        print thingD\n        print precS\n        print precD\n        print $ withVector (LA.vector [1..15]) sumV\n        splittest\n\n    sumV w = w <\u00b7> konst 1\n\n    u = vec2 3 5\n\n    \ud835\udd67 x = vector [x] :: R 1\n\n    v = \ud835\udd67 2 & 4 & 7\n\n    tm :: GL\n    tm = lmat 0 [1..]\n\n    lmat :: forall m n . (KnownNat m, KnownNat n) => \u211d -> [\u211d] -> L m n\n    lmat z xs = r\n      where\n        r = mkL . reshape n' . LA.fromList . take (m'*n') $ xs ++ repeat z\n        (m',n') = size r\n\n    sm :: GSq\n    sm = lmat 0 [1..]\n\n    thingS = (u & 1) <\u00b7> tr q #> q #> v\n      where\n        q = tm :: L 10 3\n\n    thingD = vjoin [ud1 u, 1] LA.<.> tr m LA.#> m LA.#> ud1 v\n      where\n        m = LA.matrix 3 [1..30]\n\n    precS = (1::Float) + (2::Float) * ((1 :: R 3) * (u & 6)) <\u00b7> konst 2 #> v\n    precD = 1 + 2 * vjoin[ud1 u, 6] LA.<.> LA.konst 2 (LA.size (ud1 u) +1, LA.size (ud1 v)) LA.#> ud1 v\n\n\nsplittest\n    = do\n    let v = range :: R 7\n        a = snd (split v) :: R 4\n    print $ a\n    print $ snd . headTail . snd . headTail $ v\n    print $ first (vec3 1 2 3)\n    print $ second (vec3 1 2 3)\n    print $ third (vec3 1 2 3)\n    print $ (snd $ splitRows eye :: L 4 6)\n where\n    first v = fst . headTail $ v\n    second v = first . snd . headTail $ v\n    third v = first . snd . headTail . snd . headTail $ v\n\n\ninstance (KnownNat n', KnownNat m') => Testable (L n' m')\n  where\n    checkT _ = test\n\n--------------------------------------------------------------------------------\n\ninstance KnownNat n => Normed (R n)\n  where\n    norm_0 v = norm_0 (extract v)\n    norm_1 v = norm_1 (extract v)\n    norm_2 v = norm_2 (extract v)\n    norm_Inf v = norm_Inf (extract v)\n\ninstance (KnownNat m, KnownNat n) => Normed (L m n)\n  where\n    norm_0 m = norm_0 (extract m)\n    norm_1 m = norm_1 (extract m)\n    norm_2 m = norm_2 (extract m)\n    norm_Inf m = norm_Inf (extract m)\n\nmkSym f = Sym . f . unSym\nmkSym2 f x y = Sym (f (unSym x) (unSym y))\n\ninstance KnownNat n =>  Num (Sym n)\n  where\n    (+) = mkSym2 (+)\n    (*) = mkSym2 (*)\n    (-) = mkSym2 (-)\n    abs = mkSym abs\n    signum = mkSym signum\n    negate = mkSym negate\n    fromInteger = Sym . fromInteger\n\ninstance KnownNat n => Fractional (Sym n)\n  where\n    fromRational = Sym . fromRational\n    (/) = mkSym2 (/)\n\ninstance KnownNat n => Floating (Sym n)\n  where\n    sin   = mkSym sin\n    cos   = mkSym cos\n    tan   = mkSym tan\n    asin  = mkSym asin\n    acos  = mkSym acos\n    atan  = mkSym atan\n    sinh  = mkSym sinh\n    cosh  = mkSym cosh\n    tanh  = mkSym tanh\n    asinh = mkSym asinh\n    acosh = mkSym acosh\n    atanh = mkSym atanh\n    exp   = mkSym exp\n    log   = mkSym log\n    sqrt  = mkSym sqrt\n    (**)  = mkSym2 (**)\n    pi    = Sym pi\n\ninstance KnownNat n => Additive (Sym n) where\n    add = (+)\n\ninstance KnownNat n => Transposable (Sym n) (Sym n) where\n    tr  = id\n    tr' = id\n\ninstance KnownNat n => Transposable (Her n) (Her n) where\n    tr          = id\n    tr' (Her m) = Her (tr' m)\n", "meta": {"hexsha": "377ad826f4da98786a16eaa2115cc0b2a89f360a", "size": 26324, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/Static.hs", "max_stars_repo_name": "schnecki/hmatrix-float", "max_stars_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "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/LinearAlgebra/Static.hs", "max_issues_repo_name": "schnecki/hmatrix-float", "max_issues_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LinearAlgebra/Static.hs", "max_forks_repo_name": "schnecki/hmatrix-float", "max_forks_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-12T02:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T02:51:35.000Z", "avg_line_length": 28.8957189901, "max_line_length": 116, "alphanum_fraction": 0.497682723, "num_tokens": 8719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48644001190483266}}
{"text": "module LispType\n    (\n    LispVal(..)\n  , Array\n    ) where\nimport Data.Ratio\nimport Data.Complex\nimport Data.Array\n\n{-\n\u53f0\u6570\u7684\u30c7\u30fc\u30bf\u578b\u306e\u4e00\u4f8b\nLispVal\u578b\u306e\u5909\u6570\u304c\u6301\u3064\u3053\u3068\u306e\u3067\u304d\u308b\u5024\u306e\u96c6\u5408\u3092\u5b9a\u3081\u3066\u3044\u308b\n\u9078\u629e\u80a2\u306e\u305d\u308c\u305e\u308c(\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u3001\u3068\u547c\u3070\u308c\u3001| \u3067\u533a\u5207\u3089\u308c\u308b)\u306f\u3001\n\u3001\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u306e\u30bf\u30b0\u3068\u305d\u306e\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u304c\u6301\u3064\u3053\u3068\u306e\u3067\u304d\u308b\u30c7\u30fc\u30bf\u306e\u578b\u3092\u542b\u3080\n\u3053\u306e\u4f8b\u3067\u306f\u3001LispVal\u306f\u6b21\u306e\u3069\u308c\u304b\n  1. Atom - \u305d\u306e\u30a2\u30c8\u30e0\u306e\u793a\u3059\u6587\u5b57\u5217\u3092\u683c\u7d0d\u3057\u307e\u3059\u3002\n  2. List - \u4ed6\u306eLispVal\u306e\u30ea\u30b9\u30c8\u3092\u4fdd\u6301\u3057\u307e\u3059(Haskell\u306e\u30ea\u30b9\u30c8\u306f\u89d2\u62ec\u5f27\u3067\u8868\u3055\u308c\u307e\u3059)\u3002proper\u30ea\u30b9\u30c8\u3068\u3082\u547c\u3070\u308c\u307e\u3059\u3002\n  3. DottedList - Scheme\u306e(a b . c)\u3092\u8868\u3057\u3001improper\u30ea\u30b9\u30c8\u3068\u3082\u547c\u3070\u308c\u307e\u3059\u3002\u3053\u308c\u306f\u6700\u5f8c\u4ee5\u5916\u5168\u3066\u306e\u8981\u7d20\u306e\u30ea\u30b9\u30c8\u3092\u6301\u3061\u3001\u6700\u5f8c\u306e\u8981\u7d20\u3092\u5225\u306b\u683c\u7d0d\u3057\u307e\u3059\u3002\n  4. Number - Haskell\u306e\u6574\u6570\u3092\u4fdd\u6301\u3057\u307e\u3059\u3002\n  5. String - Haskell\u306e\u6587\u5b57\u5217\u3092\u4fdd\u6301\u3057\u307e\u3059\u3002\n  6. Bool - Haskell\u306e\u771f\u507d\u5024\u3092\u4fdd\u6301\u3057\u307e\u3059\u3002\n-}\ndata LispVal =  Atom        String\n              | String      String\n              | Character   Char\n              | Bool        Bool\n              | Number      Integer\n              | Float       Double\n              | Complex    (Complex Double)\n              | Ratio       Rational\n              | Vector     (Array Int LispVal)\n              | List       [LispVal]\n              | DottedList [LispVal] LispVal\n", "meta": {"hexsha": "6b013efcd30ac3bc3b79f88626281d197e00aab4", "size": 967, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/LispType.hs", "max_stars_repo_name": "bokuo-okubo/scheme-of-bko", "max_stars_repo_head_hexsha": "b07e6c8340c59ba543c87c757fd442294902327d", "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/LispType.hs", "max_issues_repo_name": "bokuo-okubo/scheme-of-bko", "max_issues_repo_head_hexsha": "b07e6c8340c59ba543c87c757fd442294902327d", "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/LispType.hs", "max_forks_repo_name": "bokuo-okubo/scheme-of-bko", "max_forks_repo_head_hexsha": "b07e6c8340c59ba543c87c757fd442294902327d", "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.4411764706, "max_line_length": 91, "alphanum_fraction": 0.6122026887, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.48636266161338243}}
{"text": "module ForMNIST\n ( makeImageMatrix\n , loadImage \n , loadLabel\n , datasize\n , loadImageTest\n , loadLabelTest\n ) where   \n\n-------------------------------------------------------------\n--module\n-------------------------------------------------------------\n\nimport qualified Data.ByteString.Lazy as B\nimport Numeric.LinearAlgebra\nimport Tools\n\n------------------------------------------------\n\n-------------------------------------------------------------\n--MNIST\u306e\u30c7\u30fc\u30bf\u3092\u56de\u53ce\u3059\u308b\u3002\n-------------------------------------------------------------\ndatasize = 10000\n\n--\u4e0e\u3048\u3089\u308c\u305f\u30ea\u30b9\u30c8[a]\u304b\u3089\u6307\u5b9a\u3057\u305f\u8981\u7d20\u6570(num)\u3054\u3068\u306b\u5206\u5272\u3057\u3066\u30ea\u30b9\u30c8\u306e\u30ea\u30b9\u30c8[[a]]\u3092\u4f5c\u308b\u3002\ndivideEqually :: Int -> [a] -> [[a]]\ndivideEqually _ [] = []\ndivideEqually num xs = xs1 : (divideEqually num xs2)\n    where (xs1, xs2) = splitAt num xs\n\n--\u753b\u50cf\u30a4\u30e1\u30fc\u30b8\u306eBytestring(xs)\u304b\u3089\u6307\u5b9a\u3057\u305f\u9577\u3055\u3092\u5207\u308a\u53d6\u3063\u3066\u30ea\u30b9\u30c8[Double]\u3092\u4f5c\u6210\u3059\u308b\u3002\nconvertImage :: B.ByteString -> [Double]\nconvertImage xs = fmap toEnum $ fmap fromEnum . B.unpack $ B.drop byte xs\n    where byte = 16  + 784*60000 -784 * datasize\n\n--\u30ea\u30b9\u30c8\u306e\u30ea\u30b9\u30c8[[a]]\u304b\u3089Matrix\u306e\u30ea\u30b9\u30c8[[Matrix]]\u3092\u4f5c\u6210\u3059\u308b\u3002\nmakeImageMatrix :: [[Double]] -> [Matrix Double]\nmakeImageMatrix [] = []\nmakeImageMatrix (x:xs) = (row x) : (makeImageMatrix xs)\n\nloadImage1 :: B.ByteString -> [[Double]]\nloadImage1 xs = divideEqually 784 (convertImage xs)\n\n--\u753b\u50cf\u30a4\u30e1\u30fc\u30b8\u306eBytestring(xs)\u304b\u3089\u6307\u5b9a\u3057\u305f\u9577\u3055\u3092\u5207\u308a\u53d6\u3063\u3066Matrix\u306e\u30ea\u30b9\u30c8[[Matrix]]\u3092\u4f5c\u6210\u3059\u308b\u3002\nloadImage :: B.ByteString -> [Matrix Double]\nloadImage xs = makeImageMatrix $ divideEqually 784 (convertImage xs)\n\n--\u30d3\u30b8\u30e5\u30a2\u30eb\u5316\u7528\u306a\u306e\u3067Int\u3067\u51fa\u529b\u3059\u308b\u3002\nconvertImage2 :: B.ByteString -> [Int]\nconvertImage2 xs = fmap fromEnum . B.unpack $ B.drop byte xs\n    where byte = 16  + 784*10000 -784 * datasize\n\n--\u30e9\u30d9\u30eb\u306eBytestring(xs)\u304b\u3089\u6307\u5b9a\u3057\u305f\u9577\u3055\u3092\u5207\u308a\u53d6\u3063\u3066\u30ea\u30b9\u30c8[Int]\u3092\u4f5c\u6210\u3059\u308b\u3002\nloadLabel :: B.ByteString -> [Int]\nloadLabel xs = fmap fromEnum . B.unpack $ B.drop byte xs\n    where byte = 8  + 1*60000 - 1 * datasize\n\nloadLabelTest :: B.ByteString -> [Int]\nloadLabelTest xs = fmap fromEnum . B.unpack $ B.drop byte xs\n    where byte = 8  + 1*10000 - 1 * 1000\n\nconvertImageTest :: B.ByteString -> [Double]\nconvertImageTest xs = fmap toEnum $ fmap fromEnum . B.unpack $ B.drop byte xs\n    where byte = 16  + 784*10000 -784 * 1000\n\nloadImageTest :: B.ByteString -> [Matrix Double]\nloadImageTest xs = makeImageMatrix $ divideEqually 784 (convertImageTest xs)\n\n------------------------------------------------", "meta": {"hexsha": "8568f00e307ec147f56b9870faaa47075b01423f", "size": 2266, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ForMNIST.hs", "max_stars_repo_name": "llbxg/Fukami", "max_stars_repo_head_hexsha": "28e5cb963e372db7f2fe532043092a4bbc4c0101", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-08T10:00:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-08T10:00:17.000Z", "max_issues_repo_path": "src/ForMNIST.hs", "max_issues_repo_name": "llbxg/Fukami", "max_issues_repo_head_hexsha": "28e5cb963e372db7f2fe532043092a4bbc4c0101", "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/ForMNIST.hs", "max_forks_repo_name": "llbxg/Fukami", "max_forks_repo_head_hexsha": "28e5cb963e372db7f2fe532043092a4bbc4c0101", "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.8405797101, "max_line_length": 77, "alphanum_fraction": 0.6067961165, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4862455984309629}}
{"text": "{-# LANGUAGE DataKinds            #-}\n{-# LANGUAGE FlexibleContexts     #-}\n{-# LANGUAGE FlexibleInstances    #-}\n{-# LANGUAGE GADTs                #-}\n{-# LANGUAGE PatternSynonyms      #-}\n{-# LANGUAGE RankNTypes           #-}\n{-# LANGUAGE ScopedTypeVariables  #-}\n{-# LANGUAGE StandaloneDeriving   #-}\n{-# LANGUAGE TypeFamilies         #-}\n{-# LANGUAGE TypeOperators        #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# OPTIONS_GHC -Wall #-}\n-- | This module is wrongly named.\nmodule VectorSpace (\n    LinMap (.., LI),\n    lmul,\n    HasDim(Dim, dimDict),\n    toRawMatrix,\n    evalL,\n    L (..),\n    linear,\n    VectorSpace (..),\n    toVector,\n    fromVector,\n) where\n\nimport Data.Constraint       (Dict (..), withDict, (:-))\nimport Data.Proxy            (Proxy (..))\nimport GHC.TypeLits\nimport Overloaded.Categories\n\nimport qualified Control.Category      as C\nimport qualified Data.Constraint.Nat   as C\nimport qualified Numeric.LinearAlgebra as L\n\n-- import qualified Numeric.LinearAlgebra.Static as LS\n\ndata LinMap a b where\n    LZ :: LinMap a b\n    LD :: Double -> LinMap a a\n    LH :: LinMap a b -> LinMap a c -> LinMap a (b, c)\n    LV :: LinMap a c -> LinMap b c -> LinMap (a, b) c\n    LA :: LinMap a b -> LinMap a b -> LinMap a b\n\nderiving instance Show (LinMap a b)\n\npattern LI :: forall a b. () => (b ~ a) => LinMap a b\npattern LI = LD 1\n\nlmul :: Double -> LinMap a b -> LinMap a b\nlmul _ LZ       = LZ\nlmul k (LD x)   = LD (k * x)\nlmul k (LH f g) = LH (lmul k f) (lmul k g)\nlmul k (LV f g) = LV (lmul k f) (lmul k g)\nlmul k (LA f g) = LA (lmul k f) (lmul k g)\n\nlcomp :: LinMap b c -> LinMap a b -> LinMap a c\nlcomp LZ       _        = LZ\nlcomp _        LZ       = LZ\nlcomp (LD k)   h        = lmul k h\nlcomp h        (LD k)   = lmul k h\nlcomp (LA f g) h        = LA (lcomp f h) (lcomp g h)\nlcomp f        (LA g h) = LA (lcomp f g) (lcomp f h)\nlcomp (LH f g) h        = LH (lcomp f h) (lcomp g h)\nlcomp h        (LV f g) = LV (lcomp h f) (lcomp h g)\nlcomp (LV f g) (LH u v) = LA (lcomp f u) (lcomp g v)\n\ninstance Category LinMap where\n    id  = LI\n    (.) = lcomp\n\ninstance CategoryWith1 LinMap where\n    type Terminal LinMap = ()\n    terminal = LZ\n\ninstance CartesianCategory LinMap where\n    type Product LinMap = (,)\n    proj1  = LV C.id LZ\n    proj2  = LV LZ C.id\n    fanout = LH\n\ninstance CategoryWith0 LinMap where\n    type Initial LinMap = ()\n    initial = LZ\n\ninstance CocartesianCategory LinMap where\n    type Coproduct LinMap = (,)\n    inl   = LH C.id LZ\n    inr   = LH LZ C.id\n    fanin = LV\n\ninstance BicartesianCategory LinMap where\n    distr = LH\n        (LH (LV (LV LI LZ) LZ) (LV LZ LI))\n        (LH (LV (LV LZ LI) LZ) (LV LZ LI))\n\nnewtype L a b = L (forall r. LinMap r a -> LinMap r b)\n\nlfst :: LinMap a (b, c) -> LinMap a b\nlfst (LA f g) = LA (lfst f) (lfst g)\nlfst (LH f _) = f\nlfst (LV f g) = LV (lfst f) (lfst g)\nlfst LZ       = LZ\nlfst (LD k)   = LV (LD k) LZ\n\nlsnd :: LinMap a (b, c) -> LinMap a c\nlsnd (LH _ g) = g\nlsnd (LA f g) = LA (lsnd f) (lsnd g)\nlsnd (LV f g) = LV (lsnd f) (lsnd g)\nlsnd LZ       = LZ\nlsnd (LD k)   = LV LZ (LD k)\n\nlinitial :: LinMap r () -> LinMap r a\nlinitial _ = LZ\n\nlinear :: Double -> L a a\nlinear k = L $ lmul k\n\n-- lmult :: Double -> Double -> LinMap r (a, a) -> LinMap r a\n-- lmult x y (LH f g) = LA (LK y f) (LK x g)\n-- lmult x y (LV f g) = LV (lmult x y f) (lmult x y g)\n-- lmult x y (LA f g) = LA (lmult x y f) (lmult x y g)\n-- lmult x y (LK k f) = LK k (lmult x y f)\n-- lmult _ _ LZ       = LZ\n-- lmult x y LI       = LV (LK y LI) (LK x LI)\n\ninstance Category L where\n    id = L id\n    L f . L g = L (f . g)\n\ninstance CategoryWith1 L where\n    type Terminal L = ()\n\n    terminal = L (\\_ -> LZ)\n\ninstance CartesianCategory L where\n    type Product L = (,)\n\n    proj1 = L lfst\n    proj2 = L lsnd\n\n    fanout (L f) (L g) = L $ \\x -> LH (f x) (g x)\n\ninstance CategoryWith0 L where\n    type Initial L = ()\n\n    initial = L linitial\n\n-- Is this correct?\ninstance CocartesianCategory L where\n    type Coproduct L = (,)\n\n    inl = L $ \\f -> LH f LZ\n    inr = L $ \\g -> LH LZ g\n\n    fanin (L f) (L g) = L $ \\x -> LA (f (lfst x)) (g (lsnd x))\n\nclass HasDim a where\n    type Dim a :: Nat\n\n    dimDict :: Proxy a -> Dict (KnownNat (Dim a))\n\n    splitPair :: (a ~ (b, c)) => (Dict (HasDim b), Dict (HasDim c))\n    splitPair = error \"impossible: splitPair\"\n\ninstance HasDim () where\n    type Dim () = 0\n    dimDict _ = Dict\n\ninstance HasDim Double where\n    type Dim Double = 1\n    dimDict _ = Dict\n\ninstance (HasDim a, HasDim b) => HasDim (a, b) where\n    type Dim (a, b) = Dim a + Dim b\n\n    dimDict _ =\n        withDimDict (Proxy :: Proxy a) $\n        withDimDict (Proxy :: Proxy b) $\n        withDict (C.plusNat :: (KnownNat (Dim a), KnownNat (Dim b)) :- KnownNat (Dim a + Dim b))\n        Dict\n\n    splitPair = (Dict, Dict)\n\n\nwithDimDict :: HasDim a => Proxy a -> (KnownNat (Dim a) => r) -> r\nwithDimDict p = withDict (dimDict p)\n\ndim :: forall a. HasDim a => Proxy a -> Int\ndim p = withDimDict p $ fromInteger $ natVal (Proxy :: Proxy (Dim a))\n\ntoRawMatrix :: forall a b. (HasDim a, HasDim b) => LinMap a b -> L.Matrix Double\ntoRawMatrix LZ       = (dim (Proxy :: Proxy a) L.>< dim (Proxy :: Proxy b)) (repeat 0)\ntoRawMatrix (LD k)   = L.scale k (L.ident (dim (Proxy :: Proxy a)))\ntoRawMatrix (LA f g) = L.add (toRawMatrix f) (toRawMatrix g)\ntoRawMatrix (LH f g) = go splitPair f g where\n    go :: (Dict (HasDim x), Dict (HasDim y)) -> LinMap a x -> LinMap a y -> L.Matrix Double\n    go (Dict, Dict) f' g' = toRawMatrix f' L.||| toRawMatrix g'\ntoRawMatrix (LV f g) = go splitPair f g where\n    go :: (Dict (HasDim x), Dict (HasDim y)) -> LinMap x b -> LinMap y b -> L.Matrix Double\n    go (Dict, Dict) f' g' = toRawMatrix f' L.=== toRawMatrix g'\n\nevalL :: (HasDim a, HasDim b) => L a b -> L.Matrix Double\nevalL (L f) = toRawMatrix (f (LD 1))\n\n-- toStaticMatrix :: forall a b. (HasDim a, HasDim b) => LinMap a b -> LS.L (Dim a) (Dim b)\n-- toStaticMatrix LZ =\n--     withDimDict (Proxy :: Proxy a) $\n--     withDimDict (Proxy :: Proxy b) 0\n-- toStaticMatrix LI =\n--     withDimDict (Proxy :: Proxy a) LS.eye\n-- toStaticMatrix (LA f g) =\n--     withDimDict (Proxy :: Proxy a) $\n--     withDimDict (Proxy :: Proxy b) $\n--     L.add (toStaticMatrix f) (toStaticMatrix g)\n-- toStaticMatrix (LK k f) =\n--     withDimDict (Proxy :: Proxy a) $\n--     withDimDict (Proxy :: Proxy b) $\n--     toStaticMatrix f LS.<> LS.diag (LS.konst k)\n-- toStaticMatrix (LH f g) = go splitPair f g where\n--     go :: forall x y. (x,y) ~ b => (Dict (HasDim x), Dict (HasDim y)) -> LinMap a x -> LinMap a y -> LS.L (Dim a) (Dim x + Dim y)\n--     go (Dict, Dict) f' g' =\n--         withDimDict (Proxy :: Proxy a) $\n--         withDimDict (Proxy :: Proxy b) $\n--         withDimDict (Proxy :: Proxy x) $\n--         withDimDict (Proxy :: Proxy y) $\n--         toStaticMatrix f' LS.||| toStaticMatrix g'\n-- toStaticMatrix (LV f g) = go splitPair f g where\n--     go :: forall x y. (x,y) ~ a => (Dict (HasDim x), Dict (HasDim y)) -> LinMap x b -> LinMap y b -> LS.L (Dim x + Dim y) (Dim b)\n--     go (Dict, Dict) f' g' =\n--         withDimDict (Proxy :: Proxy a) $\n--         withDimDict (Proxy :: Proxy b) $\n--         withDimDict (Proxy :: Proxy x) $\n--         withDimDict (Proxy :: Proxy y) $\n--         toStaticMatrix f' LS.=== toStaticMatrix g'\n\n-------------------------------------------------------------------------------\n-- Vector space\n-------------------------------------------------------------------------------\n\nclass HasDim a => VectorSpace a where\n    toVector' :: a -> [Double] -> [Double]\n\n    fromVector' :: [Double] -> (a -> [Double] -> r) -> r\n\ntoVector :: VectorSpace a => a -> [Double]\ntoVector x = toVector' x []\n\nfromVector :: VectorSpace a => [Double] -> a\nfromVector ds = fromVector' ds const\n\ninstance VectorSpace Double where\n    toVector' d = (d :)\n\n    fromVector' []     k = k 0 []\n    fromVector' (d:ds) k = k d ds\n\ninstance (VectorSpace a, VectorSpace b) => VectorSpace (a, b) where\n    toVector' (a, b) = toVector' a . toVector' b\n\n    fromVector' xs k =\n        fromVector' xs $ \\a ys ->\n        fromVector' ys $ \\b zs ->\n        k (a, b) zs\n", "meta": {"hexsha": "501ba00c582fd145e7e80661a3f6b35a74961592", "size": 8109, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "example/VectorSpace.hs", "max_stars_repo_name": "Mikolaj/overloaded", "max_stars_repo_head_hexsha": "9290d9be88107c5032a4b229fd1d9ef177041c17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-09-08T14:56:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T01:13:15.000Z", "max_issues_repo_path": "example/VectorSpace.hs", "max_issues_repo_name": "Mikolaj/overloaded", "max_issues_repo_head_hexsha": "9290d9be88107c5032a4b229fd1d9ef177041c17", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-17T00:58:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-31T10:40:44.000Z", "max_forks_repo_path": "example/VectorSpace.hs", "max_forks_repo_name": "Mikolaj/overloaded", "max_forks_repo_head_hexsha": "9290d9be88107c5032a4b229fd1d9ef177041c17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-14T23:17:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T23:17:25.000Z", "avg_line_length": 30.6, "max_line_length": 132, "alphanum_fraction": 0.5612282649, "num_tokens": 2679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593358430449435}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell #-}\n\nmodule Day15 where\n\nimport Control.Lens\nimport Control.Lens.TH\n\nimport qualified Data.ByteString as BS\nimport Data.Attoparsec.ByteString (Parser)\nimport qualified Data.Attoparsec.ByteString as DAB\nimport qualified Data.Attoparsec.ByteString.Char8 as DABC8\nimport Data.Attoparsec.ByteString.Char8 (decimal, inClass, digit, endOfLine, char, anyChar, letter_ascii, notChar)\n\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\nimport qualified Data.List as DL\nimport qualified Data.List.Split as DLS\n\nimport Debug.Trace\n\nimport Control.Arrow\n\nimport Data.Array.IArray (Array)\nimport qualified Data.Array.IArray as IA\n\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Either (isRight)\nimport Data.Maybe (mapMaybe, catMaybes)\nimport Data.Bool (bool)\n\nimport Data.Vector (Vector, (!))\nimport qualified Data.Vector as Vec\n\nimport Data.Function (on)\n\nimport Control.Monad.State.Strict (State)\nimport qualified Control.Monad.State.Strict as State\n\nimport qualified Control.Monad as CM\n\nimport qualified Control.Foldl as L\n\nimport Data.Bifunctor (bimap)\n\nimport Data.Complex\nimport Data.Functor\n\nimport Data.Word\nimport Data.Bits\nimport Data.Semigroup\nimport Data.List.NonEmpty (NonEmpty(..))\nimport qualified Data.List.NonEmpty as DLNE\n\ntype Input = Integer\n\nsolver input fTurn = State.evalState (code 6 (fromIntegral $ length input + 1)) $ -- turns start at length input + 1\n\tMap.fromList $ zip input $ fmap (,Nothing) [1..] --Insert the seed input with their order\n\twhere\n\t-- Monadic loop. Maybe avoid custom recursion\n\t-- It returns the fTurn-th value\n\tcode :: Integer -> Integer -> State (Map Integer (Integer, Maybe Integer)) Integer\n\tcode prev turn\n\t\t| turn > fTurn = pure prev\n\t\t| otherwise =\n\t\t\t-- Check is the previous value is repeated\n\t\t\tState.get >>= \\m -> case Map.lookup prev m of\n\t\t\t\tJust (_, Nothing) -> do --not repeated\n\t\t\t\t\tState.modify (Map.insertWith inserter 0 (turn, Nothing))\n\t\t\t\t\tcode 0 (turn + 1)\n\t\t\t\tJust (l, Just ll) -> do -- repeated\n\t\t\t\t\tState.modify (Map.insertWith inserter (l-ll) (turn, Nothing))\n\t\t\t\t\tcode (l - ll) (turn + 1)\n\n\t-- Update the map keeping the previous position\n\t-- DONE: Use a tupple (Integer, Maybe Integer)\n\t-- DONE: avoid error (removed safety check)\n\tinserter :: (Integer, Maybe Integer) -> (Integer, Maybe Integer) -> (Integer, Maybe Integer)\n\tinserter (new, Nothing) (prev, _) = (new, Just prev)\n\t\t-- | new > prev =  (new, Just prev)\n\t\t-- | otherwise = error $ show (prev, new)\n\nrunSolution :: FilePath -> IO ()\nrunSolution _ = do\n\tputStrLn \"**Day 15**\"\n\tprint $ solver input 30000000\n\twhere\n\tinput :: [Input]\n\t--input = [0,3,6]\n\tinput = [0,13,1,16,6,17]\n", "meta": {"hexsha": "a53eb136e74f53062407dfb5e06fd009c489c125", "size": 2774, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src-lib/Day15.hs", "max_stars_repo_name": "argent0/adventOfCode2020", "max_stars_repo_head_hexsha": "e3c81ce3db38490bcfd5de230f605086cc3df06c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src-lib/Day15.hs", "max_issues_repo_name": "argent0/adventOfCode2020", "max_issues_repo_head_hexsha": "e3c81ce3db38490bcfd5de230f605086cc3df06c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src-lib/Day15.hs", "max_forks_repo_name": "argent0/adventOfCode2020", "max_forks_repo_head_hexsha": "e3c81ce3db38490bcfd5de230f605086cc3df06c", "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.2, "max_line_length": 116, "alphanum_fraction": 0.7253064167, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4854702518429226}}
{"text": "{-# LANGUAGE CPP                       #-}\n{-# LANGUAGE BangPatterns              #-}\n{-# LANGUAGE DataKinds                 #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE FlexibleContexts          #-}\n{-# LANGUAGE GADTs                     #-}\n{-# LANGUAGE RankNTypes                #-}\n{-# LANGUAGE ScopedTypeVariables       #-}\n{-# LANGUAGE TypeFamilies              #-}\n\nimport           Control.Applicative\nimport           Control.Monad.Random\nimport           Options.Applicative\n\nimport           Data.Function                (on)\nimport           Data.List\n\nimport           Graphics.Image               hiding (map, on)\n\nimport qualified Numeric.LinearAlgebra        as LA\nimport qualified Numeric.LinearAlgebra.Static as H\n\nimport           Grenade\nimport           Grenade.Utils.ImageNet\n\n\ndata ResNetOptions = ResNetOptions FilePath         -- onnx file\n                                   FilePath         -- input image\n\npResnet :: Parser ResNetOptions\npResnet = ResNetOptions <$> argument str (metavar \"onnx\") <*> argument str (metavar \"image\")\n\n-- loadResNetImage :: FilePath -> IO (Maybe (S ('D3 224 224 3)))\nloadResNetImage :: FilePath -> IO (Maybe (S ('D3 224 224 3)))\nloadResNetImage path = do\n  img <- readImageRGB VU path\n  displayImage img\n  return $ do\n    guard $ dims img == (224, 224)\n    let [img_red, img_green, img_blue] = toImagesX img\n        [reds, greens, blues]          = map (map (\\(PixelX y) -> doubleToRealNum y) . concat . toLists) [img_red, img_green, img_blue]\n\n        redM   = H.dmmap (\\a -> (a - 0.485) / 0.229) . H.tr $ H.fromList reds   :: H.L 224 224\n        greenM = H.dmmap (\\a -> (a - 0.456) / 0.224) . H.tr $ H.fromList greens :: H.L 224 224\n        blueM  = H.dmmap (\\a -> (a - 0.406) / 0.225) . H.tr $ H.fromList blues  :: H.L 224 224\n        mat    = redM H.=== greenM H.=== blueM\n\n    return (S3D mat)\n\nmain :: IO ()\nmain = do\n    ResNetOptions netPath imgPath <- execParser (info (pResnet <**> helper) idm)\n    res <- loadResNet netPath\n\n    inputM <- loadResNetImage imgPath\n\n    case (res, inputM) of\n      (Right net, Just input)  -> do\n        let S1D y = runNet net input\n            tops  = getTop 5 $ LA.toList $ H.extract y\n        mapM_ (\\(i :: Int, x) -> print $ show i ++ \": \" ++ (show . getLabel) x) $ zip [1..] tops\n      (Left err, _) -> print err\n      _             -> error \"Could not load image\"\n  where\n    getTop :: Ord a => Int -> [a] -> [Int]\n    getTop n xs = map fst $ take n $ sortBy (flip compare `on` snd) $ zip [0..] xs\n", "meta": {"hexsha": "c0428471ae0a215fd0f453990edb694565cf406d", "size": 2518, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/resnet.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "examples/main/resnet.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/main/resnet.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5820895522, "max_line_length": 135, "alphanum_fraction": 0.5555996823, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4849925295258425}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DeriveGeneric         #-}\n{-# LANGUAGE DerivingStrategies    #-}\n{-# LANGUAGE DerivingVia           #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RecordWildCards       #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TemplateHaskell       #-}\n{-# LANGUAGE TupleSections         #-}\n{-# LANGUAGE TypeApplications      #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-# LANGUAGE ViewPatterns          #-}\n{-# OPTIONS_GHC -fno-warn-orphans  #-}\n\nimport           Control.DeepSeq\nimport           Control.Lens hiding                          ((<.>))\nimport           Control.Monad.Primitive\nimport           Control.Monad.Trans.Maybe\nimport           Data.Bitraversable\nimport           Data.Default\nimport           Data.IDX\nimport           Data.Mutable\nimport           Data.Traversable\nimport           Data.Tuple\nimport           GHC.Generics                                 (Generic)\nimport           GHC.TypeLits\nimport           Numeric.Backprop hiding                      (auto)\nimport           Numeric.LinearAlgebra.Static.Backprop hiding ((<>))\nimport           Numeric.OneLiner\nimport           Numeric.Opto hiding                          ((<.>))\nimport           Numeric.Opto.Backprop\nimport           Numeric.Opto.Run.Simple\nimport           Options.Applicative\nimport           System.FilePath hiding                       ((<.>))\nimport           Text.Printf\nimport qualified Data.Vector.Generic                          as VG\nimport qualified Numeric.LinearAlgebra                        as HM\nimport qualified Numeric.LinearAlgebra.Static                 as H\nimport qualified System.Random.MWC                            as MWC\n\ndata OMode = OSingle\n           | OParallel Bool Int\n\ndata Opts = Opts\n    { oDataDir :: FilePath\n    , oReport  :: Int\n    , oBatch   :: Int\n    , oMode    :: OMode\n    }\n\nparseOMode :: Parser OMode\nparseOMode = subparser\n    ( command \"single\" (info (pure OSingle) (progDesc \"Single-threaded\"))\n   <> command \"parallel\" (info (uncurry OParallel <$> parseParallel) (progDesc \"Parallel\"))\n    )\n  where\n    parseParallel :: Parser (Bool, Int)\n    parseParallel = (,)\n        <$> switch (long \"chunked\" <> help \"Chunked mode\")\n        <*> option auto\n                ( long \"split\"\n               <> short 's'\n               <> help \"Number of items per thread\"\n               <> metavar \"INT\"\n               <> showDefault\n               <> value 750\n                )\n\nparseOpts :: Parser Opts\nparseOpts = Opts\n    <$> strArgument ( help \"Data directory (containing uncompressed MNIST data set)\"\n                   <> metavar \"DIR\"\n                    )\n    <*> option auto\n          ( long \"report\"\n         <> short 'r'\n         <> help \"Report frequency (in batches)\"\n         <> metavar \"INT\"\n         <> showDefault\n         <> value 2500\n          )\n    <*> option auto\n          ( long \"batch\"\n         <> short 'b'\n         <> help \"Batching amount\"\n         <> metavar \"INT\"\n         <> showDefault\n         <> value 1\n          )\n    <*> (parseOMode <|> pure OSingle)\n\ndata Net = N { _weights1 :: !(L 250 784)\n             , _bias1    :: !(R 250)\n             , _weights2 :: !(L 10 250)\n             , _bias2    :: !(R 10)\n             }\n  deriving (Generic)\n  deriving (Num, Fractional, Floating) via (GNum Net)\nmakeLenses ''Net\n\ninstance Linear Double Net\ninstance Mutable q Net\ninstance LinearInPlace q Double Net\n\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n\nsoftMax\n    :: Reifies s W\n    => BVar s (R 10)\n    -> BVar s (R 10)\nsoftMax x = expx / konst (norm_1V expx)\n  where\n    expx = exp x\n\ncrossEntropy\n    :: Reifies s W\n    => BVar s (R 10)\n    -> BVar s (R 10)\n    -> BVar s Double\ncrossEntropy targ res = -(log res <.> targ)\n\nrunNet\n    :: Reifies s W\n    => BVar s Net\n    -> BVar s (R 784)\n    -> BVar s (R 10)\nrunNet n x = z\n  where\n    y = logistic $ (n ^^. weights1) #> x + (n ^^. bias1)\n    z = softMax  $ (n ^^. weights2) #> y + (n ^^. bias2)\n\nnetErr\n    :: Reifies s W\n    => BVar s (R 784)\n    -> BVar s (R 10)\n    -> BVar s Net\n    -> BVar s Double\nnetErr x targ n = crossEntropy targ (runNet n x)\n\n-- *********************************************\n-- Plumbing for running the network on real data\n-- *********************************************\n\nmain :: IO ()\nmain = MWC.withSystemRandom $ \\g -> do\n    Opts{..} <- execParser $ info (parseOpts <**> helper)\n        ( fullDesc\n       <> progDesc \"Run optimizer samples on MNIST\"\n       <> header \"opto-neural - opto runner on MNIST data set\"\n        )\n\n    Just train <- loadMNIST (oDataDir </> \"train-images-idx3-ubyte\")\n                            (oDataDir </> \"train-labels-idx1-ubyte\")\n    Just test  <- loadMNIST (oDataDir </> \"t10k-images-idx3-ubyte\")\n                            (oDataDir </> \"t10k-labels-idx1-ubyte\")\n    putStrLn \"Loaded data.\"\n    net0 <- MWC.uniformR (-0.5, 0.5) g\n\n    let o :: Opto (PrimState IO) (R 784, R 10) Net\n        o = adam def $\n              bpGradSample $ \\(x, y) -> netErr (constVar x) (constVar y)\n\n        runTest chnk net = printf \"Error: %.2f%%\" ((1 - score) * 100)\n          where\n            score = testNet chnk net\n\n        ro = def { roBatch = oBatch\n                 }\n        so = def { soTestSet   = Just test\n                 , soEvaluate  = runTest\n                 , soSkipSamps = oReport\n                 }\n\n    case oMode of\n      OSingle       -> simpleRunner so train SOSingle ro net0 o g\n      OParallel c s -> do\n        let po = def { poSplit = s }\n        if c\n          then simpleRunner so train (SOParallel   po) ro net0 o g\n          else simpleRunner so train (SOParChunked po) ro net0 o g\n\ntestNet :: [(R 784, R 10)] -> Net -> Double\ntestNet xs n = sum (map (uncurry test) xs) / fromIntegral (length xs)\n  where\n    test x (H.extract->t)\n        | HM.maxIndex t == HM.maxIndex (H.extract r) = 1\n        | otherwise                                  = 0\n      where\n        r = evalBP (`runNet` constVar x) n\n\nloadMNIST\n    :: FilePath\n    -> FilePath\n    -> IO (Maybe [(R 784, R 10)])\nloadMNIST fpI fpL = runMaybeT $ do\n    i <- MaybeT          $ decodeIDXFile       fpI\n    l <- MaybeT          $ decodeIDXLabelsFile fpL\n    d <- MaybeT . return $ labeledIntData l i\n    MaybeT . return $ for d (bitraverse mkImage mkLabel . swap)\n  where\n    mkImage = H.create . VG.convert . VG.map (\\i -> fromIntegral i / 255)\n    mkLabel n = H.create $ HM.build 10 (\\i -> if round i == n then 1 else 0)\n\ninstance KnownNat n => MWC.Variate (R n) where\n    uniform g = H.randomVector <$> MWC.uniform g <*> pure H.Uniform\n    uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance (KnownNat m, KnownNat n) => MWC.Variate (L m n) where\n    uniform g = H.uniformSample <$> MWC.uniform g <*> pure 0 <*> pure 1\n    uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance MWC.Variate Net where\n    uniform g = N <$> MWC.uniform g\n                  <*> MWC.uniform g\n                  <*> MWC.uniform g\n                  <*> MWC.uniform g\n    uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance NFData Net\n\ninstance Backprop Net\n", "meta": {"hexsha": "0f358ae5cfcacc066eac1bc1de333a3f0a7e1599", "size": 7304, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/opto-neural.hs", "max_stars_repo_name": "mstksg/opto", "max_stars_repo_head_hexsha": "ffdd862e858cd00581eee3b0b81e07d80d617cff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-01-23T06:32:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:23.000Z", "max_issues_repo_path": "app/opto-neural.hs", "max_issues_repo_name": "mstksg/opto", "max_issues_repo_head_hexsha": "ffdd862e858cd00581eee3b0b81e07d80d617cff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T00:08:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-05T02:10:12.000Z", "max_forks_repo_path": "app/opto-neural.hs", "max_forks_repo_name": "mstksg/opto", "max_forks_repo_head_hexsha": "ffdd862e858cd00581eee3b0b81e07d80d617cff", "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.1762114537, "max_line_length": 91, "alphanum_fraction": 0.5250547645, "num_tokens": 1937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.48494247431981047}}
{"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE UndecidableInstances #-}\n\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Numeric.ContainerBoot\n-- Copyright   :  (c) Alberto Ruiz 2010\n-- License     :  GPL-style\n--\n-- Maintainer  :  Alberto Ruiz <aruiz@um.es>\n-- Stability   :  provisional\n-- Portability :  portable\n--\n-- Module to avoid cyclyc dependencies.\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.ContainerBoot (\n    -- * Basic functions\n    ident, diag, ctrans,\n    -- * Generic operations\n    Container(..),\n    -- * Matrix product and related functions\n    Product(..),\n    mXm,mXv,vXm,\n    outer, kronecker,\n    -- * Element conversion\n    Convert(..),\n    Complexable(),\n    RealElement(),\n\n    RealOf, ComplexOf, SingleOf, DoubleOf,\n\n    IndexOf,\n    module Data.Complex,\n    -- * Experimental\n    build', konst'\n) where\n\nimport Data.Packed\nimport Data.Packed.ST as ST\nimport Numeric.Conversion\nimport Data.Packed.Internal\nimport Numeric.GSL.Vector\nimport Data.Complex\nimport Control.Monad(ap)\n\nimport Numeric.LinearAlgebra.LAPACK(multiplyR,multiplyC,multiplyF,multiplyQ)\n\n-------------------------------------------------------------------\n\ntype family IndexOf (c :: * -> *)\n\ntype instance IndexOf Vector = Int\ntype instance IndexOf Matrix = (Int,Int)\n\ntype family ArgOf (c :: * -> *) a\n\ntype instance ArgOf Vector a = a -> a\ntype instance ArgOf Matrix a = a -> a -> a\n\n-------------------------------------------------------------------\n\n-- | Basic element-by-element functions for numeric containers\nclass (Complexable c, Fractional e, Element e) => Container c e where\n    -- | create a structure with a single element\n    scalar      :: e -> c e\n    -- | complex conjugate\n    conj        :: c e -> c e\n    scale       :: e -> c e -> c e\n    -- | scale the element by element reciprocal of the object:\n    --\n    -- @scaleRecip 2 (fromList [5,i]) == 2 |> [0.4 :+ 0.0,0.0 :+ (-2.0)]@\n    scaleRecip  :: e -> c e -> c e\n    addConstant :: e -> c e -> c e\n    add         :: c e -> c e -> c e\n    sub         :: c e -> c e -> c e\n    -- | element by element multiplication\n    mul         :: c e -> c e -> c e\n    -- | element by element division\n    divide      :: c e -> c e -> c e\n    equal       :: c e -> c e -> Bool\n    --\n    -- element by element inverse tangent\n    arctan2     :: c e -> c e -> c e\n    --\n    -- | cannot implement instance Functor because of Element class constraint\n    cmap        :: (Element b) => (e -> b) -> c e -> c b\n    -- | constant structure of given size\n    konst       :: e -> IndexOf c -> c e\n    -- | create a structure using a function\n    --\n    -- Hilbert matrix of order N:\n    --\n    -- @hilb n = build (n,n) (\\\\i j -> 1/(i+j+1))@\n    build       :: IndexOf c -> (ArgOf c e) -> c e\n    --build       :: BoundsOf f -> f -> (ContainerOf f) e\n    --\n    -- | indexing function\n    atIndex     :: c e -> IndexOf c -> e\n    -- | index of min element\n    minIndex    :: c e -> IndexOf c\n    -- | index of max element\n    maxIndex    :: c e -> IndexOf c\n    -- | value of min element\n    minElement  :: c e -> e\n    -- | value of max element\n    maxElement  :: c e -> e\n    -- the C functions sumX/prodX are twice as fast as using foldVector\n    -- | the sum of elements (faster than using @fold@)\n    sumElements :: c e -> e\n    -- | the product of elements (faster than using @fold@)\n    prodElements :: c e -> e\n\n    -- | A more efficient implementation of @cmap (\\\\x -> if x>0 then 1 else 0)@\n    --\n    -- @> step $ linspace 5 (-1,1::Double)\n    -- 5 |> [0.0,0.0,0.0,1.0,1.0]@\n    \n    step :: RealElement e => c e -> c e\n\n    -- | Element by element version of @case compare a b of {LT -> l; EQ -> e; GT -> g}@.\n    --\n    -- Arguments with any dimension = 1 are automatically expanded: \n    --\n    -- @> cond ((1>\\<4)[1..]) ((3>\\<1)[1..]) 0 100 ((3>\\<4)[1..]) :: Matrix Double\n    -- (3><4)\n    -- [ 100.0,   2.0,   3.0,  4.0\n    -- ,   0.0, 100.0,   7.0,  8.0\n    -- ,   0.0,   0.0, 100.0, 12.0 ]@\n    \n    cond :: RealElement e \n         => c e -- ^ a\n         -> c e -- ^ b\n         -> c e -- ^ l \n         -> c e -- ^ e\n         -> c e -- ^ g\n         -> c e -- ^ result\n\n    -- | Find index of elements which satisfy a predicate\n    --\n    -- @> find (>0) (ident 3 :: Matrix Double)\n    -- [(0,0),(1,1),(2,2)]@\n\n    find :: (e -> Bool) -> c e -> [IndexOf c]\n\n    -- | Create a structure from an association list\n    --\n    -- @> assoc 5 0 [(2,7),(1,3)] :: Vector Double\n    -- 5 |> [0.0,3.0,7.0,0.0,0.0]@\n    \n    assoc :: IndexOf c        -- ^ size\n          -> e                -- ^ default value\n          -> [(IndexOf c, e)] -- ^ association list\n          -> c e              -- ^ result\n\n    -- | Modify a structure using an update function\n    --\n    -- @> accum (ident 5) (+) [((1,1),5),((0,3),3)] :: Matrix Double\n    -- (5><5)\n    --  [ 1.0, 0.0, 0.0, 3.0, 0.0\n    --  , 0.0, 6.0, 0.0, 0.0, 0.0\n    --  , 0.0, 0.0, 1.0, 0.0, 0.0\n    --  , 0.0, 0.0, 0.0, 1.0, 0.0\n    --  , 0.0, 0.0, 0.0, 0.0, 1.0 ]@\n    \n    accum :: c e              -- ^ initial structure\n          -> (e -> e -> e)    -- ^ update function\n          -> [(IndexOf c, e)] -- ^ association list\n          -> c e              -- ^ result\n\n--------------------------------------------------------------------------\n\ninstance Container Vector Float where\n    scale = vectorMapValF Scale\n    scaleRecip = vectorMapValF Recip\n    addConstant = vectorMapValF AddConstant\n    add = vectorZipF Add\n    sub = vectorZipF Sub\n    mul = vectorZipF Mul\n    divide = vectorZipF Div\n    equal u v = dim u == dim v && maxElement (vectorMapF Abs (sub u v)) == 0.0\n    arctan2 = vectorZipF ATan2\n    scalar x = fromList [x]\n    konst = constantD\n    build = buildV\n    conj = id\n    cmap = mapVector\n    atIndex = (@>)\n    minIndex     = round . toScalarF MinIdx\n    maxIndex     = round . toScalarF MaxIdx\n    minElement  = toScalarF Min\n    maxElement  = toScalarF Max\n    sumElements  = sumF\n    prodElements = prodF\n    step = stepF\n    find = findV\n    assoc = assocV\n    accum = accumV\n    cond = condV condF\n\ninstance Container Vector Double where\n    scale = vectorMapValR Scale\n    scaleRecip = vectorMapValR Recip\n    addConstant = vectorMapValR AddConstant\n    add = vectorZipR Add\n    sub = vectorZipR Sub\n    mul = vectorZipR Mul\n    divide = vectorZipR Div\n    equal u v = dim u == dim v && maxElement (vectorMapR Abs (sub u v)) == 0.0\n    arctan2 = vectorZipR ATan2\n    scalar x = fromList [x]\n    konst = constantD\n    build = buildV\n    conj = id\n    cmap = mapVector\n    atIndex = (@>)\n    minIndex     = round . toScalarR MinIdx\n    maxIndex     = round . toScalarR MaxIdx\n    minElement  = toScalarR Min\n    maxElement  = toScalarR Max\n    sumElements  = sumR\n    prodElements = prodR\n    step = stepD\n    find = findV\n    assoc = assocV\n    accum = accumV\n    cond = condV condD\n\ninstance Container Vector (Complex Double) where\n    scale = vectorMapValC Scale\n    scaleRecip = vectorMapValC Recip\n    addConstant = vectorMapValC AddConstant\n    add = vectorZipC Add\n    sub = vectorZipC Sub\n    mul = vectorZipC Mul\n    divide = vectorZipC Div\n    equal u v = dim u == dim v && maxElement (mapVector magnitude (sub u v)) == 0.0\n    arctan2 = vectorZipC ATan2\n    scalar x = fromList [x]\n    konst = constantD\n    build = buildV\n    conj = conjugateC\n    cmap = mapVector\n    atIndex = (@>)\n    minIndex     = minIndex . fst . fromComplex . (zipVectorWith (*) `ap` mapVector conjugate)\n    maxIndex     = maxIndex . fst . fromComplex . (zipVectorWith (*) `ap` mapVector conjugate)\n    minElement  = ap (@>) minIndex\n    maxElement  = ap (@>) maxIndex\n    sumElements  = sumC\n    prodElements = prodC\n    step = undefined -- cannot match\n    find = findV\n    assoc = assocV\n    accum = accumV\n    cond = undefined -- cannot match\n\ninstance Container Vector (Complex Float) where\n    scale = vectorMapValQ Scale\n    scaleRecip = vectorMapValQ Recip\n    addConstant = vectorMapValQ AddConstant\n    add = vectorZipQ Add\n    sub = vectorZipQ Sub\n    mul = vectorZipQ Mul\n    divide = vectorZipQ Div\n    equal u v = dim u == dim v && maxElement (mapVector magnitude (sub u v)) == 0.0\n    arctan2 = vectorZipQ ATan2\n    scalar x = fromList [x]\n    konst = constantD\n    build = buildV\n    conj = conjugateQ\n    cmap = mapVector\n    atIndex = (@>)\n    minIndex     = minIndex . fst . fromComplex . (zipVectorWith (*) `ap` mapVector conjugate)\n    maxIndex     = maxIndex . fst . fromComplex . (zipVectorWith (*) `ap` mapVector conjugate)\n    minElement  = ap (@>) minIndex\n    maxElement  = ap (@>) maxIndex\n    sumElements  = sumQ\n    prodElements = prodQ\n    step = undefined -- cannot match\n    find = findV\n    assoc = assocV\n    accum = accumV\n    cond = undefined -- cannot match\n\n---------------------------------------------------------------\n\ninstance (Container Vector a) => Container Matrix a where\n    scale x = liftMatrix (scale x)\n    scaleRecip x = liftMatrix (scaleRecip x)\n    addConstant x = liftMatrix (addConstant x)\n    add = liftMatrix2 add\n    sub = liftMatrix2 sub\n    mul = liftMatrix2 mul\n    divide = liftMatrix2 divide\n    equal a b = cols a == cols b && flatten a `equal` flatten b\n    arctan2 = liftMatrix2 arctan2\n    scalar x = (1><1) [x]\n    konst v (r,c) = reshape c (konst v (r*c))\n    build = buildM\n    conj = liftMatrix conj\n    cmap f = liftMatrix (mapVector f)\n    atIndex = (@@>)\n    minIndex m = let (r,c) = (rows m,cols m)\n                     i = (minIndex $ flatten m)\n                 in (i `div` c,i `mod` c)\n    maxIndex m = let (r,c) = (rows m,cols m)\n                     i = (maxIndex $ flatten m)\n                 in (i `div` c,i `mod` c)\n    minElement = ap (@@>) minIndex\n    maxElement = ap (@@>) maxIndex\n    sumElements = sumElements . flatten\n    prodElements = prodElements . flatten\n    step = liftMatrix step\n    find = findM\n    assoc = assocM\n    accum = accumM\n    cond = condM\n\n----------------------------------------------------\n\n-- | Matrix product and related functions\nclass Element e => Product e where\n    -- | matrix product\n    multiply :: Matrix e -> Matrix e -> Matrix e\n    -- | dot (inner) product\n    dot        :: Vector e -> Vector e -> e\n    -- | sum of absolute value of elements (differs in complex case from @norm1@)\n    absSum     :: Vector e -> RealOf e\n    -- | sum of absolute value of elements\n    norm1      :: Vector e -> RealOf e\n    -- | euclidean norm\n    norm2      :: Vector e -> RealOf e\n    -- | element of maximum magnitude\n    normInf    :: Vector e -> RealOf e\n\ninstance Product Float where\n    norm2      = toScalarF Norm2\n    absSum     = toScalarF AbsSum\n    dot        = dotF\n    norm1      = toScalarF AbsSum\n    normInf    = maxElement . vectorMapF Abs\n    multiply = multiplyF\n\ninstance Product Double where\n    norm2      = toScalarR Norm2\n    absSum     = toScalarR AbsSum\n    dot        = dotR\n    norm1      = toScalarR AbsSum\n    normInf    = maxElement . vectorMapR Abs\n    multiply = multiplyR\n\ninstance Product (Complex Float) where\n    norm2      = toScalarQ Norm2\n    absSum     = toScalarQ AbsSum\n    dot        = dotQ\n    norm1      = sumElements . fst . fromComplex . vectorMapQ Abs\n    normInf    = maxElement . fst . fromComplex . vectorMapQ Abs\n    multiply = multiplyQ\n\ninstance Product (Complex Double) where\n    norm2      = toScalarC Norm2\n    absSum     = toScalarC AbsSum\n    dot        = dotC\n    norm1      = sumElements . fst . fromComplex . vectorMapC Abs\n    normInf    = maxElement . fst . fromComplex . vectorMapC Abs\n    multiply = multiplyC\n\n----------------------------------------------------------\n\n-- synonym for matrix product\nmXm :: Product t => Matrix t -> Matrix t -> Matrix t\nmXm = multiply\n\n-- matrix - vector product\nmXv :: Product t => Matrix t -> Vector t -> Vector t\nmXv m v = flatten $ m `mXm` (asColumn v)\n\n-- vector - matrix product\nvXm :: Product t => Vector t -> Matrix t -> Vector t\nvXm v m = flatten $ (asRow v) `mXm` m\n\n{- | Outer product of two vectors.\n\n@\\> 'fromList' [1,2,3] \\`outer\\` 'fromList' [5,2,3]\n(3><3)\n [  5.0, 2.0, 3.0\n , 10.0, 4.0, 6.0\n , 15.0, 6.0, 9.0 ]@\n-}\nouter :: (Product t) => Vector t -> Vector t -> Matrix t\nouter u v = asColumn u `multiply` asRow v\n\n{- | Kronecker product of two matrices.\n\n@m1=(2><3)\n [ 1.0,  2.0, 0.0\n , 0.0, -1.0, 3.0 ]\nm2=(4><3)\n [  1.0,  2.0,  3.0\n ,  4.0,  5.0,  6.0\n ,  7.0,  8.0,  9.0\n , 10.0, 11.0, 12.0 ]@\n\n@\\> kronecker m1 m2\n(8><9)\n [  1.0,  2.0,  3.0,   2.0,   4.0,   6.0,  0.0,  0.0,  0.0\n ,  4.0,  5.0,  6.0,   8.0,  10.0,  12.0,  0.0,  0.0,  0.0\n ,  7.0,  8.0,  9.0,  14.0,  16.0,  18.0,  0.0,  0.0,  0.0\n , 10.0, 11.0, 12.0,  20.0,  22.0,  24.0,  0.0,  0.0,  0.0\n ,  0.0,  0.0,  0.0,  -1.0,  -2.0,  -3.0,  3.0,  6.0,  9.0\n ,  0.0,  0.0,  0.0,  -4.0,  -5.0,  -6.0, 12.0, 15.0, 18.0\n ,  0.0,  0.0,  0.0,  -7.0,  -8.0,  -9.0, 21.0, 24.0, 27.0\n ,  0.0,  0.0,  0.0, -10.0, -11.0, -12.0, 30.0, 33.0, 36.0 ]@\n-}\nkronecker :: (Product t) => Matrix t -> Matrix t -> Matrix t\nkronecker a b = fromBlocks\n              . splitEvery (cols a)\n              . map (reshape (cols b))\n              . toRows\n              $ flatten a `outer` flatten b\n\n-------------------------------------------------------------------\n\n\nclass Convert t where\n    real    :: Container c t => c (RealOf t) -> c t\n    complex :: Container c t => c t -> c (ComplexOf t)\n    single  :: Container c t => c t -> c (SingleOf t)\n    double  :: Container c t => c t -> c (DoubleOf t)\n    toComplex   :: (Container c t, RealElement t) => (c t, c t) -> c (Complex t)\n    fromComplex :: (Container c t, RealElement t) => c (Complex t) -> (c t, c t)\n\n\ninstance Convert Double where\n    real = id\n    complex = comp'\n    single = single'\n    double = id\n    toComplex = toComplex'\n    fromComplex = fromComplex'\n\ninstance Convert Float where\n    real = id\n    complex = comp'\n    single = id\n    double = double'\n    toComplex = toComplex'\n    fromComplex = fromComplex'\n\ninstance Convert (Complex Double) where\n    real = comp'\n    complex = id\n    single = single'\n    double = id\n    toComplex = toComplex'\n    fromComplex = fromComplex'\n\ninstance Convert (Complex Float) where\n    real = comp'\n    complex = id\n    single = id\n    double = double'\n    toComplex = toComplex'\n    fromComplex = fromComplex'\n\n-------------------------------------------------------------------\n\ntype family RealOf x\n\ntype instance RealOf Double = Double\ntype instance RealOf (Complex Double) = Double\n\ntype instance RealOf Float = Float\ntype instance RealOf (Complex Float) = Float\n\ntype family ComplexOf x\n\ntype instance ComplexOf Double = Complex Double\ntype instance ComplexOf (Complex Double) = Complex Double\n\ntype instance ComplexOf Float = Complex Float\ntype instance ComplexOf (Complex Float) = Complex Float\n\ntype family SingleOf x\n\ntype instance SingleOf Double = Float\ntype instance SingleOf Float  = Float\n\ntype instance SingleOf (Complex a) = Complex (SingleOf a)\n\ntype family DoubleOf x\n\ntype instance DoubleOf Double = Double\ntype instance DoubleOf Float  = Double\n\ntype instance DoubleOf (Complex a) = Complex (DoubleOf a)\n\ntype family ElementOf c\n\ntype instance ElementOf (Vector a) = a\ntype instance ElementOf (Matrix a) = a\n\n------------------------------------------------------------\n\nclass Build f where\n    build' :: BoundsOf f -> f -> ContainerOf f\n\ntype family BoundsOf x\n\ntype instance BoundsOf (a->a) = Int\ntype instance BoundsOf (a->a->a) = (Int,Int)\n\ntype family ContainerOf x\n\ntype instance ContainerOf (a->a) = Vector a\ntype instance ContainerOf (a->a->a) = Matrix a\n\ninstance (Element a, Num a) => Build (a->a) where\n    build' = buildV\n\ninstance (Element a, Num a) => Build (a->a->a) where\n    build' = buildM\n\nbuildM (rc,cc) f = fromLists [ [f r c | c <- cs] | r <- rs ]\n    where rs = map fromIntegral [0 .. (rc-1)]\n          cs = map fromIntegral [0 .. (cc-1)]\n\nbuildV n f = fromList [f k | k <- ks]\n    where ks = map fromIntegral [0 .. (n-1)]\n\n----------------------------------------------------\n-- experimental\n\nclass Konst s where\n    konst' :: Element e => e -> s -> ContainerOf' s e\n\ntype family ContainerOf' x y\n\ntype instance ContainerOf' Int a = Vector a\ntype instance ContainerOf' (Int,Int) a = Matrix a\n\ninstance Konst Int where\n    konst' = constantD\n\ninstance Konst (Int,Int) where\n    konst' k (r,c) = reshape c $ konst' k (r*c)\n\n--------------------------------------------------------\n-- | conjugate transpose\nctrans :: (Container Vector e, Element e) => Matrix e -> Matrix e\nctrans = liftMatrix conj . trans\n\n-- | Creates a square matrix with a given diagonal.\ndiag :: (Num a, Element a) => Vector a -> Matrix a\ndiag v = diagRect 0 v n n where n = dim v\n\n-- | creates the identity matrix of given dimension\nident :: (Num a, Element a) => Int -> Matrix a\nident n = diag (constantD 1 n)\n\n--------------------------------------------------------\n\nfindV p x = foldVectorWithIndex g [] x where\n    g k z l = if p z then k:l else l\n\nfindM p x = map ((`divMod` cols x)) $ findV p (flatten x)\n\nassocV n z xs = ST.runSTVector $ do\n        v <- ST.newVector z n\n        mapM_ (\\(k,x) -> ST.writeVector v k x) xs\n        return v\n\nassocM (r,c) z xs = ST.runSTMatrix $ do\n        m <- ST.newMatrix z r c\n        mapM_ (\\((i,j),x) -> ST.writeMatrix m i j x) xs\n        return m\n\naccumV v0 f xs = ST.runSTVector $ do\n        v <- ST.thawVector v0\n        mapM_ (\\(k,x) -> ST.modifyVector v k (f x)) xs\n        return v\n\naccumM m0 f xs = ST.runSTMatrix $ do\n        m <- ST.thawMatrix m0\n        mapM_ (\\((i,j),x) -> ST.modifyMatrix m i j (f x)) xs\n        return m\n\n----------------------------------------------------------------------\n\ncondM a b l e t = reshape (cols a'') $ cond a' b' l' e' t'\n  where\n    args@(a'':_) = conformMs [a,b,l,e,t]\n    [a', b', l', e', t'] = map flatten args\n\ncondV f a b l e t = f a' b' l' e' t'\n  where\n    [a', b', l', e', t'] = conformVs [a,b,l,e,t]\n\n", "meta": {"hexsha": "d50dd36d1672cab0e67aba91c0010d516bcd20a2", "size": 18054, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/ContainerBoot.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/ContainerBoot.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/ContainerBoot.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": 29.8907284768, "max_line_length": 94, "alphanum_fraction": 0.5514013515, "num_tokens": 5638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4846469094221983}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes, DataKinds, RankNTypes, TypeFamilies,\n             TypeOperators #-}\n{-# OPTIONS_GHC -Wno-missing-export-lists #-}\n{-# OPTIONS_GHC -fconstraint-solver-iterations=16 #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n-- | Shaped tensor-based implementation of Convolutional Neural Network\n-- for classification of MNIST digits. Sports 2 hidden layers.\nmodule HordeAd.Tool.MnistCnnShaped where\n\nimport Prelude\n\nimport qualified Data.Array.DynamicS as OT\nimport           Data.Array.Internal (valueOf)\nimport qualified Data.Array.Shape\nimport qualified Data.Array.ShapedS as OS\nimport           Data.Proxy (Proxy)\nimport qualified Data.Vector.Generic as V\nimport           GHC.TypeLits (KnownNat, type (+), type (<=), type Div)\nimport qualified Numeric.LinearAlgebra as HM\n\n-- until stylish-haskell accepts NoStarIsType\nimport qualified GHC.TypeLits\n\nimport HordeAd.Core.DualNumber\nimport HordeAd.Core.Engine\nimport HordeAd.Core.PairOfVectors (DualNumberVariables, varS)\nimport HordeAd.Tool.MnistData\n\nconvMnistLayerS\n  :: forall kheight_minus_1 kwidth_minus_1 out_channels\n            in_height in_width in_channels batch_size d r m.\n     ( KnownNat kheight_minus_1, KnownNat kwidth_minus_1, KnownNat out_channels\n     , KnownNat in_height, KnownNat in_width\n     , KnownNat in_channels, KnownNat batch_size\n     , 1 <= kheight_minus_1\n     , 1 <= kwidth_minus_1  -- wrongly reported as redundant\n     , DualMonad d r m )\n  => DualNumber d (OS.Array '[ out_channels, in_channels\n                             , kheight_minus_1 + 1, kwidth_minus_1 + 1 ] r)\n  -> DualNumber d (OS.Array '[batch_size, in_channels, in_height, in_width] r)\n  -> DualNumber d (OS.Array '[out_channels] r)\n  -> m (DualNumber d (OS.Array '[ batch_size, out_channels\n                                , (in_height + kheight_minus_1) `Div` 2\n                                , (in_width + kwidth_minus_1) `Div` 2 ] r))\nconvMnistLayerS ker x bias = do\n  let yConv = conv24 ker x\n      replicateBias\n        :: DualNumber d (OS.Array '[] r)\n        -> DualNumber d (OS.Array '[ in_height + kheight_minus_1\n                                   , in_width + kwidth_minus_1 ] r)\n      replicateBias = konstS . fromS0\n      biasStretched = ravelFromListS\n                      $ replicate (valueOf @batch_size)\n                      $ mapS replicateBias bias\n        -- TODO: this is weakly typed; add and use replicateS instead\n        -- or broadcastS or stretchS, possibly with transposeS?\n  yRelu <- reluAct $ yConv + biasStretched\n  maxPool24 @1 @2 yRelu\n\n\nconvMnistTwoS\n  :: forall kheight_minus_1 kwidth_minus_1 num_hidden out_channels\n            in_height in_width in_channels batch_size d r m.\n     ( KnownNat kheight_minus_1, KnownNat kwidth_minus_1\n     , KnownNat num_hidden, KnownNat out_channels\n     , KnownNat in_height, KnownNat in_width, KnownNat batch_size\n     , in_channels ~ 1\n     , 1 <= kheight_minus_1\n     , 1 <= kwidth_minus_1\n     , DualMonad d r m )\n  => OS.Array '[batch_size, in_channels, in_height, in_width] r\n  -- All below is the type of all paramters of this nn. The same is reflected\n  -- in the length function below and read from variables further down.\n  -> DualNumber d (OS.Array '[ out_channels, in_channels\n                             , kheight_minus_1 + 1, kwidth_minus_1 + 1 ] r)\n  -> DualNumber d (OS.Array '[out_channels] r)\n  -> DualNumber d (OS.Array '[ out_channels, out_channels\n                             , kheight_minus_1 + 1, kwidth_minus_1 + 1 ] r)\n  -> DualNumber d (OS.Array '[out_channels] r)\n  -> DualNumber d (OS.Array '[ num_hidden\n                             , out_channels\n                                 GHC.TypeLits.*\n                                   (((in_height + kheight_minus_1) `Div` 2\n                                     + kheight_minus_1) `Div` 2)\n                                 GHC.TypeLits.*\n                                   (((in_width + kwidth_minus_1) `Div` 2\n                                     + kwidth_minus_1) `Div` 2)\n                             ] r)\n  -> DualNumber d (OS.Array '[num_hidden] r)\n  -> DualNumber d (OS.Array '[SizeMnistLabel, num_hidden] r)\n  -> DualNumber d (OS.Array '[SizeMnistLabel] r)\n  -> m (DualNumber d (OS.Array '[SizeMnistLabel, batch_size] r))\nconvMnistTwoS x ker1 bias1 ker2 bias2\n              weigthsDense biasesDense weigthsReadout biasesReadout = do\n  t1 <- convMnistLayerS ker1 (constant x) bias1\n  t2 <- convMnistLayerS ker2 t1 bias2\n  let m1 = mapS reshapeS t2\n      m2 = transpose2S m1\n      denseLayer = weigthsDense <>$ m2 + asColumnS biasesDense\n  denseRelu <- reluAct denseLayer\n  returnLet $ weigthsReadout <>$ denseRelu + asColumnS biasesReadout\n\nconvMnistLenS\n  :: forall kheight_minus_1 kwidth_minus_1 num_hidden out_channels\n            in_height in_width.\n     ( KnownNat kheight_minus_1, KnownNat kwidth_minus_1\n     , KnownNat num_hidden, KnownNat out_channels\n     , KnownNat in_height, KnownNat in_width )\n  => Proxy kheight_minus_1\n  -> Proxy kwidth_minus_1\n  -> Proxy num_hidden\n  -> Proxy out_channels\n  -> Proxy in_height\n  -> Proxy in_width\n  -> (Int, [Int], [(Int, Int)], [OT.ShapeL])\nconvMnistLenS _ _ _ _ _ _ =\n  ( 0\n  , []\n  , []\n  , [ Data.Array.Shape.shapeT @'[ out_channels, 1\n                                , kheight_minus_1 + 1, kwidth_minus_1 + 1 ]\n    , Data.Array.Shape.shapeT @'[out_channels]\n    , Data.Array.Shape.shapeT @'[ out_channels, out_channels\n                                , kheight_minus_1 + 1, kwidth_minus_1 + 1 ]\n    , Data.Array.Shape.shapeT @'[out_channels]\n    , Data.Array.Shape.shapeT @'[ num_hidden\n                                , out_channels\n                                    GHC.TypeLits.*\n                                      ((in_height + kheight_minus_1) `Div` 2\n                                       + kheight_minus_1) `Div` 2\n                                    GHC.TypeLits.*\n                                      ((in_width + kwidth_minus_1) `Div` 2\n                                       + kheight_minus_1) `Div` 2\n                                ]\n    , Data.Array.Shape.shapeT @'[num_hidden]\n    , Data.Array.Shape.shapeT @'[SizeMnistLabel, num_hidden]\n    , Data.Array.Shape.shapeT @'[SizeMnistLabel]\n    ]\n  )\n\nconvMnistS\n  :: forall kheight_minus_1 kwidth_minus_1 num_hidden out_channels\n            in_height in_width batch_size d r m.\n     ( KnownNat kheight_minus_1, KnownNat kwidth_minus_1\n     , KnownNat num_hidden, KnownNat out_channels\n     , KnownNat in_height, KnownNat in_width, KnownNat batch_size\n     , 1 <= kheight_minus_1\n     , 1 <= kwidth_minus_1\n     , DualMonad d r m )\n  => OS.Array '[batch_size, 1, in_height, in_width] r\n  -> DualNumberVariables d r\n  -> m (DualNumber d (OS.Array '[SizeMnistLabel, batch_size] r))\nconvMnistS x variables = do\n  let ker1 = varS variables 0\n      bias1 = varS variables 1\n      ker2 = varS variables 2\n      bias2 = varS variables 3\n      weigthsDense = varS variables 4\n      biasesDense = varS variables 5\n      weigthsReadout = varS variables 6\n      biasesReadout = varS variables 7\n  convMnistTwoS @kheight_minus_1 @kwidth_minus_1 @num_hidden @out_channels\n                x ker1 bias1 ker2 bias2\n                weigthsDense biasesDense weigthsReadout biasesReadout\n\nconvMnistLossFusedS\n  :: forall kheight_minus_1 kwidth_minus_1 num_hidden out_channels\n            in_height in_width batch_size d r m.\n     ( KnownNat kheight_minus_1, KnownNat kwidth_minus_1\n     , KnownNat num_hidden, KnownNat out_channels\n     , KnownNat in_height, KnownNat in_width, KnownNat batch_size\n     , 1 <= kheight_minus_1\n     , 1 <= kwidth_minus_1\n     , DualMonad d r m )\n  => Proxy kheight_minus_1\n  -> Proxy kwidth_minus_1\n  -> Proxy num_hidden\n  -> Proxy out_channels\n  -> ( OS.Array '[batch_size, in_height, in_width] r\n     , OS.Array '[batch_size, SizeMnistLabel] r )\n  -> DualNumberVariables d r\n  -> m (DualNumber d r)\nconvMnistLossFusedS _ _ _ _ (glyphS, labelS) variables = do\n  let xs :: OS.Array '[batch_size, 1, in_height, in_width] r\n      xs = OS.reshape glyphS\n  result <- convMnistS @kheight_minus_1 @kwidth_minus_1\n                       @num_hidden @out_channels\n                       xs variables\n  let targets2 = HM.tr $ HM.reshape (valueOf @SizeMnistLabel)\n                       $ OS.toVector labelS\n  vec <- lossSoftMaxCrossEntropyL targets2 (fromS2 result)\n  returnLet $ scale (recip $ fromIntegral (valueOf @batch_size :: Int))\n            $ sumElements0 vec\n\n-- For simplicity, testing is performed in mini-batches of 1.\n-- See RNN for testing done in batches.\nconvMnistTestS\n  :: forall kheight_minus_1 kwidth_minus_1 num_hidden out_channels\n            in_height in_width r.\n     ( KnownNat kheight_minus_1, KnownNat kwidth_minus_1\n     , KnownNat num_hidden, KnownNat out_channels\n     , KnownNat in_height, KnownNat in_width\n     , 1 <= kheight_minus_1\n     , 1 <= kwidth_minus_1\n     , IsScalar 'DModeGradient r )\n  => Proxy r\n  -> Proxy kheight_minus_1\n  -> Proxy kwidth_minus_1\n  -> Proxy num_hidden\n  -> Proxy out_channels\n  -> [( OS.Array '[in_height, in_width] r\n      , OS.Array '[SizeMnistLabel] r )]\n  -> Domains r\n  -> r\nconvMnistTestS _ _ _ _ _ inputs parameters =\n  let matchesLabels :: ( OS.Array '[in_height, in_width] r\n                       , OS.Array '[SizeMnistLabel] r )\n                    -> Bool\n      matchesLabels (glyph, label) =\n        let tx :: OS.Array '[1, 1, in_height, in_width] r\n            tx = OS.reshape glyph\n            nn :: DualNumberVariables 'DModeGradient r\n               -> DualMonadValue r (DualNumber 'DModeGradient (OS.Array '[SizeMnistLabel, 1] r))\n            nn = convMnistS @kheight_minus_1 @kwidth_minus_1\n                            @num_hidden @out_channels\n                            tx\n            value = primalValue nn parameters\n        in V.maxIndex (OS.toVector value) == V.maxIndex (OS.toVector label)\n  in fromIntegral (length (filter matchesLabels inputs))\n     / fromIntegral (length inputs)\n", "meta": {"hexsha": "73e71d7d406c482c783437c5cfc421342ab1c084", "size": 10004, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Tool/MnistCnnShaped.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HordeAd/Tool/MnistCnnShaped.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "src/HordeAd/Tool/MnistCnnShaped.hs", "max_forks_repo_name": "Mikolaj/horde-ad", "max_forks_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1206896552, "max_line_length": 96, "alphanum_fraction": 0.6330467813, "num_tokens": 2704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4843583237427442}}
{"text": "{-# LANGUAGE DeriveFunctor #-}\nmodule Main where\n\nimport Lib\nimport Data.Complex\nimport Data.Fixed (mod')\nimport Linear.Vector\n\ndata ChebFun a = ChebFun {pow2 :: Int, coefficients :: [a] } deriving (Show, Functor)\n\n-- data SampleFun a = \n-- interpolate :: Vector a => SampleFun a -> (Circ -> a) -- need to use linear inteperpolation\n{-\ninstance Functor ChebFun where\n\tfmap f (ChebFun i cs) = ChebFun i (fmap f cs)\n-}\n\n{-\nzipWith' f dx dy (x : xs) (y : ys) = (f x y) : (zipWith' f dx dy xs ys)\nzipWith' f dx _ [] ys = map (f dx) ys\nzipWith' f _ dy xs [] = map (flip f dy) xs\n-}\n\nunionWith' f (x : xs) (y : ys) = (f x y) : (unionWith' f xs ys)\nunionWith' f [] ys = ys\nunionWith' f xs [] = xs\n\n-- Linear package makes scalar multiplication a piece of being a functor.\n-- I'm not sure I can make ChebFun a Functor? Well, it can be for the purposes of scalar multiply.\n-- But usually we need to FFT it to real space before applying pointwise stuff\n\ninstance Additive ChebFun where\n\tzero = ChebFun 0 []\n\tliftI2 f (ChebFun n xs) (ChebFun n' ys) = ChebFun (min n n') (zipWith f xs ys) \n\tliftU2 f (ChebFun n xs) (ChebFun n' ys) = ChebFun (max n n') (unionWith' f xs ys)\n\n-- intance Additive ChebFun where \n-- possible conventions: incorrect sized lists are error, everything past nil is 0, everything past last element is a repeat of last constant\n-- Last convention allows for efficient representation of constant values. A pure nil is represented as 0. case on (a:[])\n-- TrigFun is better name\n-- ChebFun b a where ChebFun (b ~ Circ, Num a) => \n\n-- compose\n-- Possible optimization\ndata Consty f a = NonConsty (f a) | Consty a \n\n{-\nwe can lift pointwise functions?\ncheblift\n\n\nalmost applicative, except that the object inside needs to be foureir transformable.\n\n\ninstance Applicative ChebFun where\n\tNum a b c => (a -> b -> c) -> ChebFun a -> ChebFun b -> ChebFun c\n\n\n\n-}\n-- chebcompose :: ChebFun Circ -> ChebFun Circ -> ChebFun Circ\n\n{-\ninstance Num a => Num (ChubFun a) where\n\t(ChebFun n xs) + (ChebFun n' ys) = ChebFun (max n n') (zipWithDefault 0 (+) xs ys) -- not right. We want to add with default 0 is [] and then re-shorten.  also the min needs to be a max.\n\t(ChebFun n xs) * (ChebFun n' ys) = chebify $ (funcify x) * (funcify y) -- all pointwise stuff tends to be in the real domain\n\tabs x = chebify $ abs . (funicfy x)\n\n\n\n\ninstance Vector a => Vector (ChebFun a) where\n\tsmul s = fmap (smul s) coefficients\n\tvadd x y = x + y\n\n-}\n\nnewtype Circ = Circ Double\ncirc :: Double -> Circ -- smart constructor\ncirc x = Circ $ mod' (abs x) (2 * pi)\n\n-- https://ro-che.info/articles/2015-12-04-fft\nsplit :: [a] -> ([a], [a])\nsplit = foldr f ([], [])\n  where\n    f a (r1, r2) = (a : r2, r1)\n\n-- interleave (The opposite of split). Not super sure I got the order right.\n\n-- liquid haskell: interleave split = split interleave\ninterleave (x : xs, ys) = x : (interleave (ys, xs))\n\n\n-- only takes 2^n sized lists, or we can assume is zero. Split is incorrect possible then. If not an even number it will swap\nfourier :: [Complex Double] -> [Complex Double]\nfourier [] = []\nfourier [a] = [a]\nfourier xs =  (zipWith (+) ffte ffto') <> (zipWith (-) ffte ffto')  where\n\t        (evens, odds) = split xs\n\t        ffte = fourier evens\n\t        n = length ffte\n\t        ffto = fourier odds\n\t        ffto' = zipWith (*) ffto (twiddle n) \n\n-- we may want to seperate out the real and imag part\ndata Fourier = Fourier {k0 :: Double, kcos :: [Double] , ksin :: [Double] }\n\n-- could we get liquid haskell to verify this?\n\n-- I can fourier any sequence Vector a => [a] -> [a]\n-- Need scalar multiplication via fourier coefficents.\n-- need vector add for + and - of \n-- I can make ChebFun a functor. Which can be useful, but perhaps suspicious.\n\n-- instance Num a => Vector a a\n\n\nfourier' :: [Double] -> [Complex Double]\nfourier' [] = []\nfourier' [a] = [a :+ 0]\nfourier' xs =  (zipWith (+) ffte ffto') <> (zipWith (-) ffte ffto')  where\n\t        (evens, odds) = split xs\n\t        ffte = fourier' evens\n\t        n = length ffte\n\t        ffto = fourier' odds\n\t        ffto' = zipWith (*) ffto (twiddle n) \n\ntwiddle :: Int -> [Complex Double]\ntwiddle n = map cis $ iterate (+ (pi / n')) 0 where n' = fromInteger $ toInteger n\n\n\n\n\n\n-- only takes 2^n sized lists, or we can assume is zero. Split is incorrect possible then. If not an even number it will swap\nifourier :: [Complex Double] -> [Complex Double]\nifourier [] = []\nifourier [a] = [a]\nifourier xs =  (zipWith (+) ffte ffto') <> (zipWith (-) ffte ffto')  where\n\t        (evens, odds) = split xs\n\t        ffte = ifourier evens\n\t        n = length ffte\n\t        ffto = ifourier odds\n\t        ffto' = zipWith (*) ffto (map conjugate (twiddle n)) \n{-\n{-# Rewrite (ifourier (fourier x) = x #-}\n{-# Rewrite (fourier (ifourier x) = x #-}\n\tDo I need fourier . ifourier = id ? couldn't hurt I guess.\n\t\tThese laws aren't strictly true, but pretty close. A nightmare for consistency, but will always make accuracy better.\n\n-}\n-- his is some bull.\nifft :: [Complex Double] -> [Complex Double]\nifft (x : xs) = fourier (x : (reverse xs))\n\nfourierGood :: [Complex Double] -> Bool\nfourierGood _ = True -- implement the envelope test\n\nenvelope :: (Ord a, Num a) => [a] -> [a] -- an envelope that replaces the list with the maximum of the list form then on\nenvelope = (scanr1 max) . (map abs)  -- (\\x acc -> max x acc) \n\n\n-- plateaujtest j env = env ! j >= env ! j2 * (1 - )   where j2 = 1.25*j + 5\n-- hmm a constant 0 may be unhappy with this. probably shouldn't use it.\n-- The maximum will be the head of the envelope by the way\n-- normalize xs = map (/ m) xs where m = maximum xs\n\n--normalize . envelope\n\n\n-- The stupidest test. WHat if we are accidentally in a zero of the spectrum\n-- maybe lsightly less stupid would be to take the maximum of the last 1/4.\n-- These really are garbage. We should actually follow the chebfun prescirption.\n\nsimpleTest :: (Fractional a, Ord a) => [a] -> Bool\nsimpleTest xs = if (last absxs) >= (m * (1e-12)) then False else True where\n\t    absxs = fmap abs xs\n\t    m = maximum absxs\n\n\n-- If we consider iterated ChebFuns, we may want different complexity depending on whether we are at low rank pieces or not.\n-- so part of our chebify should recurse inside and chebify for every element.\n-- I guess i roughly expect the needed coefficients to form a polytope ?\n-- It will be this blob on nenzero coefficients. In higher dimension, surfacc is large, so cutting down on that is helpful.\n-- Hmm. This isn't really hierarchical. Maybe some even odd splitting combined with left right splitting in real space?\n-- I get a faint sensation I might want to look at a maxi-min? Maybe not. \n{-\nThe new expansion test should decide on both whether to expand internally and at this level.\n-- Chebify (Chebify a) => Chebify (Double -> a) where\n  chebify f = (fmap chebify) f -\n\n  Chebify Double where\n  \tchebify = id\n\n-}\n-- G(x,x') considered as a 2d function \n-- 1/r^2 also should seperate out into peices\n\n\n-- integrate -- from 0 to x\n-- differentiate -- differentiation with resepct to the coordinate\n-- functional_differenation -- = differntation with resepct to the value held.\n-- sample :: Double -> ChebFun a -> a -- function application \n-- fmap diff (For a composed chebfun this idffierentiates the third coordinate)\n-- diff2 = diff . diff\n-- 3d laplacian.\n-- diff2 + fmap diff2 + fmap . fmap diff2\n\n\n\n{-\nincreasingFourier :: [Complex Double] -> (Double -> Double) -> [Complex Double]\nincreasingFourier evens f | fourierGood evens = increasingFourier evens' f \n                          | otherwise = evens where\n                                               evens' = (zipWith (+) evens ffto') <> (zipWith (-) evens ffto')\n                                               odds = sample f oddpositions\n                                               ffto =  fourier odds\n                                               twiddle =    \n                                               ffto' = zipWith      -- if evens acceptable, stop, otherwise \n\n--- increasing fourier is chebify basically\nchebify = increasingFourier []\n-- sinc interpolation I guess? just take nearest point of reverse fft? Linear interpolation of fft? All of these corresopnd to filters, the choice of\n\t-- which should not matter much\n\n-- sum_x0  sinc(x-x0) * f(x0)\nfuncify = \\x -> Chebfun\n-}\n\n\n\n\nmain :: IO ()\nmain = someFunc\n", "meta": {"hexsha": "4e831cd7b1128a44d0b30d73b036227ec6594252", "size": 8328, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "philzook58/chebfun-hask", "max_stars_repo_head_hexsha": "e8cace69f372c52a1bbc008d46130b7e7ab5bfee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T04:11:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T04:11:29.000Z", "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "philzook58/chebfun-hask", "max_issues_repo_head_hexsha": "e8cace69f372c52a1bbc008d46130b7e7ab5bfee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "philzook58/chebfun-hask", "max_forks_repo_head_hexsha": "e8cace69f372c52a1bbc008d46130b7e7ab5bfee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4382978723, "max_line_length": 187, "alphanum_fraction": 0.648054755, "num_tokens": 2412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.484347197697209}}
{"text": "import Foreign.Marshal.Array\nimport Data.Complex\nimport Foreign.Storable.Complex\nimport FFTW\n\nmain = do\n    inA  <- fftwAllocComplex 1024\n    outA <- fftwAllocComplex 1024\n\n    plan <- planDFT1d 1024 inA outA Forward fftwEstimate\n\n    pokeArray inA $ map (:+ 0) [0..1023]\n    execute plan\n    res <- peekArray 1024 outA\n\n    fftwFree inA\n    fftwFree outA\n\n    print res\n", "meta": {"hexsha": "2548176ea067be1426ccd6a598b990fb6a393e99", "size": 371, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/example.hs", "max_stars_repo_name": "adamwalker/haskell-fftw-simple", "max_stars_repo_head_hexsha": "5b7705386432f98f2571ae74bbf18375bfe2265a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-06-04T07:34:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T03:45:39.000Z", "max_issues_repo_path": "examples/example.hs", "max_issues_repo_name": "adamwalker/haskell-fftw-simple", "max_issues_repo_head_hexsha": "5b7705386432f98f2571ae74bbf18375bfe2265a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-23T09:41:59.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-23T14:18:53.000Z", "max_forks_repo_path": "examples/example.hs", "max_forks_repo_name": "adamwalker/haskell-fftw-simple", "max_forks_repo_head_hexsha": "5b7705386432f98f2571ae74bbf18375bfe2265a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-07-19T13:11:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-19T13:11:18.000Z", "avg_line_length": 18.55, "max_line_length": 56, "alphanum_fraction": 0.6981132075, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48383755815253415}}
{"text": "{-# LANGUAGE BangPatterns #-}\n\nmodule SimParse where\n\nimport Data.List\nimport NEC\nimport System.Process\nimport System.Random\nimport Data.Complex\n\n\n\nvswr :: Double -> (Double, Double) -> Double\nvswr target = vswr' (target, 0)\n\nvswr' :: (Double, Double) -> (Double, Double) -> Double\nvswr' (reTar, imTar) (reLoad, imLoad) = swr where\n  z0 = reTar :+ imTar\n  zL = reLoad :+ imLoad\n  refRatio = (zL - z0) / (zL + z0)\n  (ro :+ _) = abs $ refRatio\n  swr = (1 + ro)  / (1 - ro)\n\n\nbandwidthInterval :: Double -> Double -> [[String]] -> (Double, Double)\nbandwidthInterval targetImp swrThre lnss = (lo, hi) where\n  swrs = map (\\l -> (frequency l , vswr targetImp (impedance l))) lnss\n  below = takeWhile (\\s -> (snd s) <= swrThre) $ dropWhile (\\s -> (snd s) > swrThre) swrs\n  lo = fst $ head below\n  hi = fst $ last below\n\n\nbandwidth t s = (\\(lo, hi) -> hi - lo) . bandwidthInterval t s\n\n\ngain :: [String] -> Double\ngain lns = read gn where\n  gn = head $ drop 4 $ words gainline\n  gainline =  head $ drop 5 $ dropWhile (not . isSubsequenceOf \"RADIATION PATTERN\") lns\n\n\nimpedance :: [String] -> (Double, Double)\nimpedance lns = (zr, zi) where\n  zr = read $ head line\n  zi = read $ head $ tail line\n  line = drop 6 $ words paramsLine\n  paramsLine = head $ drop 3 $ dropWhile (not . isSubsequenceOf \"ANTENNA INPUT PARAMETERS\") lns\n\n\nfrequency :: [String] -> Double\nfrequency lns = read freq where\n  freq = head $ drop 2 $ words $ head $ dropWhile (not . isSubsequenceOf \"FREQUENCY\") $ lns\n\n\nfitness targetImpedance lns = a * gn - b * (abs $ targetImpedance - reZ) - c * (abs imZ) where\n  a = 40\n  b = 2\n  c = 2\n  gn = gain lns\n  (reZ, imZ) = impedance lns\n\n\n\nfitnessImepd targetImpedance lns = - b * (abs $ targetImpedance - reZ) - c * (abs imZ) where\n  b = 2\n  c = 2\n  gn = gain lns\n  (reZ, imZ) = impedance lns\n\n\n\nfitness' targetImpedance lns = a * gn - b * ((targetImpedance - reZ)*(targetImpedance - reZ)) - c * (imZ * imZ) where\n  a = 40\n  b = 2\n  c = 2\n  gn = gain lns\n  (reZ, imZ) = impedance lns\n\nfitnessImepd' targetImpedance lns =  - b * ((targetImpedance - reZ)*(targetImpedance - reZ)) - c * (imZ * imZ) where\n  b = 2\n  c = 2\n  gn = gain lns\n  (reZ, imZ) = impedance lns\n\n\nrunSim sim sfreq efreq steps = go where\n  splitRuns [] = []\n  splitRuns xs = first : splitRuns rest where\n    first = takeWhile (not . isSubsequenceOf \"- FREQUENCY -\") $ rest\n    rest = tail $ (dropWhile (not . isSubsequenceOf \"- FREQUENCY -\")) xs\n\n  go = do\n    rn <- randomIO :: IO Int\n    let fl = \"/tmp/evalnec\"++(show rn)\n    writeFile (fl++\".nec\") $ printSim sfreq efreq steps False sim\n    system $ \"nec2c -i \"++fl++\".nec\"\n    !lns <- fmap lines $ readFile (fl++\".out\")\n    system $ \"rm \"++fl++\"*\"\n    return $ init $ splitRuns $ lns ++ [\"- FREQUENCY -\"]\n\n\nevalSim sim freq fitnessF = go where\n  --freq = 447.625\n  go = do  \n    rn <- randomIO :: IO Int\n    let fl = \"/tmp/evalnec\"++(show rn)\n    writeFile (fl++\".nec\") $ printSim freq freq 1 False sim\n    system $ \"nec2c -i \"++fl++\".nec\"\n    !lns <- fmap lines $ readFile (fl++\".out\")\n    system $ \"rm \"++fl++\"*\"\n    --print $ gain lns\n    --print $ impedance lns\n    return $ fitnessF lns\n\n\n  \n\n", "meta": {"hexsha": "d1d5c3f616a183647748a560fd8378685f6361e1", "size": 3127, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SimParse.hs", "max_stars_repo_name": "bssstudio/NECGenHS", "max_stars_repo_head_hexsha": "cf5e0a645555a6a4b63984807a9a3dffb1ae5db9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SimParse.hs", "max_issues_repo_name": "bssstudio/NECGenHS", "max_issues_repo_head_hexsha": "cf5e0a645555a6a4b63984807a9a3dffb1ae5db9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SimParse.hs", "max_forks_repo_name": "bssstudio/NECGenHS", "max_forks_repo_head_hexsha": "cf5e0a645555a6a4b63984807a9a3dffb1ae5db9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5, "max_line_length": 117, "alphanum_fraction": 0.6130476495, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.483710024904175}}
{"text": "{-# LANGUAGE OverloadedStrings, NoImplicitPrelude, BangPatterns #-}\nmodule Main where\nimport ClassyPrelude\nimport qualified Numeric.LinearAlgebra as HMatrix\nimport NLP.Albemarle.Dict (counts, ids)\nimport qualified NLP.Albemarle.Dict as Dict\nimport NLP.Albemarle.LSA (termvectors, topicweights)\nimport qualified NLP.Albemarle.LSA as LSA\nimport qualified NLP.Albemarle.Tokens as Tokens\nimport qualified System.IO.Streams as Streams\nimport Data.Text.Encoding.Error (lenientDecode)\nimport Lens.Micro\n\nmain :: IO ()\nmain = do\n  (final_dict, model) <- Streams.withFileAsInput \"kjv.verses.txt.gz\" $ \\file ->\n    Streams.gunzip file\n    >>= Streams.lines\n    >>= Streams.decodeUtf8With lenientDecode\n    >>= Streams.map Tokens.wordTokenize\n    >>= Streams.chunkList 5000 -- Yep, I'm making this stuff up.\n    >>= Streams.map (\\chunk -> let\n      dict = Dict.dictifyAllWords chunk\n      sparsem = Dict.asSparseMatrix dict chunk\n      lsa = LSA.lsa 100 sparsem\n      in (dict, lsa))\n    >>= Streams.fold (\\(!d1, !lsa1) (d2, lsa2) -> let\n      d3 = Dict.filterDict 2 0.5 1000 $ d1 <> d2\n      lsa3 = LSA.rebase d1 d3 lsa1 <> LSA.rebase d2 d3 lsa2\n      in (d3, lsa3)) (mempty, mempty)\n\n  -- It should use all 100 words allowed plus the unknown\n  print $ length (final_dict^.counts)\n  -- It should have a full size LSA as well\n  print $ HMatrix.size (model^.termvectors)\n  -- Plus topic weights\n  print $ HMatrix.size (model^.topicweights)\n", "meta": {"hexsha": "513093301ec4b97780e4222874f5ea81d0443553", "size": 1428, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "SeanTater/albemarle", "max_stars_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-07-16T15:06:24.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-19T00:51:45.000Z", "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "SeanTater/albemarle", "max_issues_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-05-05T14:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-04T14:04:54.000Z", "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "SeanTater/albemarle", "max_forks_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "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.5789473684, "max_line_length": 79, "alphanum_fraction": 0.7100840336, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48371001491190385}}
{"text": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n\n\nmodule Spinell.Fitting\n    (fit, \n     unscaledFit,\n     mvarFit,\n     mvarUnscaledFit,\n     defFitOpt,\n     FitOptions(..),\n     Jacobianable(..),\n     Model,\n     UnboxedModel,\n     getParams,\n     getUnscaledParams) where\n\n\nimport Numeric.GSL.Fitting\nimport Numeric.LinearAlgebra\nimport Numeric.AD\nimport Numeric.AD.Internal.Reverse\nimport Data.Reflection\n\n\ntype FitData = [([Double],([Double],Double))]\ntype FitRes = ([(Double, Double)], Matrix Double)\ntype UnscaledFitRes = ([Double], Matrix Double)\n\n--\ntype Model = (forall a . Floating a => [a]->[a]->[a])\n\ntype UnboxedModel = (forall a . Floating a => [a]->a->a)\n \nbox :: UnboxedModel -> Model\nbox unmodel = (\\p -> \\x -> return (unmodel p (x !! 0)))\n\n--\ntype FullJacob = ([Double] -> [Double] -> [[Double]])\n\ndata Jacobianable = AutoJacob | ManualJacob FullJacob\n\nsanitize :: Jacobianable -> Model -> FullJacob\nsanitize AutoJacob model = mkJac model\nsanitize (ManualJacob jac) model = jac\n\n--\n\ndata FitOptions = FitOptions { \n        jacob :: Jacobianable,\n        iter :: Int, \n        absTol :: Double, \n        relTol :: Double\n    } \n\ndefFitOpt = FitOptions { jacob = AutoJacob,iter = 1000,absTol = 1E-20,relTol = 1E-20 }\n\n--\n\nfit :: [Double]\n     -> [Double]\n     -> [Double]\n     -> UnboxedModel\n     -> [Double]\n     -> FitOptions\n     -> FitRes\n\nfit xs ys sigma rawmodel guess fitparams\n    | xeqy && ( seqx || seqone) = fitModelScaled setAbsTol setResTol setIter (box rawmodel, sanitize jacobian (box rawmodel)) fitdata guess\n    | otherwise = error \"Input data has the wrong size\"\n    where \n    lx = length xs\n    ly = length ys\n    ls = length sigma\n    xeqy = lx == ly\n    seqx = ls == lx\n    seqone = ls == 1\n\n    jacobian = jacob fitparams --we extract the \"jacobian\" parameter from the record\n\n    setIter = iter fitparams\n    setAbsTol = absTol fitparams\n    setResTol = relTol fitparams\n\n    fitdata = formatData xs ys sigma\n\n\nformatData :: [Double] -> [Double] -> [Double] -> FitData\nformatData xs ys sigma\n    |  length sigma == length xs = zip (return <$> xs) $ zip (return <$> ys) sigma\n    |  length sigma == 1 = zip (return <$> xs) $ zip (return <$> ys) (repeat (head sigma))\n\n\nunscaledFit :: [Double]\n     -> [Double]\n     -> UnboxedModel\n     -> [Double]\n     -> FitOptions\n     -> UnscaledFitRes\n\nunscaledFit xs ys rawmodel guess fitparams\n    | xeqy = fitModel setAbsTol setResTol setIter (box rawmodel, sanitize jacobian (box rawmodel)) fitdata guess\n    | otherwise = error \"Input data has the wrong size\"\n    where \n    lx = length xs\n    ly = length ys\n    xeqy = lx == ly\n\n    jacobian = jacob fitparams\n\n    setIter = iter fitparams\n    setAbsTol = absTol fitparams\n    setResTol = relTol fitparams\n\n    fitdata = zip (return <$> xs) (return <$> ys) \n\nmvarFit :: [[Double]]\n     -> [[Double]]\n     -> [Double]\n     -> Model\n     -> [Double]\n     -> FitOptions\n     -> FitRes\n\nmvarFit xs ys sigma model guess fitparams\n    | xeqy && ( seqx || seqone) = fitModelScaled setAbsTol setResTol setIter (model, sanitize jacobian model) fitdata guess\n    | otherwise = error \"Input data has the wrong size\"\n    where \n    lx = length xs\n    ly = length ys\n    ls = length sigma\n    xeqy = lx == ly\n    seqx = ls == lx\n    seqone = ls == 1\n\n    jacobian = jacob fitparams\n\n    setIter = iter fitparams\n    setAbsTol = absTol fitparams\n    setResTol = relTol fitparams\n\n    fitdata = formatDataBoxed xs ys sigma\n\n\nformatDataBoxed :: [[Double]] -> [[Double]] -> [Double] -> FitData\nformatDataBoxed xs ys sigma\n    |  length sigma == length xs = zip xs $ zip ys sigma\n    |  length sigma == 1 = zip xs $ zip ys (repeat (head sigma))\n\nmvarUnscaledFit :: [[Double]]\n     -> [[Double]]\n     -> Model\n     -> [Double]\n     -> FitOptions\n     -> UnscaledFitRes\n\nmvarUnscaledFit xs ys model guess fitparams\n    | xeqy = fitModel setAbsTol setResTol setIter (model, sanitize jacobian model) fitdata guess\n    | otherwise = error \"Input data has the wrong size\"\n    where \n    lx = length xs\n    ly = length ys\n    xeqy = lx == ly\n\n    jacobian = jacob fitparams\n\n    setIter = iter fitparams\n    setAbsTol = absTol fitparams\n    setResTol = relTol fitparams\n\n    fitdata = zip xs ys\n\nmkJac :: (Num a) => (forall s. Reifies s Tape => [Reverse s a] -> [Reverse s a] -> [Reverse s a])\n       -> [a]\n       -> [a]\n       -> [[a]]\n\nmkJac f p x = jacobian ((flip f) (fmap auto x)) p\n\ngetParams :: FitRes -> [Double]\ngetParams res = fst . unzip . fst $ res\n\ngetUnscaledParams :: UnscaledFitRes -> [Double]\ngetUnscaledParams res = fst res\n", "meta": {"hexsha": "1b93780169bd4c99b0bed5b49ee50ca1ea6b9004", "size": 4602, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Spinell/Fitting.hs", "max_stars_repo_name": "Magalame/Spinell", "max_stars_repo_head_hexsha": "03e819e4164f6e0361b9b320002a34f123d47ecd", "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/Spinell/Fitting.hs", "max_issues_repo_name": "Magalame/Spinell", "max_issues_repo_head_hexsha": "03e819e4164f6e0361b9b320002a34f123d47ecd", "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/Spinell/Fitting.hs", "max_forks_repo_name": "Magalame/Spinell", "max_forks_repo_head_hexsha": "03e819e4164f6e0361b9b320002a34f123d47ecd", "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": 24.7419354839, "max_line_length": 139, "alphanum_fraction": 0.6282051282, "num_tokens": 1358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.48359843460231683}}
{"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}\n\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DeriveAnyClass        #-}\n{-# LANGUAGE DeriveGeneric         #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedLabels      #-}\n{-# LANGUAGE OverloadedStrings     #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-|\nModule      : Grenade.Layers.BatchNormalisation\nDescription : Batch normalization layer\nCopyright   : (c) Theo Charalambous, 2020\nLicense     : BSD2\nStability   : experimental\n\nThe layer follows the implementation as described in the paper:\nSergey Ioffe and Christian Szegedy. Batch normalization:  Accelerating deep network training by reducing internal covariate shift\n<http://arxiv.org/abs/1502.03167>\n-}\n\nmodule Grenade.Layers.BatchNormalisation \n  (\n  -- * Layer Definition\n    BatchNorm (..)\n  , BatchNormParams(..)\n\n  -- * Differentation Types\n  , BatchNormTape(..)\n  , BatchNormGrad(..)\n\n  -- * Helper functions\n  , initBatchNorm\n  )\nwhere\n\nimport           Control.DeepSeq\nimport           Data.Kind                         (Type)\nimport           Data.List                         (transpose, zipWith5)\nimport           Data.Maybe                        (fromJust)\nimport           Data.Proxy\nimport           Data.Serialize\nimport           GHC.TypeLits\n\nimport qualified Numeric.LinearAlgebra             as LA\nimport           Numeric.LinearAlgebra.Static      hiding (Seed)\n\nimport           Grenade.Core\nimport           Grenade.Layers.Internal.BatchNorm\nimport           Grenade.Layers.Internal.Update\nimport           Grenade.Onnx\nimport           Grenade.Types\nimport           Grenade.Utils.LinearAlgebra\nimport           Grenade.Utils.ListStore\n\nimport           Lens.Micro\n\ndata BatchNormTape :: Nat -- The number of channels of the tensor\n                   -> Nat -- The number of rows of the tensor\n                   -> Nat -- The number of columns of the tensor\n                   -> Type where\n  -- | there is no back propogation when using network for testing, so \n  --   so the tape for automatic differentiation is empty\n  TestBatchNormTape  :: ( KnownNat channels\n                     , KnownNat rows\n                     , KnownNat columns)\n                     => BatchNormTape channels rows columns -- ^ empty tape\n\n  -- | prevents having to calculate information twice during forward and backwards pass\n  TrainBatchNormTape :: ( KnownNat channels\n                     , KnownNat rows\n                     , KnownNat columns)\n                     => [R (channels * rows * columns)]  -- ^ xnorm\n                     -> R channels                       -- ^ std\n                     -> R channels                       -- ^ running mean\n                     -> R channels                       -- ^ running variance\n                     -> BatchNormTape channels rows columns\n\ndata BatchNorm :: Nat -- The number of channels of the tensor\n               -> Nat -- The number of rows of the tensor\n               -> Nat -- The number of columns of the tensor\n               -> Nat -- momentum\n               -> Type where\n  BatchNorm :: ( KnownNat channels\n               , KnownNat rows\n               , KnownNat columns\n               , KnownNat momentum)\n            => Bool                                 -- ^ True: training, False: testing\n            -> BatchNormParams channels             -- ^ gamma and beta\n            -> R channels                           -- ^ running mean\n            -> R channels                           -- ^ running variance\n            -> RealNum                              -- ^ epsilon (used for numerical stability)\n            -> ListStore (BatchNormParams channels) -- ^ momentum store\n            -> BatchNorm channels rows columns momentum\n\ndata BatchNormParams :: Nat -> Type where\n  BatchNormParams :: KnownNat channels\n                  => R channels -- gamma\n                  -> R channels -- beta\n                  -> BatchNormParams channels\n\ndata BatchNormGrad :: Nat -- The number of channels of the tensor\n                   -> Nat -- The number of rows of the tensor\n                   -> Nat -- The number of columns of the tensor\n                   -> Type where\n  BatchNormGrad :: ( KnownNat channels\n                   , KnownNat rows\n                   , KnownNat columns)\n            => R channels -- ^ running mean\n            -> R channels -- ^ running variance\n            -> R channels -- ^ derivative of loss wrt gamma\n            -> R channels -- ^ derivative of loss wrt beta\n            -> BatchNormGrad channels rows columns\n\n\n-- | NFData instances\ninstance NFData (BatchNormTape channels rows columns) where\n  rnf TestBatchNormTape = ()\n  rnf (TrainBatchNormTape xnorm std mean var) = rnf xnorm `seq` rnf std `seq` rnf mean `seq` rnf var\n\ninstance NFData (BatchNormParams flattenSize) where\n  rnf (BatchNormParams gamma beta)\n    = rnf gamma `seq` rnf beta\n\ninstance NFData (BatchNorm channels rows columns momentum) where\n  rnf (BatchNorm training bnparams mean var eps store)\n    = rnf training `seq` rnf bnparams `seq` rnf mean `seq` rnf var `seq` rnf eps `seq` rnf store\n\n-- | Show instance\n\ninstance Show (BatchNorm channels rows columns momentum) where\n  show _ = \"Batch Normalization\"\n\n-- Serialize instances\ninstance (KnownNat channels, KnownNat rows, KnownNat columns, KnownNat momentum)\n  => Serialize (BatchNorm channels rows columns momentum) where\n\n  put (BatchNorm training bnparams mean var \u03b5 store) = do\n    put training\n    put bnparams\n    putListOf put . LA.toList . extract $ mean\n    putListOf put . LA.toList . extract $ var\n    put \u03b5\n    put store\n\n  get = do\n    training <- get\n    bnparams <- get\n    mean     <- maybe (fail \"Vector of incorrect size\") return . create . LA.fromList =<< getListOf get\n    var      <- maybe (fail \"Vector of incorrect size\") return . create . LA.fromList =<< getListOf get\n    \u03b5        <- get\n    store    <- get\n\n    return $ BatchNorm training bnparams mean var \u03b5 store\n\ninstance KnownNat flattenSize => Serialize (BatchNormParams flattenSize) where\n  put (BatchNormParams gamma beta) = do\n    putListOf put . LA.toList . extract $ gamma\n    putListOf put . LA.toList . extract $ beta\n\n  get = do\n    gamma <- maybe (fail \"Vector of incorrect size\") return . create . LA.fromList =<< getListOf get\n    beta  <- maybe (fail \"Vector of incorrect size\") return . create . LA.fromList =<< getListOf get\n\n    return $ BatchNormParams gamma beta\n\n-- | Neural network operations\ninstance (KnownNat channels, KnownNat rows, KnownNat columns, KnownNat mom, KnownNat (channels * rows * columns))\n  => UpdateLayer (BatchNorm channels rows columns mom) where\n\n  type Gradient (BatchNorm channels rows columns mom) = BatchNormGrad channels rows columns\n  type MomentumStore (BatchNorm channels rows columns mom) = ListStore (BatchNormParams channels)\n\n  reduceGradient = undefined\n\n  runUpdate opt@OptSGD{} x@(BatchNorm training (BatchNormParams oldGamma oldBeta) _ _ \u03b5 store) (BatchNormGrad runningMean runningVar dGamma dBeta)\n    = let BatchNormParams oldGammaMomentum oldBetaMomentum = getData opt x store\n          VectorResultSGD newGamma newGammaMomentum        = descendVector opt (VectorValuesSGD oldGamma dGamma oldGammaMomentum)\n          VectorResultSGD newBeta  newBetaMomentum         = descendVector opt (VectorValuesSGD oldBeta dBeta oldBetaMomentum)\n          newStore                                         = setData opt x store (BatchNormParams newGammaMomentum newBetaMomentum)\n      in  BatchNorm training (BatchNormParams newGamma newBeta) runningMean runningVar \u03b5 newStore\n\n  runUpdate opt@OptAdam{} x@(BatchNorm training (BatchNormParams oldGamma oldBeta) _ _ \u03b5 store) (BatchNormGrad runningMean runningVar dGamma dBeta)\n    = let [BatchNormParams oldMGamma oldMBeta, BatchNormParams oldVGamma oldVBeta] = getData opt x store\n          VectorResultAdam newGamma newMGamma newVGamma                            = descendVector opt (VectorValuesAdam (getStep store) oldGamma dGamma oldMGamma oldVGamma)\n          VectorResultAdam newBeta  newMBeta  newVBeta                             = descendVector opt (VectorValuesAdam (getStep store) oldBeta  dBeta  oldMBeta  oldVBeta)\n          newStore                                                                 = setData opt x store [BatchNormParams newMGamma newMBeta, BatchNormParams newVGamma newVBeta]\n      in  BatchNorm training (BatchNormParams newGamma newBeta) runningMean runningVar \u03b5 newStore\n\n  runSettingsUpdate NetworkSettings{trainingActive=training} (BatchNorm _ bnparams mean var \u03b5 store) = BatchNorm training bnparams mean var \u03b5 store\n\ninstance (KnownNat channels, KnownNat rows, KnownNat columns, KnownNat mom)\n  => LayerOptimizerData (BatchNorm channels rows columns mom) (Optimizer 'SGD) where\n\n  type MomentumDataType (BatchNorm channels rows columns mom) (Optimizer 'SGD) = BatchNormParams channels\n  getData opt x store = head $ getListStore opt x store\n  setData opt x store = setListStore opt x store . return\n  newData _ _ = BatchNormParams (konst 0) (konst 0)\n\ninstance (KnownNat channels, KnownNat rows, KnownNat columns, KnownNat mom)\n  => LayerOptimizerData (BatchNorm channels rows columns mom) (Optimizer 'Adam) where\n\n  type MomentumDataType (BatchNorm channels rows columns mom) (Optimizer 'Adam) = BatchNormParams channels\n  type MomentumExpOptResult (BatchNorm channels rows columns mom) (Optimizer 'Adam) = [BatchNormParams channels]\n  getData     = getListStore\n  setData     = setListStore\n  newData _ _ = BatchNormParams (konst 0) (konst 0)\n\ninstance (KnownNat channels, KnownNat rows, KnownNat columns, KnownNat momentum)\n  => RandomLayer (BatchNorm channels rows columns momentum) where\n  createRandomWith _ _ = pure initBatchNorm\n\n-- | Initialize a batch norm layer with gamma set to zero for each channel and beta \n--   set to one for each channel. Running mean is 0 and running var is 1. The default\n--   value for epsilon is 0.00001\ninitBatchNorm :: forall channels rows columns momentum.\n  (KnownNat channels, KnownNat rows, KnownNat columns, KnownNat momentum)\n  => BatchNorm channels rows columns momentum\ninitBatchNorm =\n  let ch     = fromIntegral $ natVal (Proxy :: Proxy channels)\n      zeroes = replicate ch 0\n      ones   = replicate ch 1\n      gamma  = vector ones   :: R channels\n      beta   = vector zeroes :: R channels\n      mean   = vector zeroes :: R channels\n      var    = vector ones   :: R channels\n      \u03b5      = 0.00001\n  in BatchNorm True (BatchNormParams gamma beta) mean var \u03b5 mkListStore\n\ninstance (KnownNat rows, KnownNat momentum)\n  => Layer (BatchNorm 1 1 rows momentum) ('D1 rows) ('D1 rows) where\n\n  type Tape (BatchNorm 1 1 rows momentum) ('D1 rows) ('D1 rows) = BatchNormTape 1 1 rows\n\n  runForwards (BatchNorm True _ _ _ _ _) _\n    = error \"Cannot train use batch size of 1 with BatchNorm layer during training\"\n\n  runForwards (BatchNorm False (BatchNormParams gamma beta) runningMean runningVar \u03b5 _) (S1D x)\n    = let gamma'       = extract gamma LA.! 0\n          beta'        = extract beta LA.! 0\n          runningMean' = extract runningMean LA.! 0\n          runningVar'  = extract runningVar LA.! 0\n\n          std = sqrt $ runningVar' + \u03b5\n\n          y = dvmap (\\x -> ((x - runningMean') / std ) * gamma' + beta') x\n\n      in (TestBatchNormTape, S1D y)\n\n  runBatchForwards bn@(BatchNorm False _ _ _ _ _) xs\n    = let outs = map (snd . runForwards bn) xs\n      in ([TestBatchNormTape], outs)\n\n  runBatchForwards (BatchNorm True (BatchNormParams gamma beta) runningMean runningVar \u03b5 _) xs\n    = let [m]             = vectorToList runningMean :: [RealNum]\n          [v]             = vectorToList runningVar  :: [RealNum]\n          [g]             = vectorToList gamma       :: [RealNum]\n          [b]             = vectorToList beta        :: [RealNum]\n          mom             = (/ 100) $ fromIntegral $ natVal (Proxy :: Proxy momentum)\n\n          xs'             = map extractV xs\n\n          sample_mean     = batchNormMean xs'                 :: RealNum\n          sample_var      = batchNormVariance xs'             :: RealNum\n\n          m'              = mom * m + (1 - mom) * sample_mean :: RealNum\n          v'              = mom * v + (1 - mom) * sample_var  :: RealNum\n          std             = sqrt $ sample_var + \u03b5             :: RealNum\n\n          x_extracted     = map (\\(S1D x) -> x) xs\n          x_normalised    = map (dvmap (\\a -> (a - sample_mean) / std)) x_extracted\n          scaledShifted   = map (dvmap (\\a -> g * a + b)) x_normalised\n          out             = map S1D scaledShifted\n\n          stdV            = listToVector [std] :: R 1\n          runningMeanV    = listToVector [m']  :: R 1\n          runningVarV     = listToVector [v']  :: R 1\n\n      in ([TrainBatchNormTape x_normalised stdV runningMeanV runningVarV], out)\n\n  runBatchBackwards (BatchNorm True (BatchNormParams _ _) _ _ _ _) _ _\n    = undefined\n\n  runBatchBackwards _ _ _\n    = undefined\n\ninstance (KnownNat rows, KnownNat columns, KnownNat momentum)\n  => Layer (BatchNorm 1 rows columns momentum) ('D2 rows columns) ('D2 rows columns) where\n\n  type Tape (BatchNorm 1 rows columns momentum) ('D2 rows columns) ('D2 rows columns) = BatchNormTape 1 rows columns\n\n  runForwards (BatchNorm True _ _ _ _ _) _\n    = error \"Cannot train use batch size of 1 with BatchNorm layer during training\"\n\n  runForwards (BatchNorm False (BatchNormParams gamma beta) runningMean runningVar \u03b5 _) (S2D x)\n    = let rows     = fromIntegral $ natVal (Proxy :: Proxy rows)\n          columns  = fromIntegral $ natVal (Proxy :: Proxy columns)\n\n          gamma'       = extract gamma\n          beta'        = extract beta\n          runningMean' = extract runningMean\n          runningVar'  = extract runningVar\n          mat          = extract x\n\n          y  = batchnorm 1 rows columns \u03b5 mat gamma' beta' runningMean' runningVar'\n          y' = fromJust . create $ y\n\n      in (TestBatchNormTape, S2D y')\n\n  runBatchForwards bn@(BatchNorm False _ _ _ _ _) xs\n    = let outs = map (snd . runForwards bn) xs\n      in ([TestBatchNormTape], outs)\n\n  runBatchForwards (BatchNorm True (BatchNormParams gamma beta) runningMean runningVar \u03b5 _) xs\n    = let [m]             = vectorToList runningMean :: [RealNum]\n          [v]             = vectorToList runningVar  :: [RealNum]\n          [g]             = vectorToList gamma       :: [RealNum]\n          [b]             = vectorToList beta        :: [RealNum]\n          mom             = (/ 100) $ fromIntegral $ natVal (Proxy :: Proxy momentum)\n\n          xs'             = map (sflatten . extractM2D) xs\n\n          sample_mean     = batchNormMean xs'                 :: RealNum\n          sample_var      = batchNormVariance xs'             :: RealNum\n\n          m'              = mom * m + (1 - mom) * sample_mean :: RealNum\n          v'              = mom * v + (1 - mom) * sample_var  :: RealNum\n          std             = sqrt $ sample_var + \u03b5             :: RealNum\n\n          x_extracted     = map (\\(S2D x) -> x) xs\n          x_normalised    = map (dmmap (\\a -> (a - sample_mean) / std)) x_extracted\n          scaledShifted   = map (dmmap (\\a -> g * a + b)) x_normalised\n          out             = map S2D scaledShifted\n\n          x_normalised'   = map sflatten x_normalised\n          stdV            = listToVector [std] :: R 1\n          runningMeanV    = listToVector [m']  :: R 1\n          runningVarV     = listToVector [v']  :: R 1\n\n      in ([TrainBatchNormTape x_normalised' stdV runningMeanV runningVarV], out)\n\n  runBatchBackwards (BatchNorm True (BatchNormParams _ _) _ _ _ _) _ _\n    = undefined\n\n  runBatchBackwards _ _ _\n    = undefined\n\ninstance (KnownNat channels, KnownNat rows, KnownNat columns, KnownNat momentum)\n  => Layer (BatchNorm channels rows columns momentum) ('D3 rows columns channels) ('D3 rows columns channels) where\n\n  type Tape (BatchNorm channels rows columns momentum) ('D3 rows columns channels) ('D3 rows columns channels) = BatchNormTape channels rows columns\n\n  runForwards (BatchNorm True _ _ _ _ _) _\n    = error \"Cannot train use batch size of 1 with BatchNorm layer during training\"\n\n  runForwards (BatchNorm False (BatchNormParams gamma beta) runningMean runningVar \u03b5 _) (S3D x)\n    = let rows     = fromIntegral $ natVal (Proxy :: Proxy rows)\n          columns  = fromIntegral $ natVal (Proxy :: Proxy columns)\n          channels = fromIntegral $ natVal (Proxy :: Proxy channels)\n\n          gamma'       = extract gamma\n          beta'        = extract beta\n          runningMean' = extract runningMean\n          runningVar'  = extract runningVar\n          mat          = extract x\n\n          y  = batchnorm channels rows columns \u03b5 mat gamma' beta' runningMean' runningVar'\n          y' = fromJust . create $ y\n\n      in (TestBatchNormTape, S3D y')\n\n  runBatchForwards bn@(BatchNorm False _ _ _ _ _) xs\n    = let outs = map (snd . runForwards bn) xs\n      in ([TestBatchNormTape], outs)\n\n  runBatchForwards (BatchNorm True (BatchNormParams gamma beta) runningMean runningVar \u03b5 _) xs\n    = let ms     = vectorToList runningMean\n          vs     = vectorToList runningVar\n          gs     = vectorToList gamma\n          bs     = vectorToList beta\n\n          cs     = map splitChannels xs :: [[S ('D2 rows columns)]]\n          cs'    = transpose cs\n\n          f c g b m v = let gs' = listToVector [g] :: R 1\n                            bs' = listToVector [b] :: R 1\n                            ms' = listToVector [m] :: R 1\n                            vs' = listToVector [v] :: R 1\n                            bn' = BatchNorm True (BatchNormParams gs' bs') ms' vs' \u03b5 undefined :: BatchNorm 1 rows columns momentum\n                        in  runBatchForwards bn' c\n\n          (tapes, outs) = unzip $ zipWith5 f cs' gs bs ms vs\n          outs' = transpose outs\n      in (combineTapes tapes, map combineChannels outs')\n    where\n      combineTapes :: [[BatchNormTape 1 i j]] -> [BatchNormTape k i j]\n      combineTapes = undefined\n\n  runBatchBackwards (BatchNorm True (BatchNormParams _ _) _ _ _ _) _ _\n    = undefined\n\n  runBatchBackwards _ _ _ = undefined\n\ninstance OnnxOperator (BatchNorm channels rows columns momentum) where\n  onnxOpTypeNames _ = [\"BatchNormalization\"]\n\ninstance (KnownNat channels, KnownNat rows, KnownNat columns, KnownNat momentum) => OnnxLoadable (BatchNorm channels rows columns momentum) where\n  loadOnnxNode inits node = case node ^. #input of\n    [_, scale, b, mean, var] -> do\n      epsilon     <- readFloatAttributeToRealNum \"epsilon\" node\n      loadedScale <- readInitializerVector inits scale\n      loadedB     <- readInitializerVector inits b\n      loadedMean  <- readInitializerVector inits mean\n      loadedVar   <- readInitializerVector inits var\n\n      return $ BatchNorm False (BatchNormParams loadedScale loadedB) loadedMean loadedVar epsilon mkListStore\n    _               -> onnxIncorrectNumberOfInputs\n\n\n", "meta": {"hexsha": "bf25036f28211ecc85c475f1175bb41fbcb1f370", "size": 19174, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/BatchNormalisation.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/BatchNormalisation.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/BatchNormalisation.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.7990654206, "max_line_length": 177, "alphanum_fraction": 0.6233962658, "num_tokens": 4631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4834921172987905}}
{"text": "{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE EmptyDataDeriving #-}\n{-# LANGUAGE EmptyCase #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE ExplicitNamespaces #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RankNTypes #-}\nmodule Models.Integrals.Types (module Models.Integrals.Types, module TLC.Terms) where\n\n-- import Data.Ratio\nimport Algebra.Classes\nimport qualified Algebra.Morphism.Affine as A\nimport qualified Algebra.Morphism.LinComb as LC\nimport Prelude hiding (Num(..), Fractional(..), (^), product, sum, pi, sqrt\n                      , exp, (**))\nimport Data.Complex\nimport TLC.Terms (type (\u2208)(..), Type(..), type(\u00d7), type(\u27f6))\nimport qualified Algebra.Expression as E\nimport Data.Function (on)\nimport Data.Foldable\nimport Data.List\n--------------------------------------------------------------------------------\n-- | Types\n\ntype C = Complex Double\n\ndata Zero deriving (Show,Eq,Ord)\nnewtype Number = Number (E.Expr Zero) deriving\n  (Additive,Group,AbelianAdditive,Multiplicative,Division,Field,Ring,Roots,Transcendental)\ninstance Scalable Number Number where (*^) = (*)\ntype Rat = Number\nfromNumber :: Number -> E.Expr Zero\nfromNumber (Number x) = x\nevalNumber :: Number -> Double\nevalNumber (Number e) = E.eval (\\case) e\ninstance Show Number where show = show . fromNumber\ninstance Eq Rat where\n  (==) = (==) `on` evalNumber\ninstance Ord Rat where\n  compare = compare `on` evalNumber\ninstance DecidableZero Rat where\n  isZero  = (== 0) . evalNumber\ntype RatLike \u03b1 = (Ring \u03b1, Ord \u03b1, DecidableZero \u03b1)\n\n\ntype Var \u03b3 = 'R \u2208 \u03b3\ndata Dir = Min | Max deriving (Eq,Ord,Show)\ndata Elem \u03b3 = Vari (Var \u03b3)\n            | Supremum Dir [Ret \u03b3] -- either minimum or maximum of the arguments\n  deriving (Eq, Ord, Show)\ntype Available \u03b1 \u03b3 = \u03b1 \u2208 \u03b3\ntype Expr \u03b3 = A.Affine (Var \u03b3) Rat\ntype Ret \u03b3 = E.Expr (Elem \u03b3)\ntype Cond \u03b3 = Cond' (Expr \u03b3)\ndata Cond' e = IsNegative { condExpr :: e }\n              -- Meaning of this constructor: expression \u2264 0\n              | IsZero { condExpr :: e }\n              -- Meaning of this constructor: expression = 0\n   deriving (Eq, Show, Functor, Foldable, Traversable, Ord)\n\ndata Domain \u03b3 = Domain { domainLoBounds, domainHiBounds :: [Expr \u03b3] }\n  deriving (Show, Eq, Ord)\n\n\n-- | needs to be 1st a order representation for optimisations to be\n-- implementable\ndata P (\u03b3 :: Type) where\n  Done :: Ret \u03b3 -> P \u03b3\n  Cond :: Cond \u03b3 -> P \u03b3 -> P \u03b3\n  Integrate :: Domain \u03b3 -> P (\u03b3 \u00d7 'R) -> P \u03b3\n  Add :: P \u03b3 -> P \u03b3 -> P \u03b3\n  Power :: P \u03b3 -> Rat -> P \u03b3\n  Mul :: [P \u03b3] -> P \u03b3\n  -- Can this replaced by \"Scale\"? No, because we do integration in\n  -- normalisation factors as well.\n  -- Scale :: Ret \u03b3 -> P \u03b3 -> P \u03b3\n  deriving (Ord, Eq)\n\n\nlift' :: Applicative f\n  => (forall v. Available v \u03b3 -> f (Available v \u03b4))\n  -> (forall v. Available v (\u03b3 \u00d7 \u03b1) -> f (Available v (\u03b4 \u00d7 \u03b1)))\nlift' _ (Get) = pure Get\nlift' f (Weaken x) = Weaken <$> (f x)\n\nclass VarTraversable t where\n  varTraverse :: (Applicative f)\n    => (forall x. Available x \u03b3 -> f (Available x \u03b4))\n    -> t \u03b3 -> f (t \u03b4)\n\ninstance VarTraversable Domain where\n varTraverse f (Domain los his)\n  = Domain <$> traverse (A.traverseVars f) los <*>\n               traverse (A.traverseVars f) his\n\ninstance VarTraversable P where\n  varTraverse f = \\case\n    Power e k -> Power <$> varTraverse f e <*> pure k\n    Done x -> Done <$> traverse (varTraverse f) x\n    Mul xs -> Mul <$> traverse (varTraverse f) xs\n    Integrate d e ->\n      Integrate <$> (varTraverse f d) <*> (varTraverse (lift' f) e)\n    Cond e x -> Cond <$> traverse (A.traverseVars f) e <*> varTraverse f x\n    Add x y  -> Add <$> varTraverse f x <*> varTraverse f y\n\ninstance VarTraversable Elem where\n  varTraverse f = \\case\n    Vari x -> Vari <$> f x\n    Supremum d es -> Supremum d <$> traverse (traverse (varTraverse f)) es\n\nderiving instance Show (P \u03b3)\n\n\n----------------------------------\n-- | Smart constructors\n\n\nconds_ :: [Cond \u03b3] -> P \u03b3 -> P \u03b3\nconds_ cs e = foldr Cond e cs\n\nisPositive,isNegative :: Expr \u03b3 -> Cond \u03b3\nisPositive e = isNegative (negate e)\nisNegative e = IsNegative e\n\n\n-- Domain without restriction\nfull :: Domain \u03b3\nfull = Domain [] []\n\nlessThan, greaterThan :: Expr \u03b3 -> Expr \u03b3 -> Cond \u03b3\nt `lessThan` u = isNegative (t - u)\nt `greaterThan` u = u `lessThan` t\n\n\n\n----------------------------\n-- Instances\n\ninstance Multiplicative (P \u03b3) where\n  one = Done one\n  x * y = Mul [x,y]\n\ninstance Division (P \u03b3) where\n  recip x = Power x (negate one)\n\ninstance AbelianAdditive (P \u03b3)\ninstance Group (P \u03b3) where\n  negate = (negate (one :: Ret \u03b3) *^)\ninstance Scalable (E.Expr (Elem \u03b3)) (P \u03b3) where\n  k *^ e = Done k * e\n\npattern PZero :: P \u03b3\npattern PZero <- Done E.Zero\n\ninstance Additive (P \u03b3) where\n  zero =  Done E.Zero\n  PZero + x = x\n  x + PZero = x\n  x + y = Add x y\n\n\n\nsetHere :: f \u03b3 -> (Var \u03b3 -> f \u03b3) -> Var (\u03b3 \u00d7 \u03b1) -> f \u03b3\nsetHere a f = \\case\n  Get -> a\n  Weaken x -> f x\n\n----------------------------------------------------------------\n-- Normalising substitutions of variables to affine expressions\n\ntype SubstE \u03b3 \u03b4 = Var \u03b3 -> Expr \u03b4\n\nwkSubst :: SubstE \u03b3 \u03b4 -> SubstE (\u03b3 \u00d7 \u03b1) (\u03b4 \u00d7 \u03b1)\nwkSubst f = \\case\n  Get -> A.var Get \n  Weaken x -> A.mapVars Weaken (f x)\n\nsubstExpr :: SubstE \u03b3 \u03b4 ->  Expr \u03b3 -> Expr \u03b4\nsubstExpr = A.subst\n\nsubstCond :: SubstE \u03b3 \u03b4 -> Cond \u03b3 -> Cond \u03b4\nsubstCond f = fmap (substExpr f)\n\nsubstDomain :: SubstE \u03b3 \u03b4 -> Domain \u03b3 -> Domain \u03b4\nsubstDomain f (Domain lo hi) = Domain\n                                 (nub (substExpr f <$> lo))\n                                 (nub (substExpr f <$> hi))\n\nwkP :: P \u03b3 -> P (\u03b3 \u00d7 \u03b1)\nwkP = substP $ \\i -> A.var (Weaken i) \n\nsubstElem :: forall \u03b3 \u03b6. SubstE \u03b3 \u03b6 -> Elem \u03b3 -> Ret \u03b6\nsubstElem v = \\case\n  Supremum dir es -> supremum dir (substRet v <$> es)\n  Vari x -> exprToPoly (v x)\n\nsubstRet  :: forall \u03b3 \u03b6. SubstE \u03b3 \u03b6 -> Ret \u03b3 -> Ret \u03b6\nsubstRet v = E.eval (substElem v)\n\nsubstP :: SubstE \u03b3 \u03b4 -> P \u03b3 -> P \u03b4\nsubstP f p0 = case p0 of\n  Done e -> Done (E.eval (substElem f) e)\n  Add p1 p2 -> substP f p1 + substP f p2\n  Power p k -> Power (substP f p) k\n  Mul ps -> Mul (substP f <$> ps)\n  Cond c p -> Cond (substCond f c) (substP f p)\n  Integrate d p -> Integrate (substDomain f d) (substP (wkSubst f) p) -- integrations are never simplified by substitution\n\nswap2P :: P (\u03b3 \u00d7 \u03b1 \u00d7 \u03b2) -> P (\u03b3 \u00d7 \u03b2 \u00d7 \u03b1)\nswap2P = substP $ \\case\n  Get -> A.var (Weaken Get)\n  Weaken Get -> A.var Get\n  Weaken (Weaken x) -> A.var (Weaken (Weaken x))\n\nwkExpr :: Expr \u03b3 -> Expr (\u03b3 \u00d7 \u03b2)\nwkExpr = substExpr (A.var . Weaken) \n\ncondVars :: Cond \u03b3 -> [Var \u03b3]\ncondVars c = case condExpr c of\n   (A.Affine _ e) -> map fst (LC.toList e)\n\nretVars :: Ret \u03b3 -> [Var \u03b3]\nretVars x = concatMap elemVars (toList x)\n\nelemVars :: Elem \u03b3 -> [Var \u03b3]\nelemVars = \\case\n   Vari x -> [x]\n   Supremum _ es -> concatMap retVars es\n\nsupremum :: Dir -> [Ret \u03b3] -> Ret \u03b3\nsupremum _ [e] = e\nsupremum dir es = \n  case traverse (fmap retToNumber . traverse (varTraverse (const Nothing))) es of\n    Just cs | not (null es) ->\n       constPoly ((case dir of\n                     Max -> maximum\n                     Min -> minimum)\n                   cs)\n    _ -> E.Var (Supremum dir es)\n\nconstPoly :: Number -> Ret \u03b3\nconstPoly (Number n) = (\\case) <$> n\n\nvarPoly :: 'R \u2208 \u03b3 -> Ret \u03b3\nvarPoly = E.Var . Vari\n\nretToNumber :: Ret 'Unit -> Number\nretToNumber = E.eval $ \\case\n     Vari x -> case x of\n     Supremum d xs -> (case d of Max -> maximum; Min -> minimum) (fmap retToNumber xs)\n\nnumberToRet :: Number -> Ret \u03b3\nnumberToRet (Number x) = fmap (\\case) x\nexprToPoly :: Expr \u03b3 -> Ret \u03b3\nexprToPoly = A.eval (fmap (\\case) .fromNumber) (E.Var .  Vari)\n\nmkSuprema :: Domain \u03b3 -> (Ret \u03b3, Ret \u03b3)\nmkSuprema (Domain los his) = (supremum Max $ map exprToPoly los,\n                              supremum Min $ map exprToPoly his)\n\n", "meta": {"hexsha": "4a585c9629551c2cce76bd7e5c25b82b4c7520d0", "size": 8065, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Models/Integrals/Types.hs", "max_stars_repo_name": "juliangrove/grove-bernardy-bayesian-semantics-tlc", "max_stars_repo_head_hexsha": "70efc3f8fcdf28a4560c77a9a4c089f3e978ff74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Models/Integrals/Types.hs", "max_issues_repo_name": "juliangrove/grove-bernardy-bayesian-semantics-tlc", "max_issues_repo_head_hexsha": "70efc3f8fcdf28a4560c77a9a4c089f3e978ff74", "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/Models/Integrals/Types.hs", "max_forks_repo_name": "juliangrove/grove-bernardy-bayesian-semantics-tlc", "max_forks_repo_head_hexsha": "70efc3f8fcdf28a4560c77a9a4c089f3e978ff74", "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": 29.5421245421, "max_line_length": 122, "alphanum_fraction": 0.609299442, "num_tokens": 2384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4833379965021626}}
{"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule Year2020.Day20 where\n\nimport Util hiding ((??))\n\nimport Numeric.LinearAlgebra\n\nimport Data.Char\nimport Data.Function\nimport Data.List hiding (find)\nimport Data.List.Extra hiding (find)\n\nimport Control.Arrow\nimport Control.Monad\n\nimport System.FilePath\n\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\ntype Tile = Matrix Z\n\nmakeTile :: [String] -> (Int, Tile)\nmakeTile (x:xs) = (n, fromLists (map (map (\\case '#' -> 1 ; _ -> 0)) xs))\n  where n = read (filter isDigit x) :: Int\n\ntransforms :: Tile -> [Tile]\ntransforms m = take 8 . scanl (&) m $ cycle [tr, flipud]\n\nplace :: Int -> Map Int Tile -> Map (Int, Int) (Int, Tile)\n       -> Int -> Int -> [[[(Int, Tile)]]]\nplace size tiles placed _ _ | Map.null tiles = pure . transpose\n  .  map (map snd) . groupOn (fst . fst) $ Map.toList placed\nplace size tiles placed x y = do\n  let xp = snd (placed Map.! (x - 1, y)) ?? (All, TakeLast 1)\n      yp = snd (placed Map.! (x, y - 1)) ?? (TakeLast 1, All)\n  (num, tile') <- Map.toList tiles\n  tile <- transforms tile'\n  guard $ (x == 1 || tile ?? (All, Take 1) == xp)\n       && (y == 1 || tile ?? (Take 1, All) == yp)\n  let (x', y') = ((+ x) *** (+ 1)) (divMod y size)\n  place size (Map.delete num tiles) (Map.insert (x, y) (num, tile) placed) x' y'\n\npart1, part2 :: [[(Int, Tile)]] -> Int\npart1 xs = product . map (fst . ($ xs)) $ (.) <$> [head, last] <*> [head, last]\npart2 = fromIntegral . minimum . checks . transforms . fromBlocks\n  . map (map ((?? (DropLast 1, DropLast 1)) . (?? (Drop 1, Drop 1)) . snd))\n  where goal = fromIntegral $ sumElements monster\n        check xs = sumElements $ cond (corr2 monster xs) goal 0 goal 0\n        checks (x:xs) = map ((sumElements x -) . check) (x:xs)\n        monster = snd . makeTile $ \"\" :\n          [ \"                  # \"\n          , \"#    ##    ##    ###\"\n          , \" #  #  #  #  #  #   \" ]\n\nmain = do\n  input <- readFile (replaceExtension __FILE__ \".in\")\n  let tiles = map makeTile . filter notNull $ paragraphs input\n      size = round . sqrt . fromIntegral $ length tiles\n  print . part2 . head $ place size (Map.fromList tiles) mempty 1 1\n\n", "meta": {"hexsha": "8116ec76261e5264f1b36df135e7bd09702e6a31", "size": 2152, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Year2020/Day20.hs", "max_stars_repo_name": "mingmingrr/advent-of-code-2018", "max_stars_repo_head_hexsha": "89b6f0474877f954aea0528069b5553d18174a99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-14T06:02:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-14T06:02:01.000Z", "max_issues_repo_path": "src/Year2020/Day20.hs", "max_issues_repo_name": "mingmingrr/advent-of-code-2018", "max_issues_repo_head_hexsha": "89b6f0474877f954aea0528069b5553d18174a99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Year2020/Day20.hs", "max_forks_repo_name": "mingmingrr/advent-of-code-2018", "max_forks_repo_head_hexsha": "89b6f0474877f954aea0528069b5553d18174a99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.625, "max_line_length": 80, "alphanum_fraction": 0.5799256506, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48331598617711985}}
{"text": "{-# LANGUAGE DeriveFunctor                            #-}\n{-# LANGUAGE DeriveGeneric                            #-}\n{-# LANGUAGE FlexibleContexts                         #-}\n{-# LANGUAGE GADTs                                    #-}\n{-# LANGUAGE KindSignatures                           #-}\n{-# LANGUAGE LambdaCase                               #-}\n{-# LANGUAGE NoStarIsType                             #-}\n{-# LANGUAGE RankNTypes                               #-}\n{-# LANGUAGE RecordWildCards                          #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE StandaloneDeriving                       #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeFamilyDependencies                   #-}\n{-# LANGUAGE TypeInType                               #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# LANGUAGE UndecidableInstances                     #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise       #-}\n\nmodule Numeric.Wavelet.Discrete (\n    DWavelet(..)\n  , DWT(..)\n  , cdwt\n  , dwt\n  , idwt\n  , haar\n    -- DWD(..)\n  -- , dwdApprox, dwdDetail\n  -- , flattenDWD\n  -- , denseDWD\n  -- , haar\n  -- , unHaar\n  ) where\n\nimport           Data.Complex\nimport           Data.Finite\nimport           Data.Finite.Internal\nimport           Data.Kind\nimport           Data.Proxy\nimport           Data.Vector.Generic.Sized    (Vector)\nimport           GHC.Generics\nimport           GHC.TypeLits.Compare\nimport           GHC.TypeNats\nimport           Numeric.Wavelet.Internal.FFT\nimport qualified Data.Vector                  as UV\nimport qualified Data.Vector.Generic          as UVG\nimport qualified Data.Vector.Generic.Sized    as VG\nimport qualified Data.Vector.Sized            as V\n\n\ndata DWavelet v l a = DW\n    { dwHiDecomp :: VG.Vector v l a      -- ^ High-pass decomposition filter\n    , dwLoDecomp :: VG.Vector v l a      -- ^ Low-pass decomposition filter\n    , dwHiRecon  :: VG.Vector v l a      -- ^ High-pass reconstruction filter\n    , dwLoRecon  :: VG.Vector v l a      -- ^ Low-pass reconstruction filter\n    }\n  deriving (Show, Eq, Ord, Functor, Generic)\n\ndata DWT v n a = DWT\n    { dwtApprox :: VG.Vector v n a\n    , dwtDetail :: VG.Vector v n a\n    }\n  deriving (Show, Eq, Ord, Functor, Generic)\n\ncdwt\n    :: (UVG.Vector v (Complex a), KnownNat l, KnownNat n, 1 <= l, 1 <= n, FFTWReal a)\n    => DWavelet  v l (Complex a)\n    -> VG.Vector v n (Complex a)\n    -> DWT v ((n + l - 1) `Div` 2) (Complex a)\ncdwt DW{..} x = DWT{..}\n  where\n    dwtApprox = downsamp $ convolve x dwLoDecomp\n    dwtDetail = downsamp $ convolve x dwHiDecomp\n\ndwt\n    :: (UVG.Vector v (Complex a), UVG.Vector v a, KnownNat l, KnownNat n, 1 <= l, 1 <= n, FFTWReal a)\n    => DWavelet  v l a\n    -> VG.Vector v n a\n    -> DWT v ((n + l - 1) `Div` 2) a\ndwt DW{..} x = DWT{..}\n  where\n    dwtApprox = downsamp $ rconvolve x dwLoDecomp\n    dwtDetail = downsamp $ rconvolve x dwHiDecomp\n\nidwt\n    :: forall v l n a.\n     ( UVG.Vector v (Complex a)\n     , UVG.Vector v a\n     , KnownNat l\n     , KnownNat n\n     , FFTWReal a\n     , Div ((((Div ((n + l) - 1) 2 * 2) + l) - 1) - n) 2 <= ((((Div ((n + l) - 1) 2 * 2) + l) - 1) - n)\n     )\n    => DWavelet  v l a\n    -> DWT v ((n + l - 1) `Div` 2) a\n    -> VG.Vector v n a      -- todo: remove the choice\nidwt DW{..} DWT{..} = VG.slice @_ @((((n+l-1)`Div`2)*2+l-1-n)`Div`2) @n @(((n+l-1)`Div`2)*2+l-1-n-((((n+l-1)`Div`2)*2+l-1-n)`Div`2)) Proxy $\n                VG.zipWith (+) x y\n  where\n    x = rconvolve (upsamp dwtApprox) dwLoRecon\n    y = rconvolve (upsamp dwtDetail) dwHiRecon\n\ndownsamp :: (UVG.Vector v a, KnownNat n) => VG.Vector v n a -> VG.Vector v (n `Div` 2) a\ndownsamp v = VG.generate $ \\i -> v `VG.index` doubleFinite i\n  where\n    doubleFinite :: Finite (n `Div` 2) -> Finite n\n    doubleFinite (Finite x) = Finite (x * 2 + 1)\n\nupsamp :: (UVG.Vector v a, KnownNat n, Num a) => VG.Vector v n a -> VG.Vector v (n * 2) a\nupsamp v = VG.generate $ \\i -> case separateProduct @2 i of\n    (j, k)\n      | j == 0    -> v `VG.index` k\n      | otherwise -> 0\n\n-- upsamp :: forall v n a. (UVG.Vector v a, KnownNat n, Num a) => VG.Vector v (n `Div` 2) a -> VG.Vector v n a\n-- upsamp v = VG.generate $ \\(Finite i) -> case i `divMod` 2 of\n--     (d, m)\n--       | m == 0    -> v `VG.index` Finite d\n--       | otherwise -> 0\n\n\n    -- let (j, k) = case separateProduct @2 i\n    -- in  if j == 0\n    --       then\n\n-- unhaarPass\n--     :: (UVG.Vector v a, KnownNat n, Num a)\n--     => Vector v (2 ^ n) a\n--     -> Vector v (2 ^ n) a\n--     -> Vector v (2 ^ (n + 1)) a\n-- unhaarPass app det = VG.generate $ \\i ->\n--     let (j, k) = separateProduct @2 i\n--         combiner\n--           | j == 0    = (+)\n--           | otherwise = (-)\n--     in  combiner (app `VG.index` k) (det `VG.index` k)\n\n\nhaar :: (UVG.Vector v a, Floating a) => DWavelet v 2 a\nhaar = DW{..}\n  where\n    srtot = sqrt 2 / 2\n    dwHiDecomp = VG.fromTuple (-srtot, srtot)\n    dwLoDecomp = VG.fromTuple ( srtot, srtot)\n    dwHiRecon  = VG.fromTuple ( srtot,-srtot)\n    dwLoRecon  = VG.fromTuple ( srtot, srtot)\n\n-- data DWD :: (Type -> Type) -> Nat -> Type -> Type where\n--     DWDZ :: { _dwdDetailZ :: !a\n--            , _dwdApprox  :: !a\n--            } -> DWD v 0 a\n--     DWDS :: { _dwdDetailS :: !(Vector  v (2 ^ (n + 1)) a)\n--            , _dwdNext    :: !(DWD v n             a)\n--            } -> DWD v (n + 1) a\n\n-- deriving instance (Show (v a), Show a) => Show (DWD v n a)\n\n-- dwdDetail :: UVG.Vector v a => DWD v n a -> Vector v (2 ^ n) a\n-- dwdDetail = \\case\n--     DWDZ d _ -> VG.singleton d\n--     DWDS d _ -> d\n\n-- dwdApprox :: DWD v n a -> a\n-- dwdApprox = \\case\n--     DWDZ _ a -> a\n--     DWDS _ a -> dwdApprox a\n\n-- testDec :: DWD UV.Vector 4 Double\n-- testDec = DWDS (0 :: V.Vector 16 Double)\n--         . DWDS (0 :: V.Vector  8 Double)\n--         . DWDS (0 :: V.Vector  4 Double)\n--         . DWDS (0 :: V.Vector  2 Double)\n--         $ DWDZ 0 0\n\n-- flattenDWD :: UVG.Vector v a => DWD v n a -> Vector v (2 ^ (n + 1)) a\n-- flattenDWD = \\case\n--     DWDZ d  a  -> VG.fromTuple (a, d)\n--     -- whoops this is O(n^2)\n--     DWDS ds as -> flattenDWD as VG.++ ds\n\n-- denseDWD\n--     :: forall v n a. (KnownNat n, UVG.Vector v a)\n--     => DWD v n a\n--     -> V.Vector (n + 1) (Vector v (2 ^ n) a)\n-- denseDWD = \\case\n--     DWDZ d  _  -> VG.singleton $ VG.singleton d\n--     -- whoops this is O(n^3) or something\n--     DWDS ds as -> (densify @_ @_ @(n - 1) <$> denseDWD as) `VG.snoc` ds\n\n-- densify\n--     :: (UVG.Vector v a, KnownNat n)\n--     => Vector v (2 ^ n) a\n--     -> Vector v (2 ^ (n + 1)) a\n-- densify xs = VG.generate $ \\i -> xs `VG.index` snd (separateProduct @2 i)\n\n-- haar\n--     :: forall v n a. (UVG.Vector v a, KnownNat n, Fractional a)\n--     => Vector  v (2 ^ (n + 1)) a\n--     -> DWD v n a\n-- haar xs = case pNat (Proxy @n) of\n--     PZ -> let x = xs `VG.index` 0\n--               y = xs `VG.index` 1\n--           in  DWDZ ((x - y) / 2) ((x + y) / 2)\n--     PS -> let (a, d) = haarPass xs\n--           in  DWDS d (haar a)\n\n-- unHaar\n--     :: (UVG.Vector v a, KnownNat n, Num a)\n--     => DWD v n a\n--     -> Vector v (2 ^ (n + 1)) a\n-- unHaar = \\case\n--     DWDZ d  a  -> VG.fromTuple (a + d, a - d)\n--     DWDS ds as -> unhaarPass (unHaar as) ds\n\n-- haarPass\n--     :: (UVG.Vector v a, KnownNat n, Fractional a)\n--     => Vector v (2 ^ (n + 1)) a\n--     -> (Vector v (2 ^ n) a, Vector v (2 ^ n) a)\n-- haarPass xs = (app, det)\n--   where\n--     app = VG.generate $ \\i -> ( xs `VG.index` combineProduct (0, i)\n--                               + xs `VG.index` combineProduct (1, i)\n--                               ) / 2\n--     det = VG.generate $ \\i -> ( xs `VG.index` combineProduct (0, i)\n--                               - xs `VG.index` combineProduct (1, i)\n--                               ) / 2\n\n-- unhaarPass\n--     :: (UVG.Vector v a, KnownNat n, Num a)\n--     => Vector v (2 ^ n) a\n--     -> Vector v (2 ^ n) a\n--     -> Vector v (2 ^ (n + 1)) a\n-- unhaarPass app det = VG.generate $ \\i ->\n--     let (j, k) = separateProduct @2 i\n--         combiner\n--           | j == 0    = (+)\n--           | otherwise = (-)\n--     in  combiner (app `VG.index` k) (det `VG.index` k)\n\n", "meta": {"hexsha": "0efa521cecf3578cc71e439863ae44c76027c20b", "size": 8246, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Wavelet/Discrete.hs", "max_stars_repo_name": "mstksg/wavelets", "max_stars_repo_head_hexsha": "0ab91527b74bf136c306a940f6d4534b330d8e1f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-10-11T20:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T07:49:54.000Z", "max_issues_repo_path": "src/Numeric/Wavelet/Discrete.hs", "max_issues_repo_name": "mstksg/pure-wavelets", "max_issues_repo_head_hexsha": "0ab91527b74bf136c306a940f6d4534b330d8e1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Wavelet/Discrete.hs", "max_forks_repo_name": "mstksg/pure-wavelets", "max_forks_repo_head_hexsha": "0ab91527b74bf136c306a940f6d4534b330d8e1f", "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.3583333333, "max_line_length": 140, "alphanum_fraction": 0.4951491632, "num_tokens": 2730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48316105699423434}}
{"text": "module Main where\n\nimport Parser\nimport Analyzer\nimport qualified Data.MultiSet as M\nimport Control.Lens hiding ((??),(|>),(<.>))\nimport qualified Data.Text.Lazy.IO as I\nimport Data.List (sortBy)\nimport Data.Function (on)\nimport Text.Megaparsec (parseMaybe)\nimport Numeric.LinearAlgebra\nimport Data.Complex (realPart)\n\nfile :: String\nfile = \"/home/bertram/Downloads/la famiglia.txt\"\n\nmessages :: IO [Chunk]\nmessages = filter isMessage <$> ((parseMaybe chunksP <$> I.readFile file)\n           >>= maybe (putStrLn \"Parse failed\" >> return []) return)\n\nmain' :: IO ()\nmain' = do\n  msg <- messages\n  let users = map (toText . (^.user)) msg\n  let counts = M.fromList users\n  mapM_ (\\(a,b)->I.putStr a >> putStr \" | \" >> print b) . sortBy (compare `on` snd) . M.toOccurList $ counts\n\nmain :: IO ()\nmain = do\n  input <- I.readFile file\n  let (matrix,users) = maybe undefined id (parseMaybe matrixP input)\n  let n = length users\n  let probs =  cmap realPart . flatten . (?? (All, Take 1)) \n               . snd . eig . tr $ matrix\n  let probs' = scale (1 / (probs <.> (n |> repeat 1))) probs\n  mapM_ print . sortBy (compare `on` snd). zip users $ toList probs'\n  print $ sum . toList $ probs'\n", "meta": {"hexsha": "54c5558d8afb3abc4343c3c4bc7688769ee276af", "size": 1185, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "bnarnold/WAAnalyzer", "max_stars_repo_head_hexsha": "fd2347d773a0ce55bf8c1b33c322719e95843105", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "bnarnold/WAAnalyzer", "max_issues_repo_head_hexsha": "fd2347d773a0ce55bf8c1b33c322719e95843105", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main.hs", "max_forks_repo_name": "bnarnold/WAAnalyzer", "max_forks_repo_head_hexsha": "fd2347d773a0ce55bf8c1b33c322719e95843105", "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.1842105263, "max_line_length": 108, "alphanum_fraction": 0.6540084388, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4828262687252267}}
{"text": "module D20\n    ( largestNumberOfDoors, countRoomsAfterDoors\n    ) where\n\nimport Text.Parsec\nimport Data.Functor.Identity\nimport Data.Either\nimport Data.Complex\nimport qualified Data.HashMap.Strict as M\n\ntype Position = Complex Float\ndata Navigation = Navigation  { currentPosition :: Position\n                              , pastBranches :: [Position]\n                              , distances :: M.HashMap Position Int } deriving (Show,Eq)\n\nchangePosition :: Position -> Navigation -> Navigation\nchangePosition p (Navigation cp pb d) = Navigation np pb (M.insert np (shortest (M.lookup np d) (M.lookup cp d)) d)\n  where np=cp+p\n        shortest Nothing (Just n) = n+1\n        shortest (Just n) Nothing = n\n        shortest (Just m) (Just n) = min m (n+1)\n\nenterBranch :: Navigation -> Navigation\nenterBranch (Navigation cp pb d) = Navigation cp (cp:pb) d\n\ntryAlternateBranch :: Navigation -> Navigation\ntryAlternateBranch (Navigation _ pb@(p:_) d) = Navigation p pb d\n\nleaveBranch :: Navigation -> Navigation\nleaveBranch (Navigation _ (p:pb) d) = Navigation p pb d\n\ntype RoomParser = ParsecT String Navigation Identity\n\ntryAllPaths :: ParsecT String Navigation Identity Navigation\ntryAllPaths = char '^'\n              >> (many $ choice [ char 'N' >> modifyState (changePosition $ 0:+(-1))\n                                , char 'S' >> modifyState (changePosition $ 0:+1)\n                                , char 'E' >> modifyState (changePosition $ 1:+0)\n                                , char 'W' >> modifyState (changePosition $ (-1):+0)\n                                , char '(' >> modifyState enterBranch\n                                , char '|' >> modifyState tryAlternateBranch\n                                , char ')' >> modifyState leaveBranch ])\n              >> char '$'\n              >> getState\n\ngetAllDistances :: String -> [Int]\ngetAllDistances = M.elems . distances . fromRight nav . runParser tryAllPaths nav \"\"\n  where nav = Navigation (0:+0) [] (M.singleton (0:+0) 0)\n\nlargestNumberOfDoors :: String -> Int\nlargestNumberOfDoors = maximum . getAllDistances\n\ncountRoomsAfterDoors :: Int -> String -> Int\ncountRoomsAfterDoors threshold = length . filter (((<=)threshold)) . getAllDistances\n\n", "meta": {"hexsha": "f2bf1d09735f3f1a49142da049c9709ec82cd0c1", "size": 2210, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/D20.hs", "max_stars_repo_name": "Oaz/aoc2018", "max_stars_repo_head_hexsha": "7a3dc0a62581aad0bae8d69da80d87fe40592cc7", "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/D20.hs", "max_issues_repo_name": "Oaz/aoc2018", "max_issues_repo_head_hexsha": "7a3dc0a62581aad0bae8d69da80d87fe40592cc7", "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/D20.hs", "max_forks_repo_name": "Oaz/aoc2018", "max_forks_repo_head_hexsha": "7a3dc0a62581aad0bae8d69da80d87fe40592cc7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4642857143, "max_line_length": 115, "alphanum_fraction": 0.6176470588, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48264435146548984}}
{"text": "{-|\nModule      : Lib\nDescription : Main component of your project.\nCopyright   : (c) Fabricio Olivetti de Franca, 2021\nLicense     : GPL-3\nMaintainer  : fabricio.olivetti@gmail.com\nStability   : experimental\nPortability : POSIX\n|-}\n\nmodule GAPoly\n    ( parseFile\n    , runGA\n    , generateReports\n    , Solution(..)\n    , Poly(..)\n    ) where\n\nimport GA\nimport Fitness\nimport Dataset\nimport Report\nimport Random\nimport Evolution\n\nimport Control.Monad.State.Strict\nimport System.Random\nimport Numeric.LinearAlgebra (Vector)\nimport GHC.TypeLits\n\ngaPoly :: KnownNat n => Double -> Evolution (Poly n)\ngaPoly pm = Select generational End\n              (Cross crossover\n                (Mutate (mutate pm) End))\n\n-- | Run a genetic algorithm with the provided parameters\nrunGA :: KnownNat n => Int -> Int -> Int -> Int -> Double -> [[Double]] -> Vector Double -> IO ([Double], Solution (Poly n))\nrunGA nTerms nVars it nPop pm xss ys =\n  do g <- newStdGen \n     let fitness   = evalFitness nTerms xss ys\n         createSol = createRndSolution (nVars*nTerms) \n         gens      = runEvolution createSol fitness it nPop (gaPoly pm)\n     evalStateT gens g\n\n", "meta": {"hexsha": "b73215679d5bb61b33884ed90e5d9270c1141351", "size": 1149, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/GAPoly.hs", "max_stars_repo_name": "folivetti/gapoly", "max_stars_repo_head_hexsha": "a0e2b727f046b1284353f56699b0459ed536155d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-06T11:25:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T11:25:13.000Z", "max_issues_repo_path": "src/GAPoly.hs", "max_issues_repo_name": "folivetti/gapoly", "max_issues_repo_head_hexsha": "a0e2b727f046b1284353f56699b0459ed536155d", "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/GAPoly.hs", "max_forks_repo_name": "folivetti/gapoly", "max_forks_repo_head_hexsha": "a0e2b727f046b1284353f56699b0459ed536155d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5333333333, "max_line_length": 124, "alphanum_fraction": 0.6744995648, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48264434513635973}}
{"text": "module ComplexUtils (toComplex, toComplexM) where\n\nimport Data.Complex (Complex((:+)))\n\n\ntoComplex :: Double -> (Complex Double)\ntoComplex a = (a :+ 0)\n\n\ntoComplexM :: [Double] -> [(Complex Double)]\ntoComplexM = map toComplex\n", "meta": {"hexsha": "ff0fbcbc3e1d3947acced95296df5aa099cca226", "size": 226, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ComplexUtils.hs", "max_stars_repo_name": "vined/fourier", "max_stars_repo_head_hexsha": "804a11098c912bb6bbac2e8ae5fa419aab10bb43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ComplexUtils.hs", "max_issues_repo_name": "vined/fourier", "max_issues_repo_head_hexsha": "804a11098c912bb6bbac2e8ae5fa419aab10bb43", "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/ComplexUtils.hs", "max_forks_repo_name": "vined/fourier", "max_forks_repo_head_hexsha": "804a11098c912bb6bbac2e8ae5fa419aab10bb43", "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": 18.8333333333, "max_line_length": 49, "alphanum_fraction": 0.6946902655, "num_tokens": 62, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.48233634339961634}}
{"text": "module Math.FROG.Types\n( Nonlinearity(..)\n, ComplexSignal\n, Trace\n) where\n\nimport qualified Numeric.LinearAlgebra as LA\n\n\ntype ComplexSignal = LA.Vector (LA.Complex Double)\ntype Trace = LA.Matrix Double\n\n\ndata Nonlinearity = PG | SHG | SD | THG\n", "meta": {"hexsha": "32297c2a96d4ca17dec6a6990bb35a707b49489d", "size": 245, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/FROG/Types.hs", "max_stars_repo_name": "leroix/haskell-spsa-frog", "max_stars_repo_head_hexsha": "0ff98b2941840b317a08a0c2a8aa8d101c1503fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-25T19:38:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-25T19:38:00.000Z", "max_issues_repo_path": "src/Math/FROG/Types.hs", "max_issues_repo_name": "leroix/haskell-spsa-frog", "max_issues_repo_head_hexsha": "0ff98b2941840b317a08a0c2a8aa8d101c1503fe", "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/Math/FROG/Types.hs", "max_forks_repo_name": "leroix/haskell-spsa-frog", "max_forks_repo_head_hexsha": "0ff98b2941840b317a08a0c2a8aa8d101c1503fe", "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": 16.3333333333, "max_line_length": 50, "alphanum_fraction": 0.7428571429, "num_tokens": 66, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4820503985375163}}
{"text": "{-# language BangPatterns        #-}\n{-# language LambdaCase          #-}\n{-# language NoImplicitPrelude   #-}\n{-# language ScopedTypeVariables #-}\n\n-- | This module exposes functions for performing\n--   Fast Fourier Transform (FFT) and Inverse Fast Fourier Transform (IFFT)\n--   over 'Contiguous' data structures.\nmodule Data.Primitive.Contiguous.FFT\n  ( fft\n  , ifft\n  , mfft\n  ) where\n\nimport qualified Prelude\n\nimport Control.Applicative (pure)\nimport Control.Monad (when)\nimport Control.Monad.Primitive (PrimMonad(..))\nimport Control.Monad.ST (runST)\nimport Data.Bits (shiftR,shiftL,(.&.),(.|.))\nimport Data.Bool (Bool,otherwise)\nimport Data.Complex (Complex(..),conjugate)\nimport Data.Eq (Eq(..))\nimport Data.Function (($),(.))\nimport Data.Ord (Ord(..))\nimport Data.Primitive.Contiguous (Contiguous,Element,Mutable)\nimport Data.Semiring (negate,(+),(*),(-))\nimport GHC.Exts\nimport GHC.Real ((/))\nimport qualified Data.Primitive.Contiguous as Contiguous\n\n{-# RULES\n\"fft/ifft\" forall x. fft (ifft x) = x\n\"ifft/fft\" forall x. ifft (fft x) = x\n  #-}\n\n-- | Radix-2 decimation-in-time fast Fourier Transform.\n--   The given array must have a length that is a power of two.\nfft :: forall arr. (Contiguous arr, Element arr (Complex Double))\n  => arr (Complex Double)\n  -> arr (Complex Double)\n{-# inlinable [1] fft #-}\nfft arr = if arrOK arr\n  then runST $ do {\n      marr <- copyWhole arr\n    ; mfft marr\n    ; Contiguous.unsafeFreeze marr\n  }\n  else Prelude.error \"Data.Primitive.Contiguous.FFT.fft: bad array length\"\n-- | Inverse fast Fourier transform.\nifft :: forall arr. (Contiguous arr, Element arr (Complex Double))\n  => arr (Complex Double)\n  -> arr (Complex Double)\n{-# inlinable [1] ifft #-}\nifft arr = if arrOK arr\n  then\n    let lenComplex = intToComplexDouble (Contiguous.size arr)\n    in cmap ((/lenComplex) . conjugate) . fft . cmap conjugate $ arr\n  else Prelude.error \"Data.Primitive.Contiguous.FFT.ifft: bad vector length\"\n\ncopyWhole :: forall arr m a. (PrimMonad m, Contiguous arr, Element arr a)\n  => arr a\n  -> m (Mutable arr (PrimState m) a)\n{-# inline copyWhole #-}\ncopyWhole arr = do\n  let len = Contiguous.size arr\n  marr <- Contiguous.new len\n  Contiguous.copy marr 0 arr 0 len\n  pure marr\n\narrOK :: forall arr a. (Contiguous arr, Element arr a)\n  => arr a\n  -> Bool\n{-# inline arrOK #-}\narrOK arr =\n  let n = Contiguous.size arr\n  in (1 `shiftL` log2 n) == n\n\n-- | Radix-2 decimation-in-time fast Fourier Transform.\n--   The given array must have a length that is a power of two,\n--   though this property is not checked.\nmfft :: forall arr m. (PrimMonad m, Contiguous arr, Element arr (Complex Double))\n  => Mutable arr (PrimState m) (Complex Double)\n  -> m ()\nmfft mut = do {\n    len <- Contiguous.sizeMutable mut\n  ; let bitReverse !i !j = do {\n          ; if i == len - 1\n              then stage 0 1\n              else do {\n                  when (i < j) $ swap mut i j\n                ; let inner k l = if k <= l\n                        then inner (k `shiftR` 1) (l - k)\n                        else bitReverse (i + 1) (l + k)\n                ; inner (len `shiftR` 1) j\n              }\n        }\n        stage l l1 = if l == (log2 len)\n          then pure ()\n          else do {\n              let !l2 = l1 `shiftL` 1\n                  !e = (negate twoPi) / (intToDouble l2)\n                  flight j !a = if j == l1\n                    then stage (l + 1) l2\n                    else do {\n                        let butterfly i = if i >= len\n                              then flight (j + 1) (a + e)\n                              else do {\n                                  let i1 = i + l1\n                                ; xi1 :+ yi1 <- Contiguous.read mut i1\n                                ; let !c = Prelude.cos a\n                                      !s' = Prelude.sin a\n                                      d = (c*xi1 - s'*yi1) :+ (s'*xi1 + c*yi1)\n                                ; ci <- Contiguous.read mut i\n                                ; Contiguous.write mut i1 (ci - d)\n                                ; Contiguous.write mut i (ci + d)\n                                ; butterfly (i + l2)\n                              }\n                      ; butterfly j\n                    }\n            ; flight 0 0\n         }\n  ; bitReverse 0 0\n}\n\n-- wildcard cases should never happen. if they do, really bad things will happen.\nb,s :: Int -> Int\nb = \\case { 0 -> 0x02; 1 -> 0x0c; 2 -> 0xf0; 3 -> 0xff00; 4 -> wordToInt 0xffff0000; 5 -> wordToInt 0xffffffff00000000; _ -> 0; }\ns = \\case { 0 -> 1; 1 -> 2; 2 -> 4; 3 -> 8; 4 -> 16; 5 -> 32; _ -> 0; }\n{-# inline b #-}\n{-# inline s #-}\n\nlog2 :: Int -> Int\nlog2 v0 = if v0 <= 0\n  then Prelude.error $ \"Data.Primitive.Contiguous.FFT: nonpositive input, got \" Prelude.++ Prelude.show v0\n  else go 5 0 v0\n  where\n    go !i !r !v\n      | i == -1 = r\n      | v .&. b i /= 0 =\n          let si = s i\n          in go (i - 1) (r .|. si) (v `shiftR` si)\n      | otherwise = go (i - 1) r v\n\nswap :: forall arr m x. (PrimMonad m, Contiguous arr, Element arr x)\n  => Mutable arr (PrimState m) x\n  -> Int\n  -> Int\n  -> m ()\n{-# inline swap #-}\nswap mut i j = do\n  atI <- Contiguous.read mut i\n  atJ <- Contiguous.read mut j\n  Contiguous.write mut i atJ\n  Contiguous.write mut j atI\n\ntwoPi :: Double\n{-# inline twoPi #-}\ntwoPi = 6.283185307179586\n\nintToDouble :: Int -> Double\n{-# inline intToDouble #-}\nintToDouble = Prelude.fromIntegral\n\nwordToInt :: Word -> Int\n{-# inline wordToInt #-}\nwordToInt = Prelude.fromIntegral\n\nintToComplexDouble :: Int -> Complex Double\n{-# inline intToComplexDouble #-}\nintToComplexDouble = Prelude.fromIntegral\n\ncmap :: (Contiguous arr, Element arr (Complex Double))\n  => (Complex Double -> Complex Double)\n  -> arr (Complex Double)\n  -> arr (Complex Double)\n{-# inline cmap #-}\ncmap = Contiguous.map\n", "meta": {"hexsha": "6c2cb0fbf42067d3c1e6ce443e45690442ee2a5a", "size": 5803, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Primitive/Contiguous/FFT.hs", "max_stars_repo_name": "nprindle/contiguous-fft", "max_stars_repo_head_hexsha": "39277125cc183480de21ce06d6beacd1eeead68a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-07-02T18:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-17T13:54:36.000Z", "max_issues_repo_path": "src/Data/Primitive/Contiguous/FFT.hs", "max_issues_repo_name": "nprindle/contiguous-fft", "max_issues_repo_head_hexsha": "39277125cc183480de21ce06d6beacd1eeead68a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-08-05T05:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-15T18:53:20.000Z", "max_forks_repo_path": "src/Data/Primitive/Contiguous/FFT.hs", "max_forks_repo_name": "chessai/contiguous-fft", "max_forks_repo_head_hexsha": "39277125cc183480de21ce06d6beacd1eeead68a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-17T22:44:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-17T22:44:07.000Z", "avg_line_length": 32.2388888889, "max_line_length": 129, "alphanum_fraction": 0.5607444425, "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4818720734831431}}
{"text": "------------------------------------------------\n-- |\n-- Module    :  Numeric.Matrix.Integral.SmithNF\n-- Copyright :  (c) Jun Yoshida 2019\n-- License   :  BSD3\n--\n-- Compute Smith normal form\n--\n------------------------------------------------\n\nmodule Numeric.Matrix.Integral.SmithNF where\n\nimport Control.Monad (when, unless, forM_, guard, join)\nimport Control.Monad.ST\nimport Control.Monad.Loops (whileM_, whileJust_)\n\nimport Data.List as L\nimport Data.STRef\n\nimport Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Devel\n\n--import Numeric.Matrix.Integral.HNFLLL (hnfLLLST)\nimport Numeric.Matrix.Integral.NormalForms (hermiteNFST)\n\n-- | Find off-diagonal entries and calculate min of min{row,col} among them\nfindDiagSz :: LA.Matrix LA.Z -> Maybe Int\nfindDiagSz ma =\n  let offdiag = filter (uncurry (/=)) $ LA.find (/=0) ma\n  in L.foldl' bin Nothing offdiag\n  where\n    bin Nothing (i,j) = Just (min i j)\n    bin (Just k) (i,j) = Just $ L.foldl' min k [i,j]\n\n-- | Compute \"pre-Smith\" form with a function calculating Hermite normal forms\n-- \"Pre-Smith\" means diag(c_1,c_2,..) with not necessarily c_i|c_{i+1}\npreSmithNFST :: STMatrix s LA.Z -> STMatrix s LA.Z ->  STMatrix s LA.Z -> ST s ()\npreSmithNFST stMatUL stMatA stMatURt = do\n  whileJust_ (liftSTMatrix findDiagSz stMatA) $ \\diagSz -> do\n    -- Extract a submatrix containing all the off-diagonal entries.\n    stMatAex <- thawMatrix =<< extractMatrix stMatA (FromRow diagSz) (FromCol diagSz)\n    stMatULex <- thawMatrix =<< extractMatrix stMatUL (FromRow diagSz) AllCols\n    stMatURtex <- thawMatrix =<< extractMatrix stMatURt (FromRow diagSz) AllCols\n    -- Compute the Hermite normal forms of the extracted submatrix and of the transpose of the result.\n    --hnfLLLST stMatULex stMatAex\n    join $ hermiteNFST <$> newMatrix 0 0 0 <*> pure stMatULex <*> pure stMatAex\n    stMatAext <- thawMatrix =<< (LA.tr' <$> freezeMatrix stMatAex)\n    --hnfLLLST stMatURtex stMatAext\n    join $ hermiteNFST <$> newMatrix 0 0 0 <*> pure stMatURtex <*> pure stMatAext\n    -- Write out the result\n    setMatrix stMatA diagSz diagSz =<< (LA.tr' <$> freezeMatrix stMatAext)\n    setMatrix stMatUL diagSz 0 =<< freezeMatrix stMatULex\n    setMatrix stMatURt diagSz 0 =<< freezeMatrix stMatURtex\n\nisHeadGCD :: LA.Vector LA.Z -> Bool\nisHeadGCD = isHeadGCD' . LA.toList\n  where\n    isHeadGCD' [] = True\n    isHeadGCD' (x:xs) = L.foldl' (\\b y -> b && rem y x == 0) True xs\n\n-- Compute the submatrix containing all the non-zero diagonal entries\nextractMaxNZDiag :: LA.Matrix LA.Z -> (Int,LA.Matrix LA.Z)\nextractMaxNZDiag mx = runST $ do\n  dRef <- newSTRef 0\n  let p d = d < uncurry min (LA.size mx) && (mx!d!d) /= 0\n  whileM_ (p <$> readSTRef dRef) $ modifySTRef' dRef (+1)\n  d <- readSTRef dRef\n  return (d,LA.subMatrix (0,0) (d,d) mx)\n\n-- | Normalize diagonals to form a divisible chain; i.e. c_1 | c_2 | c_3 | ...\nnormalizeST :: STMatrix s LA.Z -> STMatrix s LA.Z ->  STMatrix s LA.Z -> ST s ()\nnormalizeST stMatUL stMatA stMatURt = do\n  (dlen,matD) <- liftSTMatrix extractMaxNZDiag stMatA\n  stMatD <- thawMatrix matD\n  stMatULex <- thawMatrix =<< extractMatrix stMatUL (RowRange 0 (dlen-1)) AllCols\n  stMatURtex <- thawMatrix =<< extractMatrix stMatURt (RowRange 0 (dlen-1)) AllCols\n  normalizeST' stMatULex stMatD stMatURtex\n  setMatrix stMatA 0 0 =<< freezeMatrix stMatD\n  setMatrix stMatUL 0 0 =<< freezeMatrix stMatULex\n  setMatrix stMatURt 0 0 =<< freezeMatrix stMatURtex\n  where\n    normalizeST' stMatULex stMatD stMatURtex = do\n      b <- (isHeadGCD . LA.takeDiag) <$> freezeMatrix stMatD\n      n <- liftSTMatrix LA.rows stMatD\n      unless b $ do\n        forM_ [1..(n-1)] $ \\i -> do\n          readMatrix stMatD i i >>= writeMatrix stMatD i 0\n          rowOper (AXPY 1 i 0 AllCols) stMatURtex\n        preSmithNFST stMatULex stMatD stMatURtex\n      when (n > 1) $ do\n        stMatDex <- thawMatrix =<< extractMatrix stMatD (FromRow 1) (FromCol 1)\n        stMatULexex <- thawMatrix =<< extractMatrix stMatULex (FromRow 1) AllCols\n        stMatURtexex <- thawMatrix =<< extractMatrix stMatURtex (FromRow 1) AllCols\n        normalizeST' stMatULexex stMatDex stMatURtexex\n        setMatrix stMatD 1 1 =<< freezeMatrix stMatDex\n        setMatrix stMatULex 1 0 =<< freezeMatrix stMatULexex\n        setMatrix stMatURtex 1 0 =<< freezeMatrix stMatURtexex\n\n-- | Compute Smith normal form together with transform unimodular matrices.\nsmithNF :: LA.Matrix LA.Z -> (LA.Matrix LA.Z, LA.Matrix LA.Z, LA.Matrix LA.Z)\nsmithNF matA = runST $ do\n  stMatA <- thawMatrix matA\n  stMatUL <- thawMatrix $ LA.ident (LA.rows matA)\n  stMatURt <- thawMatrix $ LA.ident (LA.cols matA)\n  preSmithNFST stMatUL stMatA stMatURt\n  normalizeST stMatUL stMatA stMatURt\n  resMatS <- freezeMatrix stMatA\n  resMatUL <- freezeMatrix stMatUL\n  resMatURt <- freezeMatrix stMatURt\n  return (resMatUL, resMatS, LA.tr' resMatURt)\n\n-- | For debug.\n-- Compute \"pre-Smith form.\"\npreSmithNF :: LA.Matrix LA.Z -> (LA.Matrix LA.Z, LA.Matrix LA.Z, LA.Matrix LA.Z)\npreSmithNF matA = runST $ do\n  stMatA <- thawMatrix matA\n  stMatUL <- thawMatrix $ LA.ident (LA.rows matA)\n  stMatURt <- thawMatrix $ LA.ident (LA.cols matA)\n  preSmithNFST stMatUL stMatA stMatURt\n  resMatS <- freezeMatrix stMatA\n  resMatUL <- freezeMatrix stMatUL\n  resMatURt <- freezeMatrix stMatURt\n  return (resMatUL, resMatS, LA.tr' resMatURt)\n", "meta": {"hexsha": "948033c19c41c26dbd7b4e999b1fc71c8712c08e", "size": 5313, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Matrix/Integral/SmithNF.hs", "max_stars_repo_name": "Junology/linkedgram", "max_stars_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-21T06:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:54:21.000Z", "max_issues_repo_path": "src/Numeric/Matrix/Integral/SmithNF.hs", "max_issues_repo_name": "Junology/linkedgram", "max_issues_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Matrix/Integral/SmithNF.hs", "max_forks_repo_name": "Junology/linkedgram", "max_forks_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "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": 42.8467741935, "max_line_length": 102, "alphanum_fraction": 0.6890645586, "num_tokens": 1733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954684, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4818646887756967}}
{"text": "{-# LANGUAGE ViewPatterns #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module      : ArrayFire.Signal\n-- Copyright   : David Johnson (c) 2019-2020\n-- License     : BSD 3\n-- Maintainer  : David Johnson <djohnson.m@gmail.com>\n-- Stability   : Experimental\n-- Portability : GHC\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft.htm)\n--\n-- Functions performing signal processing on 'Array'\n--\n-- >>> input = vector 3 [10,20,30]\n-- >>> positions = vector 5 [0.0, 0.5, 1.0, 1.5, 2.0]\n-- >>> approx1 @Double input positions Cubic 0.0\n-- ArrayFire Array\n-- [5 1 1 1]\n--    10.0000\n--    13.7500\n--    20.0000\n--    26.2500\n--    30.0000\n--\n--------------------------------------------------------------------------------\nmodule ArrayFire.Signal where\n\nimport Data.Complex\n\nimport ArrayFire.FFI\nimport ArrayFire.Internal.Signal\nimport ArrayFire.Internal.Types\n\n-- | 'approx1' interpolates data along the first dimensions\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__approx1.htm)\n--\n-- Interpolation is performed assuming input data is equally spaced with indices in the range [0, n). The positions are sampled with respect to data at these locations.\n--\n-- >>> input = vector 3 [10,20,30]\n-- >>> positions = vector 5 [0.0, 0.5, 1.0, 1.5, 2.0]\n-- >>> approx1 @Double input positions Cubic 0.0\n-- ArrayFire Array\n-- [5 1 1 1]\n--    10.0000\n--    13.7500\n--    20.0000\n--    26.2500\n--    30.0000\napprox1\n  :: AFType a\n  => Array a\n  -- ^ the input array\n  -> Array a\n  -- ^ array contains the interpolation locations\n  -> InterpType\n  -- ^ is the interpolation type, it can take one of the values defined by 'InterpType'\n  -> Float\n  -- ^ is the value that will set in the output array when certain index is out of bounds\n  -> Array a\n  -- ^ is the array with interpolated values\napprox1 arr1 arr2 (fromInterpType -> i1) f =\n  op2 arr1 arr2 (\\p x y -> af_approx1 p x y i1 f)\n\n-- | approx2 performs interpolation on data along the first and second dimensions.\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__approx2.htm)\n--\n-- Interpolation is performed assuming input data is equally spaced with indices in the range [0, n) along each dimension. The positions are sampled with respect to data at these locations.\n--\n-- >>> input = matrix @Double (3,3) [ [ 1.0,1.0,1.0 ], [ 2.0, 2.0, 2.0 ], [ 3.0,3.0,3.0 ] ]\n-- >>> positions1 = matrix @Double (2,2) [ [ 0.5,1.5 ],[ 0.5,1.5 ] ]\n-- >>> positions2 = matrix @Double (2,2) [ [ 0.5,0.5 ],[ 1.5,1.5 ] ]\n-- >>> approx2 @Double input positions1 positions2 Cubic 0.0\n-- ArrayFire Array\n-- [2 2 1 1]\n--     1.3750     2.6250\n--     1.3750     2.6250\n--\napprox2\n  :: AFType a\n  => Array a\n  -- ^ is the input array\n  -> Array a\n  -- ^ array contains the interpolation locations for first dimension\n  -> Array a\n  -- ^ array contains the interpolation locations for second dimension\n  -> InterpType\n  -- ^ is the interpolation type, it can take one of the values defined by 'InterpType'\n  -> Float\n  -- ^ is the value that will set in the output array when certain index is out of bounds\n  -> Array a\n  -- ^\tis the array with interpolated values\napprox2 arr1 arr2 arr3 (fromInterpType -> i1) f =\n  op3 arr1 arr2 arr3 (\\p x y z -> af_approx2 p x y z i1 f)\n\n-- DMJ: Where did these functions go? Were they removed?\n-- http://arrayfire.org/docs/group__approx__mat.htm\n-- approx1Uniform\n--   :: AFType a\n--   => Array a\n--   -> Array a\n--   -> Int\n--   -> Double\n--   -> Double\n--   -> InterpType\n--   -> Float\n--   -> Array a\n-- approx1Uniform arr1 arr2 (fromIntegral -> i1) d1 d2 (fromInterpType -> interp) f =\n--   op2 arr1 arr2 (\\p x y -> af_approx1_uniform p x y i1 d1 d2 interp f)\n\n-- approx2Uniform\n--   :: AFType a\n--   => Array a\n--   -> Array a\n--   -> Int\n--   -> Double\n--   -> Double\n--   -> Array a\n--   -> Int\n--   -> Double\n--   -> Double\n--   -> InterpType\n--   -> Float\n--   -> Array a\n-- approx2Uniform arr1 arr2 (fromIntegral -> i1) d1 d2 arr3 (fromIntegral -> i2) d3 d4 (fromInterpType -> interp) f =\n--   op3 arr1 arr2 arr3 (\\p x y z -> af_approx2_uniform p x y i1 d1 d2 z i2 d3 d4 interp f)\n\n-- | Fast Fourier Transform\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft.htm#ga64d0db9e59c9410ba738591ad146a884)\n--\n-- The Fast Fourier Transform (FFT) is an efficient algorithm to compute the discrete Fourier transform (DFT) of a signal or array. This is most commonly used to convert data in the time (or space) domain to the frequency domain, Then, the inverse FFT (iFFT) is used to return the data to the original domain.\n--\n-- >>> fft (vector @Double 10 [1..]) 2.0 10\n-- ArrayFire Array\n-- [10 1 1 1]\n--          (110.0000,0.0000)\n--          (-10.0000,30.7768)\n--          (-10.0000,13.7638)\n--          (-10.0000,7.2654)\n--          (-10.0000,3.2492)\n--          (-10.0000,0.0000)\n--          (-10.0000,-3.2492)\n--          (-10.0000,-7.2654)\n--          (-10.0000,-13.7638)\n--          (-10.0000,-30.7768)\nfft\n  :: (AFType a, Fractional a)\n  => Array a\n  -- ^ input 'Array'\n  -> Double\n  -- ^ the normalization factor with which the input is scaled after the transformation is applied\n  -> Int\n  -- ^ is the length of output signals - used to either truncate or pad the input signals.\n  -> Array a\n  -- ^ is the transformed array\nfft a d (fromIntegral -> x) =\n  op1 a (\\j k -> af_fft j k d x)\n\n-- | Fast Fourier Transform (in-place)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft.htm#gaa2f03c9ee1cb80dc184c0b0a13176da1)\n--\n-- C Interface for fast fourier transform on one dimensional signals.\n--\n-- *Note* The input in must be a complex array\n--\nfftInPlace\n  :: (AFType a, Fractional a)\n  => Array (Complex a)\n  -- ^ is the input array on entry and the output of 1D forward fourier transform at exit\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> IO ()\nfftInPlace a d = a `inPlace` (flip af_fft_inplace d)\n\n-- | Fast Fourier Transform (2-dimensional)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft2.htm#gaab3fb1ed398e208a615036b4496da611)\n--\n-- C Interface for fast fourier transform on two dimensional signals.\n--\nfft2\n  :: AFType a\n  => Array a\n  -- ^ the input array\n  -> Double\n  -- ^ the normalization factor with which the input is scaled after the transformation is applied\n  -> Int\n  -- ^ is the length of output signals along first dimension - used to either truncate/pad the input\n  -> Int\n  -- ^ is the length of output signals along second dimension - used to either truncate/pad the input\n  -> Array a\n  -- ^ the transformed array\nfft2 a d x y =\n  op1 a (\\j k -> af_fft2 j k d (fromIntegral x) (fromIntegral y))\n\n-- | Fast Fourier Transform (2-dimensional, in-place)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft2.htm#gacdeebb3f221ae698833dc4900a172b8c)\n--\n-- C Interface for fast fourier transform on two dimensional signals.\n--\n-- *Note* The input in must be a complex array\n--\nfft2_inplace\n  :: (Fractional a, AFType a)\n  => Array (Complex a)\n  -- ^  input array on entry and the output of 2D forward fourier transform on exit\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> IO ()\nfft2_inplace a d = a `inPlace` (flip af_fft2_inplace d)\n\n-- | Fast Fourier Transform (3-dimensional)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft3.htm#ga5138ef1740ece0fde2c796904d733c12)\n--\n-- C Interface for fast fourier transform on three dimensional signals.\n--\nfft3\n  :: AFType a\n  => Array a\n  -- ^ the input array\n  -> Double\n  -- ^ the normalization factor with which the input is scaled after the transformation is applied\n  -> Int\n  -- ^ is the length of output signals along first dimension - used to either truncate/pad the input\n  -> Int\n  -- ^ is the length of output signals along second dimension - used to either truncate/pad the input\n  -> Int\n  -- ^ is the length of output signals along third dimension - used to either truncate/pad the input\n  -> Array a\n  -- ^ the transformed array\nfft3 a d x y z =\n  op1 a (\\j k -> af_fft3 j k d (fromIntegral x) (fromIntegral y) (fromIntegral z))\n\n-- | Fast Fourier Transform (3-dimensional, in-place)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft2.htm#gacdeebb3f221ae698833dc4900a172b8c)\n--\n-- C Interface for fast fourier transform on three dimensional signals.\n--\n-- *Note* The input in must be a complex array\n--\nfft3_inplace\n  :: (Fractional a, AFType a)\n  => Array (Complex a)\n  -- ^  input array on entry and the output of 3D forward fourier transform on exit\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> IO ()\nfft3_inplace a d = a `inPlace` (flip af_fft3_inplace d)\n\n-- | Inverse Fast Fourier Transform\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__ifft.htm#ga2d62c120b474b3b937b0425c994645fe)\n--\n-- C Interface for inverse fast fourier transform on one dimensional signals.\n--\nifft\n  :: AFType a\n  => Array a\n  -- ^ the input array\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> Int\n  -- ^  is the length of output signals - used to either truncate or pad the input signals\n  -> Array a\n  -- ^ the transformed array\nifft a d x =\n  op1 a (\\j k -> af_ifft j k d (fromIntegral x))\n\n-- | Inverse Fast Fourier Transform (in-place)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__ifft.htm#ga827379bef0e2cadb382c1b6301c91429)\n--\n-- C Interface for fast fourier transform on one dimensional signals.\n--\nifft_inplace\n  :: (AFType a, Fractional a)\n  => Array (Complex a)\n  -- ^ is the input array on entry and the output of 1D forward fourier transform at exit\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> IO ()\nifft_inplace a d = a `inPlace` (flip af_ifft_inplace d)\n\n\n-- | Inverse Fast Fourier Transform (2-dimensional signals)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__ifft2.htm#ga7cd29c6a35c19240635b62cc5c30dc4f)\n--\n-- C Interface for inverse fast fourier transform on two dimensional signals.\n--\nifft2\n  :: AFType a\n  => Array a\n  -- ^ the input array\n  -> Double\n  -- ^ the normalization factor with which the input is scaled after the transformation is applied\n  -> Int\n  -- ^ is the length of output signals along first dimension - used to either truncate/pad the input\n  -> Int\n  -- ^ is the length of output signals along second dimension - used to either truncate/pad the input\n  -> Array a\n  -- ^ the transformed array\nifft2 a d x y =\n  op1 a (\\j k -> af_ifft2 j k d (fromIntegral x) (fromIntegral y))\n\n-- | Inverse Fast Fourier Transform (2-dimensional, in-place)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__ifft2.htm#ga9e6a165d44306db4552a56d421ce5d05)\n--\n-- C Interface for fast fourier transform on two dimensional signals.\n--\nifft2_inplace\n  :: (AFType a, Fractional a)\n  => Array (Complex a)\n  -- ^ is the input array on entry and the output of 1D forward fourier transform at exit\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> IO ()\nifft2_inplace a d = a `inPlace` (flip af_ifft2_inplace d)\n\n-- | Inverse Fast Fourier Transform (3-dimensional)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__ifft3.htm)\n--\n-- C Interface for inverse fast fourier transform on three dimensional signals.\n--\nifft3\n  :: AFType a\n  => Array a\n  -- ^ the input array\n  -> Double\n  -- ^ the normalization factor with which the input is scaled after the transformation is applied\n  -> Int\n  -- ^ is the length of output signals along first dimension - used to either truncate/pad the input\n  -> Int\n  -- ^ is the length of output signals along second dimension - used to either truncate/pad the input\n  -> Int\n  -- ^ is the length of output signals along third dimension - used to either truncate/pad the input\n  -> Array a\n  -- ^ the transformed array\nifft3 a d x y z =\n  op1 a (\\j k -> af_ifft3 j k d (fromIntegral x) (fromIntegral y) (fromIntegral z))\n\n-- | Inverse Fast Fourier Transform (3-dimensional, in-place)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__ifft3.htm#ga439a7a49723bc6cf77cf4fe7f8dfe334)\n--\n-- C Interface for fast fourier transform on two dimensional signals.\n--\nifft3_inplace\n  :: (AFType a, Fractional a)\n  => Array (Complex a)\n  -- ^ is the input array on entry and the output of 1D forward fourier transform at exit\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> IO ()\nifft3_inplace a d = a `inPlace` (flip af_ifft3_inplace d)\n\n-- | Real to Complex Fast Fourier Transform\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft__r2c.htm#ga7486f342182a18e773f14cc2ab4cb551)\n--\n-- C Interface for real to complex fast fourier transform for one dimensional signals.\n--\n-- The first dimension of the output will be of size (pad0 / 2) + 1. The second dimension of the output will be pad1. The third dimension of the output will be pad 2.\n--\nfftr2c\n  :: (Fractional a, AFType a)\n  => Array a\n  -- ^ is a real array\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> Int\n  -- ^ is the length of output signals along first dimension - used to either truncate/pad the input\n  -> Array a\n  -- ^ is a complex array containing the non redundant parts of in.\nfftr2c a d x =\n  op1 a (\\j k -> af_fft_r2c j k d (fromIntegral x))\n\n-- | Real to Complex Fast Fourier Transform\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft__r2c.htm#ga7486f342182a18e773f14cc2ab4cb551)\n--\n-- C Interface for real to complex fast fourier transform for two dimensional signals.\n--\n-- The first dimension of the output will be of size (pad0 / 2) + 1. The second dimension of the output will be pad1. The third dimension of the output will be pad 2.\n--\nfft2r2c\n  :: (Fractional a, AFType a)\n  => Array a\n  -- ^ is a real array\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> Int\n  -- ^ is the length of output signals along first dimension - used to either truncate/pad the input\n  -> Int\n  -- ^ is the length of output signals along second dimension - used to either truncate/pad the input\n  -> Array a\n  -- ^ is a complex array containing the non redundant parts of in.\nfft2r2c a d x y =\n  op1 a (\\j k -> af_fft2_r2c j k d (fromIntegral x) (fromIntegral y))\n\n-- | Real to Complex Fast Fourier Transform\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft__r2c.htm#gab4ca074b54218b74d8cfbda63d38be51)\n--\n-- C Interface for real to complex fast fourier transform for three dimensional signals.\n--\n-- The first dimension of the output will be of size (pad0 / 2) + 1. The second dimension of the output will be pad1. The third dimension of the output will be pad 2.\n--\nfft3r2c\n  :: (Fractional a, AFType a)\n  => Array a\n  -- ^ is a real array\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> Int\n  -- ^ is the length of output signals along first dimension - used to either truncate/pad the input\n  -> Int\n  -- ^ is the length of output signals along second dimension - used to either truncate/pad the input\n  -> Int\n  -- ^ is the length of output signals along third dimension - used to either truncate/pad the input\n  -> Array a\n  -- ^ is a complex array containing the non redundant parts of in.\nfft3r2c a d x y z =\n  op1 a (\\j k -> af_fft3_r2c j k d (fromIntegral x) (fromIntegral y) (fromIntegral z))\n\n-- | Complex to Real Fast Fourier Transform\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft__c2r.htm#gaa5efdfd84213a4a07d81a5d534cde5ac)\n--\n-- C Interface for complex to real fast fourier transform for one dimensional signals.\n--\n-- The first dimension of the output will be 2 * dim0 - 1 if is_odd is true else 2 * dim0 - 2 where dim0 is the first dimension of the input. The remaining dimensions are unchanged.\n--\nfftc2r\n  :: AFType a\n  => Array a\n  -- ^ is a complex array containing only the non redundant parts of the signals.\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> Bool\n  -- ^ is a flag signifying if the output should be even or odd size\n  -> Array a\n  -- ^ is a real array containing the output of the transform.\nfftc2r a cm (fromIntegral . fromEnum -> cd) = op1 a (\\x y -> af_fft_c2r x y cm cd)\n\n-- | Complex to Real Fast Fourier Transform (2-dimensional)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft__c2r.htm#gaaa7da16f226cacaffced631e08da4493)\n--\n-- C Interface for complex to real fast fourier transform for two dimensional signals.\n--\n-- The first dimension of the output will be 2 * dim0 - 1 if is_odd is true else 2 * dim0 - 2 where dim0 is the first dimension of the input. The remaining dimensions are unchanged.\n--\nfft2C2r\n  :: AFType a\n  => Array a\n  -- ^ is a complex array containing only the non redundant parts of the signals.\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> Bool\n  -- ^ is a flag signifying if the output should be even or odd size\n  -> Array a\n  -- ^ is a real array containing the output of the transform.\nfft2C2r a cm (fromIntegral . fromEnum -> cd) = op1 a (\\x y -> af_fft2_c2r x y cm cd)\n\n-- | Complex to Real Fast Fourier Transform (3-dimensional)\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft__c2r.htm#gaa9b3322d9ffab15268919e1f114bed24)\n--\n-- C Interface for complex to real fast fourier transform for three dimensional signals.\n--\n-- The first dimension of the output will be 2 * dim0 - 1 if is_odd is true else 2 * dim0 - 2 where dim0 is the first dimension of the input. The remaining dimensions are unchanged.\n--\nfft3C2r\n  :: AFType a\n  => Array a\n  -- ^ is a complex array containing only the non redundant parts of the signals.\n  -> Double\n  -- ^ is the normalization factor with which the input is scaled after the transformation is applied\n  -> Bool\n  -- ^ is a flag signifying if the output should be even or odd size\n  -> Array a\n  -- ^ is a real array containing the output of the transform.\nfft3C2r a cm (fromIntegral . fromEnum -> cd) = op1 a (\\x y -> af_fft3_c2r x y cm cd)\n\n-- | Convolution Integral for one dimensional data\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__convolve1.htm#ga25d77b794463b5cd72cd0b7f4af140d7)\n--\n-- C Interface for convolution on one dimensional signals.\n--\n-- *Note* The default parameter of domain, AF_CONV_AUTO, heuristically switches between frequency and spatial domain.\n--\nconvolve1\n  :: AFType a\n  => Array a\n  -- ^ the input signal\n  -> Array a\n  -- ^ the signal that shall be flipped for the convolution operation\n  -> ConvMode\n  -- ^ indicates if the convolution should be expanded or not(where output size equals input)\n  -> ConvDomain\n  -- ^ specifies if the convolution should be performed in frequency os spatial domain\n  -> Array a\n  -- ^ convolved array\nconvolve1 a b (toConvMode -> cm) (fromConvDomain -> cd) = op2 a b (\\x y z -> af_convolve1 x y z cm cd)\n\n-- | Convolution Integral for two dimensional data\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__convolve2.htm#ga25d77b794463b5cd72cd0b7f4af140d7)\n--\n-- C Interface for convolution on two dimensional signals.\n--\n-- *Note* The default parameter of domain, AF_CONV_AUTO, heuristically switches between frequency and spatial domain.\n--\nconvolve2\n  :: AFType a\n  => Array a\n  -- ^ the input signal\n  -> Array a\n  -- ^ the signal that shall be flipped for the convolution operation\n  -> ConvMode\n  -- ^ indicates if the convolution should be expanded or not(where output size equals input)\n  -> ConvDomain\n  -- ^ specifies if the convolution should be performed in frequency os spatial domain\n  -> Array a\n  -- ^ convolved array\nconvolve2 a b (toConvMode -> cm) (fromConvDomain -> cd) = op2 a b (\\x y z -> af_convolve2 x y z cm cd)\n\n-- | Convolution Integral for three dimensional data\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__convolve3.htm#ga25d77b794463b5cd72cd0b7f4af140d7)\n--\n-- C Interface for convolution on three dimensional signals.\n--\n-- *Note* The default parameter of domain, AF_CONV_AUTO, heuristically switches between frequency and spatial domain.\n--\nconvolve3\n  :: AFType a\n  => Array a\n  -- ^ the input signal\n  -> Array a\n  -- ^ the signal that shall be flipped for the convolution operation\n  -> ConvMode\n  -- ^ indicates if the convolution should be expanded or not(where output size equals input)\n  -> ConvDomain\n  -- ^ specifies if the convolution should be performed in frequency os spatial domain\n  -> Array a\n  -- ^ convolved array\nconvolve3 a b (toConvMode -> cm) (fromConvDomain -> cd) =\n  op2 a b (\\x y z -> af_convolve3 x y z cm cd)\n\n-- | C Interface for separable convolution on two dimensional signals.\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__convolve.htm#gaeb6ba88155cf3ef29d93f97b147e372f)\n--\n-- C Interface for separable convolution on two dimensional signals.\n--\n-- *Note* The default parameter of domain, AF_CONV_AUTO, heuristically switches between frequency and spatial domain.\n--\nconvolve2Sep\n  :: AFType a\n  => Array a\n  -- ^ filter that has to be applied along the coloumns\n  -> Array a\n  -- ^ filter that has to be applied along the rows\n  -> Array a\n  -- ^ the input array\n  -> ConvMode\n  -- ^ indicates if the convolution should be expanded or not(where output size equals input)\n  -> Array a\n  -- ^ convolved array\nconvolve2Sep a b c (toConvMode -> d) = op3 a b c (\\x y z j -> af_convolve2_sep x y z j d)\n\n-- DMJ: did this get removed? Can't find in latest docs\n-- fftConvolve1\n--   :: AFType a\n--   => Array a\n--   -> Array a\n--   -> ConvMode\n--   -> Array a\n-- fftConvolve1 a b (toConvMode -> c) = op2 a b (\\x y z -> af_fft_convolve1 x y z c)\n\n-- | 2D Convolution using Fast Fourier Transform\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft__convolve2.htm#gab52ebe631d8358cdef1b5c8a95550556)\n--\n-- A convolution is a common operation between a source array, a, and a filter (or kernel) array b. The answer to the convolution is the same as computing the coefficients in polynomial multiplication, if a and b are the coefficients.\n--\n-- C Interface for FFT-based convolution on two dimensional signals.\n--\nfftConvolve2\n  :: AFType a\n  => Array a\n  -- ^ is the input signal\n  -> Array a\n  --  ^ is the signal that shall be used for the convolution operation\n  -> ConvMode\n  -- ^ indicates if the convolution should be expanded or not(where output size equals input)\n  -> Array a\n  -- ^  is convolved array\nfftConvolve2 a b (toConvMode -> c) = op2 a b (\\x y z -> af_fft_convolve2 x y z c)\n\n-- | 3D Convolution using Fast Fourier Transform\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft__convolve3.htm)\n--\n-- A convolution is a common operation between a source array, a, and a filter (or kernel) array b. The answer to the convolution is the same as computing the coefficients in polynomial multiplication, if a and b are the coefficients.\n--\n-- C Interface for FFT-based convolution on three dimensional signals.\n--\nfftConvolve3\n  :: AFType a\n  => Array a\n  -- ^ is the input signal\n  -> Array a\n  --  ^ is the signal that shall be used for the convolution operation\n  -> ConvMode\n  -- ^ indicates if the convolution should be expanded or not(where output size equals input)\n  -> Array a\n  -- ^  is convolved array\nfftConvolve3 a b (toConvMode -> c) = op2 a b (\\x y z -> af_fft_convolve3 x y z c)\n\n-- | Finite Impulse Filter.\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fir.htm#ga2a850e69775eede4709e0d607bba240b)\n--\n-- Finite impulse filters take an input x and a co-efficient array b to generate an output y such that:\n--\n-- C Interface for finite impulse response filter.\n--\nfir\n  :: AFType a\n  => Array a\n  -- ^ is the input signal to the filter\n  -> Array a\n  -- ^ is the array containing the coefficients of the filter\n  -> Array a\n  -- ^ is the output signal from the filter\nfir a b = op2 a b af_fir\n\n-- | Infinite Impulse Filter.\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__iir.htm#ga7adcc364da0a66cdfd2bb351215456c4)\n--\n-- Infinite impulse filters take an input x and a feedforward array b, feedback array a to generate an output y such that:\n--\n-- C Interface for infinite impulse response filter.\n--\n-- *Note* The feedforward coefficients are currently limited to a length of 512\n--\niir\n  :: AFType a\n  => Array a\n  -- ^ the array containing the feedforward coefficient\n  -> Array a\n  -- ^ is the array containing the feedback coefficients\n  -> Array a\n  -- ^ is the input signal to the filter\n  -> Array a\n  -- ^ the output signal from the filter\niir a b c = op3 a b c af_iir\n\n-- | Median Filter\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__image__func__medfilt.htm#gaaf3f62f2de0f4dc315b831e494e1b2c0)\n--\n-- A median filter is similar to the arbitrary filter except that instead of a weighted sum, the median value of the pixels covered by the kernel is returned.\n--\n-- C Interface for median filter.\n--\nmedFilt\n  :: AFType a\n  => Array a\n  -- ^ 'Array' is the input image\n  -> Int\n  -> Int\n  -> BorderType\n  -> Array a\n  -- ^ 'Array' is the processed image\nmedFilt a l w (fromBorderType -> b) =\n a `op1` (\\x y -> af_medfilt x y (fromIntegral l) (fromIntegral w) b)\n\n-- | 1D Median Filter\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__image__func__medfilt.htm#gad108ea62cbbb5371bd14a17d06384359)\n--\n-- A median filter is similar to the arbitrary filter except that instead of a weighted sum, the median value of the pixels covered by the kernel is returned.\n--\n-- C Interface for 1D median filter.\n--\nmedFilt1\n  :: AFType a\n  => Array a\n  -- ^ 'Array' is the input signal\n  -> Int\n  -- ^ Is the kernel width\n  -> BorderType\n  -- ^ value will decide what happens to border when running filter in their neighborhood. It takes one of the values [AF_PAD_ZERO | AF_PAD_SYM]\n  -> Array a\n  -- ^ 'Array' is the processed signal\nmedFilt1 a w (fromBorderType -> b) =\n a `op1` (\\x y -> af_medfilt1 x y (fromIntegral w) b)\n\n-- | 2D Median Filter\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__image__func__medfilt.htm#ga2cb99dca5842f74f6b9cd28eb187a9cd)\n--\n-- A median filter is similar to the arbitrary filter except that instead of a weighted sum, the median value of the pixels covered by the kernel is returned.\n--\n-- C Interface for 2D median filter.\n--\nmedFilt2\n  :: AFType a\n  => Array a\n  -- ^ 'Array' is the input image\n  -> Int\n  -- ^ the kernel height\n  -> Int\n  -- ^ the kernel width\n  -> BorderType\n  -- ^ value will decide what happens to border when running filter in their neighborhood. It takes one of the values [AF_PAD_ZERO | AF_PAD_SYM]\n  -> Array a\n  -- ^ 'Array' is the processed image\nmedFilt2 a l w (fromBorderType -> b) =\n a `op1` (\\x y -> af_medfilt2 x y (fromIntegral l) (fromIntegral w) b)\n\n-- | C Interface for setting plan cache size.\n--\n-- [ArrayFire Docs](http://arrayfire.org/docs/group__signal__func__fft.htm#ga4ddef19b43d9a50c97b1a835df60279a)\n--\n-- This function doesn't do anything if called when CPU backend is active. The plans associated with the most recently used array sizes are cached.\n--\n-- >>> setFFTPlanCacheSize 2\n-- ()\n--\nsetFFTPlanCacheSize\n  :: Int\n  -- ^ is the number of plans that shall be cached\n  -> IO ()\nsetFFTPlanCacheSize =\n afCall . af_set_fft_plan_cache_size . fromIntegral\n", "meta": {"hexsha": "4a2f7aa952bad525d0c7584e4103e8b92219bc01", "size": 27919, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ArrayFire/Signal.hs", "max_stars_repo_name": "arrayfire/arrayfire-haskell", "max_stars_repo_head_hexsha": "5d621602bb925ce5122a66011003498cbe638e2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:54:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:59:15.000Z", "max_issues_repo_path": "src/ArrayFire/Signal.hs", "max_issues_repo_name": "arrayfire/arrayfire-haskell", "max_issues_repo_head_hexsha": "5d621602bb925ce5122a66011003498cbe638e2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2019-11-04T03:45:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T00:49:36.000Z", "max_forks_repo_path": "src/ArrayFire/Signal.hs", "max_forks_repo_name": "arrayfire/arrayfire-haskell", "max_forks_repo_head_hexsha": "5d621602bb925ce5122a66011003498cbe638e2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-11-04T03:45:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-17T01:02:23.000Z", "avg_line_length": 37.1263297872, "max_line_length": 309, "alphanum_fraction": 0.7010637917, "num_tokens": 7964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.4817503175856376}}
{"text": "module Numeric.DataFrame\n  ( module Numeric.DataFrame.Type\n    -- * Simplified type aliases\n  , module Numeric.Scalar\n  , module Numeric.Vector\n  , module Numeric.Matrix\n    -- * Functionality\n  , module Numeric.DataFrame.SubSpace\n  , module Numeric.DataFrame.Contraction\n  , module Numeric.Basics\n  , module Numeric.Subroutine.Sort\n  ) where\n\nimport Numeric.DataFrame.Internal.Backend ()\n\nimport Numeric.DataFrame.Contraction\nimport Numeric.DataFrame.SubSpace\nimport Numeric.DataFrame.Type\n\nimport Numeric.Matrix\nimport Numeric.Scalar\nimport Numeric.Vector\n\nimport Numeric.Basics\n\nimport Numeric.Subroutine.Sort (sort, sortBy)\n", "meta": {"hexsha": "c3022305b7afca0b85c7b5b80f72a96331fb7349", "size": 628, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "easytensor/src/Numeric/DataFrame.hs", "max_stars_repo_name": "achirkin/fasttensor", "max_stars_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2017-06-30T04:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:46:17.000Z", "max_issues_repo_path": "easytensor/src/Numeric/DataFrame.hs", "max_issues_repo_name": "achirkin/fasttensor", "max_issues_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-07-17T18:20:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T06:31:42.000Z", "max_forks_repo_path": "easytensor/src/Numeric/DataFrame.hs", "max_forks_repo_name": "achirkin/fasttensor", "max_forks_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-08T20:44:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T22:08:04.000Z", "avg_line_length": 23.2592592593, "max_line_length": 45, "alphanum_fraction": 0.7834394904, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4817269231230066}}
{"text": "{-# LANGUAGE BangPatterns #-}\n\n-- | 2D FFT functions\nmodule SatOpt.FFT where\n\nimport           Control.Parallel.Strategies   (parMap, rdeepseq)\nimport           Numeric.GSL.Fourier           (fft, ifft)\nimport           Numeric.LinearAlgebra.HMatrix\n\n\nhalf [] = []\nhalf (x:y:xs) = x : half xs\n\nclone [] = []\nclone (x:xs) = x : x : clone xs\n\n-- | Take the FFT of a matrix of complex numbers\nfft2dM :: Matrix \u2102 -> Matrix \u2102\nfft2dM m = fromColumns $ clone $ clone $ inter0\n  where\n    !inter0 = mapFFT $ inter1\n    !inter1 = half $ half $ toColumns $ fromRows $ clone $ clone $ inter2\n    !inter2 = mapFFT $ inter3\n    !inter3 = half $ half $ toRows m\n    mapFFT = parMap rdeepseq fft\n\n-- | Take the inverse FFT of a matrix of complex numbers\nifft2dM :: Matrix \u2102 -> Matrix \u2102\nifft2dM m = fromColumns $ mapIFFT $ toColumns inter\n  where\n    !inter = fromRows $ mapIFFT $ toRows m\n    mapIFFT = parMap rdeepseq ifft\n", "meta": {"hexsha": "46a7ecc7b9f44d722c0bba5a108168964f143589", "size": 909, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "library/SatOpt/FFT.hs", "max_stars_repo_name": "taktoa/SatOpt", "max_stars_repo_head_hexsha": "b3920635c179103f1f127431e91845ea92a0f64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T05:08:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T05:08:33.000Z", "max_issues_repo_path": "library/SatOpt/FFT.hs", "max_issues_repo_name": "taktoa/SatOpt", "max_issues_repo_head_hexsha": "b3920635c179103f1f127431e91845ea92a0f64f", "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": "library/SatOpt/FFT.hs", "max_forks_repo_name": "taktoa/SatOpt", "max_forks_repo_head_hexsha": "b3920635c179103f1f127431e91845ea92a0f64f", "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": 27.5454545455, "max_line_length": 73, "alphanum_fraction": 0.6424642464, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4814607278587594}}
{"text": "module RandomUtil.RandomMatrixTest\n  (\n    testsRandomMatrix\n  ) where\n\nimport Test.HUnit\n\nimport Numeric.LinearAlgebra.HMatrix hiding (corr)\nimport System.Random\n\nimport RandomUtil.RandomMatrix\nimport Matrix.State\n\nmat :: Matrix Double\nmat = reshape 3 $ fromList $ take 9 [1..]\n\ndata Two = Two\n\ninstance RandomGen Two where\n  next g  = (2, g)\n  split g = (g, g)\n\ntestsRandomMatrix :: Test\ntestsRandomMatrix = TestList [ TestLabel \"selectRandomMatrixElement\" testsSelectRandomMatrixElement,\n                               TestLabel \"randomMatrixIndex\" testsRandomMatrixIndex\n                             ]\n\n\ntestsSelectRandomMatrixElement :: Test\ntestsSelectRandomMatrixElement = TestList [TestLabel \"test1\" testSelects]\ntestsRandomMatrixIndex :: Test\ntestsRandomMatrixIndex = TestList [TestLabel \"test1\" testInBounds]\n\n-- testsSelectRandomMatrixElement\ntestSelects :: Test\ntestSelects = TestCase (assertEqual \"selectRandomMatrixElement - Select\"\n                         5\n                         (fst $ selectRandomMatrixElement Two mat))\n\n-- testsRandomMatrixIndex\ntestInBounds :: Test\ntestInBounds = TestCase (do gen <- getStdGen\n                            let listI  = getListRandomIndex gen 100 mat\n                            let result = checkAllTrue listI (isValid mat)\n                            assertEqual \"randomMatrixIndex - Indices in bounds\" True result)\n\n              \n-- testsRandomMatrixIndex helper function\nisValid :: Matrix a -> MatrixIndex -> Bool\nisValid m (i,j) = i >= 0 && j >= 0 && i < rows m && j < cols m\n\ngetListRandomIndex :: (Element a) => StdGen -> Int -> Matrix a -> [MatrixIndex]\ngetListRandomIndex _ 0 _ = []\ngetListRandomIndex g n m = rIndex : getListRandomIndex g' (n-1) m\n  where\n    (rIndex,g') = randomMatrixIndex g m\n\ncheckAllTrue :: [a] -> (a -> Bool) -> Bool\ncheckAllTrue xs f = foldr (&&) True $ map f xs\n", "meta": {"hexsha": "cf80e972eeca2e442d72f3e34e1837fe94d8b2d0", "size": 1854, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/RandomUtil/RandomMatrixTest.hs", "max_stars_repo_name": "eklinkhammer/neural-algorithms", "max_stars_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/RandomUtil/RandomMatrixTest.hs", "max_issues_repo_name": "eklinkhammer/neural-algorithms", "max_issues_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/RandomUtil/RandomMatrixTest.hs", "max_forks_repo_name": "eklinkhammer/neural-algorithms", "max_forks_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9, "max_line_length": 100, "alphanum_fraction": 0.6666666667, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.48142290151173894}}
{"text": "{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE OverloadedStrings   #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE TypeApplications    #-}\n{-# LANGUAGE TypeOperators    #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE PolyKinds #-}\nmodule Main where\n\nimport qualified Control.Foldl                 as FL\nimport qualified Data.List                     as List\nimport           Data.Maybe                     ( fromMaybe )\nimport qualified Data.Text                     as T\nimport qualified Data.Vector.Storable          as V\nimport qualified Data.Vinyl                    as V\nimport qualified Frames                        as F\n\nimport           Numeric.LinearAlgebra          ( (#>)\n                                                , (<#)\n                                                , (<.>)\n                                                , (<\\>)\n                                                )\nimport qualified Numeric.LinearAlgebra         as LA\nimport           Numeric.LinearAlgebra.Data     ( Matrix\n                                                , R\n                                                , Vector\n                                                )\nimport qualified Numeric.LinearAlgebra.Data    as LA\nimport           Statistics.Types               ( cl95 )\n\nimport           Control.Applicative\nimport           Control.Monad\nimport           EasyTest\nimport           Control.Monad.IO.Class         ( MonadIO\n                                                , liftIO\n                                                )\n\nimport qualified Math.Regression.LeastSquares  as LS\nimport qualified Math.Regression.Regression    as RE\n\nimport qualified Knit.Effect.Logger            as KL\nimport qualified Polysemy.IO                   as P\nimport qualified Polysemy                      as P\n\nmain = runOnly \"all\" suite\n\nsuite :: Test\nsuite = scope \"all.Regression\" $ tests [testOLS, testWOLS, testTLS, testWTLS]\n\nlogged\n  :: forall m a\n   . MonadIO m\n  => P.Sem '[KL.Logger KL.LogEntry, KL.PrefixLog, P.Lift IO, P.Lift m] a\n  -> m a\nlogged = P.runM . P.runIO @m . KL.filteredLogEntriesToIO KL.logAll\n-- regression tests\n\n-- build some data for testing\n-- uniformly distributed measurements, normally distributed noise.  Separate noise amplitudes for xs and ys\n-- also allow building heteroscedastic data\nbuildRegressable\n  :: [Double]\n  -> Maybe (LA.Vector R)\n  -> Double\n  -> LA.Vector R\n  -> Double\n  -> IO (LA.Vector R, LA.Matrix R)\nbuildRegressable variances offsetsM noiseObs coeffs noiseMeas = do\n  -- generate random measurements\n  let d    = LA.size coeffs\n      nObs = List.length variances\n      xsO  = LA.asColumn (LA.fromList (List.replicate nObs 1))\n        LA.<> LA.asRow (fromMaybe (LA.fromList $ List.replicate d 0) offsetsM)\n  xs0    <- LA.rand nObs d\n  xNoise <- LA.randn nObs d\n  let xs  = xs0 + xsO + LA.scale noiseMeas xNoise\n  let ys0 = (xs0 + xsO) LA.<> LA.asColumn coeffs\n  yNoise <- fmap (List.head . LA.toColumns) (LA.randn nObs 1)\n  let ys = ys0 + LA.asColumn\n        (LA.scale\n          noiseObs\n          (V.zipWith (*) yNoise (LA.cmap sqrt (LA.fromList variances)))\n        )\n  return (List.head (LA.toColumns ys), xs)\n\nunweighted :: Int -> [Double]\nunweighted n = List.replicate n (1.0)\n\nconeWeighted :: Int -> Double -> [Double]\nconeWeighted n increment =\n  let w0 = [ 1 + (realToFrac i) * increment | i <- [0 .. n] ]\n      s  = realToFrac n / FL.fold FL.sum w0\n  in  fmap (* s) w0\n\nshowText :: Show a => a -> T.Text\nshowText = T.pack . show\n\nerrR2 res = let r2 = RE.rSquared res in (r2 <= 1 && r2 > 0.0)\ncoeffs :: LA.Vector R = LA.fromList [1.0, 2.2, 0.3]\noffsets :: LA.Vector R = LA.fromList [0, 1, 0]\nvars = coneWeighted 100 0.1\nvarListToWeights = LA.cmap (\\x -> 1 / sqrt x) . LA.fromList\nwgts = varListToWeights vars\n\ntestRegression\n  :: ( r\n         ~\n         '[KL.Logger KL.LogEntry, KL.PrefixLog, P.Lift IO, P.Lift (PropertyT IO)]\n     ) --KL.LogWithPrefixesLE r\n  => Double\n  -> Double\n  -> Bool\n  -> Bool\n  -> (  Matrix R\n     -> Vector R\n     -> Vector R\n     -> P.Sem r (RE.RegressionResult R)\n     )\n  -> Test\ntestRegression yNoise xNoise weighted offset f = do\n  let scopeT =\n        \"Vy=\"\n          <> showText yNoise\n          <> \"; Vx=\"\n          <> showText xNoise\n          <> (if weighted then \"; cone weights\" else \"\")\n          <> (if offset then \"; w/offsets\" else \"\")\n      vars    = if weighted then coneWeighted 100 0.1 else unweighted 100\n      wgts    = varListToWeights vars\n      offsetM = if offset then (Just offsets) else Nothing\n  property $ do\n    (ys, xs) <- liftIO $ buildRegressable vars offsetM yNoise coeffs xNoise\n    result   <- logged $ f xs ys wgts\n    footnote\n      ( T.unpack\n      $ RE.prettyPrintRegressionResult \"y\" [\"x1\", \"x2\", \"x3\"] result cl95\n      )\n    success -- expect $ errR2 result\n\nconst3 f x y z = f x y\n\ntype RegressF = (Matrix R\n                -> Vector R\n                -> Vector R\n                -> P.Sem\n                   '[KL.Logger KL.LogEntry, KL.PrefixLog, P.Lift IO, P.Lift\n                                                                     (PropertyT IO)]\n                   (RE.RegressionResult R))\n\ntestOLS :: Test\ntestOLS =\n  let regress :: RegressF\n      regress xs ys ws = LS.ordinaryLS False xs ys\n  in  scope \"OLS\" $ tests\n        [ testRegression 0   0   False False regress\n        , testRegression 0.1 0   False False regress\n        , testRegression 0.5 0   False False regress\n        , testRegression 0.1 0   False True  regress\n        , testRegression 0.3 0.3 False False regress\n        , testRegression 0.3 0   True  False regress\n        , testRegression 0.3 0.3 True  False regress\n        ]\n\ntestWOLS :: Test\ntestWOLS =\n  let regress :: RegressF = LS.weightedLS False\n  in  scope \"WOLS\" $ tests\n        [ testRegression 0   0   True  False regress\n        , testRegression 0.1 0   True  False regress\n        , testRegression 0.1 0   False False regress\n        , testRegression 0.3 0   True  False regress\n        , testRegression 0.1 0.1 True  False regress\n        , testRegression 0.1 0.1 True  True  regress\n        , testRegression 0.3 0.3 True  False regress\n        ]\n\ntestTLS :: Test\ntestTLS =\n  let regress :: RegressF\n      regress xs ys ws = LS.totalLS False xs ys\n  in  scope \"TLS\" $ tests\n        [ testRegression 0   0   False False regress\n        , testRegression 0.1 0   False False regress\n        , testRegression 0.5 0   False False regress\n        , testRegression 0.1 0   False True  regress\n        , testRegression 0.3 0.3 False False regress\n        , testRegression 0.3 0   True  False regress\n        , testRegression 0.3 0.3 True  False regress\n        ]\n\ntestWTLS :: Test\ntestWTLS =\n  let regress :: RegressF\n      regress = LS.weightedTLS False\n  in  scope \"WTLS\" $ tests\n        [ testRegression 0   0   True  False regress\n        , testRegression 0.1 0   True  False regress\n        , testRegression 0.1 0   False False regress\n        , testRegression 0.3 0   True  False regress\n        , testRegression 0.1 0.1 True  False regress\n        , testRegression 0.1 0.1 True  True  regress\n        , testRegression 0.3 0.3 True  False regress\n        ]\n", "meta": {"hexsha": "89b17844a4c86b5e61c521b5d91a237270bb66de", "size": 7171, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/UnitTests.hs", "max_stars_repo_name": "teto/Frames-utils", "max_stars_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-01-17T21:51:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T08:20:19.000Z", "max_issues_repo_path": "test/UnitTests.hs", "max_issues_repo_name": "teto/Frames-utils", "max_issues_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-22T13:50:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T13:50:50.000Z", "max_forks_repo_path": "test/UnitTests.hs", "max_forks_repo_name": "teto/Frames-utils", "max_forks_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-04T12:49:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T11:25:11.000Z", "avg_line_length": 34.9804878049, "max_line_length": 107, "alphanum_fraction": 0.566169293, "num_tokens": 1902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4814061795357582}}
{"text": "{-# LANGUAGE BangPatterns #-}\n\n{- | Some extra facilities to work with 'Rand' monad and 'PureMT'\n     random number generator.\n-}\n\nmodule Moo.GeneticAlgorithm.Random\n    (\n    -- * Random numbers from given range\n      getRandomR\n    , getRandom\n    -- * Probability distributions\n    , getNormal2\n    , getNormal\n    -- * Random samples and shuffles\n    , randomSample\n    , randomSampleIndices\n    , shuffle\n    -- * Building blocks\n    , withProbability\n    -- * Re-exports from random number generator packages\n    , getBool, getInt, getWord, getInt64, getWord64, getDouble\n    , runRandom, evalRandom, newPureMT\n    , Rand, Random, PureMT\n    ) where\n\nimport Control.Monad (liftM)\nimport Control.Monad.State.Strict (MonadState(..), State, runState, evalState)\nimport Data.Complex (Complex (..))\nimport System.Random (RandomGen, Random(..))\nimport System.Random.Mersenne.Pure64\nimport qualified System.Random.Shuffle as S\nimport qualified Data.Set as Set\nimport Data.Word (Word64)\nimport Data.Int (Int64)\n\n-- | Monad for handling randomized computation. This uses the mersenne twister RNG.\ntype Rand = State PureMT\n\n-- | Run a random computation using the generator @g@, returning the result\n-- and the updated generator.\nrunRandom  :: Rand a -> PureMT -> (a, PureMT)\nrunRandom = runState\n\n-- | Evaluate a random computation using the mersenne generator @g@.  Note that the\n-- generator @g@ is not returned, so there's no way to recover the\n-- updated version of @g@.\nevalRandom :: Rand a -> PureMT -> a\nevalRandom = evalState\n\n-- | Yield a new boolean value from the generator.\ngetBool     :: Rand Bool\ngetBool     = fmap (<0) getInt\n\n-- | Yield a new 'Int' value from the generator.\ngetInt      :: Rand Int\ngetInt      = state randomInt\n\n-- | Yield a new 'Word' value from the generator.\ngetWord     :: Rand Word\ngetWord     = state randomWord\n\n-- | Yield a new 'Int64' value from the generator.\ngetInt64    :: Rand Int64\ngetInt64    = state randomInt64\n\n-- | Yield a new 53-bit precise 'Double' value from the generator.\ngetDouble :: Rand Double\ngetDouble = state randomDouble\n\n-- | Yield a new 'Word64' value from the generator.\ngetWord64   :: Rand Word64\ngetWord64   = state randomWord64\n\n-- | Yield a new randomly selected value of type @a@ in the range @(lo, hi)@.\n-- See 'System.Random.randomR' for details.\ngetRandomR :: Random a => (a, a) -> Rand a\ngetRandomR range = state $ randomR range\n\n-- | Yield a new randomly selected value of type @a@.\n-- See 'System.Random.random' for details.\ngetRandom :: Random a => Rand a\ngetRandom = state random\n\n-- | Yield two randomly selected values which follow standard\n-- normal distribution.\ngetNormal2 :: Rand (Double, Double)\ngetNormal2 = do\n  -- Box-Muller method\n  u <- getDouble\n  v <- getDouble\n  let (c :+ s) = exp (0 :+ (2*pi*v))\n  let r = sqrt $ (-2) * log u\n  return (r*c, r*s)\n\n-- | Yield one randomly selected value from standard normal distribution.\ngetNormal :: Rand Double\ngetNormal = fst `liftM` getNormal2\n\n-- | Take at most n random elements from the list. Preserve order.\nrandomSample :: Int -> [a] -> Rand [a]\nrandomSample n xs =\n  state $ \\g -> select g n (length xs) xs []\n  where\n    select rng _ _ [] acc = (reverse acc, rng)\n    select rng n m xs acc\n        | n <= 0     = (reverse acc, rng)\n        | otherwise  =\n            let (k, rng') = randomR (0, m - n) rng\n                (x:rest) = drop k xs\n            in  select rng' (n-1) (m-k-1) rest (x:acc)\n\n-- | Select @sampleSize@ numbers in the range from @0@ to @(populationSize-1)@.\n-- The function works best when @sampleSize@ is much smaller than @populationSize@.\nrandomSampleIndices :: Int -> Int -> Rand [Int]\nrandomSampleIndices sampleSize populationSize =\n    state $ \\g ->\n        let (sampleSet, g') = buildSampleSet g sampleSize Set.empty\n        in  (Set.toList sampleSet, g')\n  where\n    buildSampleSet g n s\n        | n <= 0 = (s, g)\n        | otherwise =\n            let (i, g') = randomR (0, populationSize-1) g\n            in  if (i `Set.member` s)\n                then buildSampleSet g' n s\n                else buildSampleSet g' (n-1) (Set.insert i s)\n\n-- | Randomly reorder the list.\nshuffle :: [a] -> Rand [a]\nshuffle xs = state $ randomShuffle xs (length xs)\n\n-- | Given a sequence (e1,...en) to shuffle, its length, and a random\n-- generator, compute the corresponding permutation of the input\n-- sequence, return the permutation and the new state of the\n-- random generator.\nrandomShuffle :: RandomGen gen => [a] -> Int -> gen -> ([a], gen)\nrandomShuffle elements len g =\n    let (rs, g') = rseq len g\n    in  (S.shuffle elements rs, g')\n  where\n  -- | The sequence (r1,...r[n-1]) of numbers such that r[i] is an\n  -- independent sample from a uniform random distribution\n  -- [0..n-i]\n  rseq :: RandomGen gen => Int -> gen -> ([Int], gen)\n  rseq n g = second lastGen . unzip $ rseq' (n - 1) g\n      where\n        rseq' :: RandomGen gen => Int -> gen -> [(Int, gen)]\n        rseq' i gen\n          | i <= 0    = []\n          | otherwise = let (j, gen') = randomR (0, i) gen\n                        in  (j, gen') : rseq' (i - 1) gen'\n        -- apply a function on the second element of a pair\n        second :: (b -> c) -> (a, b) -> (a, c)\n        second f (x,y) = (x, f y)\n        -- the last returned random number generator\n        lastGen [] = g   -- didn't use the generator yet\n        lastGen (lst:[]) = lst\n        lastGen gens = lastGen (drop 1 gens)\n\n-- |Modify value with probability @p@. Return the unchanged value with probability @1-p@.\nwithProbability :: Double -> (a -> Rand a) -> (a -> Rand a)\nwithProbability p modify x = do\n  t <- getDouble\n  if t < p\n     then modify x\n     else return x\n", "meta": {"hexsha": "ab901fc862bda4a64bbc463b8088788cadb0a3bc", "size": 5667, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Moo/GeneticAlgorithm/Random.hs", "max_stars_repo_name": "Batou99/moo", "max_stars_repo_head_hexsha": "1258202262edefb3bbdd77980e7ff9b5f6ac7de3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-20T08:13:27.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-20T08:13:27.000Z", "max_issues_repo_path": "src/Moo/GeneticAlgorithm/Random.hs", "max_issues_repo_name": "Batou99/moo", "max_issues_repo_head_hexsha": "1258202262edefb3bbdd77980e7ff9b5f6ac7de3", "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/Moo/GeneticAlgorithm/Random.hs", "max_forks_repo_name": "Batou99/moo", "max_forks_repo_head_hexsha": "1258202262edefb3bbdd77980e7ff9b5f6ac7de3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-11T07:56:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T07:56:25.000Z", "avg_line_length": 33.7321428571, "max_line_length": 89, "alphanum_fraction": 0.6370213517, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4809779452467098}}
{"text": "module NeuralNet.TrainSpec (trainSpec) where\n\nimport Test.Hspec\nimport Numeric.LinearAlgebra\nimport NeuralNet.Net\nimport NeuralNet.Activation\nimport NeuralNet.Example\nimport NeuralNet.Layer\nimport NeuralNet.Train\n\ntrainSpec :: SpecWith ()\ntrainSpec =\n  describe \"NeuralNet.Train\" $ do\n    describe \"nnBackward\" $ do\n      it \"calculates correctly for simple example\" $\n        let\n          layer1W = [-1.31386475, 0.88462238, 0.88131804, 1.70957306\n                    , 0.05003364, -0.40467741, -0.54535995, -1.54647732\n                    , 0.98236743, -1.10106763, -1.18504653, -0.2056499]\n          layer1B = [1.48614836, 0.23671627, -1.02378514]\n          layer2W = [-1.02387576, 1.12397796, -0.13191423]\n          layer2B = [-1.62328545]\n          nn = buildNNFromList (4, [LayerDefinition ReLU 3, LayerDefinition Sigmoid 1]) (layer1W ++ layer1B ++ layer2W ++ layer2B)\n          examples = createExampleSet [ ([0.09649747, -0.2773882, -0.08274148, -0.04381817], 1)\n                                      , ([-1.8634927, -0.35475898, -0.62700068, -0.47721803], 0)]\n\n          inputs = exampleSetX examples\n          layer1As = fromLists [[1.97611078, -1.24412333], [-0.62641691, -0.80376609], [-2.41908317, -0.92379202]]\n          layer1Zs = fromLists [[-0.7129932, 0.62524497], [-0.16051336, -0.76883635], [-0.23003072, 0.74505627]]\n          layer2As = fromLists [[1.78862847, 0.43650985]]\n          layer2Zs = fromLists [[0.64667545, -0.35627076]]\n          steps = [createInputForwardPropStep inputs, createForwardPropStep layer1As layer1Zs, createForwardPropStep layer2As layer2Zs]\n\n          dW1 = fromLists [ [0.4101000190122487, 7.807203346853248e-2, 0.13798443685274048, 0.10502167417988162]\n                          , [0, 0, 0, 0]\n                          , [5.2836516249770524e-2, 1.0058654166727896e-2, 1.77776556985907e-2, 1.3530795262454464e-2]]\n          db1 = fromLists [[-0.22007063350033446], [0], [-2.835348711039787e-2]]\n          dW2 = fromLists [[-0.39202432174003965, -0.13325854898009654, -4.601088848081533e-2]]\n          db2 = fromLists [[0.15187860742650333]]\n        in\n          nnBackward nn steps examples `shouldBe` [(dW1, db1), (dW2, db2)]\n\n    describe \"updateNNParams\" $ do\n      it \"calculates correctly for logreg case\" $\n        let\n          nn = buildNNFromList (2, [LayerDefinition ReLU 1]) [1, 2, 3]\n          grads = [(fromLists [[10, 100]], fromLists [[1000]])]\n          learningRate = 0.1\n          expected = buildNNFromList (2, [LayerDefinition ReLU 1]) [0, -8, -97]\n        in\n          updateNNParams nn grads learningRate `shouldBe` expected\n", "meta": {"hexsha": "763e3d9dbaf4a4977deed94e448198cf5cca5197", "size": 2600, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/NeuralNet/TrainSpec.hs", "max_stars_repo_name": "danielholmes/neural-net", "max_stars_repo_head_hexsha": "2088c858498fbc58ed326dc85bb370b814b0b6a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-02-18T22:55:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-20T09:23:24.000Z", "max_issues_repo_path": "test/NeuralNet/TrainSpec.hs", "max_issues_repo_name": "danielholmes/neural-net", "max_issues_repo_head_hexsha": "2088c858498fbc58ed326dc85bb370b814b0b6a6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/NeuralNet/TrainSpec.hs", "max_forks_repo_name": "danielholmes/neural-net", "max_forks_repo_head_hexsha": "2088c858498fbc58ed326dc85bb370b814b0b6a6", "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": 50.0, "max_line_length": 135, "alphanum_fraction": 0.6246153846, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.4809779343177092}}
{"text": "{-# LANGUAGE DataKinds                                #-}\n{-# LANGUAGE DeriveAnyClass                           #-}\n{-# LANGUAGE DeriveDataTypeable                       #-}\n{-# LANGUAGE DeriveGeneric                            #-}\n{-# LANGUAGE DerivingVia                              #-}\n{-# LANGUAGE FlexibleInstances                        #-}\n{-# LANGUAGE GADTs                                    #-}\n{-# LANGUAGE KindSignatures                           #-}\n{-# LANGUAGE MultiParamTypeClasses                    #-}\n{-# LANGUAGE PatternSynonyms                          #-}\n{-# LANGUAGE RankNTypes                               #-}\n{-# LANGUAGE RecordWildCards                          #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE StandaloneDeriving                       #-}\n{-# LANGUAGE TemplateHaskell                          #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeFamilies                             #-}\n{-# LANGUAGE TypeInType                               #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# LANGUAGE UndecidableInstances                     #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise       #-}\n\nmodule Backprop.Learn.Model.Neural.LSTM (\n    -- * LSTM\n    lstm\n  , LSTMp(..), lstmForget, lstmInput, lstmUpdate, lstmOutput\n  , reshapeLSTMpInput\n  , reshapeLSTMpOutput\n  , lstm'\n    -- * GRU\n  , gru\n  , GRUp(..), gruMemory, gruUpdate, gruOutput\n  , gru'\n  ) where\n\nimport           Backprop.Learn.Initialize\nimport           Backprop.Learn.Model.Function\nimport           Backprop.Learn.Model.Neural\nimport           Backprop.Learn.Model.Regression\nimport           Backprop.Learn.Model.State\nimport           Backprop.Learn.Model.Types\nimport           Control.DeepSeq\nimport           Control.Monad\nimport           Control.Monad.Primitive\nimport           Data.Type.Tuple\nimport           Data.Typeable\nimport           GHC.Generics                          (Generic)\nimport           GHC.TypeNats\nimport           Lens.Micro\nimport           Lens.Micro.TH\nimport           Numeric.Backprop\nimport           Numeric.LinearAlgebra.Static.Backprop\nimport           Numeric.OneLiner\nimport           Numeric.Opto.Ref\nimport           Numeric.Opto.Update\nimport           Statistics.Distribution\nimport qualified Data.Binary                           as Bi\nimport qualified Numeric.LinearAlgebra.Static          as H\nimport qualified System.Random.MWC                     as MWC\n\n-- TODO: allow parameterize internal activation function?\n-- TODO: Peepholes\n\n-- | 'LSTM' layer parmateters\ndata LSTMp (i :: Nat) (o :: Nat) =\n    LSTMp { _lstmForget :: !(FCp (i + o) o)\n          , _lstmInput  :: !(FCp (i + o) o)\n          , _lstmUpdate :: !(FCp (i + o) o)\n          , _lstmOutput :: !(FCp (i + o) o)\n          }\n  deriving stock     (Generic, Typeable, Show)\n  deriving anyclass  (NFData, Linear Double, Metric Double, Bi.Binary, Regularize, Backprop)\n\nderiving via (GNum (LSTMp i o)) instance (KnownNat i, KnownNat o) => Num (LSTMp i o)\nderiving via (GNum (LSTMp i o)) instance (KnownNat i, KnownNat o) => Fractional (LSTMp i o)\nderiving via (GNum (LSTMp i o)) instance (KnownNat i, KnownNat o) => Floating (LSTMp i o)\n\nmakeLenses ''LSTMp\n\ninstance (PrimMonad m, KnownNat i, KnownNat o) => Mutable m (LSTMp i o) where\n    type Ref m (LSTMp i o) = GRef m (LSTMp i o)\n    thawRef   = gThawRef\n    freezeRef = gFreezeRef\n    copyRef   = gCopyRef\ninstance (PrimMonad m, KnownNat i, KnownNat o) => LinearInPlace m Double (LSTMp i o)\n\ninstance (PrimMonad m, KnownNat i, KnownNat o) => Learnable m (LSTMp i o)\n\n-- | Stateless version of 'lstm' that takes the \"previous input\" as a part\n-- of the input vector.\nlstm'\n    :: (KnownNat i, KnownNat o)\n    => Model ('Just (LSTMp i o)) ('Just (R o)) (R (i + o)) (R o)\nlstm' = modelD $ \\(PJust p) x (PJust s) ->\n    let forget = logistic $ runLRp (p ^^. lstmForget) x\n        input  = logistic $ runLRp (p ^^. lstmInput ) x\n        update = tanh     $ runLRp (p ^^. lstmUpdate) x\n        s'     = forget * s + input * update\n        o      = logistic $ runLRp (p ^^. lstmOutput) x\n        h      = o * tanh s'\n    in  (h, PJust s')\n\n-- | Long-term short-term memory layer\n--\n-- <http://colah.github.io/posts/2015-08-Understanding-LSTMs/>\n--\nlstm\n    :: (KnownNat i, KnownNat o)\n    => Model ('Just (LSTMp i o)) ('Just (R o :# R o)) (R i) (R o)\nlstm = recurrent H.split (H.#) id lstm'\n\nreshapeLSTMpInput\n    :: (ContGen d, PrimMonad m, KnownNat i, KnownNat i', KnownNat o)\n    => d\n    -> MWC.Gen (PrimState m)\n    -> LSTMp i o\n    -> m (LSTMp i' o)\nreshapeLSTMpInput d g (LSTMp forget input update output) =\n    LSTMp <$> reshaper forget\n          <*> reshaper input\n          <*> reshaper update\n          <*> reshaper output\n  where\n    reshaper = reshapeLRpInput d g\n\nreshapeLSTMpOutput\n    :: (ContGen d, PrimMonad m, KnownNat i, KnownNat o, KnownNat o')\n    => d\n    -> MWC.Gen (PrimState m)\n    -> LSTMp i o\n    -> m (LSTMp i o')\nreshapeLSTMpOutput d g (LSTMp forget input update output) =\n    LSTMp <$> reshaper forget\n          <*> reshaper input\n          <*> reshaper update\n          <*> reshaper output\n  where\n    reshaper = reshapeLRpInput  d g\n           <=< reshapeLRpOutput d g\n\n-- | Forget biases initialized to 1\ninstance (KnownNat i, KnownNat o) => Initialize (LSTMp i o) where\n    initialize d g = LSTMp <$> set (mapped . fcBias) 1 (initialize d g)\n                           <*> initialize d g\n                           <*> initialize d g\n                           <*> initialize d g\n\n-- | 'GRU' layer parmateters\ndata GRUp (i :: Nat) (o :: Nat) =\n    GRUp { _gruMemory :: !(FCp (i + o) o)\n         , _gruUpdate :: !(FCp (i + o) o)\n         , _gruOutput :: !(FCp (i + o) o)\n         }\n  deriving stock     (Generic, Typeable, Show)\n  deriving anyclass  (NFData, Linear Double, Metric Double, Bi.Binary, Initialize, Regularize, Backprop)\n\nderiving via (GNum (GRUp i o)) instance (KnownNat i, KnownNat o) => Num (GRUp i o)\nderiving via (GNum (GRUp i o)) instance (KnownNat i, KnownNat o) => Fractional (GRUp i o)\nderiving via (GNum (GRUp i o)) instance (KnownNat i, KnownNat o) => Floating (GRUp i o)\n\nmakeLenses ''GRUp\n\ninstance (PrimMonad m, KnownNat i, KnownNat o) => Mutable m (GRUp i o) where\n    type Ref m (GRUp i o) = GRef m (GRUp i o)\n    thawRef   = gThawRef\n    freezeRef = gFreezeRef\n    copyRef   = gCopyRef\ninstance (KnownNat i, KnownNat o, Mutable m (GRUp i o)) => LinearInPlace m Double (GRUp i o)\n\ninstance (KnownNat i, KnownNat o, PrimMonad m) => Learnable m (GRUp i o)\n\n-- | Stateless version of 'gru' that takes the \"previous input\" as a part\n-- of the input vector.\ngru'\n    :: forall i o. (KnownNat i, KnownNat o)\n    => Model ('Just (GRUp i o)) 'Nothing (R (i + o)) (R o)\ngru' = modelStatelessD $ \\(PJust p) x ->\n    let z      = logistic $ runLRp (p ^^. gruMemory) x\n        r      = logistic $ runLRp (p ^^. gruUpdate) x\n        r'     = 1 # r\n        h'     = tanh     $ runLRp (p ^^. gruOutput) (r' * x)\n    in  (1 - z) * snd (split @i x) + z * h'\n\n-- | Gated Recurrent Unit\n--\n-- <http://colah.github.io/posts/2015-08-Understanding-LSTMs/>\n--\ngru :: (KnownNat i, KnownNat o)\n    => Model ('Just (GRUp i o)) ('Just (R o)) (R i) (R o)\ngru = recurrent H.split (H.#) id gru'\n", "meta": {"hexsha": "f31b0933010f86e7248b9bb393232498ff76b5d1", "size": 7337, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Backprop/Learn/Model/Neural/LSTM.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "src/Backprop/Learn/Model/Neural/LSTM.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "src/Backprop/Learn/Model/Neural/LSTM.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 38.2135416667, "max_line_length": 104, "alphanum_fraction": 0.5648085048, "num_tokens": 2046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4807457170647794}}
{"text": "module Main where\n\nimport           Control.Monad.Error (runErrorT)\nimport           Control.Monad.Mersenne.Random (evalRandom)\nimport           Numeric.IEEE (IEEE, epsilon)\nimport           System.Random.Mersenne.Pure64 (pureMT)\nimport qualified Data.Vector.Unboxed as V\nimport           Statistics.Test.ApproxRand\nimport           Test.HUnit (Assertion, assertBool, assertEqual)\nimport           Test.Framework\nimport           Test.Framework.Providers.HUnit\n\ntests :: Test\ntests = testGroup \"Paired approximate randomization tests\" $\n  concat [statTests, randomizationTests]\n\nmain :: IO ()\nmain = defaultMain [ tests ]\n\n-- Statistics tests\n\nstatTests :: [Test]\nstatTests = [meanDifferenceTest]\n\nmeanDifferenceTest :: Test\nmeanDifferenceTest =\n  testIEEEEquality \"mean difference robot competition\"\n    1.8 $ meanDifference cohenRobotsAlpha cohenRobotsBeta\n\n-- Approximate andomization tests\n\nrandomizationTests :: [Test]\nrandomizationTests = [pairApproxExactTestScores]\n\npairApproxExactTestScores :: Test\npairApproxExactTestScores =\n  testEquality  \"number of extreme values robot competition\"\n    (Right 21) $ V.length `fmap` V.filter (>= 1.8) `fmap` scores\n  where\n    test = runErrorT $\n      approxRandPairStats differenceMean 1024 cohenRobotsAlpha cohenRobotsBeta\n    scores = evalRandom test $ pureMT 42\n\n-- Helper functions\n\ntestEquality :: (Show a, Eq a) => String -> a -> a -> Test\ntestEquality msg a b = testCase msg $ assertEqual msg a b\n\ntestIEEEEquality :: IEEE a => String -> a -> a -> Test\ntestIEEEEquality msg a b = testCase msg $ assertEqualIEEE msg a b\n\nassertEqualIEEE :: IEEE a => String -> a -> a -> Assertion\nassertEqualIEEE msg a b = assertBool msg $ fracEq epsilon a b\n\n-- Suggested in The Floating Point Guide: http://floating-point-gui.de/\nfracEq :: (Fractional a, Ord a) => a -> a -> a -> Bool\nfracEq eps a b\n  | a == b     = True\n  | a * b == 0 = diff < (eps * eps)\n  | otherwise  = diff / (abs a + abs b) < eps\n  where diff = abs (a - b)\n   \n\n-- Example from Cohen, 1995\ncohenRobotsAlpha :: V.Vector Double\ncohenRobotsAlpha = V.fromList [8,3,9,6,5,8,7,8,9,9]\n\ncohenRobotsBeta :: V.Vector Double\ncohenRobotsBeta  = V.fromList [7,0,9,4,5,9,8,3,4,5]\n", "meta": {"hexsha": "c4680a58e1968ba629704f37b289fe7ea20e03f7", "size": 2179, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/tests.hs", "max_stars_repo_name": "danieldk/approx-rand-test", "max_stars_repo_head_hexsha": "0bfc9a3f16381960bb0420264915f2baf2eea175", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-15T18:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-15T18:15:56.000Z", "max_issues_repo_path": "tests/tests.hs", "max_issues_repo_name": "danieldk/approx-rand-test", "max_issues_repo_head_hexsha": "0bfc9a3f16381960bb0420264915f2baf2eea175", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/tests.hs", "max_forks_repo_name": "danieldk/approx-rand-test", "max_forks_repo_head_hexsha": "0bfc9a3f16381960bb0420264915f2baf2eea175", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1285714286, "max_line_length": 78, "alphanum_fraction": 0.7003212483, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.48065360440394095}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\nmodule Numeric.Layer where\n\nimport Dependent.Size\nimport Numeric.Vector.Sized\nimport Data.Kind(Type)\n\nclass Layer layer where\n  type Inputs layer :: Size\n  type Outputs layer :: Size\n  type Tape layer :: Type\n  type Gradient layer :: Type\n\n  forward :: layer\n          -> SizedArray (Inputs layer)\n          -> (SizedArray (Outputs layer), Tape layer)\n\n  backward :: layer\n           -> Tape layer\n           -> SizedArray (Outputs layer)\n           -> (Gradient layer, SizedArray (Inputs layer))\n\n  applyGradient :: layer -> Gradient layer -> layer\n", "meta": {"hexsha": "dce3067698a80a0b3cdc9bf8ce1730020d7a2778", "size": 641, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Layer.hs", "max_stars_repo_name": "mixed-signals/mixed-signals", "max_stars_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/Layer.hs", "max_issues_repo_name": "mixed-signals/mixed-signals", "max_issues_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "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/Numeric/Layer.hs", "max_forks_repo_name": "mixed-signals/mixed-signals", "max_forks_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "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.6538461538, "max_line_length": 57, "alphanum_fraction": 0.655226209, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48052325539005264}}
{"text": "\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE OverloadedLists     #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE FlexibleInstances   #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE TypeApplications    #-}\n{-# LANGUAGE TypeOperators       #-}\n\nimport Data.Maybe\nimport Data.Number.Symbolic\nimport qualified Data.Number.Symbolic as Sym\nimport Data.Proxy\n\nimport qualified Naperian as N\nimport qualified Data.Foldable as F\nimport           Control.Applicative ( liftA2 )\nimport qualified GHC.TypeLits as M\nimport           Data.Functor\nimport           Data.List.Split\n\nimport           Numeric.Sundials.ARKode.ODE\nimport           Numeric.LinearAlgebra\n\nkx, ky :: Floating a => a\nkx = 0.5\nky = 0.75\n\n-- spatial mesh size\nnx, ny :: Int\nnx = 30\nny = 60\n\n-- x mesh spacing\n-- y mesh spacing\ndx :: Floating a => a\ndx = 1 / (fromIntegral nx - 1)\n\ndy :: Floating a => a\ndy = 1 / (fromIntegral ny - 1)\n\nc1, c2 :: Floating a => a\nc1 = kx/dx/dx\nc2 = ky/dy/dy\n\ncc4' :: forall b m n . (M.KnownNat m, M.KnownNat n, Num b) =>\n        N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] b\ncc4' = N.Prism $ N.Prism $ N.Prism $ N.Prism $ N.Scalar $\n      N.viota @m <&> (\\(N.Fin x) ->\n      N.viota @n <&> (\\(N.Fin w) ->\n      N.viota @m <&> (\\(N.Fin v) ->\n      N.viota @n <&> (\\(N.Fin u) ->\n      (f m n x w v u)))))\n        where\n          m = fromIntegral $ M.natVal (undefined :: Proxy m)\n          n = fromIntegral $ M.natVal (undefined :: Proxy n)\n          f m n i j k l | i == 0               = 0\n                        | j == 0               = 0\n                        | i == n - 1           = 0\n                        | j == m - 1           = 0\n                        | k == i - 1 && l == j = 1\n                        | k == i     && l == j = -2\n                        | k == i + 1 && l == j = 1\n                        | otherwise            = 0\n\ncc5' :: forall a m n . (M.KnownNat m, M.KnownNat n, Floating a) =>\n        N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] a\ncc5' = N.binary (*) (N.Scalar c2) cc4'\n\ncc5Sym' :: forall a m n . (M.KnownNat m, M.KnownNat n, Floating a, Eq a) =>\n          N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] (Sym a)\ncc5Sym' = N.binary (*) (N.Scalar $ var \"c2\") cc4'\n\nyy4' :: forall b m n . (M.KnownNat m, M.KnownNat n, Num b) =>\n        N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] b\nyy4' = N.Prism $ N.Prism $ N.Prism $ N.Prism $ N.Scalar $\n      N.viota @m <&> (\\(N.Fin x) ->\n      N.viota @n <&> (\\(N.Fin w) ->\n      N.viota @m <&> (\\(N.Fin v) ->\n      N.viota @n <&> (\\(N.Fin u) ->\n      (f m n x w v u)))))\n        where\n          m = fromIntegral $ M.natVal (undefined :: Proxy m)\n          n = fromIntegral $ M.natVal (undefined :: Proxy n)\n          f :: Int -> Int -> Int -> Int -> Int -> Int -> b\n          f m n i j k l | i == 0                   = 0\n                        | j == 0                   = 0\n                        | i == n - 1               = 0\n                        | j == m - 1               = 0\n                        | k == i     && l == j - 1 = 1\n                        | k == i     && l == j     = -2\n                        | k == i     && l == j + 1 = 1\n                        | otherwise                = 0\n\nyy5' :: forall a m n . (M.KnownNat m, M.KnownNat n, Floating a) =>\n        N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] a\nyy5' = N.binary (*) (N.Scalar c1) yy4'\n\nyy5Sym' :: forall a m n . (M.KnownNat m, M.KnownNat n, Floating a, Eq a) =>\n           N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] (Sym a)\nyy5Sym' = N.binary (*) (N.Scalar $ var \"c1\") yy4'\n\nccSym5 = cc5Sym' @Double @4 @5\nyy5Sym = yy5Sym' @Double @4 @5\n\nccSym5\n\nyy5Sym\n\nfmap (N.elements . N.Prism . N.Prism . N.Scalar) $ N.elements $ N.crystal $ N.crystal $ N.binary (+) cc5Sym yy5Sym\n\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE OverloadedLists       #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE GADTs               #-}\n\nimport Data.Maybe\nimport Data.Number.Symbolic\nimport Data.Proxy\n\nimport qualified Naperian as N\nimport qualified Data.Foldable as F\nimport           Control.Applicative ( liftA2 )\nimport qualified GHC.TypeLits as M\n\nimport           Numeric.Sundials.ARKode.ODE\nimport           Numeric.LinearAlgebra\n\nx1, a, x2 :: Double\nx1 = 0\na = 1.0\nx2 = a\n\ny1, y2 :: Double\ny1 = 0.0\ny2 = 1.0\n\nbigT :: Double\nbigT = 1000.0\n\nn :: Int\nn = 2\n\ndx :: Double\ndx = a / (fromIntegral n + 1)\n\ndy :: Double\ndy = a / (fromIntegral n + 1)\n\nbeta, s :: Double\nbeta = 1.0e-5\ns = beta / (dx * dx)\n\nkx, ky :: Double\nkx = 0.5\nky = 0.75\n\nc1, c2 :: Double\nc1 = kx/dx/dx\nc2 = ky/dy/dy\n\nbigAA1 :: Matrix Double\nbigAA1 = assoc (n * n, n * n) 0.0 [((i, j), f (i, j)) | i <- [0 .. n * n - 1]\n                                                      , j <- [i - n, i,  i + n]\n                                                      , j `elem` [0 .. n * n -1]]\n  where\n    f (i, j) | i     == j = (-2.0) * c1\n             | i - n == j = 1.0    * c1\n             | i + n == j = 1.0    * c1\n             | otherwise = error $ show (i, j)\n\nbigAA2 :: Matrix Double\nbigAA2 = diagBlock (replicate n bigA)\n  where\n    bigA :: Matrix Double\n    bigA = assoc (n, n) 0.0 [((i, j), f (i, j)) | i <- [0 .. n - 1]\n                                                , j <- [i-1..i+1]\n                                                , j `elem` [0..n-1]]\n      where\n        f (i, j) | i     == j = (-2.0) * c2\n                 | i - 1 == j = 1.0    * c2\n                 | i + 1 == j = 1.0    * c2\n\nbigAA :: Matrix Double\nbigAA = bigAA1 + bigAA2\n\nbigAA1\n\nbigAA2\n\nn\n\nbigZZ1 :: Matrix Double\nbigZZ1 = assoc (m * m, m * m) 0.0 [((i, j), f (i, j)) | i <- [0 .. m * m - 1]\n                                                      , j <- [0 .. m * m - 1]]\n  where\n    m = n + 2\n    f (i, j) | i     == 0     = 0.0\n             | j     == 0     = 0.0\n             | i     == j     = (-2.0) * c1\n             | i - n == j     = 1.0    * c1\n             | i + n == j     = 1.0    * c1\n             | i     == n + 1 = 0.0\n             | j     == n + 1 = 0.0\n             | otherwise      = 0.0\n\n\nbigZZ1\n\nx :: forall m n . (M.KnownNat m, M.KnownNat n) => N.Vector n (N.Vector m (Sym Int))\nx = (fromJust . N.fromList) $\n    map (fromJust . N.fromList) ([[var $ (\\(x,y) -> \"A\" ++ show x ++ \",\" ++ show y) (x,y) | y <- [1..m]] | x <- [1..n]] :: [[Sym Int]])\n    where\n      m = M.natVal (undefined :: Proxy m)\n      n = M.natVal (undefined :: Proxy n)\n\nu1 :: N.Hyper '[N.Vector 3, N.Vector 2] (Sym Int)\nu1 = N.Prism $ N.Prism (N.Scalar x)\n\nu1\n\ny :: forall n . M.KnownNat n => N.Vector n (Sym Int)\ny = (fromJust . N.fromList) $\n    (map (var . (\"v\" ++) . show) [1..n ] :: [Sym Int])\n    where\n    n = M.natVal (undefined :: Proxy n)\n\nu2 :: N.Hyper '[N.Vector 3] (Sym Int)\nu2 = N.Prism (N.Scalar y)\n\nN.innerH u1 u2\n", "meta": {"hexsha": "e0767d9e2d729e44380e3ea3439dedc298b9b4b4", "size": 6904, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Two Dimensional Heat Equation.hs", "max_stars_repo_name": "idontgetoutmuch/Diffusions", "max_stars_repo_head_hexsha": "b07eb63aeb8d7b12e5a2ba18a01eca520af3e128", "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": "Two Dimensional Heat Equation.hs", "max_issues_repo_name": "idontgetoutmuch/Diffusions", "max_issues_repo_head_hexsha": "b07eb63aeb8d7b12e5a2ba18a01eca520af3e128", "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": "Two Dimensional Heat Equation.hs", "max_forks_repo_name": "idontgetoutmuch/Diffusions", "max_forks_repo_head_hexsha": "b07eb63aeb8d7b12e5a2ba18a01eca520af3e128", "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.3787234043, "max_line_length": 135, "alphanum_fraction": 0.4513325608, "num_tokens": 2351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.48052324953741093}}
{"text": "{-# LANGUAGE Rank2Types #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module     : Numeric.LinearAlgebra.Matrix.Herm\n-- Copyright  : Copyright (c) 2010, Patrick Perry <patperry@gmail.com>\n-- License    : BSD3\n-- Maintainer : Patrick Perry <patperry@gmail.com>\n-- Stability  : experimental\n--\n-- Hermitian views of matrices.\n--\n\nmodule Numeric.LinearAlgebra.Matrix.Herm (\n    -- * Immutable interface\n    \n    -- ** Vector multiplication\n    hermMulVector,\n    hermMulVectorWithScale,\n    addHermMulVectorWithScales,\n    \n    -- ** Matrix  multiplication\n    hermMulMatrix,\n    hermMulMatrixWithScale,\n    addHermMulMatrixWithScales,\n\n    -- ** Updates\n    hermRank1Update,\n    hermRank2Update,\n    hermRankKUpdate,   \n    hermRank2KUpdate,    \n\n    \n    -- * Mutable interface\n    hermCreate,\n    \n    -- ** Vector multiplication\n    hermMulVectorTo,\n    hermMulVectorWithScaleTo,\n    addHermMulVectorWithScalesM_,\n    \n    -- ** Matrix multiplication\n    hermMulMatrixTo,\n    hermMulMatrixWithScaleTo,\n    addHermMulMatrixWithScalesM_,\n\n    -- ** Updates\n    hermRank1UpdateM_,\n    hermRank2UpdateM_,\n    hermRankKUpdateM_,  \n    hermRank2KUpdateM_,\n    \n    ) where\n\nimport Control.Monad( when )\nimport Control.Monad.ST( ST, runST, unsafeIOToST )\nimport Text.Printf( printf )\n\nimport Numeric.LinearAlgebra.Vector( Vector, RVector, STVector )\nimport qualified Numeric.LinearAlgebra.Vector as V\nimport Numeric.LinearAlgebra.Matrix.Base( Matrix )\nimport Numeric.LinearAlgebra.Matrix.STBase( STMatrix, RMatrix )\nimport qualified Numeric.LinearAlgebra.Matrix.STBase as M\nimport Numeric.LinearAlgebra.Types\nimport qualified Foreign.BLAS as BLAS\n\n\n-- | A safe way to create and work with a mutable Herm Matrix before returning \n-- an immutable one for later perusal.\nhermCreate :: (Storable e)\n           => (forall s. ST s (Herm (STMatrix s) e))\n           -> Herm Matrix e\nhermCreate mh = runST $ do\n    (Herm u ma) <- mh\n    a <- M.unsafeFreeze ma\n    return $ Herm u a\n\n-- | @hermRank1Update alpha x a@ returns\n-- @alpha * x * x^H + a@.\nhermRank1Update :: (BLAS2 e)\n                => Double -> Vector e -> Herm Matrix e -> Herm Matrix e\nhermRank1Update alpha x (Herm uplo a) = runST $ do\n    ma' <- M.newCopy a\n    hermRank1UpdateM_ alpha x (Herm uplo ma')\n    a' <- M.unsafeFreeze ma'\n    return $ Herm uplo a'\n\n-- | @hermRank2Update alpha x y a@ returns\n-- @alpha * x * y^H + conj(alpha) * y * x^H + a@.\nhermRank2Update :: (BLAS2 e)\n                => e -> Vector e -> Vector e -> Herm Matrix e\n                -> Herm Matrix e\nhermRank2Update alpha x y (Herm uplo a) = runST $ do\n    ma' <- M.newCopy a\n    hermRank2UpdateM_ alpha x y (Herm uplo ma')\n    a' <- M.unsafeFreeze ma'\n    return $ Herm uplo a'\n\n-- | @hermRankKUpdate alpha trans a beta c@ returns\n-- @c := alpha * a * a^H + beta * c@ when @trans@ is @NoTrans@ and\n-- @c := alpha * a^H * a + beta * c@ when @trans@ is @ConjTrans@.  The\n-- function signals an error when @trans@ is @Trans@.\nhermRankKUpdate :: (BLAS3 e)\n                => e -> Trans -> Matrix e -> e -> Herm Matrix e\n                -> Herm Matrix e\nhermRankKUpdate alpha trans a beta (Herm uplo c) = runST $ do\n    mc' <- M.newCopy c\n    hermRankKUpdateM_ alpha trans a beta (Herm uplo mc')\n    c' <- M.unsafeFreeze mc'\n    return $ Herm uplo c'\n\n-- | @hermRank2KUpdate alpha trans a b beta c@ returns\n-- @c := alpha * a * b^H + conj(alpha) * b * a^H + beta * c@ when @trans@ is\n-- @NoTrans@ and @c := alpha * b^H * a + conj(alpha) * a^H * b + beta * c@\n-- when @trans@ is @ConjTrans@.  The function signals an error when @trans@\n-- is @Trans@.\nhermRank2KUpdate :: (BLAS3 e)\n                 => e -> Trans -> Matrix e -> Matrix e -> e -> Herm Matrix e\n                 -> Herm Matrix e\nhermRank2KUpdate alpha trans a b beta (Herm uplo c) = runST $ do\n    mc' <- M.newCopy c\n    hermRank2KUpdateM_ alpha trans a b beta (Herm uplo mc')\n    c' <- M.unsafeFreeze mc'\n    return $ Herm uplo c'\n\n-- | @hermRank1UpdateM_ alpha x a@ sets\n-- @a := alpha * x * x^H + a@.\nhermRank1UpdateM_ :: (RVector v, BLAS2 e)\n                  => Double -> v e -> Herm (STMatrix s) e -> ST s ()\nhermRank1UpdateM_ alpha x (Herm uplo a) = do\n    nx <- V.getDim x\n    (ma,na) <- M.getDim a\n    let n = nx\n\n    when ((not . and) [ nx == n, (ma,na) == (n,n) ]) $ error $\n        printf (\"hermRank1UpdateM_ _ <vector with dim %d>\"\n                 ++ \" (Herm _ <matrix with dim (%d,%d)>):\"\n                 ++ \" invalid dimensions\") nx ma na\n\n    unsafeIOToST $\n        V.unsafeWith x $ \\px ->\n        M.unsafeWith a $ \\pa lda ->\n            BLAS.her uplo n alpha px 1 pa lda\n\n\n-- | @hermRank2UpdateM_ alpha x y a@ sets\n-- @a := alpha * x * y^H + conj(alpha) * y * x^H + a@.\nhermRank2UpdateM_ :: (RVector v1, RVector v2, BLAS2 e)\n                  => e -> v1 e -> v2 e -> Herm (STMatrix s) e -> ST s ()\nhermRank2UpdateM_ alpha x y (Herm uplo a) = do\n    nx <- V.getDim x\n    ny <- V.getDim y\n    (ma,na) <- M.getDim a\n    let n = nx\n    \n    when ((not . and) [ nx == n, ny == n, (ma,na) == (n,n) ]) $ error $\n        printf (\"hermRank2UpdateM_ _ <vector with dim %d>\"\n                 ++ \" <vector with dim %d>\"\n                 ++ \" (Herm _ <matrix with dim (%d,%d)>):\"\n                 ++ \" invalid dimensions\") nx ny ma na\n\n    unsafeIOToST $\n        V.unsafeWith x $ \\px ->\n        V.unsafeWith y $ \\py ->\n        M.unsafeWith a $ \\pa lda ->\n            BLAS.her2 uplo n alpha px 1 py 1 pa lda\n\n\n-- | @hermRankKUpdateM_ alpha trans a beta c@ sets\n-- @c := alpha * a * a^H + beta * c@ when @trans@ is @NoTrans@ and\n-- @c := alpha * a^H * a + beta * c@ when @trans@ is @ConjTrans@.  The\n-- function signals an error when @trans@ is @Trans@.\nhermRankKUpdateM_ :: (RMatrix m, BLAS3 e)\n                  => e -> Trans -> m e -> e -> Herm (STMatrix s) e\n                  -> ST s ()\nhermRankKUpdateM_ alpha trans a beta (Herm uplo c) = do\n    (ma,na) <- M.getDim a\n    (mc,nc) <- M.getDim c\n    let (n,k) = if trans == NoTrans then (ma,na) else (na,ma)\n\n    when (trans == Trans) $ error $\n        printf (\"hermRankKUpdateM_ _ %s:\"\n                 ++ \" trans argument must be NoTrans or ConjTrans\")\n               (show trans)\n               \n    when ((not . and) [ (mc,nc) == (n,n)\n                      , case trans of NoTrans -> (ma,na) == (n,k)\n                                      _       -> (ma,na) == (k,n)\n                      ]) $ error $\n            printf (\"hermRankKUpdateM_ _ %s <matrix with dim (%d,%d)> _\"\n                    ++ \" (Herm _ <matrix with dim (%d,%d)>):\"\n                    ++ \" invalid dimensions\") (show trans) ma na mc nc\n\n    unsafeIOToST $\n        M.unsafeWith a $ \\pa lda ->\n        M.unsafeWith c $ \\pc ldc ->\n            BLAS.herk uplo trans n k alpha pa lda beta pc ldc\n\n\n-- | @hermRank2KUpdateM_ alpha trans a b beta c@ sets\n-- @c := alpha * a * b^H + conj(alpha) * b * a^H + beta * c@ when @trans@ is\n-- @NoTrans@ and @c := alpha * b^H * a + conj(alpha) * a^H * b + beta * c@\n-- when @trans@ is @ConjTrans@.  The function signals an error when @trans@\n-- is @Trans@.\nhermRank2KUpdateM_ :: (RMatrix m1, RMatrix m2, BLAS3 e)\n                   => e -> Trans -> m1 e -> m2 e -> e -> Herm (STMatrix s) e\n                   -> ST s ()\nhermRank2KUpdateM_ alpha trans a b beta (Herm uplo c) = do\n    (ma,na) <- M.getDim a\n    (mb,nb) <- M.getDim b\n    (mc,nc) <- M.getDim c\n    let (n,k) = if trans == NoTrans then (ma,na) else (na,ma)\n\n    when (trans == Trans) $ error $\n        printf (\"hermRank2KUpdateM_ _ %s:\"\n                 ++ \" trans argument must be NoTrans or ConjTrans\")\n               (show trans)\n\n    when ((not . and) [ (mc,nc) == (n,n)\n                      , (mb,nb) == (ma,na)\n                      , case trans of NoTrans -> (ma,na) == (n,k)\n                                      _       -> (ma,na) == (k,n)\n                      ]) $ error $\n            printf (\"hermRank2KUpdateM_ _ %s <matrix with dim (%d,%d)>\"\n                    ++ \" <matrix with dim (%d,%d)> _\"\n                    ++ \" (Herm _ <matrix with dim (%d,%d)>):\"\n                    ++ \" invalid dimensions\") (show trans) ma na mb nb mc nc\n\n    unsafeIOToST $\n        M.unsafeWith a $ \\pa lda ->\n        M.unsafeWith b $ \\pb ldb ->\n        M.unsafeWith c $ \\pc ldc ->\n            BLAS.her2k uplo trans n k alpha pa lda pb ldb beta pc ldc\n\n\n-- | @hermMulVector a x@ returns @a * x@.\nhermMulVector :: (BLAS2 e)\n              => Herm Matrix e\n              -> Vector e\n              -> Vector e\nhermMulVector a x =\n    V.create $ do\n        n <- V.getDim x\n        y <- V.new_ n\n        hermMulVectorTo y a x\n        return y\n\n-- | @hermMulVectorWithScale alpha a x@ retunrs @alpha * a * x@.\nhermMulVectorWithScale :: (BLAS2 e)\n                       => e\n                       -> Herm Matrix e\n                       -> Vector e\n                       -> Vector e\nhermMulVectorWithScale alpha a x =\n    V.create $ do\n        n <- V.getDim x\n        y <- V.new_ n\n        hermMulVectorWithScaleTo y alpha a x\n        return y\n                       \n-- | @addHermMulVectorWithScales alpha a x y@\n-- returns @alpha * a * x + beta * y@.\naddHermMulVectorWithScales :: (BLAS2 e)\n                           => e\n                           -> Herm Matrix e\n                           -> Vector e\n                           -> e\n                           -> Vector e\n                           -> Vector e\naddHermMulVectorWithScales alpha a x beta y =\n    V.create $ do\n        y' <- V.newCopy y\n        addHermMulVectorWithScalesM_ alpha a x beta y'\n        return y'\n\n-- | @hermMulMatrix side a b@\n-- returns @alpha * a * b@ when @side@ is @LeftSide@ and\n-- @alpha * b * a@ when @side@ is @RightSide@.\nhermMulMatrix :: (BLAS3 e)\n              => Side -> Herm Matrix e\n              -> Matrix e\n              -> Matrix e\nhermMulMatrix side a b = \n    M.create $ do\n        mn <- M.getDim b\n        c <- M.new_ mn\n        hermMulMatrixTo c side a b\n        return c\n\n-- | @hermMulMatrixWithScale alpha side a b@\n-- returns @alpha * a * b@ when @side@ is @LeftSide@ and\n-- @alpha * b * a@ when @side@ is @RightSide@.\nhermMulMatrixWithScale :: (BLAS3 e)\n                       => e\n                       -> Side -> Herm Matrix e\n                       -> Matrix e\n                       -> Matrix e\nhermMulMatrixWithScale alpha side a b =\n    M.create $ do\n        mn <- M.getDim b\n        c <- M.new_ mn\n        hermMulMatrixWithScaleTo c alpha side a b\n        return c\n\n-- | @addHermMulMatrixWithScales alpha side a b beta c@\n-- returns @alpha * a * b + beta * c@ when @side@ is @LeftSide@ and\n-- @alpha * b * a + beta * c@ when @side@ is @RightSide@.\naddHermMulMatrixWithScales :: (BLAS3 e)\n                           => e\n                           -> Side -> Herm Matrix e\n                           -> Matrix e\n                           -> e\n                           -> Matrix e\n                           -> Matrix e\naddHermMulMatrixWithScales alpha side a b beta c = \n    M.create $ do\n        c' <- M.newCopy c\n        addHermMulMatrixWithScalesM_ alpha side a b beta c'\n        return c'\n\n-- | @hermMulVectorTo dst a x@ sets @dst := a * x@.\nhermMulVectorTo :: (RMatrix m, RVector v, BLAS2 e)\n                => STVector s e\n                -> Herm m e\n                -> v e\n                -> ST s ()\nhermMulVectorTo dst = hermMulVectorWithScaleTo dst 1\n\n-- | @hermMulVectorWithScaleTo dst alpha a x@\n-- sets @dst := alpha * a * x@.\nhermMulVectorWithScaleTo :: (RMatrix m, RVector v, BLAS2 e)\n                         => STVector s e\n                         -> e\n                         -> Herm m e\n                         -> v e\n                         -> ST s ()\nhermMulVectorWithScaleTo dst alpha a x =\n    addHermMulVectorWithScalesM_ alpha a x 0 dst\n\n-- | @addHermMulVectorWithScalesM_ alpha a x beta y@\n-- sets @y := alpha * a * x + beta * y@.\naddHermMulVectorWithScalesM_ :: (RMatrix m, RVector v, BLAS2 e)\n                             => e\n                             -> Herm m e\n                             -> v e\n                             -> e\n                             -> STVector s e\n                             -> ST s ()\naddHermMulVectorWithScalesM_ alpha (Herm uplo a) x beta y = do\n    (ma,na) <- M.getDim a\n    nx <- V.getDim x\n    ny <- V.getDim y\n    let n = ny\n    \n    when (ma /= na) $ error $\n        printf (\"addHermMulVectorWithScalesM_ _\"\n                ++ \" (Herm %s <matrix with dim (%d,%d)>)\"\n                ++ \" %s <vector with dim %d>\"\n                ++ \" _\"\n                ++ \" <vector with dim %d>: Herm matrix is not square\")\n               (show uplo) ma na\n               nx ny\n               \n    when ((not . and) [ (ma,na) == (n,n)\n                      , nx == n\n                      , ny == n\n                      ]) $ error $\n        printf (\"addHermMulVectorWithScalesM_ _\"\n                ++ \" (Herm %s <matrix with dim (%d,%d)>)\"\n                ++ \" %s <vector with dim %d>\"\n                ++ \" _\"\n                ++ \" <vector with dim %d>: dimension mismatch\")\n               (show uplo) ma na\n               nx ny\n\n    unsafeIOToST $\n        M.unsafeWith a $ \\pa lda ->\n        V.unsafeWith x $ \\px ->\n        V.unsafeWith y $ \\py ->\n            BLAS.hemv uplo n alpha pa lda px 1 beta py 1\n\n-- | @hermMulMatrixTo dst side a b@\n-- sets @dst := a * b@ when @side@ is @LeftSide@ and\n-- @dst := b * a@ when @side@ is @RightSide@.\nhermMulMatrixTo :: (RMatrix m1, RMatrix m2, BLAS3 e)\n                => STMatrix s e\n                -> Side -> Herm m1 e\n                -> m2 e\n                -> ST s ()\nhermMulMatrixTo dst = hermMulMatrixWithScaleTo dst 1\n\n-- | @hermMulMatrixWithScaleTo dst alpha side a b@\n-- sets @dst := alpha * a * b@ when @side@ is @LeftSide@ and\n-- @dst := alpha * b * a@ when @side@ is @RightSide@.\nhermMulMatrixWithScaleTo :: (RMatrix m1, RMatrix m2, BLAS3 e)\n                         => STMatrix s e\n                         -> e\n                         -> Side -> Herm m1 e\n                         -> m2 e\n                         -> ST s ()\nhermMulMatrixWithScaleTo dst alpha side a b =\n    addHermMulMatrixWithScalesM_ alpha side a b 0 dst\n\n-- | @addHermMulMatrixWithScalesM_ alpha side a b beta c@\n-- sets @c := alpha * a * b + beta * c@ when @side@ is @LeftSide@ and\n-- @c := alpha * b * a + beta * c@ when @side@ is @RightSide@.\naddHermMulMatrixWithScalesM_ :: (RMatrix m1, RMatrix m2, BLAS3 e)\n                             => e\n                             -> Side -> Herm m1 e\n                             -> m2 e\n                             -> e\n                             -> STMatrix s e\n                             -> ST s ()\naddHermMulMatrixWithScalesM_ alpha side (Herm uplo a) b beta c = do\n    (ma,na) <- M.getDim a\n    (mb,nb) <- M.getDim b\n    (mc,nc) <- M.getDim c\n    let (m,n) = (mc,nc)\n    \n    when (ma /= na) $ error $\n        printf (\"addHermMulMatrixWithScalesM_ _\"\n                ++ \" %s (Herm %s <matrix with dim (%d,%d)>)\" \n                ++ \" <matrix with dim (%d,%d)>\"\n                ++ \" _\"\n                ++ \" <matrix with dim (%d,%d)>: Herm matrix is not square\")\n               (show side) (show uplo) ma na\n               mb nb\n               mc nc\n    when ((not . and) [ case side of LeftSide  -> (ma,na) == (m,m)\n                                     RightSide -> (ma,na) == (n,n)\n                      , (mb, nb ) == (m,n)\n                      , (mc, nc ) == (m,n)\n                      ]) $ error $\n        printf (\"addHermMulMatrixWithScalesM_ _\"\n                ++ \" %s (Herm %s <matrix with dim (%d,%d)>)\" \n                ++ \" <matrix with dim (%d,%d)>\"\n                ++ \" _\"\n                ++ \" <matrix with dim (%d,%d)>: dimension mismatch\")\n               (show side) (show uplo) ma na\n               mb nb\n               mc nc\n\n    unsafeIOToST $\n        M.unsafeWith a $ \\pa lda ->\n        M.unsafeWith b $ \\pb ldb ->\n        M.unsafeWith c $ \\pc ldc ->\n            BLAS.hemm side uplo m n alpha pa lda pb ldb beta pc ldc\n", "meta": {"hexsha": "bb0d922f647ba32888e8ccb7bbc8cc5e307c5c80", "size": 15952, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Herm.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Herm.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Herm.hs", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 35.6868008949, "max_line_length": 79, "alphanum_fraction": 0.5003134403, "num_tokens": 4715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4805232495374109}}
{"text": "module Test.Grenade.Layers.Internal.Reference where\n\nimport           Numeric.LinearAlgebra\n\nim2col :: Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double\nim2col nrows ncols srows scols m =\n  let starts = fittingStarts (rows m) nrows srows (cols m) ncols scols\n  in  im2colFit starts nrows ncols m\n\nvid2col :: Int -> Int -> Int -> Int -> Int -> Int -> [Matrix Double] -> Matrix Double\nvid2col nrows ncols srows scols inputrows inputcols ms =\n  let starts = fittingStarts inputrows nrows srows inputcols ncols scols\n      subs   = fmap (im2colFit starts nrows ncols) ms\n  in  foldl1 (|||) subs\n\nim2colFit :: [(Int,Int)] -> Int -> Int -> Matrix Double -> Matrix Double\nim2colFit starts nrows ncols m =\n  let imRows = fmap (\\start -> flatten $ subMatrix start (nrows, ncols) m) starts\n  in  fromRows imRows\n\ncol2vid :: Int -> Int -> Int -> Int -> Int -> Int -> Matrix Double -> [Matrix Double]\ncol2vid nrows ncols srows scols drows dcols m =\n  let starts = fittingStart (cols m) (nrows * ncols) (nrows * ncols)\n      r      = rows m\n      mats   = fmap (\\s -> subMatrix (0,s) (r, nrows * ncols) m) starts\n      colSts = fittingStarts drows nrows srows dcols ncols scols\n  in  fmap (col2imfit colSts nrows ncols drows dcols) mats\n\ncol2im :: Int -> Int -> Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double\ncol2im krows kcols srows scols drows dcols m =\n  let starts     = fittingStarts drows krows srows dcols kcols scols\n  in  col2imfit starts krows kcols drows dcols m\n\ncol2imfit :: [(Int,Int)] -> Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double\ncol2imfit starts krows kcols drows dcols m =\n  let indicies   = (\\[a,b] -> (a,b)) <$> sequence [[0..(krows-1)], [0..(kcols-1)]]\n      convs      = fmap (zip indicies . toList) . toRows $ m\n      pairs      = zip convs starts\n      accums     = concatMap (\\(conv',(stx',sty')) -> fmap (\\((ix,iy), val) -> ((ix + stx', iy + sty'), val)) conv') pairs\n  in  accum (konst 0 (drows, dcols)) (+) accums\n\npoolForward :: Int -> Int -> Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double\npoolForward nrows ncols srows scols outputRows outputCols m =\n  let starts = fittingStarts (rows m) nrows srows (cols m) ncols scols\n  in  poolForwardFit starts nrows ncols outputRows outputCols m\n\npoolForwardList :: Functor f => Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> f (Matrix Double) -> f (Matrix Double)\npoolForwardList nrows ncols srows scols inRows inCols outputRows outputCols ms =\n  let starts = fittingStarts inRows nrows srows inCols ncols scols\n  in  poolForwardFit starts nrows ncols outputRows outputCols <$> ms\n\npoolForwardFit :: [(Int,Int)] -> Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double\npoolForwardFit starts nrows ncols _ outputCols m =\n  let els    = fmap (\\start -> maxElement $ subMatrix start (nrows, ncols) m) starts\n  in  matrix outputCols els\n\npoolBackward :: Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double -> Matrix Double\npoolBackward krows kcols srows scols inputMatrix gradientMatrix =\n  let inRows     = rows inputMatrix\n      inCols     = cols inputMatrix\n      starts     = fittingStarts inRows krows srows inCols kcols scols\n  in  poolBackwardFit starts krows kcols inputMatrix gradientMatrix\n\npoolBackwardList :: Functor f => Int -> Int -> Int -> Int -> Int -> Int -> f (Matrix Double, Matrix Double) -> f (Matrix Double)\npoolBackwardList krows kcols srows scols inRows inCols inputMatrices =\n  let starts     = fittingStarts inRows krows srows inCols kcols scols\n  in  uncurry (poolBackwardFit starts krows kcols) <$> inputMatrices\n\npoolBackwardFit :: [(Int,Int)] -> Int -> Int -> Matrix Double -> Matrix Double -> Matrix Double\npoolBackwardFit starts krows kcols inputMatrix gradientMatrix =\n  let inRows     = rows inputMatrix\n      inCols     = cols inputMatrix\n      inds       = fmap (\\start -> maxIndex $ subMatrix start (krows, kcols) inputMatrix) starts\n      grads      = toList $ flatten gradientMatrix\n      grads'     = zip3 starts grads inds\n      accums     = fmap (\\((stx',sty'),grad,(inx, iny)) -> ((stx' + inx, sty' + iny), grad)) grads'\n  in  accum (konst 0 (inRows, inCols)) (+) accums\n\n-- | These functions are not even remotely safe, but it's only called from the statically typed\n--   commands, so we should be good ?!?!?\n--   Returns the starting sub matrix locations which fit inside the larger matrix for the\n--   convolution. Takes into account the stride and kernel size.\nfittingStarts :: Int -> Int -> Int -> Int -> Int -> Int -> [(Int,Int)]\nfittingStarts nrows kernelrows steprows ncols kernelcols stepcolsh =\n  let rs = fittingStart nrows kernelrows steprows\n      cs = fittingStart ncols kernelcols stepcolsh\n      ls = sequence [rs, cs]\n  in  fmap (\\[a,b] -> (a,b)) ls\n\n-- | Returns the starting sub vector which fit inside the larger vector for the\n--   convolution. Takes into account the stride and kernel size.\nfittingStart :: Int -> Int -> Int -> [Int]\nfittingStart width kernel steps =\n  let go left | left + kernel < width\n              = left : go (left + steps)\n              | left + kernel == width\n              = [left]\n              | otherwise\n              = []\n  in go 0\n", "meta": {"hexsha": "9179fb98a117b0e0d5e586b07afbc9756521758e", "size": 5153, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Layers/Internal/Reference.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1527, "max_stars_repo_stars_event_min_datetime": "2016-06-23T13:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T05:22:00.000Z", "max_issues_repo_path": "test/Test/Grenade/Layers/Internal/Reference.hs", "max_issues_repo_name": "Alien-Inc/grenade", "max_issues_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 69, "max_issues_repo_issues_event_min_datetime": "2016-06-27T22:16:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-20T17:50:09.000Z", "max_forks_repo_path": "test/Test/Grenade/Layers/Internal/Reference.hs", "max_forks_repo_name": "Alien-Inc/grenade", "max_forks_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2016-06-28T02:24:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:17:29.000Z", "avg_line_length": 51.0198019802, "max_line_length": 128, "alphanum_fraction": 0.6681544731, "num_tokens": 1436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4805057467729142}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule STC.OrientationScaleAnalysis where\n\nimport           Control.Monad.Parallel    as MP\nimport           Data.Array.Repa           as R\nimport           Data.Complex\nimport           Data.List                 as L\nimport           Data.Vector.Unboxed       as VU\nimport           DFT.Plan\nimport           FokkerPlanck.DomainChange (r2z1Tor2s1)\nimport           Graphics.Gnuplot.Simple\nimport           Image.IO                  (ImageRepa (..), plotImageRepa,\n                                            plotImageRepaComplex)\nimport           STC.Convolution       \nimport           System.FilePath\nimport           Types\nimport           Utils.Array\nimport           Utils.Parallel\nimport Text.Printf\n\n\n-- {-# INLINE analyzeOrientation #-}\n-- analyzeOrientation :: Int -> [Double] -> R2T0Array -> (R2T0Array, R2T0Array)\n-- analyzeOrientation numOrientation thetaFreqs arr =\n--   let arrR2S1 = R.map magnitude . r2z1Tor2s1 numOrientation thetaFreqs $ arr\n--       deltaTheta = 2 * pi / fromIntegral numOrientation :: Double\n--       (Z :. _ :. cols :. rows) = extent arrR2S1\n--       orientationArr =\n--         fromListUnboxed (Z :. cols :. rows) .\n--         parMap\n--           rdeepseq\n--           (\\(i, j) ->\n--              deltaTheta *\n--              (fromIntegral .\n--               VU.maxIndex . toUnboxed . computeS . R.slice arrR2S1 $\n--               (Z :. All :. i :. j))) $\n--         [(i, j) | i <- [0 .. cols - 1], j <- [0 .. rows - 1]]\n--       freqArr = fromListUnboxed (Z :. (L.length thetaFreqs)) thetaFreqs\n--       magArr =\n--         R.map sqrt . sumS . R.map (\\x -> (magnitude x) ^ 2) . rotate3D $ arr\n--       func theta =\n--         computeS .\n--         R.traverse3 orientationArr freqArr magArr (\\_ _ _ -> extent arr) $ \\fOri fFreq fMag (Z :. k :. i :. j) ->\n--           (fMag (Z :. i :. j) :+ 0) *\n--           (exp $ 0 :+ (1) * fFreq (Z :. k) * (fOri (Z :. i :. j) + theta))\n--    in (func 0, func 0) \n\n\n-- {-# INLINE analyzeOrientationR2Z1T0 #-}\n-- analyzeOrientationR2Z1T0 ::\n--      Int -> [Double] -> [Double] -> R2T0Array -> (R2Z1T0Array, R2Z1T0Array)\n-- analyzeOrientationR2Z1T0 numOrientation thetaFreqs theta0Freqs arr =\n--   let arrR2S1 = R.map magnitude . r2z1Tor2s1 numOrientation thetaFreqs $ arr\n--       deltaTheta = 2 * pi / fromIntegral numOrientation :: Double\n--       (Z :. _ :. cols :. rows) = extent arrR2S1\n--       orientationArr =\n--         fromListUnboxed (Z :. cols :. rows) .\n--         parMap\n--           rdeepseq\n--           (\\(i, j) ->\n--              deltaTheta *\n--              (fromIntegral .\n--               VU.maxIndex . toUnboxed . computeS . R.slice arrR2S1 $\n--               (Z :. All :. i :. j))) $\n--         [(i, j) | i <- [0 .. cols - 1], j <- [0 .. rows - 1]]\n--       freqArr = fromListUnboxed (Z :. (L.length thetaFreqs)) thetaFreqs\n--       freq0Arr = fromListUnboxed (Z :. (L.length theta0Freqs)) theta0Freqs\n--       magArr =\n--         R.map sqrt . sumS . R.map (\\x -> (magnitude x) ^ 2) . rotate3D $ arr\n--       func theta =\n--         computeS .\n--         R.traverse4\n--           orientationArr\n--           freqArr\n--           freq0Arr\n--           magArr\n--           (\\_ _ _ _ ->\n--              (Z :. (L.length thetaFreqs) :. (L.length theta0Freqs) :. cols :.\n--               rows)) $ \\fOri fFreq fFreq0 fMag (Z :. k :. l :. i :. j) ->\n--           (fMag (Z :. i :. j) :+ 0) *\n--           (exp $ 0 :+ (-1) * (fFreq (Z :. k) + fFreq0 (Z :. l)) * (fOri (Z :. i :. j) + theta))\n--    in (func (pi / 2),func 0)\n\n\n-- {-# INLINE normalizeList #-}\n-- normalizeList :: (Ord e, Fractional e) => [e] -> [e]\n-- normalizeList xs = L.map (/ L.maximum xs) xs\n\n-- plotMagnitudeOrientation ::\n--      (R.Source s (Complex Double))\n--   => FilePath\n--   -> Int\n--   -> [Double]\n--   -> R.Array s DIM3 (Complex Double)\n--   -> (Int, Int)\n--   -> IO (Int,Int)\n-- plotMagnitudeOrientation folderPath numOrientationSample thetaFreqs arr (i', j') = do\n--   let orientationSampleRad =\n--         [ 2 * pi / fromIntegral numOrientationSample * fromIntegral i\n--         | i <- [0 .. numOrientationSample - 1]\n--         ]\n--       orientationSampleDeg =\n--         [ 360 * fromIntegral i / fromIntegral numOrientationSample\n--         | i <- [0 .. numOrientationSample - 1]\n--         ]\n--       freqArr = fromListUnboxed (Z :. (L.length thetaFreqs)) thetaFreqs\n--       xsFreqDomain\n--         -- normalizeList $\n--        =\n--         parMap\n--           rdeepseq\n--           (\\theta ->\n--              magnitude .\n--              R.sumAllS .\n--              R.zipWith (\\freq x -> x * exp (0 :+ theta * freq)) freqArr .\n--              R.slice arr $\n--              (Z :. All :. i :. j))\n--           orientationSampleRad\n--       xs =\n--         normalizeList $\n--         R.toList .\n--         R.map magnitude .\n--         r2z1Tor2s1 numOrientationSample thetaFreqs .\n--         extend (Z :. All :. (1 :: Int) :. (1 :: Int)) . R.slice arr $\n--         (Z :. All :. i :. j)\n--       (Z :. _ :. cols :. rows) = extent arr\n--       magVec =\n--         VU.concat $\n--         parMap\n--           rdeepseq\n--           (\\theta ->\n--              toUnboxed .\n--              computeS .\n--              R.map magnitude . R.sumS . rotate3D . R.traverse2 arr freqArr const $ \\f1 f2 idx@(Z :. k :. _ :. _) ->\n--                f1 idx * exp (0 :+ theta * f2 (Z :. k)))\n--           orientationSampleRad\n--       (Z :. c :. a :. b) =\n--         fromIndex (Z :. (L.length thetaFreqs) :. cols :. rows) . VU.maxIndex $\n--         magVec\n--       maxMag = VU.maximum magVec\n--       (i,j) = (a,b)\n--   printf\n--     \"Max magnitude: %0.5f at (%d,%d) %f degree.\\n\"\n--     maxMag\n--     a\n--     b\n--     ((fromIntegral c :: Double) / (fromIntegral numOrientationSample) * 360)\n--   plotPathsStyle\n--     [ PNG (folderPath </> \"Magnitude.png\")\n--     , Title (\"Magnitude at \" L.++ show (i, j))\n--     ] $\n--     L.zip\n--         -- defaultStyle\n--       --     { plotType = LinesPoints\n--       --     , lineSpec = CustomStyle [LineTitle \"Spatial Domain\", PointType 1]\n--       --     }\n--       -- ,\n--       [ defaultStyle\n--           { plotType = Lines\n--           , lineSpec =\n--               CustomStyle\n--                 [ LineTitle \"Frequency Domain\" -- , PointType 0\n--                 ]\n--           }\n--       ]\n--        -- L.zip orientationSampleDeg xs,\n--       [L.zip orientationSampleDeg xsFreqDomain]\n--   return (a,b)\n\n\n-- plotMagnitudeOrientationSource ::\n--      (R.Source s (Complex Double))\n--   => DFTPlan\n--   -> FilePath\n--   -> Int\n--   -> Int\n--   -> [Double]\n--   -> R2Z1T0Array\n--   -> R.Array s DIM3 (Complex Double)\n--   -> (Int, Int)\n--   -> IO ()\n-- plotMagnitudeOrientationSource plan folderPath numOrientationSample numOrientation thetaFreqs filter input (i, j) = do\n--   let orientationSampleRad =\n--         [ 2 * pi / fromIntegral numOrientationSample * fromIntegral i\n--         | i <- [0 .. numOrientationSample - 1]\n--         ]\n--       orientationSampleDeg =\n--         [ 360 * fromIntegral i / fromIntegral numOrientationSample\n--         | i <- [0 .. numOrientationSample - 1]\n--         ]\n--       freqArr = fromListUnboxed (Z :. (L.length thetaFreqs)) thetaFreqs\n--       (Z :. numThetaFreq :. cols :. rows) = extent input\n--   xs <-\n--     MP.mapM\n--       (\\theta -> do\n--          initialDistF <-\n--            fmap (fromUnboxed (Z :. numThetaFreq :. cols :. rows) . VU.convert) .\n--            dftExecute plan (DFTPlanID DFT1DG [numThetaFreq, cols, rows] [1, 2]) .\n--            VU.convert . toUnboxed . computeS . R.traverse2 input freqArr const $\n--            (\\f1 f2 idx@(Z :. k :. i :. j) ->\n--               f1 idx * exp (0 :+ theta * (1) * f2 (Z :. k)))\n--          sourceArr <- convolveR2T0 plan filter initialDistF\n--          let sourceR2Z1 = R.sumS . rotateR2Z1T0Array $ sourceArr\n--              mag =\n--                magnitude .\n--                R.sumAllS .\n--                r2z1Tor2s1 numOrientation thetaFreqs .\n--                extend (Z :. All :. (1 :: Int) :. (1 :: Int)) .\n--                R.slice sourceR2Z1 $\n--                (Z :. All :. i :. j)\n--          return mag)\n--       orientationSampleRad\n--   plotPath\n--     [ PNG (folderPath </> \"SourceMagnitude.png\")\n--     , Title (\"Source Magnitude at \" L.++ show (i, j))\n--     ] .\n--     L.zip orientationSampleDeg . normalizeList $\n--     xs\n", "meta": {"hexsha": "cd8e482d85d2fceb266ff03a858a24d60aaab981", "size": 8381, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/STC/OrientationScaleAnalysis.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/STC/OrientationScaleAnalysis.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/STC/OrientationScaleAnalysis.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 38.0954545455, "max_line_length": 121, "alphanum_fraction": 0.4969574037, "num_tokens": 2497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48037615929182054}}
{"text": "#!/usr/bin/env stack\n-- stack --resolver lts-15.04 runghc --package reanimate\nmodule Main where\n\nimport           Codec.Picture.Types\nimport           Control.Lens\nimport           Control.Monad\nimport           Data.List\nimport           Data.Maybe\nimport qualified Data.Text                     as T\nimport           Data.Tuple\nimport qualified Data.Vector                   as V\nimport           Linear.V2\nimport           Linear.Vector\nimport qualified Numeric.LinearAlgebra         as Matrix\nimport           Numeric.LinearAlgebra.HMatrix (Matrix, linearSolve, toLists,\n                                                (><))\nimport           Reanimate\nimport           Reanimate.Math.Common         (barycentricCoords, isBetween,\n                                                rayIntersect)\n\ntype Points = V.Vector (V2 Double)\ntype Edges = [(Int, Int, Int)]\ndata Mesh = Mesh { meshPoints :: Points, meshEdges :: Edges }\ndata MeshPair = MeshPair Points Points Edges\n-- The points in a RelMesh are:\n--   relMeshStatic ++ x where Ax = B\ndata RelMesh = RelMesh\n  { relMeshStatic :: Points\n  , relMeshEdges  :: Edges\n  , relMeshA      :: Matrix Double\n  , relMeshB      :: Matrix Double\n  }\ndata RelMeshPair = RelMeshPair Points Edges (Matrix Double) (Matrix Double) (Matrix Double) (Matrix Double)\n-- Linear interpolation on RelMesh gives smooth morph.\n-- solveMesh :: RelMesh -> Mesh\n-- mkRelative :: Mesh -> RelMesh\n-- mkRelativePair :: MeshPair -> RelMeshPair\n-- triangulate :: Polygon -> Polygon -> MeshPair ?\n-- embed :: MeshPair -> MeshPair\n-- compatible :: Mesh -> Mesh -> Maybe MeshPair\n-- linearInterpolate :: MeshPair -> Double -> Mesh\n-- convexInterpolate :: RelMeshPair -> Double -> RelMesh\n\nmain :: IO ()\nmain = reanimate morphAnimation\n\nmorphAnimation :: Animation\nmorphAnimation = playThenReverseA $ pauseAround 1 1 $ addStatic (mkBackground \"black\") $\n  signalA (curveS 2) $ mkAnimation 5 $ \\t -> lowerTransformations $ scale 3 $ pathify $ center $\n  mkGroup\n  [ translate (-1) 0 $ drawTrig (linearInterpolate meshPair t)\n  , translate 1 0 $ drawTrig $ solveMesh $ convexInterpolate relPair t\n  ]\n  where\n    relPair = mkRelativePair meshPair\n    meshPair = fromJust $ compatible example1 example2\n\nmkLineP :: P -> P -> SVG\nmkLineP (V2 x1 y1) (V2 x2 y2) = mkLine (x1,y1) (x2,y2)\n\n-- FIXME: Check that the triangles are all anticlockwise.\n-- FIXME: Check that the edges connect all the points.\n-- FIXME: Check that the edgse leave no gaps.\ncompatible :: Mesh -> Mesh -> Maybe MeshPair\ncompatible a b =\n  if meshEdges a == meshEdges b && V.length (meshPoints a) == V.length (meshPoints b)\n    then Just $ MeshPair (meshPoints a) (meshPoints b) (meshEdges a)\n    else Nothing\n\nlinearInterpolate :: MeshPair -> Double -> Mesh\nlinearInterpolate (MeshPair aP bP edges) t = Mesh\n    { meshPoints = V.zipWith (lerp (1-t)) aP bP\n    , meshEdges = edges }\n\nexample1 :: Mesh\nexample1 = Mesh points edges\n  where\n    points = V.fromList\n      [ V2 1 0\n      , V2 (-1/2) (sqrt 3 / 2)\n      , V2 (-1/2) (-sqrt 3 / 2)\n      , 3 * points V.! 0 ^/ 4\n      , 3 * points V.! 1 ^/ 4\n      , 3 * points V.! 2 ^/ 4\n      , points V.! 0 ^/ 2\n      , points V.! 1 ^/ 2\n      , points V.! 2 ^/ 2\n      ]\n    edges =\n      [ (1,5,4), (1,2,5), (2,6,5), (2,3,6), (3,4,6), (3,1,4)\n      , (4,8,7), (4,5,8), (5,9,8), (5,6,9), (6,7,9), (6,4,7), (7,8,9)]\n\nexample2 :: Mesh\nexample2 = Mesh points edges\n  where\n    points = V.fromList\n      [ V2 1 0\n      , V2 (-1/2) (sqrt 3 / 2)\n      , V2 (-1/2) (-sqrt 3 / 2)\n      , 3 * points V.! 2 ^/ 4\n      , 3 * points V.! 0 ^/ 4\n      , 3 * points V.! 1 ^/ 4\n      , points V.! 1  ^/ 2\n      , points V.! 2 ^/ 2\n      , points V.! 0 ^/ 2\n      ]\n    edges = meshEdges example1\n\ndrawTrig (Mesh points gs) = withStrokeColor \"grey\" $ withFillColor \"white\" $\n  withStrokeWidth (defaultStrokeWidth/2) $ mkGroup\n  [ mkGroup\n    [ mkGroup\n      [ mkLine (ax, ay) (bx, by)\n      , mkLine (bx, by) (cx, cy)\n      , mkLine (cx, cy) (ax, ay)\n      ]\n    | (a, b, c) <- gs\n    , let V2 ax ay = points V.! (a-1)\n          V2 bx by = points V.! (b-1)\n          V2 cx cy = points V.! (c-1)\n    ]\n  , mkGroup $ concat\n    [ [ colored v $ translate ax ay $ mkCircle circleRadius\n      , withStrokeWidth 0 $\n        withStrokeColor \"white\" $ withFillColor \"black\" $ mkGroup\n        [ translate ax ay $ ppNum v ]\n      ]\n    | v <- nub $ concat [ [a,b,c] | (a,b,c) <- gs]\n    , let V2 ax ay = points V.! (v-1)\n    ]]\n  where\n    colored n =\n      let c = promotePixel $ turbo (fromIntegral n / fromIntegral (length gs-1))\n      in withStrokeColorPixel c . withFillColorPixel c\n    ppNum n = cachedNumbers !! n\n     --scaleToHeight (circR*1.5) $ center $ latex $ T.pack $ \"\\\\texttt{\" ++ show n ++ \"}\"\n\ncachedNumbers =\n  [ scaleToHeight (circleRadius*1.5) $ center $ latex $ T.pack $ \"\\\\texttt{\" ++ show n ++ \"}\"\n  | n <- [0 .. ] ]\n\ncircleRadius :: Double\ncircleRadius = 0.05\n\n-- Anticlockwise. No duplicate vertices. length >= 3\ntype Polygon = [V2 Double]\ntype P = V2 Double\n\n-- T = (U, G)\n-- G = [Polygon]\n-- U = nub $ concat G\n\nfindStarNeighbours :: Eq a => [(a,a,a)] -> a -> [(a, a)]\nfindStarNeighbours allTrig self =\n  [ (b,c)\n  | (a,b,c) <- allTrig\n  , self == a\n  ] ++\n  [ (c,a)\n  | (a,b,c) <- allTrig\n  , self == b\n  ] ++\n  [ (a,b)\n  | (a,b,c) <- allTrig\n  , self == c\n  ]\n\nisInterior :: Eq a => [(a, a)] -> Bool\nisInterior = isJust . getExteriorPoly\n\ngetExteriorPoly :: Eq a => [(a, a)] -> Maybe [a]\ngetExteriorPoly [] = Nothing\ngetExteriorPoly ((a,b):rest) = worker [a] a b rest\n  where\n    worker acc start this [] = do\n      guard (start == this)\n      return (reverse acc)\n    worker acc start this xs =\n      case lookup this xs of\n        Just next -> worker (this:acc) start next (delete (this,next) xs)\n        Nothing   ->\n          case lookup this (map swap xs) of\n            Just next -> worker (this:acc) start next (delete (next, this) xs)\n            Nothing   -> Nothing\n\nconvexInterpolate :: RelMeshPair -> Double -> RelMesh\nconvexInterpolate (RelMeshPair static edges leftM leftB rightM rightB) t =\n  RelMesh\n  { relMeshStatic = static\n  , relMeshEdges  = edges\n  , relMeshA      = Matrix.scale (1-t) leftM +\n                    Matrix.scale t rightM\n  , relMeshB      = Matrix.scale (1-t) leftB +\n                    Matrix.scale t rightB\n  }\n\nsolveMesh :: RelMesh -> Mesh\nsolveMesh (RelMesh static edges m b) =\n  case linearSolve m b of\n    Nothing -> error \"Failed to solve mesh\"\n    Just ret ->\n      Mesh (static <> V.fromList (worker (toLists ret))) edges\n  where\n    worker []             = []\n    worker ([x]:[y]:rest) = V2 x y : worker rest\n    worker _              = error \"invalid result\"\n\nmkRelative :: Mesh -> RelMesh\nmkRelative (Mesh points edges) = RelMesh (V.fromList exteriorPoints) edges mM bM\n  where\n    mM = (s><s) (concat m)\n    bM = (s><1) b\n    (s,exterior, (m, b)) = toParameters points edges\n    exteriorPoints =\n      [ points V.! (i-1)\n      | i <- exterior\n      ]\n\nmkRelativePair :: MeshPair -> RelMeshPair\nmkRelativePair (MeshPair p1 p2 edges) =\n  let RelMesh static _ leftM leftB = mkRelative (Mesh p1 edges)\n      RelMesh _ _ rightM rightB = mkRelative (Mesh p2 edges)\n  in RelMeshPair static edges leftM leftB rightM rightB\n\ntoParameters points groups = (length interior*2,exterior,unzip $ concat\n  [ let lst = [(if i == j then -1 else t)\n              | j <- interior\n              , let t = fromMaybe 0 $ lookup (i,j) lam_ij_cache\n              ]\n        pos = negate $ sum\n           [ pj ^* t\n           | j <- exterior\n           , let t = fromMaybe 0 $ lookup (i,j) lam_ij_cache\n                 pj = points V.! (j-1)\n           ]\n    in [ (dupX lst, pos ^. _x)\n       , (dupY lst, pos ^. _y)]\n  | i <- interior ])\n  where\n    lam_ij_cache = lam_ij points groups\n    dupX []     = []\n    dupX (x:xs) = x:0:dupX xs\n    dupY []     = []\n    dupY (x:xs) = 0:x:dupY xs\n    (interior, exterior) =\n      partition (isInterior . findStarNeighbours groups) [1 .. length points]\n\nlam_ij points groups =\n  [ ((i, j), t)\n  | i <- [1..V.length points]\n  , (j, t) <- lam_j points groups i\n  ]\nlam_j points groups p =\n  [ (nP, sum [ t | (j,k,t) <- mu, j == nP ] / fromIntegral (length nPoints))\n  | let n = findStarNeighbours groups p\n        nPoints = fromMaybe [] $ getExteriorPoly n\n        mu = calcMu points groups p\n  , nP <- nPoints ]\ncalcMu points groups p = concat\n    [ [ (nP, nP, t1)\n      , (a, nP, t2)\n      , (b, nP, t3) ]\n      -- (nP, a, b)\n    | {-p <- [1..length points]-}\n      let selfVert = points V.! (p-1)\n          n = findStarNeighbours groups p\n          nPoints :: [Int]\n          nPoints = fromMaybe [] $ getExteriorPoly n\n    , (i, nP) <- zip [1 .. ] nPoints\n    , let vert = points V.! (nP-1)\n    , let line = (vert, selfVert)\n    , let (a,b,aP,bP) = head $\n            [ (a,b,aP,bP)\n            | (a,b) <- n\n            , let aP = points V.! (a-1)\n                  bP = points V.! (b-1)\n                  segment = (points V.! (a-1), points V.! (b-1))\n            , case rayIntersect line segment of\n                Nothing -> False\n                Just u  -> isBetween u segment\n            , a /= nP\n            , b /= nP ]\n    -- , b == (nPoints ++ nPoints) !! i\n    , let (t1,t2,t3) = barycentricCoords vert aP bP selfVert\n    ]\n", "meta": {"hexsha": "ef4cf2dfbaca93cedb907eca96b8e5e3ab0429f0", "size": 9227, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "videos/morph/morph.hs", "max_stars_repo_name": "TristanCacqueray/reanimate", "max_stars_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "videos/morph/morph.hs", "max_issues_repo_name": "TristanCacqueray/reanimate", "max_issues_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "videos/morph/morph.hs", "max_forks_repo_name": "TristanCacqueray/reanimate", "max_forks_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.149825784, "max_line_length": 107, "alphanum_fraction": 0.5648639861, "num_tokens": 2892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4800496793361257}}
{"text": "{-# LANGUAGE DeriveGeneric             #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE FlexibleInstances         #-}\n{-# LANGUAGE InstanceSigs              #-}\n{-# LANGUAGE LambdaCase                #-}\n{-# LANGUAGE MultiParamTypeClasses     #-}\n{-# LANGUAGE PolyKinds                 #-}\n{-# LANGUAGE StandaloneDeriving        #-}\n{-# LANGUAGE TypeFamilies              #-}\n{-# LANGUAGE TypeInType                #-}\n\nmodule Learn.Neural.Layer.FullyConnected (\n    FullyConnected\n  ) where\n\nimport           Data.Kind\nimport           Data.Singletons.Prelude\nimport           Data.Singletons.TypeLits\nimport           GHC.Generics                   (Generic)\nimport           GHC.Generics.Numeric\nimport           Learn.Neural.Layer\nimport           Numeric.BLAS\nimport           Numeric.Backprop\nimport           Statistics.Distribution\nimport           Statistics.Distribution.Normal\nimport qualified Generics.SOP                   as SOP\n\ndata FullyConnected :: Type\n\ninstance (Num (b '[o,i]), Num (b '[o])) => Num (CParam FullyConnected b '[i] '[o]) where\n    FCP w1 b1 + FCP w2 b2 = FCP (w1 + w2) (b1 + b2)\n    FCP w1 b1 - FCP w2 b2 = FCP (w1 - w2) (b1 - b2)\n    FCP w1 b1 * FCP w2 b2 = FCP (w1 * w2) (b1 * b2)\n    negate (FCP w b) = FCP (negate w) (negate b)\n    signum (FCP w b) = FCP (signum w) (signum b)\n    abs    (FCP w b) = FCP (abs    w) (abs    b)\n    fromInteger x = FCP (fromInteger x) (fromInteger x)\n\ninstance (Fractional (b '[o,i]), Fractional (b '[o])) => Fractional (CParam FullyConnected b '[i] '[o]) where\n    FCP w1 b1 / FCP w2 b2 = FCP (w1 / w2) (b1 / b2)\n    recip (FCP w b)       = FCP (recip w) (recip b)\n    fromRational x        = FCP (fromRational x) (fromRational x)\n\ninstance (Floating (b '[o,i]), Floating (b '[o])) => Floating (CParam FullyConnected b '[i] '[o]) where\n    sqrt (FCP w b)       = FCP (sqrt w) (sqrt b)\n\ninstance Num (CState FullyConnected b '[i] '[o]) where\n    _ + _         = FCS\n    _ * _         = FCS\n    _ - _         = FCS\n    negate _      = FCS\n    abs    _      = FCS\n    signum _      = FCS\n    fromInteger _ = FCS\n\ninstance Fractional (CState FullyConnected b '[i] '[o]) where\n    _ / _          = FCS\n    recip _        = FCS\n    fromRational _ = FCS\n\ninstance Floating (CState FullyConnected b '[i] '[o]) where\n    sqrt _ = FCS\n\n\n\n\n\nderiving instance Generic (CParam FullyConnected b '[i] '[o])\ninstance SOP.Generic (CParam FullyConnected b '[i] '[o])\n\ninstance (BLAS b, KnownNat i, KnownNat o, Floating (b '[o,i]), Floating (b '[o]))\n        => Component FullyConnected b '[i] '[o] where\n    data CParam  FullyConnected b '[i] '[o] =\n            FCP { _fcWeights :: !(b '[o,i])\n                , _fcBiases  :: !(b '[o])\n                }\n    data CState  FullyConnected b '[i] '[o] = FCS\n    type CConstr FullyConnected b '[i] '[o] = Num (b '[o,i])\n    data CConf   FullyConnected b '[i] '[o] = forall d. ContGen d => FCC d\n\n    componentOp = componentOpDefault\n\n    initParam = \\case\n      i `SCons` SNil -> \\case\n        so@(o `SCons` SNil) -> \\(FCC d) g -> do\n          w <- genA (o `SCons` (i `SCons` SNil)) $ \\_ ->\n            realToFrac <$> genContVar d g\n          b <- genA so $ \\_ ->\n            realToFrac <$> genContVar d g\n          return $ FCP w b\n        _ -> error \"inaccessible.\"\n      _ -> error \"inaccessible.\"\n\n    initState _ _ _ _ = return FCS\n\n    defConf = FCC (normalDistr 0 0.01)\n\ninstance (BLAS b, KnownNat i, KnownNat o, Floating (b '[o,i]), Floating (b '[o]))\n        => ComponentFF FullyConnected b '[i] '[o] where\n    componentOpFF = bpOp . withInps $ \\(x :< p :< \u00d8) -> do\n        w :< b :< \u00d8 <- gTuple #<~ p\n        y <- matVecOp ~$ (w :< x :< \u00d8)\n        z <- (+.)     ~$ (y :< b :< \u00d8)\n        return . only $ z\n\ninstance (BLAS b, KnownNat i, KnownNat o, Floating (b '[o,i]), Floating (b '[o]))\n        => ComponentLayer r FullyConnected b '[i] '[o] where\n    componentRunMode = RMIsFF\n", "meta": {"hexsha": "cffcfc66d22eef5f7b29410326c75dd705553706", "size": 3898, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "old/src/Learn/Neural/Layer/FullyConnected.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "old/src/Learn/Neural/Layer/FullyConnected.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "old/src/Learn/Neural/Layer/FullyConnected.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 35.7614678899, "max_line_length": 109, "alphanum_fraction": 0.5454079015, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.47998126760628196}}
{"text": "module KalmanAxioms\nwhere\n\nimport Numeric.LinearAlgebra\nimport Unsafe.Coerce\n\ntype Float_t = Double\ntype SDM = Matrix Float_t\ntype SSM = Matrix Float_t\n\nfloat_zero :: Float_t\nfloat_zero = 0\n\nfloat_one :: Float_t\nfloat_one = 1\n\nfloat_opp :: Float_t -> Float_t\nfloat_opp = negate\n\nfloat_plus :: Float_t -> Float_t -> Float_t\nfloat_plus = (+)\n\nfloat_minus :: Float_t -> Float_t -> Float_t\nfloat_minus = (-)\n\nfloat_times :: Float_t -> Float_t -> Float_t\nfloat_times = (*)\n\nfloat_div :: Float_t -> Float_t -> Float_t\nfloat_div = (/)\n\nfloat_inv :: Float_t -> Float_t\nfloat_inv = (1 /)\n\nfloat_eq_dec :: Float_t -> Float_t -> Bool\nfloat_eq_dec = (==)\n\nfloat_lt :: a -> a' -> Bool\nfloat_lt x y = (unsafeCoerce x :: Float_t) < (unsafeCoerce y :: Float_t)\n\ncholesky_DC :: a -> Int -> sdm -> sdm'\ncholesky_DC _ _ a = unsafeCoerce (chol (trustSym (unsafeCoerce a :: SDM)))\n\ndense_sparse_mul_to_sparse :: a -> Int -> sdm -> ssm -> ssm'\ndense_sparse_mul_to_sparse _ _ a b = unsafeCoerce ((unsafeCoerce a :: SDM) <> (unsafeCoerce b :: SSM))\n\nsparse_dense_mul :: a -> Int -> ssm -> sdm -> sdm'\nsparse_dense_mul _ _ a b = unsafeCoerce ((unsafeCoerce a :: SSM) <> (unsafeCoerce b :: SDM))\n\ndense_sparse_mul :: a -> Int -> sdm -> ssm -> sdm'\ndense_sparse_mul _ _ a b = unsafeCoerce ((unsafeCoerce a :: SDM) <> (unsafeCoerce b :: SSM))\n\nsolveR_upper :: a -> Int -> sdm -> sdm -> sdm'\nsolveR_upper _ _ a b = unsafeCoerce ((unsafeCoerce a :: SDM) <\\> (unsafeCoerce b :: SDM))\n\nsolveR_lower :: a -> Int -> sdm -> sdm -> sdm'\nsolveR_lower _ _ a b = unsafeCoerce ((unsafeCoerce a :: SDM) <\\> (unsafeCoerce b :: SDM))\n\ndense_get :: a -> Int -> Int -> sdm -> Int -> Int -> Float_t\ndense_get _ _ _ m i j = (unsafeCoerce m :: SDM) `atIndex` (i, j)\n\ndense_mul :: a -> Int -> Int -> Int -> sdm -> sdm' -> sdm''\ndense_mul _ _ _ _ a b = unsafeCoerce ((unsafeCoerce a :: SDM) <> (unsafeCoerce b :: SDM))\n\ndense_fill :: a -> Int -> Int -> (Int -> Int -> Float_t) -> sdm\ndense_fill _ m n f = unsafeCoerce (fromLists [ [f i j | j <- [0..n - 1]] | i <- [0..m-1]] :: SDM)\n\ndense_elementwise_op :: a -> Int -> Int -> (Float_t -> Float_t -> Float_t) -> SDM -> SDM -> SDM\ndense_elementwise_op me m n f a b = dense_fill me m n (\\i j -> f (a `atIndex` (i, j)) (b `atIndex` (i, j)))\n\nsparse_get :: a -> Int -> Int -> SSM -> Int -> Int -> Float_t\nsparse_get _ _ _ m i j = m `atIndex` (i, j)\n\nsparse_mul :: a -> Int -> Int -> Int -> SSM -> SSM -> SSM\nsparse_mul _ _ _ _ a b = a <> b\n\nsparse_fill :: a ->  Int -> Int -> (Int -> Int -> Float_t) -> SSM\nsparse_fill _ m n f = fromLists [ [f i j | j <- [0..n - 1]] | i <- [0..m-1]]\n\nsparse_elementwise_op :: a -> Int -> Int -> (Float_t -> Float_t -> Float_t) -> SSM -> SSM -> SSM\nsparse_elementwise_op me m n f a b = sparse_fill me m n (\\i j -> f (a `atIndex` (i, j)) (b `atIndex` (i, j)))\n", "meta": {"hexsha": "3a48b904f85ea8aa1f33ff5256be9f340a02b84b", "size": 2787, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/KalmanAxioms.hs", "max_stars_repo_name": "mit-plv/Fiat_matrix", "max_stars_repo_head_hexsha": "cc68414a55b90212d855587bffc59cecaf999e58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-14T12:57:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-14T12:57:00.000Z", "max_issues_repo_path": "haskell/KalmanAxioms.hs", "max_issues_repo_name": "mit-plv/Fiat_matrix", "max_issues_repo_head_hexsha": "cc68414a55b90212d855587bffc59cecaf999e58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "haskell/KalmanAxioms.hs", "max_forks_repo_name": "mit-plv/Fiat_matrix", "max_forks_repo_head_hexsha": "cc68414a55b90212d855587bffc59cecaf999e58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-30T05:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T05:10:39.000Z", "avg_line_length": 33.987804878, "max_line_length": 109, "alphanum_fraction": 0.619303911, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4799812531137396}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module    : Statistics.Distribution.Gamma\n-- Copyright : (c) 2009, 2011 Bryan O'Sullivan\n-- License   : BSD3\n--\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : portable\n--\n-- The gamma distribution.  This is a continuous probability\n-- distribution with two parameters, /k/ and &#977;. If /k/ is\n-- integral, the distribution represents the sum of /k/ independent\n-- exponentially distributed random variables, each of which has a\n-- mean of &#977;.\n\nmodule Statistics.Distribution.Gamma\n    (\n      GammaDistribution\n    -- * Constructors\n    , gammaDistr\n    , gammaDistrE\n    , improperGammaDistr\n    , improperGammaDistrE\n    -- * Accessors\n    , gdShape\n    , gdScale\n    ) where\n\nimport Control.Applicative\nimport Data.Aeson           (FromJSON(..), ToJSON, Value(..), (.:))\nimport Data.Binary          (Binary(..))\nimport Data.Data            (Data, Typeable)\nimport GHC.Generics         (Generic)\nimport Numeric.MathFunctions.Constants (m_pos_inf, m_NaN, m_neg_inf)\nimport Numeric.SpecFunctions (incompleteGamma, invIncompleteGamma, logGamma, digamma)\nimport qualified System.Random.MWC.Distributions as MWC\n\nimport Statistics.Distribution.Poisson.Internal as Poisson\nimport qualified Statistics.Distribution as D\nimport Statistics.Internal\n\n\n-- | The gamma distribution.\ndata GammaDistribution = GD {\n      gdShape :: {-# UNPACK #-} !Double -- ^ Shape parameter, /k/.\n    , gdScale :: {-# UNPACK #-} !Double -- ^ Scale parameter, &#977;.\n    } deriving (Eq, Typeable, Data, Generic)\n\ninstance Show GammaDistribution where\n  showsPrec i (GD k theta) = defaultShow2 \"improperGammaDistr\" k theta i\ninstance Read GammaDistribution where\n  readPrec = defaultReadPrecM2 \"improperGammaDistr\" improperGammaDistrE\n\n\ninstance ToJSON GammaDistribution\ninstance FromJSON GammaDistribution where\n  parseJSON (Object v) = do\n    k     <- v .: \"gdShape\"\n    theta <- v .: \"gdScale\"\n    maybe (fail $ errMsgI k theta) return $ improperGammaDistrE k theta\n  parseJSON _ = empty\n\ninstance Binary GammaDistribution where\n  put (GD x y) = put x >> put y\n  get = do\n    k     <- get\n    theta <- get\n    maybe (fail $ errMsgI k theta) return $ improperGammaDistrE k theta\n\n\n-- | Create gamma distribution. Both shape and scale parameters must\n-- be positive.\ngammaDistr :: Double            -- ^ Shape parameter. /k/\n           -> Double            -- ^ Scale parameter, &#977;.\n           -> GammaDistribution\ngammaDistr k theta\n  = maybe (error $ errMsg k theta) id $ gammaDistrE k theta\n\nerrMsg :: Double -> Double -> String\nerrMsg k theta\n  =  \"Statistics.Distribution.Gamma.gammaDistr: \"\n  ++ \"k=\" ++ show k\n  ++ \"theta=\" ++ show theta\n  ++ \" but must be positive\"\n\n-- | Create gamma distribution. Both shape and scale parameters must\n-- be positive.\ngammaDistrE :: Double            -- ^ Shape parameter. /k/\n            -> Double            -- ^ Scale parameter, &#977;.\n            -> Maybe GammaDistribution\ngammaDistrE k theta\n  | k > 0 && theta > 0 = Just (GD k theta)\n  | otherwise          = Nothing\n\n\n-- | Create gamma distribution. Both shape and scale parameters must\n-- be non-negative.\nimproperGammaDistr :: Double            -- ^ Shape parameter. /k/\n                   -> Double            -- ^ Scale parameter, &#977;.\n                   -> GammaDistribution\nimproperGammaDistr k theta\n  = maybe (error $ errMsgI k theta) id $ improperGammaDistrE k theta\n\nerrMsgI :: Double -> Double -> String\nerrMsgI k theta\n  =  \"Statistics.Distribution.Gamma.gammaDistr: \"\n  ++ \"k=\" ++ show k\n  ++ \"theta=\" ++ show theta\n  ++ \" but must be non-negative\"\n\n-- | Create gamma distribution. Both shape and scale parameters must\n-- be non-negative.\nimproperGammaDistrE :: Double            -- ^ Shape parameter. /k/\n                    -> Double            -- ^ Scale parameter, &#977;.\n                    -> Maybe GammaDistribution\nimproperGammaDistrE k theta\n  | k >= 0 && theta >= 0 = Just (GD k theta)\n  | otherwise            = Nothing\n\ninstance D.Distribution GammaDistribution where\n    cumulative = cumulative\n\ninstance D.ContDistr GammaDistribution where\n    density    = density\n    logDensity (GD k theta) x\n      | x <= 0    = m_neg_inf\n      | otherwise = log x * (k - 1) - (x / theta) - logGamma k - log theta * k\n    quantile   = quantile\n\ninstance D.Variance GammaDistribution where\n    variance (GD a l) = a * l * l\n\ninstance D.Mean GammaDistribution where\n    mean (GD a l) = a * l\n\ninstance D.MaybeMean GammaDistribution where\n    maybeMean = Just . D.mean\n\ninstance D.MaybeVariance GammaDistribution where\n    maybeStdDev   = Just . D.stdDev\n    maybeVariance = Just . D.variance\n\ninstance D.MaybeEntropy GammaDistribution where\n  maybeEntropy (GD a l)\n    | a > 0 && l > 0 =\n      Just $\n      a\n      + log l\n      + logGamma a\n      + (1-a) * digamma a\n    | otherwise = Nothing\n\ninstance D.ContGen GammaDistribution where\n    genContVar (GD a l) = MWC.gamma a l\n\n\ndensity :: GammaDistribution -> Double -> Double\ndensity (GD a l) x\n  | a < 0 || l <= 0   = m_NaN\n  | x <= 0            = 0\n  | a == 0            = if x == 0 then m_pos_inf else 0\n  | x == 0            = if a < 1 then m_pos_inf else if a > 1 then 0 else 1/l\n  | a < 1             = Poisson.probability (x/l) a * a / x\n  | otherwise         = Poisson.probability (x/l) (a-1) / l\n\ncumulative :: GammaDistribution -> Double -> Double\ncumulative (GD k l) x\n  | x <= 0    = 0\n  | otherwise = incompleteGamma k (x/l)\n\nquantile :: GammaDistribution -> Double -> Double\nquantile (GD k l) p\n  | p == 0         = 0\n  | p == 1         = 1/0\n  | p > 0 && p < 1 = l * invIncompleteGamma k p\n  | otherwise      =\n    error $ \"Statistics.Distribution.Gamma.quantile: p must be in [0,1] range. Got: \"++show p\n", "meta": {"hexsha": "4c41b8b168a16a934cc059b63bf015904abe7555", "size": 5802, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Gamma.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-11T23:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T22:33:10.000Z", "max_issues_repo_path": "Statistics/Distribution/Gamma.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-02-26T06:10:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:27:01.000Z", "max_forks_repo_path": "Statistics/Distribution/Gamma.hs", "max_forks_repo_name": "infinity0/statistics", "max_forks_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-12-14T09:59:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T23:04:37.000Z", "avg_line_length": 32.2333333333, "max_line_length": 93, "alphanum_fraction": 0.6363322992, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.479965472839903}}
{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections       #-}\n{-# LANGUAGE TypeFamilies        #-}\n{-# LANGUAGE TypeOperators       #-}\nimport           Control.Monad\nimport           Control.Monad.Random\nimport           Data.List                    (foldl')\n\nimport qualified Data.ByteString              as B\nimport           Data.Semigroup               ((<>))\nimport           Data.Serialize\n\nimport           GHC.TypeLits\n\nimport qualified Numeric.LinearAlgebra.Static as SA\n\nimport           Options.Applicative\n\nimport           Grenade\n\n-- The definition for our simple feed forward network.\n-- The type level lists represents the layers and the shapes passed through the layers.\n-- One can see that for this demonstration we are using relu, tanh and logit non-linear\n-- units, which can be easily substitute for each other in and out.\n--\n-- With around 100000 examples, this should show two clear circles which have been learned by the network.\ntype FFNet = Network '[ FullyConnected 2 40, Tanh, FullyConnected 40 30, Relu, FullyConnected 30 20, Relu, FullyConnected 20 10, Relu, FullyConnected 10 1, Logit ]\n                     '[ 'D1 2, 'D1 40, 'D1 40, 'D1 30, 'D1 30, 'D1 20, 'D1 20, 'D1 10, 'D1 10, 'D1 1, 'D1 1]\n\nrandomNet :: IO FFNet\nrandomNet = randomNetworkInitWith HeEtAl  -- you might want to try `Xavier` or `UniformInit` instead of `HeEtAl`\n\n\nnetTrain :: FFNet -> LearningParameters -> Int -> IO FFNet\nnetTrain net0 rate n = do\n    inps <- replicateM n $ do\n      s  <- getRandom\n      return $ S1D $ SA.randomVector s SA.Uniform * 2 - 1\n    let outs = flip map inps $ \\(S1D v) ->\n                 if v `inCircle` (fromRational 0.50, 0.50)  || v `inCircle` (fromRational (-0.50), 0.50)\n                   then S1D $ fromRational 1\n                   else S1D $ fromRational 0\n\n    let trained = foldl' trainEach net0 (zip inps outs)\n    return trained\n\n  where trainEach !network (i,o) = train rate network i o\n\nnetLoad :: FilePath -> IO FFNet\nnetLoad modelPath = do\n  modelData <- B.readFile modelPath\n  either fail return $ runGet (get :: Get FFNet) modelData\n\nrenderClass :: IO ()\nrenderClass = do\n  let testIns = [ [ (x,y)  | x <- [0..50] ]\n                           | y <- [0..20] ]\n  let outMat  = fmap (fmap (\\(x,y) -> (render (x/25-1) (y/10-1)))) testIns\n  putStrLn $ unlines outMat\n\n  where\n    render x y  | x == 0 && y == 0 = '+'\n                | y == 0 = '-'\n                | x == 0 = '|'\n                | otherwise = let v = SA.vector [x,y] :: SA.R 2\n                              in if v `inCircle` (fromRational 0.50, 0.50)  || v `inCircle` (fromRational (-0.50), 0.50)\n                                 then '1'\n                                 else ' '\n\n\nnetScore :: FFNet -> IO ()\nnetScore network = do\n    let testIns = [ [ (x,y)  | x <- [0..50] ]\n                             | y <- [0..20] ]\n        outMat  = fmap (fmap (\\(x,y) -> (render (x/25-1) (y/10-1) . normx) $ runNet network (S1D $ SA.vector [x / 25 - 1,y / 10 - 1]))) testIns\n    putStrLn $ unlines outMat\n\n  where\n    render x y n'  | x == 0 && y == 0 = '+'\n                   | y == 0 = '-'\n                   | x == 0 = '|'\n                   | n' <= 0.2  = ' '\n                   | n' <= 0.4  = '.'\n                   | n' <= 0.6  = '-'\n                   | n' <= 0.8  = '='\n                   | otherwise = '#'\n\nnormx :: S ('D1 1) -> Double\nnormx (S1D r) = SA.mean r\n\ntestValues :: FFNet -> IO ()\ntestValues network = do\n  inps <- replicateM 1000 $ do\n      s  <- getRandom\n      return $ S1D $ SA.randomVector s SA.Uniform * 2 - 1\n  let outs = flip map inps $ \\(S1D v) ->\n                 if v `inCircle` (fromRational 0.50, 0.50)  || v `inCircle` (fromRational (-0.50), 0.50)\n                   then 1 :: Integer\n                   else 0\n  let ress = zip outs (map (round . normx . runNet network) inps)\n      correct = length $ filter id $ map (uncurry (==)) ress\n      incorrect = length $ filter id $ map (uncurry (/=)) ress\n      falsePositives = length $ filter id $ map (uncurry (\\shd nn -> shd == 0 && nn == 1)) ress\n      falseNegatives = length $ filter id $ map (uncurry (\\shd nn -> shd == 1 && nn == 0)) ress\n  putStr $ show correct  ++ \" | \"\n  putStr $ show incorrect ++ \" | \"\n  putStr $ show falsePositives ++ \" | \"\n  putStrLn $ show falseNegatives ++ \" | \"\n\n\ninCircle :: KnownNat n => SA.R n -> (SA.R n, Double) -> Bool\nv `inCircle` (o, r) = SA.norm_2 (v - o) <= r\n\n\ndata FeedForwardOpts = FeedForwardOpts Int LearningParameters\n\nfeedForward' :: Parser FeedForwardOpts\nfeedForward' =\n  FeedForwardOpts <$> option auto (long \"examples\" <> short 'e' <> value 1000)\n                  <*> (LearningParameters\n                      <$> option auto (long \"train_rate\" <> short 'r' <> value 0.005)\n                      <*> option auto (long \"momentum\" <> value 0.0)\n                      <*> option auto (long \"l2\" <> value 0.0005)\n                      )\n\n\nmain :: IO ()\nmain = do\n  FeedForwardOpts examples rate <- execParser (info (feedForward' <**> helper) idm)\n\n  putStrLn \"| Nr | Correct | Incorrect | FalsePositives | FalseNegatives |\"\n  putStrLn \"--------------------------------------------------------------\"\n  let nr = 100 :: Int\n  mapM_ (\\n -> do\n    putStr $ \"| \" ++ show n  ++ \" | \"\n    net0 <- randomNet\n    net <- netTrain net0 rate examples\n    -- netScore net\n    testValues net) [1..nr]\n", "meta": {"hexsha": "a3b2bffd765b7daf564adb86a60144536f177521", "size": 5415, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/feedforwardweightinit.hs", "max_stars_repo_name": "koenigmaximilian/grenade", "max_stars_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/main/feedforwardweightinit.hs", "max_issues_repo_name": "koenigmaximilian/grenade", "max_issues_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/main/feedforwardweightinit.hs", "max_forks_repo_name": "koenigmaximilian/grenade", "max_forks_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1338028169, "max_line_length": 163, "alphanum_fraction": 0.5325946445, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4797165771147451}}
{"text": "import qualified Statistics.Distribution.Normal as Stats\nimport qualified Amby as Am\n\nmain :: IO ()\nmain = do\n  z <- Am.random Stats.standard 10000\n  Am.save $ Am.rugPlot' z\n", "meta": {"hexsha": "23d2f355d30fd22d6ea4994484b4b5e92ae77fec", "size": 174, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/Bench.hs", "max_stars_repo_name": "jsermeno/amby", "max_stars_repo_head_hexsha": "3c73501c75926eca8f3f7cc4274bc7751fc49788", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-10-25T06:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T21:09:10.000Z", "max_issues_repo_path": "bench/Bench.hs", "max_issues_repo_name": "jsermeno/amby", "max_issues_repo_head_hexsha": "3c73501c75926eca8f3f7cc4274bc7751fc49788", "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": "bench/Bench.hs", "max_forks_repo_name": "jsermeno/amby", "max_forks_repo_head_hexsha": "3c73501c75926eca8f3f7cc4274bc7751fc49788", "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": 21.75, "max_line_length": 56, "alphanum_fraction": 0.7356321839, "num_tokens": 46, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.4792970424243505}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeOperators #-}\n---------------------------------\n-- |\n-- Module      :  HMM\n-- Copyright   :  (C) Kaushik Chakraborty, 2019\n-- License     :  Apache v2 (see the file LICENSE)\n-- Maintainer  :  Kaushik Chakraborty <git@kaushikc.org>\n-- Stability   :  experimental\n--\n---------------------------------\n\nmodule HMM\n  (\n    HMM(..),\n    -- ** Smart Constructors\n    mkHMM_, mkHMM, mkHMM1, sensorDiagonal,\n    -- * Utility Functions\n    normalise, inverse, reverseV, extract1, (!**!), unitColumn,\n    -- ** Converting to/from HMatrix matrices\n    toHM, fromHM,\n    -- * Inference Algorithms\n    -- ** Forward-Backward\n    forward, backward, forwardBackward,\n    -- ** Fixed Lag Smoothing\n    fixedLagSmoothing,\n    -- * Sample HMM Models\n    umbrellaHMM,\n    -- * Miscellaneous\n    -- ** Type Synonyms\n    R, TransitionModel, SensorDiagonal, SensorModel, Message, Distribution,\n    -- ** Data Types\n    Persistent(..),\n    -- ** Test Functions\n    runFLSAlgo, runFBAlgo,\n    -- ** Lenses\n    prior, tModel, sDist, sModel\n) where\n\nimport Text.Printf (printf)\n\nimport Papa\nimport GHC.TypeNats\nimport Data.Proxy (Proxy(..))\n\nimport Control.Monad.State (State, runState)\nimport Control.Monad.Trans.Maybe (MaybeT, runMaybeT)\n\nimport qualified Data.Vector as Vec\n\nimport Linear.V\nimport Linear\n\nimport qualified Numeric.LinearAlgebra.Static as HM\nimport qualified Numeric.LinearAlgebra as HMat\n-----------------------------------------------------------------------------------\n\ntype R = Double\ntype TransitionModel (s :: Nat) a = V s (V s a)\ntype SensorDiagonal (s  :: Nat) a = V s (V s a)\ntype SensorModel (t :: Nat) (s :: Nat) a = V t (SensorDiagonal s a)\ntype Message (s :: Nat) a = V s (V 1 a)\ntype Distribution (s :: Nat) a = V s a\n\n-- | Hidden Markov Models\ndata HMM (s :: Nat) (t :: Nat)  a b = HMM {\n  -- | prior distribution which is used as initial forward message\n  _prior :: Message s a,\n  -- | transition model with @s@ states as @sxs@ matrix \n  _tModel :: TransitionModel s a,\n  -- | evidence value vector, each index maps to the corresponding evidence values\n  _sDist :: V t b,\n  -- | sensor model with @t@ evidence values having @sxs@ diagonal matrix capturing their ditributions for each state @s@\n  _sModel :: SensorModel t s a\n  } deriving (Show)\n\nmakeLenses ''HMM\n\nmkHMM_ :: (KnownNat s, KnownNat t) => Maybe (Message s R) -- ^ Prior distribution on the initial state, @P(X0)@. If nothing then considered @(0.5,0.5)@\n       -> TransitionModel s R -- ^ Transition Model as @sxs@ matrix, @s@ being the number of states\n       -> V t b -- ^ evidence values vector map\n       -> V t (V s R) -- ^ a @txs@ matrix for each evidence value @t@, a vector capturing conditional probabilities for each state @s@\n       -> HMM s t R b\nmkHMM_ mp xs evs = let p = fromMaybe (V $ Vec.replicate (dim xs) 0.5) mp\n              in\n              HMM p xs evs . (scaled <$>)\n\n-- | A default HMM where both transition model states and evidence variables have boolean support\nmkHMM :: KnownNat s => TransitionModel s R -> V 2 (V s R) -> HMM s 2 R Bool\nmkHMM ts = mkHMM_ Nothing ts (V $ Vec.fromList [True, False])\n\n-- | A default HMM with one state variable having boolean support\nmkHMM1 :: V2 (V2 R) -> V2 (V2 R) -> HMM 2 2 R Bool\nmkHMM1 ts ss = let f = (_V #) . over mapped toV\n               in\n                 uncurry mkHMM $ over both f (ts , ss)\n\n-- | create a @sxs@ diagonal matrix with corresponding posterior probabilities from the sensor model of the @HMM@ for an input sensor value\nsensorDiagonal :: (KnownNat s, KnownNat t, Eq b)\n               => HMM s t a b\n               -> b -- ^ sensor value\n               -> Maybe (SensorDiagonal s a)\nsensorDiagonal hmm e = findIndexOf (sDist.folded) (== e) hmm >>= (\\i -> hmm ^? sModel . ix i)\n\n\n\n-- | Multiply each number by a constant such that the sum is 1.0\nnormalise :: (Fractional a, Foldable f, Functor f) => f a -> f a\nnormalise xs | null xs = xs\n             | otherwise =\n                 let\n                   s = sum xs\n                 in\n                   (/ s) <$> xs\n\n-- | inverse a square matrix\ninverse :: forall s. (KnownNat s) => V s (V s R) -> V s (V s R)\ninverse  = fromHM . HM.inv . toHM\n\n-- | reverse contents of a 'Linear.V' vector\nreverseV :: forall s a. (KnownNat s) => V s a -> V s a\nreverseV = V . Vec.fromList . Papa.reverse . toList\n\nextract1 :: (KnownNat s) => V s (V 1 a) -> V s a\nextract1 =  V . foldMap toVector\n\n-- | Pointwise product of 2 @mxn@ 'V' vectors\ninfix 8 !**!\n(!**!) :: (KnownNat m, KnownNat n) => V m (V n R) -> V m (V n R) -> V m (V n R)\nas !**! bs = fromHM $ toHM as * toHM bs\n\n-- | an unit vector having @s@ columns\nunitColumn :: forall s. KnownNat s => Message s R\nunitColumn = V $ Vec.replicate (fromIntegral $ natVal (Proxy :: Proxy s))  (toV $ V1 1.0)\n\n-- | take a @sxt@ 'Linear.V.V' matrix and give corresponding 'Numeric.LinearAlgebra.Static.L' version\ntoHM :: (KnownNat s, KnownNat t) => V s (V t R) -> HM.L s t\ntoHM = HM.matrix . foldMap (Vec.toList . toVector)\n\n-- | take a @sxt@ 'Numeric.LinearAlgebra.Static.L' matrix and give corresponding 'Linear.V.V' version\nfromHM :: (KnownNat s, KnownNat t) => HM.L s t -> V s (V t R)\nfromHM m = V $ V <$> Vec.fromList (fmap Vec.fromList $ HMat.toLists $ HM.extract m)\n\n-- | Filtering message propagated forward\nforward :: (KnownNat s) => HMM s t R b -> SensorDiagonal s R  -> Message s R -> Message s R\nforward hmm ot f = normalise (ot !*! Linear.transpose (hmm ^. tModel) !*! f)\n\n-- | Smoothing message propagated backward\nbackward :: (KnownNat s) => HMM s t R b -> SensorDiagonal s R -> Message s R -> Message s R\nbackward hmm ok1 bk2 = (hmm ^. tModel) !*! ok1 !*! bk2\n\n-- | The forward\u2013backward algorithm for smoothing: computing posterior prob- abilities of a sequence of states given a sequence of observations\nforwardBackward :: forall s t u b . (KnownNat t, KnownNat s, KnownNat u, Eq b)\n                => HMM s u R b -- ^ HMM model as a way to implement\n                -> V t b -- ^ list of evidences for each time step\n                -> V t (Distribution s R)\nforwardBackward hmm evs = let\n  -- reifying the number of evidences\n  tNat = dim evs\n  -- forward messages from time t .. 0\n  fv :: V (t + 1) (Message s R)\n  fv = V $ Vec.fromList $ foldl' (\\m@(x:_) e -> forward hmm (sensorDiagonal hmm e ^?! _Just) x : m) [hmm ^. prior] evs\n  -- getting rid of the prior message from the end of the list\n  -- so now forward messages vector is from time t .. 1\n  fv_0 :: V t (Message s R)\n  fv_0 = V $ Vec.fromList $ fv ^.. taking tNat traversed\n\n  --  backward messages from time 1 .. t\n  bs :: V t (Message s R)\n  bs = V $ Vec.fromList $ foldl' (\\m@(x:_) e -> backward hmm (sensorDiagonal hmm e ^?! _Just) x : m) [unitColumn] $ reverseV evs\n  -- reversing the backward messages\n  -- so now the backward messages vector is from time t .. 1\n  revBs :: V t (Message s R)\n  revBs = reverseV bs\n  in\n    -- smoothing probabilities in reverse order of the list of evidences\n    -- i.e. starting from time t .. 1\n    liftA2 (\\f b' -> extract1 $ normalise $ f !**! b') fv_0 revBs\n\n\n-- | Persistent State\ndata Persistent (s :: Nat) a b d= Persistent {\n  _t :: d, -- ^ current time\n  _f_msg :: Message s a, -- ^ the forward message @P(Xt|e1:t)@\n  _b :: V s (V s a), -- ^ the @d@-step backward transformation matrix\n  _e_td_t :: Vec.Vector b -- ^ double-ended list of evidence from @t \u2212 d@ to @t@\n  } deriving (Show)\n\nmakeLenses ''Persistent\n\n-- | Initial persistent state where\n--\n--  * t = 1\n--\n--  * f_msg  = hmm.prior\n--\n--  * b = identity matrix\n--\n--  * e_td_t = empty vector\npersistentInit :: forall s b d. (KnownNat s, Integral d) => Message s R -> Persistent s R b d\npersistentInit p = Persistent { _t = 1, _f_msg = p, _b = identity, _e_td_t = Vec.empty}\n\n-- | Online Algorithm for smoothing with a fixed time lag of @d@ steps\nfixedLagSmoothing :: forall s u b d. (KnownNat s, KnownNat u, Eq b, Integral d)\n                  => HMM s u R b -- ^ HMM model\n                  -> d -- ^ length of lag\n                  -> b -- ^ evidence at time @t@\n                  -> MaybeT (State (Persistent s R b d)) (Distribution s R)\nfixedLagSmoothing hmm d e = do\n  e_td_t %= flip Vec.snoc e\n\n  o_t <- uses e_td_t $ (^?! _Just) . sensorDiagonal hmm . Vec.last\n\n  t' <- use t\n  if t' > d then\n    do\n      e_td_t %= Vec.drop 1\n      o_tmd <- uses e_td_t $ (^?! _Just) . sensorDiagonal hmm . Vec.head\n      f_msg %= forward hmm o_tmd\n      b %= \\b' -> inverse o_tmd !*! inverse (hmm ^. tModel) !*! b' !*! (hmm ^. tModel) !*! o_t\n      t += 1\n\n      (f'', b'') <- liftA2 (,) (use f_msg) (use b)\n\n      return $ extract1 $ normalise (f'' !**! (b'' !*! unitColumn))\n  else\n    do\n      b %= \\b' -> b' !*! (hmm ^. tModel) !*! o_t\n      t += 1\n      mzero\n\n\numbrellaHMM :: HMM 2 2 R Bool\numbrellaHMM = mkHMM1 (V2 (V2 0.7 0.3) (V2 0.3 0.7)) (V2 (V2 0.9 0.2) (V2 0.1 0.8))\n\n\nrunFLSAlgo  :: [Bool] -> Integer -> [Maybe (Distribution 2 String)]\nrunFLSAlgo bs d = let hmm = mkHMM1 (V2 (V2 0.7 0.3) (V2 0.3 0.7)) (V2 (V2 0.9 0.2) (V2 0.1 0.8))\n                      initState = persistentInit (V $ Vec.fromList [V $ Vec.singleton 0.5, V $ Vec.singleton 0.5]) :: Persistent 2 R Bool Integer\n                      algo = fixedLagSmoothing hmm d\n                      a :: ([Maybe (Distribution 2 R)], Persistent 2 R Bool Integer)\n                      a = foldl' (\\(rs, s) x -> runState (runMaybeT $ algo x) s & _1 #%~ ((rs ++) . pure)) ([], initState) bs\n                  in\n                    (a ^. _1) & traverse.traverse.traverse %~ \\(x :: R) -> printf \"%.3f\" x :: String\n\n\nrunFBAlgo :: [Bool] -> [Distribution 2 R]\nrunFBAlgo bs = reifyVectorNat (Vec.fromList bs) (toList . forwardBackward umbrellaHMM)\n", "meta": {"hexsha": "6ace400cdc65e722b7490a010528a75761a3f14a", "size": 9780, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/hmm.hs", "max_stars_repo_name": "kaychaks/hmm", "max_stars_repo_head_hexsha": "18784d87383620c53827d3b24a7606f3167d5b6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hmm.hs", "max_issues_repo_name": "kaychaks/hmm", "max_issues_repo_head_hexsha": "18784d87383620c53827d3b24a7606f3167d5b6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hmm.hs", "max_forks_repo_name": "kaychaks/hmm", "max_forks_repo_head_hexsha": "18784d87383620c53827d3b24a7606f3167d5b6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8095238095, "max_line_length": 151, "alphanum_fraction": 0.6011247444, "num_tokens": 3021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4792970424243505}}
{"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ExplicitNamespaces #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ParallelListComp #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# OPTIONS_GHC -fno-warn-name-shadowing #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Presburger #-}\n\n{- | Algorithms for zero-dimensional ideals.\n\n   Since 0.4.0.0\n-}\nmodule Algebra.Algorithms.ZeroDim\n  ( -- * Root finding for zero-dimensional ideal\n    solveM,\n    solve',\n    solveViaCompanion,\n    solveLinear,\n\n    -- * Radical computation\n    radical,\n    isRadical,\n\n    -- * Converting monomial ordering to Lex using FGLM algorithm\n    fglm,\n    fglmMap,\n\n    -- ** Internal helper function\n    solveWith,\n    univPoly,\n    reduction,\n    matrixRep,\n    subspMatrix,\n    vectorRep,\n  )\nwhere\n\nimport Algebra.Algorithms.FGLM\nimport Algebra.Algorithms.Groebner\nimport Algebra.Instances ()\nimport Algebra.Internal hiding (OLt)\nimport qualified Algebra.Matrix as AM\nimport Algebra.Prelude.Core\nimport Algebra.Ring.Polynomial.Quotient\nimport Control.Lens\nimport Control.Monad.Loops (whileM_)\nimport Control.Monad.Random hiding (next)\nimport Control.Monad.Reader (runReaderT)\nimport Control.Monad.ST (runST)\nimport Data.Complex (Complex (..), magnitude)\nimport Data.Convertible (Convertible, convert)\nimport qualified Data.Matrix as M\nimport Data.Maybe (fromJust)\nimport Data.Reflection (Reifies)\nimport Data.STRef.Strict (newSTRef)\nimport qualified Data.Sized as SV\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Mutable as MV\nimport qualified Numeric.Algebra as NA\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Prelude as P\n\n{- | Finds complex approximate  roots of given zero-dimensional ideal,\n   using randomized altorithm.\n\n   See also @'solve''@ and @'solveViaCompanion'@.\n-}\nsolveM ::\n  forall m r ord n.\n  ( Normed r\n  , Ord r\n  , MonadRandom m\n  , Field r\n  , CoeffRing r\n  , KnownNat n\n  , IsMonomialOrder n ord\n  , Convertible r Double\n  , 0 < n\n  ) =>\n  Ideal (OrderedPolynomial r ord n) ->\n  m [Sized n (Complex Double)]\nsolveM ideal =\n  {-# SCC \"solveM\" #-}\n  withKnownNat (sSucc (sNat :: SNat n)) $\n    reifyQuotient (radical ideal) $ \\pxy ->\n      case standardMonomials' pxy of\n        Just bs -> step 10 (length bs)\n        Nothing -> error \"Given ideal is not zero-dimensional\"\n  where\n    step bd len =\n      {-# SCC \"solveM/step\" #-}\n      do\n        coeffs <-\n          {-# SCC \"solveM/coeff-gen\" #-}\n          replicateM (sNatToInt (sSucc (sNat :: SNat n))) $ getRandomR (- bd, bd)\n        let vars = one : SV.toList allVars\n            f = sum $ zipWith (.*.) (map (NA.fromInteger :: Integer -> r) coeffs) vars\n        case solveWith f ideal of\n          Nothing -> step (bd * 2) len\n          Just sols -> return sols\n\n{- | @solveWith f is@ finds complex approximate roots of the given zero-dimensional @n@-variate polynomial system @is@,\n   using the given relatively prime polynomial @f@.\n-}\nsolveWith ::\n  forall r n ord.\n  ( DecidableZero r\n  , Normed r\n  , Ord r\n  , Field r\n  , CoeffRing r\n  , 0 < n\n  , IsMonomialOrder n ord\n  , KnownNat n\n  , Convertible r Double\n  ) =>\n  OrderedPolynomial r ord n ->\n  Ideal (OrderedPolynomial r ord n) ->\n  Maybe [Sized n (Complex Double)]\nsolveWith f0 i0 =\n  {-# SCC \"solveWith\" #-}\n  withKnownNat (sSucc (sNat :: SNat n)) $\n    reifyQuotient (radical i0) $ \\pxy ->\n      let ideal = gBasis' pxy\n          Just base = map (leadingMonomial . quotRepr) <$> standardMonomials' pxy\n       in case {-# SCC \"findOne\" #-} elemIndex one base of\n            Nothing -> Just []\n            Just cind ->\n              let f = modIdeal' pxy f0\n                  vars =\n                    sortBy (flip $ comparing snd) $\n                      map (\\on -> (on, leadingMonomial $ var on `asTypeOf` f0)) $\n                        enumOrdinal $ sArity' f0\n                  inds = flip map vars $\n                    second $ \\b ->\n                      case findIndex (== b) base of\n                        Just ind -> Right ind\n                        Nothing ->\n                          let Just g = find ((== b) . leadingMonomial) ideal\n                              r = leadingCoeff g\n                              answer = mapCoeff toComplex $ injectCoeff (recip r) * (toPolynomial (leadingTerm g) - g)\n                           in Left answer\n                  mf = AM.fromLists $ map (map toComplex) $ matrixRep f\n                  (_, evecs) = LA.eig $ LA.tr mf\n                  calc vec =\n                    {-# SCC \"calc\" #-}\n                    let c = vec LA.! cind\n                        phi (idx, Right nth) acc = acc & ix idx .~ (vec LA.! nth) P./ c\n                        phi (idx, Left g) acc = acc & ix idx .~ substWith (*) acc g\n                     in if c == 0\n                          then Nothing\n                          else Just $ foldr ({-# SCC \"rewrite-answer\" #-} phi) (SV.replicate (sArity' f0) (error \"indec!\")) inds\n               in sequence $ map calc $ LA.toColumns evecs\n\n{- | @'solve'' err is@ finds numeric approximate root of the\n   given zero-dimensional polynomial system @is@,\n   with error <@err@.\n\n   See also @'solveViaCompanion'@ and @'solveM'@.\n-}\nsolve' ::\n  forall r n ord.\n  ( Field r\n  , CoeffRing r\n  , KnownNat n\n  , 0 < n\n  , IsMonomialOrder n ord\n  , Convertible r Double\n  ) =>\n  Double ->\n  Ideal (OrderedPolynomial r ord n) ->\n  [Sized n (Complex Double)]\nsolve' err ideal =\n  reifyQuotient ideal $ \\ii ->\n    if gBasis' ii == [one]\n      then []\n      else\n        let vs =\n              map (nub . LA.toList . LA.eigenvalues . AM.fromLists . map (map toComplex) . matrixRep . modIdeal' ii) $\n                SV.toList allVars\n            mul p q = toComplex p * q\n         in [ xs\n            | xs0 <- sequence vs\n            , let xs = SV.unsafeFromList' xs0\n            , all ((< err) . magnitude . substWith mul xs) $ generators ideal\n            ]\n\n{- | Given a zero-dimensional ideal \\(I\\),\n   \\('subspMatrix' i I\\) computes a multiplication matrix\n   \\(m_{x_i} \\mathbin{\\upharpoonright} V_i \\) by \\(x_i\\)\n   restricted to the subspace \\(V_i = \\mathop{\\mathrm{span}}(\\left\\{\\ x_i^n \\ \\middle|\\ 1 \\leq n \\right\\})\\) of \\(k[\\mathbf{X}]\\).\n-}\nsubspMatrix ::\n  forall r n ord.\n  (Show r, Ord r, Field r, CoeffRing r, KnownNat n, IsMonomialOrder n ord) =>\n  Ordinal n ->\n  Ideal (OrderedPolynomial r ord n) ->\n  M.Matrix r\nsubspMatrix on ideal =\n  let poly = univPoly on ideal\n      v = var on :: OrderedPolynomial r ord n\n      dim = totalDegree' poly\n      cfs = [negate $ coeff (leadingMonomial $ pow v (j :: Natural)) poly | j <- [0 .. fromIntegral (dim - 1)]]\n      leftTops = M.fromLists [replicate (dim - 1) zero]\n      leftBots = fmap unwrapAlgebra (M.identity (dim - 1))\n      lfts =\n        leftTops\n          M.<-> leftBots\n      rights = M.colVector (V.fromList cfs)\n   in lfts M.<|> rights\n\n{- | @'solveViaCompanion' err is@ finds numeric approximate root of the\n   given zero-dimensional polynomial system @is@,\n   with error <@err@.\n\n   See also @'solve''@ and @'solveM'@.\n-}\nsolveViaCompanion ::\n  forall r ord n.\n  (Show r, Ord r, Field r, CoeffRing r, KnownNat n, IsMonomialOrder n ord, Convertible r Double) =>\n  Double ->\n  Ideal (OrderedPolynomial r ord n) ->\n  [Sized n (Complex Double)]\nsolveViaCompanion err ideal =\n  if calcGroebnerBasis ideal == [one]\n    then []\n    else\n      let vs =\n            map (nub . LA.toList . LA.eigenvalues . LA.fromLists . matToLists . fmap toComplex . flip subspMatrix ideal) $\n              enumOrdinal (sNat :: SNat n)\n          mul p q = toComplex p * q\n       in [ xs\n          | xs0 <- sequence vs\n          , let xs = SV.unsafeFromList' xs0\n          , all ((< err) . magnitude . substWith mul xs) $ generators ideal\n          ]\n\nmatToLists :: M.Matrix a -> [[a]]\nmatToLists mat = [V.toList $ M.getRow i mat | i <- [1 .. M.nrows mat]]\n\nmatrixRep ::\n  ( DecidableZero t\n  , Eq t\n  , Field t\n  , KnownNat n\n  , IsMonomialOrder n order\n  , Reifies ideal (QIdeal (OrderedPolynomial t order n))\n  ) =>\n  Quotient (OrderedPolynomial t order n) ideal ->\n  [[t]]\nmatrixRep f =\n  {-# SCC \"matrixRep\" #-}\n  case standardMonomials of\n    Just [] -> []\n    Just bases ->\n      let anss = map (quotRepr . (f *)) bases\n       in transpose $ map (\\a -> map (flip coeff a . leadingMonomial . quotRepr) bases) anss\n    Nothing -> error \"Not finite dimension\"\n\ntoComplex :: Convertible a Double => a -> Complex Double\ntoComplex a = convert a :+ 0\n\n-- | Calculates n-th reduction of f: @f `div` < f, \u2202_{x_n} f >@.\nreduction ::\n  (CoeffRing r, KnownNat n, IsMonomialOrder n ord, Field r) =>\n  Ordinal n ->\n  OrderedPolynomial r ord n ->\n  OrderedPolynomial r ord n\nreduction on f =\n  {-# SCC \"reduction\" #-}\n  let df = {-# SCC \"differentiate\" #-} diff on f\n   in snd $ head $ f `divPolynomial` calcGroebnerBasis (toIdeal [f, df])\n\n-- | Calculate the monic generator of \\( k[X_0, ..., X_n] \\cap k[X_i]\\).\nunivPoly ::\n  forall r ord n.\n  (Ord r, Field r, CoeffRing r, KnownNat n, IsMonomialOrder n ord) =>\n  Ordinal n ->\n  Ideal (OrderedPolynomial r ord n) ->\n  OrderedPolynomial r ord n\nunivPoly nth ideal =\n  {-# SCC \"univPoly\" #-}\n  reifyQuotient ideal $ \\pxy ->\n    if gBasis' pxy == [one]\n      then one\n      else\n        let x = var nth\n            monomDeg =\n              fromIntegral $\n                length $\n                  fromJust $\n                    standardMonomials' pxy\n            p0 : pows =\n              [ fmap WrapAlgebra $ vectorRep $ modIdeal' pxy (pow x i)\n              | i <- [0 :: Natural .. monomDeg]\n              ]\n            step m ~(p : ps) =\n              {-# SCC \"univPoly/step\" #-}\n              case solveLinear m p of\n                Nothing -> {-# SCC \"recur\" #-} step ({-# SCC \"consCol\" #-} m M.<|> M.colVector p) ps\n                Just ans ->\n                  let cur = fromIntegral $ V.length ans :: Natural\n                   in {-# SCC \"buildRelation\" #-}\n                      pow x cur\n                        - sum\n                          ( zipWith\n                              (.*.)\n                              (fmap unwrapAlgebra $ V.toList ans)\n                              [pow x i | i <- [0 :: Natural .. cur P.- 1]]\n                          )\n         in step (M.colVector p0) pows\n\n-- | Solves linear system. If the given matrix is degenerate, this returns @Nothing@.\nsolveLinear ::\n  (Ord r, P.Fractional r) =>\n  M.Matrix r ->\n  V.Vector r ->\n  Maybe (V.Vector r)\nsolveLinear mat vec =\n  {-# SCC \"solveLinear\" #-}\n  if ({-# SCC \"uRank\" #-} uRank u) < uRank u' || M.diagProd u == 0 || uRank u < M.ncols mat\n    then Nothing\n    else\n      let ans = M.getCol 1 $ p P.* M.colVector vec\n          lsol = {-# SCC \"solveL\" #-} solveL ans\n          cfs = M.getCol 1 $ q P.* M.colVector ({-# SCC \"solveU\" #-} solveU lsol)\n       in Just cfs\n  where\n    Just (u, l, p, q, _, _) = M.luDecomp' mat\n    Just (u', _, _, _, _, _) = M.luDecomp' (mat M.<|> M.colVector vec)\n    uRank = V.foldr (\\a acc -> if a /= 0 then acc + 1 else acc) (0 :: Int) . M.getDiag\n    solveL v = V.create $ do\n      let stop = min (M.ncols l) (M.nrows l)\n      mv <- MV.replicate (M.ncols l) 0\n      forM_ [0 .. stop - 1] $ \\i -> do\n        MV.write mv i $ v V.! i\n        forM_ [0, 1 .. min (i -1) (M.ncols l - 1)] $ \\j -> do\n          a <- MV.read mv i\n          b <- MV.read mv j\n          MV.write mv i $ a P.- (l M.! (i + 1, j + 1)) P.* b\n      return mv\n    solveU v = V.create $ do\n      let stop = min (M.ncols u) (M.nrows u)\n      mv <- MV.replicate (M.ncols u) 0\n      forM_ [stop - 1, stop - 2 .. 0] $ \\i -> do\n        MV.write mv i $ v V.! i\n        forM_ [i + 1, i + 2 .. M.ncols u -1] $ \\j -> do\n          a <- MV.read mv i\n          b <- MV.read mv j\n          MV.write mv i $ a P.- (u M.! (i + 1, j + 1)) P.* b\n        a0 <- MV.read mv i\n        MV.write mv i $ a0 P./ (u M.! (i + 1, i + 1))\n      return mv\n\n-- | Calculate the radical of the given zero-dimensional ideal.\nradical ::\n  forall r ord n.\n  ( Ord r\n  , CoeffRing r\n  , KnownNat n\n  , Field r\n  , IsMonomialOrder n ord\n  ) =>\n  Ideal (OrderedPolynomial r ord n) ->\n  Ideal (OrderedPolynomial r ord n)\nradical ideal =\n  {-# SCC \"radical\" #-}\n  let gens = {-# SCC \"calcGens\" #-} map (\\on -> reduction on $ univPoly on ideal) $ enumOrdinal (sNat :: SNat n)\n   in toIdeal $ calcGroebnerBasis $ toIdeal $ generators ideal ++ gens\n\n-- | Test if the given zero-dimensional ideal is radical or not.\nisRadical ::\n  forall r ord n.\n  ( Ord r\n  , CoeffRing r\n  , KnownNat n\n  , 0 < n\n  , Field r\n  , IsMonomialOrder n ord\n  ) =>\n  Ideal (OrderedPolynomial r ord n) ->\n  Bool\nisRadical ideal =\n  let gens =\n        map (\\on -> reduction on $ univPoly on ideal) $\n          enumOrdinal (sNat :: SNat n)\n   in all (`isIdealMember` ideal) gens\n\n-- * FGLM\n\n{- | Calculate the Groebner basis w.r.t. lex ordering of the zero-dimensional ideal using FGLM algorithm.\n   If the given ideal is not zero-dimensional this function may diverge.\n-}\nfglm ::\n  ( Ord r\n  , KnownNat n\n  , Field r\n  , IsMonomialOrder n ord\n  , 0 < n\n  ) =>\n  Ideal (OrderedPolynomial r ord n) ->\n  ([OrderedPolynomial r Lex n], [OrderedPolynomial r Lex n])\nfglm ideal = reifyQuotient ideal $ \\pxy ->\n  fglmMap (vectorRep . modIdeal' pxy)\n\n-- | Compute the kernel and image of the given linear map using generalized FGLM algorithm.\nfglmMap ::\n  forall k ord n.\n  ( Ord k\n  , Field k\n  , 0 < n\n  , IsMonomialOrder n ord\n  , CoeffRing k\n  , KnownNat n\n  ) =>\n  -- | Linear map from polynomial ring.\n  (OrderedPolynomial k ord n -> V.Vector k) ->\n  -- | The tuple of:\n  --\n  --     * lex-Groebner basis of the kernel of the given linear map.\n  --\n  --     * The vector basis of the image of the linear map.\n  ( [OrderedPolynomial k Lex n]\n  , [OrderedPolynomial k Lex n]\n  )\nfglmMap l = runST $ do\n  env <- FGLMEnv l <$> newSTRef [] <*> newSTRef [] <*> newSTRef Nothing <*> newSTRef one\n  flip runReaderT env $ do\n    mainLoop\n    whileM_ toContinue $ nextMonomial >> mainLoop\n    (,) <$> look gLex <*> (map (changeOrder Lex) <$> look bLex)\n\nmainLoop ::\n  (DecidableZero r, Ord r, KnownNat n, Field r, IsMonomialOrder n o) =>\n  Machine s r o n ()\nmainLoop = do\n  m <- look monomial\n  let f = toPolynomial (one, changeMonomialOrderProxy Proxy m)\n  lx <- image f\n  bs <- mapM image =<< look bLex\n  let mat = foldr (M.<|>) (M.fromList 0 0 []) $ map (M.colVector . fmap WrapAlgebra) bs\n      cond\n        | null bs =\n          if V.all (== zero) lx\n            then Just $ V.replicate (length bs) 0\n            else Nothing\n        | otherwise = solveLinear mat (fmap WrapAlgebra lx)\n  case cond of\n    Nothing -> do\n      proced .== Nothing\n      bLex @== (f :)\n    Just cs -> do\n      bps <- look bLex\n      let g = changeOrder Lex $ f - sum (zipWith (.*.) (V.toList $ fmap unwrapAlgebra cs) bps)\n      proced .== Just (changeOrder Lex f)\n      gLex @== (g :)\n\ntoContinue ::\n  forall s r o n.\n  ( 0 < n\n  , Ord r\n  , KnownNat n\n  , Field r\n  ) =>\n  Machine s r o n Bool\ntoContinue = do\n  mans <- look proced\n  case mans of\n    Nothing -> return True\n    Just g -> do\n      let xLast = P.maximum allVars `asTypeOf` g\n      return $ not $ leadingMonomial g `isPowerOf` leadingMonomial xLast\n\nnextMonomial ::\n  forall s r ord n.\n  (CoeffRing r, KnownNat n) =>\n  Machine s r ord n ()\nnextMonomial = do\n  m <- look monomial\n  gs <- map leadingMonomial <$> look gLex\n  let next =\n        fst $\n          maximumBy\n            (comparing snd)\n            [ (OrderedMonomial monom, fromEnum od)\n            | od <- enumOrdinal (sNat :: SNat n)\n            , let monom = beta (getMonomial m) od\n            , all (not . (`divs` OrderedMonomial monom)) gs\n            ]\n  monomial .== next\n\nbeta :: KnownNat n => Monomial n -> Ordinal n -> Monomial n\nbeta xs o@(OLt k) =\n  let n = sizedLength xs\n   in (SV.take (sSucc k) $ xs & ix o +~ 1) SV.++ SV.replicate (n %- sSucc k) 0\nbeta _ _ = error \"beta: Bug in ghc!\"\n", "meta": {"hexsha": "84193012229cb87d67060a3abd9a365b93233a3a", "size": 16230, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "halg-algorithms/src/Algebra/Algorithms/ZeroDim.hs", "max_stars_repo_name": "hangingman/computational-algebra", "max_stars_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2015-02-09T01:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T04:37:09.000Z", "max_issues_repo_path": "halg-algorithms/src/Algebra/Algorithms/ZeroDim.hs", "max_issues_repo_name": "hangingman/computational-algebra", "max_issues_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-09-18T16:31:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T08:28:37.000Z", "max_forks_repo_path": "halg-algorithms/src/Algebra/Algorithms/ZeroDim.hs", "max_forks_repo_name": "hangingman/computational-algebra", "max_forks_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-12-22T16:04:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T19:35:53.000Z", "avg_line_length": 31.8860510806, "max_line_length": 130, "alphanum_fraction": 0.5748613678, "num_tokens": 4763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47926225589233296}}
{"text": "{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DeriveAnyClass        #-}\n{-# LANGUAGE DeriveGeneric         #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-|\nModule      : Grenade.Core.Softmax\nDescription : Softmax loss layer\nCopyright   : (c) Huw Campbell, 2016-2017\nLicense     : BSD2\nStability   : experimental\n-}\nmodule Grenade.Layers.Softmax (\n    Softmax (..)\n  , softmax\n  , softmax'\n  ) where\n\nimport           Data.Serialize\n\nimport           Control.DeepSeq              (NFData (..))\nimport           GHC.Generics                 (Generic)\nimport           GHC.TypeLits\nimport           Grenade.Core\n\nimport           Numeric.LinearAlgebra.Static as LAS\n\n-- | A Softmax layer\n--\n--   This layer is like a logit layer, but normalises\n--   a set of matricies to be probabilities.\n--\n--   One can use this layer as the last layer in a network\n--   if they need normalised probabilities.\ndata Softmax = Softmax\n  deriving (Show, Generic, NFData)\n\ninstance UpdateLayer Softmax where\n  type Gradient Softmax = ()\n  runUpdate _ _ _ = Softmax\n\ninstance RandomLayer Softmax where\n  createRandomWith _ _ = return Softmax\n\ninstance ( KnownNat i ) => Layer Softmax ('D1 i) ('D1 i) where\n  type Tape Softmax ('D1 i) ('D1 i) = S ('D1 i)\n\n  runForwards _ (S1D y) = (S1D y, S1D (softmax y))\n  runBackwards _ (S1D y) (S1D dEdy) = ((), S1D (softmax' y dEdy))\n\ninstance Serialize Softmax where\n  put _ = return ()\n  get = return Softmax\n\nsoftmax :: KnownNat i => LAS.R i -> LAS.R i\nsoftmax xs =\n  let xs' = LAS.dvmap exp xs\n      s   = LAS.dot xs' 1\n  in  LAS.dvmap (/ s) xs'\n\nsoftmax' :: KnownNat i => LAS.R i -> LAS.R i -> LAS.R i\nsoftmax' x grad =\n  let yTy = outer sm sm\n      d   = diag sm\n      g   = d - yTy\n  in  g #> grad\n    where\n  sm = softmax x\n\n\n-------------------- GNum instances --------------------\n\n\ninstance GNum Softmax where\n  _ |* Softmax = Softmax\n  _ |+ Softmax = Softmax\n  gFromRational _ = Softmax\n\n", "meta": {"hexsha": "5704fbc603c8a396af158e190ab6012dbafb9baf", "size": 2037, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Softmax.hs", "max_stars_repo_name": "koenigmaximilian/grenade", "max_stars_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Grenade/Layers/Softmax.hs", "max_issues_repo_name": "koenigmaximilian/grenade", "max_issues_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Softmax.hs", "max_forks_repo_name": "koenigmaximilian/grenade", "max_forks_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1481481481, "max_line_length": 65, "alphanum_fraction": 0.6077565047, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4790624125147331}}
{"text": "-- |\n-- = Single-node reservoir\n--\n-- In this project, we exploit an established analogy between\n-- spatially extended and delay systems (refs. 1-3). That makes possible\n-- to employ DDEs as a reservoir substrate.\n--\n-- 1. Arecchi, F. T., et al. \u201cTwo-Dimensional Representation of\n--    a Delayed Dynamical System.\u201d Physical Review A, vol. 45, no. 7,\n--    Jan. 1992, doi:10.1103/physreva.45.r4225.\n-- 2. Appeltant, L., et al. \u201cInformation Processing Using a Single\n--    Dynamical Node as Complex System.\u201d Nature Communications, vol. 2,\n--    2011, p. 468., doi:10.1038/ncomms1476.\n-- 3. Virtual Chimera States for Delayed-Feedback Systems - Laurent Larger,\n--    Bogdan Penkovsky, Yuri Maistrenko. Physical Review Letters - 08 / 2013.\n\n{-# LANGUAGE BangPatterns #-}\nmodule RC.NTC.Reservoir\n  ( Reservoir (..)\n  , genReservoir\n  ) where\n\nimport           Numeric.LinearAlgebra\nimport qualified Data.Vector.Storable as V\nimport qualified Linear.V2 as V2\nimport qualified Numeric.DDE as DDE\nimport qualified Numeric.DDE.Model as DDEModel\n\nimport           RC.NTC.Types\nimport qualified RC.Helpers as H\n\n\n-- | Substrate-specific low-level reservoir implementation\ngenReservoir :: DDEModel.RC -> Reservoir\ngenReservoir par@DDEModel.RC {\n    DDEModel._filt = DDEModel.BandpassFiltering { DDEModel._tau = tau }\n  } = Reservoir _r\n  where\n    _r sample = H.unflatten' nodes responseX\n      where\n        oversampling = 1 :: Int  -- No oversampling\n        detuning = 1.0 :: Double  -- Delay detuning factor, 1 = no detuning\n        nodes = rows sample\n        delaySamples = round $ detuning * fromIntegral (oversampling * nodes)\n\n        -- Matrix to timetrace\n        trace1 = H.flatten' sample\n\n        -- Duplicate the last element (DDE.integHeun2_2D consumes one extra input)\n        trace = trace1 V.++ V.singleton (V.last trace1)\n\n        -- Empirically chosen integration time step:\n        -- twice faster than the system response time tau\n        hStep = tau / 2\n\n        (_, response) = DDE.integHeun2_2D [delaySamples] hStep (DDEModel.bandpassRhs par) (DDE.Input trace)\n        responseX = V.map (\\(V2.V2 x _) -> x) response\n\n", "meta": {"hexsha": "77f36a712d397400cb8d7c40d3b4b9c736c826aa", "size": 2132, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "rc/RC/NTC/Reservoir.hs", "max_stars_repo_name": "masterdezign/rc", "max_stars_repo_head_hexsha": "0a37c27aff70a096d010d2043ef6eab33dee2dc8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-02-24T22:31:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T11:44:32.000Z", "max_issues_repo_path": "rc/RC/NTC/Reservoir.hs", "max_issues_repo_name": "masterdezign/rc", "max_issues_repo_head_hexsha": "0a37c27aff70a096d010d2043ef6eab33dee2dc8", "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": "rc/RC/NTC/Reservoir.hs", "max_forks_repo_name": "masterdezign/rc", "max_forks_repo_head_hexsha": "0a37c27aff70a096d010d2043ef6eab33dee2dc8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-05-16T01:08:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-16T01:08:19.000Z", "avg_line_length": 36.1355932203, "max_line_length": 107, "alphanum_fraction": 0.685272045, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4790624067520887}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DeriveGeneric #-}\n\n-- HdpH implementaion of a Mandelbrot set creation\n--\n-- Based largely on code by Rob Stewart <R.Stewart@hw.ac.uk> who adapted it\n-- from the monad-par implementation.\n--\n-- Author: Blair Archbald\n-- Date: 2/3/2015\n-----------------------------------------------------------------------------\n\n\nmodule Main where\n\nimport Control.DeepSeq hiding (force)\nimport Control.Exception (evaluate)\nimport Control.Monad (when)\nimport Control.Parallel.HdpH\nimport Control.Parallel.HdpH.Strategies\nimport qualified Control.Monad.Par as MonadPar\nimport qualified Control.Monad.Par.Combinator as MonadPar.C\nimport qualified Control.Parallel.HdpH as HdpH (declareStatic)\nimport qualified Control.Parallel.HdpH.Strategies as Strategies (declareStatic)\n\nimport Data.Binary (Binary)\nimport Data.Complex\nimport Data.Functor ((<$>))\nimport Data.List (stripPrefix)\nimport Data.List.Split (splitOn)\nimport Data.Maybe (isJust,fromJust)\nimport Data.Monoid (mconcat)\nimport Data.Serialize\nimport Data.Typeable (Typeable)\nimport Data.Vector.Cereal () -- To get the generic deriving for cereal and vectors.\nimport qualified Data.Vector.Unboxed as V\n\nimport GHC.Generics (Generic)\n\nimport System.Clock\nimport System.Environment (getArgs)\nimport System.IO (stdout, stderr, hSetBuffering, BufferMode(..))\nimport System.Random (mkStdGen, setStdGen)\n\nimport Prelude\n\ntype MSTime = Double\n\ndata VecTree = Leaf (V.Vector Int)\n             | MkNode VecTree VecTree\n             deriving (Eq,Show,Generic,Typeable)\ninstance Serialize VecTree\ninstance NFData VecTree\ninstance ToClosure VecTree\n  where locToClosure = $(here)\n\ninstance ToClosure (Int, Int)\n  where locToClosure = $(here)\n\n----------------------------------------------------------------------------\n-- sequential mandel function\n\nmandel :: Int -> Complex Double -> Int\nmandel max_depth c = loop 0 0\n  where\n   loop i !z\n    | i == max_depth       = i\n    | magnitude z >= 2.0   = i\n    | otherwise            = loop (i+1) (z*z + c)\n\ncheckSum :: VecTree -> Int\ncheckSum (Leaf vec) = V.foldl (+) 0 vec\ncheckSum (MkNode v1 v2) = checkSum v1 + checkSum v2\n\n-----------------------------------------------\n-- Mandel using monad-par\n--  From: https://github.com/simonmar/monad-par/blob/master/examples/src/mandel.hs\n\nmonadparRunMandel :: Int -> Int -> Int -> Int -> MonadPar.Par VecTree\nmonadparRunMandel = monadparRunMandel' (-2) (-2) 2 2\n\n--This is where the skeleton comes from.\nmonadparRunMandel' :: Double -> Double -- (minX, MinY)\n                    -> Double -> Double -- (maxX, maxY)\n                    -> Int -> Int -- (winX, winY)\n                    -> Int -- Depth\n                    -> Int -- Threshold\n                    -> MonadPar.Par VecTree\nmonadparRunMandel' minX minY maxX maxY winX winY max_depth threshold =\n  MonadPar.C.parMapReduceRangeThresh threshold (MonadPar.C.InclusiveRange 0 (winY-1))\n     (\\y ->\n       do\n          let vec = V.generate winX (\\x -> mandelStep y x)\n          seq (vec V.! 0) $ return (Leaf vec))\n     (\\ a b -> return$ MkNode a b)\n     (Leaf V.empty)\n  where\n    mandelStep i j = mandel max_depth z\n        where z = ((fromIntegral j * r_scale) / fromIntegral winY + minY) :+\n                  ((fromIntegral i * c_scale) / fromIntegral winX + minX)\n    r_scale  =  maxY - minY  :: Double\n    c_scale =   maxX - minX  :: Double\n\n-----------------------------------------------\n-- Mandel using the generic HpdH D&C skeleton\n\nhdphDandCMandel :: Int -> Int -> Int -> Int -> Par VecTree\nhdphDandCMandel = hdphDandCMandel' (-2) (-2) 2 2\n\nhdphDandCMandel' :: Double -> Double -- (minX, MinY)\n                 -> Double -> Double -- (maxX, maxY)\n                 -> Int -> Int -- (winX, winY)\n                 -> Int -- Depth\n                 -> Int -- Threshold\n                 -> Par VecTree\nhdphDandCMandel' minX minY maxX maxY winX winY maxDepth threshold = do\n  res <- parDivideAndConquer\n          $(mkClosure [|dc_trivial threshold|])\n          $(mkClosure [|dc_decompose|])\n          $(mkClosure [|dc_combine|])\n          $(mkClosure [|dc_algorithm (minX, minY, maxX, maxY, winX, winY, maxDepth)|])\n          (toClosure (0,winY-1))\n  return $ unClosure res\n\ndc_trivial :: Int -> Thunk (Closure (Int, Int) -> Bool)\ndc_trivial threshold = Thunk $ \\bnds -> let (min,max) = unClosure bnds\n                                        in   max - min <= threshold\n\ndc_decompose :: Closure (Int, Int) -> [Closure (Int, Int)]\ndc_decompose bnds = let (min, max) = unClosure bnds\n                        mid = min + (max - min) `quot` 2\n                     in [toClosure (min, mid), toClosure (mid+1, max)]\n\n-- This could prove to be a bottleneck and reason to use Rob's Skeleton\n-- (TODO: compare performance between approaches)\ndc_combine :: Closure a -> [Closure VecTree] -> Closure VecTree\ndc_combine _ ts = toClosure $ foldl1 MkNode $ map unClosure ts\n\ndc_algorithm :: (Double, Double, -- (minX, minY)\n                 Double, Double, -- (maxX, maxY)\n                 Int, Int, -- (winX, winY)\n                 Int) -- maxDepth\n              -> Thunk (Closure (Int,Int) -> Par (Closure VecTree))\ndc_algorithm (minX, minY, maxX, maxY, winX, winY, maxDepth) = Thunk $ \\bnds ->\n  let (min,max) = unClosure bnds\n      v = foldl go V.empty [min..max]\n  in  do vec <- force v\n         return $ toClosure (Leaf vec)\n  where\n    go a y = a V.++ V.generate winX (\\x -> mandelStep y x)\n    mandelStep i j = mandel maxDepth (calcZ i j)\n    calcZ i j = ((fromIntegral j * r_scale) / fromIntegral winY + minY) :+\n                ((fromIntegral i * c_scale) / fromIntegral winX + minX)\n    r_scale =  maxY - minY  :: Double\n    c_scale =  maxX - minX  :: Double\n\n---------------------------------------------------------------------------\n-- Timed Version\nhdphDandCMandelTimed :: Int -> Int -> Int -> Int -> Par VecTree\nhdphDandCMandelTimed = hdphDandCMandelTimed' (-2) (-2) 2 2\n\nhdphDandCMandelTimed' :: Double -> Double -- (minX, MinY)\n                 -> Double -> Double -- (maxX, maxY)\n                 -> Int -> Int -- (winX, winY)\n                 -> Int -- Depth\n                 -> Int -- Threshold\n                 -> Par VecTree\nhdphDandCMandelTimed' minX minY maxX maxY winX winY maxDepth threshold = do\n  res <- parDivideAndConquer\n          $(mkClosure [|dc_trivial threshold|])\n          $(mkClosure [|dc_decompose|])\n          $(mkClosure [|dc_combine|])\n          $(mkClosure [|dc_algorithm_timed (minX, minY, maxX, maxY, winX, winY, maxDepth)|])\n          (toClosure (0,winY-1))\n  return $ unClosure res\n\ndc_algorithm_timed :: (Double, Double, -- (minX, minY)\n                       Double, Double, -- (maxX, maxY)\n                       Int, Int, -- (winX, winY)\n                       Int) -- maxDepth\n                   -> Thunk (Closure (Int,Int) -> Par (Closure VecTree))\ndc_algorithm_timed (minX, minY, maxX, maxY, winX, winY, maxDepth) = Thunk $ \\bnds ->\n  let (min,max) = unClosure bnds\n      v = foldl go V.empty [min..max]\n  in  do s <- io $ getTime Monotonic\n         vec <- force v\n         e <- io $ getTime Monotonic\n         io $ putStrLn $ show min ++ \",\" ++ show max ++ \":\" ++ show (timeDiffMSecs s e)\n         return $ toClosure (Leaf vec)\n  where\n    go a y = a V.++ V.generate winX (\\x -> mandelStep y x)\n    mandelStep i j = mandel maxDepth (calcZ i j)\n    calcZ i j = ((fromIntegral j * r_scale) / fromIntegral winY + minY) :+\n                ((fromIntegral i * c_scale) / fromIntegral winX + minX)\n    r_scale =  maxY - minY  :: Double\n    c_scale =  maxX - minX  :: Double\n-----------------------------------------------------------------------------\n-- initialisation, argument processing and 'main'\n\ntimeDiffMSecs :: TimeSpec -> TimeSpec -> MSTime\ntimeDiffMSecs (TimeSpec s1 n1) (TimeSpec s2 n2) = fromIntegral (t2 - t1)\n                                                          /\n                                                  fromIntegral (10 ^ 6)\n  where t1 = (fromIntegral s1 * 10 ^ 9) + fromIntegral n1\n        t2 = (fromIntegral s2 * 10 ^ 9) + fromIntegral n2\n\ntimeIOMs :: IO a -> IO (a, MSTime)\ntimeIOMs action = do s  <- getTime Monotonic\n                     x  <- action\n                     e  <- getTime Monotonic\n                     return (x, timeDiffMSecs s e)\n\n-----------------------------------------------------\n-- Static Closures\n\n$(return []) -- Bring the types into scope so that reify works.\ndeclareStatic :: StaticDecl\ndeclareStatic =\n  mconcat\n    [HdpH.declareStatic,         -- declare Static deserialisers\n     Strategies.declareStatic,   -- from imported modules\n     declare (staticToClosure :: StaticToClosure VecTree),\n     declare (staticToClosure :: StaticToClosure (Int,Int)),\n\n     declare $(static 'dc_trivial),\n     declare $(static 'dc_decompose),\n     declare $(static 'dc_combine),\n     declare $(static 'dc_algorithm),\n\n     declare $(static 'dc_algorithm_timed),\n\n     declare $(static 'mandel)]\n---------------------------------------------------------------------------\n\n-- parse (optional) arguments in this order:\n-- * version to run\n-- * X value for Mandel\n-- * Y value for Mandel\n-- * Depth value for Mandel\n-- * Threshold for Mandel\nparseArgs :: [String] -> (Int, Int, Int, Int, Int, Int)\nparseArgs []     = (defVers, defX, defY, defDepth,defThreshold,defExpected)\nparseArgs (s:ss) =\n  let go :: Int -> [String] -> (Int, Int, Int, Int,Int, Int)\n      go v []              = (v, defX, defY, defDepth,defThreshold,defExpected)\n      go v [s1]            = (v, defX, read s1,  defDepth,defThreshold,defExpected)\n      go v [s1,s2]         = (v, read s1,  read s2,  defDepth,defThreshold,defExpected)\n      go v [s1,s2,s3]      = (v, read s1,  read s2,  read s3, defThreshold,defExpected)\n      go v [s1,s2,s3,s4] = (v, read s1,  read s2,  read s3, read s4,defExpected)\n      go v (s1:s2:s3:s4:s5:_) = (v, read s1,  read s2,  read s3, read s4, read s5)\n  in case stripPrefix \"v\" s of\n       Just s' -> go (read s') ss\n       Nothing -> go defVers (s:ss)\n\n-- defaults from Simon Marlow from monad-par example\ndefVers, defX, defY, defDepth, defThreshold, defExpected :: Int\ndefVers      = 0\ndefX         = 1024\ndefY         = 1024\ndefDepth     = 256\ndefThreshold = 1\ndefExpected  = 0\n\nmain :: IO ()\nmain = do\n  hSetBuffering stdout LineBuffering\n  hSetBuffering stderr LineBuffering\n  register Main.declareStatic\n\n  hdphCfg    <- flip updateConf defaultRTSConf =<< getArgs\n  (conf, as) <- case hdphCfg of\n    Left err -> error $ \"Could not initialise HdpH config: \" ++ show err\n    Right a  -> return a\n\n  let (version, valX, valY, valDepth,valThreshold,expected) = parseArgs as\n  case version of\n      1 -> do (p, t) <- timeIOMs $ evaluate =<< return (MonadPar.runPar\n                (monadparRunMandel valX valY valDepth valThreshold))\n              printOutput (Just p,t)\n      2 -> do res <- timeIOMs $ evaluate =<< runParIO conf\n                                (hdphDandCMandel valX valY valDepth valThreshold)\n              printOutput res\n      3 -> do res <- timeIOMs $ evaluate =<< runParIO conf\n                                (hdphDandCMandelTimed valX valY valDepth valThreshold)\n              printOutput res\n      _ -> return ()\n\nprintOutput :: (Maybe VecTree, MSTime) -> IO ()\nprintOutput (p,t) = case p of\n                     Just pixels -> do\n                       putStrLn $ \"CHECKSUM: \" ++ show (checkSum pixels)\n                       putStrLn $ \"RUNTIME: \"  ++ show t ++ \"ms\"\n                     Nothing -> return ()\n", "meta": {"hexsha": "12a98fd90c57b05b5dd2e8d631ee87b6d0c228c4", "size": 11552, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "mandel.hs", "max_stars_repo_name": "BlairArchibald/HdpH-applications", "max_stars_repo_head_hexsha": "d3de9add36cec6c3ecd68e23a76988e5851c9e26", "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": "mandel.hs", "max_issues_repo_name": "BlairArchibald/HdpH-applications", "max_issues_repo_head_hexsha": "d3de9add36cec6c3ecd68e23a76988e5851c9e26", "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": "mandel.hs", "max_forks_repo_name": "BlairArchibald/HdpH-applications", "max_forks_repo_head_hexsha": "d3de9add36cec6c3ecd68e23a76988e5851c9e26", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8956228956, "max_line_length": 92, "alphanum_fraction": 0.5784279778, "num_tokens": 3131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4790551776856325}}
{"text": "{-# LANGUAGE ScopedTypeVariables, FlexibleContexts, BangPatterns #-}\nmodule Statistics.Sampler.Slice (\n  slice,\n  newSlicerState,\n  adaptOff,\n  SlicerState()\n) where\n\nimport           Random.CRI\nimport qualified Statistics.Distribution.Random.Exponential as D\nimport qualified Statistics.Distribution.Random.Uniform as D\nimport           Numeric.MathFunctions.Constants (m_epsilon)\nimport           Control.Monad (when)\n\nimport           Prelude hiding (max)\n\n-- | slice sampling as described in\n-- Radford M. Neal, \"Slice sampling\",\n-- Ann. Statist. Volume 31, Number 3 (2003), 705-767.\n-- http://projecteuclid.org/euclid.aos/1056562461\n\ndata SlicerState  = SlicerState {\n    lower    :: !Double,             -- ^ lower bound of distribution\n    upper    :: !Double,             -- ^ upper bound of distribution\n    width    :: !Double,             -- ^ width of step out size (approximate scale parameter)\n    steps    :: !Int,                -- ^ maximum number of step outs\n    adapt    :: !Bool,               -- ^ adapt phase underway\n    sumdiff  :: !Double,             -- ^ store sumdiff for adaption phase\n    iter     :: !Int                 -- ^ number of iterations\n    } deriving Show\n\nnewSlicerState :: Double    -- ^ lower bound\n               -> Double    -- ^ upper bound\n               -> Double    -- ^ initial width\n               -> SlicerState\nnewSlicerState l u w = SlicerState {\n                          lower   = l,\n                          upper   = u,\n                          width   = w,\n                          steps   = 10,\n                          adapt   = True,\n                          iter    = 1,\n                          sumdiff = 0.0\n                        }\n\nadaptOff :: SlicerState -> SlicerState\nadaptOff st = st { adapt = False }\n\nslice :: (Source m g Double) =>\n         SlicerState\n      -> (Double -> Double)       -- ^ x -> log(f x) where f is proportional to probibility density\n      -> Double                   -- ^ current value\n      -> g m                      -- ^ a random number generator\n      -> m (SlicerState, Double)  -- ^ return slicer state and new sample value\nslice st g x0 rng =\n  do\n    let !g0 = g x0\n\n    when (isInfinite g0) $\n        error $ \"Infinite value found in slice sampler: \" ++ show x0 ++ \" -> \" ++ show g0\n\n    when (isNaN g0) $\n        error $ \"NaN found in slice sampler: \" ++ show x0 ++ \" -> \" ++ show g0\n\n    -- 1. define slice\n    e <- D.exponential rng\n    let !z = g0 - e\n\n    -- 2. find interval\n    u <- D.uniform rng\n    let !l = x0 - width st * u\n        !r = l + width st\n\n    v :: Double <- D.uniform rng\n    let !j = floor (fromIntegral (steps st) * v)\n        !k = (steps st - 1) - j\n\n    let !left = calc_left j l\n        calc_left n l'\n            | l' < lower st  = lower st\n            | n == 0         = l'\n            | z >= g l'      = l'\n            | otherwise      = calc_left  (n-1) (l' - width st)\n\n    let !right = calc_right k r\n        calc_right n r'\n            | r' > upper st  = upper st\n            | n == 0         = r'\n            | z >= g r'      = r'\n            | otherwise      = calc_right (n-1) (r' + width st)\n\n    -- 3. loop until accept (guaranteed)\n    let sample left' right' =\n          do\n            u' <- D.uniform rng\n            let !x = left' + u' * (right' - left')\n            if z - m_epsilon <= g x\n              then return x -- accept\n              else\n                if x < x0\n                  then sample x     right'\n                  else sample left' x\n\n    !x1 <- sample left right\n\n    let !st' | adapt st  = adaptSlicer x0 x1 st\n             | otherwise = st\n\n    return (st', x1)\n\nadaptSlicer :: Double -> Double -> SlicerState -> SlicerState\nadaptSlicer old new oldst = newst\n  where\n    !iterf    = fromIntegral (iter oldst)\n    !sumdiff' = sumdiff oldst +  iterf * abs (new - old)\n    !newst    = oldst {\n                    sumdiff = sumdiff',\n                    iter    = iter oldst + 1,\n                    width   = if iter oldst > 50\n                                 then 2 * sumdiff' / (iterf * (iterf - 1))\n                                 else width oldst\n                    }\n\n", "meta": {"hexsha": "7d17d558e30d6f5e519539f9c2444d9893ba384b", "size": 4155, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Sampler/Slice.hs", "max_stars_repo_name": "finlay/random-dist", "max_stars_repo_head_hexsha": "26a12396c61762565ef12c47313d5ab71302af62", "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": "Statistics/Sampler/Slice.hs", "max_issues_repo_name": "finlay/random-dist", "max_issues_repo_head_hexsha": "26a12396c61762565ef12c47313d5ab71302af62", "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": "Statistics/Sampler/Slice.hs", "max_forks_repo_name": "finlay/random-dist", "max_forks_repo_head_hexsha": "26a12396c61762565ef12c47313d5ab71302af62", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5080645161, "max_line_length": 99, "alphanum_fraction": 0.4856799037, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4789819255308595}}
{"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-|\nModule      : RatioExemplars\nDescription : Instance for the ContextualizedConcept class for exemplars on a rational measurement scale\nCopyright   : (c) Juergen Hahn, 2016\nLicense     : GPL-3\nMaintainer  : hahn@geoinfo.tuwien.ac.at\nStability   : tested\n-}\nmodule ExemplarScales.RatioExemplars where\n\nimport Data.Function (on)\nimport qualified Data.Vector.Unboxed as U\nimport Statistics.Sample.KernelDensity (kde)\nimport qualified Data.List as List\nimport ContextualizedConcept\nimport Concept\n\ninstance ContextualizedConcept c Double where\n  calculatePrototype =calculatePrototype' . createKDE . extractData\n\ncalculatePrototype' :: [(Double,Double)] -> (Double, Double)\ncalculatePrototype' = List.maximumBy (compare `on` snd)\n\ncreateKDE :: [Double] -> [(Double,Double)]\ncreateKDE  rawdata =U.toList . uncurry U.zip . kde 64 $ dataVector\n  where dataVector= U.fromList rawdata\n\nextractData :: Concept c Double -> [Double]\nextractData = map getExemplar . toObservationList\n\n", "meta": {"hexsha": "66a04abe9bea96c3596a07ebd2134b2897e17d84", "size": 1048, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ExemplarScales/RatioExemplars.hs", "max_stars_repo_name": "juergenhah/ContextAlgebra", "max_stars_repo_head_hexsha": "c477e1057537a93c8d04d35bebee879cebafe37e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-08-24T09:57:22.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T09:57:22.000Z", "max_issues_repo_path": "src/ExemplarScales/RatioExemplars.hs", "max_issues_repo_name": "juergenhah/ContextAlgebra", "max_issues_repo_head_hexsha": "c477e1057537a93c8d04d35bebee879cebafe37e", "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/ExemplarScales/RatioExemplars.hs", "max_forks_repo_name": "juergenhah/ContextAlgebra", "max_forks_repo_head_hexsha": "c477e1057537a93c8d04d35bebee879cebafe37e", "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.7575757576, "max_line_length": 104, "alphanum_fraction": 0.7719465649, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4789150878958745}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n\nimport Debug.Trace\n-- import Control.Monad.State.Lazy\n\nimport System.Environment (getArgs)\nimport System.IO (readFile)\nimport Data.Map.Strict (Map, (!), insert, elems, fromList, toList, findWithDefault, size, empty, member, findMin, findMax, singleton, filter)\nimport qualified Data.Map.Strict as M\nimport Data.Set (Set)\nimport qualified Data.Set as S\n--import qualified Data.Array as A\nimport Data.List (find, intercalate, intersperse, permutations, inits, tails, isPrefixOf, sort, subsequences, nub)\nimport Data.List.Split (splitOn)\n-- import Data.Complex (Complex((:+)), realPart, imagPart) -- define my own complex\n\nimport UI.NCurses\nimport Data.Char (chr, ord, isLower, isUpper, toUpper, isDigit)\n-- import Data.Complex (Complex((:+)))\nimport Data.Maybe (fromJust)\n\n\n-- removeEach xs =  zip xs (map (flip List.delete xs) xs)\n\n\ndata Complex a = C a a\n\ninstance (Show a) => Show (Complex a) where\n  show (C x y) = \"C \" ++ show x ++ \" \" ++ show y\n  \ninstance (Eq a) => Eq (Complex a) where\n  (C a ai) == (C b bi) = a == b && ai == bi\n  \ninstance (Eq a, Ord a) => Ord (Complex a) where\n  compare (C a ai) (C b bi) | a < b || a == b && ai < bi = LT\n                            | a > b || a == b && ai > bi = GT\n                            | otherwise = EQ\n\ninstance Num a => Num (Complex a) where\n  (C x y) + (C u v) = C (x+u) (y+v)\n  (C x y) * (C u v) = C (x*u-y*v) (x*v+y*u)\n  fromInteger n = C (fromInteger n) 0\n  abs (C x y) = C (abs $ x + y) 0 -- manhattan distance -- sqrt $ x*x + y*y\n  signum (C x y) = C (signum x) 0\n  negate (C x y) = C (negate x) (negate y)\n\n\n  \ntype Point = Complex Int\n\nneighbors :: Complex Int -> [Complex Int]\nneighbors x = [ x + (C 0 1)\n              , x + (C 0 (-1))\n              , x + (C 1 0)\n              , x + (C (-1) 0)\n              ]\n\ntype Maze = Map Point Char\nstrToMaze :: String -> Maze\nstrToMaze s = fromList [(C i j, c) | (l, j) <- zip ls (reverse [0 .. (rows - 1)])\n                                   , (c, i) <- zip l [0 ..]\n                                   , c /= '#']\n  where ls = lines s\n        rows = length ls\n\n-- optimize maze for lots of hallways\ntype Cost = Int\ntype MazeGraph' = Map Point (Map Point Cost) -- Graph, from pt to neighbors, with cost, eliminates hallways\nmazeToGraph' :: Maze -> MazeGraph'\nmazeToGraph' m = foldl graph M.empty $ [ pt\n                                       | (pt, c) <- M.toList m\n                                       , isLower c || isUpper c || isDigit c || c == '@']\n  where graph g pt = addNeighbors (g, S.empty) $ S.singleton (0, pt)\n          where addNeighbors :: (MazeGraph', Set Point) -> Set (Cost, Point) -> MazeGraph'\n                addNeighbors (g, seen) heap -- note that seen does not\n                                            -- include the\n                                            -- destinations (locations\n                                            -- marked with letters or\n                                            -- the start)\n                  | null heap -- no more neighbors to process, we're done\n                  = g\n                  | neighbor == pt -- initial case, add true neighbors to the heap\n                  = --traceShow (\"starting with \", pt) $\n                  addNeighbors (g, seen') heap''\n                  | neighbor `S.member` seen -- we've already seen this neighbor, skip\n                  = addNeighbors (g, seen) heap'\n                  | m!neighbor == '.'  -- we're in a passage, add neighbor's neighbors to the heap\n                  = --traceShow (\"in hall\", pt, neighbor) $\n                  addNeighbors (g, seen') heap''\n                  | otherwise -- we've reached a destination, add it to the graph\n                  = traceShow (\"adding\", m!pt, m!neighbor) $\n                  addNeighbors (g', seen) heap'\n                  where ((pathLength, neighbor), heap') = S.deleteFindMin heap\n                        seen' = neighbor `S.insert` seen\n                        heap'' = heap' `S.union`\n                          S.fromList [(pathLength+1, n) | n <- neighbors neighbor\n                                                        , not $ n `S.member` seen\n                                                        , n `M.member` m]\n                        g' = M.unionWith (M.union) g $\n                             fromList[ (pt, M.fromList [(neighbor, pathLength)])\n                                     , (neighbor, M.fromList [(pt, pathLength)]) ]\n\nmazeToPositions :: Maze -> Map Char Point\nmazeToPositions m = fromList [(c, pt) | (pt, c) <- toList m, isLower c || isUpper c || c == '@']\n\ntype MazeGraph = Map Char (Map Char Cost) -- Graph, from char to neighbors, with cost, eliminates hallways\nmazeToGraph m = foldl addPt M.empty $ toList g\n  where g = mazeToGraph' m\n        addPt g (pt, nbrs) = M.insertWith M.union (m!pt) nbrs' g\n          where nbrs' = fromList [(m!k, v) | (k,v) <- toList nbrs]\n\n\n-- We want to collect all the keys in the shortest path, where the\n-- maze can change after each key is collected. We can solve this\n-- using a search routine that takes a starting point and a\n-- particular maze, and finds all the next keys reachable from that\n-- point. For example, suppose that starting at @, we can get to\n-- keys a and b only. Then, we can search from these points to the\n-- next reachable points. \n\n-- How much does this search cost? Let's overestimate, and assume\n-- that all 26 keys are reachable at every stage. Then we have 26\n-- keys from which to pick first, then for each pick, we have 25\n-- keys from which to pick the second key, then for each second key,\n-- we have 24 ways to pick the third key, and so on. The total\n-- number of paths is 26 factorial: 4E26, a very big number.\n\n-- We can prune the search tree by realizing that many searches are\n-- duplicates. For example, suppose we pick 'a' first, then 'b',\n-- then 'c'. This is the same as first picking 'b', then 'a', then\n-- 'c'. So if we find ourselves searching at 'c' after having\n-- uncovered 'a' and 'b', then we should check to see if we've been\n-- at this state before. If we have, we don't have to keep\n-- searching. What if the cost of abc is different than bac? In\n-- general it will be, but we want the lowest cost. So if we process\n-- states lowest-cost first, as they come off a heap, then if we\n-- encounter a duplicate state, we can be sure that the first state\n-- was better, or at least not worse.\n\nopenDoors :: MazeGraph -> [Char] -> MazeGraph -- aka removeVertex\nopenDoors g ds = foldl openDoor g ds\n\nopenDoor :: MazeGraph -> Char -> MazeGraph -- aka removeVertex\nopenDoor g d | d `M.member` g = --traceShow (\"open door\", d) $ traceShow g $ traceShow g' $ traceShowId $\n               M.mapWithKey merge g'\n             | otherwise = -- trace (\"openDoor: door \"++ show d ++ \"not in graph \") $\n               g -- error $ show (\"no such door\", d, g)\n  where\n    paths = --traceShowId $\n      g!d\n    g' = M.delete d g\n    merge pt nbrs | pt == d = error \"should not be here\"\n                  | d `M.member` nbrs = M.unionWith min (M.delete d nbrs) nbrsThruDoor\n                  | otherwise =  nbrs\n      where nbrsThruDoor = fromList [ (n, cost + doorCost)\n                                    | (n, cost) <- toList $ paths\n                                     , n /= pt\n                                     , n /= d]\n            doorCost =  nbrs!d\n            \n-- keysReachable :: MazeGraph -> Char -> [(Char, Cost)]\n-- keysReachable g pt\n--   | pt  `M.member` g\n--   = --traceShow (\"keysReachable\", g, pt) $ traceShowId $\n--     [(nbr, cost) | (nbr, cost) <- M.toList $ g!pt\n--                  , isLower nbr]\n--   | otherwise = error \"bad pt\"\n\nisCapitalized s = isUpper $ head s\nisLowered s = isLower $ head s\ncapitalize s = (toUpper $ head s): tail s\n\nfindShortestPath :: (String -> Bool) -> MazeGraph -> Set (Cost, String) -> (Cost, [Char])\nfindShortestPath isDone graph myheap = search (M.singleton \"\" graph) S.empty $ myheap\n\n\n  -- 'search graphs isDone seen heap' removes the best state (state with\n  -- lowest cost) from the heap and checks if we're done. If we're\n  -- not, then it inserts the next states on the heap and recurses.\n\n  -- graphs is a dictionary which holds graphs with various states\n  -- removed. graphs!\"abc\" is the graph with states a, b, and c\n  -- removed. Note that \"abc\" is sorted.\n\n  -- The heap stores states in the tuple (363, \"abc1 xyz2 uv3 4\")\n  -- where the first element is the cost and the send is the paths\n  -- concatenated with a space. The initial state is (0, \"1 2 3 4\")\n\n  -- I use the convention of adding a tick to denote the next\n  -- variable, so gs' is the next gs.\n  where search ::  Map [Char] MazeGraph -> Set [Char] -> Set (Cost, String) -> (Cost, [Char])\n        search gs seen heap\n          | null heap = error \"null heap\" -- should never have an empty heap\n          | isDone pathsString\n          = traceShow \"Done\" $\n            best -- collected all the keys, return\n          | pathsString `S.member` seen\n          = traceShow (\"Search seen: \", cost, pathsString, \"new heapsize\", S.size heap') $\n            search gs seen heap' -- we've already seen this state\n          | otherwise\n          = traceShow (\"Search running: \", cost, best, pathsString, \"new heapsize\", S.size heap'') $ trace \"\\n\" $\n            -- traceShow (\"new heap\", S.toList heap'' ) $\n            search gs' seen' heap''\n          where\n            (best@(cost, pathsString), heap') = S.deleteFindMin heap\n            seen' = pathsString `S.insert` seen\n            paths = [ p | p <- words pathsString, not $ null p ]\n            state0 = sort $ xs ++ cxs\n              where xs = concatMap tail paths\n                    cxs = map toUpper $ Prelude.filter isLower xs\n            g0 | state0 `M.member` gs = gs!state0\n               | otherwise = error $  \"bad state0 \" ++ state0 ++ \": keys for gs are: \" ++ (show $ M.keys gs)++ \"\\nbest = \" ++ show best ++\"\\nstateNow = \" ++ stateNow\n            stateDelta = -- trace \"stateDelta\" $ traceShowId $\n              concatMap (map toUpper . Prelude.filter isLower) paths\n            stateNow = sort $ state0 ++ stateDelta\n            gNow = openDoors g0 stateDelta -- This is the current graph with the doors open.\n\n\n            -- gNext is a list of the next graphs, once any path is\n            -- lengthened. When a path is lengthened, the old pathhead\n            -- is removed from the graph. It's only needed so that\n            -- neighbors can be calculated. After that, it just slows\n            -- up the search.\n            gNext = S.fromList $ \n                    [(sort $ h:stateNow, openDoor gNow h)\n                    | h <- map head paths ]\n                    ++ [(sort $ h'++state0, openDoors g0 h') | h <- map head paths, h' <- if h == toUpper h then [[h]] else [[h], [h, toUpper h]]]\n            gs' = foldr (uncurry M.insert) gs $ (stateNow, gNow): S.toList gNext\n            newStates = [(cost+nbrCost, pathsString')\n                        | i <- [0 .. (length paths - 1)]\n                        , let (paths0, (x: xs): paths2) = splitAt i paths -- expand from x\n                        , (nbr, nbrCost) <- M.toList $ gNow!x\n                        , isLower nbr\n                        , let pathsString' = unwords $ paths0 ++ (nbr:x:xs): paths2\n                        ]\n            heap'' = foldr S.insert heap' newStates\n\n\nmain = do\n  -- [instructionFile] <- getArgs\n  -- putStrLn \"Part 1\"\n  -- mazeString <- readFile \"18.input.txt\" -- instructionFile\n  -- -- mazeString <- readFile \"18.2.input.txt\" -- instructionFile\n  -- -- mazeString <- readFile \"18.test4\" -- instructionFile\n  -- let maze = strToMaze mazeString\n  -- let mazeGraph = mazeToGraph maze\n  -- -- print $ mazeToGraph' maze\n  -- -- print mazeGraph\n  -- let positions = mazeToPositions maze\n  -- print (\"maze size\", M.size maze, \"graph size\", M.size mazeGraph) -- reduced from 3201 nodes to 53 nodes\n  -- print $ sort $ M.keys mazeGraph \n  -- print $ findShortestPath isDone mazeGraph $ S.singleton (0, ['@'])\n\n  putStrLn \"Part 2\"\n  let file2 = \"18.2.input.txt\"\n  -- let file2 = \"18.2.test1\"\n  -- mazeGraph2 <- readFile \"18.2.test1\" >>= (return . mazeToGraph . strToMaze)\n  mazeGraph2 <- readFile file2 >>= (return . mazeToGraph . strToMaze)\n  let allKeys = Prelude.filter isLower $ M.keys mazeGraph2\n  let isDone state = all (`elem` state') allKeys\n        where state' = Prelude.filter isLower state\n        \n  -- print mazeGraph2\n  print $ findShortestPath isDone mazeGraph2 $ S.singleton (0, \"1 2 3 4\")\n", "meta": {"hexsha": "41683d3e8c273081b6d66ed106c41506fe196c82", "size": 12496, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "18.hs", "max_stars_repo_name": "dpatru/aoc2019", "max_stars_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-30T21:19:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T21:19:29.000Z", "max_issues_repo_path": "18.hs", "max_issues_repo_name": "dpatru/aoc2019", "max_issues_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "18.hs", "max_forks_repo_name": "dpatru/aoc2019", "max_forks_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1547169811, "max_line_length": 165, "alphanum_fraction": 0.5629801536, "num_tokens": 3319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4785246233894012}}
{"text": "module Raytracer.Light where\n\nimport Numeric.LinearAlgebra.Data (Vector, (|>), toList)\nimport Numeric.LinearAlgebra ((<.>))\nimport Raytracer.Geometry (Pos, rayTo, Intersectable, Ray(Ray))\nimport Raytracer.Camera (fire_ray)\nimport Data.Maybe (isJust)\n\nimport Codec.Picture (PixelRGB8(PixelRGB8), colorMap)\n\n-- This has the position of the light, the cutoff range of the light, and the colour\ndata Light a = Light Pos Double a deriving (Show)\n\n--computeLighting :: (Intersectable a) => a b -> [Light b] -> Pos -> [b]\ncomputeLighting mesh lights pos = fmap attenuate $ filter (not . visible) $ fmap makeRay lights\n  where\n  makeRay light@(Light lPos _ _) = (pos `rayTo` lPos, light)\n  visible (ray, _) = isJust $ fire_ray mesh $ ray\n\nattenuate (Ray ray _, Light _ cutoff a) = if dist > cutoff then PixelRGB8 0 0 0 else blend\n  where\n  dist = sqrt $ ray <.> ray\n  blend = colorMap (\\x -> round $ (fromIntegral x) * (cutoff - dist) / cutoff) a\n", "meta": {"hexsha": "cfece69fd8c63274b197d3aca1abdf15cd55817e", "size": 939, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Raytracer/Light.hs", "max_stars_repo_name": "psycotica0/ray-tracer", "max_stars_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Raytracer/Light.hs", "max_issues_repo_name": "psycotica0/ray-tracer", "max_issues_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Raytracer/Light.hs", "max_forks_repo_name": "psycotica0/ray-tracer", "max_forks_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.125, "max_line_length": 95, "alphanum_fraction": 0.7071352503, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.47838242611123133}}
{"text": "{-# LANGUAGE BangPatterns , RankNTypes, GADTs, DataKinds #-}\n\n{- | The 'Numerical.HBLAS.BLAS.Level3' module provides a fully general\nyet type safe Level3 BLAS API.\n\nWhen in doubt about the semantics of an operation,\nconsult your system's BLAS api documentation, or just read the documentation\nfor\n<https://software.intel.com/sites/products/documentation/hpc/mkl/mklman/index.htm the Intel MKL BLAS distribution>\n\nA few basic notes about how to invoke BLAS routines.\n\nMany BLAS operations take one or more arguments of type 'Transpose'.\n'Tranpose' has the following different constructors, which tell BLAS\nroutines what transformation to implicitly apply to an input matrix @mat@ with dimension @n x m@.\n\n*  'NoTranspose' leaves the matrix @mat@ as is.\n\n* 'Transpose' treats the @mat@ as being implicitly transposed, with dimension\n    @m x n@. Entry @mat(i,j)@ being treated as actually being the entry\n    @mat(j,i)@. For Real matrices this is also the matrix adjoint operation.\n    ie @Tranpose(mat)(i,j)=mat(j,i)@\n\n*  'ConjNoTranspose' will implicitly conjugate @mat@, which is a no op for Real ('Float' or 'Double') matrices, but for\n'Complex Float' and 'Complex Double' matrices, a given matrix entry @mat(i,j)==x':+'y@\nwill be treated as actually being  @conjugate(mat)(i,j)=y':+'x@.\n\n* 'ConjTranpose' will implicitly transpose and conjugate the input matrix.\nConjugateTranpose acts as matrix adjoint for both real and complex matrices.\n\n\n\nThe *gemm operations  work as follows (using 'sgemm' as an example):\n\n* @'sgemm trLeft trRight alpha beta left right result'@, where @trLeft@ and @trRight@\nare values of type 'Transpose' that respectively act on the matrices @left@ and @right@.\n\n* the generalized matrix computation thusly formed can be viewed as being\n@result = alpha * trLeft(left) * trRight(right) + beta * result@\n\n\nthe *gemv operations are akin to the *gemm operations, but with @right@ and @result@\nbeing vectors rather than matrices.\n\n\nthe *trsv operations solve for @x@ in the equation @A x = y@ given @A@ and @y@.\nThe 'MatUpLo' argument determines if the matrix should be treated as upper or\nlower triangular and 'MatDiag' determines if the triangular solver should treat\nthe diagonal of the matrix as being all 1's or not.  A general pattern of invocation\nwould be @'strsv' matuplo  tranposeMatA  matdiag  matrixA  xVector@.\nA key detail to note is that the input vector is ALSO the result vector,\nie 'strsv' and friends updates the vector place.\n\n-}\n\nmodule Numerical.HBLAS.BLAS.Level3(\n        dgemm\n        ,sgemm\n        ,cgemm\n        ,zgemm\n\n        ,chemm\n        ,zhemm\n\n        ,cherk\n        ,zherk\n\n        ,cher2k\n        ,zher2k\n\n        ,ssymm\n        ,dsymm\n        ,csymm\n        ,zsymm\n\n        ,ssyrk\n        ,dsyrk\n        ,csyrk\n        ,zsyrk\n\n        ,ssyr2k\n        ,dsyr2k\n        ,csyr2k\n        ,zsyr2k\n\n        ,strmm\n        ,dtrmm\n        ,ctrmm\n        ,ztrmm\n\n        ,strsm\n        ,dtrsm\n        ,ctrsm\n        ,ztrsm\n            ) where\n\n\nimport Numerical.HBLAS.UtilsFFI\nimport Numerical.HBLAS.BLAS.FFI.Level3\nimport Numerical.HBLAS.BLAS.Internal.Level3\nimport Control.Monad.Primitive\nimport Data.Complex\n\nsgemm :: PrimMonad m=>  GemmFun Float  orient  (PrimState m) m\nsgemm =  gemmAbstraction \"sgemm\"  cblas_sgemm_safe cblas_sgemm_unsafe (\\x f -> f x )\n\ndgemm :: PrimMonad m=>  GemmFun  Double orient  (PrimState m) m\ndgemm = gemmAbstraction \"dgemm\"  cblas_dgemm_safe cblas_dgemm_unsafe  (\\x f -> f x )\n\ncgemm :: PrimMonad m=>  GemmFun (Complex Float) orient  (PrimState m) m\ncgemm = gemmAbstraction \"cgemm\" cblas_cgemm_safe cblas_cgemm_unsafe  withRStorable_\n\nzgemm :: PrimMonad m=>  GemmFun (Complex Double) orient  (PrimState m) m\nzgemm = gemmAbstraction \"zgemm\"  cblas_zgemm_safe cblas_zgemm_unsafe withRStorable_\n\nchemm :: PrimMonad m=>  HemmFun (Complex Float) orient (PrimState m) m\nchemm = hemmAbstraction \"chemm\" cblas_chemm_safe cblas_chemm_unsafe withRStorable_\n\nzhemm :: PrimMonad m=>  HemmFun (Complex Double) orient (PrimState m) m\nzhemm = hemmAbstraction \"zhemm\" cblas_zhemm_safe cblas_zhemm_unsafe withRStorable_\n\ncherk :: PrimMonad m=>  HerkFun Float (Complex Float) orient (PrimState m) m\ncherk = herkAbstraction \"cherk\" cblas_cherk_safe cblas_cherk_unsafe (\\x f -> f x)\n\nzherk :: PrimMonad m=>  HerkFun Double (Complex Double) orient (PrimState m) m\nzherk = herkAbstraction \"zherk\" cblas_zherk_safe cblas_zherk_unsafe (\\x f -> f x)\n\ncher2k :: PrimMonad m=>  Her2kFun Float (Complex Float) orient (PrimState m) m\ncher2k = her2kAbstraction \"cher2k\" cblas_cher2k_safe cblas_cher2k_unsafe withRStorable_\n\nzher2k :: PrimMonad m=>  Her2kFun Double (Complex Double) orient (PrimState m) m\nzher2k = her2kAbstraction \"zher2k\" cblas_zher2k_safe cblas_zher2k_unsafe withRStorable_\n\nssymm :: PrimMonad m=>  SymmFun Float orient (PrimState m) m\nssymm = symmAbstraction \"ssymm\" cblas_ssymm_safe cblas_ssymm_unsafe (\\x f -> f x)\n\ndsymm :: PrimMonad m=>  SymmFun Double orient (PrimState m) m\ndsymm = symmAbstraction \"dsymm\" cblas_dsymm_safe cblas_dsymm_unsafe (\\x f -> f x)\n\ncsymm :: PrimMonad m=>  SymmFun (Complex Float) orient (PrimState m) m\ncsymm = symmAbstraction \"csymm\" cblas_csymm_safe cblas_csymm_unsafe withRStorable_\n\nzsymm :: PrimMonad m=>  SymmFun (Complex Double) orient (PrimState m) m\nzsymm = symmAbstraction \"zsymm\" cblas_zsymm_safe cblas_zsymm_unsafe withRStorable_\n\nssyrk :: PrimMonad m=>  SyrkFun Float orient (PrimState m) m\nssyrk = syrkAbstraction \"ssyrk\" cblas_ssyrk_safe cblas_ssyrk_unsafe (\\x f -> f x)\n\ndsyrk :: PrimMonad m=>  SyrkFun Double orient (PrimState m) m\ndsyrk = syrkAbstraction \"dsyrk\" cblas_dsyrk_safe cblas_dsyrk_unsafe (\\x f -> f x)\n\ncsyrk :: PrimMonad m=>  SyrkFun (Complex Float) orient (PrimState m) m\ncsyrk = syrkAbstraction \"csyrk\" cblas_csyrk_safe cblas_csyrk_unsafe withRStorable_\n\nzsyrk :: PrimMonad m=>  SyrkFun (Complex Double) orient (PrimState m) m\nzsyrk = syrkAbstraction \"zsyrk\" cblas_zsyrk_safe cblas_zsyrk_unsafe withRStorable_\n\nssyr2k :: PrimMonad m=>  Syr2kFun Float orient (PrimState m) m\nssyr2k = syr2kAbstraction \"ssyr2k\" cblas_ssyr2k_safe cblas_ssyr2k_unsafe (\\x f -> f x)\n\ndsyr2k :: PrimMonad m=>  Syr2kFun Double orient (PrimState m) m\ndsyr2k = syr2kAbstraction \"dsyr2k\" cblas_dsyr2k_safe cblas_dsyr2k_unsafe (\\x f -> f x)\n\ncsyr2k :: PrimMonad m=>  Syr2kFun (Complex Float) orient (PrimState m) m\ncsyr2k = syr2kAbstraction \"csyr2k\" cblas_csyr2k_safe cblas_csyr2k_unsafe withRStorable_\n\nzsyr2k :: PrimMonad m=>  Syr2kFun (Complex Double) orient (PrimState m) m\nzsyr2k = syr2kAbstraction \"zsyr2k\" cblas_zsyr2k_safe cblas_zsyr2k_unsafe withRStorable_\n\nstrmm :: PrimMonad m=> TrmmFun Float orient (PrimState m) m\nstrmm = trmmAbstraction \"strmm\" cblas_strmm_safe cblas_strmm_unsafe (\\x f -> f x)\n\ndtrmm :: PrimMonad m=> TrmmFun Double orient (PrimState m) m\ndtrmm = trmmAbstraction \"dtrmm\" cblas_dtrmm_safe cblas_dtrmm_unsafe (\\x f -> f x)\n\nctrmm :: PrimMonad m=> TrmmFun (Complex Float) orient (PrimState m) m\nctrmm = trmmAbstraction \"ctrmm\" cblas_ctrmm_safe cblas_ctrmm_unsafe withRStorable_\n\nztrmm :: PrimMonad m=> TrmmFun (Complex Double) orient (PrimState m) m\nztrmm = trmmAbstraction \"ztrmm\" cblas_ztrmm_safe cblas_ztrmm_unsafe withRStorable_\n\nstrsm :: PrimMonad m=> TrsmFun Float orient (PrimState m) m\nstrsm = trsmAbstraction \"strsm\" cblas_strsm_safe cblas_strsm_unsafe (\\x f -> f x)\n\ndtrsm :: PrimMonad m=> TrsmFun Double orient (PrimState m) m\ndtrsm = trsmAbstraction \"dtrsm\" cblas_dtrsm_safe cblas_dtrsm_unsafe (\\x f -> f x)\n\nctrsm :: PrimMonad m=> TrsmFun (Complex Float) orient (PrimState m) m\nctrsm = trsmAbstraction \"ctrsm\" cblas_ctrsm_safe cblas_ctrsm_unsafe withRStorable_\n\nztrsm :: PrimMonad m=> TrsmFun (Complex Double) orient (PrimState m) m\nztrsm = trsmAbstraction \"ztrsm\" cblas_ztrsm_safe cblas_ztrsm_unsafe withRStorable_\n", "meta": {"hexsha": "2c717a20e468f76405dd46c0ca43a4e27fb5239d", "size": 7767, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numerical/HBLAS/BLAS/Level3.hs", "max_stars_repo_name": "schnecki/hblas", "max_stars_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-05-03T23:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-17T22:58:54.000Z", "max_issues_repo_path": "src/Numerical/HBLAS/BLAS/Level3.hs", "max_issues_repo_name": "schnecki/hblas", "max_issues_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-01-24T13:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T22:15:09.000Z", "max_forks_repo_path": "src/Numerical/HBLAS/BLAS/Level3.hs", "max_forks_repo_name": "schnecki/hblas", "max_forks_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-01-09T12:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:37:37.000Z", "avg_line_length": 40.2435233161, "max_line_length": 119, "alphanum_fraction": 0.7432728209, "num_tokens": 2529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4781723250927764}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\n-- By Christian Oliveros and Minmin Chen\r\nmodule PingPong.Player.Stig (stig) \r\nwhere\r\n\r\nimport Control.Lens (view, (&), (.~), (^.))\r\nimport Data.Bool (bool)\r\nimport Data.Ext\r\nimport Data.Geometry hiding (head, Above, Below)\r\nimport Data.Maybe\r\nimport Debug.Trace\r\nimport GHC.Float\r\nimport qualified Numeric.LinearAlgebra as Numerical\r\nimport PingPong.Model\r\nimport PingPong.Player.Stig.General\r\nimport PingPong.Player.Stig.GeometryHelpers\r\nimport PingPong.Player.Stig.Kinematics\r\nimport PingPong.Player.Stig.Fabrik\r\n\r\nimport Control.Monad\r\n\r\n-- | Simulation's gravity\r\nsimulationGravity :: Float\r\nsimulationGravity = 2\r\n\r\n-- | Simulation's max speed\r\nsimulationMaxSpeed :: Float\r\nsimulationMaxSpeed = 2\r\n\r\n-- | Simulation's Table Height\r\nsimulationTableHeight :: Float\r\nsimulationTableHeight = 0.5\r\n\r\n-- | Simulation's Table Center X Position\r\nsimulationTableCenterX :: Float\r\nsimulationTableCenterX = 0\r\n\r\n-- | Simulation's Table Max X Position\r\nsimulationTableMaxX :: Float\r\nsimulationTableMaxX = 1\r\n\r\n-- | Normalized direction of the table\r\nsimulationTableDir :: Vector 2 Float\r\nsimulationTableDir = Vector2 (-1) 0\r\n\r\n-- | Bat's Length\r\nsimulationBatLength :: Float\r\nsimulationBatLength = 0.1\r\n\r\n-- | Simulation's Table Center X Position\r\nsimulationTableOpponentCenterX :: Float\r\nsimulationTableOpponentCenterX = -0.5\r\n\r\n-- | Simulation's Table Max X Position\r\nsimulationTableOpponentMinX :: Float\r\nsimulationTableOpponentMinX = -0.8\r\n\r\n-- | If the x value is inside the opponent's table range\r\ninsideOpponentTableX :: Float -> DistanceToRange Float\r\ninsideOpponentTableX = signedDistanceToRange simulationTableOpponentMinX simulationTableOpponentCenterX\r\n\r\n-- | Predict the time (relative to current time) the gravity parabole is going to intersect a height\r\npredictFreefallHeightInter :: Point 2 Float -> Vector 2 Float -> Float -> Maybe Float \r\npredictFreefallHeightInter p v tH = bool res Nothing (isNothing possible || null tsRaw) \r\n  where\r\n    a2 = -simulationGravity / 2\r\n    a1 = view yComponent v\r\n    a0 = view yCoord p - tH\r\n    possible = solveQuadratic a2 a1 a0\r\n    tsRaw = fromJust possible\r\n    -- If solveQuadratic is [] change for 0, because all t are valid\r\n    -- Also, make sure the times are valid between 0 and 1 (threshold is used for approximations)\r\n    ts = filter (0 <=) $ map (globalThreshold 0) $ bool tsRaw [0] (null tsRaw)\r\n    res = case possible of\r\n        Nothing -> Nothing\r\n        Just _ -> case ts of\r\n                    [] -> Nothing -- No solution\r\n                    _ -> Just $ minimum ts -- Minimum Valid Time\r\n      \r\n\r\n-- | Evaluate the free fall formulas for a time\r\nfreeFallEvaluateTime :: Point 2 Float -> Vector 2 Float -> Float -> (Point 2 Float, Vector 2 Float)\r\nfreeFallEvaluateTime p v t = (Point2 x y, Vector2 vx vy)\r\n  where\r\n    vx = view xComponent v\r\n    x = vx * t + view xCoord p\r\n\r\n    vy0 = view yComponent v\r\n    vy = -simulationGravity * t + vy0\r\n    y = -simulationGravity * t * t / 2 + vy0 * t + view yCoord p\r\n\r\n-- | Reflect a velocity vector againts the table like in a collision\r\nreflectVelocityTable :: Vector 2 Float -> Vector 2 Float\r\nreflectVelocityTable v = reflect v simulationTableDir\r\n\r\n-- | Reflect Ball Velocity against a bat\r\nreflectVelocityBat :: LineSegment 2 () Float -> Vector 2 Float -> Vector 2 Float\r\nreflectVelocityBat bat v = reflect v (segmentDir bat)\r\n\r\n-- | Get the normal of the free fall velocity\r\nfreefallNormal :: Vector 2 Float -> Vector 2 Float\r\nfreefallNormal v = n\r\n  where\r\n    nUnorm = Vector2 (-view yComponent v) (view xComponent v)\r\n    (n, _) = normalizeVector nUnorm\r\n\r\n-- | Get the (relative) time of maximum height of a freefall. Note, it might be negative, meaning it already peaked\r\nfreeFallMaxHeightTime :: Vector 2 Float -> Float\r\nfreeFallMaxHeightTime v = view yComponent v / simulationGravity\r\n\r\n-- | Calculates the (relative) time to reach a x position in a freefall. Note, it might be negative, meaning it already passed\r\nfreeFallTimeToXPos :: Point 2 Float -> Vector 2 Float -> Float -> Float\r\nfreeFallTimeToXPos p v x = (x - view xCoord p) / view xComponent v\r\n\r\n-- | Predict the info of the ball bouncing on our side of the table\r\npredictTableBounce :: Point 2 Float -> Vector 2 Float -> Maybe (Point 2 Float, Vector 2 Float, Float)\r\npredictTableBounce p v = res\r\n  where \r\n    tPossible = predictFreefallHeightInter p v simulationTableHeight\r\n    (pB, vB) = freeFallEvaluateTime p v (fromJust tPossible)\r\n    xPos = view xCoord pB\r\n    xPosValid =  simulationTableCenterX <= xPos && xPos <= simulationTableMaxX\r\n    res = case tPossible of\r\n            Nothing -> Nothing\r\n            Just t -> if xPosValid then return (pB, reflectVelocityTable vB, t) else Nothing\r\n\r\n\r\n-- | Checks if a position is valid for our side of the table\r\ncheckValidPos :: Point 2 Float -> Bool\r\ncheckValidPos p0 = simulationTableCenterX <= xPos && xPos <= simulationTableMaxX && simulationTableHeight <= yPos\r\n  where\r\n    xPos = view xCoord p0\r\n    yPos = view yCoord p0\r\n\r\n-- | Try to predict the best interception time\r\npredictBestInterceptionTime :: Point 2 Float -> Vector 2 Float -> Maybe Float\r\npredictBestInterceptionTime p v = res\r\n  where\r\n    ts = [freeFallMaxHeightTime v, freeFallTimeToXPos p v simulationTableMaxX, freeFallTimeToXPos p v (simulationTableMaxX / 2), freeFallTimeToXPos p v (simulationTableMaxX / 4)]\r\n    tF = filter tFilter ts\r\n\r\n    res =  if null tF then Nothing else Just $ traceShowId $ minimum tF\r\n\r\n    tFilter :: Float -> Bool\r\n    tFilter t = 0 <= t && checkValidPos p0\r\n      where\r\n        (p0, _) = freeFallEvaluateTime p v t\r\n\r\n\r\n\r\n-- | Place the bat normal to a ball point and velocity\r\nplaceBatInBounceCurve :: Point 2 Float -> Vector 2 Float -> Float -> LineSegment 2 () Float\r\nplaceBatInBounceCurve p v q = line\r\n  where\r\n    \r\n    -- Normal to Velocity\r\n    n0 = freefallNormal v\r\n    n = rotateVector2D q n0\r\n    --(n, _) = normalizeVector v\r\n    p0 = p .+^ (n ^* (simulationBatLength / 2))\r\n    p1 = p .-^ (n ^* (simulationBatLength / 2))\r\n    {- p0 = p\r\n    p1 = p .+^ (n ^* simulationBatLength) -}\r\n    p0Dist = distToSpecialBase p0\r\n    p1Dist = distToSpecialBase p1\r\n    \r\n    line = bool (ClosedLineSegment (p1 :+ ()) (p0 :+ ())) (ClosedLineSegment (p0 :+ ()) (p1 :+ ()))  (p0Dist < p1Dist)\r\n\r\n    -- | Distance to Stig base at table height\r\n    distToSpecialBase :: Point 2 Float -> Float\r\n    distToSpecialBase po = norm $ po .-. Point2 stigFoot simulationTableHeight\r\n\r\n-- | Maximum ITerations to guess\r\nbinaryGuessMaxIter :: Int\r\nbinaryGuessMaxIter = 10\r\n\r\n-- | Place the ball at the center of the opponents table\r\nrotateBatToCenter :: Point 2 Float -> Vector 2 Float -> DistanceToRange (Float, LineSegment 2 () Float)\r\nrotateBatToCenter p v = fromMaybe (trace \"Never interception with table?!\" Below (read \"Infinity\" :: Float, placeBatInBounceCurve p v 0)) finalGuess\r\n  where\r\n    -- If we are going up\r\n    goingUp = view yComponent v > 0\r\n\r\n    finalGuess = -- binaryGuess 0 (-binaryGuessLimit) binaryGuessLimit 0\r\n      bool \r\n        (binaryGuess 0 0 (pi/2) 0) -- Case going down\r\n        (binaryGuess 0 (-pi/4) 0 (-pi/4)) -- Case going up\r\n        goingUp\r\n\r\n    -- | Guess a possible bat possition\r\n    binaryGuess iter qmin qmax qcurr\r\n      | noTPossible = trace \"No interception with table?!\" Nothing \r\n      {- | iter >= binaryGuessMaxIter = trace (\"Max Iter Selected q=\" ++ show qcurr) Just (useInsideInfo insideInfo bat)-}\r\n      | iter >= binaryGuessMaxIter = Just (useInsideInfo insideInfo bat)\r\n      | otherwise = guess\r\n      where\r\n        -- Generate bat\r\n        bat = placeBatInBounceCurve p v qcurr\r\n        nV = reflectVelocityBat bat v\r\n        tPossible = predictFreefallHeightInter p nV simulationTableHeight\r\n        noTPossible = isNothing tPossible\r\n        t = fromJust tPossible\r\n        (pI, _) = freeFallEvaluateTime p nV t\r\n        pIX = view xCoord pI\r\n\r\n        -- If Bounce is going up\r\n        bounceGoingUp = view yComponent nV > 0\r\n\r\n        insideInfo = insideOpponentTableX pIX\r\n\r\n        useInsideInfo (Inside _) b = Inside (pIX, b)\r\n        useInsideInfo (Above _) b = Below (pIX, b)\r\n        useInsideInfo (Below _) b = Above (pIX, b)\r\n\r\n        -- Guess Selection to improve\r\n        -- Ball Going Up\r\n        guessTry x True = case insideOpponentTableX x of\r\n                  {- Above _ -> trace (\"X=\" ++ show x ++ \" Up:Below \" ++ show bounceGoingUp ++ \" qs=\" ++ show (qmin, qmax, qcurr)) $ binaryGuess (iter + 1) qmin qcurr ((qmin + qcurr) / 2)\r\n                  Below _ -> trace (\"X=\" ++ show x ++ \" Up:Above \" ++ show bounceGoingUp ++ \" qs=\" ++ show (qmin, qmax, qcurr)) $ binaryGuess (iter + 1) qcurr qmax ((qmax + qcurr) / 2)\r\n                  Inside _ -> trace (\"X=\" ++ show x ++ \" Up:Inside Selected q=\" ++ show qcurr) Just (Inside (pIX, bat)) -}\r\n                  Above _ ->  binaryGuess (iter + 1) qmin qcurr ((qmin + qcurr) / 2)\r\n                  Below _ ->  binaryGuess (iter + 1) qcurr qmax ((qmax + qcurr) / 2)\r\n                  Inside _ -> Just (Inside (pIX, bat))\r\n        \r\n        -- Ball Going Down\r\n        guessTry x False = case insideOpponentTableX x of\r\n          {- Above _ -> trace (\"X=\" ++ show x ++ \" Down:Below \" ++ show bounceGoingUp ++ \" qs=\" ++ show (qmin, qmax, qcurr)) $ binaryGuess (iter + 1) qmin qcurr ((qmin + qcurr) / 2)\r\n          Below _ -> trace (\"X=\" ++ show x ++ \" Down:Above \" ++ show bounceGoingUp ++ \" qs=\" ++ show (qmin, qmax, qcurr)) $ binaryGuess (iter + 1) qcurr qmax ((qmax + qcurr) / 2)\r\n          Inside _ -> trace (\"X=\" ++ show x ++ \" Down:Inside Selected q=\" ++ show qcurr) Just (Inside (pIX, bat)) -}\r\n          Above _ -> binaryGuess (iter + 1) qmin qcurr ((qmin + qcurr) / 2)\r\n          Below _ -> binaryGuess (iter + 1) qcurr qmax ((qmax + qcurr) / 2)\r\n          Inside _ -> Just (Inside (pIX, bat))\r\n\r\n        --guess = traceShow (p, nV, t, pI) guessTry pIX goingUp\r\n        guess = guessTry pIX goingUp\r\n\r\n-- | Move bat to center low limit\r\nmoveBatToCenterLowLim :: Float\r\nmoveBatToCenterLowLim = 0.6\r\n\r\n-- | Move bat to center high limit\r\nmoveBatToCenterHighLim :: Float\r\nmoveBatToCenterHighLim = 1.3\r\n\r\n\r\n-- | Move bat to center number of steps\r\nmoveBatToCenterSteps :: Float\r\nmoveBatToCenterSteps = 40\r\n\r\n-- | Move bat to center step size\r\nmoveBatToCenterStepSize :: Float\r\nmoveBatToCenterStepSize = (moveBatToCenterHighLim - moveBatToCenterLowLim) / moveBatToCenterSteps\r\n\r\n-- | Maximum Time apply Motion\r\nmaxTimeToMotion :: Motion-> Float\r\nmaxTimeToMotion m = maximum $ map (\\v -> abs v / simulationMaxSpeed) m\r\n\r\n\r\nbestMotion :: Arm -> Point 2 Float -> Vector 2 Float -> Motion\r\nbestMotion arm p v = finalMotion\r\n  where\r\n    (finalMotion, _) = move 0 moveBatToCenterHighLim\r\n    -- Approach to good bat center\r\n    move iter x\r\n      | iter >= moveBatToCenterSteps || moveBatToCenterLowLim > x = (bM, bMV) -- Limit\r\n      | isInside possible = bool (bMN, mVN) (bM, bMV) (bMV <= mVN) -- We are inside check if we are better\r\n      | otherwise = (bMN, bMV) -- We are not inside, continue checking\r\n      where\r\n        tX = freeFallTimeToXPos p v x\r\n        (pN, vN) = freeFallEvaluateTime p v tX\r\n        possible = rotateBatToCenter pN vN\r\n        (_, bat) = getDistanceToRangeContent possible\r\n\r\n        batInv = segmentInvert bat\r\n        (mIntercept, _, _) = fabrikToSegment stigFoot arm bat\r\n        (mInterceptInv, _, _) = fabrikToSegment stigFoot arm batInv\r\n        m = armToMotion arm mIntercept\r\n        mV = maxTimeToMotion m\r\n        mInv = armToMotion arm mInterceptInv\r\n        mVInv = maxTimeToMotion mInv\r\n\r\n        -- Current Best Motion\r\n        bM = bool mInv m (mV <= mVInv)\r\n        bMV = maxTimeToMotion bM\r\n\r\n        -- Possible Next Best Motion\r\n        (bMN, mVN) = move (iter + 1) (x - moveBatToCenterStepSize)\r\n\r\n\r\n-- | Try to intercept Ball\r\ntryInterceptBall :: Arm -> Point 2 Float -> Vector 2 Float -> Float -> IO Motion\r\ntryInterceptBall arm p v tColl =\r\n   do \r\n     let bM = bestMotion arm p v\r\n     --return $ trace (\"Opponent did a proper hit we can catch at \" ++ show tColl ++ \"\\n\" ++ show bM) bM \r\n     return bM \r\n\r\n\r\n-- | Stig's player\r\nstig :: Player\r\nstig =\r\n  Player\r\n    { \r\n      name = \"Stig\",\r\n      arm = stigArm,\r\n      initArm = stigArm,\r\n      foot = stigFoot,\r\n      prepare = return (),\r\n      terminate = return (),\r\n      action = stigAction,\r\n      collide = stigCollide,\r\n      planPnt = stigPlanPnt,\r\n      planSeg = stigPlanSeg,\r\n      stretch = \\_ arm -> return $ armToStigRestMotion arm,\r\n      dance   = \\_ arm -> return $ armToStigRestMotion arm\r\n    }\r\n\r\n\r\n-- Internal Stig Arm\r\nstigInternalArm :: Arm\r\nstigInternalArm = checkArm\r\n    [ Link paleBlue 0.5,\r\n      Joint red (0.5112798), -- (0.1)\r\n      Link paleBlue 0.3,\r\n      Joint red 1.247675, -- (0.1)\r\n      Link paleBlue 0.25,\r\n      Joint red 0.4820231, -- (-0.1)\r\n      Link paleBlue 0.1,\r\n      Joint red (-2.2409778), -- (-0.1)\r\n      Link hotPink 0.1 -- Bat\r\n    ]\r\n\r\n-- | Arm to use\r\nstigArm :: Arm\r\nstigArm = mapMotion stigInternalArm stigRest\r\n\r\n-- | Stig Arm Length\r\nstigArmLength :: Float\r\nstigArmLength = armLength stigArm\r\n\r\n-- | Separation from the center of the table\r\nstigFoot :: Float\r\nstigFoot = 1.3\r\n\r\n-- | Stig rest postion\r\nstigRest :: Motion\r\nstigRest = m\r\n  where\r\n    (m, _, _) = fabrikToSegment stigFoot stigInternalArm (ClosedLineSegment (Point2 1.1 0.65 :+()) (Point2 1.1 0.75 :+()))\r\n\r\n-- | Stig rest 2 postion\r\nstigRest2 :: Motion\r\nstigRest2 = m\r\n  where\r\n    (m, _, _) = fabrikToSegment stigFoot stigInternalArm (ClosedLineSegment (Point2 0.9 0.83 :+()) (Point2 0.9 0.93 :+()))\r\n\r\n-- | Get the a zeroed Motion list for Stig's arm\r\nstigNoMotion :: Motion\r\nstigNoMotion = map f stigRest\r\n  where\r\n    f = const 0\r\n\r\n-- | Calculate Motion Velocity to Rest Motion. !Warning: no limits are applied\r\narmToStigRestMotion :: Arm -> Motion\r\narmToStigRestMotion ar = armToMotion ar stigRest \r\n\r\n-- | Calculate Motion Velocity to Rest Motion2. !Warning: no limits are applied\r\narmToStigRestMotion2 :: Arm -> Motion\r\narmToStigRestMotion2 ar = armToMotion ar stigRest2 \r\n\r\n-- | Check collision of moving line and point\r\nstigCollide ::\r\n  forall r.\r\n  (Num r, Floating r, Ord r, Eq r, Show r) =>\r\n  (r, Point 2 r, LineSegment 2 () r) ->\r\n  (r, Point 2 r, LineSegment 2 () r) ->\r\n  IO (Point 2 r)\r\nstigCollide t1 t2 = bool (error \"Stig Collide Failed a Test Case\") (return (f t1 t2)) completeCheck\r\n  where\r\n    f = movingBallMovingLineCollide\r\n    generateTestState :: (Num r, Floating r, Ord r) => r -> (r, r) -> (r, r) -> (r, r) -> (r, Point 2 r, LineSegment 2 () r)\r\n    generateTestState t (px, py) (pl0x, pl0y) (pl1x, pl1y) = (t, Point2 px py, ClosedLineSegment (Point2 pl0x pl0y :+ ()) (Point2 pl1x pl1y :+ ()))\r\n\r\n    testCases =\r\n      [ (Point2 0 0, generateTestState 0 (0, 0) (1, -1) (1, 1), generateTestState 1 (0, 0) (1, -1) (1, 1)),\r\n        (Point2 0 2, generateTestState 0 (0, 0) (0, 0) (1, 0), generateTestState 1 (0, 0) (0, 1) (1, 1)),\r\n        (Point2 0 0, generateTestState 0 (0, 0) (1, -1) (1, 1), generateTestState 1 (2, 0) (1, -1) (1, 1)),\r\n        (Point2 (-1) 0, generateTestState 0 (0, 0) (1, -1) (1, 1), generateTestState 1 (1, 0) (0, -1) (0, 1)),\r\n        (Point2 1 1, generateTestState 0 (0, 0) (0, -1) (2, 1), generateTestState 1 (2, 0) (0, -1) (2, 1)),\r\n        (Point2 (-1) 1, generateTestState 0 (0, 0) (0, -1) (2, 1), generateTestState 1 (0, 0) (-2, -1) (0, 1)),\r\n        (Point2 1.2 0.8, generateTestState 0 (0.3, 1.0) (0.1, 2.1) (-0.5, 0.9), generateTestState 1 (1.2, 0.8) (-0.2, 2.2) (-0.3, 1.1))\r\n        --(Point2 (-6) (-4), generateTestState 0 (-5, -5) (0, 1) (1, 0), generateTestState 1 (5, 7) (0, 1) (1, 0))\r\n      ]\r\n\r\n    checkCollision :: (Num r, Floating r, Ord r, Show r) => (Point 2 r, (r, Point 2 r, LineSegment 2 () r), (r, Point 2 r, LineSegment 2 () r)) -> (Bool, Diff (Point 2) r, Point 2 r)\r\n    checkCollision (ans, s1, s2) = (diffX == 0 && diffY == 0, diff, c)\r\n      where\r\n        c = f s1 s2\r\n        diff = c .-. ans\r\n        diffX = globalThreshold 0 $ abs $ view xComponent diff\r\n        diffY = globalThreshold 0 $ abs $ view yComponent diff\r\n\r\n    performTest :: (Num r, Floating r, Ord r, Show r) => (Point 2 r, (r, Point 2 r, LineSegment 2 () r), (r, Point 2 r, LineSegment 2 () r)) -> Bool\r\n    performTest testCase@(ans, s1, s2) = bool (error showError) True correct\r\n      where\r\n        (correct, diff, p) = checkCollision testCase\r\n        showError =\r\n          \"Expected \" ++ show ans ++ \" but got \"\r\n            ++ show p\r\n            ++ \" with Diff \"\r\n            ++ show diff\r\n            ++ \" \\n\\tFor case:\\n\\t\"\r\n            ++ show s1\r\n            ++ \"\\n\\t->\\n\\t\"\r\n            ++ show s2\r\n\r\n    completeCheck = all performTest testCases\r\n\r\n--test = stigCollide (0, Point2 0 0, ClosedLineSegment (Point2 0 0 :+ ()) (Point2 1 0 :+ ())) (1, Point2 0 0, ClosedLineSegment (Point2 1 0 :+ ()) (Point2 1 0 :+ ()))\r\n--test = stigCollide (0, Point2 (-1) 1, ClosedLineSegment (Point2 0 0 :+ ()) (Point2 1 1 :+ ())) (1, Point2 0 0, ClosedLineSegment (Point2 0 0 :+ ()) (Point2 (-1) 1 :+ ()))\r\n--test = stigCollide (0, Point2 (-1) 1, ClosedLineSegment (Point2 0 (-1) :+ ()) (Point2 1 1 :+ ())) (1, Point2 0 0, ClosedLineSegment (Point2 0 (-1) :+ ()) (Point2 (-1) 1 :+ ()))\r\n\r\nstigAction :: Float -> (Float, Item) -> BallState -> Arm -> IO Motion\r\nstigAction _ (tColl, Net) _ arm =\r\n  return $\r\n    -- Ball hit the net, this means someone scored\r\n    -- Go to rest\r\n    let toBase = armToMotion arm stigNoMotion\r\n     --in trace (\"Someone Scored at \" ++ show tColl) applyMotionLimits toBase -- Velocity limits\r\n     in applyMotionLimits toBase \r\nstigAction _ (tColl, Other _) _ arm =\r\n  return $\r\n    -- Ball hit something out of the game, this means someone scored\r\n    -- Go to rest\r\n    let toBase = armToMotion arm stigNoMotion\r\n     --in trace (\"Someone Scored at \" ++ show tColl) applyMotionLimits toBase -- Velocity limits\r\n     in applyMotionLimits toBase \r\nstigAction _ (tColl, Bat Self) _ arm =\r\n  return $\r\n    -- We hit the ball, go to rest motion\r\n    let toRest2 = armToStigRestMotion2 arm \r\n     --in trace (\"We just hit the ball at \" ++ show tColl) toRest2 -- Velocity limits\r\n     in toRest2\r\nstigAction _ (tColl, Table Opponent) _ arm =\r\n  return $\r\n    -- Our hit was correct and we reached the other player's side\r\n    -- So rest\r\n    let toRest2 = armToStigRestMotion2 arm \r\n     -- in trace (\"We did a proper hit at \" ++ show tColl) toRest2\r\n     in toRest2\r\nstigAction t (tColl, Air) bs arm =\r\n  return $\r\n    -- Invalid State\r\n    let toBase = armToMotion arm stigNoMotion\r\n     -- in trace (\"Impossible State \" ++ show tColl) applyMotionLimits toBase -- Velocity limits\r\n     in applyMotionLimits toBase\r\nstigAction t (tColl, Table Self) bs arm =\r\n    do \r\n      -- Other player did a proper hit we have to respond to \r\n      -- Distance to max point for now\r\n      let p = loc bs\r\n      let v = dir bs\r\n      tryInterceptBall arm p v tColl\r\nstigAction t (tColl, Bat Opponent) bs arm =\r\n  do\r\n\r\n      -- Other player did a hit we have to respond to \r\n      let p = loc bs\r\n      let v = dir bs\r\n\r\n      let mayBounce = predictTableBounce p v\r\n\r\n      case mayBounce of\r\n        {- Nothing -> return $ trace (\"Opponent did a wrong hit at \" ++ show tColl) (armToStigRestMotion arm) -- Velocity limits\r\n        Just (pT, vT, _) -> trace (\"Opponent did a proper hit at \" ++ show tColl) tryInterceptBall arm pT vT tColl -}\r\n        Nothing -> return $ armToStigRestMotion arm\r\n        Just (pT, vT, _) -> tryInterceptBall arm pT vT tColl\r\nstigAction _ (tColl, _) _ arm =\r\n  return $\r\n    -- Ball: Don't know what happened\r\n    -- Go to rest\r\n    let toBase = armToMotion arm stigNoMotion\r\n     --in trace (\"Someone Scored at \" ++ show tColl) applyMotionLimits toBase -- Velocity limits\r\n     in trace (\"Don't know what happened at: \" ++ show tColl) applyMotionLimits toBase \r\n\r\n-- | Stig Plan Threshold\r\nstigPlanThreshold :: (Num r, Ord r, Fractional r) => r -> r -> r\r\nstigPlanThreshold = threshold 0.01\r\n\r\n-- | Calculates the possible motion values to achieve a point. If it fails it returns []\r\nstigPlanPnt :: Float -> Arm -> Point 2 Float -> IO Motion\r\nstigPlanPnt foot arm p\r\n  | isTooFar = trace \"Too Far\" return []\r\n  | stigPlanThreshold 0 eB == 0 = return $ map normalizeAngle qB\r\n  | otherwise = trace (\"Error: \" ++ show eB) return []\r\n  where\r\n    isTooFar = norm (p .-. Point2 foot 0) > 1.2 * armLength arm\r\n    (qB, eB) = fabrikToPoint foot arm p\r\n\r\n-- | Calculates the possible motion values to achieve a line segment. If it fails it returns []\r\nstigPlanSeg :: Float -> Arm -> LineSegment 2 () Float -> IO Motion\r\nstigPlanSeg foot arm s\r\n  | stigPlanThreshold 0 eB == 0 && stigPlanThreshold 0 eBat == 0 = return m\r\n  | otherwise = return []\r\n  where\r\n    (m, eB, eBat) = fabrikToSegment foot arm s\r\n\r\n-- Testing Starts Here\r\n-- | Create a Test Case for stigPlanPnt\r\ncreatePlanPntCase :: Float -> Arm -> (Float, Float) -> Motion -> (Float, Arm, Point 2 Float, Motion)\r\ncreatePlanPntCase f a (xT, yT) m = (f, a, Point2 xT yT, m)\r\n\r\n-- | Test stigPlanPnt\r\ntestPlanPnt :: (Float, Arm, Point 2 Float, Motion) -> IO Bool\r\ntestPlanPnt (f, arm, pT, mT)\r\n  = do\r\n      -- Expected Position\r\n      let qT = motionToJointVector mT\r\n      let xTargetGlobal = pointToHomogenousPoint pT\r\n\r\n      -- Arm\r\n      let (a, _) = getArmKinematicAndMotion f arm\r\n\r\n      -- Calculate Answer\r\n      mB <- stigPlanPnt f arm pT\r\n      if null mB then\r\n        return $ bool (trace \"Wrong Null\" False) (null mT) (null mT)\r\n      else\r\n        do\r\n          let qB = motionToJointVector mB\r\n\r\n          -- Forward Transforms\r\n          let fwdTT = applyForwardKinematicTrans a qT\r\n          let fwdTB = applyForwardKinematicTrans a qB\r\n\r\n          -- Bat Global Position\r\n          let batGlobalB = applyForwardKinematicMatrixTrans fwdTB Numerical.#> homogeneousZero\r\n          let batGlobalT = applyForwardKinematicMatrixTrans fwdTT Numerical.#> homogeneousZero\r\n\r\n          -- Error\r\n          let eB = xTargetGlobal - batGlobalB\r\n          let eNormB = Numerical.norm_2 eB\r\n\r\n          let eT = trace (\"Best \" ++ show (batGlobalB, eNormB, mB)) $ xTargetGlobal - batGlobalT\r\n          let eNormT = Numerical.norm_2 eT\r\n\r\n          let result = trace (\"Target \" ++ show (batGlobalT, eNormT, mT) ++ \"\\n\") $ (globalThreshold 0 eNormB == 0) && (eNormB <= eNormT)\r\n          return $ result && (length mB == length mT)\r\n \r\n-- | Test Cases for testPlanPnt\r\nplanPntTestCases :: [(Float, Arm, Point 2 Float, Motion)]\r\nplanPntTestCases =\r\n  [ createPlanPntCase\r\n      0\r\n      [\r\n        Joint red 0.0,\r\n        Link red 0.1\r\n      ]\r\n      (0, 0.1)\r\n      [0],\r\n    createPlanPntCase\r\n      0\r\n      [\r\n        Joint red 0.0,\r\n        Link red 0.1\r\n      ]\r\n      (0.1, 0)\r\n      [pi/2],\r\n    createPlanPntCase\r\n      1.5\r\n      [ Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.1\r\n      ]\r\n      (1.22385, 0.80917)\r\n      [0.1, 0.2, 0.3, 0.4],\r\n    createPlanPntCase\r\n      1.5\r\n      [ Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.1\r\n      ]\r\n      (1.77615, 0.80917)\r\n      [-0.5, 0.0, 0.4, 0.6],\r\n    createPlanPntCase\r\n      1.5\r\n      [ Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.1\r\n      ]\r\n      (1.48013, 0.89202)\r\n      [0.1, -0.2, 0.3, -0.4],\r\n      createPlanPntCase\r\n      1.5\r\n      [ Link red 0.1,\r\n        Joint red 0.0,\r\n        Link red 0.1,\r\n        Joint red 0.0,\r\n        Link red 0.1\r\n      ]\r\n      (1.5, 0)\r\n      [2.094,2.094],\r\n      createPlanPntCase\r\n      1.5\r\n      [ Link red 0.1,\r\n        Joint red 0.0,\r\n        Link red 0.1,\r\n        Joint red 0.0,\r\n        Link red 0.1\r\n      ]\r\n      (1.5, 0)\r\n      [2.094,2.094]\r\n  ]\r\n\r\n-- | Executes testPlanPnt\r\nexecutePlanPntTestCases :: IO Bool\r\nexecutePlanPntTestCases = foldM f True planPntTestCases\r\n  where\r\n    f True params = testPlanPnt params\r\n    f False _ = return False\r\n\r\n\r\n-- | Create a Test Case for stigPlanSeg\r\ncreatePlanSegCase :: Float -> Arm -> (Float, Float) -> (Float, Float) -> Motion -> (Float, Arm, LineSegment 2 () Float, Motion)\r\ncreatePlanSegCase f a (xP0, yP0) (xP1, yP1) m = (f, a, ClosedLineSegment (Point2 xP0 yP0 :+ ()) (Point2 xP1 yP1 :+ ()), m)\r\n\r\n-- | Test stigPlanSeg\r\ntestPlanSeg :: (Float, Arm, LineSegment 2 () Float, Motion) -> IO Bool\r\ntestPlanSeg (f, arm, sT, mT)\r\n  = \r\n    do\r\n      -- Expected Position\r\n      let pT = sT ^. (end . core)\r\n      let qT = motionToJointVector mT\r\n      let xTargetGlobal = pointToHomogenousPoint pT\r\n\r\n      -- Arm\r\n      let (a, _) = getArmKinematicAndMotion f arm\r\n\r\n      -- Calculate Answer\r\n      mB <- stigPlanSeg f arm sT\r\n      if null mB then\r\n        return $ bool (trace \"Wrong Null\" False) (null mT) (null mT)\r\n      else\r\n        do\r\n          let qB = motionToJointVector mB\r\n\r\n          -- Forward Transforms\r\n          let fwdTT = applyForwardKinematicTrans a qT\r\n          let fwdTB = applyForwardKinematicTrans a qB\r\n\r\n          -- Bat Global Position\r\n          let batGlobalB = applyForwardKinematicMatrixTrans fwdTB Numerical.#> homogeneousZero\r\n          let batGlobalT = applyForwardKinematicMatrixTrans fwdTT Numerical.#> homogeneousZero\r\n\r\n          -- Error\r\n          let eB = xTargetGlobal - batGlobalB\r\n          let eNormB = Numerical.norm_2 eB\r\n\r\n          let eT = trace (\"Best \" ++ show (batGlobalB, eNormB, mB)) $ xTargetGlobal - batGlobalT\r\n          let eNormT = Numerical.norm_2 eT\r\n\r\n          let result = trace (\"Target \" ++ show (batGlobalT, eNormT, mT)) $\r\n                (globalThreshold 0 eNormB == 0)\r\n                  && ((eNormB <= eNormT) || (eNormT > 0 && eNormB / eNormT <= 1.1) || (eNormT == 0 && globalThreshold 0 eNormB == 0))\r\n          return $ result && bool (trace \"Different Motion Sizes\" False) True (length mB == length mT)\r\n\r\n-- | Test Cases for testPlanPnt\r\nplanSegTestCases :: [(Float, Arm, LineSegment 2 () Float, Motion)]\r\nplanSegTestCases =\r\n  [ createPlanSegCase\r\n      1.5\r\n      [ Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.1\r\n      ]\r\n      (1.48023, 0.79501)\r\n      (1.48023, 0.89501)\r\n      [0.2, -0.2, -0.1, 0.1],\r\n    createPlanSegCase\r\n      1.5\r\n      [ Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.2,\r\n        Joint red 0.0,\r\n        Link red 0.1\r\n      ]\r\n      (1.71174, 0.75003)\r\n      (1.66379, 0.83779)\r\n      [-0.5, 0.0, 0.4, 0.6],\r\n    createPlanSegCase\r\n      1.5\r\n      [ Link red 0.1,\r\n        Joint red 0.0,\r\n        Link red 0.1,\r\n        Joint red 0.0,\r\n        Link red 0.1\r\n      ]\r\n      (1.4134, 5.0e-2)\r\n      (1.5, 0)\r\n      [2.094,2.094]\r\n  ]\r\n\r\n\r\n-- | Executes testPlanSeg\r\nexecutePlanSegTestCases :: IO Bool\r\nexecutePlanSegTestCases = foldM f True planSegTestCases\r\n  where\r\n    f True params = testPlanSeg params\r\n    f False _ = return False\r\n \r\n", "meta": {"hexsha": "9191961c07c0b730fcd9ba69e6f3367ffaaa3c23", "size": 27351, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PingPong/Player/Stig.hs", "max_stars_repo_name": "maniatic0/Motion-Manipulation-Project", "max_stars_repo_head_hexsha": "a4818a4362cced5a67c29683161044477d7ce087", "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/PingPong/Player/Stig.hs", "max_issues_repo_name": "maniatic0/Motion-Manipulation-Project", "max_issues_repo_head_hexsha": "a4818a4362cced5a67c29683161044477d7ce087", "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/PingPong/Player/Stig.hs", "max_forks_repo_name": "maniatic0/Motion-Manipulation-Project", "max_forks_repo_head_hexsha": "a4818a4362cced5a67c29683161044477d7ce087", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9109311741, "max_line_length": 188, "alphanum_fraction": 0.6088625644, "num_tokens": 8473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.47806033147896027}}
{"text": "{-# LANGUAGE RankNTypes #-}\n\nmodule Observable.MCMC.AffineInvariantEnsemble where\n\nimport Control.Monad.Primitive\nimport Control.Monad.State.Strict\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector.Unboxed as V\nimport Observable.Core\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal\n\ntype Ensemble = Vector [Double]\n\n-- | Generate a random value from a distribution having the property that \n--   g(1/z) = z g(z).\nsymmetricVariate :: PrimMonad m => Observable m Double\nsymmetricVariate = do\n  z <- unit\n  return $ 0.5 * (z + 1) ^ 2\n\nperturbParticle w0 w1 = do\n  zs <- replicateM (length w0) symmetricVariate\n\nV.zipWith (+) (V.map (* z) w0) (V.map (* (1 - z)) w1)\n\n\n-- acceptanceRatio\n--   :: [Double] -> [Double]\n--   -> Double -> Double\n--   -> ([Double] -> Double)\n--   -> ([Double], Int)\n-- acceptanceRatio target w0 w1 z zc = \n--   let val      = target proposal - target w0 + (fromIntegral (length w0) - 1) * log z\n--       proposal = zipWith (+) (map (*z) w0) (map (*(1-z)) w1) \n--   in  if zc <= min 1 (exp val) then (proposal, 1) else (w0, 0)\n-- \n-- -- | Calculate the acceptance ratio for a proposed move.\n-- acceptRejectRatio\n--   :: Target Double -> Double -> Vector Double -> Vector Double -> Double\n-- acceptRejectRatio target e current proposed = exp . min 0 $\n--     logObjective target proposed + log (isoGauss current proposed e)\n--   - logObjective target current  - log (isoGauss proposed current e)\n\n\n", "meta": {"hexsha": "0ac38959b18c801bf639b95c0226cce9d87f74df", "size": 1456, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Observable/MCMC/AffineInvariantEnsemble.hs", "max_stars_repo_name": "jtobin/deprecated-observable", "max_stars_repo_head_hexsha": "66ef6b510896d66d812467e6bfbe96bcdc195340", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-10T03:12:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-10T03:12:49.000Z", "max_issues_repo_path": "src/Observable/MCMC/AffineInvariantEnsemble.hs", "max_issues_repo_name": "jtobin/deprecated-observable", "max_issues_repo_head_hexsha": "66ef6b510896d66d812467e6bfbe96bcdc195340", "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/Observable/MCMC/AffineInvariantEnsemble.hs", "max_forks_repo_name": "jtobin/deprecated-observable", "max_forks_repo_head_hexsha": "66ef6b510896d66d812467e6bfbe96bcdc195340", "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.652173913, "max_line_length": 88, "alphanum_fraction": 0.6710164835, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4780603219802569}}
{"text": "{-# LANGUAGE RankNTypes #-}\n\nmodule Sim\n  ( State (..),\n    Plant (..),\n    Measurement (..),\n    simulate,\n  )\nwhere\n\nimport Numeric.LinearAlgebra\n\ntype Measurement = Vector Double\n\ntype State = Vector Double\n\ndata Plant = Plant {fA, fC, fB, fD :: forall a. Floating a => ([a] -> [a])}\n\nsimulate :: Plant -> State -> Int -> [(State, Measurement)]\nsimulate (Plant fA fB fC fD) x n = (x', y') : simulate (Plant fA fB fC fD) xh (n + 1)\n  where\n    x' = vector $ fA (toList x)\n    y = vector $ fC (toList x')\n    xh = x' + scale 0.0001 (randomVector (n + 1000) Gaussian (size x))\n    y' = y + scale 0.5 (randomVector n Gaussian (size y))\n", "meta": {"hexsha": "ced4f22f85d6fc24eca29b45f20e019c3e2fb132", "size": 635, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Estimation/Sim.hs", "max_stars_repo_name": "matte1/halman", "max_stars_repo_head_hexsha": "1b00010c300de931889c61bbb12141fad7285c65", "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/Estimation/Sim.hs", "max_issues_repo_name": "matte1/halman", "max_issues_repo_head_hexsha": "1b00010c300de931889c61bbb12141fad7285c65", "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/Estimation/Sim.hs", "max_forks_repo_name": "matte1/halman", "max_forks_repo_head_hexsha": "1b00010c300de931889c61bbb12141fad7285c65", "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": 24.4230769231, "max_line_length": 85, "alphanum_fraction": 0.5937007874, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47766027425151264}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule PLC1 (PLC1(..)) where\n\nimport Control.Applicative\nimport Control.Comonad\nimport Control.Comonad.Store\nimport Control.Exception (assert)\n-- import Control.Monad\n-- import Data.Distributive\nimport Data.Proxy\nimport Data.Unfoldable\nimport Data.Validity\nimport qualified Data.Vector as V\nimport Data.VectorSpace\nimport GHC.TypeLits\n-- import Linear.Metric\n-- import Linear.Vector\nimport qualified Numeric.LinearAlgebra as L\nimport qualified Test.QuickCheck as QC\nimport qualified Test.QuickCheck.Function as QC\n\nimport ComonadicVector\nimport Function\nimport Integration\n\n\n\n-- https://hackage.haskell.org/package/polynomial-0.7.3\n\nnewtype PLC1 (n' :: Nat) c s = PLC1\n  { getPLC1 :: ComonadicVector V.Vector s\n  } deriving (Eq, Ord, Read, Show, Foldable, Functor, Traversable)\n\ninstance (KnownNat n', Validity s) => Validity (PLC1 n' c s) where\n    validate (PLC1 xs) =\n        mconcat\n        [ n > 0 <?@> \"length is positive\"\n        , length xs == n <?@> \"vector has correct length \"\n        , xs <?!> \"vector\"\n        ]\n        where n = fromInteger (natVal (Proxy :: Proxy n'))\n    isValid = isValidByValidating\n\ninstance KnownNat n' => Unfoldable (PLC1 n' c) where\n    -- unfold xs = PLC1 <$> unfold xs\n    -- unfold xs = (PLC1 . ComonadicVector 0 . V.fromListN n) <$> mklist n\n    --     where n = fromInteger (natVal (Proxy :: Proxy n')) :: Int\n    --           mklist i | i == 0 = pure []\n    --                    | otherwise = (:) <$> xs <*> mklist (i-1)\n    unfold xs = PLC1 . goodlength <$> unfold xs\n        where n = fromInteger (natVal (Proxy :: Proxy n')) :: Int\n              goodlength ys = assert (n > 0 && length ys == n) ys\n\ninstance (Applicative (ComonadicVector V.Vector), KnownNat n') =>\n         Applicative (PLC1 n' c) where\n  -- pure x = PLC1 (pure x)\n  -- Note: 'pure' should use the neutral element of the monoid used\n  -- for 'pos_' in '(<*>)'\n  pure x = PLC1 (ComonadicVector (n - 1) (V.replicate n x))\n      where n = fromInteger (natVal (Proxy :: Proxy n'))\n  PLC1 fs <*> PLC1 xs = PLC1 (fs <*> xs)\n\n-- instance (Alternative (ComonadicVector V.Vector), KnownNat n') =>\n--          Alternative (PLC1 n' c) where\n--   empty = PLC1 empty\n--   PLC1 xs <|> PLC1 ys = PLC1 (xs <|> ys)\n\n-- instance Monad (ComonadicVector V.Vector) => Monad (PLC1 n' c) where\n--     -- (>>=) :: PLC1 n' c s -> (s -> PLC1 n' c t) -> PLC1 n' c t\n--     PLC1 x >>= f = PLC1 (x >>= getPLC1 . f)\n-- \n-- instance MonadPlus (ComonadicVector V.Vector) => MonadPlus (PLC1 n' c) where\n--     mzero = PLC1 mzero\n--     PLC1 xs `mplus` PLC1 ys = PLC1 (xs `mplus` ys)\n\n-- instance Distributive (ComonadicVector V.Vector) =>\n--          Distributive (PLC1 n' c) where\n--   collect f arr = PLC1 (collect (getPLC1 . f) arr)\n\ninstance Comonad (ComonadicVector V.Vector) => Comonad (PLC1 n' c) where\n  extract (PLC1 arr) = extract arr\n  extend f (PLC1 arr) = PLC1 (extend (f . PLC1) arr)\n\ninstance ComonadStore Int (ComonadicVector V.Vector) =>\n         ComonadStore Int (PLC1 n' c) where\n  pos (PLC1 arr) = pos arr\n  peek i (PLC1 arr) = peek i arr\n\n\n\ninstance (KnownNat n', QC.Arbitrary s) => QC.Arbitrary (PLC1 n' c s) where\n  -- arbitrary = do\n  --   arr <- QC.arbitrary\n  --   return (PLC1 arr)\n  -- shrink (PLC1 arr) = [PLC1 arr' | arr' <- QC.shrink arr]\n  -- arbitrary = arbitraryDefault\n  arbitrary = do\n      xs <- V.generateM n (const QC.arbitrary)\n      i <- QC.choose (0, V.length xs - 1)\n      return (PLC1 (ComonadicVector i xs))\n      where n = fromInteger (natVal (Proxy :: Proxy n'))\n  shrink arr = [arr' | pos arr > 0] ++ traverse QC.shrink arr'\n      where arr' = seek 0 arr\n\ninstance QC.CoArbitrary s => QC.CoArbitrary (PLC1 n' c s) where\n    coarbitrary = QC.coarbitrary . getPLC1\n\ninstance QC.Function s => QC.Function (PLC1 n' c s) where\n    function = QC.functionMap getPLC1 PLC1\n\n\n\n-- instance Additive (ComonadicVector V.Vector) => Additive (PLC1 n' c) where\n--     zero = PLC1 zero\n-- \n-- instance (Additive (PLC1 n' c), Bounded c, RealFrac c) => Metric (PLC1 n' c) where\n--     -- dot :: Num a => f a -> f a -> a\n--     dot xs ys =\n--         assert (length ys == n) $\n--         case n of\n--           0 -> 0\n--           _ -> sum [w i * peek i xs * peek i ys | i <- [0 .. n-1]]\n--         where n = length xs\n--               xmin = minBound :: c\n--               xmax = maxBound :: c\n--               w i = realToFrac (weight n xmin xmax i)\n\ninstance ( KnownNat n'\n         , AdditiveGroup (ComonadicVector V.Vector s)\n         , AdditiveGroup s\n         ) =>\n         AdditiveGroup (PLC1 n' c s) where\n  zeroV = pure zeroV\n  negateV = fmap negateV\n  (^+^) = liftA2 (^+^)\n\ninstance ( KnownNat n'\n         , VectorSpace (ComonadicVector V.Vector s)\n         , VectorSpace s\n         ) =>\n         VectorSpace (PLC1 n' c s) where\n  type Scalar (PLC1 n' c s) = Scalar s\n  (*^) x = fmap (x *^)\n\n-- instance ( KnownNat n'\n--          , Bounded c\n--          , RealFrac c\n--          , InnerSpace s\n--          , VectorSpace (Scalar s)\n--          , Fractional (Scalar (Scalar s))\n--          ) =>\n--          InnerSpace (PLC1 n' c s) where\n--   -- xs <.> ys =\n--   --   assert (length ys == length xs) $ sumV (weighted ((<.>) <$> xs <*> ys))\n\ninstance ( KnownNat n'\n         , Integrable (PLC1 n')\n         , IntegrableOk (PLC1 n') c s\n         , Bounded c\n         , RealFrac c\n         , InnerSpace s\n         , Fractional (Scalar s)\n         ) => InnerSpace (PLC1 n' c s) where\n  xs <.> ys = getPLC1 (extend weighted xs) <.> getPLC1 ys\n    where\n      weighted zs = weight n (xmin, xmax) (pos zs) *^ extract zs\n      -- n = length xs\n      n = fromInteger (natVal (Proxy :: Proxy n'))\n      (xmin, xmax) = bounds xs\n\n\n\ninstance Function (PLC1 n') where\n  type FunctionOk (PLC1 n') a b = ( KnownNat n'\n                                  , Bounded a\n                                  , RealFrac a\n                                  , InnerSpace b\n                                  , Floating (Scalar b)\n                                  , Ord (Scalar b)\n                                  , b ~ Double) -- TODO\n  eval (PLC1 arr) x =\n    case n of\n      0 -> zeroV\n      1 -> extract arr\n      _ ->\n        let y = ((x - cx) / rx + 1) / 2 * fromIntegral (n - 1)\n            i = max 0 $ min (n - 2) $ floor y\n            f0 = 1 - f1\n            f1 = realToFrac (y - fromIntegral i)\n        in f0 *^ peek i arr ^+^ f1 *^ peek (i + 1) arr\n    where\n      -- n = length arr\n      n = fromInteger (natVal (Proxy :: Proxy n'))\n      xmin = minBound `asTypeOf` x\n      xmax = maxBound `asTypeOf` x\n      cx = (xmax + xmin) / 2\n      rx = (xmax - xmin) / 2\n\ninstance KnownNat n' => Discretization (PLC1 n') where\n  discretized f = PLC1 (ComonadicVector 0 res)\n    where\n      n = fromInteger (natVal (Proxy :: Proxy n'))\n      -- res = V.generate n go\n      -- TODO: use (symmetric) triangular solver\n      rhs = L.vector [go i | i <- [0..n-1]]\n      mat = L.matrix n [ overlap n (xmin, xmax) i j\n                       | i <- [0..n-1], j <- [0..n-1]]\n      res = V.fromListN n $ L.toList $ mat L.<\\> rhs\n      (xmin, xmax) = (minBound, maxBound)\n      _ = (f xmin, f xmax)      -- constrain types\n      go i = integrate bf lo hi\n        where\n          bf x = b x *^ f x\n          b x = basis n (xmin, xmax) i x\n          (lo, hi) = support n (xmin, xmax) i\n\ninstance KnownNat n' => Integrable (PLC1 n') where\n  type IntegrableOk (PLC1 n') a b = ()\n  integral xs = sumV (extend weighted xs)\n    where\n      weighted ys = weight n (xmin, xmax) (pos ys) *^ extract ys\n      -- n = length xs\n      n = fromInteger (natVal (Proxy :: Proxy n'))\n      (xmin, xmax) = bounds xs\n\ninstance Differentiable (PLC1 n') where\n  type DifferentiableOk (PLC1 n') a b = ()\n  type Dir (PLC1 n') = ()\n  boundary () xs = extend bndry xs\n    where\n      bndry ys\n        | n == 1     = zeroV *^ extract ys -- or zeroV\n        | i == 0     = negateV (extract ys ^/ realToFrac dx)\n        | i == n - 1 = extract ys ^/ realToFrac dx\n        | otherwise  = zeroV *^ extract ys -- or zeroV\n        where\n          i = pos ys\n      -- n = length xs\n      n = fromInteger (natVal (Proxy :: Proxy n'))\n      (xmin, xmax) = bounds xs\n      rx = (xmax - xmin) / 2\n      hdx = rx / fromIntegral (n - 1)\n      dx = 2 * hdx\n  derivative () xs = extend deriv xs\n    where\n      deriv ys\n        | n == 1     = zeroV *^ extract ys -- or zeroV\n        | i == 0     = (peek (i + 1) ys ^-^ extract ys) ^/ realToFrac dx\n        | i == n - 1 = (extract ys ^-^ peek (i - 1) ys) ^/ realToFrac dx\n        | otherwise  =\n            (peek (i + 1) ys ^-^ peek (i - 1) ys) ^/ realToFrac (2 * dx)\n        where\n          i = pos ys\n      -- n = length xs\n      n = fromInteger (natVal (Proxy :: Proxy n'))\n      (xmin, xmax) = bounds xs\n      rx = (xmax - xmin) / 2\n      hdx = rx / fromIntegral (n - 1)\n      dx = 2 * hdx\n\ntriangle :: (Num a, Ord a) => a -> a\ntriangle x = max 0 (1 - abs x)\n\ntyped :: f a b -> a -> a\ntyped _ = id\n\nbounds :: Bounded a => f a b -> (a, a)\nbounds xs = (typed xs minBound, typed xs maxBound)\n\n-- The basis functions are defined to have a maximum of '1'\nbasis :: (RealFrac a, Fractional b) => Int -> (a, a) -> Int -> a -> b\nbasis n (xmin, xmax) i x | n == 1    = 1\n                         | otherwise = realToFrac (triangle y)\n  where\n    cx  = (xmin + xmax) / 2\n    rx  = (xmax - xmin) / 2\n    hdx = rx / fromIntegral (n - 1)\n    xi  = cx + hdx * fromIntegral (2 * i + 1 - n)\n    dx  = 2 * hdx\n    y   = (x - xi) / dx\n\nsupport :: (Fractional a, Ord a) => Int -> (a, a) -> Int -> (a, a)\nsupport n (xmin, xmax) i | n == 1    = (xmin, xmax)\n                         | otherwise = (max xmin (xi - dx), min xmax (xi + dx))\n  where\n    cx  = (xmin + xmax) / 2\n    rx  = (xmax - xmin) / 2\n    hdx = rx / fromIntegral (n - 1)\n    xi  = cx + hdx * fromIntegral (2 * i + 1 - n)\n    dx  = 2 * hdx\n\n-- Volume\nweight :: (RealFrac a, Fractional b) => Int -> (a, a) -> Int -> b\nweight n (xmin, xmax) i | n == 1     = realToFrac (2 * rx)\n                        | i == 0     = realToFrac hdx\n                        | i == n - 1 = realToFrac hdx\n                        | otherwise  = realToFrac (2 * hdx)\n  where\n    rx  = (xmax - xmin) / 2\n    hdx = rx / fromIntegral (n - 1)\n\noverlap :: (RealFrac a, Fractional b) => Int -> (a, a) -> Int -> Int -> b\noverlap n (xmin, xmax) i j\n    | n == 1                           = realToFrac (2 * rx)\n    | i == j && (i == 0 || i == n - 1) = realToFrac (2 / 3 * hdx)\n    | i == j                           = realToFrac (4 / 3 * hdx)\n    | abs (i - j) == 1                 = realToFrac (1 / 3 * hdx)\n    | otherwise                        = 0\n  where\n    rx  = (xmax - xmin) / 2\n    hdx = rx / fromIntegral (n - 1)\n", "meta": {"hexsha": "f94bae072806be804bb58bfca7bcce473869f0c8", "size": 10964, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "library/PLC1.hs", "max_stars_repo_name": "eschnett/wavetoy3", "max_stars_repo_head_hexsha": "3a1a36e7cb2be4d907de78bae49872bb7178ebee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "library/PLC1.hs", "max_issues_repo_name": "eschnett/wavetoy3", "max_issues_repo_head_hexsha": "3a1a36e7cb2be4d907de78bae49872bb7178ebee", "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": "library/PLC1.hs", "max_forks_repo_name": "eschnett/wavetoy3", "max_forks_repo_head_hexsha": "3a1a36e7cb2be4d907de78bae49872bb7178ebee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.049689441, "max_line_length": 85, "alphanum_fraction": 0.533017147, "num_tokens": 3493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.47760165437523305}}
{"text": "{-# LANGUAGE BangPatterns, FlexibleContexts, UnboxedTuples #-}\n-- |\n-- Module    : Statistics.Sample.KernelDensity\n-- Copyright : (c) 2011 Bryan O'Sullivan\n-- License   : BSD3\n--\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : portable\n--\n-- Kernel density estimation.  This module provides a fast, robust,\n-- non-parametric way to estimate the probability density function of\n-- a sample.\n--\n-- This estimator does not use the commonly employed \\\"Gaussian rule\n-- of thumb\\\".  As a result, it outperforms many plug-in methods on\n-- multimodal samples with widely separated modes.\n\nmodule Statistics.Sample.KernelDensity\n    (\n    -- * Estimation functions\n      kde\n    -- , kde_\n    -- * References\n    -- $references\n    ) where\n\nimport Numeric.MathFunctions.Constants (m_sqrt_2_pi)\nimport Prelude hiding (const, min, max, sum)\nimport Statistics.Function (minMax, nextHighestPowerOfTwo)\nimport Statistics.Math.RootFinding (fromRoot, ridders)\nimport Statistics.Sample.Histogram (histogram_)\nimport Statistics.Sample.Internal (sum)\nimport Statistics.Transform (CD, dct, idct)\nimport qualified Data.Vector.Generic  as G\nimport qualified Data.Vector.Unboxed  as U\nimport qualified Data.Vector          as V\n\n\n-- | Gaussian kernel density estimator for one-dimensional data, using\n-- the method of Botev et al.\n--\n-- The result is a pair of vectors, containing:\n--\n-- * The coordinates of each mesh point.  The mesh interval is chosen\n--   to be 20% larger than the range of the sample.  (To specify the\n--   mesh interval, use 'kde_'.)\n--\n-- * Density estimates at each mesh point.\nkde :: (G.Vector v CD, G.Vector v Double, G.Vector v Int)\n    => Int\n    -- ^ The number of mesh points to use in the uniform discretization\n    -- of the interval @(min,max)@.  If this value is not a power of\n    -- two, then it is rounded up to the next power of two.\n    -> v Double -> (v Double, v Double)\nkde n0 xs = kde_ n0 (lo - range / 10) (hi + range / 10) xs\n  where\n    (lo,hi) = minMax xs\n    range   | G.length xs <= 1 = 1       -- Unreasonable guess\n            | lo == hi         = 1       -- All elements are equal\n            | otherwise        = hi - lo\n{-# INLINABLE  kde #-}\n{-# SPECIAlIZE kde :: Int -> U.Vector Double -> (U.Vector Double, U.Vector Double) #-}\n{-# SPECIAlIZE kde :: Int -> V.Vector Double -> (V.Vector Double, V.Vector Double) #-}\n\n\n-- | Gaussian kernel density estimator for one-dimensional data, using\n-- the method of Botev et al.\n--\n-- The result is a pair of vectors, containing:\n--\n-- * The coordinates of each mesh point.\n--\n-- * Density estimates at each mesh point.\nkde_ :: (G.Vector v CD, G.Vector v Double, G.Vector v Int)\n     => Int\n     -- ^ The number of mesh points to use in the uniform discretization\n     -- of the interval @(min,max)@.  If this value is not a power of\n     -- two, then it is rounded up to the next power of two.\n     -> Double\n     -- ^ Lower bound (@min@) of the mesh range.\n     -> Double\n     -- ^ Upper bound (@max@) of the mesh range.\n     -> v Double\n     -> (v Double, v Double)\nkde_ n0 min max xs\n  | G.null xs = error \"Statistics.KernelDensity.kde: empty sample\"\n  | n0 <= 1   = error \"Statistics.KernelDensity.kde: invalid number of points\"\n  | otherwise = (mesh, density)\n  where\n    mesh = G.generate ni $ \\z -> min + (d * fromIntegral z)\n        where d = r / (n-1)\n    density = G.map (/(2 * r)) . idct $ G.zipWith f a (G.enumFromTo 0 (n-1))\n      where f b z = b * exp (sqr z * sqr pi * t_star * (-0.5))\n    !n  = fromIntegral ni\n    !ni = nextHighestPowerOfTwo n0\n    !r  = max - min\n    a   = dct . G.map (/ sum h) $ h\n        where h = G.map (/ len) $ histogram_ ni min max xs\n    !len    = fromIntegral (G.length xs)\n    !t_star = fromRoot (0.28 * len ** (-0.4)) . ridders 1e-14 (0,0.1) $ \\x ->\n              x - (len * (2 * sqrt pi) * go 6 (f 7 x)) ** (-0.4)\n      where\n        f q t = 2 * pi ** (q*2) * sum (G.zipWith g iv a2v)\n          where g i a2 = i ** q * a2 * exp ((-i) * sqr pi * t)\n                a2v = G.map (sqr . (*0.5)) $ G.tail a\n                iv = G.map sqr $ G.enumFromTo 1 (n-1)\n        go s !h | s == 1    = h\n                | otherwise = go (s-1) (f s time)\n          where time  = (2 * const * k0 / len / h) ** (2 / (3 + 2 * s))\n                const = (1 + 0.5 ** (s+0.5)) / 3\n                k0    = U.product (G.enumFromThenTo 1 3 (2*s-1)) / m_sqrt_2_pi\n    sqr x = x * x\n{-# INLINABLE  kde_ #-}\n{-# SPECIAlIZE kde_ :: Int -> Double -> Double -> U.Vector Double -> (U.Vector Double, U.Vector Double) #-}\n{-# SPECIAlIZE kde_ :: Int -> Double -> Double -> V.Vector Double -> (V.Vector Double, V.Vector Double) #-}\n\n\n-- $references\n--\n-- Botev. Z.I., Grotowski J.F., Kroese D.P. (2010). Kernel density\n-- estimation via diffusion. /Annals of Statistics/\n-- 38(5):2916&#8211;2957. <http://arxiv.org/pdf/1011.2602>\n", "meta": {"hexsha": "ac38785441f76e15f365a549b121867e9a88483b", "size": 4851, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "statistics/Statistics/Sample/KernelDensity.hs", "max_stars_repo_name": "runeksvendsen/hs-gauge", "max_stars_repo_head_hexsha": "496a8b99e7fee3039fd89ecef7305d31eb5d5a6d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 94, "max_stars_repo_stars_event_min_datetime": "2017-10-29T16:51:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T08:36:20.000Z", "max_issues_repo_path": "statistics/Statistics/Sample/KernelDensity.hs", "max_issues_repo_name": "runeksvendsen/hs-gauge", "max_issues_repo_head_hexsha": "496a8b99e7fee3039fd89ecef7305d31eb5d5a6d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 77, "max_issues_repo_issues_event_min_datetime": "2017-09-30T15:11:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T09:34:12.000Z", "max_forks_repo_path": "statistics/Statistics/Sample/KernelDensity.hs", "max_forks_repo_name": "runeksvendsen/hs-gauge", "max_forks_repo_head_hexsha": "496a8b99e7fee3039fd89ecef7305d31eb5d5a6d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-11-04T13:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T05:44:23.000Z", "avg_line_length": 39.1209677419, "max_line_length": 107, "alphanum_fraction": 0.6101834673, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.47731995236311275}}
{"text": "{-# LANGUAGE MultiWayIf #-}\nmodule Test.BigOh.Fit.Hakaru\n  ( -- * Complexity defs\n    Coefficient\n  , Order(..)\n  , Fit(..)\n  , knownOrders\n  , exponential\n  , constant\n  , linear\n  , quadratic\n  , cubic\n  , nlogn\n  , poly1d\n\n  -- * Fitting curves\n  , bestFit\n  , fit\n  ) where\n\nimport           Control.Arrow\nimport           Control.Monad\nimport           Data.Dynamic\nimport           Data.List\nimport           Data.Monoid\nimport           Data.Ord\nimport qualified Data.Vector                  as V\nimport           Language.Hakaru.Distribution\nimport           Language.Hakaru.Metropolis\nimport           Language.Hakaru.Types\nimport qualified Statistics.Sample            as S\n\nimport           Test.BigOh.Fit.Base\n\n\ndata Fit\n  = Fit { xVals :: [Double]\n        , yVals :: [Double]\n        , burnN :: Int\n        , takeN :: Int\n        }\n\n-- | Given a complexity order and some data,\n--   determine if the order best describes the data.\nfit :: (Order -> Bool) -> [Order] -> [Double] -> [Double] -> IO Bool\nfit predi orders xs ys\n  = go (50 :: Int) burnStart takeStart\n  where\n   burnStart = 10000\n   takeStart = 1000\n   go try b t\n    = do ranked    <- bestFit' orders (Fit xs ys b t)\n         putStrLn (\"ranked: \" <> show (fmap (first name) ranked))\n         let order' = fst $ head ranked\n         if | predi order'              -> return True\n            | try        == 0           -> return False\n            | otherwise                 -> go (try - 1) (b * 2) (t * 2)\n\n-- | Find the complexity order that best fits the data.\n--\nbestFit :: [Order] -> Fit ->  IO Order\nbestFit orders f\n  = fst . head <$> bestFit' orders f\n\nbestFit' :: [Order] -> Fit ->  IO [(Order, Double)]\nbestFit' orders f@(Fit xs ys _ _)\n  = do fits   <- mapM (`curveFit` f) orders\n       let fs  = fmap (<$> xs) fits\n           rs  = fmap (rSquared ys) fs\n           rs' = zip orders rs\n           rs''= sortBy (comparing snd) rs'\n       return rs''\n\n-- | Given a complexity order and some data, generate a curve of\n--   that order that fit the data.\n--\ncurveFit :: Order -> Fit -> IO (Double -> Double)\ncurveFit thing (Fit xs ys dropn taken)\n = do l <- mcmc (measureForOrder thing xs ys)\n                (map (Just . toDyn . Lebesgue) ys)\n      let means = expectations $ take taken $ drop dropn l\n      return $ mkCurve thing means\n\n-- | Create a sampler for a class of curves with some x values.\n--   e.g. sample @y = a*x^2 + b*x +c@\n--\nmeasureForOrder :: Order -> [Double] -> [Double] -> Measure [Double]\nmeasureForOrder order xs ys\n  = measureForOrder' 0 (maximum $ fmap abs ys) (sd ys) order xs\n\nmeasureForOrder' :: Double -> Double -> Double -> Order -> [Double] -> Measure [Double]\nmeasureForOrder' mean range sdev (Order _ n func) xs\n  = do w <- replicateM n $ unconditioned (normal mean range)\n       y <- mapM (conditioned . withinNormal w) xs\n       return w\n  where\n   withinNormal w x\n     = normal (func w x) sdev\n\n-- | Given a bunch of possible coefficient sets, return the\n--   expected value of each coeffient.\n--   e.g. for @a*x^2 + b^x + c@,some possible coffients might be:\n--        @[[a=0,b=1,c=4], [a=3,b=4,c=2]]@, @expectations@ returns\n--        the expected values for @a, b, c@.\n--\nexpectations :: [[Double]] -> [Double]\nexpectations l = map (S.mean . V.fromList) (transpose l)\n\n--------------------------------------------------------------------------------\n\ntype Coefficient = Double\n\n-- | A complexity order, e.g. exponential, quadratic.\ndata Order\n  = Order\n    { name      :: String\n    , numCoeffs :: Int\n    , mkCurve   :: [Coefficient] -> Double -> Double\n    }\n\nknownOrders :: [Order]\nknownOrders = [exponential, constant, linear, quadratic, cubic, nlogn]\n\nexponential :: Order\nexponential\n  = Order \"exp\" 4 $ \\[a, b, c, d] x -> a * (2 ** (b * x + c)) + d\n\nconstant :: Order\nconstant\n  = Order \"constant\" 1 poly1d\n\nlinear :: Order\nlinear\n  = Order \"linear\" 2 poly1d\n\nquadratic :: Order\nquadratic\n  = Order \"quadratic\" 3 poly1d\n\ncubic :: Order\ncubic\n  = Order \"cubic\" 4 poly1d\n\nnlogn :: Order\nnlogn\n  = Order \"nlogn\" 2\n  $ \\[a, b] n -> a * n * log  n + b\n\npoly1d :: [Double] -> Double -> Double\npoly1d weights a = poly weights a 1\n   where\n     poly [] _ _ = 0\n     poly (w:ws) x acc = w*acc + (poly ws x acc*x)\n\nsquare :: Num a => a -> a\nsquare x = x * x\n\nrSquared\n  :: [Double] -- ^ data set y1..yn\n  -> [Double] -- ^ model f1..fn\n  -> Double   -- ^ r squared\nrSquared ys fs\n = let yBar  = sum ys / fromIntegral (length ys)\n       ssTot = sum (fmap (square . subtract yBar) ys)\n       ssRes = sum (fmap square (zipWith (-) ys fs))\n   in  (ssTot - ssRes) / ssTot\n", "meta": {"hexsha": "79e9746f8e0159c092ff2f5960dec64d6a3b15c0", "size": 4585, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Test/BigOh/Fit/Hakaru.hs", "max_stars_repo_name": "tranma/shitty-complexity", "max_stars_repo_head_hexsha": "573815a8af9d5f3cda3c96e22d59b71ec9f29de9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2018-02-22T16:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-08T16:38:35.000Z", "max_issues_repo_path": "src/Test/BigOh/Fit/Hakaru.hs", "max_issues_repo_name": "tranma/shitty-complexity", "max_issues_repo_head_hexsha": "573815a8af9d5f3cda3c96e22d59b71ec9f29de9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-12-06T21:59:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-06T21:59:07.000Z", "max_forks_repo_path": "src/Test/BigOh/Fit/Hakaru.hs", "max_forks_repo_name": "tranma/shitty-complexity", "max_forks_repo_head_hexsha": "573815a8af9d5f3cda3c96e22d59b71ec9f29de9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-06T22:26:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-06T22:26:24.000Z", "avg_line_length": 27.4550898204, "max_line_length": 87, "alphanum_fraction": 0.5757906216, "num_tokens": 1361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47720310766580465}}
{"text": "{-# LANGUAGE PartialTypeSignatures #-}\nmodule PMMHTest where\n\nimport           Control.Monad.Bayes.Class\nimport           Control.Monad.Bayes.Sampler\nimport           Control.Monad\nimport           Control.Monad.Bayes.Inference.PMMH\n                                               as PMMH\nimport           Control.Monad.Bayes.Weighted\nimport           Control.Monad.State\nimport           Numeric.Log\nimport           DataParser\nimport           Statistics\nimport           Utils\n\ngenerateData\n  :: MonadSample m\n  => \n  -- | T\n     Int\n  ->\n  -- | list of latent and observable states from t=1\n     m [(Double, Double)]\ngenerateData t = do\n  (sigmaX, sigmaY) <- param\n  let sq x = x * x\n      simulate 0 _ acc = return acc\n      simulate k x acc = do\n        let n = length acc\n        x' <- normal (mean x n) sigmaX\n        y' <- normal (sq x' / 20) sigmaY\n        simulate (k - 1) x' ((x', y') : acc)\n  x0  <- normal 0 (sqrt 5)\n  xys <- simulate t x0 []\n  return $ reverse xys\n\nparam :: MonadSample m => m (Double, Double)\nparam = do\n  let a = 0.01\n  let b = 0.01\n  precX <- gamma a b\n  let sigmaX = 1 / sqrt precX\n  precY <- gamma a b\n  let sigmaY = 1 / sqrt precY\n  return (sigmaX, sigmaY)\n\nmean :: Double -> Int -> Double\nmean x n =\n  let sq x = x * x\n  in  0.5 * x + 25 * x / (1 + sq x) + 8 * cos (1.2 * fromIntegral n)\n\nmodel\n  :: (MonadInfer m)\n  => \n  -- | observed data\n     [Double]\n  ->\n  -- | prior on the parameters\n     (Double, Double)\n  ->\n  -- | list of latent states from t=1\n     m [Double]\nmodel obs (sigmaX, sigmaY) = do\n  let sq x = x * x\n      simulate []       _ acc = return acc\n      simulate (y : ys) x acc = do\n        let n = length acc\n        x' <- normal (mean x n) sigmaX\n        factor $ normalPdf (sq x' / 20) sigmaY y\n        simulate ys x' (x' : acc)\n  x0 <- normal 0 (sqrt 5)\n  xs <- simulate obs x0 []\n  return $ reverse xs\n\n\ntest :: IO [[([Double], Numeric.Log.Log Double)]]\ntest = sampleIO $ do\n  let t = 5\n  dat <- generateData t\n  let ys = map snd dat\n  pmmhRes <- prior $ pmmh 2 t 3 param (model ys)\n  liftIO $ print pmmhRes\n  return pmmhRes\n", "meta": {"hexsha": "78ce3f29e8e626edca25f8fc059075e824f979a9", "size": 2087, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PMMHTest.hs", "max_stars_repo_name": "rossng/sir-monad", "max_stars_repo_head_hexsha": "a16646a8ee6fd833a167615b44043b212896d8b6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-26T17:47:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-26T17:47:23.000Z", "max_issues_repo_path": "src/PMMHTest.hs", "max_issues_repo_name": "rossng/sir-monad", "max_issues_repo_head_hexsha": "a16646a8ee6fd833a167615b44043b212896d8b6", "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/PMMHTest.hs", "max_forks_repo_name": "rossng/sir-monad", "max_forks_repo_head_hexsha": "a16646a8ee6fd833a167615b44043b212896d8b6", "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": 24.8452380952, "max_line_length": 68, "alphanum_fraction": 0.5577383805, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.47680882485950216}}
{"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RankNTypes  #-}\n\nmodule Main where\n\nimport qualified Data.HashTable.Class                 as C\nimport           Data.HashTable.IO\nimport           Data.HashTable.Test.Common\nimport qualified Data.Vector.Unboxed as V\nimport qualified Data.Vector.Unboxed.Mutable as VM\nimport           Statistics.Quantile (continuousBy, cadpw)\nimport           Statistics.Sample\nimport           System.Environment\nimport           System.Random.MWC\n\n\noverhead :: C.HashTable h =>\n            FixedTableType h ->\n            GenIO ->\n            IO Double\noverhead dummy rng = do\n    size <- uniformR (1000,50000) rng\n    !v <- replicateM' size $ uniform rng\n    let _ = v :: [(Int,Int)]\n\n    !ht <- fromList v\n    forceType dummy ht\n\n    x <- computeOverhead ht\n    return x\n\n  where\n    replicateM' :: Int -> IO a -> IO [a]\n    replicateM' !sz f = go sz []\n      where\n        go !i !l | i == 0 = return l\n                 | otherwise = do\n                     !x <- f\n                     go (i-1) (x:l)\n\n\n-- Returns mean / stddev\nrunTrials :: C.HashTable h =>\n             FixedTableType h\n          -> GenIO\n          -> Int\n          -> IO (Double, Double, Double, Double)\nrunTrials dummy rng ntrials = do\n    sample <- rep ntrials $ overhead dummy rng\n\n    let (m, v) = meanVarianceUnb sample\n    return (m, sqrt v, p95 sample, pMax sample)\n  where\n    p95 sample = continuousBy cadpw 19 20 sample\n\n    pMax sample = V.foldl' max (-1) sample\n\n    rep !n !f = do\n        mv <- VM.new n\n        go mv\n\n      where\n        go !mv = go' 0\n          where\n            go' !i | i >= n = V.unsafeFreeze mv\n                   | otherwise = do\n                !d <- f\n                VM.unsafeWrite mv i d\n                go' $ i+1\n        \n\nmain :: IO ()\nmain = do\n    rng <- do\n        args <- getArgs\n        if null args\n          then withSystemRandom (\\x -> (return x) :: IO GenIO)\n          else initialize $ V.fromList [read $ head args]\n\n    runTrials dummyLinearTable rng nTrials >>= report \"linear hash table\"\n    runTrials dummyBasicTable rng nTrials >>= report \"basic hash table\"\n    runTrials dummyCuckooTable rng nTrials >>= report \"cuckoo hash table\"\n\n  where\n    nTrials = 200\n\n    report name md = putStrLn msg\n      where msg = concat [ \"\\n(Mean,StdDev,95%,Max) for overhead of \"\n                         , name\n                         , \" (\"\n                         , show nTrials\n                         , \" trials): \"\n                         , show md\n                         , \"\\n\" ]\n\n    dummyBasicTable = dummyTable\n                      :: forall k v . BasicHashTable k v\n\n    dummyLinearTable = dummyTable\n                       :: forall k v . LinearHashTable k v\n\n    dummyCuckooTable = dummyTable\n                       :: forall k v . CuckooHashTable k v\n    \n", "meta": {"hexsha": "53999d53fe1cc2b5c47beae3a599dbb9243912e7", "size": 2819, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "weak-hashtables/test/compute-overhead/ComputeOverhead.hs", "max_stars_repo_name": "cornell-pl/HsAdapton", "max_stars_repo_head_hexsha": "5ec36aeb4b15b999e3654c9473fc056a5d705780", "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": "weak-hashtables/test/compute-overhead/ComputeOverhead.hs", "max_issues_repo_name": "cornell-pl/HsAdapton", "max_issues_repo_head_hexsha": "5ec36aeb4b15b999e3654c9473fc056a5d705780", "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": "weak-hashtables/test/compute-overhead/ComputeOverhead.hs", "max_forks_repo_name": "cornell-pl/HsAdapton", "max_forks_repo_head_hexsha": "5ec36aeb4b15b999e3654c9473fc056a5d705780", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8476190476, "max_line_length": 73, "alphanum_fraction": 0.5218162469, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47643683268438014}}
{"text": "{-# OPTIONS_GHC -Wall -Wno-orphans #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell #-}\nmodule TestBDD (bddTestGroup) where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.IntMap.Lazy (IntMap)\nimport qualified Data.IntMap.Lazy as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.IORef\nimport Data.List\nimport qualified Data.Map.Lazy as Map\nimport Data.Proxy\nimport qualified Data.Set as Set\nimport Data.Vector (Vector)\nimport Data.Word\nimport Statistics.Distribution\nimport Statistics.Distribution.ChiSquared (chiSquared)\nimport System.IO.Unsafe\nimport qualified System.Random.MWC as Rand\nimport Test.QuickCheck.Function (apply)\nimport Test.QuickCheck.Instances.Vector ()\nimport Test.Tasty\nimport Test.Tasty.HUnit\nimport Test.Tasty.QuickCheck\nimport Test.Tasty.TH\n\nimport Data.DecisionDiagram.BDD (BDD (..), ItemOrder (..))\nimport qualified Data.DecisionDiagram.BDD as BDD\n\nimport Utils\n\n-- ------------------------------------------------------------------------\n\ninstance BDD.ItemOrder a => Arbitrary (BDD a) where\n  arbitrary = arbitraryBDDOver =<< arbitrary\n\n  shrink (BDD.Leaf _) = []\n  shrink (BDD.Branch x p0 p1) =\n    [p0, p1]\n    ++\n    [ BDD.Branch x p0' p1'\n    | (p0', p1') <- shrink (p0, p1), p0' /= p1'\n    ]\n\narbitraryBDDOver :: forall a. BDD.ItemOrder a => IntSet -> Gen (BDD a)\narbitraryBDDOver xs = do\n  let f vs n = oneof $\n        [ return BDD.true\n        , return BDD.false\n        ]\n        ++\n        [ do v <- elements vs\n             let vs' = dropWhile (\\v' -> compareItem (Proxy :: Proxy a) v' v  /= GT) vs\n             lo <- f vs' (n `div` 2)\n             hi <- f vs' (n `div` 2) `suchThat` (/= lo)\n             return (BDD.Branch v lo hi)\n        | n > 0, not (null vs)\n        ]\n  sized $ f (sortBy (BDD.compareItem (Proxy :: Proxy a)) $ IntSet.toList xs)\n\narbitrarySatisfyingAssignment :: forall a. BDD.ItemOrder a => BDD a -> IntSet -> Gen (IntMap Bool)\narbitrarySatisfyingAssignment bdd xs = do\n  m1 <- arbitrarySatisfyingPartialAssignment bdd\n  let ys = xs `IntSet.difference` IntMap.keysSet m1\n  m2 <- liftM(IntMap.fromAscList) $ forM (IntSet.toAscList ys) $ \\y -> do\n    v <- arbitrary\n    return (y,v)\n  return $ m1 `IntMap.union` m2\n\narbitrarySatisfyingPartialAssignment :: forall a. BDD.ItemOrder a => BDD a -> Gen (IntMap Bool)\narbitrarySatisfyingPartialAssignment = f\n  where\n    f (BDD.Leaf True) = return IntMap.empty\n    f (BDD.Leaf False) = undefined\n    f (BDD.Branch x lo hi) = oneof $\n      [liftM (IntMap.insert x False) (f lo) | lo /= BDD.Leaf False]\n      ++\n      [liftM (IntMap.insert x True) (f hi) | hi /= BDD.Leaf False]\n\n-- ------------------------------------------------------------------------\n-- conjunction\n-- ------------------------------------------------------------------------\n\nprop_and_unitL :: Property\nprop_and_unitL =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (BDD.true BDD..&&. a) === a\n\nprop_and_unitR :: Property\nprop_and_unitR =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a BDD..&&. BDD.true) === a\n\nprop_and_falseL :: Property\nprop_and_falseL =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (BDD.false BDD..&&. a) === BDD.false\n\nprop_and_falseR :: Property\nprop_and_falseR =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a BDD..&&. BDD.false) === BDD.false\n\nprop_and_comm :: Property\nprop_and_comm =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      (a BDD..&&. b) === (b BDD..&&. a)\n\nprop_and_assoc :: Property\nprop_and_assoc =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b, c) ->\n      (a BDD..&&. (b BDD..&&. c)) === ((a BDD..&&. b) BDD..&&. c)\n\nprop_and_idempotent :: Property\nprop_and_idempotent =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a BDD..&&. a) === a\n\n-- ------------------------------------------------------------------------\n-- disjunction\n-- ------------------------------------------------------------------------\n\nprop_or_unitL :: Property\nprop_or_unitL =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (BDD.false BDD..||. a) === a\n\nprop_or_unitR :: Property\nprop_or_unitR =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a BDD..||. BDD.false) === a\n\nprop_or_trueL :: Property\nprop_or_trueL =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (BDD.true BDD..||. a) === BDD.true\n\nprop_or_trueR :: Property\nprop_or_trueR =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a BDD..||. BDD.true) === BDD.true\n\nprop_or_comm :: Property\nprop_or_comm =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      (a BDD..||. b) === (b BDD..||. a)\n\nprop_or_assoc :: Property\nprop_or_assoc =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b, c) ->\n      (a BDD..||. (b BDD..||. c)) === ((a BDD..||. b) BDD..||. c)\n\nprop_or_idempotent :: Property\nprop_or_idempotent =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a BDD..||. a) === a\n\n-- ------------------------------------------------------------------------\n-- xor\n-- ------------------------------------------------------------------------\n\nprop_xor_unitL :: Property\nprop_xor_unitL =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (BDD.false `BDD.xor` a) === a\n\nprop_xor_unitR :: Property\nprop_xor_unitR =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a `BDD.xor` BDD.false) === a\n\nprop_xor_comm :: Property\nprop_xor_comm =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      (a `BDD.xor` b) === (b `BDD.xor` a)\n\nprop_xor_assoc :: Property\nprop_xor_assoc =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b, c) ->\n      (a `BDD.xor` (b `BDD.xor` c)) === ((a `BDD.xor` b) `BDD.xor` c)\n\nprop_xor_involution :: Property\nprop_xor_involution =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a `BDD.xor` a) === BDD.false\n\nprop_xor_dist :: Property\nprop_xor_dist =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b, c) ->\n      (a BDD..&&. (b `BDD.xor` c)) === ((a BDD..&&. b) `BDD.xor` (a BDD..&&. c))\n\n-- ------------------------------------------------------------------------\n-- distributivity\n-- ------------------------------------------------------------------------\n\nprop_dist_1 :: Property\nprop_dist_1 =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b, c) ->\n      (a BDD..&&. (b BDD..||. c)) === ((a BDD..&&. b) BDD..||. (a BDD..&&. c))\n\nprop_dist_2 :: Property\nprop_dist_2 =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b, c) ->\n      (a BDD..||. (b BDD..&&. c)) === ((a BDD..||. b) BDD..&&. (a BDD..||. c))\n\nprop_absorption_1 :: Property\nprop_absorption_1 =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      (a BDD..&&. (a BDD..||. b)) === a\n\nprop_absorption_2 :: Property\nprop_absorption_2 =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      (a BDD..||. (a BDD..&&. b)) === a\n\n-- ------------------------------------------------------------------------\n-- negation\n-- ------------------------------------------------------------------------\n\nprop_double_negation :: Property\nprop_double_negation =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      BDD.notB (BDD.notB a) === a\n\nprop_and_complement :: Property\nprop_and_complement =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a BDD..&&. BDD.notB a) === BDD.false\n\nprop_or_complement :: Property\nprop_or_complement =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a BDD..||. BDD.notB a) === BDD.true\n\nprop_de_morgan_1 :: Property\nprop_de_morgan_1 =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      BDD.notB (a BDD..||. b) === (BDD.notB a BDD..&&. BDD.notB b)\n\nprop_de_morgan_2 :: Property\nprop_de_morgan_2 =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      BDD.notB (a BDD..&&. b) === (BDD.notB a BDD..||. BDD.notB b)\n\n-- ------------------------------------------------------------------------\n-- Implication\n-- ------------------------------------------------------------------------\n\nprop_imply :: Property\nprop_imply =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      (a BDD..=>. b) === (BDD.notB a BDD..||. b)\n\nprop_imply_currying :: Property\nprop_imply_currying =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b, c) ->\n      ((a BDD..&&. b) BDD..=>. c) === (a BDD..=>. (b BDD..=>. c))\n\n-- ------------------------------------------------------------------------\n-- Equivalence\n-- ------------------------------------------------------------------------\n\nprop_equiv :: Property\nprop_equiv =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      (a BDD..<=>. b) === ((a BDD..=>. b) BDD..&&. (b BDD..=>. a))\n\n-- ------------------------------------------------------------------------\n-- If-then-else\n-- ------------------------------------------------------------------------\n\nprop_ite :: Property\nprop_ite =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(c :: BDD o, t, e) ->\n      BDD.ite c t e === ((c BDD..&&. t) BDD..||. (BDD.notB c BDD..&&. e))\n\nprop_ite_swap_branch :: Property\nprop_ite_swap_branch =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(c :: BDD o, t, e) ->\n      BDD.ite c t e === BDD.ite (BDD.notB c) e t\n\nprop_ite_dist_not :: Property\nprop_ite_dist_not =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(c :: BDD o, t, e) ->\n      BDD.notB (BDD.ite c t e) === BDD.ite c (BDD.notB t) (BDD.notB e)\n\nprop_ite_dist_and :: Property\nprop_ite_dist_and =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(c :: BDD o, t, e, d) ->\n      (d BDD..&&. BDD.ite c t e) === BDD.ite c (d BDD..&&. t) (d BDD..&&. e)\n\nprop_ite_dist_or :: Property\nprop_ite_dist_or =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(c :: BDD o, t, e, d) ->\n      (d BDD..||. BDD.ite c t e) === BDD.ite c (d BDD..||. t) (d BDD..||. e)\n\n-- ------------------------------------------------------------------------\n-- Pseudo-Boolean\n-- ------------------------------------------------------------------------\n\nprop_pbAtLeast :: Property\nprop_pbAtLeast =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrarySmallIntMap $ \\(xs :: IntMap Integer) ->\n      forAll arbitrary $ \\k ->\n        let a :: BDD o\n            a = BDD.pbAtLeast xs k\n         in counterexample (show a) $\n              if a == BDD.Leaf False then\n                property (k > sum [max 0 w | (_,w) <- IntMap.toList xs])\n              else\n                forAll (arbitrarySatisfyingAssignment a (IntMap.keysSet xs)) $ \\ys ->\n                  (IntMap.keysSet ys `IntSet.isSubsetOf` IntMap.keysSet xs)\n                  .&&.\n                  sum [xs IntMap.! y | (y,b) <- IntMap.toList ys, b] >= k\n\nprop_pbAtMost :: Property\nprop_pbAtMost =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrarySmallIntMap $ \\(xs :: IntMap Integer) ->\n      forAll arbitrary $ \\k ->\n        let a :: BDD o\n            a = BDD.pbAtMost xs k\n         in counterexample (show a) $\n              if a == BDD.Leaf False then\n                property (k < sum [min 0 w | (_,w) <- IntMap.toList xs])\n              else\n                forAll (arbitrarySatisfyingAssignment a (IntMap.keysSet xs)) $ \\ys ->\n                  (IntMap.keysSet ys `IntSet.isSubsetOf` IntMap.keysSet xs)\n                  .&&.\n                  sum [xs IntMap.! y | (y,b) <- IntMap.toList ys, b] <= k\n\nprop_pbExactly :: Property\nprop_pbExactly =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrarySmallIntMap $ \\(xs :: IntMap Integer) ->\n      forAll arbitrary $ \\k ->\n        let a :: BDD o\n            a = BDD.pbExactly xs k\n         in counterexample (show a) $\n              if a == BDD.Leaf False then\n                property True\n              else\n                forAll (arbitrarySatisfyingAssignment a (IntMap.keysSet xs)) $ \\ys ->\n                  (IntMap.keysSet ys `IntSet.isSubsetOf` IntMap.keysSet xs)\n                  .&&.\n                  sum [xs IntMap.! y | (y,b) <- IntMap.toList ys, b] === k\n\nprop_pbExactly_2 :: Property\nprop_pbExactly_2 =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrarySmallIntMap $ \\(xs :: IntMap Integer) ->\n      forAll (gen xs) $ \\(m, k) ->\n        let a :: BDD o\n            a = BDD.pbExactly xs k\n         in counterexample (show a) $ BDD.evaluate (m IntMap.!) a\n  where\n    gen :: IntMap Integer -> Gen (IntMap Bool, Integer)\n    gen xs = do\n      ys <- sublistOf (IntMap.toList xs)\n      let ys' = IntSet.fromList [y | (y,_) <- ys]\n      return\n        ( IntMap.mapWithKey (\\x _ -> x `IntSet.member` ys') xs\n        , sum [w | (_,w) <- ys]\n        )\n\nprop_pbExactlyIntegral :: Property\nprop_pbExactlyIntegral =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrarySmallIntMap $ \\(xs :: IntMap Integer) ->\n      forAll arbitrary $ \\k ->\n        (BDD.pbExactlyIntegral xs k :: BDD o) === BDD.pbExactly xs k\n\n-- ------------------------------------------------------------------------\n-- Quantification\n-- ------------------------------------------------------------------------\n\nprop_forAll :: Property\nprop_forAll =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(x, a :: BDD o) ->\n      BDD.forAll x a === (BDD.restrict x True a BDD..&&. BDD.restrict x False a)\n\nprop_exists :: Property\nprop_exists =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(x, a :: BDD o) ->\n      BDD.exists x a === (BDD.restrict x True a BDD..||. BDD.restrict x False a)\n\nprop_existsUnique :: Property\nprop_existsUnique =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(x, a :: BDD o) ->\n      BDD.existsUnique x a === (BDD.restrict x True a `BDD.xor` BDD.restrict x False a)\n\nprop_forAll_support :: Property\nprop_forAll_support =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(x, a :: BDD o) ->\n      let b = BDD.forAll x a\n          xs = BDD.support b\n       in counterexample (show (b, xs)) $\n            x `IntSet.notMember` xs\n\nprop_exists_support :: Property\nprop_exists_support =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(x, a :: BDD o) ->\n      let b = BDD.exists x a\n          xs = BDD.support b\n       in counterexample (show (b, xs)) $\n            x `IntSet.notMember` xs\n\nprop_existsUnique_support :: Property\nprop_existsUnique_support =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(x, a :: BDD o) ->\n      let b = BDD.existsUnique x a\n          xs = BDD.support b\n       in counterexample (show (b, xs)) $\n            x `IntSet.notMember` xs\n\n-- ------------------------------------------------------------------------\n\nprop_forAllSet_empty :: Property\nprop_forAllSet_empty =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      BDD.forAllSet IntSet.empty a === a\n\nprop_existsSet_empty :: Property\nprop_existsSet_empty =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      BDD.existsSet IntSet.empty a === a\n\nprop_existsUniqueSet_empty :: Property\nprop_existsUniqueSet_empty =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      BDD.existsUniqueSet IntSet.empty a === a\n\nprop_forAllSet_singleton :: Property\nprop_forAllSet_singleton =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(x, a :: BDD o) ->\n      BDD.forAllSet (IntSet.singleton x) a === BDD.forAll x a\n\nprop_existsSet_singleton :: Property\nprop_existsSet_singleton =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(x, a :: BDD o) ->\n      BDD.existsSet (IntSet.singleton x) a === BDD.exists x a\n\nprop_existsUniqueSet_singleton :: Property\nprop_existsUniqueSet_singleton =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(x, a :: BDD o) ->\n      BDD.existsUniqueSet (IntSet.singleton x) a === BDD.existsUnique x a\n\nprop_forAllSet_union :: Property\nprop_forAllSet_union =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(xs1, xs2, a :: BDD o) ->\n      BDD.forAllSet (xs1 `IntSet.union` xs2) a === BDD.forAllSet xs2 (BDD.forAllSet xs1 a)\n\nprop_existsSet_union :: Property\nprop_existsSet_union =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(xs1, xs2, a :: BDD o) ->\n      BDD.existsSet (xs1 `IntSet.union` xs2) a === BDD.existsSet xs2 (BDD.existsSet xs1 a)\n\nprop_existsUniqueSet_union :: Property\nprop_existsUniqueSet_union =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitraryDisjointSets $ \\(xs1, xs2) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      BDD.existsUniqueSet (xs1 `IntSet.union` xs2) a === BDD.existsUniqueSet xs2 (BDD.existsUniqueSet xs1 a)\n  where\n    arbitraryDisjointSets = do\n      (u, v) <- arbitrary\n      return (u `IntSet.intersection` v, u IntSet.\\\\ v)\n\n-- ------------------------------------------------------------------------\n\ncase_fold_laziness :: Assertion\ncase_fold_laziness = do\n  let bdd :: BDD BDD.AscOrder\n      bdd = BDD.Branch 0 (BDD.Branch 1 (BDD.Leaf False) (BDD.Leaf True)) (BDD.Branch 2 (BDD.Leaf False) (BDD.Leaf True))\n      f x lo _hi =\n        if x == 2 then\n          error \"unused value should not be evaluated\"\n        else\n          lo\n  seq (BDD.fold f id bdd) $ return ()\n\ncase_fold'_strictness :: Assertion\ncase_fold'_strictness = do\n  ref <- newIORef False\n  let bdd :: BDD BDD.AscOrder\n      bdd = BDD.Branch 0 (BDD.Branch 1 (BDD.Leaf False) (BDD.Leaf True)) (BDD.Branch 2 (BDD.Leaf False) (BDD.Leaf True))\n      f x lo _hi = unsafePerformIO $ do\n        when (x==2) $ writeIORef ref True\n        return lo\n  seq (BDD.fold' f id bdd) $ do\n    flag <- readIORef ref\n    assertBool \"unused value should be evaluated\" flag\n\nprop_fold_inSig :: Property\nprop_fold_inSig =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(bdd :: BDD o) ->\n      BDD.fold (\\x lo hi -> BDD.inSig (BDD.SBranch x lo hi)) (BDD.inSig . BDD.SLeaf) bdd\n      ===\n      bdd\n\nprop_fold'_inSig :: Property\nprop_fold'_inSig =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(bdd :: BDD o) ->\n      BDD.fold' (\\x lo hi -> BDD.inSig (BDD.SBranch x lo hi)) (BDD.inSig . BDD.SLeaf) bdd\n      ===\n      bdd\n\n-- ------------------------------------------------------------------------\n\nprop_unfoldHashable_outSig :: Property\nprop_unfoldHashable_outSig =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(bdd :: BDD o) ->\n      BDD.unfoldHashable BDD.outSig bdd === bdd\n\n-- ------------------------------------------------------------------------\n\ncase_support_false :: Assertion\ncase_support_false = BDD.support BDD.false @?= IntSet.empty\n\ncase_support_true :: Assertion\ncase_support_true = BDD.support BDD.true @?= IntSet.empty\n\nprop_support_var :: Property\nprop_support_var =\n  forAll arbitrary $ \\x ->\n    BDD.support (BDD.var x) === IntSet.singleton x\n\nprop_support_not :: Property\nprop_support_not =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      let lhs = BDD.support a\n          rhs = BDD.support (BDD.notB a)\n       in lhs === rhs\n\nprop_support_and :: Property\nprop_support_and =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      let lhs = BDD.support (a BDD..&&. b)\n          rhs = BDD.support a `IntSet.union` BDD.support b\n       in counterexample (show (lhs, rhs)) $ lhs `IntSet.isSubsetOf` rhs\n\nprop_support_or :: Property\nprop_support_or =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      let lhs = BDD.support (a BDD..||. b)\n          rhs = BDD.support a `IntSet.union` BDD.support b\n       in counterexample (show (lhs, rhs)) $ lhs `IntSet.isSubsetOf` rhs\n\n-- ------------------------------------------------------------------------\n\nprop_evaluate_var :: Property\nprop_evaluate_var =\n forAll arbitrary $ \\(f' :: Fun Int Bool) ->\n   let f = apply f'\n    in forAllItemOrder $ \\(_ :: Proxy o) ->\n         forAll arbitrary $ \\x ->\n           BDD.evaluate f (BDD.var x :: BDD o) === f x\n\nprop_evaluate_not :: Property\nprop_evaluate_not =\n forAll arbitrary $ \\(f' :: Fun Int Bool) ->\n   let f = apply f'\n    in forAllItemOrder $ \\(_ :: Proxy o) ->\n         forAll arbitrary $ \\(a :: BDD o) ->\n           BDD.evaluate f (BDD.notB a) === not (BDD.evaluate f a)\n\nprop_evaluate_and :: Property\nprop_evaluate_and =\n forAll arbitrary $ \\(f' :: Fun Int Bool) ->\n   let f = apply f'\n    in forAllItemOrder $ \\(_ :: Proxy o) ->\n         forAll arbitrary $ \\(a :: BDD o, b) ->\n           BDD.evaluate f (a BDD..&&. b) === (BDD.evaluate f a && BDD.evaluate f b)\n\nprop_evaluate_or :: Property\nprop_evaluate_or =\n forAll arbitrary $ \\(f' :: Fun Int Bool) ->\n   let f = apply f'\n    in forAllItemOrder $ \\(_ :: Proxy o) ->\n         forAll arbitrary $ \\(a :: BDD o, b) ->\n           BDD.evaluate f (a BDD..||. b) === (BDD.evaluate f a || BDD.evaluate f b)\n\n-- ------------------------------------------------------------------------\n\ncase_numNodes :: Assertion\ncase_numNodes = do\n  let bdd, bdd1 :: BDD BDD.AscOrder\n      bdd = BDD.Branch 0 (BDD.Branch 1 BDD.false bdd1) (BDD.Branch 2 BDD.false bdd1)\n      bdd1 = BDD.Branch 3 BDD.true BDD.false\n  BDD.numNodes bdd @?= 6\n\n-- ------------------------------------------------------------------------\n\nprop_restrict :: Property\nprop_restrict =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\x ->\n        let b = (BDD.var x BDD..&&. BDD.restrict x True a) BDD..||.\n                (BDD.notB (BDD.var x) BDD..&&. BDD.restrict x False a)\n         in a === b\n\nprop_restrict_idempotent :: Property\nprop_restrict_idempotent =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\(x, val) ->\n        let b = BDD.restrict x val a\n            c = BDD.restrict x val b\n         in counterexample (show (b, c)) $ b === c\n\nprop_restrict_not :: Property\nprop_restrict_not =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\(x, val) ->\n        BDD.restrict x val (BDD.notB a) === BDD.notB (BDD.restrict x val a)\n\nprop_restrict_and :: Property\nprop_restrict_and =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      forAll arbitrary $ \\(x, val) ->\n        BDD.restrict x val (a BDD..&&. b) === (BDD.restrict x val a BDD..&&. BDD.restrict x val b)\n\nprop_restrict_or :: Property\nprop_restrict_or =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      forAll arbitrary $ \\(x, val) ->\n        BDD.restrict x val (a BDD..||. b) === (BDD.restrict x val a BDD..||. BDD.restrict x val b)\n\nprop_restrict_var :: Property\nprop_restrict_var =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\x ->\n      let a :: BDD o\n          a = BDD.var x\n       in (BDD.restrict x True a === BDD.true) .&&.\n          (BDD.restrict x False a === BDD.false)\n\nprop_restrict_support :: Property\nprop_restrict_support =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\(x, val) ->\n        let b = BDD.restrict x val a\n            xs = BDD.support b\n         in counterexample (show b) $\n            counterexample (show xs) $\n              x `IntSet.notMember` xs\n\n-- ------------------------------------------------------------------------\n\nprop_restrictSet_empty :: Property\nprop_restrictSet_empty =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      BDD.restrictSet IntMap.empty a === a\n\nprop_restrictSet_singleton :: Property\nprop_restrictSet_singleton =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\(x, val) ->\n        BDD.restrict x val a === BDD.restrictSet (IntMap.singleton x val) a\n\nprop_restrictSet_union :: Property\nprop_restrictSet_union =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\(val1, val2) ->\n        and (IntMap.intersectionWith (==) val1 val2)\n        ==>\n        (BDD.restrictSet val2 (BDD.restrictSet val1 a) === BDD.restrictSet (val1 `IntMap.union` val2) a)\n\nprop_restrictSet_idempotent :: Property\nprop_restrictSet_idempotent =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\val ->\n        let b = BDD.restrictSet val a\n            c = BDD.restrictSet val b\n         in counterexample (show (b, c)) $ b === c\n\nprop_restrictSet_not :: Property\nprop_restrictSet_not =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\val ->\n        BDD.restrictSet val (BDD.notB a) === BDD.notB (BDD.restrictSet val a)\n\nprop_restrictSet_and :: Property\nprop_restrictSet_and =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      forAll arbitrary $ \\val ->\n        BDD.restrictSet val (a BDD..&&. b) === (BDD.restrictSet val a BDD..&&. BDD.restrictSet val b)\n\nprop_restrictSet_or :: Property\nprop_restrictSet_or =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      forAll arbitrary $ \\val ->\n        BDD.restrictSet val (a BDD..||. b) === (BDD.restrictSet val a BDD..||. BDD.restrictSet val b)\n\n-- ------------------------------------------------------------------------\n\nprop_restrictLaw :: Property\nprop_restrictLaw =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\law ->\n        (law BDD..&&. BDD.restrictLaw law a) === (law BDD..&&. a)\n\ncase_restrictLaw_case_0 :: Assertion\ncase_restrictLaw_case_0 = (law BDD..&&. BDD.restrictLaw law a) @?= (law BDD..&&. a)\n  where\n    a, law :: BDD BDD.AscOrder\n    a = BDD.Branch 2 (BDD.Leaf False) (BDD.Leaf True)\n    law = BDD.Branch 1 (BDD.Branch 2 (BDD.Leaf True) (BDD.Leaf False)) (BDD.Branch 2 (BDD.Leaf False) (BDD.Leaf True))\n\nprop_restrictLaw_true :: Property\nprop_restrictLaw_true =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      BDD.restrictLaw BDD.true a === a\n\nprop_restrictLaw_self :: Property\nprop_restrictLaw_self =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a /= BDD.false) ==> BDD.restrictLaw a a === BDD.true\n\nprop_restrictLaw_not_self :: Property\nprop_restrictLaw_not_self =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      (a /= BDD.true) ==> BDD.restrictLaw (BDD.notB a) a === BDD.false\n\nprop_restrictLaw_restrictSet :: Property\nprop_restrictLaw_restrictSet =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\val ->\n        let b = BDD.andB [if v then BDD.var x else BDD.notB (BDD.var x) | (x,v) <- IntMap.toList val]\n         in BDD.restrictLaw b a === BDD.restrictSet val a\n\n-- prop_restrictLaw_and_condition :: Property\n-- prop_restrictLaw_and_condition =\n--   forAllItemOrder $ \\(_ :: Proxy o) ->\n--     forAll arbitrary $ \\(a :: BDD o) ->\n--       forAll arbitrary $ \\(val1, val2) ->\n--         let val = val1 BDD..&&. val2\n--          in counterexample (show val) $\n--               (val /= BDD.false)\n--               ==>\n--               (BDD.restrictLaw val a === BDD.restrictLaw val2 (BDD.restrictLaw val1 a))\n\n-- counterexample to the above prop_restrictLaw_and_condition\ncase_restrictLaw_case_1 :: Assertion\ncase_restrictLaw_case_1 = do\n  -- BDD.restrictLaw val a @?= BDD.restrictLaw val2 (BDD.restrictLaw val1 a)\n  BDD.restrictLaw val a @?= BDD.Branch 2 (BDD.Leaf False) (BDD.Leaf True)\n  BDD.restrictLaw val2 (BDD.restrictLaw val1 a) @?= BDD.Branch 1 (BDD.Leaf True) (Branch 2 (BDD.Leaf False) (BDD.Leaf True))\n  where\n    a :: BDD BDD.AscOrder\n    a = Branch 2 (BDD.Leaf False) (BDD.Leaf True) -- x2\n    val1 = BDD.Branch 1 (BDD.Leaf False) (BDD.Leaf True) -- x1\n    val2 = BDD.Branch 1 (BDD.Branch 2 (BDD.Leaf False) (BDD.Leaf True)) (BDD.Leaf True) -- x1 \u2228 x2\n    val = val1 BDD..&&. val2 -- x1\n\nprop_restrictLaw_or_condition :: Property\nprop_restrictLaw_or_condition =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\(val1, val2) ->\n        let val = val1 BDD..||. val2\n         in counterexample (show val) $\n              (val BDD..&&. BDD.restrictLaw val a) === (val1 BDD..&&. BDD.restrictLaw val1 a BDD..||. val2 BDD..&&. BDD.restrictLaw val2 a)\n\nprop_restrictLaw_idempotent :: Property\nprop_restrictLaw_idempotent =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll arbitrary $ \\val ->\n        let b = BDD.restrictLaw val a\n            c = BDD.restrictLaw val b\n         in counterexample (show (b, c)) $ b === c\n\nprop_restrictLaw_not :: Property\nprop_restrictLaw_not =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      forAll (arbitrary `suchThat` (/= BDD.false)) $ \\val ->\n        BDD.restrictLaw val (BDD.notB a) === BDD.notB (BDD.restrictLaw val a)\n\nprop_restrictLaw_and :: Property\nprop_restrictLaw_and =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      forAll (arbitrary `suchThat` (/= BDD.false)) $ \\val ->\n        BDD.restrictLaw val (a BDD..&&. b) === (BDD.restrictLaw val a BDD..&&. BDD.restrictLaw val b)\n\nprop_restrictLaw_or :: Property\nprop_restrictLaw_or =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o, b) ->\n      forAll (arbitrary `suchThat` (/= BDD.false)) $ \\val ->\n        BDD.restrictLaw val (a BDD..||. b) === (BDD.restrictLaw val a BDD..||. BDD.restrictLaw val b)\n\n-- prop_restrictLaw_minimality :: Property\n-- prop_restrictLaw_minimality =\n--   forAllItemOrder $ \\(_ :: Proxy o) ->\n--     forAll arbitrary $ \\(a :: BDD o) ->\n--       forAll arbitrary $ \\law ->\n--         let b = BDD.restrictLaw law a\n--          in counterexample (show b) $\n--               ((law BDD..&&. b) === (law BDD..&&. a))\n--               .&&.\n--               conjoin [counterexample (show b') $ (law BDD..&&. b') =/= (law BDD..&&. a) | b' <- shrink b]\n\ncase_restrictLaw_non_minimal_1 :: Assertion\ncase_restrictLaw_non_minimal_1 = do\n  (law BDD..&&. BDD.restrictLaw law a) @?= (law BDD..&&. a)\n  BDD.restrictLaw law a @?= b -- should be 'a'?\n  where\n    law, a :: BDD BDD.AscOrder\n    law = BDD.Branch 1 (BDD.Branch 2 (BDD.Leaf False) (BDD.Leaf True)) (BDD.Leaf True) -- x1 \u2228 x2\n    a = BDD.Branch 2 (BDD.Leaf True) (BDD.Leaf False) -- \u00acx2\n    b = BDD.Branch 1 (BDD.Leaf False) (BDD.Branch 2 (BDD.Leaf True) (BDD.Leaf False)) -- x1 \u2227 \u00acx2\n\ncase_restrictLaw_non_minimal_2 :: Assertion\ncase_restrictLaw_non_minimal_2 = do\n  (law BDD..&&. BDD.restrictLaw law a) @?= (law BDD..&&. a)\n  BDD.restrictLaw law a @?= b -- should be 'a'?\n  where\n    law, a, b :: BDD BDD.AscOrder\n    law = BDD.Branch 1 (BDD.Leaf True) (BDD.Branch 2 (BDD.Leaf False) (BDD.Leaf True)) -- \u00acx1 \u2228 x2\n    a = BDD.Branch 2 (BDD.Leaf False) (BDD.Leaf True) -- x2\n    b = BDD.Branch 1 (BDD.Branch 2 (BDD.Leaf False) (BDD.Leaf True)) (BDD.Leaf True) -- x1 \u2228 x2\n\n-- ------------------------------------------------------------------------\n\nprop_subst_restrict_constant :: Property\nprop_subst_restrict_constant =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(m :: BDD o) ->\n    forAll arbitrary $ \\x ->\n    forAll arbitrary $ \\val ->\n      BDD.subst x (if val then BDD.true else BDD.false) m === BDD.restrict x val m\n\nprop_subst_restrict :: Property\nprop_subst_restrict =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(m :: BDD o) ->\n    forAll arbitrary $ \\x ->\n    forAll arbitrary $ \\(n :: BDD o) ->\n      BDD.subst x n m === ((n BDD..&&. BDD.restrict x True m) BDD..||. (BDD.notB n BDD..&&. BDD.restrict x False m))\n\nprop_subst_same_var :: Property\nprop_subst_same_var =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(m :: BDD o) ->\n    forAll arbitrary $ \\x ->\n      BDD.subst x (BDD.var x) m === m\n\nprop_subst_not_occured :: Property\nprop_subst_not_occured =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(m :: BDD o) ->\n    forAll (arbitrary `suchThat` (\\x -> x `IntSet.notMember` (BDD.support m))) $ \\x ->\n    forAll arbitrary $ \\(n :: BDD o) ->\n      BDD.subst x n m === m\n\n-- If x1\u2260x2 and x1\u2209FV(M2) then M[x1 \u21a6 M1][x2 \u21a6 M2] = M[x2 \u21a6 M2][x1 \u21a6 M1[x2 \u21a6 M2]].\nprop_subst_dist :: Property\nprop_subst_dist =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(x1, m1) ->\n    forAll ((,) <$> (arbitrary `suchThat` (/= x1)) <*> (arbitrary `suchThat` (\\m2 -> x1 `IntSet.notMember` BDD.support m2))) $ \\(x2, m2) ->\n    forAll arbitrary $ \\(m :: BDD o) ->\n      BDD.subst x2 m2 (BDD.subst x1 m1 m) === BDD.subst x1 (BDD.subst x2 m2 m1) (BDD.subst x2 m2 m)\n\n-- ------------------------------------------------------------------------\n\nprop_substSet_empty :: Property\nprop_substSet_empty =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(m :: BDD o) ->\n      BDD.substSet IntMap.empty m === m\n\nprop_substSet_singleton :: Property\nprop_substSet_singleton =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(m :: BDD o) ->\n    forAll arbitrary $ \\x ->\n    forAll arbitrary $ \\m1 ->\n      BDD.substSet (IntMap.singleton x m1) m === BDD.subst x m1 m\n\ncase_substSet_case_1 :: Assertion\ncase_substSet_case_1 = do\n  BDD.substSet (IntMap.singleton x m1) m @?= BDD.subst x m1 m\n  where\n    m :: BDD BDD.AscOrder\n    m = BDD.Branch 1 (BDD.Branch 2 (BDD.Leaf True) (BDD.Leaf False)) (BDD.Branch 2 (BDD.Leaf False) (BDD.Leaf True))\n    x = 1\n    m1 = BDD.Branch 1 (BDD.Leaf True) (BDD.Leaf False)\n\nprop_substSet_same_vars :: Property\nprop_substSet_same_vars =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(m :: BDD o) ->\n    forAll arbitrary $ \\xs ->\n      BDD.substSet (IntMap.fromAscList [(x, BDD.var x) | x <- IntSet.toAscList xs]) m === m\n\nprop_substSet_not_occured :: Property\nprop_substSet_not_occured =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(m :: BDD o) ->\n    forAll (f (BDD.support m)) $ \\s ->\n      BDD.substSet s m === m\n  where\n    f xs = liftM IntMap.fromList $ listOf $ do\n      y <- arbitrary `suchThat` (`IntSet.notMember` xs)\n      m <- arbitrary\n      return (y, m)\n\nprop_substSet_compose :: Property\nprop_substSet_compose =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\xs ->\n    forAll arbitrary $ \\ys ->\n    forAll (liftM IntMap.fromList $ mapM (\\x -> (,) <$> pure x <*> arbitraryBDDOver ys) (IntSet.toList xs)) $ \\s1 ->\n    forAll (liftM IntMap.fromList $ mapM (\\y -> (,) <$> pure y <*> arbitrary) (IntSet.toList ys)) $ \\s2 ->\n    forAll (arbitraryBDDOver xs) $ \\(m :: BDD o) ->\n      BDD.substSet s2 (BDD.substSet s1 m) === BDD.substSet (IntMap.map (BDD.substSet s2) s1) m\n\ncase_substSet_case_2 :: Assertion\ncase_substSet_case_2 = do\n  let m :: BDD BDD.AscOrder\n      m = BDD.var 1 BDD..&&. BDD.var 2\n  BDD.substSet (IntMap.fromList [(1, BDD.var 2), (2, BDD.var 3)]) m @?= BDD.var 2 BDD..&&. BDD.var 3\n  BDD.substSet (IntMap.fromList [(1, BDD.var 3), (2, BDD.var 1)]) m @?= BDD.var 3 BDD..&&. BDD.var 1\n\n-- ------------------------------------------------------------------------\n\ndata MonotoneExpr a\n  = MVar a\n  | MAnd (MonotoneExpr a) (MonotoneExpr a)\n  | MOr (MonotoneExpr a) (MonotoneExpr a)\n  | MConst Bool\n  deriving (Show)\n\narbitraryMonotoneExpr :: forall a. Gen a -> Gen (MonotoneExpr a)\narbitraryMonotoneExpr gen = sized f\n  where\n    f :: Int -> Gen (MonotoneExpr a)\n    f n = oneof $\n      [ liftM MConst arbitrary\n      , liftM MVar gen\n      ]\n      ++\n      concat\n      [ [liftM2 MAnd sub sub, liftM2 MOr sub sub]\n      | n > 0, let sub = f (n `div` 2)\n      ]\n\nevalMonotoneExpr :: ItemOrder a => (b -> BDD a) -> MonotoneExpr b -> BDD a\nevalMonotoneExpr f = g\n  where\n    g (MVar a) = f a\n    g (MConst v) = BDD.Leaf v\n    g (MOr a b) = g a BDD..||. g b\n    g (MAnd a b) = g a BDD..&&. g b\n\nforAllMonotonicFunction :: forall o prop. (ItemOrder o, Testable prop) => IntSet -> ((BDD o -> BDD o) -> prop) -> Property\nforAllMonotonicFunction xs k =\n  forAll (arbitraryMonotoneExpr (elements (Nothing : map Just (IntSet.toList xs)))) $ \\e -> do\n    let f :: BDD o -> BDD o\n        f x = evalMonotoneExpr g e\n          where\n            g Nothing = x\n            g (Just v) = BDD.var v\n     in k f\n\nprop_lfp_is_fixed_point :: Property\nprop_lfp_is_fixed_point =\n forAll arbitrary $ \\(xs :: IntSet) ->\n   forAllItemOrder $ \\(_ :: Proxy o) ->\n     forAllMonotonicFunction xs $ \\(f :: BDD o -> BDD o) -> do\n       let a = BDD.lfp f\n        in counterexample (show a) $ f a === a\n\n\nprop_gfp_is_fixed_point :: Property\nprop_gfp_is_fixed_point =\n forAll arbitrary $ \\(xs :: IntSet) ->\n   forAllItemOrder $ \\(_ :: Proxy o) ->\n     forAllMonotonicFunction xs $ \\(f :: BDD o -> BDD o) -> do\n       let a = BDD.gfp f\n        in counterexample (show a) $ f a === a\n\nprop_lfp_imply_gfp :: Property\nprop_lfp_imply_gfp =\n forAll arbitrary $ \\(xs :: IntSet) ->\n   forAllItemOrder $ \\(_ :: Proxy o) ->\n     forAllMonotonicFunction xs $ \\(f :: BDD o -> BDD o) -> do\n       let a = BDD.lfp f\n           b = BDD.gfp f\n        in counterexample (show (a, b)) $ (a BDD..=>. b) === BDD.true\n\n-- ------------------------------------------------------------------------\n\nprop_anySat :: Property\nprop_anySat =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(bdd :: BDD o) ->\n      case BDD.anySat bdd of\n        Just p -> counterexample (show p) $ BDD.evaluate (p IntMap.!) bdd\n        Nothing -> bdd === BDD.Leaf False\n\nprop_allSat :: Property\nprop_allSat =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrarySmallIntSet $ \\xs ->\n      forAll (arbitraryBDDOver xs) $ \\(bdd :: BDD o) ->\n         let ps = BDD.allSat bdd\n         in null ps === (bdd == BDD.Leaf False)\n            .&&.\n            conjoin [counterexample (show p) $ BDD.evaluate (p IntMap.!) bdd |  p <- ps]\n\nprop_anySatComplete :: Property\nprop_anySatComplete =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\xs ->\n      forAll (arbitraryBDDOver xs) $ \\(bdd :: BDD o) ->\n        case BDD.anySatComplete xs bdd of\n          Just p -> counterexample (show p) $\n            IntMap.keysSet p === xs\n            .&&.\n            BDD.evaluate (p IntMap.!) bdd\n          Nothing -> bdd === BDD.Leaf False\n\nprop_allSatComplete :: Property\nprop_allSatComplete =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrarySmallIntSet $ \\xs ->\n      forAll (arbitraryBDDOver xs) $ \\(bdd :: BDD o) ->\n        let ps = BDD.allSatComplete xs bdd\n            qs = [q | q <- foldM (\\m x -> [IntMap.insert x v m | v <- [False, True]]) IntMap.empty (IntSet.toList xs)\n                    , BDD.evaluate (q IntMap.!) bdd]\n         in conjoin [counterexample (show p) (IntMap.keysSet p === xs) | p <- ps]\n            .&&.\n            Set.fromList ps === Set.fromList qs\n\nprop_countSat_allSatComplete :: Property\nprop_countSat_allSatComplete =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrarySmallIntSet $ \\xs ->\n      forAll (arbitraryBDDOver xs) $ \\(bdd :: BDD o) ->\n        let ps = BDD.allSatComplete xs bdd\n            n = BDD.countSat xs bdd\n         in counterexample (show n) $\n              if bdd == BDD.Leaf False then\n                n === 0\n              else\n                -- Note that the number of partial assignments is smaller than the number of total assignments\n                (n > 0) .&&. n === length ps\n\nprop_uniformSatM :: Property\nprop_uniformSatM =\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll (arbitrarySmallIntSet `suchThat` ((>= 2) . IntSet.size)) $ \\xs ->\n      forAll (arbitraryBDDOver xs `suchThat` ((>= (2::Integer)) . BDD.countSat xs)) $ \\(bdd :: BDD o) ->\n        forAll arbitrary $ \\(seed :: Vector Word32) ->\n          let m :: Integer\n              m = BDD.countSat xs bdd\n              n = 1000\n              samples = runST $ do\n                gen <- Rand.initialize seed\n                replicateM n $ BDD.uniformSatM xs bdd gen\n              hist_actual = Map.fromListWith (+) [(s, 1 :: Double) | s <- samples]\n              hist_expected = [(s, fromIntegral n / fromIntegral m :: Double) | s <- BDD.allSatComplete xs bdd]\n              chi_sq = sum [(Map.findWithDefault 0 s hist_actual - cnt) ** 2 / cnt | (s, cnt) <- hist_expected]\n              threshold = complQuantile (chiSquared (fromIntegral m - 1)) 0.0001\n           in counterexample (show hist_actual ++ \" /= \" ++ show (Map.fromList hist_expected)) $\n                and [BDD.evaluate (a IntMap.!) bdd | a <- Map.keys hist_actual]\n                .&&.\n                counterexample (\"\u03c7\u00b2 = \" ++ show chi_sq ++ \" >= \" ++ show threshold) (chi_sq < threshold)\n\n-- ------------------------------------------------------------------------\n\nprop_toGraph_fromGraph :: Property\nprop_toGraph_fromGraph = do\n  forAllItemOrder $ \\(_ :: Proxy o) ->\n    forAll arbitrary $ \\(a :: BDD o) ->\n      BDD.fromGraph (BDD.toGraph a) === a\n\n-- ------------------------------------------------------------------------\n\narbitrarySmallIntSet :: Gen IntSet\narbitrarySmallIntSet = do\n  n <- choose (0, 12)\n  liftM IntSet.fromList $ replicateM n arbitrary\n\narbitrarySmallIntMap :: Arbitrary a => Gen (IntMap a)\narbitrarySmallIntMap = do\n  n <- choose (0, 12)\n  liftM IntMap.fromList $ replicateM n $ do\n    k <- arbitrary\n    v <- arbitrary\n    return (k, v)\n\n-- ------------------------------------------------------------------------\n\nbddTestGroup :: TestTree\nbddTestGroup = $(testGroupGenerator)\n", "meta": {"hexsha": "215721d91a7463aadcffd3f7da96d30796e11108", "size": 41996, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/TestBDD.hs", "max_stars_repo_name": "msakai/haskell-decision-diagrams", "max_stars_repo_head_hexsha": "7949fe404e12a844d7cf04810e2804d8c9d0265e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-11-04T02:03:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T19:03:52.000Z", "max_issues_repo_path": "test/TestBDD.hs", "max_issues_repo_name": "msakai/haskell-decision-diagrams", "max_issues_repo_head_hexsha": "7949fe404e12a844d7cf04810e2804d8c9d0265e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/TestBDD.hs", "max_forks_repo_name": "msakai/haskell-decision-diagrams", "max_forks_repo_head_hexsha": "7949fe404e12a844d7cf04810e2804d8c9d0265e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-01T19:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T19:40:47.000Z", "avg_line_length": 35.5898305085, "max_line_length": 139, "alphanum_fraction": 0.5594818554, "num_tokens": 12675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.47639805824068154}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Main (main) where\n\nimport Control.Monad (mzero)\nimport Control.Monad.IO.Class (liftIO)\nimport Data.Complex (Complex)\nimport Data.Foldable (toList)\nimport Data.Typeable (Typeable)\nimport System.Console.GetOpt\nimport Text.PrettyPrint.Mainland\nimport Text.PrettyPrint.Mainland.Class\n\nimport Spiral\nimport Spiral.Backend.C\nimport Spiral.Config\nimport Spiral.Driver\nimport Spiral.Exp\nimport Spiral.FFT.CooleyTukey\nimport Spiral.Monad\nimport Spiral.OpCount\nimport Spiral.Program\nimport Spiral.SPL\nimport Spiral.SPL.Run\nimport Spiral.Search\nimport Spiral.Search.FFTBreakdowns\nimport Spiral.Util.Uniq\n\nmain :: IO ()\nmain = defaultMainWith' options mempty $ \\fs args -> do\n    useComplexType <- asksConfig $ testDynFlag UseComplex\n    n <- case args of\n           [s] -> return (read s)\n           _   -> return 4\n    f <- formula fs n\n    pprint f\n    if useComplexType\n      then toProgram (\"hspiral_dft_\" ++ show n) f >>= go\n      else toProgram (\"hspiral_dft_\" ++ show n) (Re f) >>= go\n  where\n    go :: (Typed a, Num (Exp a)) => Program a -> Spiral ()\n    go prog = do\n      pprint prog\n      ops <- countProgramOps prog\n      resetUnique\n      defs <- evalCg $ cgProgram prog\n      outp <- asksConfig output\n      case outp of\n        Nothing -> return ()\n        Just{}  -> writeOutput (toList defs)\n      liftIO $ putDocLn $\n          text \"Multiplications:\" <+> ppr (mulOps ops) </>\n          text \"      Additions:\" <+> ppr (addOps ops) </>\n          text \"          Total:\" <+> ppr (allOps ops)\n\n-- The SPL formula for which we generate code and count operations.\nformula :: MonadSpiral m => [Flag] -> Int -> m (SPL (Exp (Complex Double)))\nformula fs n =\n  case fs of\n    [Dif]                -> return $ dif n\n    [Dit]                -> return $ dit n\n    [SplitRadix]         -> runSearch () splitRadixSearch (DFT n)\n    [ConjPairSplitRadix] -> runSearch () conjSplitRadixSearch (DFT n)\n    [ImpSplitRadix]      -> runSearch () impSplitRadixSearch (DFT n)\n    _                    -> fail \"Must specify exactly on of --dif, --dit, --split-radix, conj-split-radix, or --improved-split-radix\"\n  where\n    splitRadixSearch :: (Typeable a, Typed a, MonadSpiral m)\n                     => SPL (Exp a)\n                     ->\u00a0S s m (SPL (Exp a))\n    splitRadixSearch (F n w) = splitRadixBreakdown n w\n    splitRadixSearch _       = mzero\n\n    conjSplitRadixSearch :: (Typeable a, Typed a, MonadSpiral m)\n                         => SPL (Exp a)\n                         ->\u00a0S s m (SPL (Exp a))\n    conjSplitRadixSearch (F n w) = conjPairSplitRadixBreakdown n w\n    conjSplitRadixSearch _       = mzero\n\n    impSplitRadixSearch :: (Typeable a, Typed a, MonadSpiral m)\n                        => SPL (Exp a)\n                        ->\u00a0S s m (SPL (Exp a))\n    impSplitRadixSearch (F n w) = improvedSplitRadixBreakdown n w\n    impSplitRadixSearch _       = mzero\n\ndata Flag = Dif\n          | Dit\n          | SplitRadix\n          | ConjPairSplitRadix\n          | ImpSplitRadix\n  deriving (Eq, Ord, Show)\n\noptions :: [OptDescr Flag]\noptions =\n    [ Option [] [\"dif\"] (NoArg Dif)                             \"Use DIF\"\n    , Option [] [\"dit\"] (NoArg Dit)                             \"Use DIT\"\n    , Option [] [\"split-radix\"] (NoArg SplitRadix)              \"Use split radix\"\n    , Option [] [\"conj-split-radix\"] (NoArg ConjPairSplitRadix) \"Use conjugate pair split radix\"\n    , Option [] [\"imp-split-radix\"] (NoArg ImpSplitRadix)       \"Use improved split radix\"\n    ]\n", "meta": {"hexsha": "e05a317eafd4946aa25e87c211649bd6c8ef6250", "size": 3500, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/DFTGen.hs", "max_stars_repo_name": "mainland/hspiral", "max_stars_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-05-21T21:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T04:48:25.000Z", "max_issues_repo_path": "examples/DFTGen.hs", "max_issues_repo_name": "mainland/hspiral", "max_issues_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "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/DFTGen.hs", "max_forks_repo_name": "mainland/hspiral", "max_forks_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0, "max_line_length": 134, "alphanum_fraction": 0.5982857143, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4762617708602479}}
{"text": "{-# LANGUAGE DataKinds         #-}\n{-# LANGUAGE BangPatterns      #-}\n{-# LANGUAGE RankNTypes        #-}\n{-# LANGUAGE FlexibleContexts  #-}\n{-# LANGUAGE TypeFamilies      #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeOperators     #-}\n-- {-# LANGUAGE UndecidableInstances #-}\n\nmodule GrenadeExtras (\n  epochTraining,\n  trainOnBatchesEpochs,\n  binaryNetError,\n  normalize,\n  hotvector,\n  applyUpdates\n) where\n\nimport           Shuffle (shuffle)\nimport           Control.Monad.Random (MonadRandom)\n\nimport           Data.List (foldl')\n\nimport           Lens.Micro (over, both)--Lens', set)\n\nimport           Data.Singletons (SingI)\nimport           Data.Singletons.Prelude (Head, Last)\n\nimport           Numeric.LinearAlgebra.Static (extract, R, \u211d, toRows, eye)\nimport           Numeric.LinearAlgebra.Data (Vector, (!))\n\nimport           GHC.TypeLits (KnownNat)\n\nimport           Grenade (Network((:~>), NNil), Shape(D1), LearningParameters, runNet, S(S1D),\n                          Gradients((:/>)), backPropagate, train, runUpdates, Gradient, applyUpdate)\n\nimport           GrenadeExtras.OrphanNum()\nimport           GrenadeExtras.GradNorm (GradNorm(normSquared))\n\ntrainOnBatchesEpochs :: (SingI (Last shapes), MonadRandom m, Num (Gradients layers), GradNorm (Gradients layers))\n                 => Network layers shapes\n                 -> LearningParameters\n                 -> [(S (Head shapes), S (Last shapes))]\n                 -> Int\n                 -> m [(Double, Network layers shapes)]\ntrainOnBatchesEpochs net0 rate input_data batchSize =\n\n    foldMeOutList (0, net0) [(1::Int)..] $ \\(_,net) _-> do\n      shuffledInput <- shuffle input_data\n      -- traning net (an epoch) with the input shuffled\n      let batches = splitInBatches shuffledInput\n          (gradientNorm, newNet) = foldl' trainBatch (0, net) batches\n      return (gradientNorm, newNet)\n\n  where\n    trainBatch :: (SingI (Last shapes), Num (Gradients layers), GradNorm (Gradients layers))\n               => (Double, Network layers shapes)\n               -> [(S (Head shapes), S (Last shapes))]\n               -> (Double, Network layers shapes)\n    trainBatch (accNorm, !network) ios =\n      let grads = fmap (uncurry $ backPropagate network) ios\n          grad = sum grads\n          norm = sqrt $ normSquared grad\n       in (accNorm+norm, applyUpdate rate network grad)\n       --in applyUpdates rate network grads\n\n    --len = length input_data\n\n    splitInBatches :: [a] -> [[a]]\n    splitInBatches [] = []\n    splitInBatches xs =\n      let (start, finish) = splitAt batchSize xs\n       in start : splitInBatches finish\n\napplyUpdates :: LearningParameters\n             -> Network layers shapes\n             -> [Gradients layers]\n             -> Network layers shapes\napplyUpdates rate (layer :~> rest) gradients\n  = runUpdates rate layer layerGradients :~> applyUpdates rate rest restLayersGradients\n    where headTailGrad :: Gradients (layer ': layers) -> (Gradient layer, Gradients layers)\n          headTailGrad (gradient :/> grest) = (gradient, grest)\n          (layerGradients, restLayersGradients) = unzip $ fmap headTailGrad gradients\n\napplyUpdates _ NNil _\n  = NNil\n\nepochTraining :: (SingI (Last shapes), MonadRandom m) =>\n                 Network layers shapes\n                 -> LearningParameters\n                 -> [(S (Head shapes), S (Last shapes))]\n                 -> m [Network layers shapes]\nepochTraining net0 rate input_data =\n\n    foldMeOutList net0 [(1::Int)..] $ \\net _-> do\n      shuffledInput <- shuffle input_data\n      -- traning net (an epoch) with the input shuffled\n      let newNet = foldl' trainEach net shuffledInput\n      return newNet\n\n  where\n    trainEach !network (i,o) = train rate network i o\n\nfoldMeOutList :: Monad m => a -> [b] -> (a -> b -> m a) -> m [a]\nfoldMeOutList z xs_ op = f' z xs_\n  where f' _    []     = return []\n        f' zero (x:xs) = do\n          zero' <- op zero x\n          rec   <- f' zero' xs\n          return $ zero':rec\n\nbinaryNetError :: (Last shapes ~ 'D1 1, Foldable t) =>\n  Network layers shapes -> t (S (Head shapes), S ('D1 1)) -> (Double, Double)\n\nbinaryNetError net test = (fromIntegral errors / fromIntegral total, distance)\n  where\n    total, errors :: Integer\n    {-(total, errors) = foldl' step (0,0) test-}\n    distance :: Double\n    (total, errors, distance) = foldl' step (0,0,0) test\n\n    {-step (t, e) song = (t+1, e')-}\n    step (t, e, d) song = (t+1, e', d')\n      where\n        (label, netOut) = valueFromDataAndNet song\n        -- the predictions from the network come with numbers between 0 and 1,\n        -- everything above .5 is considered 1 and below 0\n        e' = if (label > 0.5) == (netOut > 0.5)\n                then e\n                else e+1\n        d' = d + (label - netOut)^(2::Int)\n\n    valueFromDataAndNet (input, label) = over both sd1toDouble (label, runNet net input)\n      where\n        sd1toDouble :: S ('D1 1) -> Double\n        sd1toDouble (S1D r) = (extract :: R 1 -> Vector \u211d) r ! 0\n\n-- taken from https://en.wikipedia.org/wiki/Normalization_(statistics)\n-- normalization method: Student's t-statistic\nnormalize :: KnownNat n => [R n] -> [R n]\nnormalize features = fmap (\\x -> (x-mean)/stdDeviation ) features\n  where\n    len = length features\n\n    --mean :: R n\n    mean = sum features / fromIntegral len\n\n    --stdDeviation :: R n\n    stdDeviation = sqrt $ (sum . fmap (\\x-> (x-mean)^(2::Int)) $ features)\n                          / fromIntegral (len-1)\n\nhotvector :: KnownNat n => Int -> Maybe (R n)\nhotvector m = toRows eye ~!! m\n  where\n    (~!!) :: [a] -> Int -> Maybe a\n    []     ~!! _ = Nothing\n    (x:xs) ~!! n\n      | n == 0 = Just x\n      | n < 0  = Nothing\n      | otherwise = xs ~!! (n-1)\n", "meta": {"hexsha": "c3878c7d1ab4aa5029bd6fac8ebd26f5526c95dc", "size": 5706, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/GrenadeExtras.hs", "max_stars_repo_name": "helq/haskell-binary-classification", "max_stars_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-10-02T06:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T11:49:35.000Z", "max_issues_repo_path": "src/GrenadeExtras.hs", "max_issues_repo_name": "helq/haskell-binary-classification", "max_issues_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "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/GrenadeExtras.hs", "max_forks_repo_name": "helq/haskell-binary-classification", "max_forks_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T14:57:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T14:57:00.000Z", "avg_line_length": 35.4409937888, "max_line_length": 113, "alphanum_fraction": 0.5949877322, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4761229462362548}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Model where\n\nimport           Control.Monad.Bayes.Class\nimport           Control.Monad.Bayes.Sampler\nimport qualified Data.Text.IO as TIO\nimport           Control.Monad\nimport           Control.Monad.Bayes.Inference.PMMH\nimport           Control.Monad.State\nimport Control.Monad.Bayes.Weighted\nimport           Numeric.Log\nimport           Text.Megaparsec \n\nimport           DataParser\nimport           Statistics\nimport           Utils\n\n\ndata Params = Params {\n    rho :: Double, -- ^ Rate of detection\n    beta :: Double, -- ^ Mean contact rate between susceptible and infected people\n    gamma :: Double -- ^ Mean recovery rate\n} deriving Show\n\ndata FixedParams = FixedParams {\n    numPop :: Int,\n    timeSlices :: Int\n}\n\ndata LatentState = LatentState {\n    sus :: Int, -- ^ Number of people susceptible to infection\n    inf :: Int, -- ^ Number of people currently infected\n    recov :: Int -- ^ Number of people recovered from infection\n}\n\n{-\nobservation model: Poisson rho * I\n-}\n\n\n-- | Model for how we observe the number of infected people\nobservationModel :: MonadSample m => Params -> LatentState -> m InfectionCount\nobservationModel (Params rho _ _) (LatentState _ inf _) =\n    poisson (rho * fromIntegral inf)\n\n\n{-\ndN_SI <-\n-}\n-- | Transition the model a single time slice\ntransitionModelSingleStep\n    :: MonadSample m => FixedParams -> Params -> LatentState -> m LatentState\ntransitionModelSingleStep (FixedParams numPop timeSlices) (Params rho beta gamma) (LatentState sus inf recov)\n    = do\n        let dt = 1 / fromIntegral timeSlices\n        dN_SI <- binomial\n            sus\n            (1 - exp ((-beta * dt * (fromIntegral inf)) / (fromIntegral numPop))\n            )\n        dN_IR <- binomial\n            inf\n            (1 - exp (-gamma * dt)\n            )\n        let sus'   = sus - dN_SI\n        let inf'   = inf + dN_SI - dN_IR\n        let recov' = recov + dN_IR\n        return (LatentState sus' inf' recov')\n\n-- | Transition the model for a full step\ntransitionModel :: MonadSample m => FixedParams -> Params -> LatentState -> m LatentState\ntransitionModel fixedParams params =\n    transitionModelSingleStep fixedParams params\n\n-- | Simulate a single step, returning the new latent state and appending the observed infection count to the state.\nsimulateStep\n    :: (MonadSample m, MonadState [InfectionCount] m)\n    => FixedParams\n    -> Params\n    -> LatentState\n    -> m LatentState\nsimulateStep fixedParams params latent = do\n    latent'        <- transitionModel fixedParams params latent\n    infectionCount <- observationModel params latent'\n    modify (++ [infectionCount])\n    return latent'\n\n-- | Simulate nsteps steps of an epidemic with the specified initial state and parameters\nsimulateEpidemic\n    :: MonadSample m => LatentState -> FixedParams -> Params -> Int -> m Epidemic\nsimulateEpidemic initialState fixedParams params nsteps =\n    Epidemic\n        <$> execStateT\n                (repeatFunction nsteps (simulateStep fixedParams params) initialState)\n                []\n\n-- | Execute a single simulation of an epidemic\ngenerateSingleEpidemic :: LatentState -> FixedParams -> Params -> Int -> IO Epidemic\ngenerateSingleEpidemic initialState fixedParams params nsteps =\n    sampleIO $ simulateEpidemic initialState fixedParams params nsteps\n\n\ngenerateEpidemics :: LatentState -> FixedParams -> Params -> Int -> Int -> IO [Epidemic]\ngenerateEpidemics initialState fixedParams params nsteps nepidemics = replicateM nepidemics (generateSingleEpidemic initialState fixedParams params nsteps)\n\nfixedParams :: FixedParams\nfixedParams = FixedParams 763 1  \n\nparams :: Params\nparams = Params 0.9 2.0 0.6 \n\ninitialState :: LatentState\ninitialState = LatentState 762 1 0\n\n\nscoreEpidemicToDatum \n    :: MonadInfer m  \n    => FixedParams \n    -> Epidemic \n    -> LatentState \n    -> Params \n    ->  m Params \nscoreEpidemicToDatum fixedParams dat  x params = do\n    let obs lambda y = score (poissonPdf lambda y)\n        go [] x = return x\n        go (y:ys) x = do\n            x' <- transitionModel fixedParams params x \n            obs ((fromIntegral $ inf x') * (rho params)) y\n            return x'\n    (go $! (unwrapEpidemic dat)) $! x\n    return params\n\nunwrapEpidemic :: Epidemic -> [Int]\nunwrapEpidemic (Epidemic xs) = xs\n\n{-\nddprior <- function(params) {\n    dgamma(params[[1]], 0.3, 10, log = TRUE) +\n    dgamma(params[[3]], 1, 8, log=TRUE) + \n    dbeta(params[[2]], 2,7, log=TRUE)\n}\n-}\nparamsPrior :: MonadSample m => m Params\nparamsPrior = do\n    pBeta <- Control.Monad.Bayes.Class.gamma 2 1\n    pRho <- Control.Monad.Bayes.Class.beta 2.0 7.0\n    pGamma <- Control.Monad.Bayes.Class.gamma 1.0  (1 / 8.0)\n    return (Params pRho pBeta pGamma )\n\ntestInferenceEpidemic :: Int -> Int -> IO [[(Params, Numeric.Log.Log Double)]]\ntestInferenceEpidemic nsteps nparticles = do\n    ys <- parseFromFile epidemicParser \"data/datafile\"\n    case ys of (Left _) -> error \"naughty\"\n               (Right dat) -> sampleIO $ do\n                       pmmhRes <- prior $ pmmh nsteps 14 nparticles paramsPrior (scoreEpidemicToDatum fixedParams dat initialState)\n                       return pmmhRes\n\nparseFromFile p file = runParser p file <$> TIO.readFile file\n\n\nextractParams :: (Params -> Double) -> [[(Params, Numeric.Log.Log Double)]] -> [Double]\nextractParams project samples = (project . fst . head) <$> samples\n\n--scoreEpidemicToData :: (MonadSample m, MonadState [InfectionCount] m => Epidemic ->  Params -> LatentState -> m Epidemic \n--scoreEpidemicToData data params initialState = do\n--    let obs lambda y = score (poissonPdf lambda y)\n    -- simulate a new x from old x (x is a latent state)\n    -- calculate new lambda\n    -- score observation at time using lambda\n    -- store x in the monad state\n    -- repeat\n\ngenerateSamples :: [Double]\ngenerateSamples = sampleSTfixed $ replicateM 1000 (normal 3 1)\n", "meta": {"hexsha": "60664c4f0c436c0b8a552761c945174241815d66", "size": 6025, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Model.hs", "max_stars_repo_name": "rossng/sir-monad", "max_stars_repo_head_hexsha": "a16646a8ee6fd833a167615b44043b212896d8b6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-26T17:47:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-26T17:47:23.000Z", "max_issues_repo_path": "src/Model.hs", "max_issues_repo_name": "rossng/sir-monad", "max_issues_repo_head_hexsha": "a16646a8ee6fd833a167615b44043b212896d8b6", "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/Model.hs", "max_forks_repo_name": "rossng/sir-monad", "max_forks_repo_head_hexsha": "a16646a8ee6fd833a167615b44043b212896d8b6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6592178771, "max_line_length": 155, "alphanum_fraction": 0.6715352697, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4761025041626365}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RankNTypes #-}\nmodule Statistics.BBVI.Examples\n  ( genMixture\n  , mixtureFit\n  , genNormal\n  , normalFit\n  , genDirichlet\n  , dirichletFit\n  , genMixedMem\n  , mixedMemFit\n  )\nwhere\n\nimport           Control.Monad.ST\nimport           Data.Propagator\nimport qualified Data.Vector                   as V\nimport           Numeric.AD                     ( grad'\n                                                , auto\n                                                , diff\n                                                )\nimport           System.Random.MWC              ( create\n                                                , uniform\n                                                , initialize\n                                                , GenST\n                                                )\nimport qualified System.Random.MWC.Distributions\n                                               as MWCD\nimport           Statistics.BBVI\n\n--- helper functions\nlogSum :: (Floating c, Ord c) => V.Vector c -> V.Vector c -> c\nlogSum v1 = log . minimumProb . V.sum . V.map exp . V.zipWith (+) v1\n\nminimumProb :: (Floating a, Ord a) => a -> a\nminimumProb = max 1e-308\n\n--- useful global params\n-- for fit\nglobalMaxStep :: Int\nglobalMaxStep = 1000\nglobalDelta :: Double\nglobalDelta = 1e-16 -- 0.00001 --\n\n-- for generating data\nnDimension :: Int\nnDimension = 1\nnTime :: Int\nnTime = 1000\nnState :: Int\nnState = 3 -- 10\n\n-----------------\n--  mixture\n------------------\n-- | log joint of a mixture model, with categorical marginalized out\nmixtureJoint :: (Floating a, Ord a) => a -> V.Vector a -> a -> V.Vector a -> a\nmixtureJoint std theta ob betas = logSum\n  (V.map log theta)\n  (V.map (\\mu -> diffableNormalLogProb mu std ob) betas)\n\n-- | transform a log joint to a gradient propagator, for use with\n-- models with a mixture-like plate structure. Updates the mixture\n-- components with the reparameterization gradient (Kucukelbir et al\n-- 2017).\nupdateReparam\n  :: (Dist b SampleVector, Differentiable c Double) -- Dist a SampleVector,\n  => Int\n  -> (  forall e\n      . (Floating e, Ord e)\n     => V.Vector e\n     -> e\n     -> V.Vector e\n     -> e\n     )\n  -> GenST s\n  -> V.Vector (V.Vector Double)\n  -> DistInvariant b\n  -> DistInvariant c\n  -> DistCell b\n  -> V.Vector (V.Vector (DistCell c))\n  -> ST\n       s\n       (DistCell b, V.Vector (V.Vector (DistCell c)))\nupdateReparam nSamp jointF gen obss thetaG betaG thetaN betasN = do\n  -- obss        <- V.replicateM nObs (resample xss gen)\n  thetaSamp   <- V.replicateM nSamp (resample theta gen)\n  betaSamples <- V.replicateM nSamp (epsilon ((betass V.! 0) V.! 0) gen)\n  let\n    (joints, gradJoints) = V.unzip $ V.zipWith\n      (\\e th ->\n        V.foldl1'\n            (\\(x1, y1) (x2, y2) -> (x1 + x2, V.zipWith (V.zipWith (+)) y1 y2))\n          $ V.map\n              (\\obs ->\n                let (joints', gradss) = V.unzip $ V.zipWith\n                      (\\ob betas -> grad' (jointF (V.map auto th) (auto ob))\n                                          (V.map (\\d -> transform d e) betas)\n                      )\n                      obs\n                      betass\n                in  (V.sum joints', gradss)\n              )\n              (obss :: V.Vector (V.Vector Double))\n      )\n      betaSamples\n      thetaSamp\n  return\n    $ ( gradientScore thetaG thetaN (nFactor, joints, thetaSamp)\n      , V.imap\n        (\\dim v -> V.imap\n          (\\c d -> gradientReparam\n            betaG\n            d\n            (nFactor, V.map ((V.! c) . (V.! dim)) gradJoints, betaSamples)\n          )\n          v\n        )\n        betasN\n      )\n where\n  nFactor = fromIntegral $ V.length obss\n  theta   = dist thetaN\n  betass  = V.map (V.map dist) betasN\n\n-- | transform a log joint to a gradient propagator, for use with\n-- models with a mixture-like plate structure. Updates the mixture\n-- components with the score gradient (Ranganath et al 2014)\nupdateScore\n  :: (Dist a1 c1, Dist a2 c2)\n  => Int\n  -> (c1 -> a3 -> V.Vector c2 -> Double)\n  -> GenST s\n  -> V.Vector (V.Vector a3)\n  -> DistInvariant a1\n  -> DistInvariant a2\n  -> DistCell a1\n  -> V.Vector (V.Vector (DistCell a2))\n  -> ST\n       s\n       ( DistCell a1\n       , V.Vector (V.Vector (DistCell a2))\n       )\nupdateScore nSamp jointF gen obss thetaG betaG thetaN betasN = do\n  -- obss        <- V.replicateM nObs (resample xs gen)\n  thetaSamp   <- V.replicateM nSamp (resample theta gen)\n  betaSamples <- V.replicateM nSamp\n                              (V.mapM (V.mapM (\\b -> resample b gen)) betass)\n  let joints = V.zipWith\n        (\\theta' betass' ->\n          V.foldl1' (V.zipWith (+))\n            . V.map (\\obs -> V.zipWith (jointF theta') obs betass')\n            $ obss\n        )\n        thetaSamp\n        betaSamples\n  return\n    $ ( gradientScore thetaG thetaN (nFactor, V.map V.sum joints, thetaSamp)\n      , V.imap\n        (\\dim v -> V.imap\n          (\\c d -> gradientScore\n            betaG\n            d\n            ( nFactor\n            , V.map (V.! dim) joints\n            , V.map ((V.! c) . (V.! dim)) betaSamples\n            )\n          )\n          v\n        )\n        betasN\n      )\n where\n  -- xs     = dist xsN\n  nFactor = fromIntegral $ V.length obss\n  theta   = dist thetaN\n  betass  = V.map (V.map dist) betasN\n\n-- | generate data for testing mixture model\ngenMixture :: ST s (V.Vector (V.Vector Double))\ngenMixture = do\n  gen <- create\n  let theta' = MWCD.categorical (V.replicate nState 1.0) gen\n  let std    = 1.0\n  let\n    mixtures = V.generate\n      nState\n      (\\k ->\n        (MWCD.normal\n          ((fromIntegral k - (fromIntegral (nState - 1) * 0.5)) * 5)\n          std\n          gen\n        )\n      )\n  xs <- V.replicateM nTime (V.replicateM nDimension . (mixtures V.!) =<< theta')\n  return xs\n\n-- | fit a mixture model, given data\nmixtureFit\n  :: V.Vector (V.Vector Double) -> (Dirichlet, V.Vector (V.Vector NormalDist))\nmixtureFit xs = runST $ do\n  genG <- create\n  gen1 <- initialize =<< V.replicateM 256 (uniform genG)\n  let priorTheta = dirichlet (V.replicate nState 1.0)\n  let priorBeta = normalDistr 0 (5 * (fromIntegral nState - 1) :: Double)\n  let nSamp      = 10\n  let localStep  = (20 :: Int)\n\n  -- initialize distribution cells (both invariant and variants)\n  let thetaGrad = DistInvariant (fromIntegral $ V.length xs)\n                                priorTheta\n                                (rhoKuc defaultKucP) --\n  qTheta <- cellWith $ mergeGeneric globalMaxStep globalDelta\n  write qTheta $ defaultDistCell (dirichlet (V.replicate nState 1.0))\n  let betaGrad = DistInvariant (fromIntegral $ V.length xs)\n                               priorBeta\n                               (rhoKuc defaultKucP) --\n  qBetas <- cellWith $ mergeGenericss globalMaxStep globalDelta\n  write qBetas =<< V.replicateM\n    nDimension\n    (V.generateM\n      nState\n      (\\_i -> do\n        mu <- resample priorBeta gen1\n        return $ defaultDistCell (normalDistr mu (1.0 :: Double))\n      )\n    )\n\n  -- attach gradient propagators to cells\n  stepTogether\n    (updateReparam nSamp (mixtureJoint 1.0) gen1 xs thetaGrad betaGrad)\n    qTheta\n    qBetas\n  -- stepSeparate localStep\n  --              globalDelta\n  --              (updateScore nSamp (mixtureJoint 1.0) gen1 xs thetaGrad betaGrad)\n  --              qTheta\n  --              qBetas\n\n  -- pull content (run network to quiesence)\n  thetaF <- unsafeContent qTheta\n  betaF  <- unsafeContent qBetas\n  let betaDists = V.map (V.map dist) betaF\n  return (dist thetaF, betaDists)\n\n\n--------------------------------------\n-- fit simple normal distribution mean\n--------------------------------------\n-- | generate normally distributed data for testing\ngenNormal :: ST s (V.Vector Double)\ngenNormal = do\n  gen <- create\n  xs  <- V.replicateM 1000 (resample (normalDistr (5.0 :: Double) 3.0) gen)\n  return xs\n\n-- | log joint of normal distribution\njointNormal :: Floating a => a -> a -> a -> a\njointNormal std ob mu = diffableNormalLogProb mu std ob\n\n-- | fit a gaussian using reparam gradient\nnormalFit :: Dist (Obs a) SampleDouble => V.Vector a -> (NormalDist, Time)\nnormalFit xs = runST $ do\n  genG <- create\n  gen1 <- initialize =<< V.replicateM 256 (uniform genG)\n  let nSamp = 100\n  xProp <- known $ defaultObs xs\n  q     <- cellWith $ mergeGeneric globalMaxStep globalDelta\n  write q (defaultDistCell $ normalDistr 0.0 2.0)\n  let qInvar = DistInvariant (fromIntegral $ V.length xs)\n                             (normalDistr 0.0 2.0)\n                             (rhoKuc defaultKucP)\n\n  (\\qP xP -> watch qP $ \\q' -> with xP $ \\xs' ->\n      singleUpdateReparam nSamp (jointNormal 1.0) gen1 qInvar xs' q' >>= write q\n    )\n    q\n    xProp\n  q' <- unsafeContent q\n  return (dist q', time q')\n\n-- | transform a log joint to a gradient propagator for a single\n-- distribution cell, using reparameterization graidient. TODO: more\n-- work on generalizing these types of functions!\nsingleUpdateReparam\n  :: (Dist b SampleDouble, Differentiable c Double)\n  => Int\n  -> (forall  e . (Floating e, Ord e) => e -> e -> e)\n  -> GenST s\n  -> DistInvariant c\n  -> DistCell b\n  -> DistCell c\n  -> ST s (DistCell c)\nsingleUpdateReparam nSamp joint gen qG xsN qN = do\n  obs     <- V.replicateM nSamp (resample xs gen)\n  samples <- V.replicateM nSamp (epsilon q gen)\n  let gradJoint = V.map\n        (\\mu -> V.sum $ V.map (\\ob -> diff (joint (auto ob)) mu) obs)\n        (V.map (transform q) samples)\n  return $ gradientReparam qG qN ((fromIntegral nSamp), gradJoint, samples)\n where\n  xs = dist xsN\n  q  = dist qN\n\n\n---------------------------\n-- simple dirichlet example\n---------------------------\n-- | generate data for testing the fit to a dirichlet\ngenDirichlet :: ST s (V.Vector Int)\ngenDirichlet = do\n  gen <- create\n  xs  <- V.replicateM\n    1000\n    (   resample (dirichlet (V.fromList [10.0, 20.0])) gen\n    >>= \\cat -> MWCD.categorical (cat :: V.Vector Double) gen\n    )\n  return (xs :: V.Vector Int)\n\n-- | git a dirichlet to samples form a categorical\ndirichletFit :: V.Vector Int -> (Dirichlet, Time)\ndirichletFit xs = runST $ do\n  genG <- create\n  gen1 <- initialize =<< V.replicateM 256 (uniform genG)\n  let priorTheta = dirichlet (V.fromList [1.0, 1.0])\n  let nSamp      = 100\n  qTheta <- cellWith $ mergeGeneric globalMaxStep globalDelta\n  let qInvar = DistInvariant 1 priorTheta (rhoKuc defaultKucP)\n  write qTheta (defaultDistCell priorTheta)\n  (\\tP -> watch tP $ \\theta' -> do\n      upTh <- dirichletGradProp nSamp gen1 xs qInvar theta'\n      write tP upTh\n    )\n    qTheta\n  thetaF <- unsafeContent qTheta\n  return (dist thetaF, time thetaF)\n\ndirichletGradProp\n  :: Dist a (V.Vector Double)\n  => Int\n  -> GenST s\n  -> V.Vector Int\n  -> DistInvariant a\n  -> DistCell a\n  -> ST s (DistCell a)\ndirichletGradProp nSamp gen xs qInvar diriQ =\n  V.replicateM nSamp (resample diri gen) >>= \\samples -> return $ gradientScore\n    qInvar\n    diriQ\n    (1, V.map (\\z -> V.sum $ V.map (\\i -> log (z V.! i)) xs) samples, samples)\n  where diri = dist diriQ\n\n----------------------\n-- mixed membership\n----------------------\n\n-- | transform a log joint to a gradient propagator, for use with\n-- models with a mixed-membership-like plate structure. Updates the\n-- mixture components with the reparameterization gradient (Kucukelbir\n-- et al 2017). TODO : generalize all these joint transformer\n-- functions better around the idea of plates\nupdateMembershipReparam\n  :: (Dist b SampleVector, Differentiable c Double) -- Dist a SampleVector,\n  => Int\n  -> (  forall e\n      . (Floating e, Ord e)\n     => V.Vector e\n     -> e\n     -> V.Vector e\n     -> e\n     )\n  -> GenST s\n  -> V.Vector (V.Vector Double)\n  -> DistInvariant b\n  -> DistInvariant c\n  -> V.Vector (DistCell b)\n  -> V.Vector (V.Vector (DistCell c))\n  -> ST\n       s\n       ( V.Vector (DistCell b)\n       , V.Vector (V.Vector (DistCell c))\n       )\nupdateMembershipReparam nSamp jointF gen obss thetaG betaG thetaN betasN = do\n  thetaSamples <- V.replicateM nSamp (V.mapM (\\th -> resample th gen) thetas)\n  betaSamples  <- V.replicateM nSamp (epsilon ((betass V.! 0) V.! 0) gen)\n  let (joints, gradJoints) = V.unzip $ V.zipWith\n        (\\e ths -> V.unzip $ V.zipWith\n          (\\obs th ->\n            let (joints', gradss) = V.unzip $ V.zipWith\n                  (\\ob betas -> grad' (jointF (V.map auto th) (auto ob))\n                                      (V.map (\\d -> transform d e) betas)\n                  )\n                  obs\n                  betass\n            in  (V.sum joints', gradss)\n          )\n          (obss :: V.Vector (V.Vector Double))\n          ths\n        )\n        betaSamples\n        thetaSamples\n  return\n    $ ( V.imap\n        (\\i thN -> gradientScore\n          thetaG\n          thN\n          (nFactor, V.map (V.! i) joints, (V.map (V.! i) thetaSamples))\n        )\n        thetaN\n      , V.imap\n        (\\dim v -> V.imap\n          (\\c d -> gradientReparam\n            betaG\n            d\n            ( nFactor\n            , V.map (V.sum . V.map ((V.! c) . (V.! dim))) gradJoints\n            , betaSamples\n            )\n          )\n          v\n        )\n        betasN\n      )\n where\n  nFactor = fromIntegral $ V.length obss\n  thetas  = V.map dist thetaN\n  betass  = V.map (V.map dist) betasN\n\n\n-- | transform a log joint to a gradient propagator, for use with\n-- models with a mixed membership-like plate structure. Updates the\n-- mixture components with the score gradient (Ranganath et al\n-- 2014). TODO: generalize these log joint to gradient propagator\n-- transformer functions\nupdateMembershipScore\n  :: (Dist a1 c1, Dist a2 c2)\n  => Int\n  -> (c1 -> a3 -> V.Vector c2 -> Double)\n  -> GenST s\n  -> V.Vector (V.Vector a3)\n  -> DistInvariant a1\n  -> DistInvariant a2\n  -> V.Vector (DistCell a1)\n  -> V.Vector (V.Vector (DistCell a2))\n  -> ST\n       s\n       ( V.Vector (DistCell a1)\n       , V.Vector (V.Vector (DistCell a2))\n       )\nupdateMembershipScore nSamp jointF gen obss thetaG betaG thetasN betasN = do\n  -- obss        <- V.replicateM nObs (resample xs gen)\n  thetaSamples <- V.replicateM nSamp\n                               (V.mapM (\\theta -> resample theta gen) thetas)\n  betaSamples <- V.replicateM nSamp\n                              (V.mapM (V.mapM (\\b -> resample b gen)) betass)\n  let joints = V.zipWith\n        (\\thetas' betass' ->\n          V.zipWith (\\obs theta -> V.zipWith (jointF theta) obs betass') obss\n            $ thetas'\n        )\n        thetaSamples\n        betaSamples\n  return\n    $ ( V.imap\n        (\\i thetaN -> gradientScore\n          thetaG\n          thetaN\n          (nFactor, V.map (V.sum . (V.! i)) joints, V.map (V.! i) thetaSamples)\n        )\n        thetasN\n      , V.imap\n        (\\dim v -> V.imap\n          (\\c d -> gradientScore\n            betaG\n            d\n            ( nFactor\n            , V.map (V.sum . V.map (V.! dim)) joints\n            , V.map ((V.! c) . (V.! dim)) betaSamples\n            )\n          )\n          v\n        )\n        betasN\n      )\n where\n  -- xs     = dist xsN\n  nFactor = fromIntegral $ V.length obss\n  thetas  = V.map dist thetasN\n  betass  = V.map (V.map dist) betasN\n\n\n-- | generate data for testing a Gaussian mixed membership model\ngenMixedMem :: ST s (V.Vector (V.Vector (Double))) -- Maybe Double\ngenMixedMem = do\n  gen <- create\n  -- initialize dirichlet that favors sparse categoricals\n  let diriParam  = 0.01\n  let thetaParam = MWCD.dirichlet (V.replicate nState diriParam) gen\n  thetasTrue <- V.replicateM nTime thetaParam\n  let thetas' = V.map (\\theta' -> MWCD.categorical theta' gen) thetasTrue\n  let betaStd = 0.001\n  let betas' = V.generate\n        nState\n        (\\k -> V.replicate\n          nDimension\n          (MWCD.normal\n            ((fromIntegral k - (fromIntegral (nState - 1) * 0.5)) * 5)\n            betaStd\n            gen\n          )\n        )\n  xs <- V.generateM\n    nTime\n    (\\day -> V.generateM\n      nDimension\n      (\\loc -> (thetas' V.! day) >>= \\z -> ((betas' V.! z) V.! loc)) -- Just <$>\n    )\n  return xs\n\n-- | fit a Gaussian mixed membership model to data\nmixedMemFit\n  :: V.Vector (V.Vector Double)\n  -> (V.Vector Dirichlet, V.Vector (V.Vector NormalDist))\nmixedMemFit xs = runST $ do\n  genG <- create\n  gen1 <- initialize =<< V.replicateM 256 (uniform genG)\n  let priorTheta = dirichlet (V.replicate nState 1.0)\n  let priorBeta = normalDistr 0 (5 * (fromIntegral nState - 1) :: Double)\n  let nSamp      = 10\n  -- let localStep  = 20\n  let betaGrad = DistInvariant (fromIntegral $ V.length xs)\n                               priorBeta\n                               (rhoKuc defaultKucP)\n  qBetas <- cellWith $ mergeGenericss globalMaxStep globalDelta\n  write qBetas =<< V.generateM\n    nDimension\n    (\\_i -> V.replicateM\n      nState\n      (do\n        mu <- resample priorBeta gen1\n        return $ defaultDistCell (normalDistr mu 1.0)\n      )\n    )\n  qThetas <- cellWith $ mergeGenerics globalMaxStep globalDelta\n  write qThetas $ V.replicate nTime (defaultDistCell priorTheta)\n  let thetaGrad = DistInvariant (fromIntegral $ V.length xs)\n                                priorTheta\n                                (rhoKuc defaultKucP)\n  stepTogether\n    (updateMembershipReparam nSamp (mixtureJoint 1.0) gen1 xs thetaGrad betaGrad\n    )\n    qThetas\n    qBetas\n  -- stepSeparate localStep\n  --              globalDelta\n  --              (updateMembershipScore nSamp (mixtureJoint 1.0) gen1 xs thetaGrad betaGrad)\n  --              qThetas\n  --              qBetas\n  thetaF <- unsafeContent qThetas\n  betaF  <- unsafeContent qBetas\n  return (V.map dist thetaF, V.map (V.map dist) betaF)\n", "meta": {"hexsha": "3f67a04dcb212ef13bc2a68ede26d43144517b79", "size": 17512, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/BBVI/Examples.hs", "max_stars_repo_name": "massma/propagator-bbvi", "max_stars_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/BBVI/Examples.hs", "max_issues_repo_name": "massma/propagator-bbvi", "max_issues_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/BBVI/Examples.hs", "max_forks_repo_name": "massma/propagator-bbvi", "max_forks_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1601423488, "max_line_length": 93, "alphanum_fraction": 0.5660118776, "num_tokens": 5037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47601427747456376}}
{"text": "module Tests.ComplexFromIntegral where\nimport Data.Complex\n\nrunTest = do\n  putStrLn $ show $ p' where\n    p' = zipWith (*) (map (fromIntegral) [1..3]) p\n    p = [1 :+ 0, 2 :+ 0, 3 :+ 0]\n", "meta": {"hexsha": "b535037460dbaa24f097c7ea566e9c7529e61703", "size": 186, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Tests/ComplexFromIntegral.hs", "max_stars_repo_name": "freizl/haste-compiler", "max_stars_repo_head_hexsha": "47d942521570eb4b8b6828b0aa38e1f6b9c3e8a8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 906, "max_stars_repo_stars_event_min_datetime": "2015-01-01T22:07:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:36:25.000Z", "max_issues_repo_path": "Tests/ComplexFromIntegral.hs", "max_issues_repo_name": "freizl/haste-compiler", "max_issues_repo_head_hexsha": "47d942521570eb4b8b6828b0aa38e1f6b9c3e8a8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 168, "max_issues_repo_issues_event_min_datetime": "2015-01-01T12:58:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T15:22:09.000Z", "max_forks_repo_path": "Tests/ComplexFromIntegral.hs", "max_forks_repo_name": "freizl/haste-compiler", "max_forks_repo_head_hexsha": "47d942521570eb4b8b6828b0aa38e1f6b9c3e8a8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2015-01-23T10:38:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T19:30:18.000Z", "avg_line_length": 23.25, "max_line_length": 50, "alphanum_fraction": 0.6021505376, "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.47565406690018086}}
{"text": "{-# LANGUAGE CPP #-}\n\nmodule Year2021.Day15 where\n\nimport Numeric.LinearAlgebra\nimport Util\nimport Safe\nimport Linear.V2\nimport System.FilePath\nimport Data.Bifunctor\n\npart1, part2 :: Int\npart1 = 1\npart2 = 5\n\nmain = readFile (replaceExtension __FILE__ \".in\") >>= \\input ->\n  let grid = fromLists . map (map (read . pure)) $ lines input :: Matrix Z\n      grid' = cmod 9 (fromBlocks [[grid + scalar (r + c) | c <- [0..4]] | r <- [0..4]] - 1) + 1\n      neigh (a, b) = [ (grid' ! x ! y, (x, y))\n        | p@(V2 x y) <- (+ V2 a b) <$> adjacent\n        , inBounds 0 (uncurry V2 (size grid') - 1) p ]\n   in print . fst . findJust ((== size grid') . bimap succ succ . head . snd)\n        $ dijkstra neigh (0, 0)\n\n", "meta": {"hexsha": "14e520bdc4dabfc263fa9dcb0b23c0caf25deae1", "size": 704, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Year2021/Day15.hs", "max_stars_repo_name": "mingmingrr/advent-of-code-2018", "max_stars_repo_head_hexsha": "89b6f0474877f954aea0528069b5553d18174a99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-14T06:02:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-14T06:02:01.000Z", "max_issues_repo_path": "src/Year2021/Day15.hs", "max_issues_repo_name": "mingmingrr/advent-of-code-2018", "max_issues_repo_head_hexsha": "89b6f0474877f954aea0528069b5553d18174a99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Year2021/Day15.hs", "max_forks_repo_name": "mingmingrr/advent-of-code-2018", "max_forks_repo_head_hexsha": "89b6f0474877f954aea0528069b5553d18174a99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.16, "max_line_length": 95, "alphanum_fraction": 0.5809659091, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.475609605880849}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE RankNTypes #-}\n-----------------------------------------------------------------------------\n--\n-- Module      :  AI.Network.RMM.LSTM\n-- Copyright   :  (c) JP Moresmau\n-- License     :  BSD3\n--\n-- Maintainer  :  JP Moresmau <jp@moresmau.fr>\n-- Stability   :  experimental\n-- Portability :\n--\n-- | Long Short Term Memory networks\n--\n-----------------------------------------------------------------------------\n\nmodule AI.Network.RNN.LSTM where\n\nimport Control.DeepSeq\n\n\nimport Data.List\n\nimport Numeric.LinearAlgebra.HMatrix\n\nimport AI.Network.RNN.Types\nimport AI.Network.RNN.Util\nimport AI.Network.RNN.Expr\nimport Debug.Trace\nimport qualified Data.IntMap as I\n\nimport Numeric.AD\n\n-- | The LSTM data type, with the different weights and states\ndata LSTMNetwork = LSTMNetwork\n    { lstmSize :: !Int\n    , lstmWeightsW :: !(Matrix Double)\n    , lstmWeightsU :: !(Matrix Double)\n    , lstmBias :: !(Vector Double)\n    , lstmState :: !(Vector Double)\n    , lstmOutput :: !(Vector Double)\n    } deriving (Show,Read,Eq)\n\n--instance Show LSTMNetwork where\n--     show s = let\n--        a= show $ (rnnsize s,toVector s)\n--        in trace (show $ length a) a\n--\n--instance Read LSTMNetwork where\n--    readsPrec d s =\n--        let [(ok,r)] = readsPrec d s\n--            dat = uncurry fromVector ok\n--        in [(dat,r)]\n\n-- | Force evaluation instance\ninstance NFData LSTMNetwork where\n    rnf LSTMNetwork{..} = rnf (lstmSize,lstmWeightsW,lstmWeightsU,lstmBias,lstmState,lstmOutput)\n\n-- | Implement the network evaluation and conversions functions\ninstance RNNEval LSTMNetwork where\n    type Size LSTMNetwork = Int\n    evalStep n@LSTMNetwork{..} is =\n        let z = (lstmWeightsW #> is) + (lstmWeightsU #> lstmOutput) + lstmBias\n            [i,f,c1,o] = takesV (replicate 4 lstmSize) z\n            c2 = cmap tanh c1\n            ns = (c2 * cmap sigmoid i) + (cmap sigmoid f * lstmState)\n            no = cmap sigmoid o * cmap tanh ns\n        in force (n{lstmState=ns,lstmOutput=no},no)\n    fromVector sz vs =\n        let\n            msize = sz * sz\n            [v1,v2,v3,v4,v5] = takesV [msize * 4,msize * 4, sz * 4,sz,sz] vs\n            m1 = reshape sz v1\n            m2 = reshape sz v2\n        in LSTMNetwork sz m1 m2 v3 v4 v5\n    toVector LSTMNetwork{..} = force $ vjoin\n        [ flatten lstmWeightsW, flatten lstmWeightsU, lstmBias, lstmState, lstmOutput]\n    rnnsize = lstmSize\n    fullSize = lstmFullSize .lstmSize\n\n-- | Full size of a network\nlstmFullSize :: FullSize LSTMNetwork\nlstmFullSize sz = (sz * sz) * 8 + sz* 4 + sz + sz\n\ndata LSTMIO = LSTMIO\n    { lioInput :: Matrix Double\n    , lioLstms :: [LSTMNetwork]\n    , lioOutput :: Matrix Double\n    , lioSer   :: Maybe (Vector Double)\n    } deriving (Eq)\n\ninstance NFData LSTMIO where\n  rnf LSTMIO{..} = rnf (lioInput,lioLstms,lioOutput)\n\ninstance RNNEval LSTMIO  where\n    type Size LSTMIO = (Int,Int,Int,Int)\n    evalStep io@LSTMIO{..} is =\n        let inps = cmap sigmoid $ lioInput #> (vjoin [is,scalar 1])\n            (lstm2,outs) = evalStep lioLstms inps\n        in (io{lioLstms=lstm2,lioSer=Nothing},lioOutput #> outs)\n    fromVector (is,lnnSize,lnnNumber,os) vs =\n        let [v1,v2,v3] = takesV [(is+1)* lnnSize ,lnnNumber * (lstmFullSize lnnSize),os * lnnSize ] vs\n            m1 = reshape (is+1) v1\n            m2 = reshape lnnSize v3\n        in LSTMIO m1 (fromVector (replicate lnnNumber lnnSize) v2) m2 $ Just vs\n    toVector LSTMIO{..} = case lioSer of\n        Just vs -> vs\n        Nothing -> vjoin [flatten lioInput,toVector lioLstms,flatten lioOutput]\n    rnnsize LSTMIO{..} = (cols lioInput - 1, rnnsize $ head lioLstms, length lioLstms,rows lioOutput)\n    fullSize =lstmioFullSize . rnnsize\n--        let (r1,c1)=size lioInput\n--            (r2,c2)=size lioOutput\n--        in (r1*c1) + (fullSize lioLstms) + (r2*c2)\n\ninstance Show LSTMIO where\n    show l = show (rnnsize l,toVector l)\n\ninstance Read LSTMIO where\n    readsPrec d s =\n        let [(ok,r)] = readsPrec d s\n            dat = uncurry fromVector ok\n        in [(dat,r)]\n\nlstmioFullSize :: FullSize LSTMIO\nlstmioFullSize (is,lnnSize,lnnNumber,os) = (is+1) * lnnSize + lnnNumber * (lstmFullSize lnnSize) + os * lnnSize\n\ndata LSTMList = LSTMList\n    { llSize :: (Int,Int,Int,Int)\n    , llData :: [Double]\n    } deriving (Show, Read, Eq)\n\ninstance NFData LSTMList where\n  rnf LSTMList{..} = rnf (llSize,llData)\n\ninstance RNNEval LSTMList where\n    type Size LSTMList = (Int,Int,Int,Int)\n    rnnsize = llSize\n    fullSize =lstmioFullSize . rnnsize\n    toDList = llData\n    fromDList sz = LSTMList sz\n    toVector = fromList . toDList\n    fromVector sz = fromDList sz . toList\n    evalStep l@LSTMList{..} is =\n        let lstmio :: LSTMIO = fromDList llSize llData\n            (io2,out) = evalStep lstmio is\n        in (l{llData=toDList io2},out)\n\n\n-- | Implementation of the LSTM evaluation step without explicit matrices and vectors\n-- just using lists, so we can use AD on it\nlstmList :: (Num b,Floating b) => Int -> [b] -> [b] -> ([b],[b])\nlstmList sz lstm is = let\n    msize = sz * sz\n    [mW,mU,vB,vS,vO] = takes [msize * 4,msize * 4, sz * 4,sz,sz] lstm\n    z = zipWith3 (\\a b c->a+b+c) (listMProd mW is) (listMProd mU vO) vB\n    [i,f,c1,o] = takes (replicate 4 sz) z\n    c2 = map tanh c1\n    ns = zipWith (+) (zipWith (*) c2 (map sigmoid i)) (zipWith (*) (map sigmoid f) vS)\n    no = zipWith (*) (map sigmoid o) (map tanh ns)\n    in (mW++mU++vB++ns++no,no)\n\n-- | Cost calculation using list representation for AD\ncost' :: (Num b,Floating b,Fractional b) => Int -> [[b]] -> [[b]] -> [b] -> b\ncost' sz is os lstm = let\n    (_,res) = mapAccumL (lstmList sz) lstm is\n--    in - (calcMeanList $ three (last res) (last os))\n--    in - (calcMeanList $ concat $ zipWith (three) res os)\n    in sum $ zipWith err os res\n    where\n      err :: (Num b,Floating b) => [b] -> [b] -> b\n      err a b  = sum (zipWith (\\c d -> (c- d)**2 ) a b)\n--      one i o = zipWith (*) o (map log i)\n--      two i o = zipWith (*) (map (\\x->1 - x) o) (map (\\x->1 - log x) i)\n--      three i o= zipWith (+) (one i o) (two i o)\n\n-- | Gradient descent learning\n-- The third parameter is a call back function to monitor progress and stop the learning process if needed\nlearnGradientDescent :: (Monad m) => LSTMNetwork -> TrainData a -> (LSTMNetwork -> TrainData a -> Int -> m Bool) -> m LSTMNetwork\nlearnGradientDescent lstm td progressF =  go (toList $ toVector lstm) 0\n    -- go2 gds 0\n    where\n      go2 (ls:lss) gen =  do\n        let rnn::LSTMNetwork = fromVector (tdRecSize td) (fromList ls)\n        cont <- progressF rnn td gen\n        if cont\n            then go2 lss (gen+1)\n            else return rnn\n      go ls gen = do\n        let rnn::LSTMNetwork = fromVector (tdRecSize td) (fromList ls)\n        cont <- progressF rnn td gen\n        if cont\n            then do\n                let\n                    gs= gf ls -- gradients using AD\n                    ls2 = zipWith (\\o g->o-g*0.1) ls gs\n                go ls2 (gen+1)\n            else return rnn\n      lis = map toList (tdInputs td)\n      los = map toList (tdOutputs td)\n      gf = grad (cost' (tdRecSize td) (map (map auto) lis) (map (map auto) los))\n      gds = gradientDescent (cost' (tdRecSize td) (map (map auto) lis) (map (map auto) los)) (toList $ toVector lstm)\n\n-- | Gradient descent learning using symbolic differentiation\n--   The goal was to calculate the derivative once and then just close and eval the result using the current data\n--   However it is much slower than normal automatic differentiation\nlearnGradientDescentSym :: (Monad m) => LSTMNetwork -> TrainData a -> (LSTMNetwork -> TrainData a -> Int -> m Bool) -> m LSTMNetwork\nlearnGradientDescentSym lstm td progressF =  go (toList $ toVector lstm) 0\n    where\n      go ls gen = do\n        let rnn::LSTMNetwork = fromVector (tdRecSize td) (fromList ls)\n        cont <- progressF rnn td gen\n        if cont\n            then do\n                let\n                    i = I.fromList $ zip [0..] ls\n                    cexpr = map (\\g-> close g i) gf\n                    gs = map eval cexpr\n                    ls2 = zipWith (\\o g->o-g*0.1) ls gs\n                go ls2 (gen+1)\n            else return rnn\n      lis = map toList (tdInputs td)\n      los = map toList (tdOutputs td)\n      ls0 = toList $ toVector lstm\n      gf = map fullSimplify $ grad (cost'\n            (tdRecSize td)\n            (map (map (\\x -> autoEval (Lit $ Lit x) I.empty)) lis)\n            (map (map (\\x -> autoEval (Lit $ Lit x) I.empty)) los))\n            (zipWith (\\_ i->Var i) ls0 [0..])\n\n-- | RMSProp learning, as far as I can make out\n-- The third parameter is a call back function to monitor progress and stop the learning process if needed\nlearnRMSProp :: (Monad m) => LSTMNetwork -> TrainData a -> (LSTMNetwork -> TrainData a -> Int -> m Bool) -> m LSTMNetwork\nlearnRMSProp lstm td progressF = go ls0 (replicate myl 0) (replicate myl 0) (replicate myl 0) 0\n    where\n      go ls rgs rgs2 ugs gen = do\n        let rnn::LSTMNetwork = fromVector (tdRecSize td) (fromList ls)\n        cont <- progressF rnn td gen\n        if cont\n            then do\n                let\n                    gs= gf ls -- gradients using AD\n                    rgup = zipWith (\\rg g-> 0.95 * rg + 0.05 * g) rgs ls\n                    rg2up = zipWith (\\rg2 g-> 0.95 * rg2 + 0.05 * (g ** 2)) rgs2 ls\n                    ugup = zipWith4 (\\ud zg rg rg2 -> 0.9 * ud - 1e-4 * zg / sqrt(rg2 - rg ** 2 + 1e-4)) ugs gs rgup rg2up\n                    ls2 = zipWith (+) ls ugup\n                go (force ls2) (force rgup) (force rg2up) (force ugup) (gen+1)\n            else return rnn\n      lis = map toList (tdInputs td)\n      los = map toList (tdOutputs td)\n      gf = grad (cost' (tdRecSize td) (map (map auto) lis) (map (map auto) los))\n      ls0 = toList $ toVector lstm\n      myl= length ls0\n", "meta": {"hexsha": "dbd89e2d338f69d01b935e178b583f77370a0603", "size": 10009, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Network/RNN/LSTM.hs", "max_stars_repo_name": "JPMoresmau/rnn", "max_stars_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-08-02T17:48:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T06:56:40.000Z", "max_issues_repo_path": "src/AI/Network/RNN/LSTM.hs", "max_issues_repo_name": "JPMoresmau/rnn", "max_issues_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-01T18:47:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-01T18:47:41.000Z", "max_forks_repo_path": "src/AI/Network/RNN/LSTM.hs", "max_forks_repo_name": "JPMoresmau/rnn", "max_forks_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-12-10T18:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-24T00:02:09.000Z", "avg_line_length": 38.7945736434, "max_line_length": 132, "alphanum_fraction": 0.5927665101, "num_tokens": 3070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.47560708403413265}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE TemplateHaskell   #-}\n{-# LANGUAGE UnicodeSyntax     #-}\n{-# LANGUAGE BangPatterns      #-}\nmodule NLP.Albemarle.LSA\n    (-- * Creating a model\n    lsa\n    -- * Managing terms\n    , rebase\n    -- * Managing topics\n    , pad\n    , trim\n    -- * Internal methods (may be subject to change)\n    , SVD.sparsify\n    , SVD.sparseSvd\n    , batchLSA\n    -- * Types (may be subject to change)\n    , LSAModel(..)\n    , termvectors\n    , topicweights\n    ) where\nimport NLP.Albemarle\nimport NLP.Albemarle.Dict (Dict)\nimport qualified NLP.Albemarle.Dict as Dict\nimport ClassyPrelude hiding (Vector)\nimport qualified Data.Vector.Generic as Vec\nimport qualified Data.Vector.Unboxed as UVec\nimport qualified Data.Vector.Storable as SVec\nimport qualified Data.HashMap.Strict as HashMap\nimport Numeric.LinearAlgebra (Vector, Matrix, tr, diag, (|||), (===))\nimport qualified Numeric.LinearAlgebra as HMatrix\nimport qualified Numeric.LinearAlgebra.Devel as HMatrix\nimport qualified Numeric.LinearAlgebra.SVD.SVDLIBC as SVD\nimport qualified System.IO.Streams as Streams\nimport System.IO.Streams (Generator, InputStream, OutputStream)\nimport Lens.Micro.TH\nimport Lens.Micro\nimport Data.Tuple\n\n-- | An LSA model (The singular values and right singular vectors of truncated\n--   SVD on a term-document matrix, where documents are rows and terms columns)\ndata LSAModel = LSAModel {\n  _topicweights :: !(HMatrix.Vector Double), -- ^ Topic weights\n  _termvectors :: !(Matrix Double) -- ^ Rows are topics, columns are terms\n} deriving (Show, Eq)\nmakeLenses ''LSAModel\n\n-- This instance may be a fib. I'm not sure this is actually associative.\n-- Even if it is, I imagine there are practical numerical stability concerns.\n-- TODO: In particular, I think we need to weight the left and weight according\n-- to how many documents they represent.\ninstance Monoid LSAModel where\n  mempty = LSAModel mempty mempty\n  mappend left right\n    | left == mempty = right\n    | right == mempty = left\n    | otherwise = trim target_len $ pad target_len $ LSAModel s v\n    where\n      target_len = max (topicCount left) (topicCount right)\n      (s, v) = HMatrix.rightSV $ combine left === combine right\ninstance Semigroup LSAModel where\n  (<>) = mappend\n\n-- | Truncate an LSAModel to a specific number of topics, if there are too many\ntrim :: Int -- ^ The maximum number of topics the model should have (inclusive)\n     -> LSAModel -> LSAModel\ntrim count model\n  | topicCount model <= count = model\n  | otherwise = LSAModel\n    (Vec.take count $ model^.topicweights)\n    (HMatrix.takeRows count $ model^.termvectors)\n\n-- | Pad an LSAModel with extra empty topics of there are too few\npad :: Int -- ^ The minimum number of topics the model should have (inclusive)\n    -> LSAModel -> LSAModel\npad count model\n  | topicCount model >= count = model\n  | otherwise = let\n    (height, width) = HMatrix.size $ model^.termvectors\n    missing = count - height\n    in LSAModel\n      (model^.topicweights <> Vec.replicate missing 0)\n      (model^.termvectors === HMatrix.konst 0 (missing, width))\n\n-- | Multiply the vectors and values of an SVD to make one matrix\ncombine :: LSAModel -> Matrix Double\ncombine model = diag (model^.topicweights) <> (model^.termvectors)\n\nsparseToCSR :: SparseMatrix -> HMatrix.CSR\nsparseToCSR (SparseMatrix width vecs) =\n  let\n    docs = (Vec.fromList . (\\ (SparseVector len wds) -> wds) <$> vecs)\n    convI = Vec.map fromIntegral . Vec.convert\n    counts = Vec.map snd <$> docs         :: [UVec.Vector Double]\n    concatcounts = Vec.concat counts      ::  UVec.Vector Double\n    storcounts = Vec.convert concatcounts ::  SVec.Vector Double\n  in HMatrix.CSR {\n    HMatrix.csrVals = storcounts,\n    HMatrix.csrCols = convI\n      $ Vec.concat\n      $ Vec.map ((+1).fst)\n      <$> docs,\n    HMatrix.csrRows = convI\n      $ Vec.scanl (+) 1\n      $ Vec.fromList\n      $ Vec.length\n      <$> docs,\n    HMatrix.csrNCols = width,\n    HMatrix.csrNRows = length docs\n  }\n\n-- | Generate an LSA Model with N topics, based on a sparse matrix.\n--\n--   You can make the sparse matrix with a Dict and some documents.\n--   See Dict.asSparseMatrix.\nlsa :: Int -- ^ Number of vectors/dimensions in the new space\n    -> SparseMatrix -- ^ Sparse representation of the term-document matrix\n    -> LSAModel -- ^ A dense representation of the term-topic matrix\nlsa top_vectors termdoc =\n  -- This astounds me, but the number of singular values may not match the\n  -- number of singular vectors. We have to balance before padding.\n  pad top_vectors $ case compare missing_values 0 of\n    LT -> LSAModel (Vec.take top_vectors s) vt\n    EQ -> LSAModel s vt\n    GT -> LSAModel (s <> Vec.replicate missing_values 0) vt\n  where\n    (u, s, vt) = SVD.sparseSvd top_vectors $ sparseToCSR termdoc\n    missing_values = fst (HMatrix.size vt) - Vec.length s\n\n-- | Rebase an LSA model made with one Dict to one made with another Dict.\n--\n--   By using this, you can split a corpus into batches, make Dicts and topic\n--   models, then merge the Dicts, rebase the Models to the merged Dict, and\n--   then merge the models. It allows working in parallel, and limits memory\n--   usage.\nrebase :: Dict -> Dict -> LSAModel -> LSAModel\nrebase d1 d2 model\n  | model == mempty = mempty\n  | otherwise = LSAModel {\n    _termvectors = (HMatrix.\u00bf) (model^.termvectors) $ Dict.select d1 d2,\n    _topicweights = model^.topicweights\n  }\n\n-- | Get the number of topics in a model\ntopicCount :: LSAModel -> Int\ntopicCount model = Vec.length $ model^.topicweights\n\n\n-- | SVD with some transposes, for convenience and speed\n-- Normally (U, Sigma, V^T) = svd A, but then the rows are topics and the cols\n-- are the documents/words (in U and V). But we use C-style (row major) matrices\n-- which means for large matrices, getting the vector of one word or one doc\n-- will require reading the whole model from memory. (A terrible waste of cache)\n-- So instead we use (U^T, sigma, V) where the rows are the vector embeddings\n-- of documents and words instead.\n--\n-- Prefer lsa (rather than batchLSA) - batchLSA is experimental and may be\n-- removed\nbatchLSA :: Int -> HMatrix.CSR -> (Matrix Double, HMatrix.Vector Double, Matrix Double)\nbatchLSA top_vectors csr = (tr u, s, tr vt)\n  where (u, s, vt) = SVD.sparseSvd top_vectors csr\n", "meta": {"hexsha": "7b422f613a3061c1b332b6ac4095b6fd61b8b4e2", "size": 6327, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NLP/Albemarle/LSA.hs", "max_stars_repo_name": "SeanTater/albemarle", "max_stars_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-07-16T15:06:24.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-19T00:51:45.000Z", "max_issues_repo_path": "src/NLP/Albemarle/LSA.hs", "max_issues_repo_name": "SeanTater/albemarle", "max_issues_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-05-05T14:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-04T14:04:54.000Z", "max_forks_repo_path": "src/NLP/Albemarle/LSA.hs", "max_forks_repo_name": "SeanTater/albemarle", "max_forks_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8159509202, "max_line_length": 87, "alphanum_fraction": 0.7008060692, "num_tokens": 1693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.47538978366375173}}
{"text": "-- test for trac #8532\n\nimport Data.Complex\n\nmain :: IO ()\nmain = do\n    print $ acosh ((-1)::Complex Double)\n    print $ acosh ((-1)::Complex Float)\n", "meta": {"hexsha": "c45e32203029c5cd5729118cb62b6ad284d0ac15", "size": 150, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/ghc/numeric/numrun016.hs", "max_stars_repo_name": "hsyl20/ghcjs", "max_stars_repo_head_hexsha": "0cfbbe2d92881016edc1087de7a0982ada71e180", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2133, "max_stars_repo_stars_event_min_datetime": "2015-01-05T12:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T19:23:54.000Z", "max_issues_repo_path": "test/ghc/numeric/numrun016.hs", "max_issues_repo_name": "hsyl20/ghcjs", "max_issues_repo_head_hexsha": "0cfbbe2d92881016edc1087de7a0982ada71e180", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 534, "max_issues_repo_issues_event_min_datetime": "2015-01-03T20:10:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T20:00:31.000Z", "max_forks_repo_path": "test/ghc/numeric/numrun016.hs", "max_forks_repo_name": "hsyl20/ghcjs", "max_forks_repo_head_hexsha": "0cfbbe2d92881016edc1087de7a0982ada71e180", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 209, "max_forks_repo_forks_event_min_datetime": "2015-01-31T11:25:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T19:18:34.000Z", "avg_line_length": 16.6666666667, "max_line_length": 40, "alphanum_fraction": 0.6066666667, "num_tokens": 46, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.47531352271528143}}
{"text": "{-# LANGUAGE CPP                        #-}\n{-# LANGUAGE PolyKinds                  #-}\n{-# LANGUAGE ConstraintKinds            #-}\n{-# LANGUAGE DefaultSignatures          #-}\n{-# LANGUAGE DeriveFunctor              #-}\n{-# LANGUAGE DeriveGeneric              #-}\n{-# LANGUAGE FlexibleContexts           #-}\n{-# LANGUAGE FlexibleInstances          #-}\n{-# LANGUAGE RebindableSyntax           #-}\n{-# LANGUAGE TypeOperators              #-}\n{-# LANGUAGE TypeFamilies               #-}\n\nmodule Data.Semimodule.Algebra (\n  -- * Algebras \n    Algebra(..)\n  -- * Unital algebras \n  , Unital(..)\n  -- * Coalgebras \n  , Coalgebra(..)\n  -- * Unital coalgebras \n  , Counital(..)\n  -- * Bialgebras \n  , Bialgebra\n) where\n\nimport Control.Arrow\nimport Control.Applicative\nimport Control.Category (Category, (<<<), (>>>))\nimport Data.Bool\nimport Data.Complex\nimport Data.Finite (Finite, finites)\nimport Data.Fixed\nimport Data.Functor.Apply\nimport Data.Functor.Compose\nimport Data.Functor.Contravariant\nimport Data.Functor.Product\nimport Data.Functor.Rep\nimport Data.Functor.Rep\nimport Data.Int\nimport Data.Semiring\nimport Data.Semimodule\nimport Data.Sequence hiding (reverse,index)\nimport Data.Tuple (swap)\nimport Data.Word\nimport Foreign.C.Types (CFloat(..),CDouble(..))\nimport GHC.Real hiding (Fractional(..))\nimport GHC.TypeNats (KnownNat(..))\nimport Numeric.Natural\nimport Prelude (Ord, reverse)\nimport Prelude (fromInteger)\nimport Prelude hiding (Num(..), Fractional(..), negate, sum, product)\nimport qualified Control.Category as C\nimport qualified Control.Monad as M\nimport qualified Data.IntSet as IntSet\nimport qualified Data.Map as Map\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as Set\n\n\n\n-------------------------------------------------------------------------------\n-- Algebras\n-------------------------------------------------------------------------------\n\n-- | An < https://en.wikipedia.org/wiki/Algebra_over_a_field#Generalization:_algebra_over_a_ring algebra > over a semiring.\n--\n-- Note that the algebra < https://en.wikipedia.org/wiki/Non-associative_algebra needn't be associative >.\n--\nclass Semiring a => Algebra a b where\n\n    -- |\n    --\n    -- @\n    -- 'joined' = 'Data.Semimodule.Free.over' 'Data.Semimodule.Free.diagonal' '.' 'uncurry'\n    -- @\n    --\n    joined :: (b -> b -> a) -> b -> a\n\n\n-- | A < https://en.wikipedia.org/wiki/Algebra_over_a_field#Unital_algebra unital algebra > over a semiring.\n--\nclass Algebra a b => Unital a b where\n\n    -- | Obtain a vector from the unit of a unital algebra.\n    --\n    -- @\n    -- 'unital' = 'Data.Semimodule.Transform.over' 'initial' '.' 'const'\n    -- @\n    --\n    unital :: a -> b -> a\n\n-------------------------------------------------------------------------------\n-- Coalgebras\n-------------------------------------------------------------------------------\n\n\n-- | A coalgebra over a semiring.\n--\nclass Semiring a => Coalgebra a c where\n\n    -- |\n    --\n    -- @\n    -- 'cojoined' = 'curry' '.' 'Data.Semimodule.Free.over' 'Data.Semimodule.Free.codiagonal'\n    -- @\n    --\n    cojoined :: (c -> a) -> c -> c -> a\n  \n-- | A counital coalgebra over a semiring.\n--\nclass Coalgebra a c => Counital a c where\n\n    -- |\n    --\n    -- @\n    -- 'Data.Semimodule.Free.Cov' 'counital' = 'Data.Semimodule.Free.coover' 'Data.Semimodule.Free.coinitial' $ pure '()'\n    -- @\n    --\n    counital :: (c -> a) -> a\n\n-------------------------------------------------------------------------------\n-- Bialgebras\n-------------------------------------------------------------------------------\n\n-- | A < https://en.wikipedia.org/wiki/Bialgebra bialgebra > over a semiring.\n--\nclass (Unital a b, Counital a b) => Bialgebra a b\n\n-------------------------------------------------------------------------------\n-- Algebra instances\n-------------------------------------------------------------------------------\n\n\ninstance Semiring a => Algebra a () where\n  joined f = f ()\n\ninstance Semiring a => Unital a () where\n  unital r () = r\n\n--TODO: consider separating out n=3 cross product case\ninstance Semiring a => Algebra a (Finite n) where\n  joined = M.join\n\ninstance Semiring a => Unital a (Finite n) where\n  unital = const\n\ninstance (Algebra a b1, Algebra a b2) => Algebra a (b1, b2) where\n  joined f (a,b) = joined (\\a1 a2 -> joined (\\b1 b2 -> f (a1,b1) (a2,b2)) b) a\n\ninstance (Unital a b1, Unital a b2) => Unital a (b1, b2) where\n  unital r (a,b) = unital r a * unital r b\n\ninstance (Algebra a b1, Algebra a b2, Algebra a b3) => Algebra a (b1, b2, b3) where\n  joined f (a,b,c) = joined (\\a1 a2 -> joined (\\b1 b2 -> joined (\\c1 c2 -> f (a1,b1,c1) (a2,b2,c2)) c) b) a\n\ninstance (Unital a b1, Unital a b2, Unital a b3) => Unital a (b1, b2, b3) where\n  unital r (a,b,c) = unital r a * unital r b * unital r c\n\n-- | Tensor algebra on /b/.\n--\n-- >>> joined (<>) [1..3 :: Int]\n-- [1,2,3,1,2,3,1,2,3,1,2,3]\n--\n-- >>> joined (\\f g -> fold (f ++ g)) [1..3] :: Int\n-- 24\n--\ninstance Semiring a => Algebra a [b] where\n  joined f = go [] where\n    go ls rrs@(r:rs) = f (reverse ls) rrs + go (r:ls) rs\n    go ls [] = f (reverse ls) []\n\ninstance Semiring a => Unital a [b] where\n  unital a [] = a\n  unital _ _ = zero\n\ninstance Semiring a => Algebra a (Seq b) where\n  joined f = go Seq.empty where\n    go ls s = case viewl s of\n       EmptyL -> f ls s \n       r :< rs -> f ls s + go (ls |> r) rs\n\ninstance Semiring a => Unital a (Seq b) where\n  unital a b | Seq.null b = a\n             | otherwise = zero\n\ninstance (Semiring a, Ord b) => Algebra a (Set.Set b) where\n  joined f = go Set.empty where\n    go ls s = case Set.minView s of\n       Nothing -> f ls s\n       Just (r, rs) -> f ls s + go (Set.insert r ls) rs\n\ninstance (Semiring a, Ord b) => Unital a (Set.Set b) where\n  unital a b | Set.null b = a\n           | otherwise = zero\n\ninstance Semiring a => Algebra a IntSet.IntSet where\n  joined f = go IntSet.empty where\n    go ls s = case IntSet.minView s of\n       Nothing -> f ls s\n       Just (r, rs) -> f ls s + go (IntSet.insert r ls) rs\n\ninstance Semiring a => Unital a IntSet.IntSet where\n  unital a b | IntSet.null b = a\n             | otherwise = zero\n\n---------------------------------------------------------------------\n-- Coalgebra instances\n---------------------------------------------------------------------\n\n--instance (Representable f, Algebra a (Rep (Co f))) => Coalgebra a (Co f a) where\n--cojoined k (Co f) (Co g) = k (index f * index g)\n--  cojoined k f g = k (f * g)\n\ninstance Semiring a => Coalgebra a () where\n  cojoined = const\n\ninstance Semiring a => Counital a () where\n  counital f = f ()\n\ninstance Semiring a => Coalgebra a (Finite n) where\n  cojoined f i j = bool zero (f i) $ i == j\n\ninstance (KnownNat n, Semiring a) => Counital a (Finite n) where\n  counital f = sum . fmap f $ finites\n\ninstance Algebra a b => Coalgebra a (b -> a) where\n  cojoined k f g = k (f * g)\n\ninstance Unital a b => Counital a (b -> a) where\n  counital f = f one\n\ninstance (Coalgebra a c1, Coalgebra a c2) => Coalgebra a (c1, c2) where\n  cojoined f (a1,b1) (a2,b2) = cojoined (\\a -> cojoined (\\b -> f (a,b)) b1 b2) a1 a2\n\ninstance (Counital a c1, Counital a c2) => Counital a (c1, c2) where\n  counital k = counital $ \\a -> counital $ \\b -> k (a,b)\n\ninstance (Coalgebra a c1, Coalgebra a c2, Coalgebra a c3) => Coalgebra a (c1, c2, c3) where\n  cojoined f (a1,b1,c1) (a2,b2,c2) = cojoined (\\a -> cojoined (\\b -> cojoined (\\c -> f (a,b,c)) c1 c2) b1 b2) a1 a2\n\ninstance (Counital a c1, Counital a c2, Counital a c3) => Counital a (c1, c2, c3) where\n  counital k = counital $ \\a -> counital $ \\b -> counital $ \\c -> k (a,b,c)\n\n-- | The tensor coalgebra on /c/.\n--\ninstance Semiring a => Coalgebra a [c] where\n  cojoined f as bs = f (mappend as bs)\n\ninstance Semiring a => Counital a [c] where\n  counital f = f []\n\ninstance Semiring a => Coalgebra a (Seq c) where\n  cojoined f as bs = f (mappend as bs)\n\ninstance Semiring a => Counital a (Seq c) where\n  counital f = f Seq.empty\n\n-- | The free commutative band coalgebra\ninstance (Semiring a, Ord c) => Coalgebra a (Set.Set c) where\n  cojoined f as bs = f (Set.union as bs)\n\ninstance (Semiring a, Ord c) => Counital a (Set.Set c) where\n  counital f = f Set.empty\n\n-- | The free commutative band coalgebra over Int\ninstance Semiring a => Coalgebra a IntSet.IntSet where\n  cojoined f as bs = f (IntSet.union as bs)\n\ninstance Semiring a => Counital a IntSet.IntSet where\n  counital f = f IntSet.empty\n\n-- | The free commutative coalgebra over a set and a given semigroup\ninstance (Semiring r, Ord a, Semigroup b) => Coalgebra r (Map.Map a b) where\n  cojoined f as bs = f (Map.unionWith (<>) as bs)\n\ninstance (Semiring r, Ord a, Semigroup b) => Counital r (Map.Map a b) where\n  counital f = f Map.empty\n\n{-\n\n-- | The free commutative coalgebra over a set and a given semigroup\ninstance (Semiring r, Ord a, Commutative b) => Coalgebra r (Map a b) where\n  cojoined f as bs = f (Map.unionWith (+) as bs)\n  counital k = k (Map.empty)\n\n-- | The free commutative coalgebra over a set and Int\ninstance (Semiring r, Commutative b) => Coalgebra r (IntMap b) where\n  cojoined f as bs = f (IntMap.unionWith (+) as bs)\n  counital k = k (IntMap.empty)\n-}\n\n\n---------------------------------------------------------------------\n-- Bialgebra instances\n---------------------------------------------------------------------\n\ninstance Semiring a => Bialgebra a () where\n\ninstance (KnownNat n, Semiring a) => Bialgebra a (Finite n) where\n\ninstance (Bialgebra a b1, Bialgebra a b2) => Bialgebra a (b1, b2) where\n\ninstance (Bialgebra a b1, Bialgebra a b2, Bialgebra a b3) => Bialgebra a (b1, b2, b3) where\n\ninstance Semiring a => Bialgebra a [b]\n\ninstance Semiring a => Bialgebra a (Seq b)\n", "meta": {"hexsha": "bb17979e95948eddc46f053c6d86f968a8f4dfab", "size": 9675, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Semimodule/Algebra.hs", "max_stars_repo_name": "cmk/rings", "max_stars_repo_head_hexsha": "f1203d693d0069169582d478c663159de9416d87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-01-16T12:37:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-20T12:58:22.000Z", "max_issues_repo_path": "src/Data/Semimodule/Algebra.hs", "max_issues_repo_name": "cmk/rings", "max_issues_repo_head_hexsha": "f1203d693d0069169582d478c663159de9416d87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/Semimodule/Algebra.hs", "max_forks_repo_name": "cmk/rings", "max_forks_repo_head_hexsha": "f1203d693d0069169582d478c663159de9416d87", "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.4123376623, "max_line_length": 123, "alphanum_fraction": 0.5748837209, "num_tokens": 2807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47481041218257886}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\nmodule LSI.FrequencyResponse where\n\nimport Data.Complex\nimport Data.Vector as V hiding (map, zip, foldr)\nimport Linear.V as V\n\n\nimport LSI.RationalFunction\n\ncomputeFR :: RealFloat f\n          => RationalFunction d f\n          -> V d f\n          -> Complex f\ncomputeFR rf = (computeFR' rf) . V.toList .V.toVector\n  where computeFR' f =\n          case f of\n            Monomial c es ->\n              let fs = map toInteger . V.toList . V.toVector $ es in\n                \\vs -> {-# SCC monom #-}\n                  let factors = map iexp $ zip zs fs\n                      iexp (z, e) | e < 0 = 1/(z^(-e))\n                      iexp (z, e) = z^e\n                      zs = map (\\w -> mkPolar 1.0 w) vs in\n                    (c :+ 0.0) * (foldr (*) 1 factors)\n\n            Add rf1 rf2 ->\n              let fr1 = computeFR' rf1\n                  fr2 = computeFR' rf2 in\n                \\vs -> (fr1 vs) + (fr2 vs)\n\n            Mul rf1 rf2 ->\n              let fr1 = computeFR' rf1\n                  fr2 = computeFR' rf2 in\n                \\vs -> (fr1 vs) * (fr2 vs)\n\n            Div rf1 rf2 ->\n              let fr1 = computeFR' rf1\n                  fr2 = computeFR' rf2 in\n                \\vs -> (fr1 vs) / (fr2 vs)\n", "meta": {"hexsha": "add901b9a5429b38034f9aeadec2351f9d48e5b7", "size": 1372, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/LSI/FrequencyResponse.hs", "max_stars_repo_name": "gdeest/lsi-systems", "max_stars_repo_head_hexsha": "71fc496bde63084f18c48577708b3c202d496a5e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-17T19:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-17T19:09:18.000Z", "max_issues_repo_path": "src/LSI/FrequencyResponse.hs", "max_issues_repo_name": "gdeest/lsi-systems", "max_issues_repo_head_hexsha": "71fc496bde63084f18c48577708b3c202d496a5e", "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/LSI/FrequencyResponse.hs", "max_forks_repo_name": "gdeest/lsi-systems", "max_forks_repo_head_hexsha": "71fc496bde63084f18c48577708b3c202d496a5e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4888888889, "max_line_length": 68, "alphanum_fraction": 0.472303207, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.47456186026405583}}
{"text": "{-# LANGUAGE BangPatterns          #-}\n{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE TupleSections         #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE FlexibleContexts      #-}\n\nimport           Control.Applicative\nimport           Control.Monad\nimport           Control.Monad.Random\n\nimport           Codec.Compression.GZip ( decompress )\nimport           Data.Serialize ( Get )\nimport qualified Data.Serialize as Serialize\nimport qualified Data.ByteString.Lazy as B\n\nimport           Data.List ( foldl' )\nimport           Data.List.Split ( chunksOf )\nimport           Data.Maybe ( fromMaybe )\n#if ! MIN_VERSION_base(4,13,0)\nimport           Data.Semigroup ( (<>) )\n#endif\nimport           Data.Word ( Word32 , Word8 )\nimport qualified Data.Vector.Storable as V\n\nimport           Numeric.LinearAlgebra ( maxIndex )\nimport qualified Numeric.LinearAlgebra.Static as SA\n\nimport           Options.Applicative\nimport           System.FilePath ( (</>) )\n\nimport           Grenade\nimport           Grenade.Utils.OneHot\n\n#ifdef COMPLEX\n-- It's logistic regression!\n--\n-- This network is used to show how we can embed a Network as a layer in the larger MNIST\n-- type.\n--\ntype FL i o =\n  Network\n    '[ FullyConnected i o, Logit ]\n    '[ 'D1 i, 'D1 o, 'D1 o ]\n\n-- The definition of our convolutional neural network.\n-- In the type signature, we have a type level list of shapes which are passed between the layers.\n-- One can see that the images we are inputing are two dimensional with 28 * 28 pixels.\n\n-- It's important to keep the type signatures, as there's many layers which can \"squeeze\" into the gaps\n-- between the shapes, so inference can't do it all for us.\n\n-- With the mnist data from Kaggle normalised to doubles between 0 and 1, learning rate of 0.01 and 15 iterations,\n-- this network should get down to about a 1.3% error rate.\n--\n-- /NOTE:/ This model is actually too complex for MNIST, and one should use the type given belowe instead.\n--         This one is just here to demonstrate Inception layers in use.\n--\ntype MNIST =\n  Network\n    '[ Reshape,\n       Concat ('D3 28 28 1) Trivial ('D3 28 28 14) (InceptionMini 28 28 1 5 9),\n       Pooling 2 2 2 2, Relu,\n       Concat ('D3 14 14 3) (Convolution 15 3 1 1 1 1) ('D3 14 14 15) (InceptionMini 14 14 15 5 10), Crop 1 1 1 1, Pooling 3 3 3 3, Relu,\n       Reshape, FL 288 80, FL 80 10 ]\n    '[ 'D2 28 28, 'D3 28 28 1,\n       'D3 28 28 15, 'D3 14 14 15, 'D3 14 14 15, 'D3 14 14 18,\n       'D3 12 12 18, 'D3 4 4 18, 'D3 4 4 18,\n       'D1 288, 'D1 80, 'D1 10 ]\n\n#else\n\n-- The simpler network can just be dropped in without changing any of the other code\n--\n\ntype MNIST\n  = Network\n    '[ Convolution 1 10 5 5 1 1, Pooling 2 2 2 2, Relu\n     , Convolution 10 16 5 5 1 1, Pooling 2 2 2 2, Reshape, Relu\n     , FullyConnected 256 80, Logit, FullyConnected 80 10, Logit]\n    '[ 'D2 28 28, 'D3 24 24 10, 'D3 12 12 10, 'D3 12 12 10\n     , 'D3 8 8 16, 'D3 4 4 16, 'D1 256, 'D1 256\n     , 'D1 80, 'D1 80, 'D1 10, 'D1 10]\n\n\n-- ... and this is an even simpler network from  https://crypto.stanford.edu/~blynn/haskell/brain.html\n{-\ntype MNIST\n  = Network\n      '[Reshape, FullyConnected 784 30, Relu, FullyConnected 30 10, Logit]\n      '[ 'D2 28 28, 'D1 784, 'D1 30, 'D1 30, 'D1 10, 'D1 10]\n-}\n\n#endif\n\nrandomMnist :: MonadRandom m => m MNIST\nrandomMnist = randomNetwork\n\nconvTest :: Int -> FilePath -> Maybe Int -> LearningParameters -> IO ()\nconvTest iterations dataDir nSamples rate = do\n  net0         <- randomMnist\n  trainData    <- readMNIST (dataDir </> \"train-images-idx3-ubyte.gz\")\n                            (dataDir </> \"train-labels-idx1-ubyte.gz\")\n  validateData <- readMNIST (dataDir </> \"t10k-images-idx3-ubyte.gz\")\n                            (dataDir </> \"t10k-labels-idx1-ubyte.gz\")\n\n  foldM_ (runIteration (maybe trainData (`take` trainData) nSamples) validateData) net0 [1..iterations]\n\n    where\n  trainEach rate' !network (i, o) = train rate' network i o\n\n  runIteration trainRows validateRows net i = do\n    let trained' = foldl' (trainEach ( rate { learningRate = learningRate rate * 0.9 ^ i} )) net trainRows\n    print trained'\n\n    putStrLn \"Checking...\"\n    let res      = fmap (\\(rowP,rowL) -> (rowL,) $ runNet trained' rowP) validateRows\n    let res'     = fmap (\\(S1D label, S1D prediction) -> (maxIndex (SA.extract label), maxIndex (SA.extract prediction))) res\n    let matched   = length $ filter ((==) <$> fst <*> snd) res'\n    let total     = length res'\n    let matchedpc = fromIntegral matched / fromIntegral total * 100.0 :: Float\n    putStrLn $ \"Iteration \" ++ show i ++ \": matched \" ++ show matched ++ \" of \" ++ show total ++ \" (\" ++ show matchedpc ++ \"%)\" \n    return trained'\n\ndata MnistOpts = MnistOpts FilePath (Maybe Int) Int LearningParameters\n\nmnist' :: Parser MnistOpts\nmnist' = MnistOpts <$> argument str (metavar \"DATADIR\")\n                       -- option to reduce the number of training samples used from 60,000\n                       -- to avoid running out of memory\n                   <*> option (Just <$> auto) (long \"limit_samples_to\" <> short 'l' <> value Nothing)\n                   <*> option auto (long \"iterations\" <> short 'i' <> value 15)\n                   <*> (LearningParameters\n                       <$> option auto (long \"train_rate\" <> short 'r' <> value 0.01)\n                       <*> option auto (long \"momentum\" <> value 0.9)\n                       <*> option auto (long \"l2\" <> value 0.0005)\n                       )\n\nmain :: IO ()\nmain = do\n    MnistOpts dataDir nSamples iter rate <- execParser (info (mnist' <**> helper) idm)\n    putStr \"Training convolutional neural network with \"\n    putStr $ maybe \"all\" show nSamples\n    putStrLn \" samples...\"\n\n    convTest iter dataDir nSamples rate\n\n\n-- Adapted from https://github.com/tensorflow/haskell/blob/master/tensorflow-mnist/src/TensorFlow/Examples/MNIST/Parse.hs\n-- Could also have used Data.IDX, although that uses a different Vector variant from that need for fromStorable\nreadMNIST :: FilePath -> FilePath -> IO [(S ( 'D2 28 28), S ( 'D1 10))]\nreadMNIST iFP lFP = do\n  labels  <- readMNISTLabels lFP\n  samples <- readMNISTSamples iFP\n  return $ zip\n    (fmap (fromMaybe (error \"bad samples\") . fromStorable) samples)\n    (fromMaybe (error \"bad labels\") . oneHot . fromIntegral <$> labels)\n\n-- | Check's the file's endianess, throwing an error if it's not as expected.\ncheckEndian :: Get ()\ncheckEndian = do\n  magic <- Serialize.getWord32be\n  when (magic `notElem` ([2049, 2051] :: [Word32]))\n    $ error \"Expected big endian, but image file is little endian.\"\n\n-- | Reads an MNIST file and returns a list of samples.\nreadMNISTSamples :: FilePath -> IO [V.Vector Double]\nreadMNISTSamples path = do\n  raw <- decompress <$> B.readFile path\n  either fail ( return . fmap (V.map normalize) ) $ Serialize.runGetLazy getMNIST raw\n where\n  getMNIST :: Get [V.Vector Word8]\n  getMNIST = do\n    checkEndian\n    -- Parse header data.\n    cnt    <- fromIntegral <$> Serialize.getWord32be\n    rows   <- fromIntegral <$> Serialize.getWord32be\n    cols   <- fromIntegral <$> Serialize.getWord32be\n    -- Read all of the data, then split into samples.\n    pixels <- Serialize.getLazyByteString $ fromIntegral $ cnt * rows * cols\n    return $ V.fromList <$> chunksOf (rows * cols) (B.unpack pixels)\n\n  normalize :: Word8 -> Double\n  normalize = (/ 255) . fromIntegral\n  -- There are other normalization functions in the literature, such as\n  -- normalize = (/ 0.3081) . (`subtract` 0.1307) . (/ 255) . fromIntegral\n  -- but we need values in the range [0..1] for the showShape' pretty printer\n\n-- | Reads a list of MNIST labels from a file and returns them.\nreadMNISTLabels :: FilePath -> IO [Word8]\nreadMNISTLabels path = do\n  raw <- decompress <$> B.readFile path\n  either fail return $ Serialize.runGetLazy getLabels raw\n where\n  getLabels :: Get [Word8]\n  getLabels = do\n    checkEndian\n    -- Parse header data.\n    cnt <- fromIntegral <$> Serialize.getWord32be\n    -- Read all of the labels.\n    B.unpack <$> Serialize.getLazyByteString cnt\n\n", "meta": {"hexsha": "792270d6858655d073af00f64eb84db4702ea6d2", "size": 8148, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/mnist.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/main/mnist.hs", "max_issues_repo_name": "jrp2014/grenade", "max_issues_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/main/mnist.hs", "max_forks_repo_name": "jrp2014/grenade", "max_forks_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7463414634, "max_line_length": 137, "alphanum_fraction": 0.6388070692, "num_tokens": 2336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.47447952917669795}}
{"text": "{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE UndecidableInstances #-}\nmodule FEECa.PolynomialTest where\n\n\nimport Control.Monad    ( liftM, liftM2 )\n\nimport FEECa.Internal.Vector\nimport FEECa.Internal.Simplex\nimport FEECa.Internal.Spaces\nimport FEECa.Polynomial\n\nimport FEECa.Utility.Utility\nimport FEECa.Utility.Combinatorics\nimport FEECa.Utility.Print\n\nimport Properties\nimport FEECa.Utility.Test\nimport qualified Test.QuickCheck as Q\n\n\n-- =======\n-- import qualified FEECa.Internal.MultiIndex as MI\n\n--import qualified Numeric.LinearAlgebra.HMatrix as M\n-- >>>>>>> efa221f... Cleaned up further tests (definitely shouldn't use `fromDouble`).\n\n------------------------------------------------------------------------------\n-- Dimension of the space to be tested. Must be greater than zero.\n------------------------------------------------------------------------------\n\nn :: Int\nn = 2\n\n------------------------------------------------------------------------------\n-- Generate a random polynomial of dimension n as fixed by the above parameter.\n-- The Polynomial may be of type Constant or Polynomial. If it is of type\n-- Polynomial, degree the degree is chosen between 0 and 10 and the constants\n-- are chosen randomly.\n------------------------------------------------------------------------------\n\ninstance (Ring r, Q.Arbitrary r) => Q.Arbitrary (Polynomial r) where\n  arbitrary = Q.frequency [(4,arbitraryPolynomial n), (1,arbitraryConstant)]\n\narbitraryPolynomial :: (Ring r, Q.Arbitrary r) => Int -> Q.Gen (Polynomial r)\narbitraryPolynomial n = do\n  r <- Q.choose (0,10)\n  s <- Q.choose (0,15)\n  let mis = Q.vectorOf s (arbitraryMI n r)\n      cs  = Q.vectorOf s Q.arbitrary\n  liftM polynomial (liftM2 zip cs mis)\n\narbitraryConstant :: (Ring r, Q.Arbitrary r) => Q.Gen (Polynomial r)\narbitraryConstant = liftM constant Q.arbitrary\n\n\n------------------------------------------------------------------------------\n-- Generate random vectors of dimension n, so that they can be used to evaluate\n-- the randomly generated polynomials.\n------------------------------------------------------------------------------\n\ninstance (Field f, Q.Arbitrary f) => Q.Arbitrary (Vector f) where\n  arbitrary = arbitraryVector n\n\n\n------------------------------------------------------------------------------\n-- Abstract propreties of arithmetic on polynomials. Addition, Subtraction and\n-- multiplication of polynomials must commute with the evaluate operator.\n------------------------------------------------------------------------------\n\npropArithmetic :: (EuclideanSpace v, Function f v, VectorSpace f, Ring f,\n                    r ~ Scalar v, r ~ Scalar f)\n                => (r -> r -> Bool)\n                -> f -> f -> v -> r\n                -> Bool\npropArithmetic eq x y v c =\n     homomorphicEv addV add && homomorphicEv mul mul && homomorphicEv sub sub\n    && prop_operator_commutativity eq (sclV c) (mul c) atV x\n  where homomorphicEv o1 o2 = prop_homomorphism eq o1 o2 atV x y\n        atV                 = evaluate v\n\n\n------------------------------------------------------------------------------\n-- Concrete arithmetic properties for polynomials defined over rationals.\n------------------------------------------------------------------------------\n\nprop_arithmetic_rf :: Polynomial Rational -> Polynomial Rational\n                   -> Vector Rational -> Rational\n                   -> Bool\nprop_arithmetic_rf = propArithmetic (==)\n\n--------------------------------------------------------------------------------\n-- Derivation of Polynomials\n--------------------------------------------------------------------------------\n\n-- Linearity\npropDerivation_linear :: (EuclideanSpace v, Function f v, VectorSpace f,\n                          r ~ Scalar v, r ~ Scalar f)\n                       => v -> v -> r -> f -> f\n                       -> Bool\npropDerivation_linear v1 v2 = prop_linearity (==) (evaluate v2 . derive v2)\n\n-- Product rule\npropDerivationProduct :: (EuclideanSpace v, Function f v, Ring f)\n                        => v -> v -> f -> f\n                        -> Bool\npropDerivationProduct v1 v2 f g =\n    ev (add (mul g (d f)) (mul f (d g))) == (ev . d) (mul f g)\n  where ev = evaluate v1\n        d  = derive v2\n\nprop_derivation_product :: Vector Rational -> Vector Rational\n                        -> Polynomial Rational -> Polynomial Rational\n                        -> Bool\nprop_derivation_product = propDerivationProduct\n\nprop_derivation_productD :: Vector Double -> Vector Double\n                         -> Polynomial Double -> Polynomial Double\n                         -> Bool\nprop_derivation_productD v1 v2 f g =\n    ev (add (mul g (d f)) (mul f (d g))) `eqNum` (ev . d) (mul f g)\n  where ev = evaluate v1\n        d  = derive v2\n\n\n\n-- Test for polynomials using exact arithmetic.\nprop_arithmetic_rational :: Polynomial Rational -> Polynomial Rational\n                         -> Vector Rational -> Rational\n                         -> Bool\nprop_arithmetic_rational = propArithmetic (==)\n\nprop_derivation_linear_rational :: Vector Rational -> Vector Rational\n                                -> Rational\n                                -> Polynomial Rational -> Polynomial Rational\n                                -> Bool\nprop_derivation_linear_rational = propDerivation_linear\n\nprop_derivation_product_rational :: Vector Rational -> Vector Rational\n                                 -> Rational\n                                 -> Polynomial Rational -> Polynomial Rational\n                                 -> Bool\nprop_derivation_product_rational = propDerivation_linear\n\n\n--------------------------------------------------------------------------------\n-- Barycentric Coordinates\n--------------------------------------------------------------------------------\n\n-- | Generate random simplex of dimesion 1 <= n <= 10.\ninstance (EuclideanSpace v, Q.Arbitrary (Scalar v)) => Q.Arbitrary (Simplex v) where\n  arbitrary = do n <- Q.choose (1, 3)\n                 k <- Q.choose (1, n)\n                 arbitrarySubsimplex k n\n\n-- TODO: Fails for n > 3 apparently due to numerical instability. To investigate\n-- further.\nprop_barycentric :: Simplex (Vector Double) -> Bool\nprop_barycentric t =\n    allEq [[evaluate v b | v <- vs] | b <- bs] oneLists\n  where allEq l1 l2 = and $ zipWith (\\l3 l4 -> (and (zipWith eqNum l3 l4))) l1 l2\n        bs          = barycentricCoordinates t\n        vs          = vertices t\n        k           = topologicalDimension t\n        oneLists    = map (map fromInt) (sumRLists (k+1) 1)\n\n--------------------------------------------------------------------------------\n-- Gradients of Barycentric Coordinates\n--------------------------------------------------------------------------------\n\n-- Helper function to create list of vector with 1.0 as first component\nd0vectors :: Field a => Int -> [Vector a]\nd0vectors n = [fromList $ [mulId]\n                 ++ (replicate (i-1) addId)\n                 ++ [addInv mulId]\n                 ++ (replicate (n - i) addId) | i <- [1..n]]\n\n-- Local gradients of barycentric coordinates, i.e. taken w.r.t the barycentric\n-- coordinates themselves. Here we ensure that for a random simplex, if we move\n-- from one corner a to corner b (in barycentric coordinates) the multiplication\n-- of the  different vector with jacobian yields the corner b\n-- (also in barycentric coordinates). This is equivalent to the vectors\n-- [x_0, ..., x_n] with x_0 = 1 and x_i = -1 for any i > 0 being eigenvectors of\n-- the gradient matrix.\nprop_local_gradients :: Simplex (Vector Double) -> Bool\nprop_local_gradients t = all (\\v -> and $ zipWith eqNum (toList ((mult grads v)::Vector Double)) (toList v)) vs\n  where grads     = localBarycentricGradients t\n        vs        = d0vectors n :: [Vector Double]\n        mult vs v = fromList [dot w v | w <- vs]\n        n         = topologicalDimension t\n\nreturn []\ntestPolynomial = $quickCheckWithAll\n", "meta": {"hexsha": "e1f3f689c79b5511a679caf9516e8614570e45ec", "size": 7979, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/FEECa/PolynomialTest.hs", "max_stars_repo_name": "Airini/FEECa", "max_stars_repo_head_hexsha": "3ffae7177fca159d965b70e3763a20ab84cd8a8b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2016-05-18T05:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T12:51:19.000Z", "max_issues_repo_path": "tests/FEECa/PolynomialTest.hs", "max_issues_repo_name": "Airini/FEECa", "max_issues_repo_head_hexsha": "3ffae7177fca159d965b70e3763a20ab84cd8a8b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-10-26T13:28:34.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-08T16:37:41.000Z", "max_forks_repo_path": "tests/FEECa/PolynomialTest.hs", "max_forks_repo_name": "Airini/FEECa", "max_forks_repo_head_hexsha": "3ffae7177fca159d965b70e3763a20ab84cd8a8b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2016-05-18T21:33:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:33:06.000Z", "avg_line_length": 40.7091836735, "max_line_length": 111, "alphanum_fraction": 0.5366587292, "num_tokens": 1692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4744670949077991}}
{"text": "module Numeric.FFT.Execute ( execute ) where\n\nimport           Control.Monad               (when)\nimport qualified Control.Monad               as CM\nimport           Control.Monad.ST\nimport           Data.Complex\nimport qualified Data.IntMap.Strict          as IM\nimport           Data.STRef\nimport qualified Data.Vector                 as V\nimport           Data.Vector.Unboxed\nimport qualified Data.Vector.Unboxed.Mutable as MV\nimport           Prelude                     hiding (concatMap, foldr, length,\n                                              map, mapM_, null, reverse, sum,\n                                              zip, zipWith)\n\nimport           Numeric.FFT.Special\nimport           Numeric.FFT.Types\nimport           Numeric.FFT.Utils\n\n\n-- | Main FFT plan execution driver.\nexecute :: Plan -> Direction -> VCD -> VCD\nexecute (Plan dlinfo perm base) dir h\n  | n == 1 = h\n  | V.null dlinfo = runST $ do\n                          mhin <- case perm of\n                            Nothing -> thaw h\n                            Just p  -> unsafeThaw $ backpermute h p\n                          mhout <- MV.replicate n 0\n                          applyBase base sign mhin mhout\n                          when (dir == Inverse) $ do\n                            let s = 1.0 / fromIntegral n :+ 0\n                            CM.forM_ [0..n-1] $ \\i -> do\n                              x <- MV.unsafeRead mhout i\n                              MV.unsafeWrite mhout i $ s * x\n                          unsafeFreeze mhout\n  | otherwise=  fullfft\n  where\n    n = length h              -- Input vector length.\n    bsize = baseSize base     -- Size of base transform.\n\n    -- Root of unity sign.\n    sign = case dir of\n      Forward -> 1\n      Inverse -> -1\n\n    -- Apply Danielson-Lanczos steps and base transform to digit\n    -- reversal ordered input vector.\n    fullfft = runST $ do\n      mhin <- case perm of\n            Nothing -> thaw h\n            Just p  -> unsafeThaw $ backpermute h p\n      mhtmp <- MV.replicate n 0\n      multBase mhin mhtmp\n      mhr <- newSTRef (mhtmp, mhin)\n      V.forM_ dlinfo $ \\dlstep -> do\n        (mh0, mh1) <- readSTRef mhr\n        dl sign dlstep mh0 mh1\n        writeSTRef mhr (mh1, mh0)\n      mhs <- readSTRef mhr\n      let vout = fst mhs\n      when (dir == Inverse) $ do\n        let s = 1.0 / fromIntegral n :+ 0\n        CM.forM_ [0..n-1] $ \\i -> do\n          x <- MV.unsafeRead vout i\n          MV.unsafeWrite vout i $ s * x\n      unsafeFreeze vout\n\n    -- Multiple base transform application for \"bottom\" of algorithm.\n    multBase :: MVCD s -> MVCD s -> ST s ()\n    multBase xmin xmout =\n      V.zipWithM_ (applyBase base sign)\n                  (slicemvecs bsize xmin) (slicemvecs bsize xmout)\n\n\n-- | Monadic FFT plan execution driver -- used by Rader's algorithm\n-- for convolutions.\nexecuteM :: Plan -> Direction -> MVCD s -> MVCD s -> ST s ()\nexecuteM (Plan dlinfo perm base) dir hin hout =\n  if n == 1\n  then MV.copy hout hin\n  else do\n    htmp <- MV.replicate n 0\n\n    -- Input permutation.\n    case perm of\n      Nothing -> MV.copy htmp hin\n      Just p  -> backpermuteM n p hin htmp\n\n    -- Apply Danielson-Lanczos steps and base transform to digit\n    -- reversal ordered input vector.\n    multBase htmp hout\n    mhr <- newSTRef (hout, htmp)\n    V.forM_ dlinfo $ \\dlstep -> do\n      (mh0, mh1) <- readSTRef mhr\n      dl sign dlstep mh0 mh1\n      writeSTRef mhr (mh1, mh0)\n    when (odd $ V.length dlinfo) $ MV.copy hout htmp\n\n    -- Output scaling for inverse transform.\n    when (dir == Inverse) $ do\n      let s = 1.0 / fromIntegral n :+ 0\n      forM_ (enumFromN 0 n) $ \\i -> do\n        x <- MV.unsafeRead hout i\n        MV.unsafeWrite hout i $ s * x\n  where\n    n = MV.length hin         -- Input vector length.\n    bsize = baseSize base     -- Size of base transform.\n\n    -- Root of unity sign.\n    sign = case dir of\n      Forward -> 1\n      Inverse -> -1\n\n    -- Multiple base transform application for \"bottom\" of algorithm.\n    multBase :: MVCD s -> MVCD s -> ST s ()\n    multBase xmin xmout =\n      V.zipWithM_ (applyBase base sign)\n                  (slicemvecs bsize xmin) (slicemvecs bsize xmout)\n\n\n-- | Single Danielson-Lanczos step: process all duplicates and\n-- concatenate into a single vector.\ndl :: Int -> (Int, Int, VVVCD, VVVCD) -> MVCD s -> MVCD s -> ST s ()\ndl sign (wfac, split, dmatp, dmatm) mhin mhout =\n  V.zipWithM_ doone (slicemvecs wfac mhin) (slicemvecs wfac mhout)\n  where\n    -- Twiddled diagonal entries in row r, column c (both\n    -- zero-indexed), where each row and column if a wfac x wfac\n    -- matrix.\n    dmat = if sign == 1 then dmatp else dmatm\n    d r c = (dmat V.! r) V.! c\n\n    -- Size of each diagonal sub-matrix.\n    ns = wfac `div` split\n\n    -- Index vectors.\n    nsidxs = enumFromN 0 ns\n    splitidxs = enumFromN 1 (split-1)\n\n    -- Process one duplicate by processing all rows and writing the\n    -- results into a single output vector.\n    doone :: MVCD s -> MVCD s -> ST s ()\n    doone vin vout = do\n      let vs = (slicemvecs ns vin, slicemvecs ns vout)\n      mapM_ (single vs) $ enumFromN 0 split\n      where\n        -- Multiply a single block by its appropriate diagonal\n        -- elements and accumulate the result.\n        mult :: VMVCD s -> MVCD s -> Int -> Bool -> Int -> ST s ()\n        mult vins vo r first c = do\n          let vi = vins V.! c\n              dvals = d r c\n          forM_ nsidxs $ \\i -> do\n            xi <- MV.unsafeRead vi i\n            xo <- if first then return 0 else MV.unsafeRead vo i\n            MV.unsafeWrite vo i (xo + xi * dvals ! i)\n        -- Multiply all blocks by the corresponding diagonal\n        -- elements in a single row.\n        single :: (VMVCD s, VMVCD s) -> Int -> ST s ()\n        single (vis, vos) r = do\n          mult vis (vos V.! r) r True 0\n          mapM_ (mult vis (vos V.! r) r False) splitidxs\n        -- single (vis, vos) r =\n        --   let m = mult vis (vos V.! r) r\n        --   in do\n        --     m True 0\n        --     mapM_ (m False) splitidxs\n\n\n-- | Apply a base transform to a single vector.\napplyBase :: BaseTransform -> Int -> MVCD s -> MVCD s -> ST s ()\n\n-- Simple DFT algorithm.\napplyBase (DFTBase sz wsfwd wsinv) sign mhin mhout = do\n  h <- freeze mhin\n  forM_ (enumFromN 0 sz) $ \\i -> MV.unsafeWrite mhout i (doone h i)\n  where ws = if sign == 1 then wsfwd else wsinv\n        doone h i = sum $ zipWith (*) h $\n                    generate sz (\\k -> ws ! (i * k `mod` sz))\n\n-- Special hard-coded cases.\napplyBase (SpecialBase sz) sign mhin mhout =\n  case IM.lookup sz specialBases of\n    Just f  -> f sign mhin mhout\n    Nothing -> error \"invalid problem size for SpecialBase\"\n\n-- Rader prime-length FFT.\napplyBase (RaderBase sz outperm bfwd binv csz cplan) sign mhin mhout = do\n  -- Padding size.\n  let pad = csz - (sz - 1)\n\n  -- Permuted input vector padded to next greater power of two size\n  -- for fast convolution.\n  apad <- MV.replicate csz 0\n  forM_ (enumFromN 0 csz) $ \\i -> do\n    val <- if i == 0 then MV.unsafeRead mhin 1\n           else if i > pad\n                then MV.unsafeRead mhin $ i - pad + 1\n                else return 0\n    MV.unsafeWrite apad i val\n\n  -- FFT-based convolution calculation.\n  convtmp <- MV.replicate csz 0\n  executeM cplan Forward apad convtmp\n  let bmult = if sign == 1 then bfwd else binv\n  forM_ (enumFromN 0 csz) $ \\i -> do\n    x <- MV.unsafeRead convtmp i\n    MV.unsafeWrite convtmp i $ x * (bmult ! i)\n  executeM cplan Inverse convtmp apad\n  conv <- unsafeFreeze apad\n\n  -- Input vector sum.\n  sumhref <- newSTRef 0\n  forM_ (enumFromN 0 sz) $ \\i -> do\n    val <- MV.unsafeRead mhin i\n    modifySTRef sumhref (+ val)\n  sumh <- readSTRef sumhref\n\n  -- Write output based on output generator index ordering.\n  h0 <- MV.unsafeRead mhin 0\n  forM_ (enumFromN 0 sz) $ \\i -> do\n    let (idx, val) = case i of\n          0 -> (0, sumh)\n          _ -> (outperm ! (i - 1), h0 + conv ! (i - 1))\n    MV.unsafeWrite mhout idx val\n", "meta": {"hexsha": "a9e4c9092eeb123cd655f3a1157cf79b98a0022b", "size": 7952, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/FFT/Execute.hs", "max_stars_repo_name": "ian-ross/arb-fft", "max_stars_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-06-15T09:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-08T13:14:27.000Z", "max_issues_repo_path": "Numeric/FFT/Execute.hs", "max_issues_repo_name": "ian-ross/arb-fft", "max_issues_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-03-08T20:31:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T20:32:09.000Z", "max_forks_repo_path": "Numeric/FFT/Execute.hs", "max_forks_repo_name": "ian-ross/arb-fft", "max_forks_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-11-25T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-06T22:54:26.000Z", "avg_line_length": 35.0308370044, "max_line_length": 78, "alphanum_fraction": 0.5690392354, "num_tokens": 2321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47446709490779904}}
{"text": "{-# language GADTs #-}\n{-# language TypeOperators #-}\n{-# language FlexibleInstances #-}\n{-# language UndecidableInstances #-}\n\nmodule Control.Commutative \n  ( Commutative\n  , CommutativeMonad\n  ) where\n\nimport Control.Applicative (ZipList, Const)\nimport Control.Applicative.Backwards\n-- import Control.Arrow (Kleisli)\nimport Control.Comonad\nimport Control.Comonad.Env\nimport Control.Comonad.Traced\nimport Control.Monad.Trans.Identity\nimport Control.Monad.Trans.Maybe\nimport Control.Monad.Trans.Reader\nimport Control.Monad.Trans.Writer.Lazy as Lazy\nimport Control.Monad.Trans.Writer.Strict as Strict\nimport Data.Complex\nimport Data.Functor.Compose\nimport Data.Functor.Identity\nimport Data.Functor.Product as Functor\nimport Data.Functor.Reverse\nimport Data.Monoid as Monoid\nimport Data.Proxy\nimport Data.Semigroup as Semigroup\nimport Data.Semigroup.Commutative\nimport Data.Tagged\nimport GHC.Generics\nimport Linear\nimport Linear.Plucker\nimport Linear.V\n\n-- |\n-- @\n-- ('<*>') = 'flip' ('<**>')\n-- @\nclass Applicative m => Commutative m\n\ninstance (Commutative f, Commutative g) => Commutative (Compose f g)\n\n-- instance (CommutativeMonoid a, CommutativeMonoid b) => Commutative ((,,) a b)\n-- instance (CommutativeMonoid a, CommutativeMonoid b, CommutativeMonoid c) => Commutative ((,,,) a b c)\n-- instance (CommutativeMonoid a, CommutativeMonoid b, CommutativeMonoid c, CommutativeMonoid d) => Commutative ((,,,,) a b c d)\n\ninstance CommutativeMonoid w => Commutative ((,) w)\ninstance Commutative ((->) e)\n\n-- linear\ninstance Commutative V4\ninstance Commutative V3\ninstance Commutative V2\ninstance Commutative Linear.V1\ninstance Commutative V0\ninstance Commutative Plucker\ninstance Dim n => Commutative (V n)\ninstance Commutative Complex\ninstance Commutative Quaternion\n\n-- @transformers@\ninstance Commutative m => Commutative (ReaderT e m)\ninstance Commutative Identity\ninstance Commutative m => Commutative (IdentityT m)\ninstance (Commutative m, Commutative n) => Commutative (Functor.Product m n)\ninstance CommutativeMonad m => Commutative (MaybeT m)\ninstance Commutative m => Commutative (Reverse m)\ninstance Commutative m => Commutative (Backwards m)\ninstance (Commutative m, CommutativeMonoid w) => Commutative (Strict.WriterT w m)\ninstance (Commutative m, CommutativeMonoid w) => Commutative (Lazy.WriterT w m)\n\n-- @tagged@\ninstance Commutative (Tagged a)\ninstance Commutative Proxy\n\n-- Control.Applicative\ninstance Commutative ZipList\ninstance CommutativeMonoid a => Commutative (Const a)\n\n-- Control.Arrow\n-- instance Commutative m => Commutative (Kleisli m a)\n\n-- Data.Semigroup\ninstance Commutative Semigroup.Last -- NB: Not CommutativeMonoid!\ninstance Commutative Semigroup.First -- NB: Not CommutativeMonoid!\ninstance Commutative Option -- NB: Not CommutativeMonoid!\n\n-- Data.Monoid\ninstance Commutative Monoid.Last -- NB: Not CommutativeMonoid!\ninstance Commutative Monoid.First -- NB: Not CommutativeMonoid!\ninstance Commutative Monoid.Product -- NB: Not CommutativeMonoid!\ninstance Commutative Monoid.Sum -- NB: Not CommutativeMonoid!\ninstance Commutative f => Commutative (Alt f)\n\n-- GHC.Generics\ninstance Commutative m => Commutative (M1 i c m)\ninstance (Commutative f, Commutative g) => Commutative (f :.: g)\ninstance (Commutative f, Commutative g) => Commutative (f :*: g)\n-- instance CommutativeSemigroup c => Commutative (K1 i c) -- missing in base \ninstance Commutative f => Commutative (Rec1 f)\ninstance Commutative Par1\ninstance Commutative U1\n\n-- @comonads@\ninstance (Commutative w, CommutativeMonoid e) => Commutative (EnvT e w)\ninstance Commutative w => Commutative (TracedT e w)\ninstance Commutative (Cokleisli w a)\n-- instance Commutative f => Commutative (Ap f) -- ghc 8.6\n\n-- instance CommutativeSemigroup w => Commutative (Validation w)\n\nclass    (Commutative m, Monad m) => CommutativeMonad m\ninstance (Commutative m, Monad m) => CommutativeMonad m\n", "meta": {"hexsha": "c6b5669ca071335df6527f2325f0b5b678d84991", "size": 3879, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Control/Commutative.hs", "max_stars_repo_name": "ekmett/abelian", "max_stars_repo_head_hexsha": "09c0b00d2f017b45da53f6bf17107b9425a283f3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-04-28T07:27:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T00:25:15.000Z", "max_issues_repo_path": "src/Control/Commutative.hs", "max_issues_repo_name": "ekmett/abelian", "max_issues_repo_head_hexsha": "09c0b00d2f017b45da53f6bf17107b9425a283f3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Control/Commutative.hs", "max_forks_repo_name": "ekmett/abelian", "max_forks_repo_head_hexsha": "09c0b00d2f017b45da53f6bf17107b9425a283f3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-04-28T07:27:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-02T12:04:49.000Z", "avg_line_length": 33.4396551724, "max_line_length": 128, "alphanum_fraction": 0.7715906161, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4742728573653565}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule PlotGreensFunctionSTS where\n\nimport           Control.Monad.Parallel    as MP\nimport           Data.Array.Repa           as R\nimport           Data.Binary               (decodeFile)\nimport           Data.Complex\nimport           Data.List                 as L\nimport           Data.Vector.Unboxed       as VU\nimport           FokkerPlanck.DomainChange\nimport           FokkerPlanck.MonteCarlo\nimport           FokkerPlanck.Pinwheel\nimport           Image.IO\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Types\nimport           Utils.Array\n\nmain = do\n  args@(numPointStr:spatialFreqStr:numOrientationStr:thetaSigmaStr:numScaleStr:scaleSigmaStr:maxScaleStr:taoStr:initStr:numTrailStr:maxTrailStr:thetaFreqsStr:scaleFreqsStr:histFileName:numThreadStr:_) <-\n    getArgs\n  print args\n  let numPoint = read numPointStr :: Int\n      spatialFreq = read spatialFreqStr :: Double\n      spatialFreqs = [-spatialFreq .. spatialFreq]\n      numOrientation = read numOrientationStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      numScale = read numScaleStr :: Int\n      scaleSigma = read scaleSigmaStr :: Double\n      maxScale = read maxScaleStr :: Double\n      tao = read taoStr :: Double\n      init@(initX, initY, initTheta, initScale) =\n        read initStr :: (Double, Double, Double, Double)\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      thetaFreq = read thetaFreqsStr :: Double\n      scaleFreq = read scaleFreqsStr :: Double\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      scaleFreqs = [-scaleFreq .. scaleFreq]\n      numThread = read numThreadStr :: Int\n      folderPath = \"output/test/PlotGreensFunctionSTS\"\n      histPath = folderPath </> histFileName\n      initArr =\n        traverse4\n          (fromListUnboxed (Z :. (L.length spatialFreqs)) spatialFreqs)\n          (fromListUnboxed (Z :. (L.length spatialFreqs)) spatialFreqs)\n          (fromListUnboxed (Z :. (L.length thetaFreqs)) thetaFreqs)\n          (fromListUnboxed (Z :. (L.length scaleFreqs)) scaleFreqs)\n          (\\(Z :. a) (Z :. b) (Z :. c) (Z :. d) ->\n             (Z :. a :. b :. c :. d :. c :. d)) $ \\fx fy ft fs (Z :. x :. y :. _ :. _ :. t :. s) ->\n          exp\n            (0 :+\n             (-1) *\n             (ft (Z :. t) * (initTheta / 180 * pi) +\n              2 * pi *\n              ((fx (Z :. x) * initX + fy (Z :. y) * initY) /\n               (fromIntegral numPoint) +\n               fs (Z :. s) * initScale / log maxScale)))\n  createDirectoryIfMissing True folderPath\n  flag <- doesFileExist histPath\n  arr <-\n    if flag\n      then fmap\n             (fromListUnboxed\n                (Z :. (L.length spatialFreqs) :. (L.length spatialFreqs) :.\n                 (L.length thetaFreqs) :.\n                 (L.length scaleFreqs) :.\n                 (L.length thetaFreqs) :.\n                 (L.length scaleFreqs))) .\n           decodeFile $\n           histPath\n      else runMonteCarloSTS\n             numThread\n             numTrail\n             maxTrail\n             numPoint\n             numPoint\n             thetaSigma\n             scaleSigma\n             maxScale\n             tao\n             spatialFreqs\n             spatialFreqs\n             thetaFreqs\n             scaleFreqs\n             histPath $\n           VU.replicate\n             (L.length scaleFreqs * L.length thetaFreqs * L.length scaleFreqs *\n              L.length thetaFreqs *\n              L.length spatialFreqs *\n              L.length spatialFreqs)\n             0\n  transformedArr <- sumP . sumS $ R.zipWith (*) arr initArr\n  -- arrR2S1RP <-\n  --   stsTor2s1rp\n  --     numPoint\n  --     (fromIntegral numPoint)\n  --     spatialFreqs\n  --     numPoint\n  --     (fromIntegral numPoint)\n  --     spatialFreqs\n  --     numOrientation\n  --     thetaFreqs\n  --     numScale\n  --     scaleFreqs\n  --     maxScale\n  --     transformedArr\n  -- plotImageRepaComplex (folderPath </> \"Greens.png\") .\n  --   ImageRepa 8 .\n  --   computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.sumS . sumS $\n  --   arrR2S1RP\n  arrMag <-\n    stsTor2'\n      numPoint\n      (fromIntegral numPoint)\n      spatialFreqs\n      numPoint\n      (fromIntegral numPoint)\n      spatialFreqs\n      transformedArr\n  plotImageRepa (folderPath </> \"GreensMag.png\") .\n    ImageRepa 8 .\n    computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.map sqrt $\n    arrMag\n", "meta": {"hexsha": "3f3eb0c6c60ef227f98fa50d6756206ea4c4d45b", "size": 4449, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/PlotGreensFunctionSTS/PlotGreensFunctionSTS.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/PlotGreensFunctionSTS/PlotGreensFunctionSTS.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/PlotGreensFunctionSTS/PlotGreensFunctionSTS.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 35.3095238095, "max_line_length": 203, "alphanum_fraction": 0.5583277141, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47410841781385854}}
{"text": "{-# LANGUAGE DefaultSignatures #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n\n{-| This module defines `Distributive` for a fixed `Monad`\n    instead of an arbitrary `Functor`.\n-}\n\nmodule Data.Distributive.Monadic (\n  -- * Type class\n    DistributiveM(..)\n\n  -- ** distributem and collectm in terms of each other\n  , distributemByCollectm\n  , collectmByDistributem\n\n  -- *  Utilities defined using `DistributiveM`\n  , wrapFoldM\n\n  -- ** ConstT\n  , ConstT(..)\n\n  -- *  MonadTrans instances\n  , distributemTrans\n  , collectmTrans\n\n  -- *  Generics\n  , gdistributem\n  , gcollectm\n  , GDistributiveM(..)\n  ) where\n\nimport Control.Comonad (Comonad(..))\nimport Control.Comonad.Cofree (Cofree(..))\nimport Control.Comonad.Trans.Cofree (CofreeT(..))\nimport qualified Control.Comonad.Trans.Cofree as Trans (CofreeF(..))\nimport Control.Comonad.Trans.Coiter (CoiterT(..))\nimport Control.Comonad.Trans.Env (EnvT(..), ask, lowerEnvT)\nimport Control.Comonad.Trans.Store (StoreT(..), pos)\nimport Control.Comonad.Trans.Traced (TracedT(..))\nimport Control.Foldl (FoldM(..))\nimport Control.Foldl.Utils (extractM, innerJoinFoldM, stepFoldM, unwrapFoldM)\nimport Control.Monad (join, liftM2)\nimport Control.Monad.Free (Free(..))\nimport Control.Monad.Free.Church (F(..), fromF, toF)\nimport Control.Monad.Trans.Accum (AccumT(..))\nimport Control.Monad.Trans.Class (MonadTrans(..))\nimport Control.Monad.Trans.Const\nimport Control.Monad.Trans.Cont (ContT(..))\nimport Control.Monad.Trans.Except (ExceptT(..))\nimport Control.Monad.Trans.Free (FreeT(..))\nimport qualified Control.Monad.Trans.Free as Trans (FreeF(..))\nimport Control.Monad.Trans.Free.Church (FT(..), fromFT, toFT)\nimport Control.Monad.Trans.Identity (IdentityT(..))\nimport Control.Monad.Trans.Iter (IterT(..))\nimport Control.Monad.Trans.Maybe (MaybeT(..))\nimport Control.Monad.Trans.RWS (RWST(..))\nimport qualified Control.Monad.Trans.RWS.Strict as Strict (RWST(..))\nimport Control.Monad.Trans.Reader (ReaderT(..))\nimport Control.Monad.Trans.State (StateT(..))\nimport qualified Control.Monad.Trans.State.Strict as Strict (StateT(..))\nimport Control.Monad.Trans.Writer (WriterT(..))\nimport qualified Control.Monad.Trans.Writer.Strict as Strict (WriterT(..))\nimport Data.Bifunctor (Bifunctor(..))\nimport Data.Complex (Complex)\nimport Data.Distributive (Distributive(..))\nimport Data.Functor.Compose (Compose(..))\nimport Data.Functor.Identity (Identity(..))\nimport Data.Proxy (Proxy(..))\nimport Data.Semigroup (Dual, Product, Sum)\nimport GHC.Generics\n  ( (:*:)(..)\n  , (:.:)(..)\n  , Generic1(..)\n  , M1(..)\n  , Par1(..)\n  , Rec1(..)\n  , U1(..)\n  )\n\n-- | This is the categorical dual of `Traversable`, for a `Monad` fixed by\n-- our choice of @f@.\n--\n-- If you define one of `distributem`, `collectm` you may define the other\n-- using `collectmByDistributem`, `distributemByCollectm`, respectively.\n--\n-- All `MonadTrans`formers that result in a `Monad` are instances of\n-- `DistributiveM`, see `collectmTrans`.\nclass Monad m => DistributiveM m f | f -> m where\n  -- | The dual of `sequence`, for a fixed `Monad`\n  --\n  -- @\n  --  `distributem` = `collectm` `id`\n  -- @\n  --\n  distributem :: m (f a) -> f (m a)\n  default distributem :: (Generic1 f, GDistributiveM m (Rep1 f)) => m (f a) -> f (m a)\n  distributem = gdistributem\n\n  -- | Map then `distributem`:\n  --\n  -- @\n  --  `collectm` f = `distributem` . `fmap` f\n  -- @\n  --\n  collectm :: (a -> f b) -> m a -> f (m b)\n  default collectm :: (Generic1 f, GDistributiveM m (Rep1 f)) => (a -> f b) -> m a -> f (m b)\n  collectm = gcollectm\n\ninstance Monad m => DistributiveM m (FoldM m a) where\n  distributem f = FoldM (fmap unwrapFoldM . flip stepFoldM) f (return . extractM)\n\n  collectm = collectmByDistributem\n\n-- | If there were no functional dependencies, this would be the \"other\"\n-- instance for `Identity`:\n--\n-- @\n--  instance `Monad` m => `DistributiveM` m `Identity` where\n--    `distributem` :: m (`Identity` a) -> `Identity` (m a)\n--    `distributem` = `Identity` . `fmap` `runIdentity`\n-- @\n--\n-- But it'd violate the functional dependency since `Identity` does not\n-- determine @m@.\n--\n-- By ignoring the chosen `Monad`, we can recreate the instance.\n--\n-- See `wrappedCofreeFToProd` for an example.\ninstance Monad m => DistributiveM m (ConstT m) where\n  distributem = ConstT . fmap runConstT\n  collectm f = ConstT . fmap (runConstT . f)\n\n\n-- distributem and collectm in terms of each other\n\n-- | `distributem` in terms of `collectm`\ndistributemByCollectm :: DistributiveM m f => m (f a) -> f (m a)\ndistributemByCollectm = collectm id\n\n-- | `collectm` in terms of `distributem`\ncollectmByDistributem :: DistributiveM m f => (a -> f b) -> m a -> f (m b)\ncollectmByDistributem f = distributem . fmap f\n\n-- Utilities defined using `DistributiveM`\n\n-- | Implement `wrap` using `distributem` and `innerJoinFoldM`\nwrapFoldM :: Monad m => m (FoldM m a b) -> FoldM m a b\nwrapFoldM = innerJoinFoldM . distributem\n\n\n-- GHC.Generics instances\n\ninstance (DistributiveM m f, DistributiveM m g) =>\n         DistributiveM m (f :*: g)\n\ninstance (DistributiveM m f, DistributiveM m g, Functor f) =>\n         DistributiveM m (f :.: g)\n\ninstance (DistributiveM m f, DistributiveM m g, Functor f) =>\n         DistributiveM m (Compose f g)\n\ninstance DistributiveM Identity Par1\n\ninstance DistributiveM m f => DistributiveM m (M1 i c f)\n\ninstance DistributiveM m f => DistributiveM m (Rec1 f)\n\ninstance DistributiveM Identity U1\n\n\n-- Lifted instances\n\ninstance DistributiveM Identity Identity\n\ninstance DistributiveM Identity Complex\n\ninstance DistributiveM Identity Dual\n\ninstance DistributiveM Identity Sum\n\ninstance DistributiveM Identity Product\n\ninstance DistributiveM Identity Proxy\n\n\n-- MonadTrans instances\n\ninstance Monad m => DistributiveM m (ReaderT a m) where\n  distributem = distributemTrans -- ReaderT . distribute . fmap runReaderT\n  collectm = collectmTrans -- f xs = ReaderT $ \\x -> flip (runReaderT . f) x <$> xs\n\ninstance (Monoid w, Monad m) => DistributiveM m (AccumT w m) where\n  distributem = distributemTrans -- AccumT . fmap (>>= fmap (first return)) . collect runAccumT\n  collectm = collectmTrans -- f xs = AccumT $ \\x -> xs >>= fmap (first return) . flip (runAccumT . f) x\n\ninstance Monad m => DistributiveM m (ContT r m) where\n  distributem = distributemTrans -- xs = ContT $ \\f -> xs >>= ($ f . return) . runContT\n  collectm = collectmTrans -- f xs = ContT $ \\g -> xs >>= \\y -> (runContT . f) y (g . return)\n\ninstance Monad m => DistributiveM m (ExceptT e m) where\n  distributem = distributemTrans -- ExceptT . (>>= fmap (fmap return) . runExceptT)\n  collectm = collectmTrans -- f xs = ExceptT $ xs >>= fmap (fmap return) . runExceptT . f\n\ninstance Monad m => DistributiveM m (IdentityT m) where\n  distributem = distributemTrans\n  collectm = collectmTrans\n\ninstance Monad m => DistributiveM m (MaybeT m) where\n  distributem = distributemTrans\n  collectm = collectmTrans\n\ninstance (Monoid w, Monad m) => DistributiveM m (RWST r w s m) where\n  distributem = distributemTrans\n  collectm = collectmTrans\n\ninstance (Monoid w, Monad m) => DistributiveM m (Strict.RWST r w s m) where\n  distributem = distributemTrans\n  collectm = collectmTrans\n\ninstance Monad m => DistributiveM m (StateT s m) where\n  distributem = distributemTrans\n  collectm = collectmTrans\n\ninstance Monad m => DistributiveM m (Strict.StateT s m) where\n  distributem = distributemTrans\n  collectm = collectmTrans\n\ninstance (Monoid w, Monad m) => DistributiveM m (WriterT w m) where\n  distributem = distributemTrans\n  collectm = collectmTrans\n\ninstance (Monoid w, Monad m) => DistributiveM m (Strict.WriterT w m) where\n  distributem = distributemTrans\n  collectm = collectmTrans\n\n\n-- | `distributem` for any `MonadTrans` that's a `Monad` when its base functor is.\ndistributemTrans :: (Monad m, MonadTrans t, Monad (t m)) => m (t m a) -> t m (m a)\ndistributemTrans = fmap return . join . lift\n\n-- | `collectm` for any `MonadTrans` that's a `Monad` when its base functor is.\n--\n-- We `lift` the `m` then @(`>>=`)@ the function to the result.\n-- Finally, we `return` inside of the transformer.\ncollectmTrans :: (Monad m, MonadTrans t, Monad (t m)) => (a -> t m b) -> m a -> t m (m b)\ncollectmTrans f = fmap return . (>>= f) . lift\n\n\n-- Comonad transformers\n\ninstance (Comonad m, Monad m) => DistributiveM m (EnvT e m) where\n  distributem = liftM2 EnvT (ask . extract) (fmap lowerEnvT)\n  collectm = collectmByDistributem\n\ninstance (Comonad m, Monad m) => DistributiveM m (StoreT s m) where\n  distributem = liftM2 StoreT (fmap (\\(~(StoreT acc _)) -> distribute acc)) (pos . extract)\n  collectm = collectmByDistributem\n\ninstance (Monoid w, Monad m) => DistributiveM m (TracedT w m) where\n  distributem = TracedT . fmap (distribute . runTracedT)\n  collectm f = TracedT . (>>= runTracedT . fmap return . f)\n\n\n-- Free\n\ninstance (Comonad m, Monad m) => DistributiveM m (Cofree m) where\n  distributem xs =\n    fmap extract xs :< (xs >>= (\\(~(_ :< ys)) -> fmap return <$> ys))\n  collectm = collectmByDistributem\n\n-- | A wrapped representation of `CofreeF` without the outermost\n-- `Comonad`ic layer\nnewtype WrappedCofreeF f w a = WrappedCofreeF\n  { runWrappedCofreeF :: Trans.CofreeF f a (CofreeT f w a)\n  }\n\ninstance (Functor f, Functor w) => Functor (WrappedCofreeF f w) where\n  fmap f = WrappedCofreeF . bimap f (fmap f) . runWrappedCofreeF\n\n-- | Convert `CofreeT` to our wrapped representation\ntoWrappedCofreeF :: Functor w => CofreeT f w a -> w (WrappedCofreeF f w a)\ntoWrappedCofreeF = fmap WrappedCofreeF . runCofreeT\n\n-- | Convert `WrappedCofreeF` to a product, which has a suitable automatically\n-- derived `DistributiveM` instance.\n{-# INLINE wrappedCofreeFToProd #-}\nwrappedCofreeFToProd ::\n     WrappedCofreeF f w a -> (ConstT f :*: Compose (IdentityT f) (CofreeT f w)) a\nwrappedCofreeFToProd ~(WrappedCofreeF (x Trans.:< xs)) =\n  ConstT x :*: Compose (IdentityT xs)\n\n-- | Convert `WrappedCofreeF` from a product\n{-# INLINE wrappedCofreeFFromProd #-}\nwrappedCofreeFFromProd ::\n     (ConstT f :*: Compose (IdentityT f) (CofreeT f w)) a -> WrappedCofreeF f w a\nwrappedCofreeFFromProd ~(ConstT x :*: Compose (IdentityT xs)) =\n  WrappedCofreeF $ x Trans.:< xs\n\ninstance (DistributiveM m f, Functor f) =>\n         DistributiveM m (WrappedCofreeF m f) where\n  distributem = wrappedCofreeFFromProd . collectm wrappedCofreeFToProd\n  collectm f = wrappedCofreeFFromProd . collectm (wrappedCofreeFToProd . f)\n\ninstance (DistributiveM m f, Functor f) => DistributiveM m (CofreeT m f) where\n  distributem =\n    CofreeT .\n    fmap runWrappedCofreeF . getCompose . collectm (Compose . toWrappedCofreeF)\n  collectm f =\n    CofreeT .\n    fmap runWrappedCofreeF .\n    getCompose . collectm (Compose . toWrappedCofreeF . f)\n\ninstance Monad m => DistributiveM m (CoiterT m) where\n  distributem = CoiterT . (>>= fmap (bimap return (fmap return)) . runCoiterT)\n  collectm f =\n    CoiterT . (>>= fmap (bimap return (fmap return)) . runCoiterT . f)\n\n-- | Deconstruct a `Free`\n{-# INLINE free #-}\nfree :: (a -> b) -> (f (Free f a) -> b) -> Free f a -> b\nfree f _ (Pure x) = f x\nfree _ g ~(Free x) = g x\n\ninstance Monad m => DistributiveM m (Free m) where\n  distributem = Free . fmap (fmap return)\n  collectm f =\n    Free . (>>= free (return . return . return) (fmap return <$>) . f)\n\ninstance Monad m => DistributiveM m (F m) where\n  distributem = toF . collectm fromF\n  collectm = collectmByDistributem\n\n-- | A wrapped representation of `FreeF` without the outermose `Monad`ic layer\nnewtype WrappedFreeF f m a = WrappedFreeF\n  { runWrappedFreeF :: Trans.FreeF f a (FreeT f m a)\n  }\n\ninstance (Functor f, Monad m) => Functor (WrappedFreeF f m) where\n  fmap f = WrappedFreeF . bimap f (fmap f) . runWrappedFreeF\n\n-- | Convert `FreeT` to our wrapped representation\ntoWrappedFreeF :: Functor m => FreeT f m a -> m (WrappedFreeF f m a)\ntoWrappedFreeF = fmap WrappedFreeF . runFreeT\n\n-- | Deconstruct a `FreeF`\n{-# INLINE freeF #-}\nfreeF :: (a -> c) -> (f b -> c) -> Trans.FreeF f a b -> c\nfreeF f _ (Trans.Pure x) = f x\nfreeF _ g ~(Trans.Free x) = g x\n\ninstance (Monad m, Monad n) => DistributiveM m (WrappedFreeF m n) where\n  distributem =\n    WrappedFreeF .\n    Trans.Free .\n    (>>= freeF (return . return . return) (fmap return <$>) . runWrappedFreeF)\n  collectm f =\n    WrappedFreeF .\n    Trans.Free .\n    (>>= freeF (return . return . return) (fmap return <$>) .\n         runWrappedFreeF . f)\n\ninstance (DistributiveM m n, Monad n) => DistributiveM m (FreeT m n) where\n  distributem =\n    FreeT .\n    fmap runWrappedFreeF . getCompose . collectm (Compose . toWrappedFreeF)\n  collectm f =\n    FreeT .\n    fmap runWrappedFreeF . getCompose . collectm (Compose . toWrappedFreeF . f)\n\ninstance (DistributiveM m n, Monad n) => DistributiveM m (FT m n) where\n  distributem = toFT . collectm fromFT\n  collectm = collectmByDistributem\n\ninstance Monad m => DistributiveM m (IterT m) where\n  distributem = IterT . (>>= fmap (bimap return (fmap return)) . runIterT)\n  collectm f = IterT . (>>= fmap (bimap return (fmap return)) . runIterT . f)\n\n\n-- Generics\n\n-- | A default implementation of `distributem` for `Generic1` types\ngdistributem :: (GDistributiveM m (Rep1 f), Generic1 f) => m (f a) -> f (m a)\ngdistributem = to1 . gcollectm' from1\n\n-- | A default implementation of `collectm` for `Generic1` types\ngcollectm :: (GDistributiveM m (Rep1 f), Generic1 f) => (a -> f b) -> m a -> f (m b)\ngcollectm f = to1 . gcollectm' (from1 . f)\n\n\n-- | The typeclass implementing `gdistributem` (as `gdistributem'`)\n-- for `Generic1` types\nclass Monad m => GDistributiveM (m :: * -> *) (f :: * -> *) | f -> m where\n  gdistributem' :: m (f a) -> f (m a)\n  gdistributem' = gcollectm' id\n\n  gcollectm' :: (a -> f b) -> m a -> f (m b)\n\ninstance GDistributiveM m f => GDistributiveM m (M1 i c f) where\n  gcollectm' f = M1 . gcollectm' (unM1 . f)\n\ninstance GDistributiveM Identity U1 where\n  gcollectm' _ _ = U1\n\ninstance GDistributiveM Identity Par1 where\n  gcollectm' f = Par1 . fmap (unPar1 . f)\n\ninstance (GDistributiveM m f, GDistributiveM m g) =>\n         GDistributiveM m (f :*: g) where\n  gcollectm' f xs = gcollectm' leftF xs :*: gcollectm' rightF xs\n    where\n      leftF = (\\(~(ys :*: _)) -> ys) . f\n      rightF = (\\(~(_ :*: zs)) -> zs) . f\n\ninstance DistributiveM m f => GDistributiveM m (Rec1 f) where\n  gcollectm' f xs = Rec1 $ collectm (unRec1 . f) xs\n\ninstance (DistributiveM m f, GDistributiveM m g, Functor f) =>\n         GDistributiveM m (f :.: g) where\n  gcollectm' f xs = Comp1 $ gdistributem' <$> collectm (unComp1 . f) xs\n\n", "meta": {"hexsha": "3cbe2ecaeb55298e86837f72e115f7b801dcab80", "size": 14694, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Distributive/Monadic.hs", "max_stars_repo_name": "michaeljklein/algebraic-foldl", "max_stars_repo_head_hexsha": "7c35fda2ad8ef06bc4a4d722a42946d2feb80314", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/Distributive/Monadic.hs", "max_issues_repo_name": "michaeljklein/algebraic-foldl", "max_issues_repo_head_hexsha": "7c35fda2ad8ef06bc4a4d722a42946d2feb80314", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/Distributive/Monadic.hs", "max_forks_repo_name": "michaeljklein/algebraic-foldl", "max_forks_repo_head_hexsha": "7c35fda2ad8ef06bc4a4d722a42946d2feb80314", "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.3317757009, "max_line_length": 103, "alphanum_fraction": 0.6855859535, "num_tokens": 4600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47397295821556107}}
{"text": "{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE RankNTypes, GADTs, TypeFamilies, TypeOperators, ConstraintKinds #-}\n{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts #-}\n{-# LANGUAGE DataKinds, PolyKinds, ConstraintKinds #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\nmodule Language.Grappa.Distribution where\n\nimport Control.Monad\nimport Control.Monad.Trans\nimport GHC.Exts\nimport Data.Typeable\nimport qualified Data.Vector.Storable as V\n--import Data.Number.LogFloat hiding (sum, product, log)\n\nimport Numeric.LinearAlgebra hiding (R, Uniform, (<>), (<#))\nimport qualified Numeric.LinearAlgebra as M\n\nimport qualified Numeric.Log as Log\nimport qualified Numeric.SpecFunctions as Gamma\n\nimport qualified Numeric.AD.Mode.Forward as ADF\nimport qualified Numeric.AD.Internal.Forward as ADF\nimport qualified Numeric.AD.Mode.Reverse as ADR\nimport qualified Numeric.AD.Internal.Reverse as ADR\nimport qualified Numeric.AD.Internal.Identity as ADR\nimport qualified Numeric.AD.Jacobian as ADR\nimport qualified Data.Reflection as ADR (Reifies)\n\n-- | The R type alias\ntype R = Double\n\n\n----------------------------------------------------------------------\n-- * Supporting the Gamma and Beta Functions\n----------------------------------------------------------------------\n\n-- | Class for computing @ln (gamma x)@\nclass HasGamma a where\n  logGamma :: a -> a\n  digamma :: a -> a\n\ninstance HasGamma Double where\n  logGamma = Gamma.logGamma\n  digamma = Gamma.digamma\n\n-- | The 'trigamma' function = the derivative of 'digamma' (which itself is the\n-- derivative of 'logGamma'). This implementation was cribbed from\n-- <https://stackoverflow.com/questions/2978979/how-to-improve-performance-of-this-numerical-computation-in-haskell/2983578 this>\n-- Stack Overflow post\ntrigamma :: Double -> Double\ntrigamma x = go 0 (x + 5) $ computeP $ x + 6\n  where\n    go :: Int -> Double -> Double -> Double\n    go !i !z !p\n        | i >= 6    = p\n        | otherwise = go (i+1) (z-1) (1 / (z*z) + p)\n    invSq z = 1 / (z * z)\n    computeP z = (((((5/66*p-1/30)*p+1/42)*p-1/30)*p+1/6)*p+1)/z+0.5*p\n      where p = invSq z\n\n\n----------------------------------------------------------------------\n-- * Helper Definitions for Automatic Differentiation\n----------------------------------------------------------------------\n\n-- | Convert between two 'AD.Forward' types, using a conversion function which\n-- should numerically be the identity, i.e., it should the representation of @r@\n-- in type @a@ to the closest representable number to @r@ in @b@.\n{-\nunsafeConvertAD :: (a -> b) -> AD.Forward a -> AD.Forward b\nunsafeConvertAD f (AD.Forward x y) =\n  AD.Forward (f x) (f y)\nunsafeConvertAD f (AD.Lift x) =\n  AD.Lift (f x)\nunsafeConvertAD _ AD.Zero = AD.Zero\n-}\n\n-- | Apply a function to an 'ADF.Forward' object that has a more efficient or\n-- accurate version for the underlying type. For instance, log1p = log . (1+)\n-- has a more accurate version in C code, but we still need to apply the above\n-- mathematical definition to compute the derivative.\noptimizedADOp :: Num a => (ADF.Forward a -> ADF.Forward a) -> (a -> a) ->\n                 ADF.Forward a -> ADF.Forward a\noptimizedADOp f f_opt x =\n  ADF.bundle (f_opt $ ADF.primal x) (ADF.tangent $ f x)\n\n-- Needed to use @'ADF.Forward' 'Double'@ Log\ninstance Log.Precise (ADF.Forward Double) where\n  log1p = optimizedADOp Log.log1p (log . (1 +))\n  expm1 = optimizedADOp Log.expm1 ((\\x -> x - 1) . exp)\n\n-- Needed to use @'ADR.Reverse' 'Double'@ Log\ninstance ADR.Reifies rs ADR.Tape => Log.Precise (ADR.Reverse rs Double) where\n  log1p x = ADR.unary Log.log1p (ADR.Id (1 / (ADR.primal x + 1))) x\n  expm1 x = ADR.unary Log.expm1 (ADR.Id ((ADR.primal x) * exp (ADR.primal x))) x\n\ninstance ADR.Reifies s ADR.Tape => HasGamma (ADR.Reverse s Double) where\n  logGamma x =\n    ADR.unary Gamma.logGamma (ADR.Id $ Gamma.digamma $ ADR.primal x) x\n  digamma x =\n    ADR.unary Gamma.digamma (ADR.Id $ trigamma $ ADR.primal x) x\n\n\n----------------------------------------------------------------------\n-- * Probabilities\n----------------------------------------------------------------------\n\n-- | We use the shorthand @Prob@ for the type of probabilities\nnewtype Prob = Prob { fromProb :: Log.Log Double }\n             deriving (Num,Eq,Ord,Real,Fractional,Typeable)\n\ninstance Show Prob where\n  show (Prob x) = show x\n\n-- | Specialized method for testing if a 'Prob' is zero\nprobIsZero :: Prob -> Bool\nprobIsZero (Prob x) = x == 0\n\n-- | Specialized method for testing if a 'Prob' is a NaN\nprobIsNaN :: Prob -> Bool\nprobIsNaN (Prob x) = isNaN $ Log.ln x\n\n-- | Convert a (non-negative) real to a 'Prob'\nrToProb :: R -> Prob\nrToProb = Prob . Log.Exp . log\n\n-- | Convert a real that is already in log-space to a 'Prob'\nlogRToProb :: R -> Prob\nlogRToProb = Prob . Log.Exp\n\n-- | Convert a 'Prob' to a real (not in log space)\nprobToR :: Prob -> R\nprobToR = exp . Log.ln . fromProb\n\n-- | Convert a 'Prob' to a real in log space\nprobToLogR :: Prob -> R\nprobToLogR = Log.ln . fromProb\n\n-- | Lifting the 'Log.sum' method to 'Prob'\nsumProb :: [Prob] -> Prob\nsumProb ps = Prob $ Log.sum $ map fromProb ps\n\n\n----------------------------------------------------------------------\n-- * Matrices of reals and probabilities\n----------------------------------------------------------------------\n\n-- | A bundled up type for unboxed real-valued vectors\nnewtype RVector = RVector { unRVector :: Vector Double } deriving (Num,Eq,Show)\n\n-- | Return the length of an 'RVector'\nlengthV :: RVector -> Int\nlengthV (RVector v) = V.length v\n\n-- | Return the @i@th element of a 'RVector'\natV :: RVector -> Int -> Double\natV (RVector v) i = v V.! i\n\n-- | Generate a probability vector of the given size\ngenerateV :: Int -> (Int -> Double) -> RVector\ngenerateV n f = RVector $ V.generate n f\n\n-- | Map over an 'RVector'\nmapV :: (R -> R) -> RVector -> RVector\nmapV f (RVector v) = RVector (V.map f v)\n\n-- | Fold over an 'RVector'\nfoldrV :: (R -> b -> b) -> b -> RVector -> b\nfoldrV f b (RVector v) = V.foldr' f b v\n\n-- | Take the sum of an 'RVector'\nsumV :: RVector -> Double\nsumV (RVector v) = V.foldl' (+) 0 v\n\n-- | Generate a vector from a list of its elements\nfromListV :: [Double] -> RVector\nfromListV = RVector . V.fromList\n\n-- | Extract the elements of a vector as a list\ntoListV :: RVector -> [Double]\ntoListV = V.toList . unRVector\n\n-- | The type of real-valued matrices\nnewtype RMatrix = RMatrix { unRMatrix :: Matrix Double } deriving (Num,Eq,Show)\n\n-- | Return the number of rows of an 'RMatrix'\nrowsM :: RMatrix -> Int\nrowsM (RMatrix m) = rows m\n\n-- | Return the number of columns of a probability matrix\ncolsM :: RMatrix -> Int\ncolsM (RMatrix m) = M.cols m\n\n-- | Return the @(i,j)@th element of a 'RMatrix'\natM :: RMatrix -> Int -> Int -> Double\natM (RMatrix m) i j = atIndex m (i,j)\n\n-- | Build a matrix from a list of its rows\nfromRowsM :: [RVector] -> RMatrix\nfromRowsM vs = RMatrix $ fromRows $ map unRVector vs\n\n-- | Build a matrix of probabilities from a list of its columns\nfromColsM :: [RVector] -> RMatrix\nfromColsM vs = RMatrix $ fromColumns $ map unRVector vs\n\n-- | Get the rows of a matrix as a list of vectors\ntoRowsM :: RMatrix -> [RVector]\ntoRowsM (RMatrix m) = map RVector $ toRows m\n\n-- | Get the columns of a matrix as a list of vectors\ntoColsM :: RMatrix -> [RVector]\ntoColsM (RMatrix m) = map RVector $ toColumns m\n\n-- | Matrix multiplication\nmulM :: RMatrix -> RMatrix -> RMatrix\nmulM (RMatrix m1) (RMatrix m2) = RMatrix (m1 M.<> m2)\n\n-- | Matrix-vector multiplication\nmulMV :: RMatrix -> RVector -> RVector\nmulMV (RMatrix m) (RVector v) = RVector (m #> v)\n\n-- | Vector-matrix multiplication\nmulVM :: RVector -> RMatrix -> RVector\nmulVM (RVector v) (RMatrix m) = RVector (v M.<# m)\n\n-- | The type of (efficient storable) vectors of values in log space\nnewtype ProbVector = ProbVector { unProbVector :: Vector Double }\n                   deriving (Eq, Show)\n\n-- | Return the length of a 'ProbVector'\nlengthPV :: ProbVector -> Int\nlengthPV (ProbVector v) = V.length v\n\n-- | Return the @i@th element of a 'ProbVector'\natPV :: ProbVector -> Int -> Prob\natPV (ProbVector v) i = Prob $ Log.Exp $ v V.! i\n\n-- | Generate a probability vector of the given size\ngeneratePV :: Int -> (Int -> Prob) -> ProbVector\ngeneratePV n f = ProbVector $ V.generate n (Log.ln . fromProb . f)\n\n-- | Generate a probability vector from a list of its elements\nfromListPV :: [Prob] -> ProbVector\nfromListPV = ProbVector . V.fromList . map probToLogR\n\n-- | Extract the elements of a probability vector as a list\ntoListPV :: ProbVector -> [Prob]\ntoListPV = map logRToProb . V.toList . unProbVector\n\n-- | Map over a 'ProbVector'\nmapPV :: (Prob -> Prob) -> ProbVector -> ProbVector\nmapPV f (ProbVector v) = ProbVector (V.map (probToLogR . f . logRToProb) v)\n\n-- | Fold over a 'ProbVector'\nfoldrPV :: (Prob -> b -> b) -> b -> ProbVector -> b\nfoldrPV f b (ProbVector v) = V.foldr' (f . logRToProb) b v\n\n-- | Apply a binary operator pointwise to two probability vectors\nbinOpPV :: (Prob -> Prob -> Prob) -> ProbVector -> ProbVector -> ProbVector\nbinOpPV f v1 v2 =\n  generatePV (min (lengthPV v1) (lengthPV v2)) (\\i -> f (atPV v1 i) (atPV v2 i))\n\ninstance Num ProbVector where\n  (+) = binOpPV (+)\n  (-) = binOpPV (-)\n  (*) = binOpPV (*)\n  abs = mapPV abs\n  signum = mapPV signum\n  fromInteger i = generatePV 1 (const $ fromInteger i)\n\n-- | Take the sum of a 'ProbVector'. The algorithm for this is adapted from\n-- 'Log.sum', though that function requires a 'Foldable' instance.\nsumPV :: ProbVector -> Prob\nsumPV (ProbVector v) | V.length v == 0 = Prob $ Log.Exp $ log 0\nsumPV (ProbVector v) =\n  let max_v = V.foldl1' max v in\n  Prob $ Log.Exp $\n  if isInfinite max_v then max_v else\n    max_v + Log.log1p (V.foldl' (\\r x -> r + Log.expm1 (x - max_v)) 0 v\n                       + fromIntegral (V.length v - 1))\n\n-- | The type of matrices of values in log space\nnewtype ProbMatrix = ProbMatrix (Matrix Double) deriving (Eq, Show)\n\n-- | Return the number of rows of a probability matrix\nrowsPM :: ProbMatrix -> Int\nrowsPM (ProbMatrix m) = rows m\n\n-- | Return the number of columns of a probability matrix\ncolsPM :: ProbMatrix -> Int\ncolsPM (ProbMatrix m) = M.cols m\n\n-- | Return the @(i,j)@th element of a 'ProbMatrix'\natPM :: ProbMatrix -> Int -> Int -> Prob\natPM pm@(ProbMatrix m) i j =\n  if i >= rowsPM pm then\n    error (\"atPM index out of bounds: row \" ++ show i ++ \" >= \" ++ show (rowsPM pm))\n    else\n    if j >= colsPM pm then\n      error (\"atPM index out of bounds: column \" ++ show j\n             ++ \" >= \" ++ show (colsPM pm))\n    else\n      Prob $ Log.Exp $ atIndex m (i,j)\n\n-- | Build a matrix of probabilities from a list of its rows\nfromRowsPM :: [ProbVector] -> ProbMatrix\nfromRowsPM vs = ProbMatrix $ fromRows $ map unProbVector vs\n\n-- | Build a matrix of probabilities from a list of its columns\nfromColsPM :: [ProbVector] -> ProbMatrix\nfromColsPM vs = ProbMatrix $ fromColumns $ map unProbVector vs\n\n-- | Get the rows of a matrix as a list of vectors\ntoRowsPM :: ProbMatrix -> [ProbVector]\ntoRowsPM (ProbMatrix m) = map ProbVector $ toRows m\n\n-- | Get the columns of a matrix as a list of vectors\ntoColsPM :: ProbMatrix -> [ProbVector]\ntoColsPM (ProbMatrix m) = map ProbVector $ toColumns m\n\n-- | Matrix-vector multiplication for probability matrices\nmulPMV :: ProbMatrix -> ProbVector -> ProbVector\nmulPMV m v =\n  generatePV (rowsPM m) $ \\i ->\n  sumPV $ generatePV (min (colsPM m) (lengthPV v)) $ \\j ->\n  (atPM m i j) * (atPV v j)\n\n-- | Vector-matrix multiplication\nmulPVM :: ProbVector -> ProbMatrix -> ProbVector\nmulPVM v m =\n  generatePV (colsPM m) $ \\j ->\n  sumPV $ generatePV (min (rowsPM m) (lengthPV v)) $ \\i ->\n  (atPM m i j) * (atPV v i)\n\n-- | Matrix-matrix multiplication for probability matrices\nmulPM :: ProbMatrix -> ProbMatrix -> ProbMatrix\nmulPM m1 (ProbMatrix m2) =\n  ProbMatrix $ fromColumns $\n  map (unProbVector . mulPMV m1 . ProbVector) $ toColumns m2\n\n\n----------------------------------------------------------------------\n-- * Distributions\n----------------------------------------------------------------------\n\n-- | This defines the support type of a distribution\ntype family Support (d :: *) :: *\n\n-- | The base class for distributions, stating that we can evaluate the density\n-- of any given distribution at a particular value.  For debugging purposes, we\n-- also require distributions to be 'Show'able.\nclass PDFDist d where\n  distDensity :: d -> Support d -> Prob\n\n-- | This type class states that monad @m@ supports distribution type @d@ by\n-- allowing distributions of type @d@ to be randomly sampled in @m@\nclass Monad m => SampleableIn m d where\n  distSample :: d -> m (Support d)\n\ninstance (SampleableIn m d,\n          Monad (t m), MonadTrans t) => SampleableIn (t m) d where\n  distSample = lift . distSample\n\n-- | This type family states that all distribution types in @ds@ satisfy @c@\ntype family DistsIn (ds :: [*]) (c :: * -> Constraint) :: Constraint where\n  DistsIn '[] c = ()\n  DistsIn (d ': ds) c = (c d, DistsIn ds c)\n\n-- | This constraint says that the distribution type @d@ is continuous, i.e.,\n-- isomorphic to the reals.\n--\n-- The class functions take @d@, not @Proxy d@, since e.g. we need\n-- different implementations for @uniform 0 1 :: Uniform@ and @uniform\n-- 1 2 :: Uniform@.\nclass Continuous d where\n  -- | Note that 'toReal' need not be defined on all of @Support d@,\n  -- and implementation should raise an error on out of bounds\n  -- values. E.g., for @uniform 0 1@, we have @Support Uniform ~\n  -- R@, but in fact 'toReal' is only defined on @[0,1]@. We\n  -- don't use @Maybe R@ as the return type, since passing an out\n  -- of bounds value to 'toReal' is probably a bug.\n  toReal :: d -> Support d -> R\n  fromReal :: d -> Double -> Support d\n\n{- FIXME: this does not seem to be the derivative in the below, and is in fact\njust fromReal in log-space. Figure this out or remove it!\n\n  -- | The derivative of 'fromReal'.\n  --\n  -- In the multivariable case the derivative becomes the determinant\n  -- of the Jacobian (matrix of partial derivatives).\n  --\n  -- We can factor this into a separate class if we end up with some\n  -- continuous distributions for which we don't have Jacobian\n  -- determinants.\n  fromReal' :: d -> Double -> LogFloat\n-}\n\n-- | The PDF of a continuous dist transformed to be a dist on the\n-- whole real line.\n--\n-- All of our single variable transforms are increasing, so I don't\n-- think we have to worry about taking absolute values; indeed, the\n-- @LogFloat@ is not even defined for negative values. (compare\n-- formulas for single dimensional change of variables which uses\n-- derivative and multiple dimension change of variables where the\n-- *absolute value* of the Jacobian is used:\n-- https://en.wikipedia.org/wiki/Integration_by_substitution).\n{-\nfromRealDistDensity :: (Continuous d, PDFDist d) => d -> Double -> Prob\nfromRealDistDensity d x = distDensity d (fromReal d x) * Prob (fromReal' d x)\n-}\n\n----------------------------------------------------------------\n-- * Helper functions for defining 'Continuous' instances\n----------------------------------------------------------------\n\n-- TODO(conathan): revisit these bijections once we have a better\n-- understanding of any additional properties we want from them. We\n-- plan to use these bijections to work in the reals and not have to\n-- worry about bounds.\n--\n-- Potential trouble: consider the open interval @(lb,ub)@ bijection\n-- below in @toRealLbUb@ and @fromRealLbUb@. The logit function @\\p ->\n-- log (p / (1 - p))@ is small for most of the reals, so if we do\n-- anything where we choose random reals over a large range, nearly\n-- all of them will cluster in the ends of underlying interval\n-- (i.e. near @lb@ and @ub@). If we want more uniform choices in the\n-- reals to map to more uniform choices in our underlying interval,\n-- then we'll need a bijection that spreads the interval much wider.\n--\n-- Some bijections to consider (these need to be scaled to work with\n-- @(lb,ub)@):\n--\n-- - @\\x -> log (x / (1 - x))@:\n--   https://www.wolframalpha.com/input/?i=plot+log+(x+/+(1+-+x))\n--\n-- - @\\x -> (1 / (1 - x)) - (1 / x)@:\n--   https://www.wolframalpha.com/input/?i=plot+(1/(1-x)+-+1/x)\n--\n-- - @\\x -> tan x@:\n--   https://www.wolframalpha.com/input/?i=plot+tan(x)\n--\n-- All of these can be made more uniform by scaling them by a\n-- constant, e.g. @\\x -> 100000 * tan x@.\n\n{- FIXME: this is only used for fromReal'; see comments for it above\n-- | The derivative of the identify function, returning @LogFloat@.\nfromRealId' :: Double -> LogFloat\nfromRealId' = logFloat\n-}\n\n-- | Biject the open interval @(lb,ub)@ onto the reals.\ntoRealLbUb :: Floating a => a -> a -> a -> a\ntoRealLbUb lb ub x = r\n  where\n    -- Biject @(lb,ub)@ onto @(0,1)@\n    p = (x - lb) / (ub - lb)\n    -- Biject @(0,1)@ onto the reals\n    --r = log (p / (1 - p))\n    r = (2*p - 1) / (p - p*p)\n\n-- | Biject the reals on the open interval @(lb,ub)@\nfromRealLbUb :: Floating a => a -> a -> a -> a\nfromRealLbUb lb ub r = x\n  where\n    -- Inverse of @\\p -> log (p / 1 - p)@, except that we have a special case\n    -- for infinite values of exp(-r), to prevent us getting NaN values for AD\n    -- exp_neg_r = exp (-r)\n    -- p = if isInfinite exp_neg_r then 0 else 1 / (1 + exp_neg_r)\n    p = (r - 2 + sqrt (r*r + 4)) / (2*r)\n    -- Inverse of @\\x -> (x - lb) / (ub - lb)@.\n    x = p * (ub - lb) + lb\n\n{-\n-- | Derivative of 'fromRealLbUb'.\nfromRealLbUb' :: R -> R -> R -> LogFloat\nfromRealLbUb' lb ub r =\n  -- The below is an expansion of\n  -- @log ((ub - lb) * (exp (-r) / (1 + exp (-r))**2))@.\n  --\n  -- Here we use @log1p@ -- an implementation of @\\p -> log (1 + p)@\n  -- that's optimized for small @p@ -- from\n  -- @Data.Numeric.LogFloat@. This implementation of @log1p@ will use\n  -- an optimized C implementation if compiled with the @useffi@ flag,\n  -- which is supposed to be enabled by default.\n  --\n  -- The @log-domain@ package that provides an native Haskell\n  -- implementation of @log1p@, I think.\n  logToLogFloat $ log (ub - lb) - r - 2 * log1p (exp (- r))\n-}\n\n-- | Biject the open interval @(0,\\infty)@ onto the reals, using the piecewise\n-- function that maps @x@ in @(0,1)@ to @log x@ and otherwise maps @x@ to @x-1@.\ntoRealZeroInftyPW :: Double -> Double\ntoRealZeroInftyPW x = if x < 1 then log x else x - 1\n\n-- | Biject the reals on the open interval @(0,\\infty)@, using the piecewise\n-- function that maps negative @x@ to @exp x@ and otherwise maps @x@ to @x+1@.\nfromRealZeroInftyPW :: Double -> Double\nfromRealZeroInftyPW x = if x < 0 then exp x else x + 1\n\n-- | Biject the open interval @(lb,\\infty)@ onto the reals.\ntoRealLbInfty :: Double -> Double -> R\ntoRealLbInfty lb x = log (x - lb)\n\n-- | Biject the reals onto the open interval @(lb,\\infty)@.\nfromRealLbInfty :: Double -> Double -> R\nfromRealLbInfty lb r = exp r + lb\n\n-- | Biject the reals onto the open interval @(lb,\\infty)@ in log-space\nfromRealLbInfty' :: Double -> Double -> Prob\nfromRealLbInfty' lb r = logRToProb lb + logRToProb r\n\n-- | Biject the open interval @(-\\infty,ub)@ onto the reals.\ntoRealInftyUb :: Double -> Double -> R\ntoRealInftyUb ub x = - log (ub - x)\n\n-- | Biject the reals onto the open interval @(-\\infty,ub)@.\nfromRealInftyUb :: Double -> Double -> R\nfromRealInftyUb ub r = - (exp (- r) - ub)\n\n-- | Biject the reals onto the open interval @(lb,\\infty)@ in log-space\nfromRealInftyUb' :: Double -> Double -> Prob\nfromRealInftyUb' _ub _r =\n  error \"FIXME: fromRealInftyUb' is not right!\"\n  -- logRToProb ub + logRToProb (- r)\n\n----------------------------------------------------------------------\n-- * Example distribution types\n----------------------------------------------------------------------\n\n-- | Evaluate the density of a normal distribution at value @r@. This is\n-- \"unchecked\" in that it assumes @sigma@ is non-negative.\nnormalDensityUnchecked :: Floating r => r -> r -> r -> Log.Log r\nnormalDensityUnchecked mu sigma x =\n  Log.Exp $ - 0.5 * sq ((x - mu) / sigma) - log sigma - halfLogTwoPi\n  where\n    sq n = n * n\n    halfLogTwoPi = 0.5 * log (2 * pi)\n\n-- | Evaluate the density of a normal distribution at value @r@\nnormalDensityGen :: (Ord r, Floating r, Show r) => r -> r -> r -> Log.Log r\nnormalDensityGen mu sigma x =\n  if sigma <= 0 then\n    error $ \"normalDensity: sigma is <= 0: sigma = \" ++ show sigma\n  else\n    normalDensityUnchecked mu sigma x\n\n-- | Evaluate the density of a normal distribution at value @r@\nnormalDensity :: Double -> Double -> Double -> Prob\nnormalDensity mu sigma x = Prob $ normalDensityGen mu sigma x\n\ndata StdNormal = StdNormal deriving Show\ntype instance Support StdNormal = R\ninstance PDFDist StdNormal where\n  distDensity StdNormal x = logRToProb $ - 0.5 * sq x - halfLogTwoPi\n    where\n    sq n = n * n\n    halfLogTwoPi = 0.5 * log (2 * pi)\n\ninstance Continuous StdNormal where\n  toReal _ = id\n  fromReal _ = id\n  --fromReal' _ = fromRealId'\n\n-- | The normal distribution\ndata Normal = Normal R R deriving Show\ntype instance Support Normal = R\n\ninstance PDFDist Normal where\n  distDensity (Normal mu sigma) r = normalDensity mu sigma r\n\ninstance Continuous Normal where\n  toReal _ = id\n  fromReal _ = id\n  --fromReal' _ = fromRealId'\n\n----------------------------------------------------------------\n\n-- | Multivariate normal distribution.\n--\n-- Our multivariate normal of @k@ dimensions is parameterized by the\n-- mean vectur @mu = [mu1,...,muk]@ and the *Cholesky factor* @c@ of\n-- the covariance matrix @Sigma@. I.e., for multivariate normal with\n-- mean @mu@ and covariance matrix @Sigma@, we use\n--\n-- > MVNormal mu c\n--\n-- for\n--\n-- > transpose c * c = Sigma\n--\n-- The requirements for @c@ to be well formed are that\n--\n-- - @c@ is upper triangular.\n--\n-- - all diagonal entries of @c@ are positive.\n--\n-- There are several reasons to prefer the Cholesky factor @c@ to the\n-- covariance matrix @Sigma@:\n--\n-- - computing the PDF is more efficient using @c@.\n--\n-- - the sampling algorithm uses @c@, so we need to compute it anyway.\n--\n-- - all upper triangular matrices with positive diagonal entries are\n--   valid Cholesky factors, and a matrix is positive definite iff it\n--   has a Cholesky factorization, and the Cholesky factorization is\n--   unique. So, it's easy to uniformly sample the space of\n--   multivariate normals by uniformly sampling the space upper\n--   triangular matrices with positive diagonal entries. We care about\n--   sampling multivariate normals e.g. when using multivariate\n--   normals as a variational family in Black Box Variation Inference.\n--\n-- There is a more general definition of multivariate normal which\n-- only requires non-negative entries on the diagonal of @c@, where\n-- zero values correspond to zero variance random variables,\n-- i.e. constants, but we don't support those here (the PDFs would be\n-- Dirac deltas).\n--\n-- A covariance matrix @Sigma@ can be converted into a Cholesky factor\n-- @c@ using the @Numeric.LinearAlgebra.chol@ function:\n--\n-- > c = chol Sigma\n--\n-- The covariance matrix @Sigma@ must be symmetric and positive\n-- definite; you can use @Numeric.LinearAlgebra.trustsym@ to construct\n-- it.\ndata MVNormal = MVNormal (Vector Double) (Matrix Double) deriving Show\n\ntype instance Support MVNormal = Vector Double\n\ninstance PDFDist MVNormal where\n  distDensity (MVNormal mu c) x =\n    mvnDensityMuC mu c x\n\ninstance (Monad m, SampleableIn m Normal) => SampleableIn m MVNormal where\n  -- https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Drawing_values_from_the_distribution\n  distSample (MVNormal mu c) = do\n    z <- V.fromList <$> (replicateM (size mu) $ distSample (Normal 0 1))\n    -- Our Cholesky factorization is @Sigma = transpose c * c@ and\n    -- Wikipedia has @Sigma = c * transpose c@, so we need to\n    -- transpose here.\n    return $ mu + (tr c #> z)\n\n-- | Multivariate normal density in terms of Cholesky factor.\nmvnDensityMuC :: Vector Double -> Matrix Double -> Vector Double -> Prob\nmvnDensityMuC mu c x =\n  if not isValidCholeskyFactor\n  then error \"distDensity: Cholesky factor is malformed!\"\n  -- https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Likelihood_function.\n  else logRToProb $ -0.5 * (logAbsDet + prod + k * log2pi)\n  where\n    log2pi = log (2 * pi)\n    k = fromIntegral $ size x\n    -- We have\n    --\n    -- > Sigma = transpose c * c\n    --\n    -- and so\n    --\n    -- > det Sigma = det c * det c .\n    --\n    -- We know @det c > 0@ since the diag is positive.\n    logAbsDet = 2 * (log $ V.product (takeDiag c))\n    -- Here @cholSolve@ solves a linear system for the matrix @Sigma@\n    -- for which @c@ is the Cholesky factor. I.e. if\n    --\n    -- > u == cholSolve m v\n    --\n    -- then\n    --\n    -- > transpose c * c * v == u .\n    prod = (x - mu) <.> flatten (cholSolve c (asColumn $ x - mu))\n\n    isValidCholeskyFactor = all (> 0) (V.toList $ takeDiag c)\n\n-- | Multivariate normal density in terms of covariance matrix @Sigma@.\n--\n-- Can use this to test the other implementation above; see\n-- 'testMvDensity' below.\nmvnDensityMuSigma :: Vector Double -> Matrix Double -> Vector Double -> Prob\nmvnDensityMuSigma mu sigma x =\n  if signDet < 0\n  then error \"distDensity: matrix is not positive definite!\"\n  -- https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Likelihood_function.\n  else logRToProb $ -0.5 * (logAbsDet + prod + k * log2pi)\n  where\n    log2pi = log (2 * pi)\n    k = fromIntegral $ size x\n    (sigmaInv, (logAbsDet, signDet)) = invlndet sigma\n    prod = (x - mu) <.> (sigmaInv #> (x - mu))\n\n-- | Check that the two mv normal density functions agree.\n--\n-- They agree if this function returns a small number.\ntestMvnDensity :: Vector Double -> Matrix Double -> Vector Double -> Double\ntestMvnDensity mu c x =\n   abs $ (probToR $ mvnDensityMuSigma mu (tr c <> c) x) -\n         (probToR $ mvnDensityMuC mu c x)\n\n-- | Should return a smalllllll number.\ntestMvnDensityExample :: Double\ntestMvnDensityExample = sum [ testMvnDensity mu c x | x <- xs ]\n  where\n    mu = V.fromList [1,2]\n    c = chol (trustSym $ (2><2) [1,0.5,0.5,1])\n    xs = [ V.fromList [x0,x1] | x0 <- [-5,-4.5..5] , x1 <- [-5,-4.5..5] ]\n\n----------------------------------------------------------------\n\n-- | The uniform distribution\ndata Uniform = Uniform Double R deriving Show\ntype instance Support Uniform = R\n\nuniformDensityGen :: (Ord r, RealFloat r, Log.Precise r) =>\n                     r -> r -> r -> Log.Log r\nuniformDensityGen lb ub r\n  | lb >= ub =\n    error \"Malformed uniform distribution! Lower bound >= upper bound!\"\n  | r >= lb && r < ub =\n    -- The expression 1 / (ub - lb) in log-space\n      Log.Exp $ negate $ log $ ub - lb\n  | otherwise = 0\n\nuniformDensity :: Double -> Double -> Double -> Prob\nuniformDensity lb ub r\n  | lb >= ub =\n    error \"Malformed uniform distribution! Lower bound >= upper bound!\"\n  | r >= lb && r < ub = 1 / rToProb (ub - lb)\n  | otherwise = 0\n\ninstance PDFDist Uniform where\n  distDensity (Uniform lb ub) = uniformDensity lb ub\n\ninstance Continuous Uniform where\n  toReal (Uniform lb ub) = toRealLbUb lb ub\n  fromReal (Uniform lb ub) = fromRealLbUb lb ub\n  --fromReal' (Uniform lb ub) = fromRealLbUb' lb ub\n\ndata StudentT = StudentT Double deriving Show\ntype instance Support StudentT = R\n\ninstance Continuous StudentT where\n  toReal _ = id\n  fromReal _ = id\n  --fromReal' _ = fromRealId'\n\ndata Cauchy = Cauchy deriving Show\ntype instance Support Cauchy = R\ninstance PDFDist Cauchy where\n  distDensity Cauchy x = logRToProb $ - log (1 + sq x) - log pi\n    where sq n = n * n\n\ninstance Continuous Cauchy where\n  toReal _ = id\n  fromReal _ = id\n  --fromReal' _ = fromRealId'\n\ndata For d = forall t. For [t] (t -> d)\ntype instance Support (For d) = [Support d]\ninstance PDFDist d => PDFDist (For d) where\n  distDensity (For xs f) ys =\n    product [distDensity (f x) y | (x,y) <- zip xs ys]\n\ndata StdUniform = StdUniform deriving Show\ntype instance Support StdUniform = R\n\ninstance PDFDist StdUniform where\n  distDensity _ = uniformDensity 0 1\n\ninstance Continuous StdUniform where\n  toReal _ = toRealLbUb 0 1\n  fromReal _ = fromRealLbUb 0 1\n  --fromReal' _ = fromRealLbUb' 0 1\n\n-- | The categorical distribution, that picks a natural number between 1 and @n@\n-- from a list of probabilisties of each number. Note that the probabilities\n-- need not be normalized, e.g., the list @[1,1,1]@ is treated the same as\n-- @[1/3,1/3,1/3]@, i.e., that each of 0, 1, and 2 has equal probability.\ndata Categorical = Categorical [Prob] deriving Show\ntype instance Support Categorical = Int\n\ninstance PDFDist Categorical where\n  distDensity (Categorical ws) n =\n    let total_w = sum ws in\n    if n >= length ws then 0 else ws!!n / total_w\n\n\ndata Exponential = Exponential R deriving Show\ntype instance Support Exponential = R\n\nexponentialDensityUnchecked :: (RealFloat a, Log.Precise a) =>\n                               a -> a -> Log.Log a\nexponentialDensityUnchecked rate x = Log.Exp $ log rate - rate * x\n\nexponentialDensity :: (Ord a, RealFloat a, Log.Precise a) => a -> a -> Log.Log a\nexponentialDensity rate x =\n  if rate > 0 then exponentialDensityUnchecked rate x else 0\n\ninstance PDFDist Exponential where\n  distDensity (Exponential rate) = Prob . exponentialDensity rate\n\n\ndata Beta = Beta R R deriving Show\ntype instance Support Beta = R\n\nbetaDensityUnchecked :: (HasGamma a, Floating a) => a -> a -> a -> Log.Log a\nbetaDensityUnchecked alpha beta x =\n  Log.Exp $\n  ((alpha - 1) * log x) + ((beta - 1) * log (1 - x)) -\n  (logGamma alpha + logGamma alpha - logGamma (alpha + beta))\n\nbetaDensity :: (Ord a, HasGamma a, RealFloat a, Log.Precise a) =>\n               a -> a -> a -> Log.Log a\nbetaDensity alpha beta x =\n  if x > 0 && x < 1 then betaDensityUnchecked alpha beta x else 0\n\n-- | Compute the PDF of the Beta distribution where the argument is already in\n-- log space\nbetaDensityLog :: (Ord a, HasGamma a, RealFloat a, Log.Precise a) =>\n                  a -> a -> Log.Log a -> Log.Log a\nbetaDensityLog alpha beta x =\n  if x > 0 && x < 1 then\n    Log.Exp $\n    ((alpha - 1) * Log.ln x) + ((beta - 1) * Log.ln (1 - x)) -\n    (logGamma alpha + logGamma alpha - logGamma (alpha + beta))\n  else 0\n\ninstance PDFDist Beta where\n  distDensity (Beta alpha beta) = Prob . betaDensity alpha beta\n\n\ndata Gamma = Gamma R R deriving Show\ntype instance Support Gamma = R\n\n-- | Calculate the PDF of the gamma distribution, given shape parameter @k@ and\n-- scale parameter @theta@, but without the @1 / (gamma k * theta ** k)@\n-- normalization constant\nrelativeGammaDensity :: Floating a => a -> a -> a -> Log.Log a\nrelativeGammaDensity k theta x =\n  Log.Exp $ (k - 1) * log x - (x / theta)\n\n-- | Calculate the PDF of the gamma distribution, assuming @x > 0@, given shape\n-- parameter @k@ and scale parameter @theta@\ngammaDensityUnchecked :: (HasGamma a, Floating a) => a -> a -> a -> Log.Log a\ngammaDensityUnchecked k theta x =\n  Log.Exp (Log.ln (relativeGammaDensity k theta x) - logGamma k - k * log theta)\n\n-- | Calculate the PDF of the gamma distribution, given shape parameter @k@ and\n-- scale parameter @theta@\ngammaDensity :: (Ord a, HasGamma a, RealFloat a, Log.Precise a) =>\n                a -> a -> a -> Log.Log a\ngammaDensity k theta x =\n  if x <= 0 then 0 else gammaDensityUnchecked k theta x\n\ninstance PDFDist Gamma where\n  distDensity (Gamma k theta) = Prob . gammaDensity k theta\n\ndata Dirichlet = Dirichlet [R] deriving Show\ntype instance Support Dirichlet = [R]\n\n-- | The log of the multivariate beta function\nlogMVBeta :: (HasGamma a, Floating a) => [a] -> Log.Log a\nlogMVBeta alphas =\n  -- Gamma (a_1) * ... * Gamma (a_n) / Gamma (a_1 + ... + a_n) in log space\n  Log.Exp $ sum (map logGamma alphas) - logGamma (sum alphas)\n\n-- | Calculate the density of the Dirichlet distribution at any type that\n-- supports the gamma function\ndirichletDensity :: (HasGamma a, Floating a) => [a] -> [a] -> Log.Log a\ndirichletDensity alphas xs =\n  -- x_1 ** (alpha_1 - 1) * ... * x_n ** (alpha_n - 1) / Beta (alphas)\n  Log.Exp $\n  sum (zipWith (\\alpha x -> (alpha - 1) * log x) alphas xs) -\n  Log.ln (logMVBeta alphas)\n\n-- | Calculate the density of the Dirichlet distribution over log space\ndirichletDensityLog :: (HasGamma a, Floating a) => [a] -> [Log.Log a] ->\n                       Log.Log a\ndirichletDensityLog alphas xs =\n  -- x_1 ** (alpha_1 - 1) * ... * x_n ** (alpha_n - 1) / Beta (alphas)\n  Log.Exp $\n  sum (zipWith (\\alpha x -> (alpha - 1) * Log.ln x) alphas xs) -\n  Log.ln (logMVBeta alphas)\n\n-- | The log of the multivariate beta function\nlogMVBetaV :: RVector -> Log.Log Double\nlogMVBetaV (RVector alphas) =\n  -- Gamma (a_1) * ... * Gamma (a_n) / Gamma (a_1 + ... + a_n) in log space\n  Log.Exp $ V.foldl' (\\r alpha -> r + logGamma alpha) 0 alphas\n\n-- | Calculate the density of the Dirichlet distribution over an 'RVector'\ndirichletDensityV :: RVector -> RVector -> Prob\ndirichletDensityV (RVector alphas) (RVector xs) =\n  -- x_1 ** (alpha_1 - 1) * ... * x_n ** (alpha_n - 1) / Beta (alphas)\n  Prob $ Log.Exp $\n  V.ifoldl' (\\r i alpha -> r + (alpha - 1) * log (xs!i)) 0 alphas -\n  Log.ln (logMVBetaV $ RVector alphas)\n\n-- | Calculate the density of the Dirichlet distribution over a 'ProbVector'\ndirichletDensityPV :: RVector -> ProbVector -> Prob\ndirichletDensityPV (RVector alphas) (ProbVector xs) =\n  -- x_1 ** (alpha_1 - 1) * ... * x_n ** (alpha_n - 1) / Beta (alphas)\n  Prob $ Log.Exp $\n  V.ifoldl' (\\r i alpha -> r + (alpha - 1) * xs!i) 0 alphas -\n  Log.ln (logMVBetaV $ RVector alphas)\n\ninstance PDFDist Dirichlet where\n  distDensity (Dirichlet alphas) xs = Prob $ dirichletDensity alphas xs\n\ndata Bernoulli = Bernoulli Double deriving Show\n\ndata Binomial = Binomial Int Double deriving Show\n\ndata Wishart = Wishart (Matrix Double) Double deriving Show\ntype instance Support Wishart = Matrix Double\ninstance PDFDist Wishart where\n  distDensity (Wishart _scaleChol _df) _x = undefined\n\n-- | A dirac delta distribution, that has a 100 percent chance of returning a\n-- given constant value\ndata Dirac a = Dirac a deriving Show\ntype instance Support (Dirac a) = a\n\ninstance Eq a => PDFDist (Dirac a) where\n  -- FIXME: this density is not really correct for R; it should really be\n  -- infinite for continuous functions and 1 for discrete ones\n  distDensity (Dirac a) x = if a == x then 1 else 0\n\n-- | A technically invalid distribution, that always returns the value @x@ but\n-- always has a score of @1@\ndata DontCare a = DontCare a deriving Show\ntype instance Support (DontCare a) = a\n\ninstance PDFDist (DontCare a) where\n  distDensity (DontCare _) _ = 1\n\n----------------------------------------------------------------------\n-- * Continuity\n----------------------------------------------------------------------\n\nclass Continuous (d f) => ReprContinuous d f\ninstance Continuous (d f) => ReprContinuous d f\n\n-- | This type class states that monad @m@ supports distribution type @d@ by\n-- allowing distributions of type @d@ to be randomly sampled in @m@\nclass Monad m => ReprSampleableIn m d f where\n  distSampleRepr :: d f -> m (f (ReprSupport d))\n\nclass DiffContinuous d f where\n  toRealF   :: d f -> f (ReprSupport d) -> f R\n  fromRealF :: d f -> f R -> f (ReprSupport d)\n\nclass DiffPDF d f where\n  distDensityF :: d f -> f (ReprSupport d) -> f Prob\n\n{-\ninstance DiffContinuous ReprNormal AD.Forward where\n  toRealF _ d = d\n  fromRealF _ d = d\n\ninstance DiffPDF ReprNormal AD.Forward where\n  distDensityF (ReprNormal mu sigma) x =\n    if sigma <= 0\n      then error $ \"distDensityAD Normal: sigma is <= 0: sigma = \" ++ show sigma\n           -- FIXME: instead of using exp below, figure out how to do an\n           -- adToProb that takes a real in log space and preserves\n      else adToProb $ exp $ -0.5 * sq((x - mu) / sigma) - log sigma - halfLogTwoPi\n      where sq n = n * n\n            halfLogTwoPi = 0.5 * log (2 * pi)\n\ninstance DiffContinuous ReprUniform AD.Forward where\n  toRealF (ReprUniform lb ub) =\n    toRealLbUbNum lb ub\n  fromRealF (ReprUniform lb ub) =\n    fromRealLbUbNum lb ub\n\ninstance DiffPDF ReprUniform AD.Forward where\n  distDensityF (ReprUniform lb ub) _\n    | lb >= ub = error \"Malformed uniform distribution! Lower bound >= upper bound!\"\n    | otherwise =\n      (1 / adToProb (lb - ub))\n-}\n\n----------------------------------------------------------------------\n-- Entropy\n----------------------------------------------------------------------\n\n-- | FIXME: document this!\nclass Entropy d where\n  entropy :: d -> Double\n\ninstance Entropy Normal where\n  entropy (Normal _mu sigma) = k + log sigma\n    where\n    k = 0.5 * (1 + log (2 * pi))\n\n----------------------------------------------------------------------\n-- * The ReprDistribution stuff\n----------------------------------------------------------------------\n\n-- | This defines the support type of a distribution\ntype family ReprSupport (d :: (* -> *) -> *) :: *\n\ndata ReprNormal f = ReprNormal (f R) (f R)\ntype instance ReprSupport ReprNormal = R\n\ndata ReprUniform f = ReprUniform (f R) (f R)\ntype instance ReprSupport ReprUniform = R\n\ndata ReprCauchy f = ReprCauchy\ntype instance ReprSupport ReprCauchy = R\n\ndata ReprCategorical f = ReprCategorical [f Prob]\ntype instance ReprSupport ReprCategorical = Int\n\n-- FIXME: this uses different vector and matrix types than MVNormal\ndata ReprMVNormal f = ReprMVNormal (f RMatrix) (f RMatrix)\ntype instance ReprSupport ReprMVNormal = RMatrix\n", "meta": {"hexsha": "4435cbf9f7d795a88952f214049bb6a9b9afad62", "size": 37357, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Language/Grappa/Distribution.hs", "max_stars_repo_name": "GaloisInc/grappa", "max_stars_repo_head_hexsha": "dd694520dfc5b6b90e01def72575235ab1c874ac", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T06:40:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T06:40:58.000Z", "max_issues_repo_path": "src/Language/Grappa/Distribution.hs", "max_issues_repo_name": "GaloisInc/grappa", "max_issues_repo_head_hexsha": "dd694520dfc5b6b90e01def72575235ab1c874ac", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-09-05T16:06:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-26T01:24:32.000Z", "max_forks_repo_path": "src/Language/Grappa/Distribution.hs", "max_forks_repo_name": "GaloisInc/grappa", "max_forks_repo_head_hexsha": "dd694520dfc5b6b90e01def72575235ab1c874ac", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-19T17:29:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-19T17:29:10.000Z", "avg_line_length": 36.410331384, "max_line_length": 129, "alphanum_fraction": 0.646599031, "num_tokens": 10694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4739729520001425}}
{"text": "-- Copyright (c) 2015-2020 Rudy Matela.\n-- Distributed under the 3-Clause BSD licence (see the file LICENSE).\nimport Test\n\nimport System.Exit (exitFailure)\nimport Data.List (elemIndices)\n\n-- import Test.LeanCheck -- already exported by Test\nimport Test.LeanCheck.Utils\n\nimport Data.Ratio\nimport Data.Complex\nimport Data.Int\nimport Data.Word\n\nmain :: IO ()\nmain  =  do\n  max <- getMaxTestsFromArgs 200\n  case elemIndices False (tests max) of\n    [] -> putStrLn \"Tests passed!\"\n    is -> do putStrLn (\"Failed tests:\" ++ show is)\n             exitFailure\n\ntests :: Int -> [Bool]\ntests n =\n  [ True\n\n  -- interleave\n  , [1,2,3] +| [0,0,0] == [1,0,2,0,3,0]\n  , take 3 ([1,2] +| (0:undefined)) == [1,0,2]\n  , [0,2..] +| [1,3..] =| n |= [0,1..]\n\n  -- etc\n  , tNatPairOrd n\n  , tNatTripleOrd n\n  , tNatQuadrupleOrd n\n  , tNatQuintupleOrd n\n  , tNatListOrd n\n  , tListsOfNatOrd n\n  , listsOf (tiers::[[Nat]]) =| 10 |= tiers\n\n  -- tests!\n  , counterExample n (\\x y -> x + y /= (x::Int)) == Just [\"0\", \"0\"]\n  , counterExample n (\\x y -> x + y == (x::Int)) == Just [\"0\", \"1\"]\n  , counterExample n (maybe True (==(0::Int))) == Just [\"(Just 1)\"]\n  , holds n (\\x -> x == (x::Int))\n\n  -- For when NaN is in the enumeration (by default, it is not):\n  --, fails 100 (\\x -> x == (x::Float))  -- NaN != NaN  :-)\n  --, counterExample 100 (\\x -> x == (x::Float)) == Just [\"NaN\"]\n  , counterExample n (\\x y -> x + y == (x::Float))  == Just [\"0.0\",\"1.0\"]\n  , counterExample n (\\x y -> x + y == (x::Double)) == Just [\"0.0\",\"1.0\"]\n  , holds          n (\\x -> x + 1 /= (x::Int))\n  , counterExample n (\\x -> x + 1 /= (x::Float))  == Just [\"Infinity\"]\n    || counterExample n (\\x -> x + 1 /= (x::Float)) == Just [\"inf\"] -- bug on Hugs 2006-09?\n  , counterExample n (\\x -> x + 1 /= (x::Double)) == Just [\"Infinity\"]\n    || counterExample n (\\x -> x + 1 /= (x::Float)) == Just [\"inf\"] -- bug on Hugs 2006-09?\n  , allUnique (take n list :: [Float])\n  , allUnique (take n list :: [Double])\n\n  , allUnique (take n list :: [Rational])\n  , allUnique (take n list :: [Ratio Nat])\n  , orderedOn (\\r -> numerator r + denominator r) (take n (list :: [Ratio Nat]))\n  , orderedOn (\\r -> abs (numerator r) + abs(denominator r)) (take n (list :: [Rational]))\n\n  , list == [LT, EQ, GT]\n  , orderedOn length (take n (list :: [[Ordering]]))\n  , orderedOn length (take n (list :: [[Bool]]))\n\n  , strictlyOrderedOn (\\xs -> (sum $ map (+1) xs, xs)) (take n (list :: [[Word]]))\n\n  , tPairEqParams n\n  , tTripleEqParams n\n\n  , tProductsIsFilterByLength (tiers :: [[ Nat ]])   10 `all` [1..10]\n  , tProductsIsFilterByLength (tiers :: [[ Bool ]])   6 `all` [1..10]\n  , tProductsIsFilterByLength (tiers :: [[ [Nat] ]])  6 `all` [1..10]\n\n  , holds n $  (\\/)  ==== zipWith' (++) [] [] -:> [[uint2]]\n  , holds n $  (\\/)  ==== zipWith' (++) [] [] -:> [[bool]]\n  , holds n $ (\\\\//) ==== zipWith' (+|) [] [] -:> [[uint2]]\n  , holds n $ (\\\\//) ==== zipWith' (+|) [] [] -:> [[bool]]\n\n  , holds n $ \\x -> x == (x :: Word)\n  , holds n $ \\x -> x == (x :: Word8)\n  , holds n $ \\x -> x == (x :: Word16)\n  , holds n $ \\x -> x == (x :: Word32)\n  , holds n $ \\x -> x == (x :: Word64)\n\n  , holds n $ \\x -> x == (x :: Int)\n  , holds n $ \\x -> x == (x :: Int8)\n  , holds n $ \\x -> x == (x :: Int16)\n  , holds n $ \\x -> x == (x :: Int32)\n  , holds n $ \\x -> x == (x :: Int64)\n\n  , holds n $ \\x -> x == (x :: Complex Double)\n  ]\n\nallUnique :: Ord a => [a] -> Bool\nallUnique [] = True\nallUnique (x:xs) = x `notElem` xs\n                && allUnique (filter (< x) xs)\n                && allUnique (filter (> x) xs)\n\n\n-- | 'zipwith\\'' works similarly to 'zipWith', but takes neutral elements to\n--   operate when one of the lists is exhausted, so, you don't loose elements.\n--\n-- > zipWith' f z e [x,y] [a,b,c,d] == [f x a, f y b, f z c, f z d]\n--\n-- > zipWith' f z e [x,y,z] [a] == [f x a, f y e, f z e]\n--\n-- > zipWith' (+) 0 0 [1,2,3] [1,2,3,4,5,6] == [2,4,6,4,5,6]\nzipWith' :: (a->b->c) -> a -> b  -> [a] -> [b] -> [c]\nzipWith' _ _  _  []     [] = []\nzipWith' f _  zy xs     [] = map (`f` zy) xs\nzipWith' f zx _  []     ys = map (f zx) ys\nzipWith' f zx zy (x:xs) (y:ys) = f x y : zipWith' f zx zy xs ys\n", "meta": {"hexsha": "fb226dda5bc7a8cf076e02b4aaa2518a30d09268", "size": 4127, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/main.hs", "max_stars_repo_name": "rudymatela/llcheck", "max_stars_repo_head_hexsha": "6375d3f859323e327b7655d043ef9f1824609ad2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2016-06-21T10:30:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T18:40:23.000Z", "max_issues_repo_path": "test/main.hs", "max_issues_repo_name": "rudymatela/llcheck", "max_issues_repo_head_hexsha": "6375d3f859323e327b7655d043ef9f1824609ad2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2016-06-20T12:18:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-13T21:46:44.000Z", "max_forks_repo_path": "test/main.hs", "max_forks_repo_name": "rudymatela/llcheck", "max_forks_repo_head_hexsha": "6375d3f859323e327b7655d043ef9f1824609ad2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2016-04-12T14:54:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T22:10:30.000Z", "avg_line_length": 34.6806722689, "max_line_length": 91, "alphanum_fraction": 0.5110249576, "num_tokens": 1528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.4739268156719015}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes                      #-}\n{-# LANGUAGE ApplicativeDo                            #-}\n{-# LANGUAGE DeriveAnyClass                           #-}\n{-# LANGUAGE DeriveDataTypeable                       #-}\n{-# LANGUAGE DeriveGeneric                            #-}\n{-# LANGUAGE DerivingVia                              #-}\n{-# LANGUAGE FlexibleContexts                         #-}\n{-# LANGUAGE FlexibleInstances                        #-}\n{-# LANGUAGE GADTs                                    #-}\n{-# LANGUAGE InstanceSigs                             #-}\n{-# LANGUAGE KindSignatures                           #-}\n{-# LANGUAGE MultiParamTypeClasses                    #-}\n{-# LANGUAGE PatternSynonyms                          #-}\n{-# LANGUAGE RankNTypes                               #-}\n{-# LANGUAGE RecordWildCards                          #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE StandaloneDeriving                       #-}\n{-# LANGUAGE TemplateHaskell                          #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeFamilies                             #-}\n{-# LANGUAGE TypeInType                               #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# LANGUAGE UndecidableInstances                     #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise       #-}\n\nmodule Backprop.Learn.Model.Regression (\n  -- * Linear Regression\n    linReg, logReg\n  , LRp(..), lrAlpha, lrBeta, runLRp\n  -- * Reshape\n  , reshapeLRpInput, reshapeLRpOutput\n  , expandLRpInput, expandLRpOutput\n  , premuteLRpInput, permuteLRpOutput\n  -- * ARIMA\n  , arima, autoregressive, movingAverage, arma\n  , ARIMAp(..), ARIMAs(..)\n  , arimaPhi, arimaTheta, arimaConstant, arimaYPred, arimaYHist, arimaEHist\n  ) where\n\nimport           Backprop.Learn.Initialize\nimport           Backprop.Learn.Model.Combinator\nimport           Backprop.Learn.Model.Function\nimport           Backprop.Learn.Model.Types\nimport           Backprop.Learn.Regularize\nimport           Control.DeepSeq\nimport           Control.Monad.Primitive\nimport           Data.Finite\nimport           Data.Kind\nimport           Data.List\nimport           Data.Maybe\nimport           Data.Proxy\nimport           Data.Type.Equality\nimport           Data.Typeable\nimport           GHC.Generics                          (Generic)\nimport           GHC.TypeLits.Compare\nimport           GHC.TypeNats\nimport           Lens.Micro.TH\nimport           Numeric.Backprop\nimport           Numeric.LinearAlgebra.Static.Backprop\nimport           Numeric.LinearAlgebra.Static.Vector\nimport           Numeric.OneLiner\nimport           Numeric.Opto.Ref\nimport           Numeric.Opto.Update hiding            ((<.>))\nimport           Statistics.Distribution\nimport           Unsafe.Coerce\nimport qualified Data.Binary                           as Bi\nimport qualified Data.Vector.Generic.Sized             as SVG\nimport qualified Data.Vector.Sized                     as SV\nimport qualified Data.Vector.Storable.Sized            as SVS\nimport qualified Numeric.LinearAlgebra                 as HU\nimport qualified Numeric.LinearAlgebra.Static          as H\nimport qualified System.Random.MWC                     as MWC\n\n-- | Linear Regression parameter\ndata LRp (i :: Nat) (o :: Nat) = LRp\n    { _lrAlpha :: !(R o)\n    , _lrBeta  :: !(L o i)\n    }\n  deriving stock     (Generic, Typeable, Show)\n  deriving anyclass  (NFData, Linear Double, Metric Double, Bi.Binary, Initialize, Backprop)\n\nderiving via (GNum (LRp i o)) instance (KnownNat i, KnownNat o) => Num (LRp i o)\nderiving via (GNum (LRp i o)) instance (KnownNat i, KnownNat o) => Fractional (LRp i o)\nderiving via (GNum (LRp i o)) instance (KnownNat i, KnownNat o) => Floating (LRp i o)\n\nmakeLenses ''LRp\n\ninstance (PrimMonad m, KnownNat i, KnownNat o) => Mutable m (LRp i o) where\n    type Ref m (LRp i o) = GRef m (LRp i o)\n    thawRef   = gThawRef\n    freezeRef = gFreezeRef\n    copyRef   = gCopyRef\ninstance (PrimMonad m, KnownNat i, KnownNat o) => LinearInPlace m Double (LRp i o)\n\ninstance (KnownNat i, KnownNat o) => Regularize (LRp i o) where\n    rnorm_1 = rnorm_1 . _lrBeta\n    rnorm_2 = rnorm_2 . _lrBeta\n    lasso r LRp{..} = LRp { _lrAlpha = 0\n                          , _lrBeta  = lasso r _lrBeta\n                          }\n    ridge r LRp{..} = LRp { _lrAlpha = 0\n                          , _lrBeta  = ridge r _lrBeta\n                          }\n\ninstance (KnownNat i, KnownNat o, PrimMonad m) => Learnable m (LRp i o)\n\nrunLRp\n    :: (KnownNat i, KnownNat o, Reifies s W)\n    => BVar s (LRp i o)\n    -> BVar s (R i)\n    -> BVar s (R o)\nrunLRp lrp x = (lrp ^^. lrBeta) #> x + (lrp ^^. lrAlpha)\n\n-- | Reshape an 'LRp' to take more or less inputs.  If more, new parameters\n-- are initialized randomly according to the given distribution.\nreshapeLRpInput\n    :: (ContGen d, PrimMonad m, KnownNat i, KnownNat i', KnownNat o)\n    => d\n    -> MWC.Gen (PrimState m)\n    -> LRp i o\n    -> m (LRp i' o)\nreshapeLRpInput d g (LRp \u03b1 \u03b2) =\n    LRp \u03b1 <$> reshapeLCols d g \u03b2\n\n-- | Reshape an 'LRp' to return more or less outputs  If more, new\n-- parameters are initialized randomly according to the given distribution.\nreshapeLRpOutput\n    :: (ContGen d, PrimMonad m, KnownNat i, KnownNat o, KnownNat o')\n    => d\n    -> MWC.Gen (PrimState m)\n    -> LRp i o\n    -> m (LRp i o')\nreshapeLRpOutput d g (LRp \u03b1 \u03b2) =\n    LRp <$> reshapeR d g \u03b1\n        <*> reshapeLRows d g \u03b2\n\nlinReg\n    :: (KnownNat i, KnownNat o)\n    => Model ('Just (LRp i o)) 'Nothing (R i) (R o)\nlinReg = modelStatelessD (\\(PJust p) -> runLRp p)\n\nlogReg\n    :: (KnownNat i, KnownNat o)\n    => Model ('Just (LRp i o)) 'Nothing (R i) (R o)\nlogReg = funcD logistic <~ linReg\n\n-- | Adjust an 'LRp' to take extra inputs, initialized randomly.\n--\n-- Initial contributions to each output is randomized.\nexpandLRpInput\n    :: (PrimMonad m, ContGen d, KnownNat i, KnownNat j, KnownNat o)\n    => LRp i o\n    -> d\n    -> MWC.Gen (PrimState m)\n    -> m (LRp (i + j) o)\nexpandLRpInput LRp{..} d g = LRp _lrAlpha . (_lrBeta H.|||) <$> initialize d g\n\n-- | Adjust an 'LRp' to return extra ouputs, initialized randomly\nexpandLRpOutput\n    :: (PrimMonad m, ContGen d, KnownNat i, KnownNat o, KnownNat p)\n    => LRp i o\n    -> d\n    -> MWC.Gen (PrimState m)\n    -> m (LRp i (o + p))\nexpandLRpOutput LRp{..} d g = do\n    newAlpha <- initialize d g\n    newBeta  <- initialize d g\n    pure (LRp (_lrAlpha H.# newAlpha) (_lrBeta H.=== newBeta))\n\n-- | Premute (or remove) inputs\n--\n-- Removed inputs will simply have their contributions removed from each\n-- output.\npremuteLRpInput\n    :: (KnownNat i, KnownNat o)\n    => SV.Vector i' (Finite i)\n    -> LRp i o\n    -> LRp i' o\npremuteLRpInput is p = p { _lrBeta = colsL . fmap (\u03b2 `SV.index`) $ is }\n  where\n    \u03b2 = lCols (_lrBeta p)\n\n-- | Premute (or remove) outputs\npermuteLRpOutput\n    :: (KnownNat i, KnownNat o)\n    => SV.Vector o' (Finite o)\n    -> LRp i o\n    -> LRp i o'\npermuteLRpOutput is LRp{..} =\n    LRp { _lrAlpha = vecR . SVG.convert . fmap (\u03b1 `SVS.index`) $ is\n        , _lrBeta  = rowsL . fmap (\u03b2 `SV.index`) $ is\n        }\n  where\n    \u03b1 = rVec _lrAlpha\n    \u03b2 = lRows _lrBeta\n\n-- | 'ARIMA' parmaeters\ndata ARIMAp :: Nat -> Nat -> Type where\n    ARIMAp :: { _arimaPhi      :: !(R p)\n              , _arimaTheta    :: !(R q)\n              , _arimaConstant :: !Double\n              }\n           -> ARIMAp p q\n  deriving stock     (Generic, Typeable, Show)\n  deriving anyclass  (NFData, Linear Double, Metric Double, Initialize, Backprop, Bi.Binary)\n\nderiving via (GNum (ARIMAp p q)) instance Num (ARIMAp p q)\nderiving via (GNum (ARIMAp p q)) instance Fractional (ARIMAp p q)\nderiving via (GNum (ARIMAp p q)) instance Floating (ARIMAp p q)\n\nmakeLenses ''ARIMAp\n\n-- | 'ARIMA' state\ndata ARIMAs :: Nat -> Nat -> Nat -> Type where\n    ARIMAs :: { _arimaYPred :: !Double\n              , _arimaYHist :: !(R (p + d))\n              , _arimaEHist :: !(R q)\n              }\n          -> ARIMAs p d q\n  deriving stock     (Generic, Typeable, Show)\n  deriving anyclass  (NFData, Linear Double, Metric Double, Initialize, Backprop, Bi.Binary)\n\nderiving via (NoRegularize (ARIMAs p d q)) instance Regularize (ARIMAs p d q)\nderiving via (GNum (ARIMAs p d q)) instance Num (ARIMAs p d q)\nderiving via (GNum (ARIMAs p d q)) instance Fractional (ARIMAs p d q)\nderiving via (GNum (ARIMAs p d q)) instance Floating (ARIMAs p d q)\n\nmakeLenses ''ARIMAs\n\narima\n    :: forall p d q. (KnownNat p, KnownNat d, KnownNat q)\n    => Model ('Just (ARIMAp p q)) ('Just (ARIMAs p d q)) Double Double\narima = modelD $ \\(PJust p) x (PJust s) ->\n    let d :: L p (p + d)\n        d = difference\n        e  = x - (s ^^. arimaYPred)\n        y  = (p ^^. arimaConstant)\n           + (p ^^. arimaPhi  ) <.> (constVar d #> (s ^^. arimaYHist))\n           + (p ^^. arimaTheta) <.> (s ^^. arimaEHist)\n        yHist' = case Proxy @1 %<=? Proxy @(p + d) of\n          LE Refl -> single y # constVar dropLast #> (s ^^. arimaYHist)\n          NLE _ _ -> 0\n        eHist' = case Proxy @1 %<=? Proxy @q of\n          LE Refl -> single e # constVar dropLast #> (s ^^. arimaEHist)\n          NLE _ _ -> 0\n        s' = isoVar3 ARIMAs (\\(ARIMAs pr yh eh) -> (pr,yh,eh))\n                y\n                yHist'\n                eHist'\n    in  (y, PJust s')\n\nautoregressive\n    :: KnownNat p\n    => Model ('Just (ARIMAp p 0)) ('Just (ARIMAs p 0 0)) Double Double\nautoregressive = arima\n\nmovingAverage\n    :: KnownNat q\n    => Model ('Just (ARIMAp 0 q)) ('Just (ARIMAs 0 0 q)) Double Double\nmovingAverage = arima\n\narma\n    :: (KnownNat p, KnownNat q)\n    => Model ('Just (ARIMAp p q)) ('Just (ARIMAs p 0 q)) Double Double\narma = arima\n\nmonosquare :: forall n. (n <=? (n ^ 2)) :~: 'True\nmonosquare = unsafeCoerce Refl\n\ndropLast :: forall n. (KnownNat n, 1 <= n) => L (n - 1) n\ndropLast = case monosquare @n of\n    Refl -> vecL . SVS.generate $ \\ij ->\n      let i :: Finite n\n          j :: Finite (n - 1)\n          (i, j) = separateProduct ij\n      in  if fromIntegral @_ @Int i == fromIntegral j\n            then 1\n            else 0\n\nsingle :: Reifies s W => BVar s Double -> BVar s (R 1)\nsingle = konst\n\ndifference'\n    :: Int                  -- ^ initial\n    -> Int                  -- ^ target\n    -> HU.Matrix Double     -- ^ target x initial\ndifference' n m = foldl' go (HU.ident m) [m + 1 .. n]\n  where\n    go x k = x HU.<> d k\n    d k = HU.build (k-1, k) $ \\i j ->\n        case round @_ @Int (j - i) of\n          0 -> 1\n          1 -> -1\n          _ -> 0\n\ndifference :: forall n m. (KnownNat n, KnownNat m) => L n (n + m)\ndifference = fromJust . H.create $ difference' (n + m) n\n  where\n    n = fromIntegral $ natVal (Proxy @n)\n    m = fromIntegral $ natVal (Proxy @m)\n\ninstance (PrimMonad m, KnownNat p, KnownNat q) => Mutable m (ARIMAp p q) where\n    type Ref m (ARIMAp p q) = GRef m (ARIMAp p q)\n    thawRef = gThawRef\n    freezeRef = gFreezeRef\n    copyRef = gCopyRef\n\ninstance (PrimMonad m, KnownNat p, KnownNat d, KnownNat q) => Mutable m (ARIMAs p d q) where\n    type Ref m (ARIMAs p d q) = GRef m (ARIMAs p d q)\n    thawRef = gThawRef\n    freezeRef = gFreezeRef\n    copyRef = gCopyRef\n\ninstance (KnownNat p, KnownNat q, PrimMonad m)  => LinearInPlace m Double (ARIMAp p q)\ninstance (KnownNat p, KnownNat d, KnownNat q, PrimMonad m) => LinearInPlace m Double (ARIMAs p d q)\n\ninstance (KnownNat p, KnownNat q) => Regularize (ARIMAp p q) where\n    rnorm_1 ARIMAp{..} = rnorm_1 _arimaPhi + rnorm_1 _arimaTheta\n    rnorm_2 ARIMAp{..} = rnorm_2 _arimaPhi + rnorm_2 _arimaTheta\n    lasso r ARIMAp{..} = ARIMAp { _arimaPhi      = lasso r _arimaPhi\n                                , _arimaTheta    = lasso r _arimaTheta\n                                , _arimaConstant = 0\n                                }\n    ridge r ARIMAp{..} = ARIMAp { _arimaPhi      = ridge r _arimaPhi\n                                , _arimaTheta    = ridge r _arimaTheta\n                                , _arimaConstant = 0\n                                }\n\ninstance (KnownNat p, KnownNat q, PrimMonad m) => Learnable m (ARIMAp p q)\ninstance (KnownNat p, KnownNat d, KnownNat q, PrimMonad m) => Learnable m (ARIMAs p d q)\n", "meta": {"hexsha": "bcede534e105433d716a2890d4444ede161a7350", "size": 12204, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Backprop/Learn/Model/Regression.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "src/Backprop/Learn/Model/Regression.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "src/Backprop/Learn/Model/Regression.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 36.7590361446, "max_line_length": 99, "alphanum_fraction": 0.5680924287, "num_tokens": 3594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.473484601436801}}
{"text": "{-# LANGUAGE BangPatterns  #-}\n{-# LANGUAGE DeriveGeneric #-}\nmodule FokkerPlanck.BrownianMotion\n  ( Particle(..)\n  , generatePath\n  , moveParticle\n  , thetaPlus\n  , scalePlus\n  , generateRandomNumber\n  , generatePath'\n  ) where\n\nimport           Control.DeepSeq\nimport           Control.Monad\nimport           Data.DList                          as DL\nimport           Data.Ix\nimport           Data.List                           as L\nimport           GHC.Generics                        (Generic)\nimport           Statistics.Distribution\nimport           Statistics.Distribution.Exponential\nimport           Statistics.Distribution.Normal\nimport           Statistics.Distribution.Uniform\nimport           System.Random.MWC\nimport           Text.Printf\nimport           Utils.Distribution\n\ndata Particle =\n  Particle {-# UNPACK #-}!Double -- \\phi\n           {-# UNPACK #-}!Double -- \\rho\n           {-# UNPACK #-}!Double -- \\theta\n           {-# UNPACK #-}!Double -- r\n           {-# UNPACK #-}!Double -- weight\n  deriving (Show,Generic)\n\ninstance NFData Particle\n\n{-# INLINE getParticleRho #-}\ngetParticleRho :: Particle -> Double\ngetParticleRho (Particle _ rho _ _ _ ) = rho\n\n\nthetaCheck :: Double -> Double\nthetaCheck theta =\n  if theta < -pi\n    then thetaCheck (theta + 2 * pi)\n    else if theta >= pi\n           then thetaCheck (theta - 2 * pi)\n           else theta\n\n{-# INLINE scaleCheck #-}\nscaleCheck :: Double -> Double -> Double\nscaleCheck maxScale scale =\n  if scale >= (1 / maxScale) && scale <= maxScale\n    then scale\n    else error\n           (printf\n              \"scaleCheck: %.2f is out of boundary (0,%.2f)\\n\"\n              scale\n              maxScale)\n\n{-# INLINE thetaPlus #-}\nthetaPlus :: Double -> Double -> Double\nthetaPlus !x !y =\n  let z = x + y\n   in thetaCheck z\n\n{-# INLINE scalePlus #-}\nscalePlus :: Double -> Double -> Double\nscalePlus x delta = x * exp delta\n\n{-# INLINE scalePlusPeriodic #-}\nscalePlusPeriodic :: Double -> Double -> Double -> Double\nscalePlusPeriodic !logMaxScale !delta !x\n  | z >= m = exp (z - 2 * m)\n  | z < -m = exp (2 * m + z)\n  | otherwise = exp z\n  where\n    !m = logMaxScale\n    !z = log x + delta\n\n{-# INLINE rhoCutoff #-}\nrhoCutoff :: Double -> Double\nrhoCutoff !rho =\n  if rho < 0\n    then 0\n    else rho\n\n{-# INLINE generateRandomNumber #-}\ngenerateRandomNumber ::\n     (Distribution d, ContGen d) => GenIO -> Maybe d -> IO Double\ngenerateRandomNumber !gen dist =\n  case dist of\n    Nothing -> return 0\n    Just d  -> genContVar d gen\n\n{-# INLINE moveParticle #-}\nmoveParticle :: Double -> Particle -> Particle\nmoveParticle deltaT (Particle phi rho theta r0 v) =\n  let !r = r0 * deltaT\n      !x = theta - phi\n      !cosX = cos x\n      !newPhi = phi `thetaPlus` atan2 (r * sin x) (rho + r * cosX)\n      !newRho = sqrt (rho * rho + r * r + 2 * r * rho * cosX)\n  in Particle newPhi newRho theta r0 v\n\n{-# INLINE diffuseParticle #-}\ndiffuseParticle :: Double -> Double -> Double -> Particle -> Particle\ndiffuseParticle !deltaTheta !deltaScale maxScale (Particle phi rho theta r v) =\n  Particle\n    phi\n    rho\n    (theta `thetaPlus` deltaTheta)\n    (r `scalePlus` deltaScale)\n    v\n\nbrownianMotion ::\n     (Distribution d1, ContGen d1, Distribution d2, ContGen d2, Distribution d3)\n  => GenIO\n  -> Maybe d1\n  -> Maybe d2\n  -> Maybe d3\n  -> Double\n  -> Double\n  -> Double\n  -> Double\n  -> Double\n  -> Particle\n  -> DList Particle\n  -> IO (DList Particle)\nbrownianMotion randomGen thetaDist scaleDist poissonDist deltaT maxRho maxR tao stdR2 particle xs = do\n  deltaTheta <- generateRandomNumber randomGen thetaDist\n  deltaScale <- generateRandomNumber randomGen scaleDist\n  let newParticle@(Particle phi rho theta r v) = moveParticle deltaT particle\n      ys =\n        if r <= maxR && r > 1 / maxR && rho <= maxRho && rho >= 1 / maxRho\n          then DL.cons\n                 (Particle phi rho theta r (1 - gaussian2DPolar rho stdR2))\n                 xs\n          else xs\n  t <- genContVar (uniformDistr 0 1) randomGen :: IO Double\n  if t > exp (1 / (-tao))\n    then return ys\n    else brownianMotion\n           randomGen\n           thetaDist\n           scaleDist\n           poissonDist\n           deltaT\n           maxRho\n           maxR\n           tao\n           stdR2\n           (diffuseParticle deltaTheta deltaScale maxR newParticle)\n           ys\n\n{-# INLINE generatePath #-}\ngeneratePath ::\n     (Distribution d1, ContGen d1, Distribution d2, ContGen d2, Distribution d3)\n  => Maybe d1\n  -> Maybe d2\n  -> Maybe d3\n  -> Double\n  -> Double\n  -> Double\n  -> Double\n  -> Double\n  -> GenIO\n  -> IO (DList Particle)\ngeneratePath thetaDist scaleDist poissonDist maxRho maxR tao deltaT stdR2 randomGen =\n  brownianMotion\n    randomGen\n    thetaDist\n    scaleDist\n    poissonDist\n    deltaT\n    maxRho\n    maxR\n    tao\n    stdR2\n    (Particle 0 1 0 1 1)\n    DL.empty\n\n{-# INLINE moveParticle' #-}\nmoveParticle' ::  Particle -> Particle\nmoveParticle' (Particle phi rho theta r v) =\n  let !x = theta - phi\n      !cosX = cos x\n      !newPhi = phi `thetaPlus` atan2 (r * sin x) (rho + r * cosX)\n      !newRho = sqrt (rho * rho + r * r + 2 * r * rho * cosX)\n   in Particle newPhi newRho theta r v\n\n{-# INLINE diffuseParticle' #-}\ndiffuseParticle' :: (Distribution d, ContGen d)\n  => GenIO ->  Double -> Maybe d -> Double -> Particle -> IO Particle\ndiffuseParticle' randomGen thetaSigma scaleDist deltaT (Particle phi rho theta r v) = do\n  deltaScale <- generateRandomNumber randomGen scaleDist\n  let r1 = r `scalePlus` deltaScale\n  deltaTheta <-\n    genContVar (normalDistr 0 (thetaSigma * sqrt (r1 * deltaT))) randomGen\n  return $ Particle phi rho (theta `thetaPlus` deltaTheta) r1 v\n\nbrownianMotion' ::\n     (Distribution d, ContGen d)\n  => GenIO\n  -> Double\n  -> Maybe d\n  -> Double\n  -> Double\n  -> Double\n  -> Double\n  -> Double\n  -> Double\n  -> Particle\n  -> DList Particle\n  -> IO (DList Particle)\nbrownianMotion' randomGen thetaSigma scaleDist poissonLambda deltaT maxRho maxR tao stdR2 particle xs = do\n  let newParticle@(Particle phi rho theta r v) = moveParticle deltaT particle\n      ys =\n        if r <= maxR && r > 1 / maxR && rho <= maxRho && rho >= 1 / maxRho\n          then DL.cons (Particle phi rho theta r (1 - gaussian2DPolar rho stdR2)) xs\n          else xs\n  t <- genContVar (uniformDistr 0 1) randomGen :: IO Double\n  if t > exp (1 / (-tao / (r * deltaT)))\n    then return ys\n    else do\n      diffusedParticle <-\n        diffuseParticle' randomGen thetaSigma scaleDist deltaT newParticle\n      brownianMotion'\n        randomGen\n        thetaSigma\n        scaleDist\n        poissonLambda\n        deltaT\n        maxRho\n        maxR\n        tao\n        stdR2\n        diffusedParticle\n        ys\n\n\n{-# INLINE generatePath' #-}\ngeneratePath' ::\n     (Distribution d, ContGen d)\n  => Double\n  -> Maybe d\n  -> Double\n  -> Double\n  -> Double\n  -> Double\n  -> Double\n  -> Double\n  -> GenIO\n  -> IO (DList Particle)\ngeneratePath' thetaSigma scaleDist poissonLambda maxRho maxR tao deltaT stdR2 randomGen = do\n  brownianMotion'\n    randomGen\n    thetaSigma\n    scaleDist\n    poissonLambda\n    deltaT\n    maxRho\n    maxR\n    tao\n    stdR2\n    (Particle 0 1 0 1 1)\n    DL.empty\n", "meta": {"hexsha": "aa7488ae896bf97daf78815e3204ca9035a5b61e", "size": 7144, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FokkerPlanck/BrownianMotion.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FokkerPlanck/BrownianMotion.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/FokkerPlanck/BrownianMotion.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 26.6567164179, "max_line_length": 106, "alphanum_fraction": 0.6129619261, "num_tokens": 2019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.473484596353852}}
{"text": "module STCR2Z2T0S0EndModal where\n\nimport           Data.Array.Repa         as R\nimport           Data.Binary             (decodeFile)\nimport           Data.Complex\nimport           Data.List               as L\nimport           DFT.Plan\nimport           FokkerPlanck.MonteCarlo\nimport           FokkerPlanck.Pinwheel\nimport           Image.IO\nimport           Image.Transform         (normalizeValueRange)\nimport           STC\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Text.Printf\nimport           Types\nimport           Utils.Array\n\nmain = do\n  args@(numPointStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:taoStr:numTrailStr:maxTrailStr:theta0FreqsStr:thetaFreqsStr:scale0FreqsStr:scaleFreqsStr:histFilePath:numIterationStr:writeSourceFlagStr:cutoffRadiusEndPointStr:cutoffRadiusStr:reversalFactorStr:cStr:numThreadStr:_) <-\n    getArgs\n  print args\n  let numPoint = read numPointStr :: Int\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      maxScale = read maxScaleStr :: Double\n      tao = read taoStr :: Double\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      theta0Freq = read theta0FreqsStr :: Double\n      theta0Freqs = [-theta0Freq .. theta0Freq]\n      thetaFreq = read thetaFreqsStr :: Double\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      scale0Freq = read scale0FreqsStr :: Double\n      scaleFreq = read scaleFreqsStr :: Double\n      scale0Freqs = [-scale0Freq .. scale0Freq]\n      scaleFreqs = [-scaleFreq .. scaleFreq]\n      numIteration = read numIterationStr :: Int\n      writeSourceFlag = read writeSourceFlagStr :: Bool\n      cutoffRadiusEndPoint = read cutoffRadiusEndPointStr :: Int\n      cutoffRadius = read cutoffRadiusStr :: Int\n      reversalFactor = read reversalFactorStr :: Double\n      numThread = read numThreadStr :: Int\n      folderPath = \"output/test/STCR2Z2T0S0EndModal.noindex\"\n      a = 20\n      b = 7\n      c = read cStr :: Int\n      endPointFilePath =\n        folderPath </>\n        (printf\n           \"EndPoint_%d_%d_%d_%d_%d_%d_%.2f_%.2f_%d_%d_%d_%f.dat\"\n           numPoint\n           (round thetaFreq :: Int)\n           (round scaleFreq :: Int)\n           (round maxScale :: Int)\n           (round tao :: Int)\n           cutoffRadiusEndPoint\n           thetaSigma\n           scaleSigma\n           a\n           b\n           c\n           reversalFactor)\n  createDirectoryIfMissing True folderPath\n  flag <- doesFileExist histFilePath\n  radialArr <-\n    if flag\n      then R.map magnitude . getNormalizedHistogramArr <$>\n           decodeFile histFilePath\n      else do\n        putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n        solveMonteCarloR2Z2T0S0Radial\n          numThread\n          numTrail\n          maxTrail\n          numPoint\n          numPoint\n          thetaSigma\n          scaleSigma\n          maxScale\n          tao\n          theta0Freqs\n          thetaFreqs\n          scale0Freqs\n          scaleFreqs\n          histFilePath\n          (emptyHistogram\n             [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n             , L.length scale0Freqs\n             , L.length theta0Freqs\n             , L.length scaleFreqs\n             , L.length thetaFreqs\n             ]\n             0)\n  arrR2Z2T0S0 <-\n    computeUnboxedP $\n    computeR2Z2T0S0ArrayRadial\n      (cutoff cutoffRadius radialArr)\n      numPoint\n      numPoint\n      1\n      maxScale\n      thetaFreqs\n      scaleFreqs\n      theta0Freqs\n      scale0Freqs\n  arrR2Z2T0S0EndPoint <-\n    computeUnboxedP $\n    computeR2Z2T0S0ArrayRadial\n      (cutoff cutoffRadiusEndPoint radialArr)\n      numPoint\n      numPoint\n      1\n      maxScale\n      thetaFreqs\n      scaleFreqs\n      theta0Freqs\n      scale0Freqs\n  plan <- makeR2Z2T0S0Plan emptyPlan arrR2Z2T0S0\n  let a' = round $ (fromIntegral a) * (sqrt 2) / 2\n      b' = round $ (fromIntegral b) * (sqrt 2) / 2\n      c' = round $ (fromIntegral c) * (sqrt 2) / 2\n      xs =\n        ([R2S1RPPoint (i, i, 0, 0) | i <- [a',a' + b' .. c']] L.++\n         [R2S1RPPoint (i, -i, 0, 0) | i <- [-a',-(a' + b') .. -c']] L.++\n         [R2S1RPPoint (i, i, 0, 0) | i <- [-a',-(a' + b') .. -c']] L.++\n         [R2S1RPPoint (i, -i, 0, 0) | i <- [a',a' + b' .. c']] L.++\n         [R2S1RPPoint (i, 0, 0, 0) | i <- [a,a + b .. c]] L.++\n         [R2S1RPPoint (0, i, 0, 0) | i <- [-a,-(a + b) .. -c]] L.++\n         [R2S1RPPoint (i, 0, 0, 0) | i <- [-a,-(a + b) .. -c]] L.++\n         [R2S1RPPoint (0, i, 0, 0) | i <- [a,a + b .. c]])\n      bias = computeBiasR2T0S0' numPoint numPoint theta0Freqs scale0Freqs xs\n      eigenVec =\n        computeInitialEigenVectorR2T0S0\n          numPoint\n          numPoint\n          theta0Freqs\n          scale0Freqs\n          thetaFreqs\n          scaleFreqs\n          xs\n  powerMethodR2Z2T0S0EndModal\n    plan\n    folderPath\n    numPoint\n    numPoint\n    numOrientation\n    thetaFreqs\n    theta0Freqs\n    numScale\n    scaleFreqs\n    scale0Freqs\n    arrR2Z2T0S0EndPoint\n    arrR2Z2T0S0\n    numIteration\n    writeSourceFlag\n    (printf\n       \"_%d_%d_%d_%d_%d_%d_%.2f_%.2f_%f\"\n       numPoint\n       (round thetaFreq :: Int)\n       (round scaleFreq :: Int)\n       (round maxScale :: Int)\n       (round tao :: Int)\n       cutoffRadiusEndPoint\n       thetaSigma\n       scaleSigma\n       reversalFactor)\n    reversalFactor\n    bias\n    eigenVec\n", "meta": {"hexsha": "57b5d22fbfab69bb8e7480fd5387fc0004666ffa", "size": 5535, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2Z2T0S0EndModal/STCR2Z2T0S0EndModal.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/STCR2Z2T0S0EndModal/STCR2Z2T0S0EndModal.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/STCR2Z2T0S0EndModal/STCR2Z2T0S0EndModal.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 31.8103448276, "max_line_length": 308, "alphanum_fraction": 0.5837398374, "num_tokens": 1666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4734693991034077}}
{"text": "{-# LANGUAGE DeriveDataTypeable    #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE KindSignatures        #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PatternSynonyms       #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE RecordWildCards       #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeInType            #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-# LANGUAGE ViewPatterns          #-}\n\nmodule Backprop.Learn.Model.Stochastic (\n    DO(..)\n  , StochFunc(..)\n  , FixedStochFunc, pattern FSF, _fsfRunDeterm, _fsfRunStoch\n  , rreLU\n  , injectNoise, applyNoise\n  , injectNoiseR, applyNoiseR\n  ) where\n\nimport           Backprop.Learn.Model.Class\nimport           Backprop.Learn.Model.Function\nimport           Control.Monad.Primitive\nimport           Data.Bool\nimport           Data.Kind\nimport           Data.Typeable\nimport           GHC.TypeNats\nimport           Numeric.Backprop\nimport           Numeric.LinearAlgebra.Static.Backprop\nimport           Numeric.LinearAlgebra.Static.Vector\nimport qualified Data.Vector.Storable.Sized            as SVS\nimport qualified Statistics.Distribution               as Stat\nimport qualified System.Random.MWC                     as MWC\nimport qualified System.Random.MWC.Distributions       as MWC\n\n-- | Dropout layer.  Parameterized by dropout percentage (should be between\n-- 0 and 1).\n--\n-- 0 corresponds to no dropout, 1 corresponds to complete dropout of all\n-- nodes every time.\nnewtype DO (n :: Nat) = DO { _doRate :: Double }\n  deriving (Typeable)\n\ninstance KnownNat n => Learn (R n) (R n) (DO n) where\n    runLearn (DO r) _ = stateless (constVar (realToFrac (1-r)) *)\n    runLearnStoch (DO r) g _ = statelessM $ \\x ->\n        (x *) . constVar . vecR <$> SVS.replicateM (mask g)\n      where\n        mask = fmap (bool 1 0) . MWC.bernoulli r\n\n-- | Represents a random-valued function, with a possible trainable\n-- parameter.\n--\n-- Requires both a \"deterministic\" and a \"stochastic\" mode.  The\n-- deterministic mode ideally should approximate some mean of the\n-- stochastic mode.\ndata StochFunc :: Maybe Type -> Type -> Type -> Type where\n    SF :: { _sfRunDeterm :: forall s. Reifies s W => Mayb (BVar s) p -> BVar s a -> BVar s b\n          , _sfRunStoch\n              :: forall m s. (PrimMonad m, Reifies s W)\n              => MWC.Gen (PrimState m)\n              -> Mayb (BVar s) p\n              -> BVar s a\n              -> m (BVar s b)\n          }\n       -> StochFunc p a b\n  deriving (Typeable)\n\ninstance Learn a b (StochFunc p a b) where\n    type LParamMaybe (StochFunc p a b) = p\n    type LStateMaybe (StochFunc p a b) = 'Nothing\n\n    runLearn SF{..} = stateless . _sfRunDeterm\n    runLearnStoch SF{..} g = statelessM . _sfRunStoch g\n\n-- | Convenient alias for a 'StochFunc' (random-valued function with both\n-- deterministic and stochastic modes) with no trained parameters.\ntype FixedStochFunc = StochFunc 'Nothing\n\n-- | Construct a 'FixedStochFunc'\npattern FSF :: (forall s. Reifies s W => BVar s a -> BVar s b)\n            -> (forall m s. (PrimMonad m, Reifies s W) => MWC.Gen (PrimState m) -> BVar s a -> m (BVar s b))\n            -> FixedStochFunc a b\npattern FSF { _fsfRunDeterm, _fsfRunStoch } <- (getFSF->(getWD->_fsfRunDeterm,getWS->_fsfRunStoch))\n  where\n    FSF d s = SF { _sfRunDeterm = const d\n                 , _sfRunStoch  = const . s\n                 }\n{-# COMPLETE FSF #-}\n\nnewtype WrapDeterm a b = WD { getWD :: forall s. Reifies s W => BVar s a -> BVar s b }\nnewtype WrapStoch  a b = WS { getWS :: forall m s. (PrimMonad m, Reifies s W) => MWC.Gen (PrimState m) -> BVar s a -> m (BVar s b) }\n\ngetFSF :: FixedStochFunc a b -> (WrapDeterm a b, WrapStoch a b)\ngetFSF SF{..} = ( WD (_sfRunDeterm N_)\n                , WS (`_sfRunStoch` N_)\n                )\n\n-- | Random leaky rectified linear unit\nrreLU\n    :: (Stat.ContGen d, Stat.Mean d, KnownNat n)\n    => d\n    -> FixedStochFunc (R n) (R n)\nrreLU d = FSF { _fsfRunDeterm = vmap' (preLU v)\n              , _fsfRunStoch  = \\g x -> do\n                  \u03b1 <- vecR <$> SVS.replicateM (Stat.genContVar d g)\n                  pure (zipWithVector preLU (constVar \u03b1) x)\n              }\n  where\n    v :: BVar s Double\n    v = constVar (Stat.mean d)\n\n-- | Inject random noise.  Usually used between neural network layers, or\n-- at the very beginning to pre-process input.\n--\n-- In non-stochastic mode, this adds the mean of the distribution.\ninjectNoise\n    :: (Stat.ContGen d, Stat.Mean d, Fractional a)\n    => d\n    -> FixedStochFunc a a\ninjectNoise d = FSF { _fsfRunDeterm = (realToFrac (Stat.mean d) +)\n                    , _fsfRunStoch  = \\g x -> do\n                        e <- Stat.genContVar d g\n                        pure (realToFrac e + x)\n                    }\n\n\n-- | 'injectNoise' lifted to 'R'\ninjectNoiseR\n    :: (Stat.ContGen d, Stat.Mean d, KnownNat n)\n    => d\n    -> FixedStochFunc (R n) (R n)\ninjectNoiseR d = FSF { _fsfRunDeterm = (realToFrac (Stat.mean d) +)\n                     , _fsfRunStoch  = \\g x -> do\n                         e <- vecR <$> SVS.replicateM (Stat.genContVar d g)\n                         pure (constVar e + x)\n                     }\n\n-- | Multply by random noise.  Can be used to implement dropout-like\n-- behavior.\n--\n-- In non-stochastic mode, this scales by the mean of the distribution.\napplyNoise\n    :: (Stat.ContGen d, Stat.Mean d, Fractional a)\n    => d\n    -> FixedStochFunc a a\napplyNoise d = FSF { _fsfRunDeterm = (realToFrac (Stat.mean d) *)\n                   , _fsfRunStoch  = \\g x -> do\n                       e <- Stat.genContVar d g\n                       pure (realToFrac e * x)\n                   }\n\n-- | 'applyNoise' lifted to 'R'\napplyNoiseR\n    :: (Stat.ContGen d, Stat.Mean d, KnownNat n)\n    => d\n    -> FixedStochFunc (R n) (R n)\napplyNoiseR d = FSF { _fsfRunDeterm = (realToFrac (Stat.mean d) *)\n                   , _fsfRunStoch  = \\g x -> do\n                       e <- vecR <$> SVS.replicateM (Stat.genContVar d g)\n                       pure (constVar e * x)\n                   }\n", "meta": {"hexsha": "0b832217a9cd38f08a66e4d3651572c6de0a9272", "size": 6088, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "old2/src/Backprop/Learn/Model/Stochastic.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "old2/src/Backprop/Learn/Model/Stochastic.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "old2/src/Backprop/Learn/Model/Stochastic.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 36.6746987952, "max_line_length": 132, "alphanum_fraction": 0.5832785808, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.47346939704204527}}
{"text": "module NN.NeuralNetworkTest\n  (\n    testsNeuralNetwork\n  ) where\n\nimport Test.HUnit\nimport AI.HNN.FF.Network\nimport Numeric.LinearAlgebra.HMatrix hiding (corr)\n\nimport NUtil\nimport NN.NeuralNetwork\nimport qualified Data.Map.Strict as Map\n\nnnVars :: Vars\nnnVars = Map.fromList [(\"numberInputs\", 2)\n                      ,(\"numberHidden\", 2)\n                      ,(\"numberOutputs\", 1)\n                      ,(\"timesToTrain\", 3)\n                      ,(\"learningRate\", 0.8)\n                      ,(\"sigmoidOrTanh\", 0)]\n\n\nsamples :: Samples Double\nsamples = [ fromList [0, 0] --> fromList [0]\n          , fromList [0, 1] --> fromList [1]\n          , fromList [1, 0] --> fromList [1]\n          , fromList [1, 1] --> fromList [0] \n          ]\n\nexpectedOutputVals :: [Double]\nexpectedOutputVals = [0,1,1,0]\n          \ntestsNeuralNetwork :: Test\ntestsNeuralNetwork = TestList [ TestLabel \"label\" testsLabel]\n\ntestsLabel :: Test\ntestsLabel = TestList [ TestLabel \"test1\" testCreate\n                      , TestLabel \"test2\" testGet\n                      , TestLabel \"test3\" testTrainV]\n\ntestCreate :: Test\ntestCreate = TestCase (do\n                          net <- create nnVars :: IO Net\n                          let smartNet = trainNTimes 1500 0.8 tanh tanh' (_network net) samples\n--                              outputValues = map (get smartNet . fst) samples\n                              outputValues = convert1 $ map (output smartNet tanh . fst) samples\n                          assertEqual \"testCreate\"\n                            True\n                            (floatVectorCompare outputValues expectedOutputVals 0.2))\n\ntestGet :: Test\ntestGet = TestCase (do\n                       net <- create nnVars :: IO Net\n                       let smartNet = trainNTimes 1000 0.8 tanh tanh' (_network net) samples\n                           outputValues = convert1 $ map (get (Net smartNet nnVars) . fst) samples\n                       assertEqual \"testGet\"\n                         True\n                         (floatVectorCompare outputValues expectedOutputVals 0.2))\n\ntestTrainV :: Test\ntestTrainV = TestCase (do\n                         net <- create nnVars :: IO Net\n                         let smartNet = repeatNet trainV net samples 1000\n                             outputValues = convert1 $ map (get smartNet . fst) samples\n                         assertEqual \"testTrainV\"\n                           True\n                           (floatVectorCompare outputValues expectedOutputVals 0.2))\n\n                         \nconvert1 :: [Vector Double] -> [Double]\nconvert1 = map (! 0)\n\nfloatVectorCompare :: [Double] -> [Double] -> Double -> Bool\nfloatVectorCompare a b tol = foldr (&&) True $ zipWith (\\x y -> abs (x - y) < tol ) a b\n\nrepeatNet :: (n -> c -> n) -> n -> c -> Int -> n\nrepeatNet _ net _ 0 = net\nrepeatNet f net c n = let net' = f net c in repeatNet f net' c (n-1)\n", "meta": {"hexsha": "d88c5f0635f432a4ad10f1ec6ecb801ebfed8ff8", "size": 2882, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/NN/NeuralNetworkTest.hs", "max_stars_repo_name": "eklinkhammer/neural-algorithms", "max_stars_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/NN/NeuralNetworkTest.hs", "max_issues_repo_name": "eklinkhammer/neural-algorithms", "max_issues_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/NN/NeuralNetworkTest.hs", "max_forks_repo_name": "eklinkhammer/neural-algorithms", "max_forks_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4810126582, "max_line_length": 98, "alphanum_fraction": 0.534351145, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6442251064863698, "lm_q1q2_score": 0.4729382378859822}}
{"text": "module Parser where\r\nimport Data.Binary\r\nimport Data.Binary.Get\r\nimport qualified Data.ByteString.Lazy as BS\r\nimport Codec.Compression.GZip (decompress)\r\nimport Control.Monad\r\nimport Numeric.LinearAlgebra\r\nimport Numeric.LinearAlgebra.Devel\r\nimport qualified Data.Vector as V\r\nimport Control.Monad.ST\r\n\r\ntype Pixel = Word8\r\ntype Image = V.Vector (Matrix Float)\r\ntype Label = Vector Float\r\n\r\ndecodeImages :: Get [Image]\r\ndecodeImages = do\r\n    mc <- getWord32be\r\n    guard (mc == 0x00000803)\r\n    [d1,d2,d3] <- many 3 getWord32be\r\n    guard (d2 == 28 && d3 == 28)\r\n    many d1 pic\r\n  where\r\n    pic :: Get Image\r\n    pic = do\r\n      bs <- getByteString (28*28)\r\n      return . V.singleton . reshape 28 . toVecDouble . fromByteString $ bs\r\n    toVecDouble :: Vector Pixel -> Vector Float\r\n    -- mapVectorM requires the monad be strict\r\n    -- so Identity monad shall not be used\r\n    toVecDouble v = runST $ mapVectorM (return . (/255) . fromIntegral) v\r\n\r\ndecodeLabels :: Get [Label]\r\ndecodeLabels = do\r\n    mc <- getWord32be\r\n    guard (mc == 0x00000801)\r\n    d1 <- getWord32be\r\n    many d1 lbl\r\n  where\r\n    lbl :: Get Label\r\n    lbl = do\r\n      v <- fromIntegral <$> (get :: Get Word8)\r\n      return $ fromList (replicate v 0 ++ [1] ++ replicate (9-v) 0)\r\n\r\nmany :: (Integral n, Monad m) => n -> m a -> m [a]\r\nmany cnt dec = sequence (replicate (fromIntegral cnt) dec)\r\n\r\ntrainingData :: IO ([Image], [Label])\r\ntrainingData = do\r\n    s <- decompress <$> BS.readFile \"tdata/train-images-idx3-ubyte.gz\"\r\n    t <- decompress <$> BS.readFile \"tdata/train-labels-idx1-ubyte.gz\"\r\n    return (runGet decodeImages s, runGet decodeLabels t)\r\n\r\ntestData :: IO ([Image], [Label])\r\ntestData = do\r\n    s <- decompress <$> BS.readFile \"tdata/t10k-images-idx3-ubyte.gz\"\r\n    t <- decompress <$> BS.readFile \"tdata/t10k-labels-idx1-ubyte.gz\"\r\n    return (runGet decodeImages s, runGet decodeLabels t)\r\n", "meta": {"hexsha": "96975b8be0aa74a12c2a36d2e67a4b3f4ad19711", "size": 1889, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Backend-hmatrix/Example/MNIST/Parser.hs", "max_stars_repo_name": "pierric/neural-network", "max_stars_repo_head_hexsha": "406ecaf334cde9b10c9324e1f6c4b8663eae58d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-05-24T17:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T22:25:52.000Z", "max_issues_repo_path": "Backend-hmatrix/Example/MNIST/Parser.hs", "max_issues_repo_name": "pierric/neural-network", "max_issues_repo_head_hexsha": "406ecaf334cde9b10c9324e1f6c4b8663eae58d7", "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": "Backend-hmatrix/Example/MNIST/Parser.hs", "max_forks_repo_name": "pierric/neural-network", "max_forks_repo_head_hexsha": "406ecaf334cde9b10c9324e1f6c4b8663eae58d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-26T19:28:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T19:28:38.000Z", "avg_line_length": 32.0169491525, "max_line_length": 76, "alphanum_fraction": 0.6553732133, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.47293823287145664}}
{"text": "{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}\n{-# LANGUAGE FlexibleContexts #-}\nmodule Neural.Training\n  ( TrainingExample(..)\n  , TestingExample(..)\n  , train\n  , backpropagation\n  )\nwhere\n\nimport           Data.List.Split                ( chunksOf )\nimport           Foreign.Marshal.Utils          ( fromBool )\nimport           Control.Monad\nimport           Control.Monad.Writer\nimport           Control.Monad.State\nimport           Control.Monad.Random\nimport           System.Random\nimport           System.Random.Shuffle          ( shuffleM )\nimport           Numeric.LinearAlgebra\nimport           Text.Printf\nimport           GHC.Generics                   ( Generic )\nimport           Control.DeepSeq\n\nimport           Neural.Activation\nimport qualified Neural.Network                as N\nimport           Neural.Network          hiding ( weights\n                                                , biases\n                                                )\nimport           Neural.Layer                   ( Layer(..) )\n\n-- | A training example with an input and desired output in vector form.\ndata TrainingExample a = TrainingExample (Vector a) (Vector a)\n    deriving (Show, Generic, NFData)\n-- | A training example with an input and desired output as an index.\ndata TestingExample a  = TestingExample (Vector a) Int\n    deriving (Show, Generic, NFData)\n\n-- | The Hadamar product, elementwise multiplication.\n(\u2299) :: Num (Vector a) => Vector a -> Vector a -> Vector a\nu \u2299 v = u * v\n\n\n-- | Train a neural network over some amount of epochs given some training\n-- data and the size of the mini batches.\ntrain\n  :: (RandomGen g, Fractional a, Numeric a, Num (Vector a))\n  => ActivationFunction a      -- ^ The activation function\n  -> ActivationFunction' a     -- ^ The derivative of the activation function\n  -> a                         -- ^ The learning rate\n  -> [TrainingExample a]       -- ^ Training data\n  -> Maybe [TestingExample a]  -- ^ Optional testing data\n  -> Int                       -- ^ Number of ephocs\n  -> Int                       -- ^ Mini batch size\n  -> Network a                 -- ^ The untrained network\n  -> StateT g (Writer [String]) (Network a) -- ^ The trained network\ntrain \u03c3 \u03c3' \u03b7 trainingData testData epochs mbs net = do\n  let tellProgress epoch net' = case testData of\n        Nothing        -> tell [\"Epoch \" ++ show epoch ++ \" complete\"]\n        Just testData' -> tell\n          [printf \"Epoch %d: %d / %d (%.2f%%)\" epoch evaluation n p]\n         where\n          evaluation = evaluate \u03c3 testData' net'\n          n          = length testData'\n          p          = fromIntegral evaluation / fromIntegral n * 100 :: Double\n  let trainEpoch net' epoch = do\n        shuffledTrainingData <- state $ runRand $ shuffleM trainingData\n        let miniBatches = chunksOf mbs shuffledTrainingData\n        let tmb         = trainMiniBatch \u03c3 \u03c3' \u03b7\n        let trainedNet  = foldr tmb net' miniBatches\n        lift $ tellProgress epoch trainedNet\n        return trainedNet\n\n  foldM trainEpoch net [1 .. epochs]\n\n-- | Evaluate the network assuming the output is the index of the neuron with\n-- the highest activation.\nevaluate\n  :: (Numeric a, Num (Vector a))\n  => ActivationFunction a     -- ^ The activation function\n  -> [TestingExample a]       -- ^ Testing data\n  -> Network a                -- ^ The untrained network\n  -> Int                      -- ^ The amount of tests the network passed\nevaluate \u03c3 testData net =\n  let eval (TestingExample x y) = maxIndex (fst $ feedforward \u03c3 x net) == y\n      results = map eval testData\n  in  foldl (\\acc r -> acc + fromBool r) 0 results\n\n-- | Train a neural network for a mini batch of training data.\ntrainMiniBatch\n  :: (Fractional a, Numeric a, Num (Vector a))\n  => ActivationFunction a    -- ^ The activation function\n  -> ActivationFunction' a   -- ^ The derivative of the activation function\n  -> a                       -- ^ The learning rate\n  -> [TrainingExample a]     -- ^ A mini batch of training examples\n  -> Network a               -- ^ The untrained network\n  -> Network a               -- ^ The trained network\ntrainMiniBatch \u03c3 \u03c3' \u03b7 miniBatch net =\n  let bp example = backpropagation \u03c3 \u03c3' example net\n      \u03b7'     = \u03b7 / fromIntegral (length miniBatch)\n      ws0    = map (konst 0 . size) (N.weights net)\n      bs0    = map (konst 0 . size) (N.biases net)\n      deltas = map (unzip . bp) miniBatch\n      f (w, b) (dw, db) = (zipWith (+) w dw, zipWith (+) b db)\n      (nabla_w, nabla_b) = foldl f (ws0, bs0) deltas\n      ws = zipWith (\\w nw -> w - scale \u03b7' nw) (N.weights net) nabla_w\n      bs = zipWith (\\b nb -> b - scale \u03b7' nb) (N.biases net) nabla_b\n  in  newNetwork ws bs\n\n-- | Find the gradient of the cost function with respects to a networks\n-- weights and biases for one training example.\nbackpropagation\n  :: (Numeric a, Num (Vector a))\n  => ActivationFunction a    -- ^ The activation function\n  -> ActivationFunction' a   -- ^ The derivative of the activation function\n  -> TrainingExample a       -- ^ A single training example\n  -> Network a               -- ^ The neural network\n  -> [(Matrix a, Vector a)]  -- ^ The weight and bias gradient of the\n                               -- quadratic cost function\nbackpropagation \u03c3 \u03c3' (TrainingExample x y) net@(Network layers) =\n  let (as, zs) = unzip $ feedforwards \u03c3 x net   -- Feed forward and save the\n                                                -- results\n      as_      = x : as\n      nabla_aC = last as - y                    -- The gradient of the cost\n                                                -- function\n      calc_\u03b4 (l, z) \u03b4 = bp2 \u03c3' (weights l) \u03b4 z  -- A function that calculates\n                                                -- the error for the previous\n                                                -- layer\n      \u03b40      = bp1 \u03c3' nabla_aC (last zs)       -- The error of the last layer\n      \u03b4s      = scanr calc_\u03b4 \u03b40 (zip (tail layers) zs)\n      nabla_b = \u03b4s                              -- The 3rd equation\n      nabla_w = zipWith outer \u03b4s as_            -- The 4th equation\n  in  zip nabla_w nabla_b\n\n-- | The first equation of backpropagation.\nbp1\n  :: (Numeric a, Num (Vector a))\n  => ActivationFunction' a    -- ^ The derivative of the activation function\n  -> Vector a                 -- ^ The gradient of the cost function\n                                -- with respects to the activation\n  -> Vector a                 -- ^ The weighted input\n  -> Vector a                 -- ^ The error in the output layer\nbp1 _\u03c3' nabla_aC z = nabla_aC \u2299 \u03c3' z where \u03c3' = cmap _\u03c3'\n\n-- | The second equation of backpropagation.\nbp2\n  :: (Numeric a, Num (Vector a))\n  => ActivationFunction' a    -- ^ The derivative of the activation function\n  -> Matrix a                 -- ^ The weights of the next layer\n  -> Vector a                 -- ^ The error of the next layer\n  -> Vector a                 -- ^ The weighted input of the current layer\n  -> Vector a                 -- ^ The error of the current layer\nbp2 _\u03c3' w \u03b4 z = (tr' w #> \u03b4) \u2299 \u03c3' z where \u03c3' = cmap _\u03c3'\n\n", "meta": {"hexsha": "7803af582e3ac8dd96d34ee6248cfbc47d14505e", "size": 7040, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Neural/Training.hs", "max_stars_repo_name": "cornelius-sevald/nnhd", "max_stars_repo_head_hexsha": "b952830829d81f2ec8c4050128abceb1e6c15b48", "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/Neural/Training.hs", "max_issues_repo_name": "cornelius-sevald/nnhd", "max_issues_repo_head_hexsha": "b952830829d81f2ec8c4050128abceb1e6c15b48", "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/Neural/Training.hs", "max_forks_repo_name": "cornelius-sevald/nnhd", "max_forks_repo_head_hexsha": "b952830829d81f2ec8c4050128abceb1e6c15b48", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.7142857143, "max_line_length": 79, "alphanum_fraction": 0.5703125, "num_tokens": 1691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4728991724889683}}
{"text": "{-#Language TypeFamilies#-}\nmodule Morse where\n\nimport Stratification as S hiding (shiftCeil)\nimport Data.Matrix (Matrix(..))\nimport Control.Monad\nimport Control.Arrow\nimport SymbolicImage (\n    fromRad, toRad, fromCeil, toCeil, myNub, mySequence, (#=))\nimport Jac (jac, e)\nimport Data.Array as A\nimport Graph\nimport Data.Function\nimport Data.List as L\nimport Data.Map as M\nimport Data.IntMap as IM\nimport Data.Complex\nimport Data\nimport Point\nimport Data.Graph\n\n\nmorse :: F Point -> Imagination -> Int -> [(Double, Double, Int)]\nmorse fp im i = mrsElem <$> cyclics\n    ((shiftCeil d1 d2 fp #=) <$> ls)\n  where\n    mrsElem :: [(Ceil3, [(Ceil3, Double)])] -> (Double, Double, Int)\n    mrsElem a = (\n                         minOptZ gr  (minBazeCircuit gr),\n                negate $ minOptZ gr' (maxBazeCircuit gr'),\n                length a\n--                       maximum $ plat a,\n--                       minimum $ plat a\n            )\n        where\n            gr  = formGraph                    a\n            gr' = formGraph $ modifyIns negate a\n\n    (Stratification d1 d2 ls) = str fp im i\n\nplat :: [(Ceil3, [(Ceil3, Double)])] -> [Double]\nplat = concatMap (\\x -> snd <$> snd x)\n\n-- XXX \u0414\u0437\u0435\u043d\nmodifyIns :: (a -> b) -> [(c, [(d, a)])] -> [(c, [(d, b)])]\nmodifyIns f l = second (second f <$>) <$> l\n\n\n\n-- \u0432\u044b\u0434\u0435\u043b\u044f\u0435\u043c \u043e\u0431\u043b\u0430\u0441\u0442\u0438 \u0441\u0432\u044f\u0437\u043d\u043e\u0441\u0442\u0438\n--cyclics :: (Ord t0, Ord k0) => [(k0, t0, [(t0, b0)])] -> [[(k0, [(t0, b0)])]]\ncyclics g = M.toList <$> do\n    let g' = (\\(a, b, l) -> (a, b, L.filter (\\x -> fst x /= a) l)) <$> g\n    CyclicSCC a <- stronglyConnComp\n        [(a, b, fst <$> c) | (a, b, c) <- g']\n    return $ elect a $ M.fromList [(a, b) | (a, _, b) <- g']\n\n\n\nshiftCeil :: Diameter -> Diameter -> F Point -> Ceil3 -> [(Ceil3, Double)]\nshiftCeil d1 d2 fp (Ceil3 c l) = myNub $ do\n    let Point x y = fromCeil d1 c\n    ret <$> mySequence x d1\n        <*> mySequence y d1\n        <*> mySequence (rad d2 l) (pi/2/d2)\n  where\n    ret x' y' t' = (\n        func d1 d2 fp x' y' t',\n        log $ x $ abs $ toPoint $ jacobian fp x' y' * e t')\n\n\nelect :: Ord a => [a] -> F (Map a b)\nelect a m = M.intersection m $ M.fromList $ (\\a -> (a,a)) <$> a\n", "meta": {"hexsha": "ae75f643a01c97d7bfa146089850966ab8ead541", "size": 2139, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Morse.hs", "max_stars_repo_name": "vojiranto/dsa", "max_stars_repo_head_hexsha": "0071c1a00db6c1cfffeca6020e3a7cb22a1aeade", "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/Morse.hs", "max_issues_repo_name": "vojiranto/dsa", "max_issues_repo_head_hexsha": "0071c1a00db6c1cfffeca6020e3a7cb22a1aeade", "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/Morse.hs", "max_forks_repo_name": "vojiranto/dsa", "max_forks_repo_head_hexsha": "0071c1a00db6c1cfffeca6020e3a7cb22a1aeade", "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.9054054054, "max_line_length": 79, "alphanum_fraction": 0.5390369331, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4728991632145215}}
{"text": "module Neural.Util where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Parallel.Strategies\nimport Data.Array.ST\nimport Data.STRef\nimport Numeric.LinearAlgebra\nimport System.Random\n\n -- shamelessly nicked from https://wiki.haskell.org/Random_shuffle\n\nshuffle' :: [a] -> StdGen -> ([a],StdGen)\nshuffle' xs gen = runST (do\n        g <- newSTRef gen\n        let randomRST lohi = do\n              (a,s') <- liftM (randomR lohi) (readSTRef g)\n              writeSTRef g s'\n              return a\n        ar <- newArray n xs\n        xs' <- forM [1..n] $ \\i -> do\n                j <- randomRST (i,n)\n                vi <- readArray ar i\n                vj <- readArray ar j\n                writeArray ar j vi\n                return vj\n        gen' <- readSTRef g\n        return (xs',gen'))\n  where\n    n = length xs\n    newArray :: Int -> [a] -> ST s (STArray s Int a)\n    newArray n xs =  newListArray (1,n) xs\n\nshuffleIO :: [a] -> IO [a]\nshuffleIO xs = getStdRandom (shuffle' xs)\n\nparZipWith :: Strategy c -> (a -> b -> c) -> [a] -> [b] -> [c]\nparZipWith strat f x y = zipWith f x y `using` parList strat\n\nparZipWith3 :: Strategy d -> (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]\nparZipWith3 strat f x y z = zipWith3 f x y z `using` parList strat\n\nfullyFlatten :: [Matrix Double] -> Vector Double\nfullyFlatten = vjoin . (parMap rdeepseq flatten)\n", "meta": {"hexsha": "de18cee87f6481ce389f2ada3b7c703120c49ec1", "size": 1358, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Neural/Util.hs", "max_stars_repo_name": "dlhawkins94/jinko-no", "max_stars_repo_head_hexsha": "45fc9fcabc1d3699d9022bbffb5264aaee64baf4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Neural/Util.hs", "max_issues_repo_name": "dlhawkins94/jinko-no", "max_issues_repo_head_hexsha": "45fc9fcabc1d3699d9022bbffb5264aaee64baf4", "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/Neural/Util.hs", "max_forks_repo_name": "dlhawkins94/jinko-no", "max_forks_repo_head_hexsha": "45fc9fcabc1d3699d9022bbffb5264aaee64baf4", "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": 30.1777777778, "max_line_length": 75, "alphanum_fraction": 0.5758468336, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.4727792250390349}}
{"text": "--------------------------------------------------------------------------------\n-- |\n-- Module    :  Datasets.Iris\n-- Copyright :  (c) Sam Stites 2017\n-- License   :  BSD3\n-- Maintainer:  sam@stites.io\n-- Stability :  experimental\n-- Portability: non-portable\n--\n-- === Iris Data Set\n--\n-- Data Set Characteristics  :  Multivariate\n-- Number of Instances       : 150\n-- Area                      : Life\n-- Attribute Characteristics : Real\n-- Number of Attributes      : 4\n-- Date Donated              : 1988-07-01\n-- Associated Tasks          : Classification\n-- Missing Values?           : No\n-- Creator                   : R. A. Fisher\n-- Source                    : https://archive.ics.uci.edu/ml/datasets/Iris\n--\n-- === Data Set Information\n--\n-- This is perhaps the best known database to be found in the pattern\n-- recognition literature. Fisher's paper is a classic in the field and is\n-- referenced frequently to this day. (See Duda & Hart, for example.) The data\n-- set contains 3 classes of 50 instances each, where each class refers to a\n-- type of iris plant. One class is linearly separable from the other 2; the\n-- latter are NOT linearly separable from each other.\n--\n-- Predicted attribute: class of iris plant.\n--\n-- This is an exceedingly simple domain.\n--\n-- This data differs from the data presented in Fishers article (identified by\n-- Steve Chadwick, spchadwick '@' espeedaz.net ). The 35th sample should be:\n-- 4.9,3.1,1.5,0.2,\"Iris-setosa\" where the error is in the fourth feature. The\n-- 38th sample: 4.9,3.6,1.4,0.1,\"Iris-setosa\" where the errors are in the second\n-- and third features.\n--\n--\n-- === Attribute Information\n--\n-- 1. Sepal length in cm\n-- 2. Sepal width in cm\n-- 3. Petal length in cm\n-- 4. Petal width in cm\n-- 5. Class: Iris Setosa | Iris Versicolour | Iris Virginica\n--\n-- === Summary Statistics:\n--\n--               Min  Max   Mean    SD   Class Correlation\n-- sepal length: 4.3  7.9   5.84  0.83    0.7826\n-- sepal width : 2.0  4.4   3.05  0.43   -0.4194\n-- petal length: 1.0  6.9   3.76  1.76    0.9490  (high!)\n-- petal width : 0.1  2.5   1.20  0.76    0.9565  (high!)\n--\n-- === Class Distribution\n--\n-- 33.3% for each of 3 classes.\n--------------------------------------------------------------------------------\n{-# LANGUAGE DeriveGeneric #-}\nmodule Datasets.Iris where\n\nimport Prelude hiding (readFile)\nimport Data.Csv\nimport Control.Arrow\nimport GHC.Generics\nimport Data.ByteString.Lazy (readFile)\nimport Control.Monad.IO.Class\nimport Control.Exception.Safe\n\nimport Data.Vector (Vector, toList, fromList)\nimport qualified Data.Vector as V\nimport Numeric.LinearAlgebra (Matrix, fromLists)\nimport Numeric.LinearAlgebra.Data ((??), Extractor(..))\n\ndata Datum = Datum\n  { sepalLength :: Double\n  , sepalWidth  :: Double\n  , petalLength :: Double\n  , petalWidth  :: Double\n  , irisClass   :: IrisClass\n  } deriving (Eq, Show, Generic)\n\ninstance FromRecord Datum\n\ntoDoubles :: Datum -> [Double]\ntoDoubles (Datum a b c d e) = [a, b, c, d, fromIntegral $ fromEnum e]\n-- ========================================================================= --\n\ndata IrisClass\n  = Setosa\n  | Versicolour\n  | Virginica\n  deriving (Eq, Bounded, Enum, Generic)\n\ninstance FromRecord IrisClass\ninstance FromField  IrisClass where\n  parseField s\n    | s == \"Iris-setosa\"     = pure Setosa\n    | s == \"Iris-versicolor\" = pure Versicolour\n    | s == \"Iris-virginica\"  = pure Virginica\n\ninstance Show IrisClass where\n  show Setosa      = \"Iris Setosa\"\n  show Versicolour = \"Iris Versicolour\"\n  show Virginica   = \"Iris Virginica\"\n\n-- ========================================================================= --\n\nloadIrisRaw :: (MonadThrow m, MonadIO m) => m (Vector Datum)\nloadIrisRaw = do\n  iris <- liftIO $ readFile \"data/Datasets/Iris.csv\"\n  Right xs <- pure $ decode NoHeader iris\n  return xs\n\n\nloadIris :: (MonadThrow m, MonadIO m) => m (Matrix Double, Vector IrisClass)\nloadIris = featureLabelSplit <$> loadIrisRaw\n  where\n    featureLabelSplit :: Vector Datum -> (Matrix Double, Vector IrisClass)\n    featureLabelSplit v = foo $ fmap ((init . toDoubles) &&& irisClass) v\n\n    foo :: Vector ([Double], IrisClass) -> (Matrix Double, Vector IrisClass)\n    foo vs = (fromLists $ toList (fmap fst vs), fmap snd vs)\n\n\ntype Dataset = (Matrix Double, Vector IrisClass)\n\n\nsplitCV :: Float -> Dataset -> (Dataset, Dataset)\nsplitCV percent (features, labels) =\n  ( (features ?? (Take splitpoint, All), V.take splitpoint labels)\n  , (features ?? (Drop splitpoint, All), V.drop splitpoint labels)\n  )\n\n  where\n    splitpoint :: Int\n    splitpoint = truncate (fromIntegral (length labels) * percent) :: Int\n\n", "meta": {"hexsha": "b8c83b93de4b1d47dc0de914fd00aa3dc1979d23", "size": 4623, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Datasets/Iris.hs", "max_stars_repo_name": "stites/hasklearn", "max_stars_repo_head_hexsha": "188464e47d624621c01c7851297b85f9446ffaf4", "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/Datasets/Iris.hs", "max_issues_repo_name": "stites/hasklearn", "max_issues_repo_head_hexsha": "188464e47d624621c01c7851297b85f9446ffaf4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-08-02T15:05:37.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T16:12:39.000Z", "max_forks_repo_path": "src/Datasets/Iris.hs", "max_forks_repo_name": "stites/hasklearn", "max_forks_repo_head_hexsha": "188464e47d624621c01c7851297b85f9446ffaf4", "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.3286713287, "max_line_length": 80, "alphanum_fraction": 0.6216742375, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.4727792117633646}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule R2Z2T0S0ToR2S1RPT0S0 where\n\nimport           Control.Monad.Parallel    as MP\nimport           Data.Array.Repa           as R\nimport           Data.Binary               (decodeFile)\nimport           Data.Complex\nimport           Data.List                 as L\nimport           FokkerPlanck.DomainChange\nimport           FokkerPlanck.MonteCarlo\nimport           FokkerPlanck.Pinwheel\nimport           Image.IO\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Text.Printf\nimport           Utils.Array\nimport           Utils.Time\n\nmain = do\n  args@(numPointStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:taoStr:lenStr:initStr:numTrailStr:maxTrailStr:theta0FreqsStr:thetaFreqsStr:scale0FreqsStr:scaleFreqsStr:histPath:alphaStr:pinwheelFlagStr:numThreadStr:_) <-\n    getArgs\n  print args\n  let numPoint = read numPointStr :: Int\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      maxScale = read maxScaleStr :: Double\n      tao = read taoStr :: Double\n      len = read lenStr :: Int\n      init = read initStr :: (Double, Double, Double, Double, Double, Double)\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      theta0Freq = read theta0FreqsStr :: Double\n      thetaFreq = read thetaFreqsStr :: Double\n      scale0Freq = read scale0FreqsStr :: Double\n      scaleFreq = read scaleFreqsStr :: Double\n      theta0Freqs = [-theta0Freq .. theta0Freq]\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      scale0Freqs = [-scale0Freq .. scale0Freq]\n      scaleFreqs = [-scaleFreq .. scaleFreq]\n      alpha = read alphaStr :: Double\n      pinwheelFlag = read pinwheelFlagStr :: Bool\n      numThread = read numThreadStr :: Int\n      folderPath = \"output/test/R2Z2T0S0ToR2S1RPT0S0\"\n  flag <- doesFileExist histPath\n  -- arrR2Z2T0S0 <-\n  --   -- if flag\n  --   --   then getNormalizedHistogramArr <$> decodeFile histPath\n  --   --   else\n  --     solveMonteCarloR2Z2T0S0\n  --            numThread\n  --            numTrail\n  --            maxTrail\n  --            numPoint\n  --            numPoint\n  --            thetaSigma\n  --            scaleSigma\n  --            maxScale\n  --            tao\n  --            len\n  --            theta0Freqs\n  --            thetaFreqs\n  --            scale0Freqs\n  --            scaleFreqs\n  --            histPath\n  --            (emptyHistogram\n  --               [ numPoint\n  --               , numPoint\n  --               , L.length scale0Freqs\n  --               , L.length theta0Freqs\n  --               , L.length scaleFreqs\n  --               , L.length thetaFreqs\n  --               ]\n  --               0)\n  radialArr <-\n    if flag\n      then R.map magnitude . getNormalizedHistogramArr <$> decodeFile histPath\n      else do\n        putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n        printCurrentTime\n        solveMonteCarloR2Z2T0S0Radial\n          numThread\n          numTrail\n          maxTrail\n          numPoint\n          numPoint\n          thetaSigma\n          scaleSigma\n          maxScale\n          tao\n          theta0Freqs\n          thetaFreqs\n          scale0Freqs\n          scaleFreqs\n          \"\"\n          (emptyHistogram\n             [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n             , L.length scale0Freqs\n             , L.length theta0Freqs\n             , L.length scaleFreqs\n             , L.length thetaFreqs\n             ]\n             0)\n  printCurrentTime\n  arrR2Z2T0S0 <-\n    computeUnboxedP $\n    computeR2Z2T0S0ArrayRadial\n      radialArr\n      numPoint\n      numPoint\n      1\n      maxScale\n      thetaFreqs\n      scaleFreqs\n      theta0Freqs\n      scale0Freqs\n  arrR2Z2 <- R.sumP . R.sumS . rotateR2Z2T0S0Array $ arrR2Z2T0S0\n      -- arr =\n      --   r2z2t0s0Tor2s1rpt0s0\n      --     numOrientation\n      --     thetaFreqs\n      --     numScale\n      --     scaleFreqs\n      --     arrR2Z2T0S0\n      -- arr4d =\n      --   R.slice arr $\n      --   (Z :. All :. All :. (L.length theta0Freqs - 1) :.\n      --    (L.length scale0Freqs - 1) :.\n      --    All :.\n      --    All)\n  let arr4d = r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs arrR2Z2\n  createDirectoryIfMissing True folderPath\n  printCurrentTime\n  MP.mapM_\n    (\\(i, j) ->\n       plotImageRepaComplex\n         (folderPath </> show (i + 1) L.++ \"_\" L.++ show (j + 1) L.++ \".png\") .\n       ImageRepa 8 .\n       computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.slice arr4d $\n       (Z :. i :. j :. All :. All))\n    [(i, j) | i <- [0 .. numOrientation - 1], j <- [0 .. numScale - 1]]\n  arr2D <- R.sumP . R.sumS . rotate4D . rotate4D $ arr4d\n  plotImageRepaComplex (folderPath </> \"sum.png\") .\n    ImageRepa 8 . computeS . R.extend (Z :. (1 :: Int) :. All :. All) $\n    arr2D\n", "meta": {"hexsha": "9121f453ebc1b64aeb3930c9796dd9e04cf83d28", "size": 4974, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/R2Z2T0S0ToR2S1RPT0S0/R2Z2T0S0ToR2S1RPT0S0.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/R2Z2T0S0ToR2S1RPT0S0/R2Z2T0S0ToR2S1RPT0S0.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/R2Z2T0S0ToR2S1RPT0S0/R2Z2T0S0ToR2S1RPT0S0.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 33.6081081081, "max_line_length": 246, "alphanum_fraction": 0.55991154, "num_tokens": 1453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4723826641474846}}
{"text": "module Statistics.Quantile.Bench.Accuracy where\n\nimport qualified Data.Vector as V\n\nimport Statistics.Quantile.Types\nimport Statistics.Quantile.Util\n\nimport Statistics.Sample\n\nimport System.IO\n\nerr :: Double\n    -> Double\n    -> Double\nerr true estimate = \n  let e = abs (true - estimate)\n  in e * e\n\nselectorAccuracy :: Stream IO\n                 -> Quantile\n                 -> Double\n                 -> Selector IO\n                 -> IO Double\nselectorAccuracy src q true (Selector select) =\n  err true <$> select q src\n\nbenchAccuracy :: Int\n              -> FilePath\n              -> Quantile\n              -> Double\n              -> Selector IO\n              -> IO Deviation\nbenchAccuracy n fp q true s = do\n  as <- V.replicateM n accuracy\n  pure $ Deviation (mean as) (stdDev as)\n  where accuracy = do\n          h <- openFile fp ReadMode\n          r <- selectorAccuracy (streamHandle h) q true s\n          hClose h\n          pure r\n", "meta": {"hexsha": "7b51af237e530daeddde14c0cc2c91713d4d5061", "size": 940, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "2015-08-26-fp-syd-approx-quantiles/approx-quantile/src/Statistics/Quantile/Bench/Accuracy.hs", "max_stars_repo_name": "fractalcat/slides", "max_stars_repo_head_hexsha": "338db16c6998dc4add9d1ebd511b3faf3a4420dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2015-08-26-fp-syd-approx-quantiles/approx-quantile/src/Statistics/Quantile/Bench/Accuracy.hs", "max_issues_repo_name": "fractalcat/slides", "max_issues_repo_head_hexsha": "338db16c6998dc4add9d1ebd511b3faf3a4420dc", "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": "2015-08-26-fp-syd-approx-quantiles/approx-quantile/src/Statistics/Quantile/Bench/Accuracy.hs", "max_forks_repo_name": "fractalcat/slides", "max_forks_repo_head_hexsha": "338db16c6998dc4add9d1ebd511b3faf3a4420dc", "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": 22.9268292683, "max_line_length": 57, "alphanum_fraction": 0.5819148936, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.47237297778205056}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Statistics.Classification.ConfusionMatrix.Binary (\n    ConfusionMatrix\n  , trueConfMatrix\n  , resultCount, classCount, totalCount\n  , actualPositive, actualNegative, predPositive, predNegative\n  , truePosRate, falseNegRate, falsePosRate, trueNegRate\n  , prevalence, accuracy, errorRate, recall, precision, specificity\n  , oddsRatio\n  , phiCorrelation\n  , fScore, f1Score\n  , actualEntropy, predEntropy, condActualEntropy, condPredEntropy, totalCondEntropy\n  , mutualInformation\n  , asBinaryConfusion\n  , asMultiConfusion\n  ) where\n\nimport Data.Monoid (Sum(..))\n\nimport Data.Csv ((.:), (.=), DefaultOrdered(..), FromNamedRecord(..), ToNamedRecord(..), header, namedRecord)\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Set as Set\n\nimport Statistics.Classification.ConfusionMatrix.Multi (MultiConfusionMatrix(..), PosNeg\n  , truePositiveCount, falsePositiveCount, falseNegativeCount, trueNegativeCount)\nimport Statistics.Classification.Types (ClassificationResult(..))\n\ndata ConfusionMatrix = ConfusionMatrix {\n    truePositive :: {-# UNPACK #-}!(Sum Int)\n  , falsePositive :: {-# UNPACK #-}!(Sum Int)\n  , falseNegative :: {-# UNPACK #-}!(Sum Int)\n  , trueNegative :: {-# UNPACK #-}!(Sum Int)\n  } deriving (Eq, Show, Read)\n\ninstance Semigroup ConfusionMatrix where\n  cm0 <> cm1 = ConfusionMatrix {\n      truePositive  = truePositive  cm0 <> truePositive  cm1\n    , falsePositive = falsePositive cm0 <> falsePositive cm1\n    , falseNegative = falseNegative cm0 <> falseNegative cm1\n    , trueNegative  = trueNegative  cm0 <> trueNegative  cm1\n    }\n\ninstance Monoid ConfusionMatrix where\n  mempty = ConfusionMatrix mempty mempty mempty mempty\n  mappend = (<>)\n\ninstance DefaultOrdered ConfusionMatrix where\n  headerOrder _ = header [\n      \"true_positive\"\n    , \"false_positive\"\n    , \"true_negative\"\n    , \"false_negative\"\n    ]\n\ninstance ToNamedRecord ConfusionMatrix where\n  toNamedRecord conf = namedRecord [\n      \"true_positive\"  .= getSum (truePositive conf)\n    , \"false_positive\" .= getSum (falsePositive conf)\n    , \"true_negative\"  .= getSum (trueNegative conf)\n    , \"false_negative\" .= getSum (falseNegative conf)\n    ]\n\ninstance FromNamedRecord ConfusionMatrix where\n  parseNamedRecord r = ConfusionMatrix <$>\n        fmap Sum (r .: \"true_positive\")\n    <*> fmap Sum (r .: \"false_positive\")\n    <*> fmap Sum (r .: \"false_negative\")\n    <*> fmap Sum (r .: \"true_negative\")\n\n-- create confusion matrix given assumed true results\n-- i.e., classifiedPredicted is the number predicted correctly\n--       classifiedActual    is the number of actual samples in class\n-- Give numbers for both true and false labels\ntrueConfMatrix :: ClassificationResult Int -> ClassificationResult Int -> ConfusionMatrix\ntrueConfMatrix pos neg = ConfusionMatrix {\n    truePositive  = Sum $ classifiedPredicted pos\n  , falseNegative = Sum $ classifiedActual pos - classifiedPredicted pos\n  , falsePositive = Sum $ classifiedActual neg - classifiedPredicted neg\n  , trueNegative  = Sum $ classifiedPredicted neg\n  }\n\nresultCount :: ConfusionMatrix -> ClassificationResult Bool -> Int\nresultCount cm (ClassificationResult actual prd) = classCount cm prd actual\n\nclassCount :: ConfusionMatrix -> Bool -> Bool -> Int\nclassCount cm prd actual = getSum $ if prd\n  then (if actual then  truePositive cm else falsePositive cm)\n  else (if actual then falseNegative cm else  trueNegative cm)\n\ntotalCount :: ConfusionMatrix -> Int\ntotalCount cm = getSum $ truePositive cm <> falsePositive cm <> falseNegative cm <> trueNegative cm\n\nactualPositive, actualNegative, predPositive, predNegative :: ConfusionMatrix -> Int\nactualPositive cm = getSum $  truePositive cm <> falseNegative cm\nactualNegative cm = getSum $ falsePositive cm <>  trueNegative cm\npredPositive   cm = getSum $  truePositive cm <> falsePositive cm\npredNegative   cm = getSum $ falseNegative cm <>  trueNegative cm\n\ntruePosRate, falseNegRate, falsePosRate, trueNegRate :: ConfusionMatrix -> Double\ntruePosRate = recall\nfalseNegRate cm = fromIntegral (getSum (falseNegative cm)) / fromIntegral (actualPositive cm)\nfalsePosRate cm = fromIntegral (getSum (falsePositive cm)) / fromIntegral (actualNegative cm)\ntrueNegRate = specificity\n\nprevalence, accuracy, errorRate, recall, precision, specificity :: ConfusionMatrix -> Double\nprevalence cm = fromIntegral (actualPositive cm) / fromIntegral (totalCount cm)\naccuracy cm = fromIntegral (getSum (truePositive cm <> trueNegative cm)) / fromIntegral (totalCount cm)\nerrorRate cm = fromIntegral (getSum (falsePositive cm <> falseNegative cm)) / fromIntegral (totalCount cm)\nrecall cm = fromIntegral (getSum (truePositive cm)) / fromIntegral (actualPositive cm)\nprecision cm = fromIntegral (getSum (truePositive cm)) / fromIntegral (predPositive cm)\nspecificity cm = fromIntegral (getSum (trueNegative cm)) / fromIntegral (actualNegative cm)\n\noddsRatio :: ConfusionMatrix -> Double\noddsRatio (ConfusionMatrix (Sum tp) (Sum fp) (Sum fn) (Sum tn)) =\n  fromIntegral (tp * tn) / fromIntegral (fn * fp)\n\nphiCorrelation :: ConfusionMatrix -> Double\nphiCorrelation (ConfusionMatrix (Sum tp) (Sum fp) (Sum fn) (Sum tn)) =\n  fromIntegral (tp * tn - fp * fn) / sqrt (fromIntegral $ (tp + fn) * (tn + fp) * (tp + fp) * (tn + fn))\n\nfScore :: Double -> ConfusionMatrix -> Double\nfScore alpha cm = recip $ alpha * recip (precision cm) + (1 - alpha) * recip (recall cm)\n\nf1Score :: ConfusionMatrix -> Double\nf1Score = fScore 0.5\n\n-- Entropy calculations\nbinomEntropy :: Double -> Double\nbinomEntropy p = p * log p + (1 - p) * log (1 - p)\n\ndiscreteEntropy :: Int -> Int -> Double\ndiscreteEntropy n tot = binomEntropy (fromIntegral n / fromIntegral tot)\n\nactualEntropy, predEntropy :: ConfusionMatrix -> Double\nactualEntropy cm = discreteEntropy (actualPositive cm) (totalCount cm)\npredEntropy cm = discreteEntropy (predPositive cm) (totalCount cm)\n\ncondActualEntropy :: ConfusionMatrix -> Bool -> Double\ncondActualEntropy cm plbl = if plbl\n  then discreteEntropy (getSum (truePositive cm)) (predPositive cm)\n  else discreteEntropy (getSum (trueNegative cm)) (predNegative cm)\n\ncondPredEntropy :: ConfusionMatrix -> Bool -> Double\ncondPredEntropy cm albl = if albl\n  then discreteEntropy (getSum (truePositive cm)) (actualPositive cm)\n  else discreteEntropy (getSum (trueNegative cm)) (actualNegative cm)\n\ntotalCondEntropy :: ConfusionMatrix -> Double\ntotalCondEntropy cm = ppos * condActualEntropy cm True + (1 - ppos) * condActualEntropy cm False\n  where ppos = fromIntegral (predPositive cm) / fromIntegral (totalCount cm)\n\nmutualInformation :: ConfusionMatrix -> Double\nmutualInformation cm = actualEntropy cm - totalCondEntropy cm\n\nasBinaryConfusion :: Ord a => PosNeg a -> MultiConfusionMatrix a -> ConfusionMatrix\nasBinaryConfusion posneg mcm = ConfusionMatrix {\n    truePositive = Sum $ truePositiveCount mcm posneg\n  , falsePositive = Sum $ falsePositiveCount mcm posneg\n  , falseNegative = Sum $ falseNegativeCount mcm posneg\n  , trueNegative = Sum $ trueNegativeCount mcm posneg\n  }\n\nasMultiConfusion :: ConfusionMatrix -> MultiConfusionMatrix Bool\nasMultiConfusion cm = MultiConfusionMatrix {\n    confCounts = Map.fromList [\n        (ClassificationResult True  True,  getSum (truePositive cm))\n      , (ClassificationResult False True,  getSum (falsePositive cm))\n      , (ClassificationResult True  False, getSum (falseNegative cm))\n      , (ClassificationResult False False, getSum (trueNegative cm))\n      ]\n  , confClasses = Set.fromList [True, False]\n  }\n", "meta": {"hexsha": "6c9b9b2f5cfd63c240638700125b39dffba77d26", "size": 7498, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Classification/ConfusionMatrix/Binary.hs", "max_stars_repo_name": "tsbattman/rochs", "max_stars_repo_head_hexsha": "b8a229ca906ae36a6b93e59db8de88d077644a55", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/Classification/ConfusionMatrix/Binary.hs", "max_issues_repo_name": "tsbattman/rochs", "max_issues_repo_head_hexsha": "b8a229ca906ae36a6b93e59db8de88d077644a55", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Classification/ConfusionMatrix/Binary.hs", "max_forks_repo_name": "tsbattman/rochs", "max_forks_repo_head_hexsha": "b8a229ca906ae36a6b93e59db8de88d077644a55", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.091954023, "max_line_length": 109, "alphanum_fraction": 0.7435316084, "num_tokens": 1881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4723364912823023}}
{"text": "{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE Strict          #-}\n\nmodule Optimization.Types where\n\nimport Control.Lens\nimport Numeric.LinearAlgebra            ( Numeric )\nimport Numeric.LinearAlgebra.Data\nimport Data.Vector.Storable       as VS ( map\n                                        , singleton\n                                        , zipWith )\n\n{- |Basic \"zippy\" Num instance for storable vectors. Note that, while this is defined\n    for some types of Vector by hmatrix, it unfortunately does not account for any\n    Num (Vector a). -}\ninstance Numeric a => Num (Vector a) where\n  a + b    = VS.zipWith (+)   a b\n  a - b    = VS.zipWith (-)   a b\n  a * b    = VS.zipWith (*)   a b\n  abs a    = VS.map  (abs)    a\n  signum a = VS.map  (signum) a\n  fromInteger i = VS.singleton (fromInteger i)\n\n{- |Termination criterion for a numerical optimization method.\n    We terminate either on maxit iterations or once our guesses are within\n    threshold of one another. -}\ndata TerminationCriterion a = TerminateAt {\n  _maxit     :: Maybe Int, -- ^Maximum number of iterations (if any).\n  _threshold :: Maybe a    -- ^Threshold used to declare convergence (if any).\n  } deriving (Show, Eq)\n\n-- |Step parameters for Nelder-Mead simplex search. a must be Storable and Num.\ndata NMStepParameters a = NMStepParameters {\n  _epsilon :: a, -- ^Offset around initial guess to construct starting simplex.\n  _alpha   :: a, -- ^Reflection coefficient for Nelder-Mead algorithm.\n  _gamma   :: a, -- ^Expansion coefficient for Nelder-Mead algorithm.\n  _rho     :: a, -- ^Contraction coefficient for Nelder-Mead algorithm.\n  _sigma   :: a  -- ^Shrink coefficient for Nelder-Mead algorithm.\n  } deriving (Show, Eq)\n\n-- |Standard Nelder-Mead parameters.\ndefaultStep :: NMStepParameters Double\ndefaultStep = NMStepParameters 1.0 1.0 2.0 0.5 0.5\n\n-- |The Nelder-Mead simplex.\ntype Simplex a = Matrix a\n\n-- |Create a TerminationCriterion with just a convergence threshold.\nterminateAt ::\n  a ->                   -- ^Convengence threshold\n  TerminationCriterion a -- ^A TerminationCriterion for optimization.\nterminateAt t = TerminateAt Nothing (Just t)\n\n-- |Create a TerminationCriterion with just a maximum iteration threshold.\nterminateAfter ::\n  Int               ->   -- ^Maximum number of iterations.\n  TerminationCriterion a -- ^A TerminationCriterion for optimization.\nterminateAfter m = TerminateAt (Just m) Nothing\n\n-- |Create a TerminationCriterion with a convergence threshold and maximum iteration\n-- |limit.\nterminateAtOrAfter ::\n  a      ->              -- ^Convergence threshold\n  Int    ->              -- ^Maximum number of iterations\n  TerminationCriterion a -- ^A TerminationCriterion for optimization.\nterminateAtOrAfter t m = TerminateAt (Just m) (Just t)\n\nmakeLenses ''TerminationCriterion\nmakeLenses ''NMStepParameters\n", "meta": {"hexsha": "b3f7406f54e72758d5a033ceb6fc73bb1e78a5d0", "size": 2828, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Optimization/Types.hs", "max_stars_repo_name": "agbrooks/buzzwords", "max_stars_repo_head_hexsha": "89fa4ef0dc5a2317b6f19bd05f1d44a5b7aa9763", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-10-10T07:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-10T07:11:28.000Z", "max_issues_repo_path": "src/Optimization/Types.hs", "max_issues_repo_name": "agbrooks/buzzwords", "max_issues_repo_head_hexsha": "89fa4ef0dc5a2317b6f19bd05f1d44a5b7aa9763", "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/Optimization/Types.hs", "max_forks_repo_name": "agbrooks/buzzwords", "max_forks_repo_head_hexsha": "89fa4ef0dc5a2317b6f19bd05f1d44a5b7aa9763", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4, "max_line_length": 85, "alphanum_fraction": 0.6803394625, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.47233320961336384}}
{"text": "{-# LANGUAGE CPP                  #-}\n{-# LANGUAGE FlexibleContexts     #-}\n{-# LANGUAGE FlexibleInstances    #-}\n{-# LANGUAGE ScopedTypeVariables  #-}\n{-# LANGUAGE UndecidableInstances #-}\n\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\n-----------------------------------------------------------------------------\n{- |\nModule      :  Numeric.LinearAlgebra.Tests.Instances\nCopyright   :  (c) Alberto Ruiz 2008\nLicense     :  BSD3\nMaintainer  :  Alberto Ruiz\nStability   :  provisional\n\nArbitrary instances for vectors, matrices.\n\n-}\n\nmodule Test.Numeric.LinearAlgebra.Tests.Instances(\n    Sq(..),     rSq,cSq,\n    Sq2WC(..),  rSq2WC,cSq2WC,\n    Rot(..),    rRot,cRot,\n                rHer,cHer,\n    WC(..),     rWC,cWC,\n    SqWC(..),   rSqWC, cSqWC, rSymWC, cSymWC,\n    PosDef(..), rPosDef, cPosDef,\n    Consistent(..), rConsist, cConsist,\n    RM,CM, rM,cM,\n    FM,ZM, fM,zM\n) where\n\nimport           System.Random\n\nimport           Control.Monad                 (replicateM)\nimport           Numeric.LinearAlgebra.HMatrix hiding (vector)\nimport           Test.QuickCheck               (Arbitrary, arbitrary, choose, shrink,\n                                                sized, vector)\n\nimport           Data.Proxy                    (Proxy (..))\nimport           GHC.TypeLits\nimport qualified Numeric.LinearAlgebra.Static  as Static\n#if MIN_VERSION_base(4,11,0)\nimport           Prelude                       hiding ((<>))\n#endif\n\nshrinkListElementwise :: (Arbitrary a) => [a] -> [[a]]\nshrinkListElementwise []     = []\nshrinkListElementwise (x:xs) = [ y:xs | y  <- shrink x                 ]\n                            ++ [ x:ys | ys <- shrinkListElementwise xs ]\n\nshrinkPair :: (Arbitrary a, Arbitrary b) => (a,b) -> [(a,b)]\nshrinkPair (a,b) = [ (a,x) | x <- shrink b ] ++ [ (x,b) | x <- shrink a ]\n\nchooseDim = sized $ \\m -> choose (1,max 1 m)\n\ninstance (Field a, Arbitrary a) => Arbitrary (Vector a) where\n    arbitrary = do m <- chooseDim\n                   l <- vector m\n                   return $ fromList l\n    -- shrink any one of the components\n    shrink = map fromList . shrinkListElementwise . toList\n\ninstance KnownNat n => Arbitrary (Static.R n) where\n    arbitrary = do\n      l <- vector n\n      return (Static.fromList l)\n\n      where\n        n :: Int\n        n = fromIntegral (natVal (Proxy :: Proxy n))\n\n    shrink _v = []\n\ninstance (Element a, Arbitrary a) => Arbitrary (Matrix a) where\n    arbitrary = do\n        m <- chooseDim\n        n <- chooseDim\n        l <- vector (m*n)\n        return $ (m><n) l\n\n    -- shrink any one of the components\n    shrink a = map (rows a >< cols a)\n               . shrinkListElementwise\n               . concat . toLists\n                     $ a\n\ninstance (KnownNat n, KnownNat m) => Arbitrary (Static.L m n) where\n    arbitrary = do\n      l <- vector (m * n)\n      return (Static.fromList l)\n\n      where\n        m :: Int\n        m = fromIntegral (natVal (Proxy :: Proxy m))\n\n        n :: Int\n        n = fromIntegral (natVal (Proxy :: Proxy n))\n\n    shrink _mat = []\n\n-- a square matrix\nnewtype (Sq a) = Sq (Matrix a) deriving Show\ninstance (Element a, Arbitrary a) => Arbitrary (Sq a) where\n    arbitrary = do\n        n <- chooseDim\n        l <- vector (n*n)\n        return $ Sq $ (n><n) l\n\n    shrink (Sq a) = [ Sq b | b <- shrink a ]\n\n-- a pair of square matrices\nnewtype (Sq2WC a) = Sq2WC (Matrix a, Matrix a) deriving Show\ninstance (ArbitraryField a, Numeric a) => Arbitrary (Sq2WC a) where\n    arbitrary = do\n        n <- chooseDim\n        l <- vector (n*n)\n        r <- vector (n*n)\n        l' <- makeWC $ (n><n) l\n        r' <- makeWC $ (n><n) r\n        return $ Sq2WC (l', r')\n        where\n            makeWC m = do\n              let (u,_,v) = svd m\n                  n = rows m\n              sv' <- replicateM n (choose (1,100))\n              let s = diag (fromList sv')\n              return $ u <> real s <> tr v\n\n-- a unitary matrix\nnewtype (Rot a) = Rot (Matrix a) deriving Show\ninstance (Field a, Arbitrary a) => Arbitrary (Rot a) where\n    arbitrary = do\n        Sq m <- arbitrary\n        let (q,_) = qr m\n        return (Rot q)\n\n\n-- a complex hermitian or real symmetric matrix\ninstance (Field a, Arbitrary a, Num (Vector a)) => Arbitrary (Herm a) where\n    arbitrary = do\n        Sq m <- arbitrary\n        let m' = m/2\n        return $ sym m'\n\n\nclass (Field a, Arbitrary a, Element (RealOf a), Random (RealOf a)) => ArbitraryField a\ninstance ArbitraryField Float\ninstance ArbitraryField (Complex Float)\n\n\n-- a well-conditioned general matrix (the singular values are between 1 and 100)\nnewtype (WC a) = WC (Matrix a) deriving Show\ninstance (Numeric a, ArbitraryField a) => Arbitrary (WC a) where\n    arbitrary = do\n        m <- arbitrary\n        let (u,_,v) = svd m\n            r = rows m\n            c = cols m\n            n = min r c\n        sv' <- replicateM n (choose (1,100))\n        let s = diagRect 0 (fromList sv') r c\n        return $ WC (u <> real s <> tr v)\n\n\n-- a well-conditioned square matrix (the singular values are between 1 and 100)\nnewtype (SqWC a) = SqWC (Matrix a) deriving Show\ninstance (ArbitraryField a, Numeric a) => Arbitrary (SqWC a) where\n    arbitrary = do\n        Sq m <- arbitrary\n        let (u,_,v) = svd m\n            n = rows m\n        sv' <- replicateM n (choose (1,100))\n        let s = diag (fromList sv')\n        return $ SqWC (u <> real s <> tr v)\n\n\n-- a positive definite square matrix (the eigenvalues are between 0 and 100)\nnewtype (PosDef a) = PosDef (Matrix a) deriving Show\ninstance (Numeric a, ArbitraryField a, Num (Vector a))\n    => Arbitrary (PosDef a) where\n    arbitrary = do\n        m <- arbitrary\n        let (_,v) = eigSH m\n            n = rows (unSym m)\n        l <- replicateM n (choose (0,100))\n        let s = diag (fromList l)\n            p = v <> real s <> tr v\n        return $ PosDef (0.5 * p + 0.5 * tr p)\n\n\n-- a pair of matrices that can be multiplied\nnewtype (Consistent a) = Consistent (Matrix a, Matrix a) deriving Show\ninstance (Field a, Arbitrary a) => Arbitrary (Consistent a) where\n    arbitrary = do\n        n <- chooseDim\n        k <- chooseDim\n        m <- chooseDim\n        la <- vector (n*k)\n        lb <- vector (k*m)\n        return $ Consistent ((n><k) la, (k><m) lb)\n\n    shrink (Consistent (x,y)) = [ Consistent (u,v) | (u,v) <- shrinkPair (x,y) ]\n\n\ntype RM = Matrix Float\ntype CM = Matrix (Complex Float)\ntype FM = Matrix Float\ntype ZM = Matrix (Complex Float)\n\n\nrM m = m :: RM\ncM m = m :: CM\nfM m = m :: FM\nzM m = m :: ZM\n\n\nrHer m = unSym m :: RM\ncHer m = unSym m :: CM\n\nrRot (Rot m) = m :: RM\ncRot (Rot m) = m :: CM\n\nrSq  (Sq m)  = m :: RM\ncSq  (Sq m)  = m :: CM\n\nrSq2WC (Sq2WC (a, b)) = (a, b) :: (RM, RM)\ncSq2WC (Sq2WC (a, b)) = (a, b) :: (CM, CM)\n\nrWC (WC m) = m :: RM\ncWC (WC m) = m :: CM\n\nrSqWC (SqWC m) = m :: RM\ncSqWC (SqWC m) = m :: CM\n\nrSymWC (SqWC m) = sym m :: Herm R\ncSymWC (SqWC m) = sym m :: Herm C\n\nrPosDef (PosDef m) = m :: RM\ncPosDef (PosDef m) = m :: CM\n\nrConsist (Consistent (a,b)) = (a,b::RM)\ncConsist (Consistent (a,b)) = (a,b::CM)\n\n", "meta": {"hexsha": "6be19749c97c667b50bdbdf0d09bd500009dfa05", "size": 7060, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Test/Numeric/LinearAlgebra/Tests/Instances.hs", "max_stars_repo_name": "schnecki/hmatrix-float", "max_stars_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "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": "tests/Test/Numeric/LinearAlgebra/Tests/Instances.hs", "max_issues_repo_name": "schnecki/hmatrix-float", "max_issues_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "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": "tests/Test/Numeric/LinearAlgebra/Tests/Instances.hs", "max_forks_repo_name": "schnecki/hmatrix-float", "max_forks_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-12T02:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T02:51:35.000Z", "avg_line_length": 28.5829959514, "max_line_length": 87, "alphanum_fraction": 0.5483002833, "num_tokens": 2063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.47224993955234873}}
{"text": "module School.Types.Encoding\n( Put\n, putDouble\n, putInt\n, putWord\n, doubleToBin\n, intToBin\n, wordToBin\n, matrixDoubleToBin\n, matrixIntToBin\n, runPut\n) where\n\nimport Data.ByteString (ByteString)\nimport Data.Serialize.IEEE754 (putFloat64be)\nimport Data.Serialize.Put (Put, putInt32be, putWord8, runPut)\nimport Data.Word (Word8)\nimport Numeric.LinearAlgebra (Element, I, Matrix, R, toLists)\nimport School.Types.DataType (DataType(..))\n\nputDouble :: R -> Put\nputDouble = putFloat64be\n\ndoubleToBin :: R -> ByteString\ndoubleToBin = runPut . putDouble\n\nputInt :: I -> Put\nputInt = putInt32be . fromIntegral\n\nintToBin :: I -> ByteString\nintToBin = runPut . putInt\n\nputWord :: Word8 -> Put\nputWord = putWord8\n\nwordToBin :: Word8 -> ByteString\nwordToBin = runPut . putWord\n\nwriter :: (Element b)\n       => (a -> Put)\n       -> ([b] -> [a])\n       -> (Matrix b -> ByteString)\nwriter put trans matrix = runPut $\n  mapM_ put ( trans\n            . concat\n            . toLists\n            $ matrix\n            )\n\nmatrixDoubleToBin :: DataType\n                  -> Matrix R\n                  -> ByteString\nmatrixDoubleToBin DBL64B = writer putDouble id\nmatrixDoubleToBin INT32B = undefined\nmatrixDoubleToBin INT08B = undefined\n\nmatrixIntToBin :: DataType\n               -> Matrix I\n               -> ByteString\nmatrixIntToBin DBL64B =\n  writer putDouble (map fromIntegral)\nmatrixIntToBin INT32B =\n  writer putInt id\nmatrixIntToBin INT08B = undefined\n", "meta": {"hexsha": "47c7a466feac85a836b84509b26a8702955e52ee", "size": 1435, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/School/Types/Encoding.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/School/Types/Encoding.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/School/Types/Encoding.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0769230769, "max_line_length": 61, "alphanum_fraction": 0.6724738676, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.47224993721154357}}
{"text": "{-# LANGUAGE TypeOperators, CPP #-}\n{-# LANGUAGE FlexibleInstances  #-}\n{-# LANGUAGE FlexibleContexts   #-}\n{-# LANGUAGE DefaultSignatures   #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n----------------------------------------------------------------------\n-- |\n-- Module      :   Data.AdditiveGroup\n-- Copyright   :  (c) Conal Elliott and Andy J Gill 2008\n-- License     :  BSD3\n-- \n-- Maintainer  :  conal@conal.net, andygill@ku.edu\n-- Stability   :  experimental\n-- \n-- Groups: zero, addition, and negation (additive inverse)\n----------------------------------------------------------------------\n\nmodule Data.AdditiveGroup\n  ( \n    AdditiveGroup(..), sumV\n  , Sum(..), inSum, inSum2\n  ) where\n\nimport Prelude hiding (foldr)\n\nimport Control.Applicative\n#if !(MIN_VERSION_base(4,8,0))\nimport Data.Monoid (Monoid(..))\nimport Data.Foldable (Foldable)\n#endif\nimport Data.Foldable (foldr)\nimport Data.Complex hiding (magnitude)\nimport Data.Ratio\n#if !(MIN_VERSION_base(4,11,0))\nimport Data.Semigroup (Semigroup(..))\n#endif\nimport Foreign.C.Types (CSChar, CInt, CShort, CLong, CLLong, CIntMax, CFloat, CDouble)\n\nimport Data.MemoTrie\n\nimport Data.VectorSpace.Generic\nimport qualified GHC.Generics as Gnrx\nimport GHC.Generics (Generic, (:*:)(..))\n\ninfixl 6 ^+^, ^-^\n\n-- | Additive group @v@.\nclass AdditiveGroup v where\n  -- | The zero element: identity for '(^+^)'\n  zeroV :: v\n  default zeroV :: (Generic v, AdditiveGroup (VRep v)) => v\n  zeroV = Gnrx.to (zeroV :: VRep v)\n  -- | Add vectors\n  (^+^) :: v -> v -> v\n  default (^+^) :: (Generic v, AdditiveGroup (VRep v)) => v -> v -> v\n  v ^+^ v' = Gnrx.to (Gnrx.from v ^+^ Gnrx.from v' :: VRep v)\n  -- | Additive inverse\n  negateV :: v -> v\n  default negateV :: (Generic v, AdditiveGroup (VRep v)) => v -> v\n  negateV v = Gnrx.to (negateV $ Gnrx.from v :: VRep v)\n  -- | Group subtraction\n  (^-^) :: v -> v -> v\n  v ^-^ v' = v ^+^ negateV v'\n\n-- | Sum over several vectors\nsumV :: (Foldable f, AdditiveGroup v) => f v -> v\nsumV = foldr (^+^) zeroV\n\ninstance AdditiveGroup () where\n  zeroV     = ()\n  () ^+^ () = ()\n  negateV   = id\n\n-- For 'Num' types:\n-- \n-- instance AdditiveGroup n where {zeroV=0; (^+^) = (+); negateV = negate}\n\n#define ScalarTypeCon(con,t) \\\n  instance con => AdditiveGroup (t) where {zeroV=0; (^+^) = (+); negateV = negate}\n\n#define ScalarType(t) ScalarTypeCon((),t)\n\nScalarType(Int)\nScalarType(Integer)\nScalarType(Float)\nScalarType(Double)\nScalarType(CSChar)\nScalarType(CInt)\nScalarType(CShort)\nScalarType(CLong)\nScalarType(CLLong)\nScalarType(CIntMax)\nScalarType(CFloat)\nScalarType(CDouble)\nScalarTypeCon(Integral a,Ratio a)\n\ninstance (RealFloat v, AdditiveGroup v) => AdditiveGroup (Complex v) where\n  zeroV   = zeroV :+ zeroV\n  (^+^)   = (+)\n  negateV = negate\n\n-- Hm.  The 'RealFloat' constraint is unfortunate here.  It's due to a\n-- questionable decision to place 'RealFloat' into the definition of the\n-- 'Complex' /type/, rather than in functions and instances as needed.\n\ninstance (AdditiveGroup u,AdditiveGroup v) => AdditiveGroup (u,v) where\n  zeroV             = (zeroV,zeroV)\n  (u,v) ^+^ (u',v') = (u^+^u',v^+^v')\n  negateV (u,v)     = (negateV u,negateV v)\n\ninstance (AdditiveGroup u,AdditiveGroup v,AdditiveGroup w)\n    => AdditiveGroup (u,v,w) where\n  zeroV                  = (zeroV,zeroV,zeroV)\n  (u,v,w) ^+^ (u',v',w') = (u^+^u',v^+^v',w^+^w')\n  negateV (u,v,w)        = (negateV u,negateV v,negateV w)\n\ninstance (AdditiveGroup u,AdditiveGroup v,AdditiveGroup w,AdditiveGroup x)\n    => AdditiveGroup (u,v,w,x) where\n  zeroV                       = (zeroV,zeroV,zeroV,zeroV)\n  (u,v,w,x) ^+^ (u',v',w',x') = (u^+^u',v^+^v',w^+^w',x^+^x')\n  negateV (u,v,w,x)           = (negateV u,negateV v,negateV w,negateV x)\n\n\n-- Standard instance for an applicative functor applied to a vector space.\ninstance AdditiveGroup v => AdditiveGroup (a -> v) where\n  zeroV   = pure   zeroV\n  (^+^)   = liftA2 (^+^)\n  negateV = fmap   negateV\n\n\n-- Maybe is handled like the Maybe-of-Sum monoid\ninstance AdditiveGroup a => AdditiveGroup (Maybe a) where\n  zeroV = Nothing\n  Nothing ^+^ b'      = b'\n  a' ^+^ Nothing      = a'\n  Just a' ^+^ Just b' = Just (a' ^+^ b')\n  negateV = fmap negateV\n\n{-\n\nAlexey Khudyakov wrote:\n\n  I looked through vector-space package and found lawless instance. Namely Maybe's AdditiveGroup instance\n\n  It's group so following relation is expected to hold. Otherwise it's not a group.\n  > x ^+^ negateV x == zeroV\n\n  Here is counterexample:\n\n  > let x = Just 2 in x ^+^ negateV x == zeroV\n  False\n\n  I think it's not possible to sensibly define group instance for\n  Maybe a at all.\n\n\nI see that the problem here is in distinguishing 'Just zeroV' from\nNothing. I could fix the Just + Just line to use Nothing instead of Just\nzeroV when a' ^+^ b' == zeroV, although doing so would require Eq a and\nhence lose some generality. Even so, the abstraction leak would probably\nshow up elsewhere.\n\nHm.\n\n-}\n\n\n\n\n-- Memo tries\ninstance (HasTrie u, AdditiveGroup v) => AdditiveGroup (u :->: v) where\n  zeroV   = pure   zeroV\n  (^+^)   = liftA2 (^+^)\n  negateV = fmap   negateV\n\n\n-- | Monoid under group addition.  Alternative to the @Sum@ in\n-- \"Data.Monoid\", which uses 'Num' instead of 'AdditiveGroup'.\nnewtype Sum a = Sum { getSum :: a }\n  deriving (Eq, Ord, Read, Show, Bounded)\n\ninstance Functor Sum where\n  fmap f (Sum a) = Sum (f a)\n\n-- instance Applicative Sum where\n--   pure a = Sum a\n--   Sum f <*> Sum x = Sum (f x)\n\ninstance Applicative Sum where\n  pure  = Sum\n  (<*>) = inSum2 ($)\n\ninstance AdditiveGroup a => Semigroup (Sum a) where\n  (<>) = liftA2 (^+^)\n\ninstance AdditiveGroup a => Monoid (Sum a) where\n  mempty  = Sum zeroV\n#if !(MIN_VERSION_base(4,11,0))\n  mappend = (<>)\n#endif\n\n-- | Application a unary function inside a 'Sum'\ninSum :: (a -> b) -> (Sum a -> Sum b)\ninSum = getSum ~> Sum\n\n-- | Application a binary function inside a 'Sum'\ninSum2 :: (a -> b -> c) -> (Sum a -> Sum b -> Sum c)\ninSum2 = getSum ~> inSum\n\n\ninstance AdditiveGroup a => AdditiveGroup (Sum a) where\n  zeroV   = mempty\n  (^+^)   = mappend\n  negateV = inSum negateV\n\n\n---- to go elsewhere\n\n(~>) :: (a' -> a) -> (b -> b') -> ((a -> b) -> (a' -> b'))\n(i ~> o) f = o . f . i\n\n-- result :: (b -> b') -> ((a -> b) -> (a -> b'))\n-- result = (.)\n\n-- argument :: (a' -> a) -> ((a -> b) -> (a' -> b))\n-- argument = flip (.)\n\n-- g ~> f = result g . argument f\n\n\n\ninstance AdditiveGroup a => AdditiveGroup (Gnrx.Rec0 a s) where\n  zeroV = Gnrx.K1 zeroV\n  negateV (Gnrx.K1 v) = Gnrx.K1 $ negateV v\n  Gnrx.K1 v ^+^ Gnrx.K1 w = Gnrx.K1 $ v ^+^ w\n  Gnrx.K1 v ^-^ Gnrx.K1 w = Gnrx.K1 $ v ^-^ w\ninstance AdditiveGroup (f p) => AdditiveGroup (Gnrx.M1 i c f p) where\n  zeroV = Gnrx.M1 zeroV\n  negateV (Gnrx.M1 v) = Gnrx.M1 $ negateV v\n  Gnrx.M1 v ^+^ Gnrx.M1 w = Gnrx.M1 $ v ^+^ w\n  Gnrx.M1 v ^-^ Gnrx.M1 w = Gnrx.M1 $ v ^-^ w\ninstance (AdditiveGroup (f p), AdditiveGroup (g p)) => AdditiveGroup ((f :*: g) p) where\n  zeroV = zeroV :*: zeroV\n  negateV (x:*:y) = negateV x :*: negateV y\n  (x:*:y) ^+^ (\u03be:*:\u03c5) = (x^+^\u03be) :*: (y^+^\u03c5)\n  (x:*:y) ^-^ (\u03be:*:\u03c5) = (x^-^\u03be) :*: (y^-^\u03c5)\n", "meta": {"hexsha": "f2f3f43d0290e3423b87af6effdfdfd7133b43de", "size": 7024, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/AdditiveGroup.hs", "max_stars_repo_name": "k0001/vector-space", "max_stars_repo_head_hexsha": "9f676d08ceaa77cbd284edc1a75bf73d5400cdd9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/AdditiveGroup.hs", "max_issues_repo_name": "k0001/vector-space", "max_issues_repo_head_hexsha": "9f676d08ceaa77cbd284edc1a75bf73d5400cdd9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/AdditiveGroup.hs", "max_forks_repo_name": "k0001/vector-space", "max_forks_repo_head_hexsha": "9f676d08ceaa77cbd284edc1a75bf73d5400cdd9", "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.4372469636, "max_line_length": 105, "alphanum_fraction": 0.6079157175, "num_tokens": 2369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6513548782017746, "lm_q1q2_score": 0.47214779819399844}}
{"text": "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleContexts         #-}\n{-# LANGUAGE FlexibleInstances        #-}\n{-# LANGUAGE BangPatterns             #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Data.Packed.Internal.Matrix\n-- Copyright   :  (c) Alberto Ruiz 2007\n-- License     :  GPL-style\n--\n-- Maintainer  :  Alberto Ruiz <aruiz@um.es>\n-- Stability   :  provisional\n-- Portability :  portable (uses FFI)\n--\n-- Internal matrix representation\n--\n-----------------------------------------------------------------------------\n-- #hide\n\nmodule Data.Packed.Internal.Matrix(\n    Matrix(..), rows, cols, cdat, fdat,\n    MatrixOrder(..), orderOf,\n    createMatrix, mat,\n    cmat, fmat,\n    toLists, flatten, reshape,\n    Element(..),\n    trans,\n    fromRows, toRows, fromColumns, toColumns,\n    matrixFromVector,\n    subMatrix,\n    liftMatrix, liftMatrix2,\n    (@@>), atM',\n    saveMatrix,\n    singleton,\n    size, shSize, conformVs, conformMs, conformVTo, conformMTo\n) where\n\nimport Data.Packed.Internal.Common\nimport Data.Packed.Internal.Signatures\nimport Data.Packed.Internal.Vector\n\nimport Foreign.Marshal.Alloc(alloca, free)\nimport Foreign.Marshal.Array(newArray)\nimport Foreign.Ptr(Ptr, castPtr)\nimport Foreign.Storable(Storable, peekElemOff, pokeElemOff, poke, sizeOf)\nimport Data.Complex(Complex)\nimport Foreign.C.Types\nimport Foreign.C.String(newCString)\nimport System.IO.Unsafe(unsafePerformIO)\nimport Control.DeepSeq\n\n-----------------------------------------------------------------\n\n{- Design considerations for the Matrix Type\n   -----------------------------------------\n\n- we must easily handle both row major and column major order,\n  for bindings to LAPACK and GSL/C\n\n- we'd like to simplify redundant matrix transposes:\n   - Some of them arise from the order requirements of some functions\n   - some functions (matrix product) admit transposed arguments\n\n- maybe we don't really need this kind of simplification:\n   - more complex code\n   - some computational overhead\n   - only appreciable gain in code with a lot of redundant transpositions\n     and cheap matrix computations\n\n- we could carry both the matrix and its (lazily computed) transpose.\n  This may save some transpositions, but it is necessary to keep track of the\n  data which is actually computed to be used by functions like the matrix product\n  which admit both orders.\n\n- but if we need the transposed data and it is not in the structure, we must make\n  sure that we touch the same foreignptr that is used in the computation.\n\n- a reasonable solution is using two constructors for a matrix. Transposition just\n  \"flips\" the constructor. Actual data transposition is not done if followed by a\n  matrix product or another transpose.\n\n-}\n\ndata MatrixOrder = RowMajor | ColumnMajor deriving (Show,Eq)\n\ntransOrder RowMajor = ColumnMajor\ntransOrder ColumnMajor = RowMajor\n{- | Matrix representation suitable for GSL and LAPACK computations.\n\nThe elements are stored in a continuous memory array.\n\n-}\n\ndata Matrix t = Matrix { irows :: {-# UNPACK #-} !Int\n                       , icols :: {-# UNPACK #-} !Int\n                       , xdat :: {-# UNPACK #-} !(Vector t)\n                       , order :: !MatrixOrder }\n-- RowMajor: preferred by C, fdat may require a transposition\n-- ColumnMajor: preferred by LAPACK, cdat may require a transposition\n\ncdat = xdat\nfdat = xdat\n\nrows :: Matrix t -> Int\nrows = irows\n\ncols :: Matrix t -> Int\ncols = icols\n\norderOf :: Matrix t -> MatrixOrder\norderOf = order\n\n\n-- | Matrix transpose.\ntrans :: Matrix t -> Matrix t\ntrans Matrix {irows = r, icols = c, xdat = d, order = o } = Matrix { irows = c, icols = r, xdat = d, order = transOrder o}\n\ncmat :: (Element t) => Matrix t -> Matrix t\ncmat m@Matrix{order = RowMajor} = m\ncmat Matrix {irows = r, icols = c, xdat = d, order = ColumnMajor } = Matrix { irows = r, icols = c, xdat = transdata r d c, order = RowMajor}\n\nfmat :: (Element t) => Matrix t -> Matrix t\nfmat m@Matrix{order = ColumnMajor} = m\nfmat Matrix {irows = r, icols = c, xdat = d, order = RowMajor } = Matrix { irows = r, icols = c, xdat = transdata c d r, order = ColumnMajor}\n\n-- C-Haskell matrix adapter\n-- mat :: Adapt (CInt -> CInt -> Ptr t -> r) (Matrix t) r\n\nmat :: (Storable t) => Matrix t -> (((CInt -> CInt -> Ptr t -> t1) -> t1) -> IO b) -> IO b\nmat a f =\n    unsafeWith (xdat a) $ \\p -> do\n        let m g = do\n            g (fi (rows a)) (fi (cols a)) p\n        f m\n-- | Creates a vector by concatenation of rows. If the matrix is ColumnMajor, this operation requires a transpose.\n--\n-- @\\> flatten ('ident' 3)\n-- 9 |> [1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0]@\nflatten :: Element t => Matrix t -> Vector t\nflatten = xdat . cmat\n\ntype Mt t s = Int -> Int -> Ptr t -> s\n-- not yet admitted by my haddock version\n-- infixr 6 ::>\n-- type t ::> s = Mt t s\n\n-- | the inverse of 'Data.Packed.Matrix.fromLists'\ntoLists :: (Element t) => Matrix t -> [[t]]\ntoLists m = splitEvery (cols m) . toList . flatten $ m\n\n-- | Create a matrix from a list of vectors.\n-- All vectors must have the same dimension,\n-- or dimension 1, which is are automatically expanded.\nfromRows :: Element t => [Vector t] -> Matrix t\nfromRows vs = case compatdim (map dim vs) of\n    Nothing -> error \"fromRows applied to [] or to vectors with different sizes\"\n    Just c  -> reshape c . join . map (adapt c) $ vs\n  where\n    adapt c v | dim v == c = v\n              | otherwise = constantD (v@>0) c\n\n-- | extracts the rows of a matrix as a list of vectors\ntoRows :: Element t => Matrix t -> [Vector t]\ntoRows m = toRows' 0 where\n    v = flatten m\n    r = rows m\n    c = cols m\n    toRows' k | k == r*c  = []\n              | otherwise = subVector k c v : toRows' (k+c)\n\n-- | Creates a matrix from a list of vectors, as columns\nfromColumns :: Element t => [Vector t] -> Matrix t\nfromColumns m = trans . fromRows $ m\n\n-- | Creates a list of vectors from the columns of a matrix\ntoColumns :: Element t => Matrix t -> [Vector t]\ntoColumns m = toRows . trans $ m\n\n-- | Reads a matrix position.\n(@@>) :: Storable t => Matrix t -> (Int,Int) -> t\ninfixl 9 @@>\nm@Matrix {irows = r, icols = c} @@> (i,j)\n    | safe      = if i<0 || i>=r || j<0 || j>=c\n                    then error \"matrix indexing out of range\"\n                    else atM' m i j\n    | otherwise = atM' m i j\n{-# INLINE (@@>) #-}\n\n--  Unsafe matrix access without range checking\natM' Matrix {icols = c, xdat = v, order = RowMajor} i j = v `at'` (i*c+j)\natM' Matrix {irows = r, xdat = v, order = ColumnMajor} i j = v `at'` (j*r+i)\n{-# INLINE atM' #-}\n\n------------------------------------------------------------------\n\nmatrixFromVector o c v = Matrix { irows = r, icols = c, xdat = v, order = o }\n    where (d,m) = dim v `quotRem` c\n          r | m==0 = d\n            | otherwise = error \"matrixFromVector\"\n\n-- allocates memory for a new matrix\ncreateMatrix :: (Storable a) => MatrixOrder -> Int -> Int -> IO (Matrix a)\ncreateMatrix ord r c = do\n    p <- createVector (r*c)\n    return (matrixFromVector ord c p)\n\n{- | Creates a matrix from a vector by grouping the elements in rows with the desired number of columns. (GNU-Octave groups by columns. To do it you can define @reshapeF r = trans . reshape r@\nwhere r is the desired number of rows.)\n\n@\\> reshape 4 ('fromList' [1..12])\n(3><4)\n [ 1.0,  2.0,  3.0,  4.0\n , 5.0,  6.0,  7.0,  8.0\n , 9.0, 10.0, 11.0, 12.0 ]@\n\n-}\nreshape :: Storable t => Int -> Vector t -> Matrix t\nreshape c v = matrixFromVector RowMajor c v\n\nsingleton x = reshape 1 (fromList [x])\n\n-- | application of a vector function on the flattened matrix elements\nliftMatrix :: (Storable a, Storable b) => (Vector a -> Vector b) -> Matrix a -> Matrix b\nliftMatrix f Matrix { icols = c, xdat = d, order = o } = matrixFromVector o c (f d)\n\n-- | application of a vector function on the flattened matrices elements\nliftMatrix2 :: (Element t, Element a, Element b) => (Vector a -> Vector b -> Vector t) -> Matrix a -> Matrix b -> Matrix t\nliftMatrix2 f m1 m2\n    | not (compat m1 m2) = error \"nonconformant matrices in liftMatrix2\"\n    | otherwise = case orderOf m1 of\n        RowMajor    -> matrixFromVector RowMajor    (cols m1) (f (xdat m1) (flatten m2))\n        ColumnMajor -> matrixFromVector ColumnMajor (cols m1) (f (xdat m1) ((xdat.fmat) m2))\n\n\ncompat :: Matrix a -> Matrix b -> Bool\ncompat m1 m2 = rows m1 == rows m2 && cols m1 == cols m2\n\n------------------------------------------------------------------\n\n{- | Supported matrix elements.\n\n    This class provides optimized internal\n    operations for selected element types.\n    It provides unoptimised defaults for any 'Storable' type,\n    so you can create instances simply as:\n    @instance Element Foo@.\n-}\nclass (Storable a) => Element a where\n    subMatrixD :: (Int,Int) -- ^ (r0,c0) starting position \n               -> (Int,Int) -- ^ (rt,ct) dimensions of submatrix\n               -> Matrix a -> Matrix a\n    subMatrixD = subMatrix'\n    transdata :: Int -> Vector a -> Int -> Vector a\n    transdata = transdataP -- transdata'\n    constantD  :: a -> Int -> Vector a\n    constantD = constantP -- constant'\n\n\ninstance Element Float where\n    transdata  = transdataAux ctransF\n    constantD  = constantAux cconstantF\n\ninstance Element Double where\n    transdata  = transdataAux ctransR\n    constantD  = constantAux cconstantR\n\ninstance Element (Complex Float) where\n    transdata  = transdataAux ctransQ\n    constantD  = constantAux cconstantQ\n\ninstance Element (Complex Double) where\n    transdata  = transdataAux ctransC\n    constantD  = constantAux cconstantC\n\n-------------------------------------------------------------------\n\ntransdata' :: Storable a => Int -> Vector a -> Int -> Vector a\ntransdata' c1 v c2 =\n    if noneed\n        then v\n        else unsafePerformIO $ do\n                w <- createVector (r2*c2)\n                unsafeWith v $ \\p ->\n                    unsafeWith w $ \\q -> do\n                        let go (-1) _ = return ()\n                            go !i (-1) = go (i-1) (c1-1)\n                            go !i !j = do x <- peekElemOff p (i*c1+j)\n                                          pokeElemOff      q (j*c2+i) x\n                                          go i (j-1)\n                        go (r1-1) (c1-1)\n                return w\n  where r1 = dim v `div` c1\n        r2 = dim v `div` c2\n        noneed = r1 == 1 || c1 == 1\n\n-- {-# SPECIALIZE transdata' :: Int -> Vector Double -> Int ->  Vector Double #-}\n-- {-# SPECIALIZE transdata' :: Int -> Vector (Complex Double) -> Int -> Vector (Complex Double) #-}\n\n-- I don't know how to specialize...\n-- The above pragmas only seem to work on top level defs\n-- Fortunately everything seems to work using the above class\n\n-- C versions, still a little faster:\n\ntransdataAux fun c1 d c2 =\n    if noneed\n        then d\n        else unsafePerformIO $ do\n            v <- createVector (dim d)\n            unsafeWith d $ \\pd ->\n                unsafeWith v $ \\pv ->\n                    fun (fi r1) (fi c1) pd (fi r2) (fi c2) pv // check \"transdataAux\"\n            return v\n  where r1 = dim d `div` c1\n        r2 = dim d `div` c2\n        noneed = r1 == 1 || c1 == 1\n\ntransdataP :: Storable a => Int -> Vector a -> Int -> Vector a\ntransdataP c1 d c2 =\n    if noneed\n       then d\n       else unsafePerformIO $ do\n          v <- createVector (dim d)\n          unsafeWith d $ \\pd ->\n              unsafeWith v $ \\pv ->\n                  ctransP (fi r1) (fi c1) (castPtr pd) (fi sz) (fi r2) (fi c2) (castPtr pv) (fi sz) // check \"transdataP\"\n          return v\n   where r1 = dim d `div` c1\n         r2 = dim d `div` c2\n         sz = sizeOf (d @> 0)\n         noneed = r1 == 1 || c1 == 1\n\nforeign import ccall unsafe \"transF\" ctransF :: TFMFM\nforeign import ccall unsafe \"transR\" ctransR :: TMM\nforeign import ccall unsafe \"transQ\" ctransQ :: TQMQM\nforeign import ccall unsafe \"transC\" ctransC :: TCMCM\nforeign import ccall unsafe \"transP\" ctransP :: CInt -> CInt -> Ptr () -> CInt -> CInt -> CInt -> Ptr () -> CInt -> IO CInt\n\n----------------------------------------------------------------------\n\nconstant' v n = unsafePerformIO $ do\n    w <- createVector n\n    unsafeWith w $ \\p -> do\n        let go (-1) = return ()\n            go !k = pokeElemOff p k v >> go (k-1)\n        go (n-1)\n    return w\n\n-- C versions\n\nconstantAux fun x n = unsafePerformIO $ do\n    v <- createVector n\n    px <- newArray [x]\n    app1 (fun px) vec v \"constantAux\"\n    free px\n    return v\n\nconstantF :: Float -> Int -> Vector Float\nconstantF = constantAux cconstantF\nforeign import ccall unsafe \"constantF\" cconstantF :: Ptr Float -> TF\n\nconstantR :: Double -> Int -> Vector Double\nconstantR = constantAux cconstantR\nforeign import ccall unsafe \"constantR\" cconstantR :: Ptr Double -> TV\n\nconstantQ :: Complex Float -> Int -> Vector (Complex Float)\nconstantQ = constantAux cconstantQ\nforeign import ccall unsafe \"constantQ\" cconstantQ :: Ptr (Complex Float) -> TQV\n\nconstantC :: Complex Double -> Int -> Vector (Complex Double)\nconstantC = constantAux cconstantC\nforeign import ccall unsafe \"constantC\" cconstantC :: Ptr (Complex Double) -> TCV\n\nconstantP :: Storable a => a -> Int -> Vector a\nconstantP a n = unsafePerformIO $ do\n    let sz = sizeOf a\n    v <- createVector n\n    unsafeWith v $ \\p -> do\n       alloca $ \\k -> do\n                      poke k a\n                      cconstantP (castPtr k) (fi n) (castPtr p) (fi sz) // check \"constantP\"\n    return v\nforeign import ccall unsafe \"constantP\" cconstantP :: Ptr () -> CInt -> Ptr () -> CInt -> IO CInt\n\n----------------------------------------------------------------------\n\n-- | Extracts a submatrix from a matrix.\nsubMatrix :: Element a\n          => (Int,Int) -- ^ (r0,c0) starting position \n          -> (Int,Int) -- ^ (rt,ct) dimensions of submatrix\n          -> Matrix a -- ^ input matrix\n          -> Matrix a -- ^ result\nsubMatrix (r0,c0) (rt,ct) m\n    | 0 <= r0 && 0 < rt && r0+rt <= (rows m) &&\n      0 <= c0 && 0 < ct && c0+ct <= (cols m) = subMatrixD (r0,c0) (rt,ct) m\n    | otherwise = error $ \"wrong subMatrix \"++\n                          show ((r0,c0),(rt,ct))++\" of \"++show(rows m)++\"x\"++ show (cols m)\n\nsubMatrix'' (r0,c0) (rt,ct) c v = unsafePerformIO $ do\n    w <- createVector (rt*ct)\n    unsafeWith v $ \\p ->\n        unsafeWith w $ \\q -> do\n            let go (-1) _ = return ()\n                go !i (-1) = go (i-1) (ct-1)\n                go !i !j = do x <- peekElemOff p ((i+r0)*c+j+c0)\n                              pokeElemOff      q (i*ct+j) x\n                              go i (j-1)\n            go (rt-1) (ct-1)\n    return w\n\nsubMatrix' (r0,c0) (rt,ct) (Matrix { icols = c, xdat = v, order = RowMajor}) = Matrix rt ct (subMatrix'' (r0,c0) (rt,ct) c v) RowMajor\nsubMatrix' (r0,c0) (rt,ct) m = trans $ subMatrix' (c0,r0) (ct,rt) (trans m)\n\n--------------------------------------------------------------------------\n\n-- | Saves a matrix as 2D ASCII table.\nsaveMatrix :: FilePath\n           -> String     -- ^ format (%f, %g, %e)\n           -> Matrix Double\n           -> IO ()\nsaveMatrix filename fmt m = do\n    charname <- newCString filename\n    charfmt <- newCString fmt\n    let o = if orderOf m == RowMajor then 1 else 0\n    app1 (matrix_fprintf charname charfmt o) mat m \"matrix_fprintf\"\n    free charname\n    free charfmt\n\nforeign import ccall unsafe \"matrix_fprintf\" matrix_fprintf :: Ptr CChar -> Ptr CChar -> CInt -> TM\n\n----------------------------------------------------------------------\n\nconformMs ms = map (conformMTo (r,c)) ms\n  where\n    r = maximum (map rows ms)\n    c = maximum (map cols ms)\n\nconformVs vs = map (conformVTo n) vs\n  where\n    n = maximum (map dim vs)\n\nconformMTo (r,c) m\n    | size m == (r,c) = m\n    | size m == (1,1) = reshape c (constantD (m@@>(0,0)) (r*c))\n    | size m == (r,1) = repCols c m\n    | size m == (1,c) = repRows r m\n    | otherwise = error $ \"matrix \" ++ shSize m ++ \" cannot be expanded to (\" ++ show r ++ \"><\"++ show c ++\")\"\n\nconformVTo n v\n    | dim v == n = v\n    | dim v == 1 = constantD (v@>0) n\n    | otherwise = error $ \"vector of dim=\" ++ show (dim v) ++ \" cannot be expanded to dim=\" ++ show n\n\nrepRows n x = fromRows (replicate n (flatten x))\nrepCols n x = fromColumns (replicate n (flatten x))\n\nsize m = (rows m, cols m)\n\nshSize m = \"(\" ++ show (rows m) ++\"><\"++ show (cols m)++\")\"\n\n----------------------------------------------------------------------\n\ninstance (Storable t, NFData t) => NFData (Matrix t)\n  where\n    rnf m | d > 0     = rnf (v @> 0)\n          | otherwise = ()\n      where\n        d = dim v\n        v = xdat m\n\n", "meta": {"hexsha": "255009c92d5076c052bb8836951c494b9a921153", "size": 16542, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Data/Packed/Internal/Matrix.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/Data/Packed/Internal/Matrix.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/Data/Packed/Internal/Matrix.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": 35.1210191083, "max_line_length": 192, "alphanum_fraction": 0.575927941, "num_tokens": 4675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.47178881326965866}}
{"text": "{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PackageImports        #-}\n\nmodule FPNLA.Matrix.Instances.HMatrix () where\n\nimport           Control.DeepSeq               (NFData (rnf))\nimport           Control.Parallel.Strategies   (rseq, withStrategy)\nimport \"hmatrix\" Numeric.LinearAlgebra hiding  (Matrix, Vector)\n--import           Numeric.LinearAlgebra.HMatrix\n--import \"hmatrix\" Numeric.LinearAlgebra         (buildVector)\nimport           Numeric.LinearAlgebra.HMatrix hiding (Matrix, Vector)\nimport qualified Numeric.LinearAlgebra.HMatrix  as HM (Matrix, Vector)\nimport           FPNLA.Matrix                  (Matrix (generate_m, fromList_m, transpose_m, dim_m, elem_m, subMatrix_m, fromBlocks_m, toBlocks_m, map_m), MatrixVector (fromCols_vm, toCols_vm, row_vm, col_vm), Vector (generate_v, fromList_v, concat_v, elem_v, length_v, foldr_v, map_v, zipWith_v))\n{-\ninstance (NFData e) => NFData (Vector e) where\n    -- Asumo que Vector es estricto\n    -- http://haskell.1045720.n5.nabble.com/NFData-instance-for-Numeric-LinearAlgebra-Matrix-td4265725.html\n    rnf v = (withStrategy rseq v) `seq` ()\n\ninstance (NFData e) => NFData (Matrix e) where\n    -- Matrix es estricto\n    -- http://haskell.1045720.n5.nabble.com/NFData-instance-for-Numeric-LinearAlgebra-Matrix-td4265725.html\n    rnf m = withStrategy rseq m `seq` ()\n-}\n\nbuildVector :: Int -> (Int -> e) -> HM.Vector e\nbuildVector size f = undefined\n\nbuildMatrix :: Int -> Int -> (Int -> Int -> e) -> HM.Matrix e\nbuildMatrix rows cols f = undefined\n\ninstance (Element e) => Vector HM.Vector e where\n    generate_v = buildVector\n    fromList_v = fromList\n    concat_v = undefined -- joinsas\n    elem_v pos v = undefined -- v @> pos\n    length_v = undefined -- dim\n    foldr_v = undefined -- foldVector\n    map_v = undefined -- mapVector\n    zipWith_v = undefined -- zipVectorWith\n\ninstance (Element e) => Matrix HM.Matrix e where\n    generate_m = buildMatrix\n    fromList_m = (><)\n    transpose_m = undefined -- trans\n    dim_m m = (rows m, cols m)\n    elem_m i j m = undefined -- m @@> (i, j)\n    map_m = undefined -- mapMatrix\n    --zipWith_m\n    subMatrix_m posI posJ cantRows cantCols = subMatrix (posI, posJ) (cantRows, cantCols)\n    fromBlocks_m = fromBlocks\n    toBlocks_m = toBlocksEvery\n\ninstance (Element e) => MatrixVector HM.Matrix HM.Vector e where\n    row_vm pos m = toRows m !! pos\n    col_vm pos m = toColumns m !! pos\n    fromCols_vm = fromColumns\n    toCols_vm = toColumns\n", "meta": {"hexsha": "e9c5d9dc154f70ee5aa60f8d5f22e62e6fdca9f8", "size": 2495, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FPNLA/Matrix/Instances/HMatrix.hs", "max_stars_repo_name": "mauroblanco/fpnla-examples", "max_stars_repo_head_hexsha": "f632e4329f604af8ab13fddf8c568b1e3a5229d7", "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/FPNLA/Matrix/Instances/HMatrix.hs", "max_issues_repo_name": "mauroblanco/fpnla-examples", "max_issues_repo_head_hexsha": "f632e4329f604af8ab13fddf8c568b1e3a5229d7", "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/FPNLA/Matrix/Instances/HMatrix.hs", "max_forks_repo_name": "mauroblanco/fpnla-examples", "max_forks_repo_head_hexsha": "f632e4329f604af8ab13fddf8c568b1e3a5229d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5833333333, "max_line_length": 297, "alphanum_fraction": 0.6853707415, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.47175610219605946}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes                      #-}\n{-# LANGUAGE ConstraintKinds                          #-}\n{-# LANGUAGE DataKinds                                #-}\n{-# LANGUAGE DefaultSignatures                        #-}\n{-# LANGUAGE FlexibleContexts                         #-}\n{-# LANGUAGE FlexibleInstances                        #-}\n{-# LANGUAGE GADTs                                    #-}\n{-# LANGUAGE RankNTypes                               #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeFamilies                             #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# LANGUAGE UndecidableInstances                     #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise       #-}\n\nmodule Backprop.Learn.Initialize (\n    Initialize(..)\n  , gInitialize\n  , initializeNormal\n  , initializeSingle\n  -- * Reshape\n  , reshapeR\n  , reshapeLRows\n  , reshapeLCols\n  ) where\n\nimport           Control.Monad.Primitive\nimport           Data.Complex\nimport           Data.Proxy\nimport           Data.Type.Equality\nimport           Data.Type.Tuple\nimport           Data.Vinyl\nimport           GHC.TypeLits.Compare\nimport           GHC.TypeNats\nimport           Generics.OneLiner\nimport           Numeric.LinearAlgebra.Static.Vector\nimport           Statistics.Distribution\nimport           Statistics.Distribution.Normal\nimport qualified Data.Vector.Generic                 as VG\nimport qualified Data.Vector.Generic.Sized           as SVG\nimport qualified Numeric.LinearAlgebra.Static        as H\nimport qualified System.Random.MWC                   as MWC\n\n-- | Class for types that are basically a bunch of 'Double's, which can be\n-- initialized with a given identical and independent distribution.\nclass Initialize p where\n    initialize\n        :: (ContGen d, PrimMonad m)\n        => d\n        -> MWC.Gen (PrimState m)\n        -> m p\n\n    default initialize\n        :: (ADTRecord p, Constraints p Initialize, ContGen d, PrimMonad m)\n        => d\n        -> MWC.Gen (PrimState m)\n        -> m p\n    initialize = gInitialize\n\n-- | 'initialize' for any instance of 'Generic'.\ngInitialize\n    :: (ADTRecord p, Constraints p Initialize, ContGen d, PrimMonad m)\n    => d\n    -> MWC.Gen (PrimState m)\n    -> m p\ngInitialize d g = createA' @Initialize (initialize d g)\n\n-- | Helper over 'inititialize' for a gaussian distribution centered around\n-- zero.\ninitializeNormal\n    :: (Initialize p, PrimMonad m)\n    => Double                               -- ^ standard deviation\n    -> MWC.Gen (PrimState m)\n    -> m p\ninitializeNormal = initialize . normalDistr 0\n\n-- | 'initialize' definition if @p@ is a single number.\ninitializeSingle\n    :: (ContGen d, PrimMonad m, Fractional p)\n    => d\n    -> MWC.Gen (PrimState m)\n    -> m p\ninitializeSingle d = fmap realToFrac . genContVar d\n\ninstance Initialize Double where\n    initialize = initializeSingle\ninstance Initialize Float where\n    initialize = initializeSingle\n\n-- | Initializes real and imaginary components identically\ninstance Initialize a => Initialize (Complex a) where\n\ninstance Initialize T0\ninstance Initialize a => Initialize (TF a)\ninstance (Initialize a, Initialize b) => Initialize (a :# b)\n\ninstance RPureConstrained Initialize as => Initialize (T as) where\n    initialize d g = rtraverse (fmap TF)\n                   $ rpureConstrained @Initialize (initialize d g)\n\n-- instance (Initialize a, ListC (Initialize <$> as), Known Length as) => Initialize (NETup (a ':| as)) where\n--     initialize d g = NET <$> initialize d g\n--                          <*> initialize d g\n\ninstance Initialize ()\ninstance (Initialize a, Initialize b) => Initialize (a, b)\ninstance (Initialize a, Initialize b, Initialize c) => Initialize (a, b, c)\ninstance (Initialize a, Initialize b, Initialize c, Initialize d) => Initialize (a, b, c, d)\ninstance (Initialize a, Initialize b, Initialize c, Initialize d, Initialize e) => Initialize (a, b, c, d, e)\n\ninstance (VG.Vector v a, KnownNat n, Initialize a) => Initialize (SVG.Vector v n a) where\n    initialize d = SVG.replicateM . initialize d\n\ninstance KnownNat n => Initialize (H.R n) where\n    initialize d = fmap vecR . initialize d\ninstance KnownNat n => Initialize (H.C n) where\n    initialize d = fmap vecC . initialize d\n\ninstance (KnownNat n, KnownNat m) => Initialize (H.L n m) where\n    initialize d = fmap vecL . initialize d\ninstance (KnownNat n, KnownNat m) => Initialize (H.M n m) where\n    initialize d = fmap vecM . initialize d\n\n-- | Reshape a vector to have a different amount of items  If the matrix is\n-- grown, new weights are initialized according to the given distribution.\nreshapeR\n    :: forall i j d m. (ContGen d, PrimMonad m, KnownNat i, KnownNat j)\n    => d\n    -> MWC.Gen (PrimState m)\n    -> H.R i\n    -> m (H.R j)\nreshapeR d g x = case Proxy @j %<=? Proxy @i of\n    LE  Refl      -> pure . vecR . SVG.take @_ @j @(i - j) . rVec $ x\n    NLE Refl Refl -> (x H.#) <$> initialize @(H.R (j - i)) d g\n\n-- | Reshape a matrix to have a different amount of rows  If the matrix\n-- is grown, new weights are initialized according to the given\n-- distribution.\nreshapeLRows\n    :: forall i j n d m. (ContGen d, PrimMonad m, KnownNat n, KnownNat i, KnownNat j)\n    => d\n    -> MWC.Gen (PrimState m)\n    -> H.L i n\n    -> m (H.L j n)\nreshapeLRows d g x = case Proxy @j %<=? Proxy @i of\n    LE Refl       -> pure . rowsL . SVG.take @_ @j @(i - j) . lRows $ x\n    NLE Refl Refl -> (x H.===) <$> initialize @(H.L (j - i) n) d g\n\n-- | Reshape a matrix to have a different amount of columns.  If the matrix\n-- is grown, new weights are initialized according to the given\n-- distribution.\nreshapeLCols\n    :: forall i j n d m. (ContGen d, PrimMonad m, KnownNat n, KnownNat i, KnownNat j)\n    => d\n    -> MWC.Gen (PrimState m)\n    -> H.L n i\n    -> m (H.L n j)\nreshapeLCols d g x = case Proxy @j %<=? Proxy @i of\n    LE Refl       -> pure . colsL . SVG.take @_ @j @(i - j) . lCols $ x\n    NLE Refl Refl -> (x H.|||) <$> initialize @(H.L n (j - i)) d g\n", "meta": {"hexsha": "69de165038d609b0082d48ef6beedb8186b33fa5", "size": 6134, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Backprop/Learn/Initialize.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "src/Backprop/Learn/Initialize.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "src/Backprop/Learn/Initialize.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 37.8641975309, "max_line_length": 109, "alphanum_fraction": 0.6116726443, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.47169617753214255}}
{"text": "module Mnist where\n\n  import Numeric.LinearAlgebra\n  import System.Environment\n\n  import Neural\n  import Test\n  import Mnist.Load\n\n  main :: IO ()\n  main = do\n    mnist <- loadExamples\n    learningRate <- (getArgs >>= (\\args -> (return.read) $ head args))\n    epoch <- (getArgs >>= (\\args -> (return.read) $ args!!1))\n    let dataSet = splitDataSet mnist\n    runSuite epoch learningRate networkSetting dataSet\n\n  -- one hidden layer with 300 nodes\n  networkSetting = [10, 300]\n", "meta": {"hexsha": "44c58d839432110b714636a6e1812ec588884c52", "size": 477, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Mnist.hs", "max_stars_repo_name": "ycjungSubhuman/hskmlp", "max_stars_repo_head_hexsha": "e30a8f5ffab52b373090be7b7d2990670bc177e3", "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/Mnist.hs", "max_issues_repo_name": "ycjungSubhuman/hskmlp", "max_issues_repo_head_hexsha": "e30a8f5ffab52b373090be7b7d2990670bc177e3", "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/Mnist.hs", "max_forks_repo_name": "ycjungSubhuman/hskmlp", "max_forks_repo_head_hexsha": "e30a8f5ffab52b373090be7b7d2990670bc177e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.85, "max_line_length": 70, "alphanum_fraction": 0.6729559748, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.47151881712704174}}
{"text": "module TwoMoon where\n\n  import Numeric.LinearAlgebra\n  import System.Environment\n\n  import Neural\n  import Test\n  import TwoMoon.Load\n\n  main :: IO ()\n  main = do\n    twomoon <- loadExamples\n    learningRate <- (getArgs >>= (\\args -> (return.read) $ head args))\n    epoch <- (getArgs >>= (\\args -> (return.read) $ args!!1))\n    let dataSet = splitDataSet twomoon\n    runSuite epoch learningRate networkSetting dataSet\n\n  -- two hidden layer with 20, 10 nodes each\n  networkSetting = [2, 4]\n\n", "meta": {"hexsha": "5b26702fc1260a6d3e26200b30c26227918d0a0b", "size": 491, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/TwoMoon.hs", "max_stars_repo_name": "ycjungSubhuman/hskmlp", "max_stars_repo_head_hexsha": "e30a8f5ffab52b373090be7b7d2990670bc177e3", "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/TwoMoon.hs", "max_issues_repo_name": "ycjungSubhuman/hskmlp", "max_issues_repo_head_hexsha": "e30a8f5ffab52b373090be7b7d2990670bc177e3", "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/TwoMoon.hs", "max_forks_repo_name": "ycjungSubhuman/hskmlp", "max_forks_repo_head_hexsha": "e30a8f5ffab52b373090be7b7d2990670bc177e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.380952381, "max_line_length": 70, "alphanum_fraction": 0.6741344196, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4714984910685622}}
{"text": "{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DeriveAnyClass        #-}\n{-# LANGUAGE DeriveGeneric         #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedLabels      #-}\n{-# LANGUAGE OverloadedStrings     #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-|\nModule      : Grenade.Layers.LeakyRelu\nDescription : Rectifying linear unit layer\nCopyright   : (c) Manuel Schneckenreither, 2020\nLicense     : BSD2\nStability   : experimental\n-}\nmodule Grenade.Layers.LeakyRelu (\n    LeakyRelu (..)\n  ) where\n\nimport           Control.DeepSeq                (NFData (..))\nimport           Data.Proxy                     (Proxy(Proxy))\nimport           Data.Maybe                     (fromJust)\nimport           Data.Serialize\nimport           GHC.Generics                   (Generic)\nimport           GHC.TypeLits\nimport qualified Numeric.LinearAlgebra.Static   as H\n\nimport           Grenade.Core\nimport           Grenade.Onnx\nimport           Grenade.Types\nimport           Grenade.Layers.Internal.Activations\n\n\n-- | A rectifying linear unit.\n--   A layer which can act between any shape of the same dimension, acting as a\n--   diode on every neuron individually.\nnewtype LeakyRelu = LeakyRelu RealNum\n  deriving (Generic, NFData, Show)\n\ninstance UpdateLayer LeakyRelu where\n  type Gradient LeakyRelu = ()\n  runUpdate _ x _ = x\n  reduceGradient _ = ()\n\ninstance RandomLayer LeakyRelu where\n  createRandomWith _ _ = return $ LeakyRelu 0.01\n\ninstance Serialize LeakyRelu where\n  put (LeakyRelu alpha) = put alpha\n  get = LeakyRelu <$> get\n\ninstance (KnownNat i) => Layer LeakyRelu ('D1 i) ('D1 i) where\n  type Tape LeakyRelu ('D1 i) ('D1 i) = S ('D1 i)\n\n  runForwards (LeakyRelu alpha) (S1D y) = (S1D y, (S1D . fromJust . H.create) relu)\n    where\n      w    = fromIntegral $ natVal (Proxy :: Proxy i)\n      relu = leakyRelu1d w alpha (H.extract y)\n\n  runBackwards (LeakyRelu alpha) (S1D y) (S1D dEdy) = ((), S1D (relu' y * dEdy))\n    where\n      relu' = H.dvmap (\\a -> if a < 0 then alpha else 1)\n\ninstance (KnownNat i, KnownNat j) => Layer LeakyRelu ('D2 i j) ('D2 i j) where\n  type Tape LeakyRelu ('D2 i j) ('D2 i j) = S ('D2 i j)\n\n  runForwards (LeakyRelu alpha) (S2D y) = (S2D y, (S2D . fromJust . H.create) relu)\n    where\n      h    = fromIntegral $ natVal (Proxy :: Proxy i)\n      w    = fromIntegral $ natVal (Proxy :: Proxy j)\n      y'   = H.extract y\n      relu = leakyRelu 1 h w alpha y'\n\n  runBackwards (LeakyRelu alpha) (S2D y) (S2D dEdy) = ((), S2D (relu' y * dEdy))\n    where\n      relu' = H.dmmap (\\a -> if a < 0 then alpha else 1)\n\ninstance (KnownNat i, KnownNat j, KnownNat k) => Layer LeakyRelu ('D3 i j k) ('D3 i j k) where\n\n  type Tape LeakyRelu ('D3 i j k) ('D3 i j k) = S ('D3 i j k)\n\n  runForwards (LeakyRelu alpha) (S3D y) = (S3D y, (S3D . fromJust . H.create) relu)\n    where\n      c    = fromIntegral $ natVal (Proxy :: Proxy k)\n      h    = fromIntegral $ natVal (Proxy :: Proxy i)\n      w    = fromIntegral $ natVal (Proxy :: Proxy j)\n      y'   = H.extract y\n      relu = leakyRelu c h w alpha y'\n\n  runBackwards (LeakyRelu alpha) (S3D y) (S3D dEdy) = ((), S3D (relu' y * dEdy))\n    where\n      relu' = H.dmmap (\\a -> if a < 0 then alpha else 1)\n\ninstance OnnxOperator LeakyRelu where\n  onnxOpTypeNames _ = [\"LeakyRelu\"]\n\ninstance OnnxLoadable LeakyRelu where\n  loadOnnxNode _ node = do\n    alpha <- readFloatAttributeToRealNum \"alpha\" node\n\n    return $ LeakyRelu alpha\n", "meta": {"hexsha": "5b9d1f5f1a5d0a05d45b2ed1058a1c57c2950c4d", "size": 3529, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/LeakyRelu.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/LeakyRelu.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/LeakyRelu.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9326923077, "max_line_length": 94, "alphanum_fraction": 0.6177387362, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47133306867598346}}
{"text": "module Scene.Material.Skylike where\n\nimport Numeric.LinearAlgebra\n\nimport Scene.Base\nimport Math.Color\nimport Math.Ray\nimport Scene.Monad\n\nimport Control.Applicative\nimport Control.Monad.Random\n\nskylike :: Color -> Color -> Material\nskylike near far (Ray p normal) (Ray q incidence) = do\n    let t = abs $ (normal <.> incidence)/(norm_2 normal * norm_2 incidence)\n    return $! weigh [(t,near),(1-t,far)]", "meta": {"hexsha": "709fa7a605b7cc1efbe2f09732e83abff0f28424", "size": 404, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Scene/Material/Skylike.hs", "max_stars_repo_name": "danrocag/raytracer", "max_stars_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "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/Scene/Material/Skylike.hs", "max_issues_repo_name": "danrocag/raytracer", "max_issues_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "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/Scene/Material/Skylike.hs", "max_forks_repo_name": "danrocag/raytracer", "max_forks_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.25, "max_line_length": 75, "alphanum_fraction": 0.7376237624, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4712839129698166}}
{"text": "{-# LANGUAGE ConstraintKinds        #-}\n{-# LANGUAGE FlexibleContexts       #-}\n{-# LANGUAGE FlexibleInstances      #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE GADTs                  #-}\n{-# LANGUAGE InstanceSigs           #-}\n{-# LANGUAGE MultiParamTypeClasses  #-}\n{-# LANGUAGE QuantifiedConstraints  #-}\n{-# LANGUAGE RankNTypes             #-}\n{-# LANGUAGE TemplateHaskell        #-}\n{-# LANGUAGE TypeOperators          #-}\n{-# LANGUAGE UndecidableInstances   #-}\n\nmodule Q.Stats.Arima where\nimport           Control.Monad.State\nimport           Data.Foldable\nimport           Data.Functor.Identity\nimport           Data.Random\nimport           Data.Random.Source\nimport           Data.RVar\nimport           Data.Time\nimport           Numeric.LinearAlgebra\nimport           Q.Stats.TimeSeries\nimport           System.Random.Mersenne.Pure64\nimport           Data.Random.Distribution\nimport           Data.Random.Distribution.Poisson\nimport           Data.Random.Distribution.T\nimport           Data.RVar\nimport           Statistics.Sample\n\ndata Ewma d = Ewma Double d\n\n--ll :: (Ewma d) -> [DataPoint Double] -> (Double -> Double)\nll (Ewma lambda d) datapoints = mapM ll_ datapoints where\n  ll_ :: DataPoint LocalTime Double -> State Double Double\n  ll_ x@(DataPoint _ v) = do\n    vart <- get\n    let vart2 = lambda * vart + (1 - lambda) * v * v\n    put vart2\n    return $ logPdf d (sqrt (v  * v / vart))\n\n\n--forecast :: (Distribution d Double) => (Ewma d) -> Int ->\nforecast :: forall d. (Distribution d Double) => Ewma (d Double) -> StateT Double RVar Double\nforecast (Ewma lambda d) = do\n  y <- lift $ rvar d\n  vart <- get\n  let vart2 = lambda * vart + (1 - lambda) * y * y\n  put vart2\n  return (y * sqrt vart)\n\n\n--forecastN :: Distribution d Double => Ewma (d Double) -> Int -> Double -> RVar ([Double], Double)\nforecastN ewma var0 n =  sample $ runStateT (replicateM n (forecast ewma)) var0\n\n", "meta": {"hexsha": "fb792265c2f8c85a8bede13fc87a53dd1ae31590", "size": 1911, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Q/Stats/Arima.hs", "max_stars_repo_name": "ghais/lowq", "max_stars_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-01T17:50:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T18:06:22.000Z", "max_issues_repo_path": "src/Q/Stats/Arima.hs", "max_issues_repo_name": "ghais/lowq", "max_issues_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "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/Q/Stats/Arima.hs", "max_forks_repo_name": "ghais/lowq", "max_forks_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "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.125, "max_line_length": 99, "alphanum_fraction": 0.6195709053, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.47116941614362035}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- | Various tests\nmodule Main where\n\n\nimport AI.Network.RNN.LSTM\nimport AI.Network.RNN.RNN\nimport AI.Network.RNN.Genetic\nimport AI.Network.RNN.Data\nimport AI.Network.RNN.Types\nimport AI.Network.RNN.Util\nimport AI.Network.RNN.Expr\n\nimport Test.Tasty\nimport Test.Tasty.HUnit\nimport Test.Tasty.QuickCheck\n\nimport qualified Numeric.LinearAlgebra.HMatrix as M\n\nimport Control.Monad.Random\nimport qualified Data.Text as T\nimport qualified Data.Set as DS\n\nimport Data.Char\nimport Data.List\nimport Numeric\n\nimport Debug.Trace\n\nimport Numeric.AD\nimport qualified Data.IntMap as I\nimport Text.PrettyPrint.HughesPJClass\n\nmain :: IO()\nmain = defaultMain tests\n\ntests :: TestTree\ntests = testGroup \"Tests\"\n    [  testGroup \"Utils\" [\n          testProperty \"Matrix/vector product\" prop_product\n        , testCase \"takes\" $ do\n            let l=[1,2,3,4,5,6]::[Int]\n            [[1],[2,3],[4,5,6]] @=? takes ([1,2,3]::[Int]) l\n            [[],[],[]] @=? takes [1,2,3] ([]::[Int])\n        , testProperty \"takes keep all data in order\" prop_takes_concat\n        , testProperty \"takes has proper number of lists\" prop_takes_length\n        , testProperty \"binary digits\" prop_binary_digits\n        , testCase \"softmax\" $ do\n            let l=[1,2,3,4,5,6]::[Double]\n                sf=softmax l\n            sum sf @?= 1\n        , testProperty \"euclidian\" prop_euclidian\n        , testProperty \"equilateral size\" prop_equilateral_size\n        , testProperty \"equilateral distance\" prop_equilateral_distance\n        , testProperty \"equilateral decoding\" prop_equilateral_decoding\n       ]\n     , testGroup \"RNN\" [\n        testCase \"Check Steps without Back\" $ checkSteps False\n        , testCase \"Check Steps with Back\" $ checkSteps True\n        , testCase \"Check array conversion without Back\" $ checkArray False\n        , testCase \"Check array conversion with Back\" $ checkArray True\n        , testCase \"Check vector conversion without Back\" $ checkArray False\n        , testCase \"Check vector conversion with Back\" $ checkArray True\n        ]\n     , testGroup \"Data\" [\n        testCase \"Text\" $ do\n            testTextData \"hello\"\n            testTextData \"hello world!\"\n        , testCase \"Text Sparse\" $ do\n            testTextDataS \"hello\"\n            testTextDataS \"hello world!\"\n     , testGroup \"Genetic\" [\n            testCase \"MixVector\" $ do\n                let v1 = M.fromList [1,1,1,1]\n                let v2 = M.fromList [2,2,2,2]\n                (v3,v4) <- evalRandIO $ mixVector v1 v2 0.5\n                (v3 /= v4) @? \"v3 == v4\"\n                M.size v1 @=? M.size v3\n                M.size v1 @=? M.size v4\n            , testCase \"crossNetworkFull\" $ testCrossover crossNetworkFull\n            , testCase \"crossNetworkHalf\" $ testCrossover crossNetworkHalf\n            , testCase \"pointMutation\" $ testMutation pointMutation\n            , testCase \"swapMutation\" $ testMutation swapMutation\n            , testCase \"insertMutation\" $ testMutation insertMutation\n        ]\n      , testGroup \"LSTM\" [\n            testCase \"Check steps\" checkLSTMSteps\n          , testProperty \"Property steps\" prop_lstm_eval_steps\n          , testCase \"Check vector conversion\" checkLSTMVector\n          , testProperty \"list and vector match\" prop_lstm_step\n          , testCase \"Check list of LSTMs\" checkLSTMList\n          , testProperty \"Property list\" prop_lstm_list\n        ]\n       , testGroup \"LSTMIO\" [\n            testCase \"LSTMIO basics\" checkLSTMIO\n        ]\n       , testGroup \"Expr\" [\n            testCase \"Expr basics\" testExpr\n        ]\n     ]\n    ]\n\nprop_product :: MatrixVector -> Bool\nprop_product (MatrixVector sz ms vs) =\n    let l=listMProd ms vs\n        m=M.toList (M.matrix sz ms M.#> M.vector vs)\n    in l == m -- (trace (show l) l)  == (trace (show m) m)\n\ndata MatrixVector = MatrixVector Int [Double] [Double]\n    deriving (Show,Read,Eq,Ord)\n\ninstance Arbitrary MatrixVector where\n    arbitrary = do\n        Positive rows<-arbitrary\n        Positive cols<-arbitrary\n        ms <- vector (rows*cols)\n        vs <- vector cols\n        return $ MatrixVector cols ms vs\n\nprop_takes_concat ::  String -> [Positive Int] -> Bool\nprop_takes_concat xs ps = let\n    idxs = map getPositive ps\n    tot = sum idxs\n    in concat (takes idxs xs) == take tot xs\n\nprop_takes_length ::  String -> [Positive Int] -> Bool\nprop_takes_length xs ps = let\n    idxs = map getPositive ps\n    in length (takes idxs xs) == length ps\n\nprop_binary_digits :: Positive Int -> Bool\nprop_binary_digits (Positive a) = binaryDigits a == length (showIntAtBase 2 intToDigit a \"\")\n\n\ndata EuclidianData = EuclidianData [Double] [Double]\n    deriving Show\n\ninstance Arbitrary EuclidianData where\n    arbitrary = do\n        Positive sz<-arbitrary\n        is1 <- vector sz\n        is2 <- vector sz\n        return $ EuclidianData is1 is2\n\nprop_euclidian :: EuclidianData -> Bool\nprop_euclidian (EuclidianData ds1 ds2) =\n    euclidian (M.fromList ds1) (M.fromList ds2)\n        == sum (map (\\x->x*x) $ zipWith (-) ds2 ds1)\n\nprop_equilateral_size :: Positive Int -> Bool\nprop_equilateral_size (Positive n) =\n    let m = equilateralEncoding n\n    in (n,n-1) == (M.rows m,M.cols m)\n\nprop_equilateral_distance :: Positive Int -> Bool\nprop_equilateral_distance (Positive n) =\n    let m = equilateralEncoding (n+1)\n        ts = M.toRows m\n        pairs = concatMap (\\(x:ys)->map (\\y->(x,y)) ys) $ init $ tails ts\n        dis = map (roundTo 5 . uncurry euclidian) pairs\n    in 1 == length (ordNub dis)\n\nprop_equilateral_decoding :: Positive Int -> Bool\nprop_equilateral_decoding (Positive n) =\n    let rn = n + 1\n        m  = equilateralEncoding rn\n        vs= M.toRows m\n        rs = map (equilateralDecoding m) vs\n    in rs == [0..n]\n\ntestTextData :: T.Text -> IO()\ntestTextData t = do\n    let (TrainData isSt is sz m) = textToTrainData t\n    let charSet = T.foldl (flip DS.insert) DS.empty t\n    DS.size charSet @=? sz+1\n    t @=? dataToText m is\n    T.init t @=? dataToText m (tail isSt)\n\ntestTextDataS :: T.Text -> IO()\ntestTextDataS t = do\n    let (TrainData isSt is sz m) = textToTrainDataS t\n    -- let charSet = T.foldl (flip DS.insert) DS.empty t\n    -- sparseSize (DS.size charSet) @=? sz\n    t @=? dataToTextS m is\n    T.init t @=? dataToTextS m (tail isSt)\n\ncheckSteps :: Bool -> IO ()\ncheckSteps back = do\n    (n::RNNetwork) <- evalRandIO $ randomNetwork (RNNDimensions 1 2 3 back) totalDataLength\n    let (n2,out)=evalStep n $ M.fromList [1::Double]\n        (n3,out1)=evalStep n2 $ M.fromList [3]\n        (n4,out2)=evalSteps n [M.fromList [1],M.fromList [3]]\n    n3 @=? n4\n    out @=? head out2\n    out1 @=? last out2\n\n\ncheckLSTMSteps :: IO ()\ncheckLSTMSteps = do\n    (n::LSTMNetwork) <- evalRandIO $ randomNetwork 2 lstmFullSize\n    let (n2,out)=evalStep n $ M.fromList [1::Double,2]\n        (n3,out1)=evalStep n2 $ M.fromList [3,4]\n        (n4,out2)=evalSteps n [M.fromList [1,2],M.fromList [3,4]]\n    n3 @=? n4\n    out @=? head out2\n    out1 @=? last out2\n\nprop_lstm_eval_steps :: LSTMData2 -> Bool\nprop_lstm_eval_steps (LSTMData2 n1 is1 _ is2) =\n    let\n        (n2,out)=evalStep n1 $ M.fromList is1\n        (n3,out1)=evalStep n2 $ M.fromList is2\n        (n4,out2)=evalSteps n1 [M.fromList is1,M.fromList is2]\n    in n3==n4 && out==head out2 && out1 == last out2\n\ncheckLSTMList :: IO ()\ncheckLSTMList = do\n    (n1::LSTMNetwork) <- evalRandIO $ randomNetwork 2 lstmFullSize\n    (n2::LSTMNetwork) <- evalRandIO $ randomNetwork 2 lstmFullSize\n    let (n1_2,out)=evalStep n1 $ M.fromList [1::Double,2]\n        (n2_2,out1)=evalStep n2 out\n        (n3,out2)=evalStep [n1,n2] $ M.fromList [1,2]\n    n3 @=? [n1_2,n2_2]\n    out1 @=? out2\n\nprop_lstm_list :: LSTMData2 -> Bool\nprop_lstm_list (LSTMData2 n1 is1 n2 _) =\n    let (n1_2,out)=evalStep n1 $ M.fromList is1\n        (n2_2,out1)=evalStep n2 out\n        (n3,out2)=evalStep [n1,n2] $ M.fromList is1\n    in n3 == [n1_2,n2_2] && out1 == out2\n\ncheckLSTMVector :: IO ()\ncheckLSTMVector = do\n    (n::LSTMNetwork) <- evalRandIO $ randomNetwork 2 lstmFullSize\n    let arr = toVector n\n        n2  = fromVector 2 arr\n    n @=? n2\n\nprop_lstm_step :: LSTMData -> Bool\nprop_lstm_step (LSTMData n is)= snd (evalStep n (M.fromList is)) == M.fromList (snd $ lstmList 10 (M.toList $ toVector n) is)\n\ncheckLSTMIO :: IO()\ncheckLSTMIO = do\n    print $ lstmFullSize 4\n    print $ lstmioFullSize (2,4,3,1)\n    (n1::LSTMIO) <- evalRandIO $ randomNetwork (2,4,3,1) lstmioFullSize\n    let sz=rnnsize n1\n        v1=toVector n1\n        n2=fromVector sz v1\n    n1 @=? n2\n    let is=M.fromList [0.3,0.4]\n        r1@(_,o1) = evalStep n1 is\n    M.size o1 @?= 1\n    let r2 = evalStep n2 is\n    r1 @=? r2\n\ndata LSTMData = LSTMData LSTMNetwork [Double]\n    deriving Show\n\ninstance Arbitrary LSTMData where\n    arbitrary = do\n        let sz=10\n        ls <- vector (lstmFullSize sz)\n        is <- vector sz\n        let n = fromVector sz $ M.fromList ls\n        return $ LSTMData n is\n\n\ndata LSTMData2 = LSTMData2 LSTMNetwork [Double] LSTMNetwork [Double]\n    deriving Show\n\ninstance Arbitrary LSTMData2 where\n    arbitrary = do\n        let sz=10\n        ls1 <- vector (lstmFullSize sz)\n        is1 <- vector sz\n        let n1 = fromVector sz $ M.fromList ls1\n        ls2 <- vector (lstmFullSize sz)\n        is2 <- vector sz\n        let n2 = fromVector sz $ M.fromList ls2\n        return $ LSTMData2 n1 is1 n2 is2\n\ncheckArray :: Bool -> IO ()\ncheckArray back = do\n    let dim = RNNDimensions 1 2 3 back\n    (n::RNNetwork) <- evalRandIO $ randomNetwork dim totalDataLength\n    let arr = networkToArray n\n        n2  = createNetworkFromArray dim arr\n    case n2 of\n        Right rn2 -> n @=? rn2\n        Left err  -> assertFailure err\n\ncheckVector :: Bool -> IO ()\ncheckVector back = do\n    let dim = RNNDimensions 1 2 3 back\n    (n::RNNetwork) <- evalRandIO $ randomNetwork dim totalDataLength\n    let arr = toVector n\n        n2  = createNetworkFromVector dim arr\n    case n2 of\n        Right rn2 -> n @=? rn2\n        Left err  -> assertFailure err\n\n\ntestCrossover :: (RNNetwork\n                        -> RNNetwork -> Rand StdGen [RNNetwork])\n                       -> IO ()\ntestCrossover f = do\n    let dim = RNNDimensions 1 2 3 True\n    (n1::RNNetwork) <- evalRandIO $ randomNetwork dim totalDataLength\n    (n2::RNNetwork) <- evalRandIO $ randomNetwork dim totalDataLength\n    rnns <- evalRandIO $ f n1 n2\n    2 @=? length rnns\n    notElem n1 rnns @? \"n1 in result\"\n    notElem n2 rnns @? \"n2 in result\"\n\ntestMutation :: (LSTMNetwork -> Rand StdGen LSTMNetwork) -> IO()\ntestMutation f = do\n    (n1::LSTMNetwork) <- evalRandIO $ randomNetwork 5 lstmFullSize\n    n2 <- evalRandIO $ f n1\n    toVector n1 /= toVector n2 @? \"n1==n2\"\n\ntestExpr :: IO()\ntestExpr = do\n    let\n        f :: (Num a,Floating a)=> [a] -> a\n        f= \\[x,y,_] -> x * sin (x + log y)\n        i = I.fromList [(1,2::Double),(2,3),(3,4)]\n        gs0 = grad f [Var 1,Var 2,Var 3]\n        gs02 = grad f [2::Double,3,4]\n        cexpr = map (\\g-> close g i) gs0\n        eexpr = map eval cexpr\n    gs02 @=? eexpr\n    let\n        f1 :: (Num a,Floating a)=> a -> [a] -> a\n        f1 = \\x [y,_] -> x * sin (x + log y)\n        i1 = I.fromList [(2,3),(3,4)]\n        x1 :: Double\n        x1 = 2\n        gs1 = grad (f1 (autoEval (Lit $ Lit x1) $ I.empty)) [Var 2,Var 3]\n        gs12 = grad (f1 2) [3,4]\n        cexpr1 = map (\\g-> fullSimplify $ close g i1) gs1\n        eexpr1 = map eval cexpr1\n    gs12 @=? eexpr1\n    let\n        f2 :: (Num a,Floating a)=> [a] -> [a] -> a\n        f2= \\[x] [y,_] -> x * sin (x + log y)\n        i2 = I.fromList [(2,3),(3,4)]\n        --ex :: [Expr (Expr Double)]\n        --ex = map (\\x->autoEval (Lit x) I.empty) [2::Double]\n        x2 :: [Double]\n        x2 = [2]\n        gs2 = grad (f2 (map (\\x->autoEval (Lit $ Lit x) I.empty) x2)) [Var 2,Var 3]\n        gs22 = grad (f2 [2]) [3,4]\n        cexpr2 = map (\\g-> fullSimplify $ close g i2) gs2\n        eexpr2 = map eval cexpr2\n    gs22 @=? eexpr2\n    let\n        fs = lstmFullSize 2\n        ixs = [1..fs]\n        ixsF = map fromIntegral ixs\n        gs3::[Expr Double] = grad costT $ map Var ixs\n        i3 = I.fromList $ zip ixs ixsF\n        gs32 = grad (costT) ixsF\n        cexpr3 = map (\\g-> fullSimplify $ close g i3) gs3\n        eexpr3 = map eval cexpr3\n    (map (rnd 6) gs32) @=? (map (rnd 6) eexpr3)\n    where rnd n f = (fromInteger $ round $ f * (10^n)) / (10.0^^n)\n--  print gs3\n--  mapM_ (print . prettyShow . fullSimplify) (take 1 gs3)\n--  print $ length gs3\n--  print fs\n\ncostT :: (Num b,Floating b,Fractional b) => [b] -> b\ncostT lstm = let\n    res = snd $ mapAccumL (lstmList 2) lstm [[1,2],[2,3]]\n    in sum $ zipWith err [[3,4],[4,5]] res\n    where\n      err :: (Num b,Floating b) => [b] -> [b] -> b\n      err a b  = sum (zipWith (\\c d -> (c- d)**2 ) a b)\n\n", "meta": {"hexsha": "2aadaaa6a15f67ff7ffe9f82db5022e09aae2fa0", "size": 12763, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/rnn-test.hs", "max_stars_repo_name": "JPMoresmau/rnn", "max_stars_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-08-02T17:48:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T06:56:40.000Z", "max_issues_repo_path": "test/rnn-test.hs", "max_issues_repo_name": "JPMoresmau/rnn", "max_issues_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-01T18:47:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-01T18:47:41.000Z", "max_forks_repo_path": "test/rnn-test.hs", "max_forks_repo_name": "JPMoresmau/rnn", "max_forks_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-12-10T18:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-24T00:02:09.000Z", "avg_line_length": 33.3237597911, "max_line_length": 125, "alphanum_fraction": 0.6072240069, "num_tokens": 4030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.47106254872094383}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule STC.DFTFilter where\n\nimport           Control.Monad                as M\nimport           Control.Monad.IO.Class\nimport           Control.Monad.Parallel       as MP\nimport           Control.Monad.Trans.Resource\nimport           Data.Array.Repa              as R\nimport           Data.Binary\nimport           Data.ByteString.Lazy         as BL\nimport           Data.Complex\nimport           Data.Conduit\nimport           Data.Conduit.List            as C\nimport           Data.Int\nimport           Data.List                    as L\nimport           Data.Vector.Storable         as VS\nimport           Data.Vector.Unboxed          as VU\nimport           DFT.Plan\nimport           Filter.Utils\nimport           FokkerPlanck.Interpolation\nimport           System.IO\nimport           Utils.Array\nimport           Utils.Parallel               hiding ((.|))\n\n{-# INLINE sourceFile #-}\nsourceFile :: FilePath -> ConduitT () (VS.Vector (Complex Double)) (ResourceT IO) ()\nsourceFile filePath = do\n  h <- liftIO $ openBinaryFile filePath ReadMode\n  sourceFunc h\n  liftIO $ hClose h\n  where\n    sourceFunc handle = do\n      flag <- liftIO $ hIsEOF handle\n      if flag\n        then sourceNull\n        else do\n          lenBS <- liftIO $ BL.hGet handle 8\n          let len = fromIntegral (decode lenBS :: Int64) :: Int\n          dataBS <- liftIO $ BL.hGet handle len\n          yield . VS.fromList $ (decode dataBS :: [Complex Double])\n          sourceFunc handle \n\n{-# INLINE sinkFile #-}\nsinkFile :: FilePath -> ConduitT ByteString Void (ResourceT IO) ()\nsinkFile filePath = do\n  h <- liftIO $ openBinaryFile filePath WriteMode\n  sinkFunc h\n  where\n    sinkFunc handle = do\n      x <- await\n      case x of\n        Nothing -> liftIO $ hClose handle\n        Just y -> do\n          let len = BL.length y\n          liftIO $ BL.hPut handle (encode len)\n          liftIO $ BL.hPut handle y\n          sinkFunc handle            \n\n{-# INLINE interpolation #-}\ninterpolation ::\n     (R.Source r Double)\n  => DFTPlan\n  -> (Double -> Double -> Double -> Double -> Int -> Int -> Complex Double)\n  -> R.Array r DIM5 Double\n  -> Int\n  -> Int\n  -> Double\n  -> Double\n  -> (VU.Vector Double)\n  -> (VU.Vector Double)\n  -> (VU.Vector Double)\n  -> (VU.Vector Double)\n  -> (Int, Int)\n  -> IO ByteString\ninterpolation plan pinwheelFunc radialArr xLen yLen scaleFactor rMax thetaFreqs scaleFreqs theta0Freqs scale0Freqs (t, s) = do\n  let tf = thetaFreqs VU.! t\n      sf = scaleFreqs VU.! s\n      pinwheelArr =\n        traverse2\n          (fromUnboxed (Z :. VU.length theta0Freqs) theta0Freqs)\n          (fromUnboxed (Z :. VU.length scale0Freqs) scale0Freqs)\n          (\\(Z :. numTheta0Freq) (Z :. numScale0Freq) ->\n             (Z :. numTheta0Freq :. numScale0Freq :. xLen :. yLen)) $ \\ft0 fs0 (Z :. t0 :. s0 :. i :. j) ->\n          pinwheelFunc\n            (tf - ft0 (Z :. t0))\n            (sf + fs0 (Z :. s0))\n            rMax\n            0\n            (i - center xLen)\n            (j - center yLen)\n      filter =\n        radialCubicInterpolation\n          (R.slice radialArr (Z :. t :. s :. All :. All :. All))\n          scaleFactor\n          pinwheelArr\n  filterF <-\n    dftExecute\n      plan\n      (DFTPlanID\n         DFT1DG\n         [VU.length theta0Freqs, VU.length scale0Freqs, xLen, yLen]\n         [2, 3]) .\n    VU.convert . toUnboxed . computeS $\n    filter\n  return . encode . VS.toList $ filterF\n\n{-# INLINE dftFilter2File #-}\ndftFilter2File ::\n     (R.Source r Double)\n  => ParallelParams\n  -> DFTPlan\n  -> (Double -> Double -> Double -> Double -> Int -> Int -> Complex Double)\n  -> R.Array r DIM5 Double\n  -> Int\n  -> Int\n  -> Double\n  -> Double\n  -> (VU.Vector Double)\n  -> (VU.Vector Double)\n  -> (VU.Vector Double)\n  -> (VU.Vector Double)\n  -> FilePath\n  -> IO ()\ndftFilter2File parallelParams plan pinwheelFunc radialArr xLen yLen scaleFactor rMax thetaFreqs scaleFreqs theta0Freqs scale0Freqs filePath =\n  runConduitRes $\n  sourceList\n    [ (t, s)\n    | t <- [0 .. VU.length thetaFreqs]\n    , s <- [0 .. VU.length scaleFreqs]\n    ] .|\n  parConduitIO\n    parallelParams\n    (interpolation\n       plan\n       pinwheelFunc\n       radialArr\n       xLen\n       yLen\n       scaleFactor\n       rMax\n       thetaFreqs\n       scaleFreqs\n       theta0Freqs\n       scale0Freqs) .|\n  sinkFile filePath\n\n{-# INLINE convolutionHelper #-}\nconvolutionHelper ::\n     DFTPlan\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> VS.Vector (Complex Double)\n  -> VS.Vector (Complex Double)\n  -> IO (VU.Vector (Complex Double))\nconvolutionHelper plan numThetaFreq numScaleFreq xLen yLen vecF1 vecF2 =\n  toUnboxed .\n  sumS .\n  sumS .\n  rotate4D .\n  rotate4D .\n  fromUnboxed (Z :. numThetaFreq :. numScaleFreq :. xLen :. yLen) . VS.convert <$>\n  dftExecute\n    plan\n    (DFTPlanID IDFT1DG [numThetaFreq, numScaleFreq, xLen, yLen] [2, 3])\n    (VS.zipWith (*) vecF1 vecF2)\n   \n\n{-# INLINE convolveSlowly #-}\nconvolveSlowly ::\n     ParallelParams\n  -> FilePath\n  -> DFTPlan\n  -> R.Array U DIM4 (Complex Double)\n  -> IO (R.Array U DIM4 (Complex Double))\nconvolveSlowly parallelParams filePath plan arr = do\n  let (Z :. numThetaFreq :. numScaleFreq :. xLen :. yLen) = extent arr\n  xs <-\n    runConduitRes $\n    sourceFile filePath .|\n    parConduitIO\n      parallelParams\n      (convolutionHelper\n         plan\n         numThetaFreq\n         numScaleFreq\n         xLen\n         yLen\n         (VU.convert . toUnboxed $ arr)) .|\n    C.consume\n  return . fromUnboxed (extent arr) . VU.concat $ xs\n\n\n{-# INLINE convolutionHelperSink #-}\nconvolutionHelperSink ::\n     DFTPlan\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> VU.Vector Double\n  -> VS.Vector (Complex Double)\n  -> ((Int, Int), VS.Vector (Complex Double))\n  -> IO (VU.Vector (Complex Double))\nconvolutionHelperSink plan numThetaFreq numScaleFreq xLen yLen thetaFreqs vecF1 ((t, _), vecF2) = do\n  let tf = thetaFreqs VU.! t\n  arr <-\n    fromUnboxed (Z :. numThetaFreq :. numScaleFreq :. xLen :. yLen) . VS.convert <$>\n    dftExecute\n      plan\n      (DFTPlanID IDFT1DG [numThetaFreq, numScaleFreq, xLen, yLen] [2, 3])\n      (VS.zipWith (*) vecF1 vecF2)\n  return . toUnboxed . sumS . sumS . rotate4D . rotate4D . R.traverse arr id $ \\f idx@(Z :. t0 :. _ :. i :. j) ->\n    f idx * exp (0 :+ ((thetaFreqs VU.! t0) + tf) * pi)\n\n\n{-# INLINE convolveSlowlySink #-}\nconvolveSlowlySink ::\n     ParallelParams\n  -> FilePath\n  -> DFTPlan\n  -> VU.Vector Double\n  -> VU.Vector Double\n  -> R.Array U DIM4 (Complex Double)\n  -> IO (R.Array U DIM4 (Complex Double))\nconvolveSlowlySink parallelParams filePath plan thetaFreqs scaleFreqs arr = do\n  let (Z :. numThetaFreq :. numScaleFreq :. xLen :. yLen) = extent arr\n  xs <-\n    runConduitRes $\n    sourceFile filePath .|\n    mergeSource\n      (sourceList\n         [ (t, s)\n         | t <- [0 .. VU.length thetaFreqs]\n         , s <- [0 .. VU.length scaleFreqs]\n         ]) .|\n    parConduitIO\n      parallelParams\n      (convolutionHelperSink\n         plan\n         numThetaFreq\n         numScaleFreq\n         xLen\n         yLen\n         thetaFreqs\n         (VU.convert . toUnboxed $ arr)) .|\n    C.consume\n  return . fromUnboxed (extent arr) . VU.concat $ xs\n", "meta": {"hexsha": "18654344587d251daa554b5c6433f1f4a3476010", "size": 7134, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/STC/DFTFilter.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/STC/DFTFilter.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/STC/DFTFilter.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 28.536, "max_line_length": 141, "alphanum_fraction": 0.588870199, "num_tokens": 2073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4708902555012384}}
{"text": "module MnistLoader (loadData, loadDataWrapper, loadTestWrapper, investigate) where\n\nimport Data.IDX\nimport qualified Data.Vector.Unboxed as V\nimport Numeric.LinearAlgebra as L\n\nvect n = (n><1)\n\nloadData :: IO ([(Int, V.Vector Double)])\nloadData = do\n  mData <- decodeIDXFile \"data/train-images-idx3-ubyte\"\n  let d = getSomething mData\n  mLabels <- decodeIDXLabelsFile \"data/train-labels-idx1-ubyte\"\n  let l = getSomething mLabels\n  return $ getSomething $ labeledDoubleData l d\n\nloadTest :: IO ([(Int, V.Vector Double)])\nloadTest = do\n  mData <- decodeIDXFile \"data/t10k-images.idx3-ubyte\"\n  let d = getSomething mData\n  mLabels <- decodeIDXLabelsFile \"data/t10k-labels.idx1-ubyte\"\n  let l = getSomething mLabels\n  return $ getSomething $ labeledDoubleData l d\n\n-- Converts the label component to a vector representation where\n-- n'th component is 1\nloadDataWrapper :: IO ([(Matrix Float, Matrix Float)])\nloadDataWrapper = do\n  theData <- loadData\n  return $ map (\\(l, d) -> (mVect d, makeVector l)) theData\n  where\n    makeVector l = vect 10 $ (map (\\i -> if i == l then 1 else 0) [0..10])\n    mVect l = vect (V.length l) (map realToFrac $ V.toList l)\n\nloadTestWrapper :: IO ([(Matrix Float, Matrix Float)])\nloadTestWrapper = do\n  theData <- loadTest\n  return $ map (\\(l, d) -> (mVect d, makeVector l)) theData\n  where\n    makeVector l = vect 10 $ (map (\\i -> if i == l then 1 else 0) [0..10])\n    mVect l = vect (V.length l) $ map realToFrac $ V.toList l\n\ninvestigate :: IO ()\ninvestigate = do\n    putStrLn \"Inspecting File\"\n    training_data_mb <- decodeIDXFile \"data/train-images-idx3-ubyte\"\n    let td = getSomething training_data_mb\n\n    putStrLn \"Image Data\"\n    putStr \"idxType: \"\n    putStrLn $ show $ idxType td\n\n    putStr \"idxDimensions: \"\n    putStrLn $ show $ idxDimensions td\n\n    putStr \"isIDXReal: \"\n    putStrLn $ show $ isIDXReal td\n\n    putStr \"isIDXIntegral: \"\n    putStrLn $ show $ isIDXIntegral td\n\n    let training_vector = idxDoubleContent td\n    putStrLn $ show $ V.length training_vector\n\n    loaded_data <- loadData\n    let (l, d) = loaded_data !! 1\n    putStrLn $ show $ V.length $ d\n    putStrLn $ show $ l\n\ngetSomething :: Maybe a -> a\ngetSomething (Just x) = x\ngetSomething Nothing = error \"Bah\"", "meta": {"hexsha": "7e93a4c57ce95de2759cbf3af921f331ac50e3b0", "size": 2227, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MnistLoader.hs", "max_stars_repo_name": "madsbuch/haskell-nn", "max_stars_repo_head_hexsha": "756c30da245b8f0f7e860d5624033c022d844e42", "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/MnistLoader.hs", "max_issues_repo_name": "madsbuch/haskell-nn", "max_issues_repo_head_hexsha": "756c30da245b8f0f7e860d5624033c022d844e42", "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/MnistLoader.hs", "max_forks_repo_name": "madsbuch/haskell-nn", "max_forks_repo_head_hexsha": "756c30da245b8f0f7e860d5624033c022d844e42", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9305555556, "max_line_length": 82, "alphanum_fraction": 0.6883700045, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6261241772283035, "lm_q1q2_score": 0.47085325401069195}}
{"text": "{-# LANGUAGE LambdaCase #-}\nmodule AI.NeuroCar where\n\nimport           AI.GeneticAlgorithm   as GA\nimport qualified AI.NeuralNetwork      as NN\nimport qualified Car                   as C\nimport           Control.Lens\nimport           Control.Monad.Loops\nimport           Control.Monad.State\nimport           Data.Foldable\nimport           Data.Functor.Identity\nimport           Data.Word             (Word32)\nimport           Game\nimport qualified Geometry              as G\nimport qualified Numeric.LinearAlgebra as LA\nimport           System.Random\nimport qualified Track                 as T\nimport           World\n\nrayAngle :: Double\nrayAngle = pi\n\nrayCount :: Int\nrayCount = 7\n\nevolveCar :: Int -> Int -> Int -> Double -> Double -> Double -> Word32 ->\n    C.CarParams -> T.Track Double -> [Population Double]\nevolveCar seed generations popSize mutChance mutStrength time deltaTicks carParams track = do\n    let gen          = mkStdGen seed\n    let drawFunc     = return . const ()\n    let inputFunc nn = Identity . getNetworkInput nn\n    let timeFunc     = return deltaTicks\n    let world        = initWorld carParams track time\n    let evolveLoop nn = gameLoop drawFunc (inputFunc nn) timeFunc\n    let runGame nn = runIdentity $ iterateUntilM (\\w -> w^.gameState /= GameRunning) (evolveLoop nn) world\n    let fitfunc nn = fromIntegral $ view score (runGame nn)\n    let mutfunc = GA.mutate mutChance mutStrength\n    let indGen = NN.newNetwork [3+rayCount, 15, 15, 2]\n    let evoFunc = evolves generations popSize indGen fitfunc mutfunc\n    evalState evoFunc gen\n\n\ngetNetworkInput :: NN.Network -> World -> [Input]\ngetNetworkInput nn w =\n    let push a        = (state $ \\xs -> ((),a:xs)) :: State [Input] ()\n        rays          = C.shootRays rayAngle rayCount $ w^.car\n        origin        = w^.car.C.position\n        intersections = T.rayIntersection (w^.track) <$> rays\n        distances     = (\\case Nothing -> 0\n                               Just v  -> G.segLength (origin, v)) <$> intersections\n        velocity      = C.localVelocity $ w^.car\n        rotation      = w^.car.C.rotation\n        x             = rotation : toList velocity ++ distances\n        y             = LA.toList $ NN.feedforward (LA.fromList x) nn\n     in execState (do { when (head y < 1/3) (push GoBackward)\n                      ; when (head y > 2/3) (push GoForward)\n                      ; when (y !! 1 < 1/3) (push GoLeft)\n                      ; when (y !! 1 > 2/3) (push GoRight) }) []\n\n", "meta": {"hexsha": "c8ab2647fcf5b95ea37c0ae152117eaf20f42cb9", "size": 2482, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/NeuroCar.hs", "max_stars_repo_name": "cornelius-sevald/neurocar", "max_stars_repo_head_hexsha": "9a8529ab2007b98ab20b6ce0b7e29ec7cbe085bb", "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/AI/NeuroCar.hs", "max_issues_repo_name": "cornelius-sevald/neurocar", "max_issues_repo_head_hexsha": "9a8529ab2007b98ab20b6ce0b7e29ec7cbe085bb", "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/AI/NeuroCar.hs", "max_forks_repo_name": "cornelius-sevald/neurocar", "max_forks_repo_head_hexsha": "9a8529ab2007b98ab20b6ce0b7e29ec7cbe085bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3666666667, "max_line_length": 106, "alphanum_fraction": 0.5946817083, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.47043005721521647}}
{"text": "{- | Example of sampling\n\nTwo samplers are availables : the 'discreteAncestralSampler' and the 'gibbsSampler'.\nOnly the 'gibbsSampler' can be used with evidence.\n\nIn this example, we have a very simple network.\n\n@\n    simple :: (['TDV' Bool],'SBN' 'CPT')\n    simple = 'runBN' $ do \n        a <- 'variable' \\\"a\\\" ('t' :: Bool)\n        b <- 'variable' \\\"b\\\" ('t' :: Bool) \n--        \n        'proba' a '~~' [0.4,0.6]\n        'cpt' b [a] '~~' [0.8,0.2,0.2,0.8]\n--    \n        return [a,b]\n@\n\nThis network is representing a sensor b. We observe the value of b and we want to infer the value of a.\n\nWe use the 'gibbsSampler' for this with an initial period of 200 samples which are dropped. The 'gibbsSampler' is\ngenerate a stream of samples. From this stream, we need to compute a probability distribution. For this, we use\nthe 'samplingHistograms' histogram function which is generating a list : the probability values of each vertex.\n\n@\n    let (vars\\@[a,b],exampleG) = simple\n    n <- 'runSampling' 5000 200 ('gibbsSampler' exampleG [b '=:' True])\n    let h = 'samplingHistograms' n\n    print $ h\n@\n\nThen, we compare this result with the exact one we get with a junction tree.\n\n@\n    let jt = 'createJunctionTree' 'nodeComparisonForTriangulation' exampleG\n        jt' = 'changeEvidence' [b '=:' True] jt\n    mapM_ (\\x -> print . 'posterior' jt' $ [x]) vars\n@\n\nWe can also use the 'discreteAncestralSampler' to compute the posterior but it is not supporting the use of evidence in this\nversion. The syntax is similar.\n\n@\n    n <- 'runSampling' 500 ('discreteAncestralSampler' exampleG)\n@\n\n-}\nmodule Bayes.Examples.Sampling(\n    -- * Test function\n\t  testSampling\n) where\n\nimport Bayes.Sampling \nimport System.Random.MWC.CondensedTable\nimport qualified Data.Vector as V\nimport Bayes.Factor\nimport Bayes\nimport Bayes.FactorElimination\nimport Data.Maybe(fromJust)\nimport Bayes.BayesianNetwork\nimport Bayes.Factor.CPT\nimport Statistics.Sample.Histogram\n\n\nsimple :: ([TDV Bool],SBN CPT)\nsimple = runBN $ do \n    a <- variable \"a\" (t :: Bool)\n    b <- variable \"b\" (t :: Bool) \n    \n    proba a ~~ [0.4,0.6]\n    cpt b [a] ~~ [0.8,0.2,0.2,0.8]\n\n    return [a,b]\n\n\ntestSampling = do\n    let (vars@[a,b],exampleG) = simple\n        jt = createJunctionTree nodeComparisonForTriangulation exampleG\n    --n <- runSampling 500 (discreteAncestralSampler exampleG)\n    putStrLn \"The bayesian network\"\n    print exampleG\n    putStrLn \"\\nThe values of the Bayesian network\"\n    printGraphValues exampleG\n\n    n <- runSampling 5000 200 (gibbsSampler exampleG [b =: True])\n    let h = samplingHistograms 2 n\n    putStrLn \"\\nThe result of the sampling\"\n    print $ h\n\n    n <- runSampling 5000 200 (gibbsMCMCSampler exampleG [b =: True])\n    let h = samplingHistograms 2 n\n    putStrLn \"\\nThe result of the sampling with MCMC\"\n    print $ h\n\n    let jt' = changeEvidence [b =: True] jt\n    putStrLn \"\\nThe result of the junction tree inference\"\n    mapM_ (\\x -> print . posterior jt' $ [x]) vars\n", "meta": {"hexsha": "968f49fac2f0dd0c6f83225508d301561172a2d1", "size": 2973, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Bayes/Examples/Sampling.hs", "max_stars_repo_name": "sid-kap/hbayes", "max_stars_repo_head_hexsha": "94557f9a6277c46c0a4b4b8c386aee7d5d6d00e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2016-05-13T14:48:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-14T14:03:26.000Z", "max_issues_repo_path": "Bayes/Examples/Sampling.hs", "max_issues_repo_name": "sid-kap/hbayes", "max_issues_repo_head_hexsha": "94557f9a6277c46c0a4b4b8c386aee7d5d6d00e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-01-24T15:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-12T20:42:53.000Z", "max_forks_repo_path": "Bayes/Examples/Sampling.hs", "max_forks_repo_name": "sid-kap/hbayes", "max_forks_repo_head_hexsha": "94557f9a6277c46c0a4b4b8c386aee7d5d6d00e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-05-19T23:33:04.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-23T16:11:24.000Z", "avg_line_length": 30.0303030303, "max_line_length": 124, "alphanum_fraction": 0.6717120753, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4703032981235909}}
{"text": "\nmodule Algebra where\n\nimport qualified Data.Text as T\nimport qualified Data.Map as M\nimport qualified Data.Vector as V\nimport Data.Maybe\nimport Statistics.LinearRegression\n\nimport Types\n\nselectKeyData :: T.Text -> [Sample ItemsMap] -> [Sample Int]\nselectKeyData key samples = [sample {sampleItems = select sample} | sample <- samples]\n  where\n    select sample = fromMaybe 0 $ M.lookup key (sampleItems sample)\n\nprepareSystem :: [Sample Int] -> (V.Vector Double, V.Vector Double)\nprepareSystem samples =\n      (V.fromList $ map sampleTime samples,\n       V.fromList $ map (fromIntegral . sampleItems) samples)\n\ngrowCoefficient :: T.Text -> [Sample ItemsMap] -> Double\ngrowCoefficient key samples =\n  let (xs, ys) = prepareSystem $ selectKeyData key samples\n      (_, beta) = linearRegression xs ys\n  in  beta\n\n", "meta": {"hexsha": "fb4491027943aa1505d31ac3c2258fd2546b2900", "size": 811, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Algebra.hs", "max_stars_repo_name": "l29ah/hpview", "max_stars_repo_head_hexsha": "5d2df184bb573d3ea14d6263e342bef8ea17fb41", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-08-11T19:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-16T16:38:59.000Z", "max_issues_repo_path": "src/Algebra.hs", "max_issues_repo_name": "l29ah/hpview", "max_issues_repo_head_hexsha": "5d2df184bb573d3ea14d6263e342bef8ea17fb41", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-08-11T17:49:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-21T16:35:27.000Z", "max_forks_repo_path": "src/Algebra.hs", "max_forks_repo_name": "l29ah/hpview", "max_forks_repo_head_hexsha": "5d2df184bb573d3ea14d6263e342bef8ea17fb41", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-29T11:39:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-29T11:39:43.000Z", "avg_line_length": 28.9642857143, "max_line_length": 86, "alphanum_fraction": 0.7311960543, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.6406358685621721, "lm_q1q2_score": 0.47030329329091874}}
{"text": "module AI.Learning.CrossValidation where\n\nimport Control.Monad.Random\nimport Foreign.Storable (Storable)\nimport Numeric.LinearAlgebra\nimport qualified Data.List as L\n\nimport AI.Util.Matrix\nimport AI.Util.Util\n\n----------------------\n-- Cross Validation --\n----------------------\n\nclass Indexable c where\n    index :: c -> Index -> c\n    nobs :: c -> Int\n\ninstance Storable a => Indexable (Vector a) where\n    index = subRefVec\n    nobs = dim\n\ninstance Element a => Indexable (Matrix a) where\n    index = subRefRows\n    nobs = rows\n\ninstance Indexable [a] where\n    index = map . (!!) \n    nobs = length\n\n-- |Indexes are lists of 'Int'. Should refactor this to use something more\n--  efficient.\ntype Index  = [Int]\n\n-- |Type for cross-validation partition.\ndata CVPartition = CVPartition [(Index, Index)]\n\n-- |Specify what type of cross-validation you want to do.\ndata CVType = LeaveOneOut\n            | KFold Int\n    \n-- |Prediction function. A prediction function should take a training and a test\n--  set, and use the training set to build a model whose performance is\n--  evaluated on the test set, returning a final score as a 'Double'.\ntype PredFun a b = a        -- Training set predictors\n                -> b        -- Training set target\n                -> a        -- Test set predictors\n                -> b        -- Test set target\n                -> Double   -- Performance score\n\n-- |Create a partition into test and training sets.\ncvPartition :: RandomGen g => Int -> CVType -> Rand g CVPartition\ncvPartition sz cvtype = case cvtype of\n    KFold i     -> cvp sz i\n    LeaveOneOut -> cvp sz sz\n\n-- |Helper function for 'cvPartition'.\ncvp :: RandomGen g => Int -> Int -> Rand g CVPartition\ncvp n k = do\n    is <- go i (k - i) idx\n    return . CVPartition $ map (\\i -> (idx L.\\\\ i, i)) is\n    where\n        go 0 0 idx = return []\n\n        go 0 j idx = do\n            (is, idx') <- selectMany' s idx\n            iss        <- go 0 (j-1) idx'\n            return (is:iss)\n\n        go i j idx = do\n            (is, idx') <- selectMany' (s+1) idx\n            iss        <- go (i-1) j idx'\n            return (is:iss)\n\n        s   = n `div` k\n        i   = n `mod` k\n        idx = [0 .. n-1]\n\n-- |Perform k-fold cross-validation. Given a 'CVPartition' containing a list\n--  of training and test sets, we repeatedly fit a model on the training set\n--  and test its performance on the test set/\nkFoldCV_ :: (Indexable a, Indexable b) => \n            CVPartition\n         -> PredFun a b\n         -> a\n         -> b\n         -> [Double]\nkFoldCV_ (CVPartition partition) predfun x y = map go partition\n    where\n        go (trainIdx,testIdx) = predfun xTrain yTrain xTest yTest\n            where\n                xTrain = x `index` trainIdx\n                yTrain = y `index` trainIdx\n                xTest  = x `index` testIdx\n                yTest  = y `index` testIdx\n\n-- |Perform k-fold cross-validation, randomly generating the training and\n--  test sets first.\nkFoldCV :: (RandomGen g, Indexable a, Indexable b) =>\n           CVType           -- What type of cross-validation?\n        -> PredFun a b      -- Prediction function\n        -> a                -- Predictors\n        -> b                -- Targets\n        -> Rand g [Double]  -- List of scores\nkFoldCV cvtype predfun x y = if nobs x /= nobs y\n    then error \"Inconsistent dimensions -- KFOLDCV\"\n    else do\n        cp <- cvPartition (nobs x) cvtype\n        return (kFoldCV_ cp predfun x y)\n\n---------------\n-- Old Stuff --\n---------------\n\n-- |Model builder. A model builder takes a training set of regressors and\n--  targets, and constructs a function that makes predictions from an out-\n--  of-sample set of regressors.\ntype ModelBuilder = Matrix Double   -- Training set regressors\n                 -> Vector Double   -- Training set target\n                 -> Matrix Double   -- Out-of-sample regressors\n                 -> Vector Double   -- Predictions\n\n-- |Evaluation function. An evaluation function takes a vector of targets and\n--  a vector of predictions, and returns a score corresponding to how closely\n--  the predictions match the target.\ntype EvalFun = Vector Double    -- Target\n            -> Vector Double    -- Predictions\n            -> Double           -- Score (e.g. MSE, MCR, likelihood)", "meta": {"hexsha": "401154cdd9f5ce147d9642927e391f6ea98bd17f", "size": 4279, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Learning/CrossValidation.hs", "max_stars_repo_name": "cagix/aima-haskell", "max_stars_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 245, "max_stars_repo_stars_event_min_datetime": "2015-01-08T18:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T06:58:10.000Z", "max_issues_repo_path": "src/AI/Learning/CrossValidation.hs", "max_issues_repo_name": "bemcho/aima-haskell-1", "max_issues_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-09T12:56:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-10T23:14:19.000Z", "max_forks_repo_path": "src/AI/Learning/CrossValidation.hs", "max_forks_repo_name": "bemcho/aima-haskell-1", "max_forks_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2015-01-12T00:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T03:09:12.000Z", "avg_line_length": 33.4296875, "max_line_length": 80, "alphanum_fraction": 0.5865856509, "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47004740749162605}}
{"text": "-- Filename: fft.hs\n-- Created by: Daniel Winograd-Cort\n-- Created on: unknown\n-- Last Modified by: Daniel Winograd-Cort\n-- Last Modified on: 12/12/2013\n\n-- This module requires the array and pure-fft packages.\n\n{-# LANGUAGE Arrows #-}\nmodule Euterpea.IO.MUI.FFT where\nimport FRP.UISF\nimport Control.Arrow.Operations\nimport Numeric.FFT (fft)\nimport Data.Complex\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\n\n\n-- | Alternative for working with Math.FFT instead of Numeric.FFT\n--import qualified Math.FFT as FFT\n--import Data.Array.IArray\n--import Data.Array.CArray\n--myFFT n lst = elems $ (FFT.dft) (listArray (0, n-1) lst)\n\n\n--------------------------------------\n-- Fast Fourier Transform\n--------------------------------------\n\n-- | Returns n samples of type b from the input stream at a time, \n--   updating after k samples.  This function is good for chunking \n--   data and is a critical component to fftA\nquantize :: ArrowCircuit a => Int -> Int -> a b (SEvent [b])\nquantize n k = proc d -> do\n    rec (ds,c) <- delay ([],0) -< (take n (d:ds), c+1)\n    returnA -< if c >= n && c `mod` k == 0 then Just ds else Nothing\n\n-- | Converts the vector result of a dft into a map from frequency to magnitude.\n--   One common use is:\n--      fftA >>> arr (fmap $ presentFFT clockRate)\npresentFFT :: Double -> [Double] -> Map Double Double\npresentFFT clockRate a = Map.fromList $ zipWith (curry mkAssoc) [0..] a where \n    mkAssoc (i,c) = (freq, c) where\n        samplesPerPeriod = fromIntegral (length a)\n        freq = i * (clockRate / samplesPerPeriod)\n\n-- | Given a quantization frequency (the number of samples between each \n--   successive FFT calculation) and a fundamental period, this will decompose\n--   the input signal into its constituent frequencies.\n--   NOTE: The fundamental period must be a power of two!\nfftA :: ArrowCircuit a => Int -> Int -> a Double (SEvent [Double])\nfftA qf fp = proc d -> do\n    carray <- quantize fp qf -< d :+ 0\n    returnA -< fmap (map magnitude . take (fp `div` 2) . fft) carray\n\n\n", "meta": {"hexsha": "861c2f7f940c4b7c1c46e9080104f5aaff9075aa", "size": 2032, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Euterpea/IO/MUI/FFT.hs", "max_stars_repo_name": "bsdr/Euterpea", "max_stars_repo_head_hexsha": "6635e483cf80ec8ae67613c40e8d61e475f4742d", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 172, "max_stars_repo_stars_event_min_datetime": "2015-01-12T13:13:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T16:40:18.000Z", "max_issues_repo_path": "Euterpea/IO/MUI/FFT.hs", "max_issues_repo_name": "EQ4/Euterpea", "max_issues_repo_head_hexsha": "6635e483cf80ec8ae67613c40e8d61e475f4742d", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2015-01-31T21:18:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-01T18:09:27.000Z", "max_forks_repo_path": "Euterpea/IO/MUI/FFT.hs", "max_forks_repo_name": "EQ4/Euterpea", "max_forks_repo_head_hexsha": "6635e483cf80ec8ae67613c40e8d61e475f4742d", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2015-03-08T19:37:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-17T11:47:46.000Z", "avg_line_length": 35.0344827586, "max_line_length": 80, "alphanum_fraction": 0.6579724409, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4699482820573399}}
{"text": "{-# LANGUAGE MagicHash, UnboxedTuples #-}\n\nmodule VecUtil (unpack2, unpack3, tangentBitangent, vec3Of, vec2Of) where\n\nimport Numeric.Vector\n\nunpack2 :: Vec2d -> (Double, Double)\nunpack2 v = case unpackV2# v of\n              (# x, y #) -> (x, y)\n\nunpack3 :: Vec3d -> (Double, Double, Double)\nunpack3 v = case unpackV3# v of\n              (# x, y, z #) -> (x, y, z)\n\ntangentBitangent :: Vec3d -> (Vec3d, Vec3d)\ntangentBitangent normal =\n  -- Cross product with an arbitrary vector to produce the tangent. The if is for the rare case that\n  -- the normal is the arbitrary vector. Is there a better approach?\n  let tangent = normalized $ normal \u00d7 (if normal == (vec3 1 0 0) then vec3 0 1 0 else vec3 1 0 0)\n      bitangent = normal \u00d7 tangent -- Don't need to normalize, magnitude is mathematically 1\n  in (tangent, bitangent)\n\nvec3Of :: Double -> Vec3d\nvec3Of = realToFrac\n\nvec2Of :: Double -> Vec2d\nvec2Of = realToFrac\n", "meta": {"hexsha": "a7658c7d6248c9d580067ed706d0ed6984c8c8f0", "size": 916, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/VecUtil.hs", "max_stars_repo_name": "craigmc08/haskell-raytracer", "max_stars_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "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/VecUtil.hs", "max_issues_repo_name": "craigmc08/haskell-raytracer", "max_issues_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "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/VecUtil.hs", "max_forks_repo_name": "craigmc08/haskell-raytracer", "max_forks_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "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.7142857143, "max_line_length": 100, "alphanum_fraction": 0.6703056769, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.469937915274214}}
{"text": "{-# LANGUAGE TemplateHaskell #-}\nmodule Turtle (main) where\nimport Data.Complex\nimport Ros.Node\nimport Ros.Topic (cons, repeatM)\nimport Ros.TopicUtil (tee, filterBy, everyNew, interruptible, gate, share)\nimport Ros.Turtlesim.Pose\nimport Ros.Turtlesim.Velocity\nimport Ros.Logging\nimport System.IO (hFlush, stdout)\n\n-- A type synonym for a 2D point.\ntype Point = Complex Float\n\n-- A Topic of user-supplied waypoint trajectories.\ngetTraj :: Topic IO [Point]\ngetTraj = repeatM (do putStr \"Enter waypoints: \" >> hFlush stdout\n                      $(logInfo \"Waiting for new traj\")\n                      (map (uncurry (:+)) . read) `fmap` getLine)\n\nwrapAngle theta \n  | theta < 0    = theta + 2 * pi\n  | theta > 2*pi = theta - 2 * pi\n  | otherwise    = theta\n\nangleDiff x y = wrapAngle (x' + pi - y') - pi\n  where x' = if x < 0 then x + 2*pi else x\n        y' = if y < 0 then y + 2*pi else y\n\n-- Produce a unit value every time a goal is reached.\narrivalTrigger :: Topic IO Point -> Topic IO Pose -> Topic IO ()\narrivalTrigger goals poses = fmap (const ()) $\n                             filterBy (fmap arrived goals) (fmap p2v poses)\n  where arrived goal pose = magnitude (goal - pose) < 1.5\n        p2v (Pose x y _ _ _) = x :+ y\n\n-- Navigate to a goal given a current pose estimate.\nnavigate :: (Point, Pose) -> Velocity\nnavigate (goal, pos) = Velocity (min 2 (magnitude v)) angVel\n  where v        = goal - (x pos :+ y pos)\n        thetaErr = (angleDiff (phase v) (theta pos)) * (180 / pi)\n        angVel   = signum thetaErr * (min 2 (abs thetaErr))\n\nmain = runNode \"HaskellBTurtle\" $\n       do enableLogging (Just Warn)\n          poses <- subscribe \"/turtle1/pose\"\n          (t1,t2) <- liftIO . tee . interruptible $ getTraj\n          let goals = gate t1 (cons () (arrivalTrigger t2 poses))\n          advertise \"/turtle1/command_velocity\" $\n                    fmap navigate (everyNew goals poses)\n", "meta": {"hexsha": "d5341794e4579f04a653c1dcbcb91aae20fbe290", "size": 1897, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Examples/Turtle/src/Turtle.hs", "max_stars_repo_name": "rgleichman/roshask", "max_stars_repo_head_hexsha": "65c20fe8fdab58bc44af7510c01b6085ae69192a", "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": "Examples/Turtle/src/Turtle.hs", "max_issues_repo_name": "rgleichman/roshask", "max_issues_repo_head_hexsha": "65c20fe8fdab58bc44af7510c01b6085ae69192a", "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/Turtle/src/Turtle.hs", "max_forks_repo_name": "rgleichman/roshask", "max_forks_repo_head_hexsha": "65c20fe8fdab58bc44af7510c01b6085ae69192a", "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.1960784314, "max_line_length": 75, "alphanum_fraction": 0.6236162362, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4697449151825168}}
{"text": "{-| \n    Module      : Vocoder\n    Description : Phase vocoder\n    Copyright   : (c) Celina Pawli\u0144ska, 2020\n                      Marek Materzok, 2021\n    License     : BSD2\n\nThis module implements the phase vocoder algorithms. \nThe implementation is designed to be used directly or to be integrated\ninto some convenient abstraction (streaming or FRP).\n-}\nmodule Vocoder (\n      Moduli,\n      Phase,\n      PhaseInc,\n      Frame,\n      Window,\n      HopSize,\n      Length,\n      STFTFrame,\n      FFTOutput,\n      VocoderParams,\n      vocoderParams,\n      vocFrameLength,\n      vocInputFrameLength,\n      vocFreqFrameLength,\n      vocHopSize,\n      vocWindow,\n      doFFT,\n      doIFFT,\n      analysisBlock,\n      analysisStep,\n      analysisStage,\n      synthesisBlock,\n      synthesisStep,\n      synthesisStage,\n      zeroPhase,\n      volumeCoeff,\n      frameFromComplex,\n      frameToComplex,\n      addFrames\n    ) where\n\nimport Data.List\nimport Data.Complex\nimport Data.Fixed\nimport Data.Tuple\nimport Control.Arrow\nimport Numeric.FFT.Vector.Invertible as FFT\nimport Numeric.FFT.Vector.Plan as FFTp\nimport qualified Data.Vector.Storable as V\n\n-- | Complex moduli of FFT frames. Represent signal amplitudes.\ntype Moduli = V.Vector Double\n\n-- | Complex arguments of FFT frames. Represent signal phases.\ntype Phase = V.Vector Double\n\n-- | Phase increments. Represent the deviation of the phase difference\n-- between successive frames from the expected difference for the center\n-- frequencies of the FFT bins.\ntype PhaseInc = V.Vector Double\n\n-- | Time domain frame.\ntype Frame = V.Vector Double\n\n-- | Sampled STFT window function.\ntype Window = Frame\n\n-- | Offset between successive STFT frames, in samples.\ntype HopSize = Int\n\n-- | Size in samples.\ntype Length = Int\n\n-- | STFT processing unit.\ntype STFTFrame = (Moduli, PhaseInc)\n\n-- | Frequency domain frame.\ntype FFTOutput = V.Vector (Complex Double)\n\n-- | Type of FFT plans for real signals.\ntype FFTPlan = FFTp.Plan Double (Complex Double)\n\n-- | Type of IFFT plans for real signals.\ntype IFFTPlan = FFTp.Plan (Complex Double) Double\n\n-- | Configuration parameters for the phase vocoder algorithm.\ndata VocoderParams = VocoderParams{\n    -- | FFT plan used in analysis stage.\n    vocFFTPlan  :: FFTPlan,\n    -- | FFT plan used in synthesis stage.\n    vocIFFTPlan :: IFFTPlan,\n    -- | STFT hop size.\n    vocHopSize :: HopSize,\n    -- | Window function used during analysis and synthesis.\n    vocWindow :: Window\n    -- TODO thread safety?\n}\n\n-- | FFT frequency frame length.\nvocFreqFrameLength :: VocoderParams -> Length\nvocFreqFrameLength par = planOutputSize $ vocFFTPlan par\n\n-- | FFT frame length. Can be larger than `vocInputFrameLength` for zero-padding.\nvocFrameLength :: VocoderParams -> Length\nvocFrameLength par = planInputSize $ vocFFTPlan par\n\n-- | STFT frame length.\nvocInputFrameLength :: VocoderParams -> Length\nvocInputFrameLength par = V.length $ vocWindow par\n\n-- | Create a vocoder configuration.\nvocoderParams :: Length -> HopSize -> Window -> VocoderParams\nvocoderParams len hs wnd = VocoderParams (plan dftR2C len) (plan dftC2R len) hs wnd\n\n-- | Apply a window function on a time domain frame.\napplyWindow :: Window -> Frame -> Frame\napplyWindow = V.zipWith (*)\n\n-- | Change the vector indexing so that the sample at the middle has the number 0.\n-- This is done so that the FFT of the window has zero phase, and therefore does not\n-- introduce phase shifts in the signal.\nrewind :: (V.Storable a) => V.Vector a -> V.Vector a\nrewind vec = uncurry (V.++) $ swap $ V.splitAt (V.length vec `div` 2) vec\n\n-- | Zero-pad the signal symmetrically from both sides.\naddZeroPadding :: Length\n    -> Frame\n    -> Frame\naddZeroPadding len v\n    | diff < 0  = error $ \"addZeroPadding: input is \" ++ (show diff) ++ \" samples longer than target length\"\n    | diff == 0 = v\n    | otherwise = res\n    where\n    l = V.length v\n    diff = len - l\n    halfdiff = diff - (diff `div` 2)\n    res = (V.++) ((V.++) (V.replicate halfdiff 0) v) (V.replicate (diff-halfdiff) 0)\n\n-- | Perform FFT processing, which includes the actual FFT, rewinding, zero-paddding\n-- and windowing.\ndoFFT :: VocoderParams -> Frame -> FFTOutput\ndoFFT par =\n    FFT.execute (vocFFTPlan par) . rewind . addZeroPadding (vocFrameLength par) . applyWindow (vocWindow par)\n\n-- | Perform analysis on a sequence of frames. This consists of FFT processing\n-- and performing analysis on frequency domain frames.\nanalysisStage :: Traversable t => VocoderParams -> Phase -> t Frame -> (Phase, t STFTFrame)\nanalysisStage par ph = mapAccumL (analysisBlock par) ph\n\n-- | Perform FFT transform and frequency-domain analysis.\nanalysisBlock :: VocoderParams -> Phase -> Frame -> (Phase, STFTFrame)\nanalysisBlock par prev_ph vec = analysisStep (vocHopSize par) (vocFrameLength par) prev_ph (doFFT par vec)\n\n-- | Analyze a frequency domain frame. Phase from a previous frame must be supplied.\n-- It returns the phase of the analyzed frame and the result.\nanalysisStep :: HopSize -> Length -> Phase -> FFTOutput -> (Phase, STFTFrame)\nanalysisStep h eN prev_ph vec =\n    (ph,(mag,ph_inc))\n    where\n    (mag, ph) = frameFromComplex vec\n    ph_inc = V.imap (calcPhaseInc eN h) $ V.zipWith (-) ph prev_ph\n\n-- | Wraps an angle (in radians) to the range [-pi : pi].\nwrap :: Double -> Double\nwrap e = (e+pi) `mod'` (2*pi) - pi\n\ncalcPhaseInc :: Length -> HopSize -> Int -> Double -> Double\ncalcPhaseInc eN hop k ph_diff =\n    (omega + wrap (ph_diff - omega)) / fromIntegral hop\n    where\n    omega = (2*pi*fromIntegral k*fromIntegral hop) / fromIntegral eN\n\n-- | Perform synthesis on a sequence of frames. This consists of performing\n-- synthesis and IFFT processing.\nsynthesisStage :: Traversable t => VocoderParams -> Phase -> t STFTFrame -> (Phase, t Frame)\nsynthesisStage par ph frs = mapAccumL (synthesisBlock par) ph frs\n\n-- | Perform frequency-domain synthesis and IFFT transform.\nsynthesisBlock :: VocoderParams -> Phase -> STFTFrame -> (Phase, Frame)\nsynthesisBlock par ph fr = (id *** doIFFT par) $ synthesisStep (vocHopSize par) ph fr\n\n-- | Synthesize a frequency domain frame. Phase from the previously synthesized frame\n-- must be supplied. It returns the phase of the synthesized frame and the result.\nsynthesisStep :: HopSize -> Phase -> STFTFrame -> (Phase, FFTOutput)\nsynthesisStep hop ph (mag, ph_inc) =\n    (new_ph, frameToComplex (mag, new_ph))\n    where\n    new_ph = V.zipWith (+) ph $ V.map (* fromIntegral hop) ph_inc\n\n-- | Perform IFFT processing, which includes the actual IFFT, rewinding, removing padding\n-- and windowing.\ndoIFFT :: VocoderParams -> FFTOutput -> Frame\ndoIFFT par =\n    applyWindow (vocWindow par) . cutCenter (vocInputFrameLength par) . rewind . FFT.execute (vocIFFTPlan par)\n\n-- | Cut the center of a time domain frame, discarding zero padding.\ncutCenter :: (V.Storable a) => Length -> V.Vector a -> V.Vector a\ncutCenter len vec = V.take len $ V.drop ((V.length vec - len) `div` 2) vec\n\n-- | Zero phase for a given vocoder configuration.\n-- Can be used to initialize the synthesis stage.\nzeroPhase :: VocoderParams -> Phase\nzeroPhase par = V.replicate (vocFreqFrameLength par) 0\n\n-- | An amplitude change coefficient for the processing pipeline.\n-- Can be used to ensure that the output has the same volume as the input.\nvolumeCoeff :: VocoderParams -> Double\nvolumeCoeff par = fromIntegral (vocHopSize par) / V.sum (V.map (**2) $ vocWindow par)\n\n-- | Converts frame representation to complex numbers.\nframeToComplex :: STFTFrame -> FFTOutput\nframeToComplex = uncurry $ V.zipWith mkPolar\n\n-- | Converts frame representation to magnitude and phase.\nframeFromComplex :: FFTOutput -> STFTFrame\nframeFromComplex = V.map magnitude &&& V.map phase\n\n-- | Adds STFT frames.\naddFrames :: STFTFrame -> STFTFrame -> STFTFrame\naddFrames f1 f2 = frameFromComplex $ V.zipWith (+) (frameToComplex f1) (frameToComplex f2)\n\n", "meta": {"hexsha": "03bb1c180401be3af7d1fa53518fdd5b24622a53", "size": 7853, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "vocoder/src/Vocoder.hs", "max_stars_repo_name": "tilk/vocoder", "max_stars_repo_head_hexsha": "540d489d87fdb5d0cdc0ee4e0bd7df774f734d47", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-02-01T17:51:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:31:50.000Z", "max_issues_repo_path": "vocoder/src/Vocoder.hs", "max_issues_repo_name": "tilk/vocoder", "max_issues_repo_head_hexsha": "540d489d87fdb5d0cdc0ee4e0bd7df774f734d47", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vocoder/src/Vocoder.hs", "max_forks_repo_name": "tilk/vocoder", "max_forks_repo_head_hexsha": "540d489d87fdb5d0cdc0ee4e0bd7df774f734d47", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0580357143, "max_line_length": 110, "alphanum_fraction": 0.707882338, "num_tokens": 2046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4696095974662506}}
{"text": "{-# LANGUAGE FlexibleContexts          #-}\n{-# LANGUAGE FlexibleInstances         #-}\n{-# LANGUAGE GADTs                     #-}\n{-# LANGUAGE MultiParamTypeClasses     #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE OverloadedStrings         #-}\n{-# LANGUAGE PolyKinds                 #-}\n{-# LANGUAGE RankNTypes                #-}\n{-# LANGUAGE ScopedTypeVariables       #-}\n{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}\n\nmodule Math.HMatrixUtils where\n\nimport qualified Knit.Effect.Logger            as KL\nimport qualified Knit.Report                   as K\nimport qualified Data.Text                     as T\n\nimport qualified Numeric.LinearAlgebra         as LA\nimport           Numeric.LinearAlgebra.Data     ( Matrix\n                                                , R\n                                                , Vector\n                                                )\n\n\ntextSize :: (LA.Container c e, Show (LA.IndexOf c)) => c e -> T.Text\ntextSize = T.pack . show . LA.size\n\ncheckEqualVectors\n  :: K.Member (KL.Logger KL.LogEntry) effs\n  => T.Text\n  -> T.Text\n  -> Vector R\n  -> Vector R\n  -> K.Sem effs ()\ncheckEqualVectors nA nB vA vB = if LA.size vA == LA.size vB\n  then return ()\n  else\n    KL.logLE KL.Error\n    $  \"Unequal vector length. length(\"\n    <> nA\n    <> \")=\"\n    <> textSize vA\n    <> \" and length(\"\n    <> nB\n    <> \")=\"\n    <> textSize vB\n\ncheckMatrixVector\n  :: K.Member (KL.Logger KL.LogEntry) effs\n  => T.Text\n  -> T.Text\n  -> Matrix R\n  -> Vector R\n  -> K.Sem effs ()\ncheckMatrixVector nA nB mA vB = if snd (LA.size mA) == LA.size vB\n  then return ()\n  else\n    KL.logLE KL.Error\n    $  \"Bad matrix * vector lengths. dim(\"\n    <> nA\n    <> \")=\"\n    <> textSize mA\n    <> \" and length(\"\n    <> nB\n    <> \")=\"\n    <> textSize vB\n\ncheckVectorMatrix\n  :: K.Member (KL.Logger KL.LogEntry) effs\n  => T.Text\n  -> T.Text\n  -> Vector R\n  -> Matrix R\n  -> K.Sem effs ()\ncheckVectorMatrix nA nB vA mB = if LA.size vA == fst (LA.size mB)\n  then return ()\n  else\n    KL.logLE KL.Error\n    $  \"Bad vector * matrix lengths. length(\"\n    <> nA\n    <> \")=\"\n    <> textSize vA\n    <> \" and dim(\"\n    <> nB\n    <> \")=\"\n    <> textSize mB\n", "meta": {"hexsha": "d2b700c4818e16d9f7e81350aa12deabe7dafe66", "size": 2167, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/HMatrixUtils.hs", "max_stars_repo_name": "teto/Frames-utils", "max_stars_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "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/Math/HMatrixUtils.hs", "max_issues_repo_name": "teto/Frames-utils", "max_issues_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "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/Math/HMatrixUtils.hs", "max_forks_repo_name": "teto/Frames-utils", "max_forks_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "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": 24.908045977, "max_line_length": 68, "alphanum_fraction": 0.5237655745, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46960958422563975}}
{"text": "{-# OPTIONS_GHC -fno-warn-dodgy-exports #-}\n{- | an incomplete extension of dimensional-tf to work with hmatrix and ad\nHaddocks are organized to follow hmatrix\n\nnote: for subscripting, use the 'HNat' while the units still use 'N.NumType'\n\nTODO:\n\n*  Friendly syntax for introduction (more matD)\n\n*  Friendly syntax for elimination (matD as pattern)\n\n*  A pretty-printer that multiplies out the dimensions at each place?\n   The current show instance makes you mentally multiply out row and column units\n   (which helps you to see the big picture, but may be more work in other cases)\n\n*  check that all types that could could be inferred are\n\n*  default columns/rows to dimensionless?\n\n*  missing operations (check export list comments)\n-}\nmodule DimMat.Internal  where\n\nimport Foreign.Storable (Storable)      \nimport GHC.Exts (Constraint)\n\n-- import Data.Type.Equality (type (==))\nimport qualified Prelude as P\nimport Prelude (Double)\nimport Numeric.Units.Dimensional hiding (Mul, Div)\nimport Numeric.Units.Dimensional.Prelude hiding (Mul, Div)\nimport qualified Numeric.Units.Dimensional as D\n\nimport qualified Numeric.LinearAlgebra as H\nimport qualified Numeric.LinearAlgebra.LAPACK as H\n\nimport Text.PrettyPrint.ANSI.Leijen\nimport Data.List (transpose)\n\nimport Data.HList.CommonMain hiding (MapFst)\n\n-- * Replacements for Dimensional classes\n\n-- | a version of Numeric.Units.Dimensional.'D.Mul' which\n-- requires the arguments to include the 'D.Dim' type constructor\nclass (D.Mul a b c) => Mul a b c\n\ninstance (D.Mul a b c,\n       a ~ Dim l m t i th n j,\n       b ~ Dim l' m' t' i' th' n' j',\n       c ~ Dim l'' m'' t'' i'' th'' n'' j'') =>\n       Mul a b c\n\n-- | a version of Numeric.Units.Dimensional.'D.Div' which\n-- requires the arguments to include the 'D.Dim' type constructor\nclass (D.Div a b c) => Div a b c\n\ninstance (D.Div a b c,\n       a ~ Dim l m t i th n j,\n       b ~ Dim l' m' t' i' th' n' j',\n       c ~ Dim l'' m'' t'' i'' th'' n'' j'') =>\n       Div a b c\n\n-- * AD\n{- $ad\nTODO: gradients, hessians, etc.\n\nTypes for derivative towers can see hlist's @HList\\/Data\\/HList\\/broken\\/Lazy.hs@,\nbut laziness doesn't really make much sense if the @take@ that is eventually used\nto get a finite list for printing etc.\n\nComplications include the fact that AD.grad needs a traversable,\nbut hmatrix stuff is not traversable (due needing Storable). In ipopt-hs\nI got around this problem by copying data. Perhaps that is the solution?\n\n> BROKEN\n> grad :: (Num a, AreRecips i iinv, H.Element a, Storable a,\n>           MapMultEq o iinv r) =>\n>         (forall s. (AD.Mode s, H.Container H.Vector (AD.AD s a),\n>                     Storable (AD.AD s a), H.Field (AD.AD s a))\n>                 => DimMat '[i] (AD.AD s a)\n>                 -> Quantity o (AD.AD s a))\n>      -> DimMat '[i] a\n>      -> DimMat '[r] a\n> grad f (DimVec x) = DimMat (H.fromLists [AD.grad (unQty . f . DimVec . H.fromList) (H.toList x)])\n>     where unQty (Dimensional a) = a\n-}\n\n#ifdef WITH_AD\n{- |\n>>> let ke velocity = velocity*velocity*(1*~kilo gram)\n>>> diff ke (3 *~ (metre/second))\n6.0 m^-1 kg^-1 s\n-}\n\ndiff :: (Num a) =>\n        (forall s. AD.Mode s => Dimensional v x (AD.AD s a)\n                             -> Dimensional v y (AD.AD s a))\n        -> Dimensional v x a -> Dimensional v (Div x y) a\ndiff f z = Dimensional $ AD.diff (unD . f . Dimensional) (unD z)\n    where unD (Dimensional a) = a\n#endif\n\n\n\n\n\n-- * GADT for linear algebra with units\n\n{- | Generalization of 'Dimensional' to matrices and vectors. Units\nin each coordinate are known at compile-time. This wraps up HMatrix.\n\n[@ 'DMat' @] the units at coordinate ij are @(r1 ': r)_i (DOne ': c)_j@\n\n[@ 'DVec' @] the units at coordinate i are @(r1 ': r)_i@\n\n[@ DScal @] is the same as Dimensional\n-}\ndata D (sh :: ( *, [[ * ]])) e where\n  DMat :: (H.Container H.Matrix e, H.Field e)\n    => H.Matrix e -> D '(r1,[r, c]) e\n  DVec :: (H.Container H.Vector e, H.Field e)\n    => H.Vector e -> D '(r1, '[r]) e\n  DScal :: (H.Field e) => e -> D '(r1,'[]) e\n\ninstance (Show a, PPUnits sh) => Pretty (D sh a) where\n    pretty (DVec v) = case ppUnits (Proxy :: Proxy sh) of\n        [rs] -> vcat\n             [ dullgreen (string label) <+> string (show e)\n                | (e,label) <- H.toList v `zip` pad rs ]\n    pretty (DMat m) = case ppUnits (Proxy :: Proxy sh) of\n        [rs,cs] -> \n            vcat $\n            map (hsep . onHead dullgreen) $\n            transpose $ map (onHead dullgreen . map string . pad) $\n            zipWith (\\a b -> a:b)\n                ((show (H.rows m) ++ \"><\"++ show (H.cols m)) : cs) $\n            transpose $\n            zipWith (\\r e -> r : map show e) rs (H.toLists m)\n        where\n            onHead f (x:xs) = f x : xs\n            onHead _ [] = []\n\ninstance Pretty (D sh a) => Show (D sh a) where\n    showsPrec p x = showsPrec p (pretty x)\n\n-- ** pretty instance\npad :: [String] -> [String]\npad [] = []\npad xs = let\n    w = maximum (map length xs)\n    in map (\\x -> take w $ x ++ replicate w ' ') xs\n\n\nclass PPUnits (sh :: k) where\n    ppUnits :: Proxy sh -> [[String]]\n\ninstance forall (r1 :: *) (r::[*]) (c :: [*]) l m t i th n j.\n      (PPUnits [r1 ': r, c], Show (Quantity r1 Int), PPUnits' c, PPUnits' r,\n       r1 ~ Dim l m t i th n j) => PPUnits '(r1, [r,c]) where\n    ppUnits _ = ppUnits (Proxy :: Proxy [r1 ': r, DOne ': c])\n\ninstance (PPUnits' x, PPUnits xs) => PPUnits (x ': xs) where\n    ppUnits _ = ppUnits' (Proxy :: Proxy x) : ppUnits (Proxy :: Proxy xs)\ninstance PPUnits '[] where\n    ppUnits _ = []\n\nclass PPUnits' (sh :: [ * ]) where\n    ppUnits' :: Proxy sh -> [String]\ninstance (PPUnits' xs) => PPUnits' (DOne ': xs) where\n    ppUnits' _ = \"1\" : ppUnits' (Proxy :: Proxy xs)\ninstance (ShowDimSpec x, PPUnits' xs) => PPUnits' (x ': xs) where\n    ppUnits' _ = showDimSpec (Proxy :: Proxy x) : ppUnits' (Proxy :: Proxy xs)\ninstance PPUnits' '[] where\n    ppUnits' _ = []\n\nclass ShowDimSpec a where\n    showDimSpec :: Proxy a -> String\n\ninstance (Show (Quantity a Int), Dim l m t i th n j ~ a) => ShowDimSpec a where\n    showDimSpec _ = case drop 2 $ show (1 *~ (Dimensional 1 :: Unit a Int)) of\n          \"\" -> \"1\"\n          x -> x\n\n-- * Constraints\n{- $justification\nA major theme in this library is that type inference goes in whichever direction\nit can: in ordinary haskell it is very common for argument types to be determined\nby the result types. For example see any code that uses 'Num' or 'Read'.\n\nWhen we use type families, things look more convenient:\n\n@\ndata Nat = S Nat | Z\n\ntype family Add (a :: Nat) (b :: Nat) :: Nat\ntype instance Add Z b = b\ntype instance Add (S a) b = Add a (S b)\n@\n\nBut ghc is unable to deduce things like @a ~ Z@ given evidence such as @Add Z a ~ Z@.\nOne way around this is to use @ConstraintKinds@:\n\n@\ntype AddT (a :: Nat) (b :: Nat) (c :: Nat)\n          = (Add a b ~ c, Sub c a ~ b, Sub c b ~ a)\n@\n\nWhich leads to functions like  @f :: AddT a b ab => ... @. This is bad for a couple reasons:\n\n* the right-hand-side of the type can only mention type variables on the\n  left-hand-side.\n* the left hand side can only bind type variables. Working around this\n  leads to many auxiliary type families such as Fst, Snd and Head, or\n  leads to a @type family AddT@\n\nSo below many constraints expressed as classes, since they have less\nof those limitations.\n\n-}\n\n-- | @a*b = c@ when any are lists\nclass MultEq (a :: k1) (b :: k2) (c :: k3)\n\n-- instance (Zip3 MultEq aas bbs ccs) => MultEq aas bbs ccs\ninstance Zip3 Mul as bs cs => MultEq as bs cs\ninstance Zip1 Mul as b  c  => MultEq as b  c\ninstance Zip1 Mul bs a  c  => MultEq a  bs c\ninstance (Zip1 Mul cs aInv b,\n          Mul a aInv DOne) => MultEq a  b  cs\n\ninstance (SameLength as bs,\n        Zip2 Mul as bs c)  => MultEq as bs c\ninstance (SameLength as cs,\n          Zip2 Div as cs bInv,\n          Mul b bInv DOne) => MultEq as b  cs\ninstance (Zip2 Div bs cs aInv,\n          SameLength bs cs,\n          Mul a aInv DOne) => MultEq a  bs cs\ninstance Mul a b c => MultEq a b c\n\n\n-- ** Zip\n\nclass (SameLength a b, SameLength b c) =>\n    Zip3\n      (op :: k -> k -> k -> Constraint)\n      (a :: [k])\n      (b :: [k])\n      (c :: [k])\n\ninstance (SameLength aas bbs,\n          SameLength ccs bbs,\n          op a b c,\n          (a ': as) ~ aas,\n          (b ': bs) ~ bbs,\n          (c ': cs) ~ ccs,\n          Zip3 op as bs cs) => Zip3 op aas bbs ccs\ninstance Zip3 op '[] '[] '[]\n\n\nclass (SameLength a b) =>\n    Zip2\n      (op :: k -> k -> k -> Constraint)\n      (a :: [k])\n      (b :: [k])\n      (c ::  k)\n\ninstance (SameLength aas bbs,\n      op a b c,\n      (a ': as) ~ aas,\n      (b ': bs) ~ bbs,\n      Zip2 op as bs c) => Zip2 op aas bbs c\n\ninstance Zip2 op '[] '[] c\n\nclass Zip1\n      (op :: k -> k -> k -> Constraint)\n      (a :: [k])\n      (b ::  k)\n      (c ::  k)\n\ninstance ((a ': as) ~ aas,\n    op a b c,\n    Zip1 op as b c) => Zip1 op aas b c\n\ninstance Zip1 op '[] b c\n\n\n{- | given @ijs :: [[Quantity a]]@ (except the : and [] constructors are\nactually (,) and (), ie. a HList that doesn't use the HList constructors),\ncalculate a @DimMat rowUnits colUnits@, where the outer product of rowUnits\nand colUnits gives the units at each index in the ijs.  The first element\nof colUnits is DOne.\n-}\nclass (SameLength a ab) => Outer a b ab\ninstance Outer '[] b '[]\ninstance (SameLength aas ccs,\n          (a ': as) ~ aas,\n          (c ': cs) ~ ccs,\n          MultEq a b c,\n          Outer as b cs) \n  => Outer aas b ccs\n\n-- * DimMatFromTuple\nclass DimMatFromTuple ijs r1 r c e\n\n\ntype family TupleToHListU (a :: *) :: [*]\ntype instance TupleToHListU (a, b) = () ': TupleToHListU b\ntype instance TupleToHListU () = '[]\n\ntype family TuplesToHListU (a :: *) :: [[*]]\ntype instance TuplesToHListU (a, b) = TupleToHListU a ': TuplesToHListU b \ntype instance TuplesToHListU () = '[]\n\ninstance (Outer (r1 ': r) (DOne ': c) ijs',\n      DMFromTuple1 e ijs ijs',\n      SameLength (TuplesToHListU ijs) ijs') => DimMatFromTuple ijs r1 r c e\n\n-- | helper for 'DimMatFromTuple'\ntype family DMFromTuple1 e b (b' :: [[*]]) :: Constraint\ntype family DMFromTuple2 e b (b' :: [*]) :: Constraint\ntype family DMFromTuple3 e b b' :: Constraint\n\ntype instance DMFromTuple3 e (Quantity b e') b' = (e ~ e', b ~ b')\ntype instance DMFromTuple1 e (x, xs) (x' ': xs') = (TupleToHListU x `SameLength` x',\n                                                    DMFromTuple2 e x x', DMFromTuple1 e xs xs')\ntype instance DMFromTuple1 e () xs = (xs ~ '[])\ntype instance DMFromTuple2 e (x, xs) (x' ': xs') = (DMFromTuple3 e x x', DMFromTuple2 e xs xs')\ntype instance DMFromTuple2 e () xs = (xs ~ '[])\n\n-- | just for types produced by the matD quasiquote\ntoDM :: DimMatFromTuple ijs r1 r c e => ijs -> Proxy (D '(r1, [r, c]) e)\ntoDM _ = Proxy\n\n\n-- | @InnerCxt t a b = t ~ 'H.dot' a b@\ntype family InnerCxt (t :: k) (a :: [k]) (b :: [k]) :: Constraint\ntype instance InnerCxt t (a ': as) (b ': bs) = (MultEq a b t, InnerCxt t as bs)\ntype instance InnerCxt t '[] '[] = ()\n\nclass (SameLength a b, InnerCxt c a b) => Inner (a :: [*]) (b :: [*]) (c :: *)\n\ninstance (SameLength aas bbs, InnerCxt c aas bbs) => Inner aas bbs c\n\n-- | @ProdEq a b@ is @product a ~ b@\nclass ProdEq a b\ninstance (ProdEq as b', Mul a b' b) => ProdEq (a ': as) b\ninstance (dOne ~ DOne) => ProdEq '[] dOne\n\n-- | @RecipEq a aInv@ is @a*aInv ~ DOne@ (or a list of DOne)\nclass RecipEq (a :: k) (aInv :: k)\ninstance (MultEq as aInvs DOne) => RecipEq as aInvs\n\n\n-- | @AtEq a n b m c@ calculates @(At a n \\`Mult\\` At b m) ~ c@,\n-- but also can infer part of the `a` if the `b` and `c` are known\ntype family AtEq2 (a :: [k]) (n :: HNat) (b :: [k]) (m :: HNat) (c :: k) :: Constraint\ntype instance AtEq2  (a ': as) HZero (b ': bs) HZero c = (MultEq a b c)\ntype instance AtEq2  (a ': as) (HSucc n) bs m c = AtEq2 as n bs m c\ntype instance AtEq2  as HZero (b ': bs) (HSucc m) c = AtEq2 as HZero bs m c\n\ntype family AtEq (a :: [k]) (n :: HNat) (b :: k) :: Constraint\ntype instance AtEq (a ': as) HZero b = (a ~ b)\ntype instance AtEq (a ': as) (HSucc n) b = AtEq as n b\n\n-- | Data.Packed.Vector.'H.@>'\n(@>) :: (HNat2Integral i, AtEq r i ri, MultEq r1 ri u)\n    => D '(r1,'[r]) a\n    -> Proxy i\n    -> Quantity u a\nDVec v @> i = Dimensional (v H.@> hNat2Integral i)\n\n-- | Data.Packed.Matrix.'H.@@>'\n(@@>) :: (HNat2Integral i, HNat2Integral j, AtEq2 (r1 ': r) i (DOne ': c) j ty)\n    => D '(r1, [r,c]) a\n    -> (Proxy i, Proxy j)\n    -> Quantity ty a\nDMat m @@> (i,j) = Dimensional (m H.@@> (hNat2Integral i,hNat2Integral j))\n\npnorm :: (AllEq r1 r, AllEq DOne c)\n         => H.NormType -> D '(r1, [r, c]) a -> Quantity r1 (H.RealOf a)\npnorm normType (DMat a) = Dimensional (H.pnorm normType a)\n\n{- | @AllEq a xs@ is like @all (all (a==)) xs@, @all (a ==) xs@, @a == xs@:\nwhichever amount of [ ] is peeled off before making the comparison (with ~)\n-}\nclass AllEq (a :: k1) (xs :: k2)\n\ninstance (a ~ x, AllEq a xs) => AllEq a (x ': xs)\ninstance AllEq a '[]\ninstance AllEq '[] xs\ninstance (AllEq a xs, AllEq as xs) => AllEq (a ': as) xs\n\n\n\n{- | @c = a `dot` b@ is one of:\n\n> c_ij = sum_j a_ij b_jk\n> c_k  = sum_j a_j  b_jk\n> c_i  = sum_j a_ij b_j\n> c    = sum_j a_j  b_j\n\n-}\nclass Dot a b c {- | a b -> c -} where\n    dot :: H.Element e => D a e -> D b e -> D c e\n\ninstance\n    ( MultEq (a ': ra) b (c ': rc),\n      MultEq ca rb b,\n      shA ~ '(a,[ra, ca]),\n      shB ~ '(b, rb ': cb),\n      shC ~ '(c, rc ': cb))\n    => Dot shA shB shC where\n    dot (DMat a) (DMat b) = DMat (H.multiply a b)\n    dot (DMat a) (DVec b) = DVec (H.mXv a b)\n    {-\n    dot (DVec a) (DMat b) = DVec (H.vXm a b)\n    dot (DVec a) (DVec b) = DScal (H.dot a b)\n    -}\n\nclass DotS s a b\n\ninstance (rest' ~ rest, MultEq s (a ': as) (b ': bs))\n    => DotS s '(a, as ': rest) '(b, bs ': rest')\n\n\nclass Trans a b where\n    trans :: D a e -> D b e\n\ninstance (a ~ '(r1, [x,y]),\n          b ~ '(r1, [y,x]))\n    => Trans a b where\n    trans (DMat a) = DMat (H.trans a)\n\n{- | type for a pseudoinverse (and inverse):\n\nThe single instance comes from looking at inverses from a 2x2 matrix (let's call A):\n\n> a b\n> c d\n\nand the inverse * determinant of the original\n\n>  d  -b\n> -c   a\n\nIn the product A * A^-1 the diagonal is dimensionless ('DOne').\n\nThat happens if the row and column type-level unit lists are reciprocals of\neachother ('AreRecips'), so the constraint on the instance of PInv encodes\nthis exactly (plus some constraints requiring that sh and sh' are at least\n1x1)\n-}\nclass PInv a b where\n  pinv :: D a e -> D b e\n\ntype family LengthSndTwo (a :: k) :: Constraint\ntype instance LengthSndTwo '(a, as) = SameLength as '[(), ()]\n\n\ntype AreRecips a b = MultEq a b DOne\ninstance (MultEq ra cb a,\n          MultEq ca rb b,\n          AreRecips a b,\n          bSh ~ '(b, [rb, cb]),\n          aSh ~ '(a, [ra, ca]))\n    => PInv aSh bSh where\n  pinv (DMat a) = DMat (H.pinv a)\n\ninv :: (PInv a b,\n        b ~ '(t1, [t2, t3]))\n  => D a e -> D b e\ninv (DMat a) = DMat (H.inv a)\n\n       \n\npinvTol :: (PInv a b,\n           b ~ '(t1, [t2, t3]) )\n  => Double -> D a e -> D b e\npinvTol tol (DMat a) = DMat (H.pinvTol tol a)\n\n\nclass Det a b where\n    det :: D a e -> Quantity b e\n\ninstance (SameLength r c,\n       ProdEq (r1 ': r) (pr :: *),\n       ProdEq c (pc :: *),\n       MultEq pr pc b,\n       a ~ '(r1, [r, c])) =>\n    Det a b where\n  det (DMat a) = Dimensional (H.det a)\n\n{- | Numeric.LinearAlgebra.Algorithms.'H.expm'\n\n@y t = expm (scale t a) \\`multiply\\` y0@ solves the DE @y' = Ay@ where y0 is the\nvalue of y at time 0\n\n-}\nexpm :: (AreRecips r c)\n    => D '(r1, [r, c]) a\n    -> D '(r1, [r, c])  a\nexpm (DMat a) = DMat (H.expm a)\n\n{- | Numeric.Container.'H.scale'\n\n-}\nclass Scale a b c where\n  scale :: Quantity a e -> D b e -> D c e\n\nfromQty :: H.Field e => Quantity a e -> D '(a, '[]) e\nfromQty (Dimensional a) = DScal a\n\ntoQty :: D '(a, '[]) e -> Quantity a e\ntoQty (DScal a) = Dimensional a\n\ninstance (MultEq a (r1 ': r) (r1' ': r'),\n      b ~ '(r1, r ': rs),\n      c ~ '(r1', r' ': rs)) =>\n  Scale a b c where\n  scale (Dimensional t) (DMat a) = DMat (H.scale t a)\n  scale (Dimensional t) (DVec a) = DVec (H.scale t a)\n\n{- | Numeric.Container.'H.scaleRecip'\n-}\nclass ScaleRecip a b c where\n  scaleRecip :: D '(a, '[]) e -> D b e -> D c e\n\nclass ScaleRecip1 (bool :: Bool) a b c where\n  scaleRecip1 :: Proxy bool -> D '(a, '[]) e -> D b e -> D c e\n\ninstance\n  (ScaleRecipCxt r1 r1' r r' rs rs' a b c\n   , rs' ~ '[ t1 ]\n   ) => ScaleRecip1 True a b c where\n  scaleRecip1 _ (DScal t) (DMat a) = DMat (H.scaleRecip t a)\n\ninstance\n  (ScaleRecipCxt r1 r1' r r' rs rs' a b c,\n   rs' ~ '[]) =>\n  ScaleRecip1 False a b c where\n  scaleRecip1 _ (DScal t) (DVec a) = DVec (H.scaleRecip t a)\n\ninstance (HEq (HLength bs) (HSucc (HSucc HZero)) bool1,\n          HEq (HLength cs) (HSucc (HSucc HZero)) bool1,\n    ScaleRecip1 bool1 a '(b, bs) '(c, cs)) => ScaleRecip a '(b, bs) '(c, cs) where\n  scaleRecip = scaleRecip1 (Proxy :: Proxy bool1)\n\n\ntype ScaleRecipCxt (r1 :: *) (r1' :: *) r r' rs rs' (a :: *) b c =\n  (MultEq a (r1' ': r') (r1 ': r) ,\n   MultEq rs rs' DOne,\n   b ~ '(r1, r ': rs),\n   c ~ '(r1', r' ': rs'))\n\n\n-- | a shortcut for @scaleRecip (DScal 1)@\nrecipMat :: forall b c e. (H.Field e, ScaleRecip DOne b c) => D b e -> D c e\nrecipMat m = scaleRecip (DScal 1 :: D '(DOne, '[]) e) m\n\n\nliftH2 :: \n  ( forall h f. (H.Container f e, h ~ f e) => h -> h -> h) ->\n    D a e -> D a e -> D a e\nliftH2 f (DMat a) (DMat b) = DMat (f a b)\nliftH2 f (DVec a) (DVec b) = DVec (f a b)\n\nadd a b = liftH2 H.add a b\nsub a b = liftH2 H.sub a b\n\nmulMat :: ( MultEq as bs cs, MultEq a b c, cs ~ '[t1 , t2] )\n  => D '(a,as) e -> D '(b,bs) e -> D '(c,cs) e\nmulMat (DMat a) (DMat b) = DMat (H.mul a b)\n\nmulVec :: ( MultEq as bs cs, MultEq a b c, cs ~ '[t1] )\n  => D '(a,as) e -> D '(b,bs) e -> D '(c,cs) e\nmulVec (DVec a) (DVec b) = DVec (H.mul a b)\n\ndivideMat :: ( MultEq as cs bs, MultEq a c b, cs ~ '[t1 , t2] )\n  => D '(a,as) e -> D '(b,bs) e -> D '(c,cs) e\ndivideMat (DMat a) (DMat b) = DMat (H.divide a b)\n\ndivideVec :: ( MultEq as cs bs, MultEq a c b, cs ~ '[t1] )\n  => D '(a,as) e -> D '(b,bs) e -> D '(c,cs) e\ndivideVec (DVec a) (DVec b) = DVec (H.divide a b)\n\narctan2 :: (bs ~ MapMapConst DOne as) => D '(a,as) e -> D '(a,as) e -> D '(b,bs) e\narctan2 (DMat a) (DMat b) = DMat (H.arctan2 a b)\narctan2 (DVec a) (DVec b) = DVec (H.arctan2 a b)\n\nequal :: D a e -> D a e -> Bool\nequal (DMat a) (DMat b) = H.equal a b\nequal (DVec a) (DVec b) = H.equal a b\n\n{- | @cmap f m@ gives a matrix @m'@\n\n@f@ is applied to \n\n-}\nclass CMap f a b e e' where\n    cmap :: f -> D a e -> D b e'\n\n-- | Maybe there's a way to implement in terms of the real cmap (possibly\n-- unsafeCoerce?)\ninstance\n    (ToHLists sh e xs,\n     FromHLists xs' sh' e',\n     SameLength xs xs',\n     HMapCxt HList (HMap f) xs xs') =>\n    CMap f sh sh' e e' where\n  cmap f m = fromHLists (HMap f `hMap` (toHLists m :: HList xs) :: HList xs')\n\ntype family AppendEq' (a :: [k]) (b :: [k]) (ab :: [k]) :: Constraint\ntype instance AppendEq' (a ': as) b (a' ': abs) = (a ~ a', AppendEq' as b abs)\ntype instance AppendEq' '[] b abs = (b ~ abs)\n\n-- | a bit overkill?\n--  @a ++ b = ab@\ntype AppendEq a b ab =\n   (ab ~ HAppendR a b,\n    AppendEq' a b ab,\n    SameLength (DropPrefix a ab) b,\n    SameLength (DropPrefix b ab) a)\n\n\ntype instance HAppendR (x ': xs) ys = x ': HAppendR xs ys\ntype instance HAppendR '[] ys = ys\n\n\ntype family DropPrefix (a :: [k]) (ab :: [k]) :: [k]\ntype instance DropPrefix (a ': as) (a' ': abs) = DropPrefix as abs\ntype instance DropPrefix '[] bs = bs\n\n{- | the slightly involved type here exists because\nci1 and ci2 both start with DOne, but ci2's contribution\nto ci3 does not need a DOne at the start. Another way to\nread the constraints here is:\n\n> map (*rem) (a11 : ri) = b11 : bi\n> ci3 = ci1 ++ map (*rem) ci2\n\nThe same idea happens with vconcat.\n-}\nhconcat ::\n    ( MultEq (rem :: *) a b,\n      MultEq rem ra rb,\n      MultEq rem (DOne ': cb) cb',\n      AppendEq ca cb' cc ) =>\n    D '(a, [ra,ca]) e -> D '(b, [rb, cb]) e -> D '(a, [ra, cc]) e\nhconcat (DMat a) (DMat b) = DMat (H.fromBlocks [[a, b]])\n\nvconcat :: (AppendEq ra (b ': rb) rc) =>\n    D '(a, '[ra,ca]) e -> D '(b, '[rb,ca]) e -> D '(a, '[rc,ca]) e\nvconcat (DMat a) (DMat b) = DMat (H.fromBlocks [[a],[b]])\n\nrank, rows, cols :: D t a -> Int \nrank (DMat a) = H.rank a\nrows (DMat a) = H.rows a\ncols (DMat a) = H.cols a\n\n-- | H.'H.rows' except type-level\nrowsNT :: D '(a, r ': c) e -> Proxy (HLength (a ': ri))\nrowsNT _ = Proxy\n\n-- | H.'H.cols' except type-level\ncolsNT :: D '(a, r ': c ': cs) e -> Proxy (HLength (DOne ': c))\ncolsNT _ = Proxy\n\n-- | (m `hasRows` n) constrains the matrix/vector @m@ to have @n@ rows\nhasRows :: (SameLength (HReplicateR n ()) r, -- forwards\n            HLength r ~ n -- backwards\n    ) => D '(a, ra ': ca) e -> Proxy (n :: HNat) -> D '(a, ra ': ca) e\nhasRows x _ = x\n\n-- | (m `hasRows` n) constrains the matrix/vector @m@ to have @n@ rows\nhasCols :: (SameLength (HReplicateR n ()) ci, -- forwards\n            HLength ci ~ n -- backwards\n    ) => D '(a, ra ': ca ': rest) e -> Proxy (n :: HNat) -> D '(a, ra ': ca ': rest) e\nhasCols x _ = x\n\n-- | H.'H.scalar'\nclass (MapConst '[] as ~ as) => Scalar as where\n    scalar :: D '(a, '[]) e -> D '(a, as) e\n\ninstance Scalar '[ '[] ] where\n  scalar (DScal a) = DVec (H.scalar a)\n\ninstance Scalar '[ '[], '[] ] where\n  scalar (DScal a) = DMat (H.scalar a)\n\n{- | Numeric.Container.'H.konst', but the size is determined by the type.\n\n>>> let n = hSucc (hSucc hZero) -- 2\n>>> konst ((1::Double) *~ second) `hasRows` n `hasCols` n\n2><2 1   1  \ns    1.0 1.0\ns    1.0 1.0\n\n-}\nkonst :: forall e a ra ca.\n    (H.Field e,\n     HNat2Integral (HLength (a ': ra)),\n     HNat2Integral (HLength (DOne ': ca)),\n     AllEq DOne ca,\n     AllEq a ra)\n    => D '(a, '[]) e -> D '(a, '[ra, ca]) e\nkonst (DScal a) = DMat (H.konst a\n    (hNat2Integral (Proxy :: Proxy (HLength (a ': ra))),\n     hNat2Integral (Proxy :: Proxy (HLength (DOne ': ca)))))\n\n\n-- | identity matrix. The size is determined by the type.\nident :: forall ones e.\n    (H.Field e, HNat2Integral (HLength (DOne ': ones))) =>\n    D '(DOne, [ones, ones]) e\nident = DMat (H.ident (hNat2Integral (Proxy :: Proxy (HLength (DOne ': ones)))))\n\n-- | zero matrix. The size and dimension is determined by the type.\nzeroes :: forall c a r e. (H.Field e,\n                        HNat2Integral (HLength (a ': r)),\n                        HNat2Integral (HLength (DOne ': c)))\n    => D '(a, '[r, c]) e\nzeroes = DMat (H.konst 0\n        (hNat2Integral (Proxy :: Proxy (HLength (a ': r))),\n         hNat2Integral (Proxy :: Proxy (HLength (DOne ': c)))))\n\ntype family CanAddConst (a :: k) (m :: [[k]]) :: Constraint\ntype instance CanAddConst a [as, ones] = (AllEq a as, AllEq '[] ones)\ntype instance CanAddConst a '[as] = (AllEq a as)\n\naddConstant :: (H.Field e, CanAddConst a sh)\n    => D '(a, '[]) e\n    -> D '(a, sh) e\n    -> D '(a, sh) e\naddConstant (DScal a) (DMat b) = DMat (H.addConstant a b)\naddConstant (DScal a) (DVec b) = DVec (H.addConstant a b)\n\nconj :: D sh a -> D sh a\nconj (DMat a) = DMat (H.conj a)\nconj (DVec a) = DVec (H.conj a)\n\n-- | conjugate transpose\nctrans x = conj . trans $ x\n\ndiag :: (MapConst DOne r ~ c, SameLength r c)\n  => D '(a, '[r]) t -> D '(a, '[r,c]) t\ndiag (DVec a) = DMat (H.diag a)\n\n-- | 'H.blockDiag'. The blocks should be provided as:\n--\n-- @blockDiag $ 'hBuild' m1 m2 m3@\n--\n-- only available if hmatrix >= 0.15\ndiagBlock :: (HMapOut UnDimMat (b ': bs) (H.Matrix e),\n              Num e, H.Field e, AppendShOf b bs (D '(a, sh) e),\n              sh ~ '[r,c])\n  => HList (b ': bs)\n  -> D '(a, sh) e\ndiagBlock pairs = DMat (H.diagBlock (hMapOut UnDimMat pairs))\n\ndata UnDimMat = UnDimMat\ninstance (D sh a ~ x, H.Matrix a ~ y) => ApplyAB UnDimMat x y where\n        applyAB _ (DMat x) = x\n\nclass DiagBlock (bs :: [*]) t\n\n-- | @AppendShOf a [b,c,d] aas@ makes aas have the type of a matrix that\n-- has a,b,c,d along the diagonal\nclass AppendShOf a (as :: [*]) aas\ninstance \n (e ~ f, f ~ g,\n  AppendShOf (D ab e) ds z,\n  AppendDims a b ab,\n     \n  -- constraints to force D in the type\n  x ~ D a e,\n  y ~ D b f,\n  z ~ D c g) =>\n  AppendShOf x (y ': ds) z \ninstance (x ~ z) => AppendShOf x '[] z\n\nclass AppendDims (a :: (*, [[*]])) (b :: (*, [[*]])) (c :: (*, [[*]]))\n    | a b -> c, c a -> b, c b -> a\ninstance (c ~ a, AppendEq ra (b ': rb) rc, AppendEq ca cb cc) =>\n  AppendDims '(a, [ra,ca]) '(b, [rb,cb]) '(c, [rc,cc])\n-- how to handle vectors?\n--type instance AppendDims '(a, '[ra]) '(b, '[rb]) = '(a, '[HAppendR ra (b ': rb)])\n\nclass ToHList sh e result where\n    toHList :: D sh e -> HList result\n\n-- | given a vector like @x = DimMat '[units] e@ this does something like\n-- @[ (x \\@> i) | i <- [1 .. n] ]@, if we had comprehensions for HLists\ninstance \n    (HListFromList e e1,\n     SameLength result e1,\n     HMapCxt HList AddDimensional e1 result,\n     -- HMapAddDimensional result e1,\n     ToHListRow (r ': rs) e result) =>\n   ToHList '(r, '[rs]) e result where\n  toHList (DVec v) = case hListFromList (H.toList v) :: HList e1 of\n      e1 -> hMap AddDimensional e1\n\n\nclass HMapAddDimensional (a :: [*]) (b :: [*]) | a -> b\ninstance HMapAddDimensional '[] '[]\ninstance (HMapAddDimensional as bs,\n    dta ~ Quantity t b) => HMapAddDimensional (dta ': as) (b ': bs)\n\nclass HListFromList e e' | e' -> e where\n        hListFromList :: [e] -> HList e'\n\ninstance HListFromList e '[e] where\n        hListFromList (e : _) = HCons e HNil\n        hListFromList _ = error \"HListFromList: not enough input\"\ninstance (e ~ e', HListFromList e es) => HListFromList e (e' ': es) where\n        hListFromList (e : es) = e `HCons` hListFromList es \n\ntype family ToHListRow (a :: [*]) e (b :: [*]) :: Constraint\ntype instance ToHListRow (a ': as) e (b ': bs) = (Quantity a e ~ b, ToHListRow as e bs)\n\ndata AddDimensional = AddDimensional\ninstance (Quantity t x ~ y) => ApplyAB AddDimensional x y where\n        applyAB _ x = Dimensional x\n\nclass FromHList list sh e where\n  fromHList :: HList list -> D sh e\n\ninstance \n    (H.Field e,\n     HMapOut RmDimensional list e,\n     ToHListRow (r ': rs) e list) =>\n  FromHList list '(r, '[rs]) e where\n  fromHList xs = DVec (H.fromList (hMapOut RmDimensional xs))\n\ndata RmDimensional = RmDimensional\ninstance (x ~ Quantity d y) => ApplyAB RmDimensional x y where\n        applyAB _ (Dimensional a) = a\n\n\nclass FromHLists lists sh e where\n  fromHLists :: HList lists -> D sh e\n\n\n-- | [[Dim e unit]] -> DimMat units e\ninstance \n  (ToHListRows' (r1 ': r) c e lists,\n   HMapOut (HMapOutWith RmDimensional) lists [e],\n   H.Field e) =>\n  FromHLists lists '(r1, [r,c]) e where\n    fromHLists xs = DMat (H.fromLists (hMapOut (HMapOutWith RmDimensional) xs))\n\nnewtype HMapOutWith f = HMapOutWith f\ninstance (HMapOut f l e, es ~ [e], HList l ~ hl) => ApplyAB (HMapOutWith f) hl es where\n    applyAB (HMapOutWith f) = hMapOut f\n\nclass ToHListRows' (r :: [*]) (c :: [*]) (e :: *) (rows :: [*])\ninstance ToHListRows' '[] c e '[]\n\ninstance (ToHListRows' r c e rows,\n          MultEq r c c',\n          HMapCxt HList (AddQty e) c' row')\n  => ToHListRows' (r1 ': r) c e (hListRow ': rows)\n\ndata AddQty u\ninstance (qty ~ Quantity u e) => ApplyAB (AddQty u) e qty where\n    applyAB _ = Dimensional\n\nclass ToHLists sh e xs where\n    toHLists :: D sh e -> HList xs\n\n-- | DimMat units e -> [[Dim e unit]]\ninstance\n    (HListFromList e e1,\n     HListFromList (HList e1) e2,\n     HMapCxt HList (HMap AddDimensional) e2 xs,\n     ToHListRows' ri ci e xs,\n     SameLength e2 xs,\n     (r1 ': r) ~ ri, (DOne ': c) ~ ci )\n  => ToHLists '(r1, [r,c]) e xs where\n  toHLists (DMat m) = case hListFromList (map hListFromList (H.toLists m) :: [HList e1]) :: HList e2 of\n    e2 -> hMap (HMap AddDimensional) e2\n\n\n\n\n{- still bad\n\n\nclass PairsToList a t where\n        pairsToList :: a -> [H.Matrix t]\ninstance PairsToList () t where\n        pairsToList _ = []\ninstance (PairsToList b t, t' ~ t) => PairsToList (DimMat sh t',b) t where\n        pairsToList (DimMat a,b) = a : pairsToList b\n\nclass EigV (sh :: [[ [DimSpec *] ]])\n           (eigenValue  :: [[DimSpec *]])\n           (eigenVector :: [[[DimSpec *]]])\n\ninstance\n  ( SameLengths [r,c,r',c',rinv,cinv,eigval,erinv],\n    -- ZipWithMul r c eigval,\n    MapConst '[] r ~ eigval,\n    PInv [r',c'] [rinv,cinv],\n    -- AreRecips r' cinv,\n    -- AreRecips c' rinv,\n    cinv ~ c,\n    c ~ ('[] ': _1),\n    c' ~ ('[] ': _2),\n    ZipWithMul eigval rinv erinv,\n    MultiplyCxt [r',c'] erinv r,\n    sh ~ [r,c],\n    sh' ~ [r',c'])\n    =>  EigV sh eigval sh'\n-- | when no eigenvectors are needed\ntype family EigE (sh :: [[ [DimSpec *] ]]) (eigenValue  :: [ [DimSpec *] ]) :: Constraint\ntype instance EigE [r,c] eigval = ( SameLengths [r,c,eigval], ZipWithMul r c eigval)\n\n{- $eigs\n\nThe Hmatrix eig factors A into P and D where A = P D inv(P) and D is diagonal.\n\nThe units for eigenvalues can be figured out:\n\n>               _____\n>      -1       |  c\n> P D P  = A =  |r\n>               |\n\n>       _______\n>       |   d\n> P   = |c\n>       |\n\n>       _______\n>       |   -1\n>       |  c\n>  -1   |   \n> P   = | -1\n>       |d\n\nSo we can see that the dimension labeled `d-1` in P inverse is actually the\nsame `c` in `A`. The actual units of `d` don't seem to matter because the\n`inv(d)` un-does any units that the `d` adds. So `d` can be all DOne. But\nanother choice, such as 1/c would be more appropriate, since then you can\nexpm your eigenvectors (not that that seems to be something people do)?\n\nTo get the row-units of A to match up, sometimes `D` will have units. \nThe equation ends up as D/c = r\n\nPlease ignore the type signatures on 'eig' 'eigC' etc. instead look at the type of\n'wrapEig' 'wrapEigOnly' together with the hmatrix documentation (linked).\n\nPerhaps the convenience definitions `eig m = wrapEig H.eig m` should be in\nanother module.\n-}\n\n{-\n-- | 'wrapEig' H.'H.eig'\neig m = wrapEig H.eig m\n-- | 'wrapEig' H.'H.eigC'\neigC m = wrapEig H.eigC m\n-- | 'wrapEig' H.'H.eigH'\neigH m = wrapEig H.eigH m\n-- | 'wrapEig' H.'H.eigH''\neigH' m = wrapEig H.eigH' m\n-- | 'wrapEig' H.'H.eigR'\neigR m = wrapEig H.eigR m\n-- | 'wrapEig' H.'H.eigS'\neigS m = wrapEig H.eigS m\n-- | 'wrapEig' H.'H.eigS''\neigS' m = wrapEig H.eigS' m\n-- | 'wrapEig' H.'H.eigSH'\neigSH m = wrapEig H.eigSH m\n-- | 'wrapEig' H.'H.eigSH''\neigSH' m = wrapEig H.eigSH' m\n\n-- | 'wrapEigOnly' H.'H.eigOnlyC'\neigOnlyC m = wrapEigOnly H.eigOnlyC m\n-- | 'wrapEigOnly' H.'H.eigOnlyH'\neigOnlyH m = wrapEigOnly H.eigOnlyH m\n-- | 'wrapEigOnly' H.'H.eigOnlyR'\neigOnlyR m = wrapEigOnly H.eigOnlyR m\n-- | 'wrapEigOnly' H.'H.eigOnlyS'\neigOnlyS m = wrapEigOnly H.eigOnlyS m\n-- | 'wrapEigOnly' H.'H.eigenvalues'\neigenvalues m = wrapEigOnly H.eigenvalues m\n-- | 'wrapEigOnly' H.'H.eigenvaluesSH'\neigenvaluesSH m = wrapEigOnly H.eigenvaluesSH m\n-- | 'wrapEigOnly' H.'H.eigenvaluesSH''\neigenvaluesSH' m = wrapEigOnly H.eigenvaluesSH' m\n-}\n\nwrapEig :: (c' ~ ('[] ': _1),\n            EigV [r,c] eigVal [r',c'],\n    H.Field y, H.Field z)\n    => (H.Matrix x -> (H.Vector y, H.Matrix z)) ->\n    DimMat [r,c] x ->\n    (DimMat '[eigVal] y, DimMat [r',c'] z)\nwrapEig hmatrixFun (DimMat a) = case hmatrixFun a of\n    (e,v) -> (DimVec e, DimMat v)\n\nwrapEigOnly :: (EigE [r,c] eigVal, H.Field y)\n    => (H.Matrix x -> H.Vector y) ->\n    DimMat [r,c] x -> DimMat '[eigVal] y\nwrapEigOnly hmatrixFun (DimMat a) = case hmatrixFun a of\n    (e) -> DimVec e\n\n-}\n\n-- | @\\\\a xs -> map (map (const a)) xs@\ntype family MapMapConst (a::k) (xs :: [[l]]) :: [[k]]\ntype instance MapMapConst a (x ': xs) = MapConst a x ': MapMapConst a xs\ntype instance MapMapConst a '[] = '[]\n\n-- | @\\\\a xs -> map (const a) xs@\ntype family MapConst (a :: k) (xs :: [l]) :: [k]\ntype instance MapConst a (x ': xs) = a ': MapConst a xs\ntype instance MapConst a '[] = '[]\n\n\n-- | convert from (a,(b,(c,(d,())))) to '[a,b,c,d]\ntype family FromPairs (a :: *) :: [*]\ntype instance FromPairs (a,b) = a ': FromPairs b\ntype instance FromPairs () = '[]\n\n{-\n-- | @map fst@\ntype family MapFst (a :: *) :: [*]\ntype instance MapFst ((a,_t) , as) = a ': MapFst as\ntype instance MapFst () = '[]\n\n-- | @\\\\a xs -> map (/a) xs@\ntype family MapDiv (a :: k) (xs :: [k]) :: [k]\ntype instance MapDiv a (x ': xs) = (x @- a) ': MapDiv a xs\ntype instance MapDiv a '[] = '[]\n\ntype family UnDQuantity (a :: [*]) :: [ [*] ]\ntype instance UnDQuantity (x ': xs) = UnDQuantity1 x ': UnDQuantity xs\ntype instance UnDQuantity '[] = '[]\n\ntype family UnDQuantity1 (a :: *) :: [*] \ntype instance UnDQuantity1 (Unit t x) = x\n\ntype family DimMatFromTuple ijs :: * -> *\ntype instance DimMatFromTuple ijs =\n        DimMat [UnDQuantity (MapFst ijs),\n               '[] ': MapDiv (UnDQuantity1 (Fst (Fst ijs)))\n               (UnDQuantity (FromPairs (Snd (Fst ijs))))]\ntype family Append (a :: [k]) (b :: [k]) :: [k]\ntype instance Append (a ': as) b = a ': Append as b\ntype instance Append '[] b = b\n-}\n", "meta": {"hexsha": "7947c4e561fdfe41fc3f679a97870c2f375fbe4b", "size": 32614, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "DimMat/Internal.hs", "max_stars_repo_name": "aavogt/DimMat", "max_stars_repo_head_hexsha": "2d53043f6e2e7d06b3ce662e3d289635ceddc1b7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-11-15T11:11:55.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-15T11:11:55.000Z", "max_issues_repo_path": "DimMat/Internal.hs", "max_issues_repo_name": "aavogt/DimMat", "max_issues_repo_head_hexsha": "2d53043f6e2e7d06b3ce662e3d289635ceddc1b7", "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": "DimMat/Internal.hs", "max_forks_repo_name": "aavogt/DimMat", "max_forks_repo_head_hexsha": "2d53043f6e2e7d06b3ce662e3d289635ceddc1b7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8260869565, "max_line_length": 103, "alphanum_fraction": 0.582633225, "num_tokens": 11471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.46943612428288634}}
{"text": "{-# LANGUAGE GADTs #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nmodule Control.Quantum\n    ( Amplitude\n    , WaveFunction\n    , Quantum\n    , quantize\n    , MonadQuantum\n    , runQuantum\n    , runQuantum'\n    , measure\n    , measurements\n    )\n    where\n\nimport qualified Data.Map  as M\nimport           Data.Map (Map)\nimport           Data.Monoid\nimport           Control.Monad\nimport           Control.Applicative\nimport           Control.Monad.Random as R\nimport           Data.Complex\n\nnearZero :: Double -> Bool\nnearZero x = abs x <= 1e-12\n\ntype Amplitude = Complex Double\n\n-- | The Wave function is the distribution of amplitudes over the\n-- possible states of the underlying data type\ntype WaveFunction a = [(a, Amplitude)]\n\nclass (Monad m) => MonadQuantum m where\n    quantize  :: (Ord a) => WaveFunction a -> m a\n    quantize' ::            WaveFunction a -> m a\n    condition :: Bool -> m ()\n\nliftQ  :: (Ord b, MonadQuantum m) => (a -> b) -> m a -> m b\nliftQ f q1 = q1 >>= always . f\n\nliftQ2 :: (Ord c, MonadQuantum m) => (a -> b -> c) -> m a -> m b -> m c\nliftQ2 f p1 p2 = do x1 <- p1\n                    x2 <- p2\n                    always (f x1 x2)\n\nliftQ3 :: (Ord d, MonadQuantum m) => (a -> b -> c -> d) -> m a -> m b -> m c -> m d\nliftQ3 f p1 p2 p3 = do x1 <- p1\n                       x2 <- p2\n                       x3 <- p3\n                       always (f x1 x2 x3)\n\nalways a = quantize [(a, 1.0:+0.0)]\nalways' a = quantize' [(a, 1.0:+0.0)]\n\n-- | Describes the quantized version of an arbitrary data type.\n-- The underlying data type defines the basis that the state is measured in.\ndata Quantum a where\n    Quantum :: Ord a => Map (Maybe a) Amplitude -> Quantum a\n    QuantumAny :: [(Maybe a, Amplitude)]  -> Quantum a\n\nnoState  :: (Ord a) => Quantum a\nnoState  = Quantum (M.singleton Nothing (1.0:+0.0))\n\nnoState' :: Quantum a\nnoState' = QuantumAny [(Nothing, 1.0 :+ 0.0)]\n\nderiving instance (Show a) => Show (Quantum a)\n\ninstance Functor Quantum where\n    fmap = liftM\n\ninstance Applicative Quantum where\n    pure  = return\n    (<*>) = ap\n\ninstance Monad Quantum where\n    return  = always'\n\n    m >>= f = if unitary then next\n                         else error \"Non-unitary transformation applied to quantum state!\"\n        where\n            unitary = nearZero $ l2norm (map snd $ toList' next) - 1.0\n            next = collect [multAmpl q (go a) | (a, q) <- toList' m]\n            go = maybe noState' f\n\nmultAmpl :: Amplitude -> Quantum a -> Quantum a\nmultAmpl q (Quantum x) = Quantum $ M.map (* conjugate q) x\nmultAmpl q (QuantumAny x) = QuantumAny [ (a, q * r) | (a, r) <- x ]\n\ntoList' :: Quantum a -> [(Maybe a, Amplitude)]\ntoList' (Quantum x) = M.toList x\ntoList' (QuantumAny x) = x\n\ntoList :: (Ord a) => Quantum a -> [(Maybe a, Amplitude)]\ntoList (Quantum x) = M.toList x\ntoList (QuantumAny x) = merge x\n\ncollect :: [Quantum a] -> Quantum a\ncollect [ ]        = QuantumAny []\ncollect [x]        = x\ncollect (Quantum x:t) = case collect t of\n                        Quantum y -> Quantum (M.unionWith (+) x y)\n                        QuantumAny y -> Quantum (M.unionWith (+) x (M.fromList y))\ncollect (QuantumAny x:t) = case collect t of\n                        Quantum y -> Quantum (M.unionWith (+) (M.fromList x) y)\n                        QuantumAny y -> QuantumAny (x ++ y)\n\nmerge :: (Ord a) => WaveFunction a -> WaveFunction a\nmerge = M.toList . M.fromListWith (+)\n\ninstance MonadQuantum Quantum where\n    quantize    = Quantum . M.fromListWith (+) . normalize\n    quantize'   = QuantumAny . normalize\n    condition test = if test then always () else noState\n\ninstance (Ord a, Monoid a) => Monoid (Quantum a) where\n    mempty  = always mempty\n    mappend = liftQ2 mappend\n\n\nnormalize :: WaveFunction a -> [(Maybe a, Amplitude)]\nnormalize xs = map (\\(a, q) -> (Just a, q / total)) xs\n    where\n        total = sum $ zipWith (*) (map conjugate ampl) ampl\n        ampl  = map snd xs\n\n-- | Remove all impossible states from the quantum state and renormalize\ncollapse :: [(Maybe a, Amplitude)] -> WaveFunction a\ncollapse xs = [ (x, q / (norm:+0)) | (Just x, q) <- xs ]\n    where\n        norm = l2norm [ q | (Just x, q) <- xs ]\n\nl2norm :: [Amplitude] -> Double\nl2norm xs = sqrt $ sum $ map (\\x -> (magnitude x)**2) xs\n\n-- | Extracts the wave function from a quantum state.\nrunQuantum :: (Ord a) => Quantum a -> WaveFunction a\nrunQuantum = collapse . toList\n\nrunQuantum' :: Quantum a -> WaveFunction a\nrunQuantum' = collapse . toList'\n\n-- | Measures a quantum state. Returns a single realization of the underlying data type\n-- with probability equal to the squared magnitude of the amplitude of that realization.\n-- Note that if this Module would be backed by a real quantum processor, this would be\n-- the only valid way to extract information from the Monad.\nmeasure :: (Ord a) => Quantum a -> IO a\nmeasure q = do\n  x <- evalRandIO $ R.fromList $ map (\\(a, b) -> (a, toRational b)) $ measurements q\n  return x\n\n-- | Converts a quantum state into a probability state through measurement.\n-- Equivalent to performing repeated measurements on equally prepared quantum states\n-- and noting the frequency of each possible realization.\nmeasurements :: (Ord a) => Quantum a -> [(a, Double)]\nmeasurements = f . runQuantum\n    where f xs = [(x, (magnitude q)**2) | (x, q) <- xs]\n\n\n", "meta": {"hexsha": "020abcd4c059a6c6ec9b1b550c00182fa98ccbc6", "size": 5371, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Control/Quantum.hs", "max_stars_repo_name": "ibab/haskell-quantum", "max_stars_repo_head_hexsha": "39f76ff6330a5cf307b0ee7c00e9a9c71515ed58", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2016-12-27T20:02:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:43:30.000Z", "max_issues_repo_path": "src/Control/Quantum.hs", "max_issues_repo_name": "ibab/haskell-quantum", "max_issues_repo_head_hexsha": "39f76ff6330a5cf307b0ee7c00e9a9c71515ed58", "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/Control/Quantum.hs", "max_forks_repo_name": "ibab/haskell-quantum", "max_forks_repo_head_hexsha": "39f76ff6330a5cf307b0ee7c00e9a9c71515ed58", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-12-28T22:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T16:32:10.000Z", "avg_line_length": 32.9509202454, "max_line_length": 90, "alphanum_fraction": 0.6105008378, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.5660185351961013, "lm_q1q2_score": 0.4691947204854312}}
{"text": "{-| Bindings to FFTW.\n\nExample usage:\n\n> import Foreign.Marshal.Array\n> import Data.Complex\n> import Foreign.Storable.Complex\n> import FFTW\n> \n> main = do\n>     inA  <- fftwAllocComplex 1024\n>     outA <- fftwAllocComplex 1024\n> \n>     plan <- planDFT1d 1024 inA outA Forward fftwEstimate\n> \n>     pokeArray inA $ map (:+ 0) [0..1023]\n>     execute plan\n>     res <- peekArray 1024 outA\n> \n>     fftwFree inA\n>     fftwFree outA\n> \n>     print res\n-}\n\nmodule Numeric.FFTW (\n    -- * Memory allocation functions\n    fftwMalloc,\n    fftwFree,\n    fftwFreePtr,\n    fftwAllocReal,\n    fftwAllocComplex,\n\n    -- * FFT planning flags\n    Direction(..),\n    Flag(),\n    -- ** Planning rigor flags\n    fftwMeasure,\n    fftwExhaustive,\n    fftwPatient,\n    fftwEstimate,\n    fftwWisdomOnly,\n    -- ** Algorithm restriction flags\n    fftwDestroyInput,\n    fftwUnaligned,\n    fftwPreserveInput,\n\n    -- * FFT planning\n    FFTWPlan,\n    planDFT1d,\n    planDFTR2C1d,\n\n    -- * FFT execution\n    execute,\n    executeDFT,\n    executeDFTR2C\n    ) where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Data.Word\nimport Data.Complex\nimport Control.Monad\nimport Data.Bits\nimport Data.Monoid\nimport Data.Semigroup as Sem\n\n#include <fftw3.h>\n\nforeign import ccall unsafe \"fftw_malloc\" \n    c_fftwMalloc :: CUInt -> IO (Ptr a)\n\n-- | Like malloc, but ensures that the pointer obeys the alignment restrictions of FFTW (e.g. for SIMD acceleration). You probably want to use 'fftwAllocReal' or 'fftwAllocComplex' instead.\nfftwMalloc :: Word32 -- ^ size\n           -> IO (Ptr a)\nfftwMalloc = c_fftwMalloc . fromIntegral \n\n-- | Free a pointer returned by 'fftwMalloc', 'fftwAllocReal', or 'fftwAllocComplex'\nforeign import ccall unsafe \"fftw_free\"\n    fftwFree :: Ptr a -- ^ the pointer to be freed\n             -> IO ()\n\n-- | A function pointer to @fftwFree@.\nforeign import ccall unsafe \"&fftw_free\"\n    fftwFreePtr :: FunPtr (Ptr a -> IO ())\n\nforeign import ccall unsafe \"fftw_alloc_real\"\n    c_fftwAllocReal :: CUInt -> IO (Ptr CDouble)\n\n-- | Allocates an array of Doubles. It ensures that the pointer obeys the alignment restrictions of FFTW (e.g. for SIMD acceleration).\nfftwAllocReal :: Word32 -- ^ size\n              -> IO (Ptr CDouble)\nfftwAllocReal = c_fftwAllocReal . fromIntegral\n\nforeign import ccall unsafe \"fftw_alloc_complex\"\n    c_fftwAllocComplex :: CUInt -> IO (Ptr (Complex CDouble))\n\n-- | Allocates an array of complex Doubles (i.e. the c type \"double complex\"). It ensures that the pointer obeys the alignment restrictions of FFTW (e.g. for SIMD acceleration).\nfftwAllocComplex :: Word32 -- ^ size\n                 -> IO (Ptr (Complex CDouble))\nfftwAllocComplex = c_fftwAllocComplex . fromIntegral\n\n-- | The direction of the transform: Forward for a normal transform, Backward for an inverse transform\ndata Direction = Forward\n               | Backward\n\ndirToInt :: Direction -> CInt\ndirToInt Forward  = #const FFTW_FORWARD\ndirToInt Backward = #const FFTW_BACKWARD\n\n-- | FFTW planner flags. These flags affect the planning process. They can be combined using the 'Monoid' instance. See the FFTW flag documentation: <http://www.fftw.org/doc/Planner-Flags.html>.\nnewtype Flag = Flag {unFlag :: CUInt}\n\ninstance Sem.Semigroup Flag where\n  (Flag x) <> (Flag y) = Flag (x .|. y)\n\ninstance Monoid Flag where\n    mempty   = Flag 0\n#if !(MIN_VERSION_base(4,11,0))\n    mappend  = (Sem.<>)\n#endif\n\nfftwMeasure, fftwExhaustive, fftwPatient, fftwEstimate, fftwWisdomOnly :: Flag\nfftwEstimate       = Flag #const FFTW_ESTIMATE\nfftwMeasure        = Flag #const FFTW_MEASURE\nfftwPatient        = Flag #const FFTW_PATIENT\nfftwExhaustive     = Flag #const FFTW_EXHAUSTIVE\nfftwWisdomOnly     = Flag #const FFTW_WISDOM_ONLY\n\nfftwDestroyInput, fftwUnaligned, fftwPreserveInput :: Flag\nfftwDestroyInput   = Flag #const FFTW_DESTROY_INPUT\nfftwUnaligned      = Flag #const FFTW_UNALIGNED\nfftwPreserveInput  = Flag #const FFTW_PRESERVE_INPUT\n\ndata CFFTWPlan\n\n-- | A @FFTWPlan i o@ contains all of the information necessary to perform a transform from an input array of type @i@ to an output array of type @o@, including pointers to the input and output arrays.\nnewtype FFTWPlan i o = FFTWPlan (Ptr CFFTWPlan)\n\nforeign import ccall unsafe \"fftw_plan_dft_1d\"\n    c_planDFT1d :: CInt -> Ptr (Complex CDouble) -> Ptr (Complex CDouble) -> CInt -> CUInt -> IO (Ptr CFFTWPlan)\n\n--This appears to be missing from the fft package on Hackage\n-- | Create a plan for a 1 dimensional complex to complex DFT. The plan stores pointers to the input and output arrays, and these will be used if you 'execute' the plan in the future. They are required even if you intend to specify different input and output arrays in the future (i.e. using 'executeDFT')\nplanDFT1d :: Int                   -- ^ size\n          -> Ptr (Complex CDouble) -- ^ input pointer\n          -> Ptr (Complex CDouble) -- ^ output pointer\n          -> Direction             -- ^ direction\n          -> Flag                  -- ^ planner flags\n          -> IO (FFTWPlan (Complex CDouble) (Complex CDouble))\nplanDFT1d n inp out sign flags = liftM FFTWPlan $ c_planDFT1d (fromIntegral n) inp out (dirToInt sign) (unFlag flags)\n\nforeign import ccall unsafe \"fftw_plan_dft_r2c_1d\"\n    c_planDFTR2C1d :: CInt -> Ptr CDouble -> Ptr (Complex CDouble) -> CUInt -> IO (Ptr CFFTWPlan)\n\n--This appears to be missing from the fft package on Hackage\n-- | Create a plan for a 1 dimensional real to complex DFT. The plan stores pointers to the input and output arrays, and these will be used if you 'execute' the plan in the future. They are required even if you intend to specify different input and output arrays in the future (i.e. using 'executeDFTR2C')\nplanDFTR2C1d :: Int                   -- ^ size\n             -> Ptr CDouble           -- ^ input pointer\n             -> Ptr (Complex CDouble) -- ^ output pointer\n             -> Flag                  -- ^ planner flags\n             -> IO (FFTWPlan CDouble (Complex CDouble))\nplanDFTR2C1d n inp out flags = liftM FFTWPlan $ c_planDFTR2C1d (fromIntegral n) inp out (unFlag flags)\n\nforeign import ccall unsafe \"fftw_execute\"\n    c_execute :: Ptr CFFTWPlan -> IO ()\n\n-- | Execute a plan. Performs an FFT. The input and output arrays are stored within the plan so do not need to be given.\nexecute :: FFTWPlan i o -- ^ the plan to execute\n        -> IO ()\nexecute (FFTWPlan p) = c_execute p\n\nforeign import ccall unsafe \"fftw_execute_dft\"\n    c_executeDFT :: Ptr CFFTWPlan -> Ptr (Complex CDouble) -> Ptr (Complex CDouble) -> IO ()\n\n-- | Execute a complex to complex DFT but on different input and output arrays to those specified when the plan was created.\nexecuteDFT :: FFTWPlan (Complex CDouble) (Complex CDouble) -- ^ the plan to execute\n           -> Ptr (Complex CDouble)                        -- ^ input pointer\n           -> Ptr (Complex CDouble)                        -- ^ output pointer\n           -> IO ()\nexecuteDFT (FFTWPlan p) inp out = c_executeDFT p inp out\n\nforeign import ccall unsafe \"fftw_execute_dft_r2c\"\n    c_executeDFTR2C :: Ptr CFFTWPlan -> Ptr CDouble -> Ptr (Complex CDouble) -> IO ()\n\n-- | Execute a real to complex DFT but on different input and output arrays to those specified when the plan was created.\nexecuteDFTR2C :: FFTWPlan CDouble (Complex CDouble) -- ^ the plan to execute\n              -> Ptr CDouble                        -- ^ input pointer\n              -> Ptr (Complex CDouble)              -- ^ output pointer\n              -> IO ()\nexecuteDFTR2C (FFTWPlan p) inp out = c_executeDFTR2C p inp out\n\n", "meta": {"hexsha": "dad6e8d31989fc2387bb6be040d74ac455bd8442", "size": 7506, "ext": "hsc", "lang": "Haskell", "max_stars_repo_path": "Numeric/FFTW.hsc", "max_stars_repo_name": "adamwalker/haskell-fftw-simple", "max_stars_repo_head_hexsha": "5b7705386432f98f2571ae74bbf18375bfe2265a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-06-04T07:34:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T03:45:39.000Z", "max_issues_repo_path": "Numeric/FFTW.hsc", "max_issues_repo_name": "adamwalker/haskell-fftw-simple", "max_issues_repo_head_hexsha": "5b7705386432f98f2571ae74bbf18375bfe2265a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-23T09:41:59.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-23T14:18:53.000Z", "max_forks_repo_path": "Numeric/FFTW.hsc", "max_forks_repo_name": "adamwalker/haskell-fftw-simple", "max_forks_repo_head_hexsha": "5b7705386432f98f2571ae74bbf18375bfe2265a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-07-19T13:11:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-19T13:11:18.000Z", "avg_line_length": 38.8911917098, "max_line_length": 305, "alphanum_fraction": 0.6795896616, "num_tokens": 2040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.46902161677217447}}
{"text": "module COMPLEX11 where\n\nimport Data.Complex\nimport Numeric\n\nx = 0 :+ 3\ny = 1 + x\n", "meta": {"hexsha": "e45b0a919d21d6a595a4de0e227da846655687d2", "size": 81, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "complex1.hs", "max_stars_repo_name": "borgauf/omnimath", "max_stars_repo_head_hexsha": "ccd043a9e9d7f986225082d65254e821b0bd07bc", "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": "complex1.hs", "max_issues_repo_name": "borgauf/omnimath", "max_issues_repo_head_hexsha": "ccd043a9e9d7f986225082d65254e821b0bd07bc", "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": "complex1.hs", "max_forks_repo_name": "borgauf/omnimath", "max_forks_repo_head_hexsha": "ccd043a9e9d7f986225082d65254e821b0bd07bc", "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": 10.125, "max_line_length": 22, "alphanum_fraction": 0.6913580247, "num_tokens": 30, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943822145997, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4689083365154029}}
{"text": "module IllusoryContourShapePinwheelBasis where\n\nimport           Control.Monad                  as M\nimport           Control.Monad.Parallel         as MP\nimport qualified Data.Array.Accelerate          as A\nimport           Data.Array.Accelerate.LLVM.PTX\nimport           Data.Array.Repa                as R\nimport           Data.Binary\nimport           Data.Complex\nimport           Data.List                      as L\nimport           Data.Vector.Storable           as VS\nimport           Data.Vector.Unboxed            as VU\nimport           FokkerPlanck\nimport           Foreign.CUDA.Driver            as CUDA\nimport           FourierMethod.BlockMatrixAcc\nimport           FourierMethod.FourierSeries2D\nimport           Image.IO\nimport           Pinwheel.FourierSeries2D\nimport           STC\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Text.Printf\nimport           Utils.Array\nimport           Utils.Time\nimport           Utils.List\nimport Data.Array.IArray as IA\nimport FourierPinwheel\nimport Utils.Distribution\nimport FourierPinwheel.GaussianEnvelopePinwheel\nimport Filter.Utils\n\nmain = do\n  args@(deviceIDsStr:numPointsStr:deltaStr:thresholdStr:numPointsReconStr:deltaReconStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:tauStr:numTrailsStr:deltaTStr:poissonWeightStr:numR2FreqStr:periodR2Str:phiFreqsStr:rhoFreqsStr:thetaFreqsStr:scaleFreqsStr:initDistStr:initScaleStr:histFilePath:histFilePathCorner:stdR2Str:stdThetaStr:stdRStr:numBatchR2Str:numBatchR2FreqsStr:numBatchOriStr:batchSizeStr:sStr:writeFlagStr:numIterationStr:shape2DStr:radiusStr:numThreadStr:_) <-\n    getArgs\n  let deviceIDs = read deviceIDsStr :: [Int]\n      numPoints = read numPointsStr :: Int\n      delta = read deltaStr :: Double\n      threshold = read thresholdStr :: Double\n      numPointsRecon = read numPointsReconStr :: Int\n      deltaRecon = read deltaReconStr :: Double\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      tau = read tauStr :: Double\n      numTrails = read numTrailsStr :: Int\n      deltaT = read deltaTStr :: Double\n      poissonWeight = read poissonWeightStr :: Double\n      numR2Freq = read numR2FreqStr :: Int\n      periodR2 = read periodR2Str :: Double\n      phiFreq = read phiFreqsStr :: Int\n      phiFreqs = L.map fromIntegral [-phiFreq .. phiFreq]\n      rhoFreq = read rhoFreqsStr :: Int\n      rhoFreqs = L.map fromIntegral [-rhoFreq .. rhoFreq]\n      thetaFreq = read thetaFreqsStr :: Int\n      thetaFreqs = L.map fromIntegral [-thetaFreq .. thetaFreq]\n      scaleFreq = read scaleFreqsStr :: Int\n      scaleFreqs = L.map fromIntegral [-scaleFreq .. scaleFreq]\n      initScale = read initScaleStr :: Double\n      initDist = read initDistStr :: [(Double, Double, Double, Double)]\n      initPoints = L.map (\\(x, y, t, s) -> Point x y t s) initDist\n      initSource = [L.head initPoints]\n      initSink = [L.last initPoints]\n      numThread = read numThreadStr :: Int\n      folderPath = \"output/test/IllusoryContourShapePinwheelBasis\"\n      stdR2 = read stdR2Str :: Double\n      stdTheta = read stdThetaStr :: Double\n      stdR = read stdRStr :: Double\n      numBatchR2 = read numBatchR2Str :: Int\n      numBatchR2Freqs = read numBatchR2FreqsStr :: Int\n      numBatchOri = read numBatchOriStr :: Int\n      batchSize = read batchSizeStr :: Int\n      s = read sStr :: Double\n      writeFlag = read writeFlagStr :: Bool\n      numIteration = read numIterationStr :: Int\n      shape2Ds = read shape2DStr :: [Points Shape2D]\n      radius = read radiusStr :: Double\n      periodEnv = periodR2 ^ 2 / 4 --  * sqrt 2 --  ^ 2 * 2\n  createDirectoryIfMissing True folderPath\n  flag <- doesFileExist histFilePath\n  flagCorner <- doesFileExist histFilePathCorner\n  hist <-\n    case (getShape . L.head $ shape2Ds) of\n      Circle _ _ ->\n        if flag\n          then do\n            printCurrentTime \"read coefficients from file\"\n            decodeFile histFilePath\n          else do\n            printCurrentTime \"Start computing coefficients...\"\n            initialise []\n            devs <- M.mapM device deviceIDs\n            ctxs <- M.mapM (\\dev -> CUDA.create dev []) devs\n            ptxs <- M.mapM createTargetFromContext ctxs\n            sampleCartesian\n              histFilePath\n              folderPath\n              ptxs\n              numPoints\n              periodEnv\n              delta\n              numOrientation\n              initScale\n              thetaSigma\n              tau\n              threshold\n              s\n              phiFreq\n              rhoFreq\n              thetaFreq\n              scaleFreq\n              stdR2\n      KoffkaCross _ _ ->\n        if flagCorner\n          then do\n            printCurrentTime \"read coefficients from file\"\n            decodeFile histFilePathCorner\n          else do\n            printCurrentTime \"Start computing coefficients...\"\n            initialise []\n            devs <- M.mapM device deviceIDs\n            ctxs <- M.mapM (\\dev -> CUDA.create dev []) devs\n            ptxs <- M.mapM createTargetFromContext ctxs\n            sampleCartesianCorner\n              histFilePathCorner\n              folderPath\n              ptxs\n              numPoints\n              periodEnv\n              delta\n              numOrientation\n              initScale\n              thetaSigma\n              tau\n              threshold\n              s\n              phiFreq\n              rhoFreq\n              thetaFreq\n              scaleFreq\n              stdR2\n              poissonWeight\n  printCurrentTime \"Done\"\n  printCurrentTime \"Start Convloution..\"\n  plan <-\n    makePlan\n      folderPath\n      emptyPlan\n      numPointsRecon\n      numPointsRecon\n      numR2Freq\n      (2 * thetaFreq + 1)\n      (2 * scaleFreq + 1)\n      (2 * phiFreq + 1)\n      (2 * rhoFreq + 1)\n  printCurrentTime \"Compute DFT Plan done.\"\n  let coefficients = getNormalizedHistogramArr hist\n      asteriskGaussianVec =\n        case getShape (L.head shape2Ds) of\n          Circle _ _ ->\n            gaussianPinwheel\n              numR2Freq\n              periodR2\n              stdR2\n              10\n              thetaFreq\n              scaleFreq\n              periodEnv\n              stdTheta\n              stdR\n          KoffkaCross _ _ ->\n            gaussianPinwheel1\n              numR2Freq\n              periodR2\n              stdR2\n              10\n              thetaFreq\n              scaleFreq\n              periodEnv\n              stdTheta\n              stdR\n  harmonicsArray <-\n    createHarmonics\n      numR2Freq\n      phiFreq\n      rhoFreq\n      thetaFreq\n      scaleFreq\n      (-s)\n      periodR2\n      periodEnv\n      coefficients\n  M.mapM_\n    (\\shape2D -> do\n       let points =\n             L.map (\\(x, y) -> Point (x) (y) 0 1) .\n             getShape2DIndexList' . makeShape2D $\n             shape2D\n       printCurrentTime (show points)\n       (bias, dftBias) --Full\n                          -- (dftBias, bias) <- -- Discrete\n          <-\n         case getShape shape2D of\n           Circle _ _ ->\n             computeBiasFourierPinwheelFull\n               plan\n               numR2Freq\n               thetaFreq\n               scaleFreq\n               (-s)\n               periodR2\n               periodEnv\n               radius\n               stdTheta\n               stdR\n               stdR2\n               asteriskGaussianVec\n               points\n           KoffkaCross _ _ ->\n             computeBiasFourierPinwheelKoffkaCorss\n               plan\n               numR2Freq\n               thetaFreq\n               scaleFreq\n               (-s)\n               periodR2\n               periodEnv\n               radius\n               stdTheta\n               stdR\n               stdR2\n               asteriskGaussianVec\n               points\n       let initDist =\n             computeInitialDistributionPowerMethodFourierPinwheelFull\n               numR2Freq\n               phiFreq\n               rhoFreq\n               thetaFreq\n               scaleFreq\n               bias -- dftBias\n       computeContourFourierPinwheel\n         plan\n         folderPath\n         writeFlag\n         harmonicsArray\n         dftBias -- bias\n         numIteration\n         numBatchR2\n         numPointsRecon\n         deltaRecon\n         periodR2\n         periodEnv\n         initDist\n         (show . getShape $ shape2D)\n         deviceIDs)\n    shape2Ds\n", "meta": {"hexsha": "75305f0e29b9307ec9e619ff104566395fb6685e", "size": 8508, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/IllusoryContourShapePinwheelBasis/IllusoryContourShapePinwheelBasis.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/IllusoryContourShapePinwheelBasis/IllusoryContourShapePinwheelBasis.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/IllusoryContourShapePinwheelBasis/IllusoryContourShapePinwheelBasis.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 32.8494208494, "max_line_length": 490, "alphanum_fraction": 0.5610014104, "num_tokens": 2023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46852666592305603}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule LearnSpec\n  ( spec\n  ) where\n\nimport           Control.Monad\nimport qualified Data.Set                as Set\nimport           Data.Tuple.Extra\nimport           Debug.Trace\nimport           Foundation.Monad\nimport           Layers\nimport           Learn\nimport           Mnist\nimport           Numeric.LinearAlgebra\nimport           Test.Hspec\nimport           Test.Hspec.QuickCheck   (prop)\nimport           Test.QuickCheck\nimport           Test.QuickCheck.Gen\nimport           Test.QuickCheck.Monadic\n\nrunTest :: IO ()\nrunTest = hspec spec\n\nspec :: Spec\nspec = do\n  describe \"hotone\" propsHotone\n  describe \"convertTests\" propsConvertTests\n  describe \"convertTrains\" propsConvertTrains\n  describe \"initNN\" propsInitNN\n\npropsHotone =\n  prop \"length\" $\n  forAll (genNM 100) $ \\(n, m) ->\n    let v = toList $ hotone n m :: [R]\n        (a, k:c) = splitAt m v\n        x = sum $ a ++ c\n     in (length v, x, k) `shouldBe` (n, 0, 1)\n\npropsConvertTests =\n  prop \"div 255\" $\n  forAll genMnistData $ \\d ->\n    let r = convertTests d\n        MnistData ns = d\n        (ts, is) = second concat $ unzip $ map (second $ concat . toLists) ns\n        (ps, vs) = second concat $ unzip $ map (second toList) r\n        x1 = map fromIntegral ts\n        x2 = map (round . (* 255)) vs\n     in (x1, is) `shouldBe` (ps, x2)\n\npropsConvertTrains = do\n  prop \"length\" $\n    forAll genMnistData $ \\d ->\n      let r = convertTrains (length ns `div` 10) d\n          MnistData ns = d\n          (xs, ys) = unzip $ map countRows r\n          countRows (TrainBatch a) = both rows a\n          a = sum xs\n          b = length ns\n       in (xs, a) `shouldBe` (ys, b)\n  prop \"size\" $\n    forAll\n      (do d <- genMnistData\n          s <- choose (2, 10)\n          return (s, d)) $ \\(s, d) ->\n      let r = convertTrains s d\n          MnistData ns = d\n          (w, c) = size $ snd $ head ns\n          xs = unzip $ map getSize r\n          getSize (TrainBatch a) = both size a\n          (a, b) = both (maximum . Set.toList . Set.fromList) xs\n       in (a, b) `shouldBe` ((s, 10), (s, w * c))\n  prop \"div 255\" $\n    forAll genMnistData $ \\d ->\n      let r = convertTrains (length ns `div` 10) d\n          MnistData ns = d\n          xs = map fromIntegral $ concatMap (concat . toLists . snd) ns\n          ys = map (round . (* 255)) $ concatMap flatMs r\n          flatMs (TrainBatch (_, ms)) = concat $ toLists ms\n       in xs `shouldBe` ys\n\npropsInitNN =\n  it \"size of layers\" $ do\n    r <- initNN ReLUForward [16, 50, 8, 10]\n    let ForwardNN lA SoftmaxWithCrossForward = r\n    let JoinedForwardLayer lB (AffineForward m3 b3) = lA\n    let JoinedForwardLayer lC ReLUForward = lB\n    let JoinedForwardLayer lD (AffineForward m2 b2) = lC\n    let JoinedForwardLayer (AffineForward m1 b1) ReLUForward = lD\n    let ms = map size [m1, m2, m3]\n    let bs = map size [b1, b2, b3]\n    (ms, bs) `shouldBe` ([(16, 50), (50, 8), (8, 10)], [50, 8, 10])\n\ngenNM :: Int -> Gen (Int, Int)\ngenNM x = do\n  n <- choose (1, x)\n  m <- choose (0, n - 1)\n  return (n, m)\n\ngenMnistData :: Gen MnistData\ngenMnistData = do\n  len <- choose (10, 100)\n  nRows <- choose (10, 20)\n  nCols <- choose (10, 20)\n  ms <- vectorOf len $ genMatrixZ 255 nRows nCols\n  vs <- vectorOf len $ choose (0, 9)\n  return $ MnistData $ zip vs ms\n\ngenMatrixZ :: Int -> Int -> Int -> Gen (Matrix Z)\ngenMatrixZ value nRows nCols = do\n  zss <- vectorOf nRows $ vectorOf nCols $ fromIntegral <$> choose (0, value)\n  return $ fromLists zss\n", "meta": {"hexsha": "582ccadb618812bb0e0a2971a2969302a4203cf5", "size": 3482, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/LearnSpec.hs", "max_stars_repo_name": "sawatani/simple_mnist", "max_stars_repo_head_hexsha": "3aa8f9ccaa9a3a58fed123a81e24ce7feab3e977", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/LearnSpec.hs", "max_issues_repo_name": "sawatani/simple_mnist", "max_issues_repo_head_hexsha": "3aa8f9ccaa9a3a58fed123a81e24ce7feab3e977", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/LearnSpec.hs", "max_forks_repo_name": "sawatani/simple_mnist", "max_forks_repo_head_hexsha": "3aa8f9ccaa9a3a58fed123a81e24ce7feab3e977", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.814159292, "max_line_length": 77, "alphanum_fraction": 0.5795519816, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859596, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4684981196326578}}
{"text": "{-# LANGUAGE ConstraintKinds     #-}\n{-# LANGUAGE DataKinds           #-}\n\n\n{-# LANGUAGE DeriveTraversable   #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE RankNTypes          #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\nmodule Test.Grenade.Recurrent.Layers.LSTM.Reference where\n\nimport           Data.Reflection\nimport           GHC.TypeLits                  (KnownNat)\nimport           Numeric.AD.Internal.Reverse   (Tape)\nimport           Numeric.AD.Mode.Reverse\nimport qualified Numeric.LinearAlgebra         as H\nimport qualified Numeric.LinearAlgebra.Static  as S\n\nimport           Grenade.Recurrent.Layers.LSTM (LSTMWeights (..))\nimport qualified Grenade.Recurrent.Layers.LSTM as LSTM\nimport           Grenade.Types\n\n\n--\n-- This module contains a set of list only versions of\n-- an LSTM layer which can be used with the AD library.\n--\n-- Using this, we can check to make sure that our fast\n-- back propagation implementation is correct.\n--\n\n-- | List only matrix deriving functor\nnewtype Matrix a = Matrix {\n    matrixWeights         :: [[a]]\n  } deriving (Functor, Foldable, Traversable, Eq, Show)\n\n-- | List only vector deriving functor\nnewtype Vector a = Vector {\n    vectorWeights         :: [a]\n  } deriving (Functor, Foldable, Traversable, Eq, Show)\n\n-- | List only LSTM weights\ndata RefLSTM a = RefLSTM\n    { refLstmWf :: Matrix a -- Weight Forget     (W_f)\n    , refLstmUf :: Matrix a -- Cell State Forget (U_f)\n    , refLstmBf :: Vector a -- Bias Forget       (b_f)\n    , refLstmWi :: Matrix a -- Weight Input      (W_i)\n    , refLstmUi :: Matrix a -- Cell State Input  (U_i)\n    , refLstmBi :: Vector a -- Bias Input        (b_i)\n    , refLstmWo :: Matrix a -- Weight Output     (W_o)\n    , refLstmUo :: Matrix a -- Cell State Output (U_o)\n    , refLstmBo :: Vector a -- Bias Output       (b_o)\n    , refLstmWc :: Matrix a -- Weight Cell       (W_c)\n    , refLstmBc :: Vector a -- Bias Cell         (b_c)\n    } deriving (Functor, Foldable, Traversable, Eq, Show)\n\nlstmToReference :: (KnownNat a, KnownNat b) => LSTM.LSTMWeights a b -> RefLSTM RealNum\nlstmToReference lw =\n    RefLSTM\n      { refLstmWf = Matrix . H.toLists . S.extract $ lstmWf lw -- Weight Forget     (W_f)\n      , refLstmUf = Matrix . H.toLists . S.extract $ lstmUf lw -- Cell State Forget (U_f)\n      , refLstmBf = Vector . H.toList  . S.extract $ lstmBf lw -- Bias Forget       (b_f)\n      , refLstmWi = Matrix . H.toLists . S.extract $ lstmWi lw -- Weight Input      (W_i)\n      , refLstmUi = Matrix . H.toLists . S.extract $ lstmUi lw -- Cell State Input  (U_i)\n      , refLstmBi = Vector . H.toList  . S.extract $ lstmBi lw -- Bias Input        (b_i)\n      , refLstmWo = Matrix . H.toLists . S.extract $ lstmWo lw -- Weight Output     (W_o)\n      , refLstmUo = Matrix . H.toLists . S.extract $ lstmUo lw -- Cell State Output (U_o)\n      , refLstmBo = Vector . H.toList  . S.extract $ lstmBo lw -- Bias Output       (b_o)\n      , refLstmWc = Matrix . H.toLists . S.extract $ lstmWc lw -- Weight Cell       (W_c)\n      , refLstmBc = Vector . H.toList  . S.extract $ lstmBc lw -- Bias Cell         (b_c)\n      }\n\nrunLSTM :: Floating a => RefLSTM a -> Vector a -> Vector a -> (Vector a, Vector a)\nrunLSTM rl cell input =\n    let -- Forget state vector\n        f_t = sigmoid   $ refLstmBf rl #+ refLstmWf rl #> input #+ refLstmUf rl #> cell\n        -- Input state vector\n        i_t = sigmoid   $ refLstmBi rl #+ refLstmWi rl #> input #+ refLstmUi rl #> cell\n        -- Output state vector\n        o_t = sigmoid   $ refLstmBo rl #+ refLstmWo rl #> input #+ refLstmUo rl #> cell\n        -- Cell input state vector\n        c_x = fmap tanh $ refLstmBc rl #+ refLstmWc rl #> input\n        -- Cell state\n        c_t = f_t #* cell #+ i_t #* c_x\n        -- Output (it's sometimes recommended to use tanh c_t)\n        h_t = o_t #* c_t\n    in (c_t, h_t)\n\nrunLSTMback :: forall a. Floating a => Vector a -> Vector a -> RefLSTM a -> RefLSTM a\nrunLSTMback cell input =\n  grad f\n    where\n  f :: forall s. Reifies s Tape => RefLSTM (Reverse s a) -> Reverse s a\n  f net =\n    let cell'   = fmap auto cell\n        input'  = fmap auto input\n        (cells, forwarded) = runLSTM net cell' input'\n    in  sum forwarded + sum cells\n\nrunLSTMbackOnInput :: forall a. Floating a => Vector a -> RefLSTM a -> Vector a -> Vector a\nrunLSTMbackOnInput cell net =\n  grad f\n    where\n  f :: forall s. Reifies s Tape => Vector (Reverse s a) -> Reverse s a\n  f input =\n    let cell'   = fmap auto cell\n        net'    = fmap auto net\n        (cells, forwarded) = runLSTM net' cell' input\n    in  sum forwarded + sum cells\n\nrunLSTMbackOnCell :: forall a. Floating a => Vector a -> RefLSTM a -> Vector a -> Vector a\nrunLSTMbackOnCell input net =\n  grad f\n    where\n  f :: forall s. Reifies s Tape => Vector (Reverse s a) -> Reverse s a\n  f cell =\n    let input'  = fmap auto input\n        net'    = fmap auto net\n        (cells, forwarded) = runLSTM net' cell input'\n    in  sum forwarded + sum cells\n\n-- | Helper to multiply a matrix by a vector\nmatMult :: Num a => Matrix a -> Vector a -> Vector a\nmatMult (Matrix m) (Vector v) = Vector result\n  where\n    lrs = map length m\n    l   = length v\n    result = if all (== l) lrs\n             then map (\\r -> sum $ zipWith (*) r v) m\n             else error $ \"Matrix has rows of length \" ++ show lrs ++\n                          \" but vector is of length \" ++ show l\n\n(#>) :: Num a => Matrix a -> Vector a -> Vector a\n(#>) = matMult\ninfixr 8 #>\n\n(#+) :: Num a => Vector a -> Vector a -> Vector a\n(#+) (Vector as) (Vector bs) = Vector $ zipWith (+) as bs\ninfixl 6 #+\n\n(#-) :: Num a => Vector a -> Vector a -> Vector a\n(#-) (Vector as) (Vector bs) = Vector $ zipWith (-) as bs\ninfixl 6 #-\n\n(#*) :: Num a => Vector a -> Vector a -> Vector a\n(#*) (Vector as) (Vector bs) = Vector $ zipWith (*) as bs\ninfixl 7 #*\n\nsigmoid :: (Functor f, Floating a) => f a -> f a\nsigmoid xs = (\\x -> 1 / (1 + exp (-x))) <$> xs\n", "meta": {"hexsha": "acef936f5cfc71b18de76fd73be53f89b70bb342", "size": 5996, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Recurrent/Layers/LSTM/Reference.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "test/Test/Grenade/Recurrent/Layers/LSTM/Reference.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Test/Grenade/Recurrent/Layers/LSTM/Reference.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9350649351, "max_line_length": 91, "alphanum_fraction": 0.600233489, "num_tokens": 1765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.46847551440284674}}
{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators       #-}\n\nmodule Grenade.Utils.Conversion\n  ( -- Column major mode helper functions\n    NrColumns\n  , Row\n  , Col\n  , ColumnMajorModeIndex\n  , columnMajorModeIndex\n  , columnMajorModeRowCol\n\n  , toLayerShape\n  -- 1D conversions\n  , toS1D\n  , toS1DV\n  , fromS1D\n  , fromS1DV\n  -- 2D converions\n  , toS2D\n  , toS2DV\n  , fromS2D\n  , fromS2DV\n  -- further conversions\n  , toRows\n  , toCols\n  , toColumnsS2D\n  , toRowsS2D\n  , fromRowMajorVectorToSD1\n  , fromRowMajorVectorToSD1V\n  , fromRowMajorVectorToSD2\n  , fromRowMajorVectorToSD2V\n  , fromColumnMajorVectorToSD2V\n  ) where\n\nimport           Data.Maybe                   (fromJust, fromMaybe)\nimport           Data.Proxy\nimport           Data.Singletons.TypeLits\nimport qualified Data.Vector.Storable         as V\nimport           Foreign\nimport qualified Numeric.LinearAlgebra        as LA\nimport qualified Numeric.LinearAlgebra.Static as LAS\nimport           System.IO.Unsafe             (unsafePerformIO)\nimport           Unsafe.Coerce                (unsafeCoerce)\n\nimport           Grenade.Core.Shape\nimport           Grenade.Types\nimport           Grenade.Utils.Vector\n\n\n-- Column major mode helper functions\n\ntype NrColumns = Int\ntype Row = Int\ntype Col = Int\ntype ColumnMajorModeIndex = Int\n\n\ncolumnMajorModeIndex :: NrColumns -> Row -> Col -> ColumnMajorModeIndex\ncolumnMajorModeIndex cols row col = row * cols + col\n\ncolumnMajorModeRowCol :: NrColumns -> ColumnMajorModeIndex -> (Row, Col)\ncolumnMajorModeRowCol cols idx = (idx `div` cols, idx `mod` cols)\n\n\n-- import           Debug.Trace\n\n-- test =\n--   toCols $\n--   (fromRowMajorVectorToSD2 (V.fromList [0..9]) :: S ('D2 2 5))\n--   (fromRowMajorVectorToSD1 (V.fromList [0..9]) :: S ('D1 10))\n\n-- testShapeV = fromRowMajorVectorToSD2V (V.fromList [0..9]) :: S ('D2 2 5)\n-- testShape = fromRowMajorVectorToSD2 (V.fromList [0..9]) :: S ('D2 2 5)\n\n-- | Convert the Shape to a list of rows.\ntoRows :: S x -> [V.Vector RealNum]\ntoRows x =\n  case x of\n    (S1DV v)  -> [v]\n    (S1D v)   -> [unsafeCoerce v]\n    (S2D m)   -> map LAS.extract . LAS.toRows $ m\n    (S2DV {}) -> toRowsS2D x\n    (S3D m)   -> map LAS.extract . LAS.toRows $ m\n{-# INLINE toRows #-}\n\n-- | Convert the Shape to a list of columns.\ntoCols :: S x -> [V.Vector RealNum]\ntoCols x =\n  case x of\n    S1DV v    -> map V.singleton . V.toList $ v\n    S1D v     -> map V.singleton . V.toList $ (unsafeCoerce v :: V.Vector RealNum)\n    (S2DV {}) -> toColumnsS2D x\n    (S2D m)   -> map LAS.extract . LAS.toColumns $ m\n    (S3D m)   -> map LAS.extract . LAS.toColumns $ m\n\n\n-- | Converts the given vector to the correct layer shape.\ntoLayerShape :: S i -> S x -> S x\ntoLayerShape x y = case (x, y) of\n  (S1D{}, S1DV{}) -> toS1D y\n  (S1DV{}, S1D{}) -> fromS1D y\n  (S2D{}, S2DV{}) -> toS2D y\n  (S2DV{}, S2D{}) -> fromS2D y\n  _               -> y\n{-# INLINE toLayerShape #-}\n\n-- 1D conversion\n\n-- | Convert to S1D.\ntoS1D :: S ('D1 l) -> S ('D1 l)\ntoS1D (S1DV vec) = S1D $ (fromMaybe err . LAS.create $ vec)\n  where\n    err = error $ \"wrong length of vector with \" ++ show (V.length vec) ++ \" in toS1D \"\ntoS1D x@S1D{} = x\n{-# INLINE toS1D #-}\n\n-- | Convert from S1DV. This is the same as @toS1D@.\nfromS1DV :: S ('D1 l) -> S ('D1 l)\nfromS1DV = toS1D\n{-# INLINE fromS1DV #-}\n\n-- | Convert from S1D to S1DV.\nfromS1D :: S ('D1 l) -> S ('D1 l)\nfromS1D (S1D vec) = S1DV (LAS.extract vec)\nfromS1D x@S1DV{}  = x\n{-# INLINE fromS1D #-}\n\n-- | Convert to S1DV (from S1D). Thsi is the same as @fromS1D@.\ntoS1DV :: S ('D1 l) -> S ('D1 l)\ntoS1DV = fromS1D\n{-# INLINE toS1DV #-}\n\n\n-- 2D conversions\n\n-- | Convert from vector representation.\ntoS2D :: forall i j . S ('D2 i j) -> S ('D2 i j)\ntoS2D mat@S2DV{} = S2D $ LAS.matrix (concatMap V.toList $ toRows mat)\ntoS2D x@S2D{}    = x\n{-# INLINE toS2D #-}\n\n-- | Convert from S2DV. This is the same as @toS2D@.\nfromS2DV :: S ('D2 i j) -> S ('D2 i j)\nfromS2DV = toS2D\n{-# INLINE fromS2DV #-}\n\n-- | Convert from S2D to S2DV.\nfromS2D :: S ('D2 i j) -> S ('D2 i j)\nfromS2D (S2D mat) = S2DV . V.concat . map LAS.extract . LAS.toColumns $ mat\nfromS2D x@S2DV{}  = x\n{-# INLINE fromS2D #-}\n\n-- | Convert to S2DV. This is the same as @fromS2D@.\ntoS2DV :: S ('D2 i j) -> S ('D2 i j)\ntoS2DV = fromS2D\n{-# INLINE toS2DV #-}\n\n\n-- test = LAS.create $ NLA.reshape 5 $ (V.fromList [0..9]) :: Maybe (LAS.L 2 5)\n-- Just (matrix\n--  [ 0.0, 1.0, 2.0, 3.0, 4.0\n--  , 5.0, 6.0, 7.0, 8.0, 9.0 ] :: L 2 5)\n\n-- | Efficiently extract the columns of the shape. Returns a list of j vectors.\ntoColumnsS2D :: forall i j . S ('D2 i j) -> [V.Vector RealNum]\ntoColumnsS2D (S2D mat) = map LAS.extract . LAS.toColumns $ mat\ntoColumnsS2D (S2DV vec) = map (\\idx -> V.slice idx m vec) [0,m .. (V.length vec - m)]\n  where\n    m = fromIntegral $ natVal (Proxy :: Proxy i)\n{-# INLINE toColumnsS2D #-}\n\n-- | Efficiently extract the rows of the shape. Returns a list of i vectors.\ntoRowsS2D :: forall i j . S ('D2 i j) -> [V.Vector RealNum]\ntoRowsS2D (S2D mat) = map LAS.extract . LAS.toRows $ mat\ntoRowsS2D (S2DV vec) =\n  unsafePerformIO $\n  V.unsafeWith vec $ \\from ->\n    flip mapM [0 .. m - 1] $ \\row -> do\n      vec' <- createVector n\n      V.unsafeWith vec' $ \\to -> do\n        let go (-1) = return ()\n            go !col = do\n              let idx = col * m + row\n              x <- peekElemOff from idx\n              pokeElemOff to col x\n              go (col - 1)\n        go (n - 1)\n        return vec'\n  where\n    m = fromIntegral $ natVal (Proxy :: Proxy i)\n    n = fromIntegral $ natVal (Proxy :: Proxy j)\n{-# INLINE toRowsS2D #-}\n\n-- | Convert from a row major vector to @SD1@.\nfromRowMajorVectorToSD1 :: forall l . (KnownNat l) => V.Vector RealNum -> S ('D1 l)\nfromRowMajorVectorToSD1 vec\n  | V.length vec /= l = error $ \"cannot create Vector R \" ++ show l ++ \" from vector with length \" ++ show (V.length vec) ++ \" in fromRowMajorVectorToSD1\"\n  | otherwise = S1D (unsafeCoerce vec)\n  where l = fromIntegral $ natVal (Proxy :: Proxy l)\n{-# INLINE fromRowMajorVectorToSD1 #-}\n\n-- | Convert from a row major vector to @SD1V@.\nfromRowMajorVectorToSD1V :: forall l . (KnownNat l) => V.Vector RealNum -> S ('D1 l)\nfromRowMajorVectorToSD1V = S1DV\n{-# INLINE fromRowMajorVectorToSD1V #-}\n\n-- | Convert from a row major vector to @SD2@.\nfromRowMajorVectorToSD2 :: forall i j . (KnownNat i, KnownNat j) => V.Vector RealNum -> S ('D2 i j)\nfromRowMajorVectorToSD2 vec\n  | V.length vec /= m * n = error $ \"cannot create matrix L \" ++ show (m,n) ++ \" from vector length \" ++ show (V.length vec) ++ \" in fromRowMajorVectorToSD2\"\n  | otherwise = toS2D $ fromRowMajorVectorToSD2V vec\n                -- in S2D $ unsafeCoerce v'\n  where\n    m = fromIntegral $ natVal (Proxy :: Proxy i)\n    n = fromIntegral $ natVal (Proxy :: Proxy j)\n{-# INLINE fromRowMajorVectorToSD2 #-}\n\n-- toRowMajorVector :: (KnownNat i, KnownNat j) => S ('D2 i j) -> V.Vector RealNum\n-- toRowMajorVector = V.concat . toColumnsS2D\n\n-- | Convert from a row major vector to @SD2V@.\nfromRowMajorVectorToSD2V :: forall i j . (KnownNat i, KnownNat j) => V.Vector RealNum -> S ('D2 i j)\nfromRowMajorVectorToSD2V vec = unsafePerformIO $ do\n  vec' <- createVector (V.length vec)\n  V.unsafeWith vec $ \\from ->\n    V.unsafeWith vec' $ \\to ->  do\n    let go (-1) = return ()\n        go !k = do\n          -- let idx = nRow * m + nCol\n              -- nCol = k `div` n\n              -- nRow = k `mod` n\n          let idx = columnMajorModeIndex n row col\n              col = k - row * n\n              row = k `mod` n\n          x <- peekElemOff from k\n          pokeElemOff to idx x\n          go (k-1)\n    go (V.length vec - 1)\n  return $ S2DV vec'\n  where\n    m = fromIntegral $ natVal (Proxy :: Proxy i)\n    n = fromIntegral $ natVal (Proxy :: Proxy j)\n{-# INLINE fromRowMajorVectorToSD2V #-}\n\n\n-- | Convert from a row major vector to @SD2V@.\nfromColumnMajorVectorToSD2V :: forall i j . (KnownNat i, KnownNat j) => V.Vector RealNum -> S ('D2 i j)\nfromColumnMajorVectorToSD2V = S2DV\n{-# INLINE fromColumnMajorVectorToSD2V #-}\n\n\ntest =\n  -- (\\x -> fromColumnMajorVectorToSD2V x :: S ('D2 5 2)) $\n  -- V.concat $\n  -- toRowsS2D $\n  -- ttoRowMajorVector $\n  fromS2D $\n  -- (\\x -> fromRowMajorVectorToSD2V x :: S ('D2 5 2) ) $ V.concat $\n  -- toRowsS2D $\n  -- ((\\(S2D x) -> S2DV $ V.concat $ map LAS.extract . LAS.toColumns $ x :: S ('D2 2 5)) )\n  -- (fromRowMajorVectorToSD2V (V.fromList [0..9]) :: S ('D2 2 5))\n  (fromRowMajorVectorToSD2 (V.fromList [0..9]) :: S ('D2 5 2))\n  -- (fromRowMajorVectorToSD1 (V.fromList [0..9]) :: S ('D1 10))\n", "meta": {"hexsha": "220c59dcbb7f211c05443304d6000b3a0af370b1", "size": 8692, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Utils/Conversion.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Utils/Conversion.hs", "max_issues_repo_name": "schnecki/grenade", "max_issues_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Utils/Conversion.hs", "max_forks_repo_name": "schnecki/grenade", "max_forks_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-02T01:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:08:47.000Z", "avg_line_length": 32.1925925926, "max_line_length": 157, "alphanum_fraction": 0.6083755177, "num_tokens": 2961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4680599454719677}}
{"text": "module LabelMatrix where\n\n-- import Data.Function    ((&))\nimport Foreign.Storable (Storable)\n\nimport           Data.Map              (Map)\n-- import qualified Data.Map              as M\nimport qualified Data.Vector  as V\n-- import qualified Data.Vector.Storable  as VS\nimport           Numeric.LinearAlgebra hiding (fromList)\n\n{-\nMatrices with labeled rows and columns.\n\nConstruction functions handle uniqueness & correct length of labels.\n\nProvides similar convenience functions to pandas DataFrames. Contrary to the latter, all\nelements in the matrix contain only one type.\n-}\n\n--bla = ((12><12) [0..] :: Matrix I) #> fromList [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] :: Vector I\n\ndata LabelMatrix a r c =\n    LabelMatrix\n        { matrix :: Matrix a\n        , rows   :: V.Vector r\n        , cols   :: V.Vector c\n        } deriving (Show)\n\nfromMatrix :: Matrix a -> [r] -> [c] -> LabelMatrix a r c\nfromMatrix = undefined\n\nfromList :: Storable a => [a] -> [r] -> [c] -> LabelMatrix a r c\nfromList content rowLabels columnLabels =\n    let\n        m = length rowLabels\n        n = length columnLabels\n        mat = (m><n) content\n    in\n        LabelMatrix mat (V.fromList rowLabels) (V.fromList columnLabels)\n\n{-\nv = m \u00bf [0] -- extract column(s)\n\nflatten v -- makes it into a vector, especially nice if the matrix is nx1 anyway.\n-}\n\ngroupBy :: LabelMatrix a r c -> r -> Map a (LabelMatrix a r c)\ngroupBy = groupByRow\n\ngroupByRow :: LabelMatrix a r c -> r -> Map a (LabelMatrix a r c)\ngroupByRow = undefined\n\ngroupByColumn :: LabelMatrix a r c -> c -> Map a (LabelMatrix a r c)\ngroupByColumn = undefined", "meta": {"hexsha": "14eb9bd962e06d98d36fca03a01fc9273d037606", "size": 1599, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/LabelMatrix.hs", "max_stars_repo_name": "2mol/decision-tree", "max_stars_repo_head_hexsha": "c7f0e2d7896938808889ec39a5136791d3ee8e68", "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/LabelMatrix.hs", "max_issues_repo_name": "2mol/decision-tree", "max_issues_repo_head_hexsha": "c7f0e2d7896938808889ec39a5136791d3ee8e68", "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/LabelMatrix.hs", "max_forks_repo_name": "2mol/decision-tree", "max_forks_repo_head_hexsha": "c7f0e2d7896938808889ec39a5136791d3ee8e68", "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.0727272727, "max_line_length": 97, "alphanum_fraction": 0.6447779862, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.46802834085944517}}
{"text": "{-# LANGUAGE CPP                   #-}\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702\n{-# LANGUAGE Trustworthy           \n           , DefaultSignatures     #-}\n#define USE_GHC_GENERICS\n#endif\n{-# LANGUAGE RankNTypes\n           , TypeFamilies         \n           , KindSignatures        \n           , DeriveGeneric         \n           , FlexibleInstances     \n           , FlexibleContexts      \n           , BangPatterns          \n           , MultiParamTypeClasses #-} \n{-# OPTIONS_GHC -fno-warn-orphans  #-}\n\n-------------------------------------------------------------------------------\n-- |\n-- Module      : OGLS.Engine.Math.Vectors\n-- description : 3D and 4D vectors arithmetic \n-- Copyright   : (c) Adam, 2017\n-- License     : MIT\n-- Maintainer  : awkure@protonmail.ch \n-- Stability   : unstable \n-- Portability : POSIX\n-------------------------------------------------------------------------------\n\nmodule OGLS.Engine.Math.Vectors \n    ( (^$+), (^$-), (^$*)\n    , dot, step \n    ) where \n\n#ifdef USE_GHC_GENERICS\nimport GHC.Generics               ( Generic (..) )\n#endif\nimport Control.Applicative        ( liftA2       )\nimport Control.Monad              ( liftM2       )\nimport Control.Parallel           ( pseq         ) \nimport Data.Complex               ( Complex (..) )\nimport Data.Orphans               (              )\nimport Control.Lens hiding ( (<.>) )\n\nimport OGLS.Engine.Math.Instances \n\n\ninfixl 6 ^$+, ^$-\ninfixl 7 ^$*\n\ndefault ()\n\nclass Vector a v where \n    -- not yet implemented\n    \n(^$+) :: forall (t :: * -> *) a. (Applicative t, Num a) => t a -> t a -> t a \n(^$-) :: forall (t :: * -> *) a. (Applicative t, Num a) => t a -> t a -> t a \n(^$*) :: forall (t :: * -> *) a. (Applicative t, Num a) => t a -> t a -> t a \n\n\nnewtype E t = E { el :: forall x. Lens' (t x) x }\n\ndata Vec3 a = Vec3 { v3x :: {-# UNPACK #-} !a\n                   , v3y :: {-# UNPACK #-} !a\n                   , v3z :: {-# UNPACK #-} !a \n                   } deriving ( Eq, Ord, Show, Generic )\n   \ninstance Functor Vec3 where \n    fmap f (Vec3 x y z) = Vec3 (f x) (f y) (f z)\n\ninstance Applicative Vec3 where \n    pure x = Vec3 x x x \n    Vec3 f g h <*> Vec3 x y z = Vec3 (f x) (g y) (h z)\n\n\ndata Vec4 a = Vec4 { v4x :: {-# UNPACK #-} !a\n                   , v4y :: {-# UNPACK #-} !a\n                   , v4z :: {-# UNPACK #-} !a\n                   , v4w :: {-# UNPACK #-} !a \n                   } deriving ( Eq, Ord, Show )\n\n\n(^$+) = liftA2 (+)\n{-# INLINE (^$+) #-}\n(^$-) = liftA2 (-)\n{-# INLINE (^$-) #-}\n(^$*) = liftA2 (*)\n{-# INLINE (^$*) #-}\n\n\n-- | Left scalar product vector\n(*^^) :: forall (f :: * -> *) a. (Functor f, Num a) => a -> f a -> f a\n(*^^) a = fmap (a*)\n{-# INLINE (*^^) #-}\n\n\n-- | Right scalar product vector\n(^^*) :: forall (f :: * -> *) a. (Functor f, Num a) => f a -> a -> f a\nf ^^* a = fmap (*a) f\n{-# INLINE (^^*) #-}\n\n\n{- Needs Additive class and instances\nbasis :: (Traversable t, Num a) => [t a]\nbasis = basisFor (zero :: Additive v => v Int)\n\nbasisFor :: (Traversable t, Num a) => t b -> [t a]\nbasisFor = \\t ->\n   ifoldMapOf traversed ?? t $ \\i _ ->\n     return $ iover  traversed ?? t $ \\j _ ->\n         if i == j then 1 else 0\n{-# INLINABLE basisFor #-}\n-}\n\n-- | Linear interpolation\nlerp :: forall (f :: * -> *) a. (Functor f, Applicative f, Num a) => a -> f a -> f a -> f a\nlerp alpha u v = alpha *^^ u ^$+ (1 - alpha) *^^ v\n{-# INLINE lerp #-}\n\n\n-- | Dot product \ndot :: forall (t :: * -> *) a. (Applicative t, Foldable t, Num a) => t a -> t a -> a \ndot v1 v2 = sum $ v1 ^$* v2\n\n\nstep :: forall (t :: * -> *) a. (Applicative t, Num a, Ord a) => t a -> t a -> t a\nstep = liftA2 (\\a b -> if b < a then 0 else 1)\n\n#ifdef HLINT\n{-# ANN module \"HLint: ignore Redundant lambda\" #-}\n#endif\n", "meta": {"hexsha": "9f684abb97605ae63c0b4cbce9edcb29346d80cb", "size": 3733, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/OGLS/Engine/Math/Vectors.hs", "max_stars_repo_name": "awkure/ogls", "max_stars_repo_head_hexsha": "eabc1532e6922192fca718fc12f05f6950ba09cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/OGLS/Engine/Math/Vectors.hs", "max_issues_repo_name": "awkure/ogls", "max_issues_repo_head_hexsha": "eabc1532e6922192fca718fc12f05f6950ba09cd", "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/OGLS/Engine/Math/Vectors.hs", "max_forks_repo_name": "awkure/ogls", "max_forks_repo_head_hexsha": "eabc1532e6922192fca718fc12f05f6950ba09cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-03-01T07:11:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T07:11:48.000Z", "avg_line_length": 28.7153846154, "max_line_length": 91, "alphanum_fraction": 0.4642378784, "num_tokens": 1133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4680003814396008}}
{"text": "#!/usr/bin/env stack\n-- stack --resolver lts-14.16 script\n{-# LANGUAGE BangPatterns #-}\n\nimport Debug.Trace\n-- import Control.Monad.State.Lazy\n\nimport System.Environment (getArgs)\nimport System.IO (readFile)\nimport Data.Map.Strict (Map, (!), insert, elems, fromList, toList, findWithDefault, size, empty, member, findMin, findMax, singleton)\nimport qualified Data.Map.Strict as M\n--import qualified Data.Array as A\nimport Data.List (permutations)\nimport Data.List.Split (splitOn)\nimport Data.Complex (Complex((:+)), realPart, imagPart)\n\ntype Instructions = Map Integer Integer\n\nrun :: (Integer, Integer) -> Instructions -> [Integer] -> [Integer]\n-- (instructionPointer, base), instructions, input, output\nrun (i, base) instructions inputs =\n  -- trace ((show $ toList instructions) ++ \": (ip, base, instr, inputs) \" ++ show (i, base, instr, inputs) ++ \"\\n\") $\n  case instr `mod` 100 of\n    1 -> run (i+4, base) (insert (addr 3) (arg 1 + arg 2) instructions) inputs\n    2 -> run (i+4, base) (insert (addr 3) (arg 1 * arg 2) instructions) inputs\n    3 -> run (i+2, base) (insert (addr 1) (head inputs) instructions) $ tail inputs\n    4 -> arg 1: run (i+2, base) instructions inputs\n    5 -> run (if arg 1 == 0 then i+3 else arg 2, base) instructions inputs\n    6 -> run (if arg 1 == 0 then arg 2 else i+3, base) instructions inputs\n    7 -> run (i+4, base) (insert (addr 3) (if arg 1 < arg 2 then 1 else 0) instructions) inputs\n    8 -> run (i+4, base) (insert (addr 3) (if arg 1 == arg 2 then 1 else 0) instructions) inputs\n    9 -> run (i+2, base+arg 1) instructions inputs\n    99 -> []\n    _ -> error \"unknown opcode\"\n  where instr = instructions!i\n        ii x = findWithDefault 0 x instructions\n        arg :: Integer -> Integer\n        arg n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ ii $ i+n\n          1 -> ii $ i+n\n          2 -> ii ((ii $ i+n) + base)\n          _ -> error \"bad argument mode\"\n        addr n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ i+n\n          1 -> error \"address in mode 1\"\n          2 -> --trace \"address in mode 2\" $\n            ii (i+n) + base\n          _ -> error $ \"address in unknown mode\"\n\ninstance Ord a => Ord (Complex a) where\n  compare a b | ar < br || ar == br && ai < bi = LT\n              | ar > br || ar == br && ai > bi = GT\n              | otherwise = EQ\n    where (ar, ai) = toParts a\n          (br, bi) = toParts b\n\ntoParts :: Complex a -> (a, a)\ntoParts c = (realPart c, imagPart c)\n\ntoIntParts :: RealFrac a => Complex a -> (Int, Int)\ntoIntParts c = (round $ realPart c, round $ imagPart c)\n\nfromParts :: (a, a) -> Complex a\nfromParts (a,b) = a :+ b\n\n\nprocess :: (Complex Float, Complex Float, Map (Complex Float) Integer) -> [Integer] -> ([Integer], Complex Float, Complex Float, Map(Complex Float) Integer)\nprocess (p, d, colors) [] =\n  -- traceShow (size colors) $\n  -- traceShow (showColors p d colors) $\n  ([], p, d, colors)\nprocess (p, d, colors) (c: t: futureOutputs) =\n  -- traceShow (\"xy\", toIntParts p,\"out\", out,robot d, \"paint\", c,\"turn\", t) $ \n  -- trace (showColors p d colors) $\n  merge out $ process (p', d', insert p c colors) futureOutputs\n  where p' = p + d' -- next position\n        d' = d * (0 :+ (1.0 - fromIntegral t * 2)) -- next direction\n        out = findWithDefault 0 p' colors\n        merge :: Integer -> ([Integer], Complex Float, Complex Float, Map(Complex Float) Integer) -> ([Integer], Complex Float, Complex Float, Map(Complex Float) Integer)\n        merge x ~(xs, p, d, m) = (x:xs, p, d, m) -- need the irrefutable match operator ~, see https://stackoverflow.com/questions/59297557/when-can-i-rely-on-haskell-to-read-a-list-lazily/59298311#59298311\n        \n-- showProcess :: [Integer] -> (Complex Float, Complex Float, Map (Complex Float) Integer) -> (Complex Float, Complex Float, Map (Complex Float) Integer)\n-- showProcess [] s = s\n-- showProcess [c] s = trace (\"leftover \" ++ show c) $ s\n-- showProcess (c: t: r) (p, d, m) = showProcess r (p', d', insert p c m)\n--   where d' = d * (0 :+ (1.0 - fromIntegral t * 2 ))\n--         p' = p + d'\n\nshowColors :: Complex Float -> Complex Float -> Map (Complex Float) Integer -> [Char]\nshowColors p d cs\n  -- | null cs = []\n  -- | otherwise\n  = --traceShow (\"showColors\", p, robot d, \"min\", (x0,y0), \"max\", (x1,y1), \"colors size\", size cs) $ \n    unlines [line y | y <- reverse $ [y0 .. y1]]\n  where line :: Int -> [Char]\n        line y = [ (v (fromIntegral x :+ fromIntegral y) $ findWithDefault 3 (fromIntegral x :+ fromIntegral y) cs) | x <- [x0 .. x1]]\n        pts = map fst $ toList cs\n        xs = map (round . realPart) $ p: pts\n        ys = map (round . imagPart) $ p: pts\n        x0, y0, x1, y1 :: Int\n        [x0, y0, x1, y1] = [minimum xs, minimum ys, maximum xs, maximum ys]\n        v :: Complex Float -> Integer -> Char\n        v p' c | p == p' = robot d\n               | p' == (0.0 :+ 0.0) && c== 0 = 'o'\n               | p' == (0.0 :+ 0.0) && c== 1 = 'O'\n               | c == 1 = '#'\n               | c == 0 = ' ' -- '.' -- change to space for clarity\n               | otherwise = ' '\n\nrobot :: Complex Float -> Char\nrobot c | x == 0 && y == 1 = '^'\n        | x == 1 && y == 0 = '>'\n        | x == 0 && y == -1 = 'V'\n        | x == -1 && y == 0 = '<'\n        where (x,y) = toParts c\n\norigin = 0 :+ 0\nup = 0 :+ 1\nstartColors = singleton origin 0\nstartColors2 = singleton origin 1\n\nmain = do\n  [instructionFile] <- getArgs\n  instructionStrings <- readFile instructionFile\n  let instructions = fromList . zip [0 ..] $ map read $ splitOn \",\" instructionStrings\n\n  putStrLn \"Part 1\"\n  let out = run (0,0) instructions $ (startColors!origin) : processOutput\n      (processOutput, finalp, finald, colors) = process (origin,up, startColors) $ out\n  putStrLn\n    $ unlines\n    $ [\"done Part 1\"\n      , show $ (\"tiles painted: \", size colors)\n      , show $ (\"finalp\", finalp, \"finald\", robot finald)\n      ]\n  putStr $ showColors finalp finald colors\n\n  putStrLn \"Part 2\"\n  let out = run (0,0) instructions $ (startColors2!origin) : processOutput\n      (processOutput, finalp, finald, colors) = process (origin,up, startColors2) $ out\n  putStrLn\n    $ unlines\n    $ [\"done Part 2\"\n      , show $ (\"tiles painted: \", size colors)\n      , show $ (\"finalp\", finalp, \"finald\", robot finald)\n      ]\n  putStr $ showColors finalp finald colors\n\n\n\n", "meta": {"hexsha": "54fcff0cdac06000a251d3a8332a92bc33a369f6", "size": 6336, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "11.hs", "max_stars_repo_name": "dpatru/aoc2019", "max_stars_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-30T21:19:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T21:19:29.000Z", "max_issues_repo_path": "11.hs", "max_issues_repo_name": "dpatru/aoc2019", "max_issues_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "11.hs", "max_forks_repo_name": "dpatru/aoc2019", "max_forks_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9602649007, "max_line_length": 206, "alphanum_fraction": 0.5817550505, "num_tokens": 2005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.46766584104953446}}
{"text": "{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule StatReport (statReport, showStatEntryValue) where\n\nimport Data.Fixed (showFixed)\nimport Data.Text (Text)\nimport Fmt\n\nimport QuoteData\nimport Statistics\n\n\ninstance Buildable Statistic where\n  build Mean = \"Mean\"\n  build Min = \"Minimum\"\n  build Max = \"Maximum\"\n  build Days = \"Days between Min/Max\"\n\n\nshowStatEntryValue :: StatEntry -> String\nshowStatEntryValue StatEntry {..} = showFixed (removeTrailing stat qfield) value\n  where\n    removeTrailing Days _ = True\n    removeTrailing Min Volume = True\n    removeTrailing Max Volume = True\n    removeTrailing _ _ = False\n\n    \ninstance Buildable StatEntry where\n  build se@StatEntry {..} = \"\"+|stat|+\": \"+|showStatEntryValue se|+\"\"\n\n\ninstance Buildable StatQFieldData where\n  build (qf, stats) = nameF (\"Statistics for \" +||qf||+\"\") $ unlinesF stats\n\n\nstatReport :: StatInfo -> Text\nstatReport = fmt . unlinesF\n", "meta": {"hexsha": "0304784fa20003eb4bc577132a13ed9f0fb0e3a9", "size": 969, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/StatReport.hs", "max_stars_repo_name": "Francososa/stockell", "max_stars_repo_head_hexsha": "362b49309e227fb311b4d941404b4e65fd603226", "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/StatReport.hs", "max_issues_repo_name": "Francososa/stockell", "max_issues_repo_head_hexsha": "362b49309e227fb311b4d941404b4e65fd603226", "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/StatReport.hs", "max_forks_repo_name": "Francososa/stockell", "max_forks_repo_head_hexsha": "362b49309e227fb311b4d941404b4e65fd603226", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6341463415, "max_line_length": 80, "alphanum_fraction": 0.7223942208, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.46747092268918095}}
{"text": "module DistanceGeometry\n  ( \n  -- * Steps of algorithm\n    generateDistBoundsMatr\n  , triangleSmooth\n  , randomDistMatr\n  , distMatrToMetricMatr\n  , largestEigValVec\n  , generateCoorFromEigValVec\n  , coordMatrToDistMatr\n  , updateCoord\n\n  -- * Error Functions\n  , distanceErrorFunction\n  , chiralErrorFunction\n  ) where\n\nimport           Control.Lens\nimport           Control.Monad.State\nimport           Data.List                   (foldl', zipWith3)\nimport           Numeric.LinearAlgebra\nimport           Numeric.LinearAlgebra.Data\nimport           Numeric.LinearAlgebra.Devel\nimport           System.Random\nimport           Types\n\n-- * Steps of algorithm\n-- | Generate of a distance bounds matrix\ngenerateDistBoundsMatr :: Molecule -> [Bond] -> (Matrix Double, Matrix Double)\ngenerateDistBoundsMatr molecule bonds =\n  let n = views atoms length molecule\n      upperDist _ _ = 100\n      lowerDist i j = getAtom i molecule ^. avdwrad +\n                      getAtom j molecule ^. avdwrad\n      fixedDist i j = sqrt $ (xj - xi) ^ 2 + (yj - yi) ^ 2 + (zj - zi) ^ 2\n        where\n          (Point xi yi zi) = getAtom i molecule ^. acoordin\n          (Point xj yj zj) = getAtom j molecule ^. acoordin\n      upper = build (n, n) (\\i' j' ->\n        let (i, j) = (fromEnum i', fromEnum j')\n        in if i == j \n           then 0\n           else if isBonded i j bonds\n                then fixedDist i j\n                else upperDist i j) \n      lower = build (n, n) (\\i' j' ->\n        let (i, j) = (fromEnum i', fromEnum j')\n        in if i == j\n           then 0\n           else if isBonded i j bonds\n                then fixedDist i j\n                else lowerDist i j)\n   in (upper, lower)\n\n-- | Triangle Inequality Bounds Smoothing\n-- triangleSmooth :: Matrix Double -> Either String (Matrix Double)\ntriangleSmooth :: (Matrix Double, Matrix Double) -> (Matrix Double, Matrix Double)\ntriangleSmooth (upper, lower) =\n  let n = rows upper\n      kij = [ (k, i, j) \n       | k <- [0 .. n - 1] \n       , i <- [0 .. n - 2] \n       , j <- [i + 1 .. n - 1]\n       ]\n      smoothing (u0, l0) (k, i, j) = do\n        let (u1, l1) = if e1 > e2 + e3\n                       then (changeMatrix u0 (i, j) (e2 + e3), l0)\n                       else (u0, l0)\n                       where\n                        e1 = u0 `atIndex` (i, j)\n                        e2 = u0 `atIndex` (i, k)\n                        e3 = u0 `atIndex` (k, j)\n        let (u2, l2) = if e1 < e2 - e3\n                       then (u1, changeMatrix l1 (i, j) (e2 - e3))\n                       else (u1, l1)\n                       where\n                        e1 = l1 `atIndex` (i, j)\n                        e2 = l1 `atIndex` (i, k)\n                        e3 = u1 `atIndex` (k, j)\n        let (u3, l3) = if e1 < e2 - e3\n                       then (u2, changeMatrix l2 (i, j) (e2 - e3))\n                       else (u2, l2)\n                       where\n                        e1 = l2 `atIndex` (i, j)\n                        e2 = l2 `atIndex` (j, k)\n                        e3 = u2 `atIndex` (k, i)\n        if l3 ! i ! j > u3 ! i ! j\n        then error \"Erroneous Bounds\"\n        else (u3, l3)\n      (upper', lower') = foldl' smoothing (upper, lower) kij\n      newUpper = build (n, n) (\\i' j' ->\n        let (i, j) = (fromEnum i', fromEnum j')\n        in if i < j\n           then upper' `atIndex` (i, j)\n           else upper' `atIndex` (j, i))\n      newLower = build (n, n) (\\i' j' ->\n        let (i, j) = (fromEnum i', fromEnum j')\n        in if i < j\n           then lower' `atIndex` (i, j)\n           else lower' `atIndex` (j, i))\n   in (newUpper, newLower)\n\n-- | Generation of a distance matrix by random selection\n-- of distances between the bounds.\nrandomDistMatr :: (Matrix Double, Matrix Double) -> IO (Matrix Double)\nrandomDistMatr (upper, lower) = do\n  let n = rows upper\n  distanceVector <- sequence [ r\n   | i <- [0 .. n - 1]\n   , j <- [0 .. n - 1]\n   , let a = lower `atIndex` (i, j)\n         b = upper `atIndex` (i, j)\n         r = if j <= i\n             then return 0\n             else randomRIO (a, b)\n             ]\n  let distanceMatrix = matrix n distanceVector\n  return $ distanceMatrix `add` tr' distanceMatrix\n\n-- | Improving Random Sampling: Metrization\nmetrization :: Matrix Double -> Matrix Double\nmetrization matrix = undefined\n\n-- | Improving Random Sampling: Partial Metrization\npartialMetrization :: Matrix Double -> Matrix Double\npartialMetrization matrix = undefined\n\n-- | Conversion of the distance matrix to a metric matrix\ndistMatrToMetricMatr :: Matrix Double -> Matrix Double\ndistMatrToMetricMatr matr =\n  let n = rows matr\n      m = fromIntegral n\n      uTriangleMatr = build (n, n) (\\i' j' ->\n        let (i, j) = (fromEnum i', fromEnum j')\n        in if j <= i\n           then 0\n           else matr `atIndex` (i, j))\n      d0 i = (1 / m) * sumElements ((matr ! i) ^ 2) - \n             (1 / m ^ 2) * sumElements (uTriangleMatr ^ 2)\n  in build (n, n) (\\i' j' ->\n    let (i, j) = (fromEnum i', fromEnum j')\n        a = d0 i\n        b = d0 j\n        c = matr `atIndex` (i, j)\n    in (a + b - c ^ 2) / 2)\n\n-- | distanceToMetricMatrix is symmetric matrix => eigenvalues is real\n-- Function return @k@ pairs of eigenvalues and eigenvectors (as columns)\n-- in descending order\nlargestEigValVec :: Matrix Double -> (Vector Double, Matrix Double)\nlargestEigValVec matr =\n  if (not . isSymmetric) matr\n  then error \"The matrix is not symmetric\"\n  else (subVector 0 k eigval, takeColumns k eigvec)\n  where\n    (eigval, eigvec) = (eigSH . trustSym) matr\n    k = min 3 (size eigval)\n\n-- | Generation of three-dimensional coordinates from\n-- eigenvalues and eigenvectors.\ngenerateCoorFromEigValVec :: \n  (Vector Double, Matrix Double) -> Matrix Double\ngenerateCoorFromEigValVec (val, vec) = \n  vec Numeric.LinearAlgebra.<> (sqrt . diag) val\n\n-- | Convert coordinate matrix to\n-- distance matrix.\ncoordMatrToDistMatr :: Matrix Double -> Matrix Double\ncoordMatrToDistMatr matr =\n  let n = rows matr\n      dist i j = sqrt $ (xj - xi) ^ 2 + (yj - yi) ^ 2 + (zj - zi) ^ 2\n        where\n          [xi, yi, zi] = toList $ matr ! i\n          [xj, yj, zj] = toList $ matr ! j\n      dmatr = build (n, n) (\\i' j' ->\n       let (i, j) = (fromEnum i', fromEnum j')\n       in if j <= i\n          then 0\n          else dist i j)\n  in dmatr `add` tr' dmatr\n\n-- | Update coordinates\nupdateCoord :: Matrix Double -> Molecule -> Molecule\nupdateCoord coord mol = set atoms newatoms mol\n  where\n    newatoms = zipWith updatec (toRows coord) (view atoms mol)\n    updatec coord' =\n      execState\n        (do acoordin . x .= coord' ! 0\n            acoordin . y .= coord' ! 1\n            acoordin . z .= coord' ! 2)\n\n-- * Error Functions\n-- | Distance error function.\ndistanceErrorFunction ::\n     Matrix Double -> Matrix Double -> Matrix Double -> [Bond] -> Double\ndistanceErrorFunction coord upper lower bonds =\n  let n = rows coord\n      dist = coordMatrToDistMatr coord\n      [d2, u2, l2] = map (^2) [dist, upper, lower]\n      ij' = [(i, j) | i <- [0 .. n - 2], j <- [i + 1 .. n - 1]]\n      ij = filter (\\(i,j) -> not $ isBonded i j bonds) ij'\n      f1 (i, j) =\n        (+) $ max 0 (d2 ! i ! j - u2 ! i ! j) ^ 2 +\n        max 0 (l2 ! i ! j ^ 2 - d2 ! i ! j) ^ 2\n      f2 (i, j) =\n        (+) $ max 0 (d2 ! i ! j / u2 ! i ! j - 1) ^ 2 +\n        max 0 (l2 ! i ! j / d2 ! i ! j - 1) ^ 2\n      f3 (i, j) =\n        (+) $ max 0 (d2 ! i ! j / u2 ! i ! j - 1) ^ 2 +\n        max 0 (2 * l2 ! i ! j / (l2 ! i ! j + d2 ! i ! j) - 1) ^ 2\n   in foldr f1 0 ij + foldr f2 0 ij + foldr f3 0 ij\n\n-- | Chiral error function.\nchiralErrorFunction ::\n     Matrix Double -> Matrix Double -> Matrix Double -> [Bond] -> Double\nchiralErrorFunction coord upper lower bonds = \n  let n = rows coord\n      dist = coordMatrToDistMatr coord\n      ijkm' = [(i,j,k,m) | i <- [0..n-1], j <- [i+1..n-1], \n                           k <- [j+1..n-1], m <- [k+1..n-1]]\n      ijkm = filter (isTetrahedra dist) ijkm'\n        where\n          isTetrahedra d (i,j,k,m) = all (isTriangle d) [(i,j,k), (i,j,m), (i,k,m), (j,k,m)] && all (checkAngles d) [(i,j,k,m)]-- (j,k,m,i), (k,m,i,j), (m,i,j,k)]\n            where isTriangle d (i,j,k) = and [a + b > c, b + c > a, c + a > b]\n                   where a = d ! i ! j\n                         b = d ! i ! k\n                         c = d ! j ! k\n                  checkAngles d (i,j,k,m) = and [b1 + b2 > b3, b1 + b3 > b2, b2 + b3 > b1]\n                   where a1 = d ! i ! j; a2 = d ! i ! k\n                         a3 = d ! i ! m; a4 = d ! j ! k\n                         a5 = d ! j ! m; a6 = d ! k ! m \n                         b1 = acos $ (a1^2 + a2^2 - a4^2) / (2*a1*a2)\n                         b2 = acos $ (a1^2 + a3^2 - a5^2) / (2*a1*a3)\n                         b3 = acos $ (a2^2 + a3^2 - a6^2) / (2*a2*a3)\n      vol (i,j,k,m) = (xj - xi) `dot` ((xk - xi) `cross` (xm - xi))\n        where [xi,xj,xk,xm] = map (coord !) [i,j,k,m]\n      u (i,j,k,m) = (sum . map (atIndex upper)) [(i, j), (j, k), (k, m), (m, i)]\n      l (i,j,k,m) = (sum . map (atIndex lower)) [(i, j), (j, k), (k, m), (m, i)]\n      f x@(i,j,k,m) = (+) $ max 0 (vol x - u x) ^ 2 + max 0 (l x - vol x)\n  in foldr f 0 ijkm\n\n-- * Utils.\n-- | \u0418\u0437\u043c\u0435\u043d\u044f\u0435\u0442 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446\u044b @m@ \u043f\u043e \u0438\u043d\u0434\u0435\u043a\u0441\u0430\u043c (@i@,@j@) \u043d\u0430 \u0443\u043a\u0430\u0437\u0430\u043d\u043d\u043e\u0435 @v@\nchangeMatrix :: Matrix Double -> (Int, Int) -> Double -> Matrix Double\nchangeMatrix m (i, j) v =\n  runSTMatrix $ do\n    m' <- thawMatrix m\n    writeMatrix m' i j v\n    return m'\n\n-- | Check the symmetric matrix\nisSymmetric :: Matrix Double -> Bool\nisSymmetric matr =\n  let r = rows matr\n      c = cols matr\n      s = [matr ! i ! j == matr ! j ! i | i <- [0 .. r - 1], j <- [i .. c - 1]]\n  in r == c && and s\n\n-- | \u041e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u0435\u0442, \u0441\u0432\u044f\u0437\u0430\u043d\u044b \u043b\u0438 \u0430\u0442\u043e\u043c\u044b\nisBonded :: Serial -> Serial -> [Bond] -> Bool\nisBonded n m s = (n, m) `elem` bonds s || (m, n) `elem` bonds s\n  where bonds = map (\\x -> (view bfid x, view bsid x))\n\n-- | Get atom from molecule\ngetAtom :: Serial -> Molecule -> Atom\ngetAtom i = views atoms (!! i)", "meta": {"hexsha": "5e6acbde3e50b9543c638f9912f353b761803473", "size": 9951, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/DistanceGeometry.hs", "max_stars_repo_name": "wurthel/distance-geometry", "max_stars_repo_head_hexsha": "b0b6146a1769781d750f99217168b6f4b06d2cb4", "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/DistanceGeometry.hs", "max_issues_repo_name": "wurthel/distance-geometry", "max_issues_repo_head_hexsha": "b0b6146a1769781d750f99217168b6f4b06d2cb4", "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/DistanceGeometry.hs", "max_forks_repo_name": "wurthel/distance-geometry", "max_forks_repo_head_hexsha": "b0b6146a1769781d750f99217168b6f4b06d2cb4", "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.2696629213, "max_line_length": 162, "alphanum_fraction": 0.5111044116, "num_tokens": 3309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4673177188623134}}
{"text": "{-# LANGUAGE FlexibleContexts       #-}\n{-# LANGUAGE FlexibleInstances      #-}\n{-# LANGUAGE MultiParamTypeClasses  #-}\n{-# LANGUAGE QuantifiedConstraints  #-}\n{-# LANGUAGE RecordWildCards        #-}\n{-# LANGUAGE ScopedTypeVariables    #-}\n{-# LANGUAGE UndecidableInstances   #-}\nmodule Q.Stochastic.Discretize\n        where\n\nimport           Data.Functor\nimport           Numeric.LinearAlgebra\nimport           Q.Stochastic.Process\n-- |Euler discretization of stochastic processes\nnewtype Euler = Euler { eDt :: Double }\n        deriving stock (Show, Eq)\n\n-- | Euler end-point discretization of stochastic processes\nnewtype EndEuler = EndEuler { eeDt :: Double }\n        deriving stock (Show, Eq)\n\n\ninstance Discretize Euler Double where\n  dDrift p Euler{..} s0 = pDrift p s0 <&> (* eDt)\n  dDiff  p Euler{..} b  = (pDiff p b) <&> (* (sqrt eDt))\n  dDt    _ Euler{..} _  = eDt\n\ninstance Discretize Euler (Vector Double) where\n  dDrift p Euler{..} s0 = pDrift p s0 <&> (scale eDt)\n  dDiff  p Euler{..} b = (pDiff p b) <&> (scale (sqrt eDt))\n  dDt    _ Euler{..} _  = eDt\n\ninstance Discretize EndEuler Double where\n  dDrift p EndEuler{..} s0@(t0, x0) = pDrift p (t0 + eeDt, x0) <&> (* eeDt)\n  dDiff  p EndEuler{..}  s0@(t0, x0) =  pDiff  p (t0 + eeDt, x0) <&> (* (sqrt eeDt))\n  dDt    _ e _   = eeDt e\n", "meta": {"hexsha": "fd86e7bd03a76dd21e9cd16e91452c122c8417ac", "size": 1299, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Q/Stochastic/Discretize.hs", "max_stars_repo_name": "ghais/HQu", "max_stars_repo_head_hexsha": "442853bb951dde706838d6aa16c619777abb2422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Q/Stochastic/Discretize.hs", "max_issues_repo_name": "ghais/HQu", "max_issues_repo_head_hexsha": "442853bb951dde706838d6aa16c619777abb2422", "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/Q/Stochastic/Discretize.hs", "max_forks_repo_name": "ghais/HQu", "max_forks_repo_head_hexsha": "442853bb951dde706838d6aa16c619777abb2422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1081081081, "max_line_length": 84, "alphanum_fraction": 0.6258660508, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.46724908567784335}}
{"text": "{-# LANGUAGE BangPatterns    #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TupleSections   #-}\n\nmodule Main where\n\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport Numeric.GSL.SimulatedAnnealing\nimport qualified Numeric.LinearAlgebra as H\nimport Text.Parsec hiding (parse)\nimport qualified Text.Parsec as Parsec\n\nmain :: IO ()\nmain = do\n  !input <- parse <$> readFile \"inputs/day-17.txt\"\n\n  putStrLn $ \"Target: \" <> show input\n\n  putStrLn \"\\nPart 1:\"\n  -- print . hitsTarget input $! fancySolve input\n  print $! bruteforce input\n\n  putStrLn \"\\nPart 2:\"\n  print $! bruteforceBy length input\n\n\n-- | The target area.\ndata Target = Target { left :: Int, right :: Int, bottom :: Int, top :: Int }\n  deriving (Show)\n\n-- | Find the velocity with the highest y-coordinate that passes through the\n-- target.\n--\n-- This doesn't actually work\nfancySolve :: Target -> (Int, Int)\nfancySolve target =\n  simanSolve 420 2 solverParams (20, 20)\n    (solverPenalty target)\n    (\\(oldX, oldY) (newX, newY) -> fromIntegral $ abs (newX - oldX) + abs (newY - oldY))\n    step\n    (Just $ \\velo -> show velo <> \": dist = \" <> show (overshootDistance target velo))\n  where\n    solverParams = SimulatedAnnealingParams\n      1000   -- Tries per step\n      1000   -- Tries per temperature\n      1      -- Maximum step size in random walk\n      1.0    -- Boltzman constant for random walks\n      2.0    -- Initial temperature\n      1.69   -- Cooling rate\n      0.0069 -- Final temperature\n\n    step :: H.Vector Double -> Double -> (Int, Int) -> (Int, Int)\n    step rands _ velo@(veloX, veloY) =\n      ( veloX + round (((rands H.! 0) - 0.5) * overshootDistance target velo * 10)\n      , veloY + round (((rands H.! 1) - 0.5) * overshootDistance target velo * 10)\n      )\n\n-- | Just exhaustively try all options to find starting velocity that results in\n-- highest reached Y-coordinate.\nbruteforce :: Target -> ((Int, Int), Int)\nbruteforce = bruteforceBy (maximumBy (comparing snd))\n\nbruteforceBy :: ([((Int, Int), Int)] -> a) -> Target -> a\nbruteforceBy f target@Target{..}\n  = f\n  $ mapMaybe (\\p -> (p,) <$> hitsTarget target p)\n    [(x, y) | x <- [1 .. right], y <- [bottom .. abs bottom]]\n\n-- | The penalty for the solver. This is negative the maximum Y-coordinate\n-- unless the trajectory would not hit the target area, in which case it is the\n-- distance to the center of the target area.\nsolverPenalty :: Target -> (Int, Int) -> Double\nsolverPenalty target initialVelo\n  | Just maxYPos <- hitsTarget target initialVelo = fromIntegral (negate maxYPos)\n  | otherwise                                     = (overshootDistance target initialVelo + 100) ** 2\n\n-- | Whether the given velocity causes the target to be hit. Returns the highest\n-- Y-position if it does.\nhitsTarget :: Target -> (Int, Int) -> Maybe Int\nhitsTarget Target{..} = go (0, 0)\n  where\n    go :: (Int, Int) -> (Int, Int) -> Maybe Int\n    go (posX, posY) (veloX, veloY)\n      | posX > right || posY < bottom = Nothing\n      | otherwise =\n          let newPos  = (posX + veloX, posY + veloY)\n              newVelo = (veloX - signum veloX, veloY - 1)\n           in if posX >= left && posX <= right && posY >= bottom && posY <= top\n                then Just posY\n                else max posY <$> go newPos newVelo\n\n-- | The minimal distance the target's center is overshot by while following the\n-- trajectory, bounded by double the target's bottom right corner.\novershootDistance :: Target -> (Int, Int) -> Double\novershootDistance Target{..} = lowestDistance (0, 0)\n  where\n    centerX = (left + right) `div` 2\n    centerY = (top + bottom) `div` 2\n    boundX = right * 2\n    boundY = bottom * 2\n\n    lowestDistance :: (Int, Int) -> (Int, Int) -> Double\n    lowestDistance (posX, posY) (veloX, veloY) =\n      let distance                  = sqrt $ fromIntegral (centerX - posX) ** 2\n                                           + fromIntegral (centerY - posY) ** 2\n          newPos@(newPosX, newPosY) = (posX + veloX, posY + veloY)\n          newVelo                   = (veloX - signum veloX, veloY - 1)\n       in if newPosX > boundX || newPosY < boundY\n            then distance\n            else min distance (lowestDistance newPos newVelo)\n\nparse :: String -> Target\nparse = fromRight' . Parsec.parse pTarget \"\"\n  where\n    fromRight' (Right x) = x\n    fromRight' _         = error \"This wasn't in our agreement!\"\n\n    pTarget :: Parsec String () Target\n    pTarget = Target <$> (string \"target area: x=\" *> pInt)     <*> (string \"..\" *> pInt)\n                     <*> (string \", y=\" *> pInt <* string \"..\") <*> pInt\n\n    pInt :: Parsec String () Int\n    pInt = read <$> many (digit <|> char '-')\n", "meta": {"hexsha": "846da76896b5cbc7c4e4c6f7e68caccb32becee2", "size": 4648, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Day17.hs", "max_stars_repo_name": "robbert-vdh/aoc2021", "max_stars_repo_head_hexsha": "f8d02794425ff3916969ee56527446078c40fce8", "max_stars_repo_licenses": ["0BSD"], "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/Day17.hs", "max_issues_repo_name": "robbert-vdh/aoc2021", "max_issues_repo_head_hexsha": "f8d02794425ff3916969ee56527446078c40fce8", "max_issues_repo_licenses": ["0BSD"], "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/Day17.hs", "max_forks_repo_name": "robbert-vdh/aoc2021", "max_forks_repo_head_hexsha": "f8d02794425ff3916969ee56527446078c40fce8", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8888888889, "max_line_length": 101, "alphanum_fraction": 0.6103700516, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46702000492521023}}
{"text": "{-# OPTIONS_GHC -fsimpl-tick-factor=150 #-}\n{-# LANGUAGE BangPatterns, RecordWildCards #-}\n\nmodule Network.HTTP.LoadTest.Analysis\n    (\n    -- * Result analysis\n      Analysis(..)\n    , Basic(..)\n    , analyseBasic\n    , analyseFull\n    ) where\n\nimport Criterion.Analysis (SampleAnalysis, analyseSample)\nimport Network.HTTP.LoadTest.Types (Analysis(..), Basic(..), Summary(..))\nimport Prelude hiding (catch)\nimport Statistics.Quantile (weightedAvg)\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Statistics.Sample as S\n\nanalyseFull :: V.Vector Summary -> Double -> IO (Analysis SampleAnalysis)\nanalyseFull sumv elapsed = do\n  let ci = 0.95\n      resamples = 10 * 1000\n  l <- analyseSample ci (G.convert . G.map summElapsed $ sumv) resamples\n  return Analysis {\n                 latency = l\n               , latency99 = weightedAvg 99 100 . G.map summElapsed $ sumv\n               , latency999 = weightedAvg 999 1000 . G.map summElapsed $ sumv\n               , latValues = sumv\n               , throughput = fromIntegral (G.length sumv) / elapsed\n    }\n\nanalyseBasic :: V.Vector Summary -> Double -> Analysis Basic\nanalyseBasic sumv elapsed = Analysis {\n                      latency = Basic {\n                                  mean = S.mean . G.map summElapsed $ sumv\n                                , stdDev = S.stdDev . G.map summElapsed $ sumv\n                                }\n                    , latency99 = weightedAvg 99 100 . G.map summElapsed $ sumv\n                    , latency999 = weightedAvg 999 1000 . G.map summElapsed $ sumv\n                    , latValues = sumv\n                    , throughput = fromIntegral (G.length sumv) / elapsed\n                    }\n", "meta": {"hexsha": "2c399522b4aad191ee73c74b98347b99ac44fd58", "size": 1725, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Network/HTTP/LoadTest/Analysis.hs", "max_stars_repo_name": "fhartwig/pronk", "max_stars_repo_head_hexsha": "e3a0f789801237b5abdd7b2c65d15b47d00d0b98", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 65, "max_stars_repo_stars_event_min_datetime": "2015-01-07T20:48:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T11:01:08.000Z", "max_issues_repo_path": "lib/Network/HTTP/LoadTest/Analysis.hs", "max_issues_repo_name": "liqd/pronk", "max_issues_repo_head_hexsha": "e3a0f789801237b5abdd7b2c65d15b47d00d0b98", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-05-07T16:41:30.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-07T16:41:30.000Z", "max_forks_repo_path": "lib/Network/HTTP/LoadTest/Analysis.hs", "max_forks_repo_name": "bos/pronk", "max_forks_repo_head_hexsha": "e3a0f789801237b5abdd7b2c65d15b47d00d0b98", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-02-06T15:09:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-27T21:04:00.000Z", "avg_line_length": 38.3333333333, "max_line_length": 82, "alphanum_fraction": 0.591884058, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4669805027194194}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule CPVO.Numeric (\n  integrateAll,\n  sumRow,\n  getY0,\n  delta,\n  integrateToZero,\n  integrateAtomicPDOS\n  ) where\n\nimport Numeric.LinearAlgebra\nimport Data.List (findIndex,groupBy)\nimport Data.Maybe (fromJust)\n\nintegrateToZero :: Matrix Double -> Double\nintegrateToZero mP = integrateAll 0\n  $ (++ ([toList $ getY0 $ takeColumns 2 mP]))\n  $ takeWhile (\\(a:_) -> a <= 0)\n  $ toLists $ takeColumns 2 mP\n\nintegrateAll :: Double -> [[Double]] -> Double\nintegrateAll res [] = res\nintegrateAll res ([enA,nA]:b@[enB,nB]:as)\n  | as == [] = integrateAll (res + (enB - enA)*(nA+nB)*0.5) []\n  | otherwise = integrateAll (res + (enB - enA)*(nA+nB)*0.5) (b:as)\nintegrateAll _ _ = 99\n\nsumRow :: Matrix Double -> Vector Double\nsumRow a = a #> konst 1 (cols a)\n\ngetY0 :: Matrix Double -> Vector Double\ngetY0 dos = getY0' lowPos higNeg\n  where\n    rTDOS = toRows $ dos\n    highestNeg = (+) (-1) $ fromJust $ findIndex (\\a -> (atIndex a 0) >= 0) rTDOS\n    lowestPos = highestNeg + 1\n    higNeg = rTDOS !! highestNeg\n    lowPos = rTDOS !! lowestPos\n\ngetY0' :: Vector Double -> Vector Double -> Vector Double\ngetY0' a b = a + (scale m v)\n  where\n    v = b - a\n    m = ((*) (-1) $ a ! 0) / ((b ! 0) - (a ! 0))\n\ndelta :: Bool -> b -> b -> b\ndelta x y z = if x then y else z\n\nintegrateAtomicPDOS :: [(Matrix Double, (Int, (String, (Int, String))))]\n                    -> [(Double, Double, (Int, (String, (Int, String))))]\nintegrateAtomicPDOS pdosAtomicPilihan =\n          (\\[us,ds] -> zipWith (\\(iu,b) (idown,_) -> (iu,idown,b)) us ds )\n          $ groupBy (\\(_,(s,_)) (_,(s',_)) -> s == s') -- [[(spin,label,iup)]]\n          $ map (\\(mp,b) -> (integrateToZero mp,b)) $ pdosAtomicPilihan\n\n", "meta": {"hexsha": "fb9d1d7c6e71859123088fa04ce6116d1723f491", "size": 1764, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/CPVO/Numeric.hs", "max_stars_repo_name": "hasanalrasyid/cpvoh", "max_stars_repo_head_hexsha": "d4e40c681a512b9ffb3f79ec46a4f4e5831e4165", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CPVO/Numeric.hs", "max_issues_repo_name": "hasanalrasyid/cpvoh", "max_issues_repo_head_hexsha": "d4e40c681a512b9ffb3f79ec46a4f4e5831e4165", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CPVO/Numeric.hs", "max_forks_repo_name": "hasanalrasyid/cpvoh", "max_forks_repo_head_hexsha": "d4e40c681a512b9ffb3f79ec46a4f4e5831e4165", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8983050847, "max_line_length": 81, "alphanum_fraction": 0.5980725624, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4668666805049089}}
{"text": "-- Test of the computational correctness of my current FFT candidate.\n--\n-- Original author: David Banas <capn.freako@gmail.com>\n-- Original date:   October 3, 2015\n--\n-- Copyright (c) 2015 David Banas; all rights reserved World wide.\n--\n-- I'm waiting for Conal to find time to look into my latest non-termination\n-- failure through his compiler. While I do, I'm attempting, here, to verify\n-- the computational correctness of my current FFT candidate.\n\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Main where\n\nimport Prelude hiding ({- id,(.), -}foldl,foldr,sum,product,zipWith,reverse,and,or,scanl,minimum,maximum)\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad (forM_, unless)\nimport Data.Complex\nimport Data.Foldable (Foldable, sum, foldl')\nimport Data.Newtypes.PrettyDouble\nimport System.Exit (exitFailure)\nimport TypeUnary.Nat (IsNat, Nat(..), nat, N2, N3, N4, N5)  -- , N6)\n\n-- import Test.QuickCheck (choose, vectorOf, elements, collect)\nimport Test.QuickCheck (choose, vectorOf)\nimport Test.QuickCheck.Arbitrary\nimport Test.QuickCheck.All (quickCheckAll)\n\nimport Circat.Scan (lproducts, LScan)\nimport qualified Circat.Pair as P\nimport qualified Circat.RTree as RT\nimport Circat.RTree (bottomSplit)\n\ntype RTree = RT.Tree\n\n-- FFT, as a class\n-- (The LScan constraint comes from the use of 'lproducts', in 'addPhase'.)\nclass (LScan f) => FFT f a where\n    fft  :: f a -> f a  -- Computes the FFT of a functor.\n\n-- Note that this definition of the FFT instance for Pair assumes DIT.\n-- How can we eliminate this assumption and make this more general?\ninstance (RealFloat a, Applicative f, Foldable f, Num (f (Complex a)), FFT f (Complex a)) => FFT P.Pair (f (Complex a)) where\n    fft = P.inP (uncurry (+) &&& uncurry (-)) . P.secondP addPhase . fmap fft\n\ninstance (IsNat n, RealFloat a) => FFT (RTree n) (Complex a) where\n    fft = fft' nat\n        where   fft' :: (RealFloat a) => Nat n -> RTree n (Complex a) -> RTree n (Complex a)\n                fft' Zero     = id\n                fft' (Succ _) = inDIT fft\n                    where   inDIT g  = RT.toB . g . bottomSplit\n\n-- Adds the proper phase adjustments to a functor containing Complex RealFloats,\n-- and instancing Num.\naddPhase :: (Applicative f, Foldable f, LScan f, RealFloat a, Num (f (Complex a))) => f (Complex a) -> f (Complex a)\naddPhase = liftA2 (*) id phasor\n  where phasor f = fst $ lproducts (pure phaseDelta)\n          where phaseDelta = cis ((-pi) / fromIntegral n)\n                n          = flen f\n\n-- Gives the \"length\" (i.e. - number of elements in) of a Foldable.\n-- (Soon, to be provided by the Foldable class, as \"length\".)\nflen :: (Foldable f) => f a -> Int\nflen = foldl' (flip ((+) . const 1)) 0\n\n-- Test config.\nrealData :: [[PrettyDouble]]\nrealData = [  [1.0,   0.0,   0.0,   0.0]  -- Delta\n            , [1.0,   1.0,   1.0,   1.0]  -- Constant\n            , [1.0,  -1.0,   1.0,  -1.0]  -- Nyquist\n            , [1.0,   0.0,  -1.0,   0.0]  -- Fundamental\n            , [0.0,   1.0,   0.0,  -1.0]  -- Fundamental w/ 90-deg. phase lag\n           ]\ncomplexData :: [[Complex PrettyDouble]]\ncomplexData = map (map (:+ 0.0)) realData\n\nmyTree2 :: [a] -> RTree N2 a\nmyTree2 [w, x, y, z] = RT.tree2 w x y z\nmyTree2 _            = error \"Something went horribly wrong!\"\n\nmyTree3 :: [a] -> RTree N3 a\nmyTree3 [a, b, c, d, e, f, g, h] = RT.tree3 a b c d e f g h\nmyTree3 _            = error \"Something went horribly wrong!\"\n\nmyTree4 :: [a] -> RTree N4 a\nmyTree4 [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = RT.tree4 a b c d e f g h i j k l m n o p\nmyTree4 _            = error \"Something went horribly wrong!\"\n\nmyTree5 :: [a] -> RTree N5 a\nmyTree5 [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p,\n         a', b', c', d', e', f', g', h', i', j', k', l', m', n', o', p'] =\n            RT.tree5 a b c d e f g h i j k l m n o p a' b' c' d' e' f' g' h' i' j' k' l' m' n' o' p'\nmyTree5 _            = error \"Something went horribly wrong!\"\n\n-- myTree6 :: [a] -> RTree N6 a\n-- myTree6 [a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1, n1, o1, p1,\n--          a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2, p2,\n--          a3, b3, c3, d3, e3, f3, g3, h3, i3, j3, k3, l3, m3, n3, o3, p3,\n--          a4, b4, c4, d4, e4, f4, g4, h4, i4, j4, k4, l4, m4, n4, o4, p4] =\n--             RT.tree6 a1 b1 c1 d1 e1 f1 g1 h1 i1 j1 k1 l1 m1 n1 o1 p1\n--                      a2 b2 c2 d2 e2 f2 g2 h2 i2 j2 k2 l2 m2 n2 o2 p2\n--                      a3 b3 c3 d3 e3 f3 g3 h3 i3 j3 k3 l3 m3 n3 o3 p3\n--                      a4 b4 c4 d4 e4 f4 g4 h4 i4 j4 k4 l4 m4 n4 o4 p4\n-- myTree6 _            = error \"Something went horribly wrong!\"\n\n-- Discrete Fourier Transform (DFT) (our \"truth\" reference)\n-- O(n^2)\n--\ndft :: RealFloat a => [Complex a] -> [Complex a]\ndft xs = [ sum [ x * exp((0.0 :+ (-1.0)) * 2 * pi / lenXs * fromIntegral(k * n))\n                 | (x, n) <- Prelude.zip xs [0..]\n               ]\n           | k <- [0..(length xs - 1)]\n         ]\n    where lenXs = fromIntegral $ length xs\n\n-- QuickCheck types & propositions\nnewtype FFTTestVal = FFTTestVal {\n    getVal :: [Complex PrettyDouble]\n} deriving (Show)\ninstance Arbitrary FFTTestVal where\n    arbitrary = do\n        xs <- vectorOf 32 $ choose (-1.0::Double, 1.0)\n        let zs = map ((:+ 0) . PrettyDouble) xs\n        return $ FFTTestVal zs\n\nprop_fft_test_N2 :: FFTTestVal -> Bool\nprop_fft_test_N2 testVal = fft (myTree2 zs) == RT.fromList (dft zs)\n    where zs = take 4 $ getVal testVal\n\nprop_fft_test_N3 :: FFTTestVal -> Bool\nprop_fft_test_N3 testVal = fft (myTree3 zs) == RT.fromList (dft zs)\n    where zs = take 8 $ getVal testVal\n\nprop_fft_test_N4 :: FFTTestVal -> Bool\nprop_fft_test_N4 testVal = fft (myTree4 zs) == RT.fromList (dft zs)\n    where zs = take 16 $ getVal testVal\n\nprop_fft_test_N5 :: FFTTestVal -> Bool\nprop_fft_test_N5 testVal = fft (myTree5 zs) == RT.fromList (dft zs)\n    where zs = take 32 $ getVal testVal\n\n-- Test definitions & choice\nbasicTest :: IO ()\nbasicTest = forM_ complexData (\\x -> do\n                putStr \"\\nTesting input: \"\n                print x\n                putStr \"Expected output: \"\n                print $ dft x\n                putStr \"Actual output:   \"\n                print $ fft $ myTree2 x\n                )\n\n-- This weirdness is required, as of GHC 7.8.\nreturn []\n\nrunTests :: IO Bool\nrunTests = $quickCheckAll\n-- End weirdness.\n\nadvancedTest :: IO ()\nadvancedTest = do\n    allPass <- runTests -- Run QuickCheck on all prop_ functions\n    unless allPass exitFailure\n\nmain :: IO ()\n-- main = basicTest\nmain = advancedTest\n\n", "meta": {"hexsha": "f62d4800177b2fd9b99f09e8880ca4dcee132dcf", "size": 6716, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/fft-ccc.hs", "max_stars_repo_name": "capn-freako/fft-ccc", "max_stars_repo_head_hexsha": "b930449d54830d3322dd8aba975164b33ed2f2b5", "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/fft-ccc.hs", "max_issues_repo_name": "capn-freako/fft-ccc", "max_issues_repo_head_hexsha": "b930449d54830d3322dd8aba975164b33ed2f2b5", "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/fft-ccc.hs", "max_forks_repo_name": "capn-freako/fft-ccc", "max_forks_repo_head_hexsha": "b930449d54830d3322dd8aba975164b33ed2f2b5", "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.7303370787, "max_line_length": 125, "alphanum_fraction": 0.6012507445, "num_tokens": 2268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.46678021652028645}}
{"text": "module Core(\n    RenderSettings(..),\n    module Scene.Base,\n    module Scene.Object.Plane,\n    module Scene.Material.Diffuse,\n    module Scene.Object.SimpleSphere,\n    module Math.Color,\n    module Math.Ray,\n    module Scene.Material.Skylike\n    ) where\n    \nimport Scene.Base(Trace, traceRay, Scene, Material)\n--import Scene.Object.SimpleSphere(sphere)\nimport Scene.Object.Plane\nimport Scene.Object.SimpleSphere\nimport Scene.Material.Skylike\nimport Scene.Material.Diffuse\nimport Math.Color\nimport Math.Ray\nimport Numeric.LinearAlgebra\nimport Scene.Object.Plane\nimport GHC.Generics (Generic)\nimport Control.DeepSeq\n\ndata RenderSettings  = RenderSettings {\n    background :: Color,\n    width :: Int,\n    height :: Int,\n    topLeft :: Vec3,\n    topRight :: Vec3,\n    bottomRight :: Vec3,\n    origin :: Vec3,\n    path :: FilePath,\n    antialiasing :: Int}", "meta": {"hexsha": "a3f68d466da9890d345da21761a98f408afdaecd", "size": 852, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Core.hs", "max_stars_repo_name": "danrocag/raytracer", "max_stars_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "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/Core.hs", "max_issues_repo_name": "danrocag/raytracer", "max_issues_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "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/Core.hs", "max_forks_repo_name": "danrocag/raytracer", "max_forks_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0588235294, "max_line_length": 51, "alphanum_fraction": 0.7194835681, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4664730075134403}}
{"text": "{-|\nModule: MachineLearning.MultiSvmClassifier\nDescription: Multiclass Support Vector Machines Classifier.\nCopyright: (c) Alexander Ignatyev, 2017-2018.\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n\nMulticalss Support Vector Machines Classifier.\n-}\n\nmodule MachineLearning.MultiSvmClassifier\n(\n  module MachineLearning.Model\n  , module MachineLearning.Classification.MultiClass\n  , MultiSvmClassifier(..)\n)\n\nwhere\n\n\nimport Prelude hiding ((<>))\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra((<>), (<.>), (|||))\nimport qualified Data.Vector.Storable as V\n\nimport qualified MachineLearning as ML\nimport MachineLearning.Types (R, Vector, Matrix)\nimport MachineLearning.Utils (sumByRows, reduceByRowsV)\nimport MachineLearning.Model\nimport MachineLearning.Classification.MultiClass\n\n\n-- | Multiclass SVM Classifier, takes delta and number of futures. Delta = 1.0 is good for all cases.\ndata MultiSvmClassifier = MultiSvm R Int\n\n\ninstance Classifier MultiSvmClassifier where\n  cscore (MultiSvm _ _) x theta = x <> (LA.tr theta)\n\n  chypothesis m x theta = predictions\n    where scores = cscore m x theta\n          predictions = reduceByRowsV (fromIntegral . LA.maxIndex) scores\n\n  ccost m@(MultiSvm d _) lambda x y theta =\n    let nSamples = fromIntegral $ LA.rows x\n        scores = cscore m x theta\n        correct_scores = LA.remap (LA.asColumn $ V.fromList [0..(fromIntegral $ LA.rows x)-1]) (LA.toInt $ LA.asColumn y) scores\n        margins = scores - (correct_scores - (LA.scalar d))\n        margins' = margins * LA.step margins\n        loss = LA.sumElements(margins') / nSamples - d\n        reg = (ccostReg lambda theta) / nSamples\n    in loss + reg\n\n  cgradient m@(MultiSvm d _) lambda x y theta =\n    let nSamples = fromIntegral $ LA.rows x\n        ys = processOutput m y\n        scores = cscore m x theta\n        correct_scores = LA.remap (LA.asColumn $ V.fromList [0..(fromIntegral $ LA.rows x)-1]) (LA.toInt $ LA.asColumn y) scores\n        margins = scores - (correct_scores - (LA.scalar d))\n        margins' = (1-ys)*(LA.step margins)  -- step == cmap (\\x -> if x>0 then 1 else 0)\n        k = sumByRows margins'\n        margins'' = margins' - (ys * k)\n        dw = ((LA.tr margins'') <> x) / nSamples\n        reg = (cgradientReg lambda theta) / nSamples\n     in dw + reg\n\n  cnumClasses (MultiSvm _ nLabels) = nLabels\n", "meta": {"hexsha": "132afd3c4c28d755ccbcecd08525a21e91689594", "size": 2364, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/MultiSvmClassifier.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "src/MachineLearning/MultiSvmClassifier.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "src/MachineLearning/MultiSvmClassifier.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 34.2608695652, "max_line_length": 128, "alphanum_fraction": 0.6945854484, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.46647300293923105}}
{"text": "module Main(main) where\n\nimport System.Environment (getArgs)\nimport Codec.Picture (generateImage, savePngImage, DynamicImage(ImageRGB8), PixelRGB8(PixelRGB8), pixelAt, colorMap, mixWith)\nimport Numeric.LinearAlgebra.Data ((|>))\nimport Raytracer.Camera (Camera(Camera), Point(Point), fire_ray, calculate_ray)\nimport Raytracer.Geometry (cube, square, dist, Collision(Collision), calc_ray)\nimport Raytracer.Light (Light(Light), computeLighting)\nimport Data.Monoid ((<>))\nimport Data.Maybe (isJust)\n\nimport Control.Parallel.Strategies (rdeepseq, parMap)\nimport Control.Concurrent (getNumCapabilities)\n\nhelp = putStrLn\n  \"Ray traces an image from a simple scene\\n\\\n  \\Run: width height step cx cy cz dx dy dz\\n\\\n  \\Where c_ is camera position, d_ is camera direction\\n\\\n  \\width and height the size of the image, and step is how many pixels exist between width and height\\n\\\n  \\For example, w=200 h=200 step=1 will be a 200x200 image, 200x200x2 will be 100x100, but have the same frame\"\n\ntest_camera wres hres = Camera 4 3 wres hres (Just 3)\ntest_cube = cube (PixelRGB8 255 0 255) (3 |> [2, 0, 0]) (3 |> [0, 2, 0]) (3 |> [0, 0, 2]) (3 |> [0, 0, 0])\ntest_floor = square (PixelRGB8 255 255 255) (3 |> [8,0,0]) (3 |> [0,0,8]) (3 |> [-2,0,-2])\ntest_mesh = test_cube <> test_floor\n\ntest_lights = [\n  Light (3|> [-1, 3, 1]) 6 $ PixelRGB8 255 255 255,\n  Light (3|> [1, 4, 1]) 5 $ PixelRGB8 0 0 255,\n  Light (3|> [6, 0, 0]) 2 $ PixelRGB8 255 0 0,\n  Light (3|> [6, 0, 2]) 2 $ PixelRGB8 0 255 0,\n  Light (3|> [6, 0, 4]) 2 $ PixelRGB8 0 0 255\n  ]\n\n-- This mixes light colours additively\nmixColours = foldr (mixWith add) (PixelRGB8 20 20 20)\n  where\n  add _ c1 c2 = if maxBound - c1 >= c2 then c1 + c2 else maxBound\n\n-- This mixes a pigment with a light subtractively\nreflectLight :: PixelRGB8 -> PixelRGB8 -> PixelRGB8\nreflectLight surface light = mixWith subColour surface light\n  where\n  subColour _ cs cl = if cl >= (maxBound - cs) then cl - (maxBound - cs) else minBound\n\nrenderPixel camera x y = computePixel $ fire_ray test_mesh ray\n  where\n  ray = calculate_ray camera $ Point x y\n  lights = computeLighting test_mesh test_lights\n  computePixel Nothing = PixelRGB8 0 0 0\n  computePixel (Just (Collision d c)) = reflectLight c $ mixColours $ lights $ calc_ray ray d\n\nverticalFlip h func camera x y = func camera x (h - y)\n\nparGenerateImage 1 func w h = generateImage func w h\nparGenerateImage n func w h = generateImage combine w h\n  where\n  -- combine rotates through the parallel images putting lines together\n  combine x y = pixelAt (images !! (y `mod` n)) x $ y `div` n\n  images = parMap rdeepseq generate [0..n-1]\n  generate offset = generateImage (\\x y -> func x $ y*n + offset) w $ heightFor offset\n  -- heightFor offset exists for when the height is not evenly divisible by n\n  -- We need to add a couple rows to the earlier images to make up the difference\n  heightFor offset = h `div` n + (if offset < h `mod` n then 1 else 0)\n\nmain = do\n  args <- getArgs\n  if length args /= 9 then\n    help\n  else do\n    numCores <- getNumCapabilities\n    let (width:height:step:cx:cy:cz:dx:dy:dz:[]) = args\n    let w' = (read width) `div` (read step)\n    let h' = (read height) `div` (read step)\n    let camera = test_camera w' h' (3 |> [read cx, read cy, read cz]) (3 |> [read dx, read dy, read dz])\n    let img = parGenerateImage numCores (verticalFlip h' renderPixel camera) w' h'\n    savePngImage \"test.png\" $ ImageRGB8 img\n", "meta": {"hexsha": "dfd150c18b5770a2101f20c547dbb50a39514559", "size": 3414, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "image_render.hs", "max_stars_repo_name": "psycotica0/ray-tracer", "max_stars_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "image_render.hs", "max_issues_repo_name": "psycotica0/ray-tracer", "max_issues_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "image_render.hs", "max_forks_repo_name": "psycotica0/ray-tracer", "max_forks_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7692307692, "max_line_length": 125, "alphanum_fraction": 0.69390744, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4661408589994101}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Simulation where\n\nimport DigitalAGC\nimport LutLogTests (sfToDouble, ufToDouble)\n\nimport Clash.Prelude (\n  UFixed, Unsigned, Signed, SFixed(..), Vec(..), Nat, KnownDomain(..), HiddenClockResetEnable, SNat(..),\n  createDomain, vInitBehavior, vName, vSystem, InitBehavior(..), Signal,\n  simulate, System,\n  shiftR,\n  register,\n  sf, bundle, df,\n  riseEvery,\n  fLitR, KnownNat\n  )\n\nimport Prelude\nimport Data.Maybe (fromMaybe)\nimport Data.List (group)\n\nimport Lucid\nimport Lucid.Html5\nimport Graphics.Plotly hiding (sort)\nimport qualified Graphics.Plotly.Base as GPB\nimport Graphics.Plotly.Simple\nimport Graphics.Plotly.Lucid\nimport Lens.Micro\nimport System.Process\nimport Data.Array\nimport Data.Foldable\n\nimport qualified Data.Complex as DC\nimport Numeric.Transform.Fourier.FFT\nimport DSP.Basic (linspace)\n\nimport DataFlow.Extra\nimport Test.QuickCheck\n\nimport Statistics.Sample\nimport qualified Data.Vector.Unboxed as V\n--import Data.Fixed\n\n--dec :: Int -> [a] -> [a]\n--dec n [] = []\n--dec n (x : xs) = x : dec n (drop (n-1) xs)\n\ninterp :: Int -> [a] -> [a]\ninterp n [] = []\ninterp n (x : xs) = replicate n x ++ interp n xs\n\nchunks :: Int -> [a] -> [[a]]\nchunks n [] = []\nchunks n xs = take n xs : chunks n (drop n xs)\n\nquantiseS :: forall i f . (KnownNat i, KnownNat f) => SNat i -> SNat f -> Double -> Double\nquantiseS _ _ x = sfToDouble (fLitR x :: SFixed i f)\n\nquantiseU :: forall i f . (KnownNat i, KnownNat f) => SNat i -> SNat f -> Double -> Double\nquantiseU _ _ x = ufToDouble (fLitR x :: UFixed i f)\n\nd0 = SNat :: SNat 0\n\niSig   = SNat :: SNat 26\niGain  = SNat :: SNat 10\nfGain  = SNat :: SNat 10\niAlpha = SNat :: SNat 1\nfAlpha = SNat :: SNat 6\niRef   = SNat :: SNat 3\nfRef   = SNat :: SNat 12\niLog   = SNat :: SNat 4\nfLog   = SNat :: SNat 22\n\nsimAgc :: Double -> Double -> Double -> [(Double, Double)] -> [(Double, Double,Double)]\nsimAgc window ref alpha iqs =\n  let window' = 2**window\n      powers blk = map (\\(i,q)-> quantiseU iSig d0 . sqrt $ i^2 + q^2) blk\n      smooth blk = quantiseU iSig d0 $ (/window') $ sum  blk\n      alg state x = quantiseS iLog fLog (\n                      (quantiseS iLog fLog state) -\n                      ((quantiseS iLog fLog $ logBase 10 (smooth $ powers x)) - (quantiseU iRef fRef ref)) *\n                      (quantiseU iAlpha fAlpha alpha))\n      gains = scanl (\\state x ->\n                quantiseS iLog fLog $\n                alg state (map (\\(i,q)->(\n                  quantiseS iSig d0 $ (i*) $ quantiseU iGain fGain $ 10**state,\n                  quantiseS iSig d0 $ (q*) $ quantiseU iGain fGain $ 10**state)\n                  ) x)\n              ) 0\n              (init $ chunks (round window') iqs)\n  in zipWith (\\(i,q) s -> let g = quantiseU iGain fGain $ 10**s\n                          in (g, quantiseS iSig d0 $ i*g, quantiseS iSig d0 $ q*g))\n     iqs (interp (round window') gains)\n\n\n-- My floating point simulation shows us that we _should_ be ok with our\n-- approach... make some tests to verify the log and exp DF behaviour.\n\ncreateDomain vSystem{vName=\"SyncDefined\", vInitBehavior=Defined}\n\nsimInput = let iqs = map (\\(i,q)->(shiftR i 1, shiftR q 1)) $ sinInputComplex 1 0.01\n           in  take 3000 iqs ++ map (\\(i,q)->(shiftR i 4, shiftR q 4)) iqs\n\n-- from 1.25 to 0.75... our ref is basically divided by 4, so this makes sense for a 100x range\n-- we have 0.5 range with 6 frac bits => resolution of 1/64, so 32 sensible settings for our signal height.\n-- This is all with alpha = 0.9375 and a window of 7\n-- Window doesn't really affect this too much\n-- Alpha seems to?\n\n-- we have a 2.6 log word ( really 4.4)\n\n-- a = 0.9375 and window = 128 ~ 1.5k         1.5k\n-- a = 0.5                       3k           3.5k\n-- a = 0.25                      4.5k         5k\n-- a = 0.125                     7k           8k\n-- a = 0.0625                                 10k\n\n--   alpha             recovery samples   diff      log10  log diff\n--        1; 5         2                  ----      0.3    --------\n--      0.5; 7.3       5.3                3.3       0.72   0.42\n--     0.25; 12        9                  3.7       0.95   0.23\n--    0.125; 20        17                 8         1.23   0.27\n--   0.0625; 33        31                 14        1.49   0.26\n\n-- ref = 1.13 for 32k\n-- for 1000, log 10\n--sim = let ref = 1.05 :: UFixed 2 10\n--          window = 7 :: Unsigned 5\n--          alpha = 2.0 :: UFixed 1 6\n--          fLog = Clash.d6\n--          fGain = Clash.d6\n--          out_gain = Clash.simulate @System (uncurry (digiAgcMult (pure window) (pure ref) (pure alpha)). unbundle) simInput\n--      in map (zip [1..]) [\n--                           map (fromIntegral . (\\(_,x,_)->x)) out_gain\n--                         , map (fromIntegral . (\\(_,_,x)->x)) out_gain\n--                         , map (ufToDouble   . (\\(x,_,_)->x)) out_gain\n--                         ]\n\n{-\nJust thinking about sensible wordlengths for RFSoC...\n\nOur input is always 16 bits.\n\n==========\n\nThis will likely be after decimation, used inside the user's RX digital logic so we can expect deal with sampling rates well below the 4 GSamples/s... say probably a max of 512 MHz.\n\nHow many window bits are needed for a period of 1 ms?\n\n1e-3 * 512e6 = 18.9 ... let's just say 19\n\n==========\n\nFullscale signal after log will be...\n\nafter ID; we need (nWindow + nSig) bits (35!!!)\nafter log10; we need (1+log2 35) bits (9) and fLog fractional bits, let's say 9.fLog\nafter sub with ref; we need 10.fLog\nafter mul with alpha we need (10+ia).(fLog+fa)\n\n{ What should alpha's range be to allow a good selection of response times? }\n\nAfter the antilog, our wordlength increases exponentially! We should be super\ncareful about growing our wordlengths in the log domain.\n\n==========\n\nnSig = 16\nnWindow = 19\n-}\n\n-- Experimentally found recovery cycles for every tenth decimal step in alpha\n-- alphas = [0.1,0.2,...1.9]\nrecoveryCycles :: [(Int, Int)]\nrecoveryCycles = [(1,56),(2,40),(3,31),(4,26),(5,22),(6,19),(7,17),(8,15),(9,14),(10,13),(11,12),(12,11),(13,10),(14,10),(15,9),(16,8),(17,8),(18,7),(19,7)]\n\ngetRecoveryCycles :: Double -> Int\ngetRecoveryCycles = fromMaybe (error \"No entry found for that alpha\") . flip lookup recoveryCycles. round . (*10)\n\nnewtype InGain = InGain Double deriving Show\nnewtype InStepTime = InStepTime Int deriving Show\n\ninstance Arbitrary InStepTime where\n  arbitrary = fmap InStepTime $ choose (1000,10000)\n\ninstance Arbitrary InGain where\n  arbitrary = fmap (InGain . recip . fromIntegral) $ choose (1::Int,63)\n\nsteppedInput :: InGain -> InGain -> InStepTime -> [(Signed 16,Signed 16)]\nsteppedInput (InGain g1) (InGain g2) (InStepTime n) =\n  let a = map (\\(i,q)->(multD i g1, multD q g1)) . take n $ sinInputComplex 1 0.01\n      b = map (\\(i,q)->(multD i g2, multD q g2))           $ sinInputComplex 1 0.01\n  in a ++ b\n  where\n  multD s d = fromIntegral . round $ fromIntegral s * d\n\nsplitInto n [] = []\nsplitInto n xs = let (a,b) = splitAt n xs\n                 in a : splitInto n b\n\nisSteady :: Int -> Double -> Double -> [Double] -> Bool\nisSteady n ref percent = (<=n) . maximum . map length . filter (\\a->False == a!!0) . group . map (\\x->abs (x-ref)/ref < (percent/100))\n\nsimDfLogErr ref alpha xs =\n  simulate @System (\\x ->\n    bundle $ df (dfLogErr (pure ref) (pure alpha)) x (riseEvery (SNat :: SNat 3)) (pure True) )\n  (cycle xs) :: [(SFixed 4 22, Bool, Bool)]\n\n{--\n\n1) Can I reproduce the variation in simulation? Maybe generating a repeating pattern with a non-integer multiple of the window size\n\n2) Does this also appear in the floating point simulation, because that doesn't have the delays from cordic stuff.\n\nIf no to 1) maybe it's to do with my DataFlow implementation?\n\nI'm seeing spikes for 32 cycles in the output. Why is this?! We should only be seeing 512 sample changes because of the window of 2^9\n\n\nI've fixed it... Two things now:\n\n  1) Are the log10 and pow10 df units *really* returning consistient values?\n\n  2) We can add a feature to set the error state! We can use that in the python instead of feeding it extra samples. Is there anything else we should flush? Maybe just pad with 32ish samples. Wait. isn't that just the reset functionality that should already exist? I've just mapped the areset pin to axi reg 0, bit 1.\n\n--}\n\nsimOutPower g1 g2 n =\n  let ref = 4.0 :: UFixed 3 12\n      alpha = 1.0 :: UFixed 1 6\n      window = 9 :: Unsigned 5\n      --inputSig = take (10000 + rec_time*(2^window)) $ steppedInput g1 g2 n\n      inputSig = take (6000*5) $ steppedInput g1 g2 n\n      rec_time = (2+) . getRecoveryCycles $ ufToDouble alpha\n      --out_gain = take 15000 $ simAgc (fromIntegral window) (ufToDouble ref) (ufToDouble alpha) (map (\\(i,q)->(fromIntegral i, fromIntegral q)) inputSig)\n      --out_pow = map (\\(_,i,q)-> sqrt $ (i)**2 + (q)**2) out_gain\n      ip x =\n               let ip = df (testBufferDF (SNat :: SNat 6000) `seqDF` throttleDF (SNat :: SNat 4) `seqDF` dfAgc (pure window) (pure ref) (pure alpha) (pure True))\n                   oR = (riseEvery (SNat :: SNat 3))\n                   (y, oV, iR) = ip x (pure True) oR\n               in bundle (y, oV, oR) :: Signal System ((UFixed 10 15, (Signed 16, Signed 16)), Bool, Bool)\n      --outs = drop 1 . take (10000 + rec_time*(2^window))\n      outs = drop 1 . take 6000 . filter (\\(_,v,r)->v&&r)\n             $ simulate @System ip inputSig\n      out_gain = map (\\((g,(i,q)), v,r)->(g,i,q)) outs\n      out_pow = map (\\(_,i,q)-> sqrt $ (fromIntegral i)**2 + (fromIntegral q)**2) out_gain\n      out_pow_block = map ((/(2^window)) . sum) $ splitInto (2^window) out_pow\n      expected_pow = 10**(ufToDouble ref)\n  in (inputSig, out_gain, out_pow, out_pow_block, rec_time, expected_pow)\n\nprop_OutPower :: InGain -> InGain -> InStepTime -> Property\nprop_OutPower g1 g2 (InStepTime n) =\n  let (_, _, _, out_pow_block, rec_time, expected_pow) = simOutPower g1 g2 (InStepTime n)\n  in property . isSteady rec_time expected_pow 1 $ drop (ceiling $ (fromIntegral n) / 2**7) out_pow_block\n\nshowTest g1 g2 n =\n    renderToFile \"/tmp/clash/sim.html\" $ doctypehtml_ $ do\n    head_ $ do meta_ [charset_ \"utf-8\"]\n               plotlyCDN\n               reloadCDN\n               styleSheet\n    body_ $ do\n               toHtml $ plotly \"time_iq_in\" (traceTime simInputTrace)\n                          & layout . title ?~ \"Time domain I/Q Input\"\n               toHtml $ plotly \"time_iq_out\" (traceTime tData)\n                          & layout . title ?~ \"Time domain I/Q Output\"\n               toHtml $ plotly \"constl_iq_out\" (traceConstl tData)\n                          & layout . title ?~ \"Constellation I/Q\"\n                          & layout . width ?~ 600\n                          & layout . height ?~ 600\n               toHtml $ plotly \"time_iq_ctrl\" (traceTime ctrlData)\n                          & layout . title ?~ \"Time domain Control\"\n  where\n  (simInput, sim, out_pow, _, _, _) = simOutPower g1 g2 n\n  tData = map (zip [1..]) $ [map (\\(_,x,_)->fromIntegral x) sim\n                            ,map (\\(_,_,x)->fromIntegral x) sim\n                            ,map (\\(x,_,_)->ufToDouble x)   sim\n                            --[map (\\(_,x,_)-> x) sim\n                            --,map (\\(_,_,x)-> x) sim\n                            --,map (\\(x,_,_)->x)   sim\n                            ] :: [[(Double, Double)]]\n  ctrlData = [tData !! 2, tData !! 2]\n  simInputTrace = map (zip [(1::Double)..] . map (sfToDouble . sf (SNat :: SNat 0)))  [map fst simInput, map snd simInput]\n\ncorr :: [(Double, Double)] -> Double\ncorr = correlation . V.fromList\n\n--prop_corrTest g1 g2 n =\n--  let (_, outsig, _, _, recTime, _) = simOutPower g1 g2 n\n--      insig = steppedInput (InGain 0.3125) (InGain 0.3125) (InStepTime 0)\n--      inI  = map (fromIntegral . fst) insig\n--      inQ  = map (fromIntegral . snd) insig\n--      outI = map (fromIntegral . (\\(_,i,_)->i)) outsig\n--      outQ = map (fromIntegral . (\\(_,_,q)->q)) outsig\n--      correlation = corr $ zip (drop recTime inI) (drop recTime outI)\n--  in property $ correlation > 0.9\n\nbl10 n = fromIntegral . ceiling $ logBase 2 (logBase 10 (2**n))\nbe10 n = fromIntegral . ceiling $ logBase 2 (10 ** (2**n))\n\nbitsCalc :: Double -> Double -> Double -> (Double, Double) -> Double\n         -> (Double, (Double, Double), (Double, Double))\nbitsCalc window sig fLog (iAlpha, fAlpha) fGain =\n  let intgInternal = 2**window + sig\n      iLog = bl10 sig\n      iGain = be10 iLog - fGain\n  in (intgInternal, (iLog,fLog), (iGain, fGain))\n\nsinInput :: Double -> Double -> [Signed 16]\nsinInput fs dt = map (fromInteger . round . ((2**15-1) * ) .  sin . (2*pi*fs * )) [0.0, dt..]\n\nsinInputComplex :: Double -> Double -> [(Signed 16, Signed 16)]\nsinInputComplex fs dt = zip sins coss\n  where sins = map (fromInteger . round . ((2**15-1) * ) .  sin . (2*pi*fs * )) [0.0, dt..]\n        coss = map (fromInteger . round . ((2**15-1) * ) .  cos . (2*pi*fs * )) [0.0, dt..]\n\nreloadCDN :: Monad m => HtmlT m ()\nreloadCDN = script_ [src_ \"http://livejs.com/live.js\"] $ toHtml (\"\"::String)\n\nstyleSheet :: Monad m => HtmlT m ()\nstyleSheet = style_ [type_ \"text/css\" ] $\n             toHtml (\".svg-container {margin: 0 auto !important;}\"::String)\n\ntraceTime a =  [trace \"I\" $ a !! 0\n               ,trace \"Q\" $ a !! 1]\n  where trace label points = linePlot points\n                               & name ?~ label\n                               & (GPB.line ?~ (defLine & lineshape ?~ Hv))\n\ntraceConstl points = [scatterPlot $ zip (map snd (points!!0)) (map snd (points!!1))]\n\nstartServer = callCommand \"mkdir -p /tmp/clash; cd /tmp/clash/; python -m http.server > /dev/null 2>&1 &\"\n\nreturn []\nrunTests = $quickCheckAll\n\n{- TODO\n\nInclude bin files in IP make script\n\nTry find what resolution we need to increase in order to better recover very very low signals.\n\n-}\n", "meta": {"hexsha": "5eef7caff12ebd179bb1a1b3a618376765287de5", "size": 13769, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "ip/agc_digital/clash/Simulation.hs", "max_stars_repo_name": "dnorthcote/pynq_agc", "max_stars_repo_head_hexsha": "d83836787163b43beec74cb8d93396854786ad1e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-02-26T17:25:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T16:02:37.000Z", "max_issues_repo_path": "ip/agc_digital/clash/Simulation.hs", "max_issues_repo_name": "dnorthcote/pynq_agc", "max_issues_repo_head_hexsha": "d83836787163b43beec74cb8d93396854786ad1e", "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": "ip/agc_digital/clash/Simulation.hs", "max_forks_repo_name": "dnorthcote/pynq_agc", "max_forks_repo_head_hexsha": "d83836787163b43beec74cb8d93396854786ad1e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-20T10:45:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T11:20:38.000Z", "avg_line_length": 39.9101449275, "max_line_length": 317, "alphanum_fraction": 0.5899484349, "num_tokens": 4296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185318, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.4659948981728419}}
{"text": "{-# LANGUAGE ScopedTypeVariables, ConstraintKinds, GADTs #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE UndecidableInstances #-} -- See below\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports #-}\n{-# OPTIONS_GHC -fno-warn-unused-binds   #-}\n\n----------------------------------------------------------------------\n-- |\n-- Module      :  Generic.FFT\n-- Copyright   :  (c) 2013 Tabula, Inc.\n-- \n-- Maintainer  :  conal@tabula.com\n-- Stability   :  experimental\n-- \n-- FFT via functor composition. Apply to depth-typed perfect binary leaf trees.\n----------------------------------------------------------------------\nmodule Generic.FFT\n  ( dft\n  , idft\n  , dct\n  , HasFFT(..)\n  ) where\n\nimport Prelude hiding (sum)\n\nimport Control.Applicative (Applicative(..), liftA2)\nimport Control.Arrow ((***))\nimport Data.Foldable (Foldable, sum)\nimport Data.Functor ((<$>))\nimport Data.Monoid (Monoid(..), Sum(..), (<>))\nimport Data.Traversable (Traversable(..), mapAccumL)\n\nimport Data.Complex (Complex(..), conjugate, realPart)\nimport Data.Tuple (swap)\n\nimport Data.UniformPair\n\nimport TypeUnary.Nat\n\nimport qualified Data.FTree.BottomUp as B\nimport qualified Data.FTree.TopDown as T\n\n{--------------------------------------------------------------------\n    Misc\n--------------------------------------------------------------------}\ntype Unop a = a -> a\n\ntranspose :: (Traversable g, Applicative f) => g (f a) -> f (g a)\ntranspose = sequenceA\n\ninTranspose ::\n     (Traversable f, Traversable k, Applicative g, Applicative h)\n  => (g (f a) -> k (h b))\n  -> (f (g a) -> h (k b))\ninTranspose = transpose --> transpose\n\ninfixr 1 -->\n\n-- | Add pre- and post processing\n(-->) :: (a' -> a) -> (b -> b') -> ((a -> b) -> (a' -> b'))\n(f --> h) g = h . g . f\n\ntype R = Double\ntype C = Complex R\n\nscanL :: (Traversable f, Monoid a) => (a, f a) -> (f a, a)\nscanL (a0, as) = swap (mapAccumL h a0 as)\n  where\n    h a a' = (a <> a', a)\n\n-- TODO: Replace scanL with my efficient parallel version.\n-- Prefix (left) sums\nsumsL :: (Traversable f, Num a) => (a, f a) -> (f a, a)\nsumsL = (fmap getSum *** getSum) . scanL . (Sum *** fmap Sum)\n\n-- Yield a structure counting from 0 to size-1, together with size\ncounts ::\n     forall f a. (TA f, Num a)\n  => (f a, a)\ncounts = sumsL (0, pure 1)\n\n-- Cross product of structures\ncross :: (Functor g, Functor f) => g a -> f b -> g (f (a, b))\nas `cross` bs = fmap (\\a -> fmap (a, ) bs) as\n\n-- All products of numbers from each structure.\nproducts :: (Functor g, Functor f, Num n) => g n -> f n -> g (f n)\nproducts = (fmap . fmap . fmap . fmap) (uncurry (*)) cross\n\n-- as `products` bs = (fmap.fmap) (uncurry (*)) (as `cross` bs)\n-- as `products` bs = fmap (\\ a -> fmap (\\ b -> a*b) bs) as\n-- Dot product of structures. Assumes a trie-like f, so that the Applicative\n-- instance combines corresponding elements. Perhaps replace Applicative with a\n-- more suitable constraint.\ndot :: (Applicative f, Foldable f, Num a) => f a -> f a -> a\nu `dot` v = sum (liftA2 (*) u v)\n\ni2pi :: C\ni2pi = 0 :+ 2 * pi\n\n-- Principle nth root of unity with negated angle\nuroot :: Int -> C\nuroot n = exp (-i2pi / fromIntegral n)\n\n{--------------------------------------------------------------------\n    Unoptimized discrete Fourier transform (DFT)\n--------------------------------------------------------------------}\n-- Discrete Fourier transform:\n-- $X_k = \\sum_{n=0}^{N-1} x_n e^{-i 2\\pi k \\frac{n}{N}}$ for $k = 0,\\ldots,N$.\ndft :: TA f => Unop (f C)\ndft xs = (xs `dot`) <$> rootses\n\nidft ::\n     forall f. TA f\n  => Unop (f C)\nidft = fmap ((/ fromIntegral n) . conjugate) . dft . fmap conjugate\n  where\n    n :: Int\n    indices :: f Int\n    (indices, n) = counts\n\n-- Inefficinet; doesn't exploit symmetry, but a starting point for testing\ndct :: TA f => Unop (f R)\ndct = fmap realPart . dft . fmap (:+ 0)\n\n-- Powers of 'uroot' needed in the DFT:\n-- $e^{\\frac{-i 2\\pi k n}{N}}$ for $k,n = 0,\\ldots,N$:\nrootses ::\n     forall f. TA f\n  => f (f C)\nrootses = rootCross tot indices indices\n  where\n    indices :: f Int\n    (indices, tot) = counts\n\nrootCross :: (Functor g, Functor f, Integral n) => Int -> g n -> f n -> g (f C)\nrootCross tot = (fmap . fmap . fmap . fmap) (uroot tot ^) products\n\n-- rootCross tot is js = (fmap.fmap) (uroot tot ^) (is `products` js)\n{--------------------------------------------------------------------\n    FFT\n--------------------------------------------------------------------}\n-- | FFT computation, parametrized by structure\nclass HasFFT f f' | f -> f' where\n  fft :: f C -> f' C\n\n-- Constraint shorthands\ntype TA f = (Traversable f, Applicative f)\n\ntype TAH f f' = (TA f, TA f', HasFFT f f')\n\n-- Binary butterfly.\ninstance HasFFT Pair Pair where\n  fft (a :# b) = a + b :# a - b\n\n-- Decimation in time (DIT)\ninstance (TAH f f', IsNat n) => HasFFT (B.T f n) (T.T f' n) where\n  fft (B.L a) = T.L a\n  fft (B.B t) = T.B (fftC t)\n\n-- Decimation in frequency (DIF)? I'm unsure.\ninstance (TAH f f', IsNat n) => HasFFT (T.T f n) (B.T f' n) where\n  fft (T.L a) = B.L a\n  fft (T.B t) = B.B (fftC t)\n\ninstance HasFFT [] [] where\n  fft = dft\n\n--     Variable s `f, f' occur more often than in the instance head\n--       in the constraint: TAH f\n--     (Use -XUndecidableInstances to permit this)\n--     In the instance declaration for `HasFFT (T f n)'\n-- \n-- This warning vanishes when we spell out TAH. Hm.\n-- I'd prefer terser definitions like `fft = T.inT' T.l (T.B . fftC)`, but I\n-- haven't found a type for `inT'` that GHC likes.\nfftsT :: (Applicative f, Traversable g, HasFFT g g') => g (f C) -> f (g' C)\nfftsT = fmap fft . transpose\n\n-- FFT of composed functors\nfftC :: (TAH f f', TAH g g') => g (f C) -> f' (g' C)\nfftC = transpose . fftsT . twiddle . fftsT\n\n{-\n\n--   fftsT     :: g  (f  C) -> f  (g' C)\n--   twiddle   :: f  (g' C) -> f  (g' C)\n--   fftsT     :: f  (g' C) -> g' (f' C)\n--   transpose :: g' (f' C) -> f' (g' C)\n\n-}\n-- Multiply by twiddle factors\ntwiddle ::\n     forall f g. (TA f, TA g)\n  => Unop (g (f C))\ntwiddle = (liftA2 . liftA2) (*) rootses'\n  where\n    rootses' = rootCross (gTot * fTot) gIndices fIndices\n      where\n        fIndices :: f Int\n        (fIndices, fTot) = counts\n        gIndices :: g Int\n        (gIndices, gTot) = counts\n\n{--------------------------------------------------------------------\n    Experimental variation\n--------------------------------------------------------------------}\n-- This version is a better fit with\n-- <https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#General_factorizations>\n-- FFT of composed functors\nfftC' :: (TAH f f', TAH g g') => g (f C) -> f' (g' C)\nfftC' = fftsT' . transpose . twiddle . fftsT'\n  where\n    fftsT' :: (TA h, TAH k k') => k (h C) -> k' (h C)\n    fftsT' = (inTranspose . fmap) fft\n\n-- Hm. This definition differs from the previous one, since `twiddle` and\n-- `transpose` got swapped. I doubt they're equivalent.\n-- Types in the fftC' definition (right to left):\n--\n--   fftsT'    :: g  (f  C) -> g' (f  C)\n--   twiddle   :: g' (f  C) -> g' (f  C)\n--   transpose :: g' (f  C) -> f  (g' C)\n--   fftsT'    :: f  (g' C) -> g' (g' C)\n{--------------------------------------------------------------------\n    Tests\n--------------------------------------------------------------------}\n-- {1, 0, 0, 0, ...} <=DFT=> {1, 1, 1, 1, ...}\\ \n-- {1, -1, 1, -1, 1, -1, ...} <=DFT=> {0, 0, ... , N, 0, 0, ...} (where the 'N' occurs at the N/2 position in the output vector.\n-- dft . idft ~= id\n-- TODO :: show some example outputs and add a series of Quickcheck tests to\n-- validate them.\n-- TODO: make B / Pair showable\n\n_p1 :: Pair C\n_p1 = 1 :# 0\n\n_t1 :: B.T Pair N3 C\n_t1 = B.B (B.B (B.B (B.L (((1 :# 0) :# (0 :# 0)) :# ((0 :# 0) :# (0 :# 0))))))\n\n_t2 :: B.T Pair N4 C\n_t2 = pure 1\n\n_t3 :: B.T Pair N3 C\n_t3 = B.B (pure (1 :# -1))\n", "meta": {"hexsha": "6065649a4f2e2273bf444dbfaa542584e3ad9140", "size": 7802, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Generic/FFT.hs", "max_stars_repo_name": "jrp2014/generic-fft", "max_stars_repo_head_hexsha": "8a1cdeddd4e4c047f4649fffc1f5d2dd9fa8953d", "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/Generic/FFT.hs", "max_issues_repo_name": "jrp2014/generic-fft", "max_issues_repo_head_hexsha": "8a1cdeddd4e4c047f4649fffc1f5d2dd9fa8953d", "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/Generic/FFT.hs", "max_forks_repo_name": "jrp2014/generic-fft", "max_forks_repo_head_hexsha": "8a1cdeddd4e4c047f4649fffc1f5d2dd9fa8953d", "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.4596774194, "max_line_length": 128, "alphanum_fraction": 0.5261471418, "num_tokens": 2485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.46589698805337676}}
{"text": "{-# LANGUAGE ConstraintKinds #-}\n\nmodule HashedExpression.Internal.Expression\n  ( R,\n    C,\n    Covector,\n    ET (..),\n    Node (..),\n    Internal,\n    NodeID,\n    ExpressionMap,\n    Expression (..),\n    Scalar,\n    Dimension,\n    ToShape (..),\n    DimensionType,\n    ElementType,\n    NumType,\n    VectorSpace,\n    InnerProductSpace,\n    PowerOp (..),\n    PiecewiseOp (..),\n    VectorSpaceOp (..),\n    FTOp (..),\n    ComplexRealOp (..),\n    RotateOp (..),\n    Shape,\n    RotateAmount,\n    Arg,\n    Args,\n    BranchArg,\n    ConditionArg,\n    InnerProductSpaceOp (..),\n  )\nwhere\n\nimport Data.Array\nimport qualified Data.Complex as DC\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.Proxy (Proxy (..))\nimport Data.Typeable (Typeable, typeRep)\nimport GHC.TypeLits (KnownNat, Nat, natVal)\nimport Prelude hiding ((^))\n\n-- | Type representation of elements in the 1D, 2D, 3D, ... grid\ndata R\n  deriving (NumType, ElementType, Typeable)\n\ndata C\n  deriving (NumType, ElementType, Typeable)\n\ndata Covector\n  deriving (ElementType, Typeable)\n\n-- | Type representation of vector dimension\ndata Scalar\n  deriving (Dimension, Typeable)\n\n-- |\ninstance (KnownNat n) => Dimension n\n\ninstance (KnownNat m, KnownNat n) => Dimension '(m, n)\n\ninstance (KnownNat m, KnownNat n, KnownNat p) => Dimension '(m, n, p)\n\n-- | Classes as constraints\nclass ElementType et\n\nclass ElementType et => NumType et\n\n-------------------------------------------------------------------------------\nclass\n  (Dimension d) =>\n  ToShape d where\n  toShape :: Proxy d -> Shape\n\ninstance ToShape Scalar where\n  toShape _ = []\n\ninstance (KnownNat n) => ToShape n where\n  toShape _ = [nat @n]\n\ninstance (KnownNat m, KnownNat n) => ToShape '(m, n) where\n  toShape _ = [nat @m, nat @n]\n\ninstance (KnownNat m, KnownNat n, KnownNat p) => ToShape '(m, n, p) where\n  toShape _ = [nat @m, nat @n, nat @p]\n\ntype DimensionType d = (Dimension d, ToShape d)\n\n-------------------------------------------------------------------------------\n\n-- |\nnat :: forall n. (KnownNat n) => Int\nnat = fromIntegral $ natVal (Proxy :: Proxy n)\n\n-------------------------------------------------------------------------------\nclass Dimension d\n\nclass VectorSpace d et s\n\nclass VectorSpace d s s => InnerProductSpace d s\n\ninstance (DimensionType d, ElementType et) => VectorSpace d et R\n\ninstance (DimensionType d) => VectorSpace d C C\n\ninstance VectorSpace d s s => InnerProductSpace d s\n\n-- | Classes for operations so that both Expression and Pattern (in HashedPattern) can implement\nclass PowerOp a b | a -> b where\n  (^) :: a -> b -> a\n\nclass VectorSpaceOp a b where\n  scale :: a -> b -> b\n  (*.) :: a -> b -> b\n  (*.) = scale\n\nclass ComplexRealOp r c | r -> c, c -> r where\n  (+:) :: r -> r -> c\n  xRe :: c -> r\n  xIm :: c -> r\n\nclass InnerProductSpaceOp a b c | a b -> c where\n  (<.>) :: a -> b -> c\n\nclass RotateOp k a | a -> k where\n  rotate :: k -> a -> a\n\nclass PiecewiseOp a b where\n  piecewise :: [Double] -> a -> [b] -> b\n\nclass FTOp a b | a -> b where\n  ft :: a -> b\n\ninfixl 6 +:\n\ninfixl 8 *., `scale`, <.>\n\ninfixl 8 ^\n\n-- | Shape type:\n-- []        --> scalar\n-- [n]       --> 1D with size n\n-- [n, m]    --> 2D with size n \u00d7 m\n-- [n, m, p] --> 3D with size n \u00d7 m \u00d7 p\ntype Shape = [Int]\n\n-- | Args - list of indices of arguments in the ExpressionMap\ntype Args = [NodeID]\n\ntype Arg = NodeID\n\ntype ConditionArg = NodeID\n\ntype BranchArg = NodeID\n\n-- | Rotation in each dimension.\n-- | Property:  the length of this must match the dimension of the data\ntype RotateAmount = [Int]\n\n-- | Data representation of element type\ndata ET\n  = R\n  | C\n  | Covector\n  deriving (Show, Eq, Ord)\n\n-- | Internal\n-- Shape: Shape of the expression\n-- we can reconstruct the type of the Expression\ntype Internal = (Shape, Node)\n\n-- | Hash map of all subexpressions\ntype ExpressionMap = IntMap Internal\n\n-- | The index/key to look for the node on the hash table\ntype NodeID = Int\n\n-- | Expression with 2 phantom types (dimension and num type)\ndata Expression d et\n  = Expression\n      { exRootID :: Int, -- the index this expression\n        exMap :: ExpressionMap -- all subexpressions\n      }\n  deriving (Show, Eq, Ord, Typeable)\n\ntype role Expression nominal nominal -- So the users cannot use Data.Coerce.coerce to convert between expression types\n\n-- | Node type\ndata Node\n  = Var String\n  | DVar String -- only contained in **Expression d Covector (1-form)**\n  | Const Double -- only all elements the same\n      -- MARK: Basics\n  | Sum ET Args -- element-wise sum\n  | Mul ET Args -- multiply --> have different meanings (scale in vector space, multiplication, ...)\n  | Power Int Arg\n  | Neg ET Arg\n  | Scale ET Arg Arg\n  | -- MARK: only apply to R\n    Div Arg Arg -- TODO: Delete?\n  | Sqrt Arg\n  | Sin Arg\n  | Cos Arg\n  | Tan Arg\n  | Exp Arg\n  | Log Arg\n  | Sinh Arg\n  | Cosh Arg\n  | Tanh Arg\n  | Asin Arg\n  | Acos Arg\n  | Atan Arg\n  | Asinh Arg\n  | Acosh Arg\n  | Atanh Arg\n  | -- MARK: Complex related\n    RealImag Arg Arg -- from real and imagine\n  | RealPart Arg -- extract real part\n  | ImagPart Arg -- extract imaginary part\n      -- MARK: Inner product Space\n  | InnerProd ET Arg Arg\n  | -- MARK: Piecewise\n    Piecewise [Double] ConditionArg [BranchArg]\n  | Rotate RotateAmount Arg\n  | -- MARK: Discrete Fourier Transform\n    ReFT Arg\n  | ImFT Arg\n  | -- Need these inside because taking real of FT twice can be very fast\n    TwiceReFT Arg\n  | TwiceImFT Arg\n  deriving (Show, Eq, Ord)\n", "meta": {"hexsha": "9d045ebc3d1dd4f1401eb48606af043fc64ad09e", "size": 5447, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HashedExpression/Internal/Expression.hs", "max_stars_repo_name": "Turboscient/HashedExpression", "max_stars_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-30T00:10:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T21:31:19.000Z", "max_issues_repo_path": "src/HashedExpression/Internal/Expression.hs", "max_issues_repo_name": "Turboscient/HashedExpression", "max_issues_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-23T19:22:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-26T18:47:55.000Z", "max_forks_repo_path": "src/HashedExpression/Internal/Expression.hs", "max_forks_repo_name": "Turboscient/HashedExpression", "max_forks_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-05-25T00:27:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T00:37:36.000Z", "avg_line_length": 23.1787234043, "max_line_length": 118, "alphanum_fraction": 0.6163025519, "num_tokens": 1527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4658969829874885}}
{"text": "{-# LANGUAGE RecordWildCards #-}\nmodule Fish ( Fish (..)\n            , Loc\n            , FishKind\n            , Tolerance\n            , FishData\n            , move\n            ) where\nimport Data.Complex\nimport qualified Data.Map.Strict as M\n\nimport Consts\n\ntype Loc = Complex Double\ntype FishKind = Int\ntype Tolerance = Double\ntype FishData = M.Map (Int,Int) Tolerance\n\ndata Fish = Fish {_kind :: FishKind, _loc :: Loc} deriving (Eq, Show)\n\ndistSquare :: Fish -> Fish -> Double\ndistSquare (Fish {_loc=l0}) (Fish {_loc=l1}) =\n        sq (realPart l0 - realPart l1) + sq (imagPart l0 - imagPart l1)\n\nsq :: Num a => a -> a\nsq = (^ (2::Int))\n\ntolerance :: FishData -> Fish -> Fish -> Double\ntolerance d f0 f1 = d M.! (_kind f0, _kind f1)\n\ntooClose :: FishData -> Fish -> Fish -> Bool\ntooClose d f0 f1 = distSquare f0 f1 < tolerance d f0 f1\n\nmove :: FishData -> [Fish] -> [(Fish, Bool)]\nmove dat fs = map moveOne fs where\n    -- TODO : consider better implementation\n    force :: Fish -> Fish -> Loc\n    force f0 f1 = let\n        v = _loc f0 - _loc f1 in\n            (dt:+0) * ((tolerance dat f0 f1 :+ 0) - abs v) * signum v\n    moveOne :: Fish -> (Fish, Bool)\n    moveOne f@(Fish {..}) = let\n        neighbours = filter (/= f) . filter (tooClose dat f) $ fs\n        mean = (/ ((fromIntegral . length) neighbours :+ 0))\n        totalForce = mean . sum . map (force f) $ neighbours\n        in\n            (f {_loc = _loc + totalForce}, toEnum . signum $ length neighbours)\n", "meta": {"hexsha": "d8d22482b109c2c6be724b9fb4b34448f6d17cf0", "size": 1468, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Fish.hs", "max_stars_repo_name": "lesguillemets/fishpackin", "max_stars_repo_head_hexsha": "891b5bf4f6779b49ab60b0c0cace1e21949a4c2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Fish.hs", "max_issues_repo_name": "lesguillemets/fishpackin", "max_issues_repo_head_hexsha": "891b5bf4f6779b49ab60b0c0cace1e21949a4c2d", "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/Fish.hs", "max_forks_repo_name": "lesguillemets/fishpackin", "max_forks_repo_head_hexsha": "891b5bf4f6779b49ab60b0c0cace1e21949a4c2d", "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": 30.5833333333, "max_line_length": 79, "alphanum_fraction": 0.5803814714, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4656508017803069}}
{"text": "{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE TupleSections #-}\n\nmodule MLP.Types (\n   Pattern(..),\n   input,\n   output,\n   DataSet(..),\n   trainSet,\n   testSet,\n   Parameters(..),\n   topology,\n   learningRate,\n   decayLearningRate,\n   normalise,\n   epochs,\n   minErrorRate,\n   trainFile,\n   testFile,\n   verbose,\n   Topology(..),\n   numInputs,\n   hiddenLayers,\n   numOutputs,\n   topoFold,\n   dataSet,\n   params,\n   State(..),\n   network,\n   curEpoch,\n   curError,\n   App(..),\n   zipWithPat,\n   MonadFileSystem(..)\n)  where\n\nimport Control.Lens (makeLenses, (^..), (^.), ix, folding, Fold)\nimport Data.Aeson (FromJSON(..), withObject, withArray, (.:), (.:?), (.!=))\nimport Numeric.LinearAlgebra.Data (Vector, Matrix, loadMatrix)\nimport Numeric.LinearAlgebra.Static (R, L, zipWithVector)\nimport Data.Aeson.Lens (key, values, _Integral)\nimport Data.Aeson.TH (deriveToJSON, defaultOptions, Options(..))\nimport Control.Monad (guard)\nimport Data.Maybe (fromMaybe)\nimport Control.Monad.State.Lazy (StateT(..), runStateT)\nimport Control.Monad.Writer.Lazy (Writer(..), runWriter)\nimport qualified Data.Text as T \nimport Data.Functor.Identity (Identity)\nimport Data.Text.Lazy.Encoding (encodeUtf8, decodeUtf8)\nimport qualified Data.ByteString.Lazy as B\nimport Control.Monad.Writer.Class (MonadWriter(..))\nimport Control.Monad.State.Class (MonadState(..))\nimport GHC.TypeLits ( KnownNat, Nat )\nimport MLP.Network (Net(..), AllCon, Learn(..), MLP(..))\nimport Data.Singletons (SingI(..))\nimport Numeric.Natural ( Natural )\nimport qualified Data.Text.IO as TIO (putStrLn)\n\ndata Pattern (i :: Nat) (o :: Nat) = Pattern {\n   _input :: R i,\n   _output :: R o\n} deriving Show\n\n-- rank 2 function\napply :: (forall n. R n -> R n -> R n) -> Pattern i o -> Pattern i o -> Pattern i o\napply f (Pattern in1 out1) (Pattern in2 out2) = Pattern (f in1 in2) (f out1 out2)\n\nzipWithPat :: (KnownNat i, KnownNat o) => (Double -> Double -> Double) -> Pattern i o -> Pattern i o -> Pattern i o\nzipWithPat f (Pattern i1 o1) (Pattern i2 o2) =\n   Pattern (zipWithVector f i1 i2) (zipWithVector f o1 o2)\n\ninstance Num (Pattern i o) where\n   (-) p1 p2 = apply (-) p1 p2\n   (+) p1 p2 = apply (+) p1 p2\n   (*) p1 p2 = apply (*) p1 p2\n   abs (Pattern inp out) = Pattern (abs inp) (abs out)\n   signum (Pattern inp out) = Pattern (signum inp) (signum out)\n   fromInteger num = Pattern (fromInteger num) (fromInteger num)\n\ninstance Fractional (Pattern i o) where\n   (/) p1 p2 = apply (/) p1 p2\n   recip (Pattern inp out) = Pattern (recip inp) (recip out)\n   fromRational rat = Pattern (fromRational rat) (fromRational rat)\n   \ndata DataSet i o = DataSet {\n   _trainSet :: [Pattern i o],\n   _testSet :: [Pattern i o]\n} deriving Show\n\ndata Topology = Topology {\n   _numInputs :: Natural,\n   _hiddenLayers :: [Natural],\n   _numOutputs :: Natural\n} deriving Show\n\ndata Parameters = Parameters {\n   _topology :: Topology,\n   _learningRate :: Double,\n   _decayLearningRate :: Bool,\n   _epochs :: Natural,\n   _minErrorRate :: Double,\n   _normalise :: Bool,\n   _trainFile :: FilePath,\n   _testFile :: FilePath,\n   _verbose :: Bool\n} deriving Show\n\ndata State i hs o = State {\n   _dataSet :: DataSet i o,\n   _params :: Parameters,\n   _network :: !(Net i hs o),\n   _curEpoch :: Natural,\n   _curError :: Double\n}\n\nmakeLenses ''Pattern\nmakeLenses ''DataSet\nmakeLenses ''Topology\n\ntopoFold :: Fold Topology Natural\ntopoFold = folding $ \\s -> (s ^. numInputs) : (s ^. hiddenLayers) ++ (s ^.. numOutputs)\n\nmakeLenses ''Parameters\nmakeLenses ''State\n\ntype Log = [T.Text]\n\nnewtype App (i :: Nat) (hs :: [Nat]) (o :: Nat) (a :: *) = App {\n   -- | this is an unpacked StateT (StateT i hs o) (Writer Log) a\n   runApp :: State i hs o -> ((a, State i hs o), Log)\n}\n\ninstance Functor (App i hs o) where\n   fmap f (App app) = \n      App $ \\s ->\n         let ((!a,!s'),!l) = app s\n            in ((f a,s'),l)\n\ninstance Applicative (App i hs o) where\n   pure a = App $ \\s -> ((a,s), mempty)\n\n   (App fab) <*> (App fa) =\n      App $ \\s ->\n         let ((!ab,!s'),!l) = fab s\n             ((a, s''), l') = fa s'\n            in ((ab a, s''), l <> l')\n\ninstance Monad (App i hs o) where\n   return = pure \n\n   (App ma) >>= amb =\n      App $ \\s ->\n         let ((!a, !s'), !l) = ma s\n             ((b, s''), l') = runApp (amb a) s'\n            in ((b, s''), l <> l')\n\ninstance MonadWriter Log (App i hs o) where\n   writer (!a, !l) = App $ \\s -> ((a,s),l)\n   tell !l = App $ \\s -> (((),s),l)\n   listen (App app) =\n      App $ \\s ->\n         let ((!a,!s''),!l) = app s \n            in (((a,l),s''),l)\n\n   pass (App app) = \n      App $ \\s ->\n         let (((!a,!f),!s'),!l) = app s \n            in ((a,s'),l)\n\ninstance MonadState (State i hs o) (App i hs o) where\n   get = App $ \\s -> ((s,s),mempty)\n   put s = App . const $ (((), s), mempty)\n   state app = App ((,mempty).app)\n\nclass (Monad m, MonadFail m) => MonadFileSystem m where\n   readFileM :: FilePath -> m B.ByteString\n   readMatrixM :: FilePath -> m (Matrix Double)\n   printText :: T.Text -> m ()\n\ninstance MonadFileSystem IO where\n   readFileM fl = B.readFile fl\n   readMatrixM = loadMatrix\n   printText = TIO.putStrLn\n\n$(deriveToJSON defaultOptions{fieldLabelModifier=drop 1} ''Topology)\n$(deriveToJSON defaultOptions{fieldLabelModifier=drop 1} ''Parameters)\n\ninstance FromJSON Topology where\n   parseJSON = withObject \"Topology\" (\\o -> do\n      inputs <- o .: \"numInputs\"\n      guard (inputs > 0)\n\n      outputs <- o .: \"numOutputs\"\n      guard (outputs > 0)\n\n      let hidden =  o ^.. ix \"hiddenLayers\".values._Integral\n\n      return $ Topology inputs hidden outputs)\n\ninstance FromJSON Parameters where\n   parseJSON = withObject \"Parameters\" (\\o -> do\n      _topology <- o .: \"topology\" \n      _learningRate <- o .:? \"learningRate\" .!= 0.6\n      _decayLearningRate <- o .:? \"decayLearningRate\" .!= False\n      _normalise <- o .:? \"normalise\" .!= False\n      _epochs <- o .:? \"epochs\" .!= 1000\n      _minErrorRate <- o .: \"minErrorRate\"\n      _trainFile <- o .: \"trainFile\"\n      _testFile <- o .: \"testFile\"\n\n      _verbose <- o .:? \"verbose\" .!= False\n\n      return $ Parameters {..})", "meta": {"hexsha": "205a6b0515e6c23fd4bf9c551f098610b9be07d7", "size": 6599, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MLP/Types.hs", "max_stars_repo_name": "ovanr/Typed-MLP", "max_stars_repo_head_hexsha": "c6cf0d5295048f0aa4bfe9b4628ccb59cb92b80c", "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/MLP/Types.hs", "max_issues_repo_name": "ovanr/Typed-MLP", "max_issues_repo_head_hexsha": "c6cf0d5295048f0aa4bfe9b4628ccb59cb92b80c", "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/MLP/Types.hs", "max_forks_repo_name": "ovanr/Typed-MLP", "max_forks_repo_head_hexsha": "c6cf0d5295048f0aa4bfe9b4628ccb59cb92b80c", "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.8165938865, "max_line_length": 115, "alphanum_fraction": 0.6158508865, "num_tokens": 1916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.46564842418040886}}
{"text": "{-|\nModule      : Data.Meta.Multiarm\nDescription : Matrix function for graphs\nCopyright   : (c) Thodoris Papakonstantinou, 2019\nLicense     : GPL-3\nMaintainer  : mail@tpapak.com\nStability   : experimental\nPortability : POSIX\n\n-}\n\nmodule Data.Meta.Matrices\n  ( createBMatrix\n  , createAMatrix\n  , createCMatrix\n  )\nwhere\n\nimport           Control.Applicative\nimport           Data.List\nimport qualified Data.Map.Strict               as Map\nimport qualified Data.Set                      as Set\nimport           Data.Maybe\nimport           Data.Either\nimport           Data.Meta.Effects\nimport qualified Numeric.LinearAlgebra         as LA\nimport qualified Numeric.LinearAlgebra.Devel   as LAD\nimport qualified Data.Graph.AdjacencyList      as G\nimport qualified Data.Graph.AdjacencyList.BFS      as BFS\n\n-- | create the edge vertex adjacency matrix given a graph\ncreateBMatrix :: G.Graph -> LA.Matrix Double\ncreateBMatrix g =\n  let vs  = G.vertices g\n      nvs = length vs\n      es  = G.edges g\n      nes = length es\n      rowfromEdge e =\n          let\n            (u, v) = G.toTuple e\n            r      = LA.fromList $ replicate nvs 0.0 :: LA.Vector Double\n            r' =\n              LAD.mapVectorWithIndex\n                (\\i _ ->\n                  if i == u - 1 then 1.0 else if i == v - 1 then (-1.0) else 0.0\n                )\n                r :: LA.Vector Double\n          in\n            r'\n      rows = map rowfromEdge es\n      b    = LA.fromRows rows\n  in  b\n\ncreateAMatrix :: G.Graph -> LA.Matrix Double\ncreateAMatrix g =\n  let vs  = G.vertices g\n      nvs = length vs\n      es  = G.edges g\n      nes = length es\n      rowfromEdge e =\n          let\n            (u, v) = G.toTuple e\n            r      = LA.fromList $ replicate (nvs - 1) 0.0 :: LA.Vector Double\n            r' =\n              LAD.mapVectorWithIndex\n                (\\i _ ->\n                  if i == u - 2 then 1.0 else if i == v - 2 then (-1.0) else 0.0\n                )\n                r :: LA.Vector Double\n           in r'\n      rows = map rowfromEdge es\n      a    = LA.fromRows rows\n  in  a\n\n-- | create the Vertex Edge adjacency matrix given a graph\n\n-- | create the Vertex Edge adjacency matrix given a graph\ncreateCMatrix :: G.Graph -> LA.Matrix Double\ncreateCMatrix g =\n  let vs  = G.vertices g\n      nvs = length vs\n      es  = G.edges g\n      nes = length es\n      rowfromVertex v =\n        let r = map (\\e -> \n              let (u, v') = G.toTuple e\n                  fillcell x | x==u = (-1.0)\n                  fillcell x | x==v' = (1.0)\n                  fillcell _ = (0.0)\n               in  fillcell v\n                  ) es\n         in LA.fromList $ r :: LA.Vector Double\n      rows = map rowfromVertex vs\n      c    = LA.fromRows rows\n  in  c\n\n-- | create the Vertex Edge adjacency matrix given a graph\ncreateXMatrix :: G.Graph -> LA.Matrix Double\ncreateXMatrix g =\n  let vs  = G.vertices g\n      nvs = length vs\n      es  = G.edges g\n      nes = length es\n      firstVertex = head vs\n      bfsNet = BFS.bfs g firstVertex\n      spanningtree = BFS.spanningTree bfsNet\n      rowfromVertex v =\n        let r = map (\\e -> \n              let (u, v') = G.toTuple e\n                  fillcell x | x==u = (-1.0)\n                  fillcell x | x==v' = (1.0)\n                  fillcell _ = (0.0)\n               in  fillcell v\n                  ) es\n         in LA.fromList $ r :: LA.Vector Double\n      rows = map rowfromVertex vs\n      c    = LA.fromRows rows\n  in  c\n", "meta": {"hexsha": "9e84ad8af07d24ca64d37d65b853a58a41d4a2c5", "size": 3460, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Meta/Matrices.hs", "max_stars_repo_name": "tpapak/meta-analysis", "max_stars_repo_head_hexsha": "e03bc51a20584f9d52f6ed81c7d34e731f793641", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/Meta/Matrices.hs", "max_issues_repo_name": "tpapak/meta-analysis", "max_issues_repo_head_hexsha": "e03bc51a20584f9d52f6ed81c7d34e731f793641", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/Meta/Matrices.hs", "max_forks_repo_name": "tpapak/meta-analysis", "max_forks_repo_head_hexsha": "e03bc51a20584f9d52f6ed81c7d34e731f793641", "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.0756302521, "max_line_length": 80, "alphanum_fraction": 0.5309248555, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4655347063946306}}
{"text": "module Eris.Predict.KNNbased where\n\nimport Data.HashMap.Strict as Map\nimport Data.Maybe (isNothing, isJust, fromJust)\nimport Control.Monad (guard)\nimport qualified Numeric.LinearAlgebra as NL\n\nimport Eris.Meta.DataStructure\nimport Eris.Compute.Similarity\n\n-- | Example:\n-- records2eCount :  get ecount\n-- pairWiseSimilarity : get similarity Matrix\n-- neighborOf : get neighbor of a entity  A\n-- f1 : filter neighbors of A which related to entity of the other type .\n-- c1 : retrive relation between two type of entity.\n-- t : compute knnbased recommendataion.\nt :: NeighborRank -> NeighborSimilarity-> Maybe Rank\nt nr ns\n    | length ns /= length nr = Nothing\n    | otherwise = Just $ knnbased  ns nr\n    where knnbased ns nr =  let\n                              v1 = NL.vector $ fmap snd ns\n                              v2 = NL.vector $ fmap snd nr\n                            in  v1 NL.<.> v2 / NL.norm_1 v1\n\n\nf1 :: PID -> ECount -> NeighborSimilarity -> NeighborSimilarity\nf1 pid ecount nsim = do\n    r@(eid,_) <- nsim\n    guard $ validRecord ecount eid pid\n    return r\n\nc1 :: PID -> ECount -> NeighborSimilarity -> NeighborRank\nc1 pid ecount nsim =do\n                    (eid, _) <- nsim\n                    let justRank = getRank ecount eid pid\n                    guard $ isJust justRank\n                    return (eid, fromJust justRank)\n\n-- | Given an ID of a entity of certain type.\n--  Based on the similairty matrix of this type of entity.\n--  collect its neighbors and sort by Order.\n--  return a list of tuple [(EID, Rank)] , rank value is necessary in case any further filter or verification process.\nneighborOf :: Order -> CID -> SimilarityMatrix -> NeighborSimilarity\nneighborOf ord cus matrix\n  | isNothing (Map.lookup cus matrix) = []\n  | otherwise = let\n      rlist = Map.toList matrix\n      neighborsRank = collectRank rlist cus\n      in sortByRank neighborsRank ord\n  where\n        collectRank :: [(EID, Map.HashMap EID Rank)] -> EID -> NeighborSimilarity\n        collectRank ((eid,edict) : exs) tid\n            | eid == tid = Map.toList edict\n            | otherwise = (eid,Map.lookupDefault 0 tid edict): collectRank exs tid\n        sortByRank :: NeighborSimilarity -> Order -> NeighborSimilarity\n        sortByRank nr o = let\n            ascOrder = quickSortRank nr\n            in if o == Desc\n               then\n                 reverse ascOrder\n                else\n                  ascOrder\n        quickSortRank :: NeighborSimilarity -> NeighborSimilarity\n        quickSortRank [] = []\n        quickSortRank ((eid,erank):ers) =\n            let smallRanks = quickSortRank [e | e <- ers , snd e <= erank]\n                biggerRanks = quickSortRank [ e | e<- ers, snd e > erank]\n            in smallRanks ++ [(eid,erank)] ++ biggerRanks\n\n-- | Auxiliary Functions\nvalidRecord :: ECount -> CID -> PID -> Bool\nvalidRecord ec c p=\n        let cContainsP = do\n                          pdict <- Map.lookup c ec\n                          Map.lookup p pdict\n        in isJust cContainsP\n\ngetRank :: ECount -> CID -> PID -> Maybe Rank\ngetRank ec c p = do\n    pdict <- Map.lookup c ec\n    Map.lookup p pdict\n", "meta": {"hexsha": "bbb1cc186ddb5f546eb54cfddb2fba5d033ffad2", "size": 3130, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Eris/Predict/KNNbased.hs", "max_stars_repo_name": "emmettng/eris", "max_stars_repo_head_hexsha": "15f10774898f2d5d636641156b8c512f2b5a0006", "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/Eris/Predict/KNNbased.hs", "max_issues_repo_name": "emmettng/eris", "max_issues_repo_head_hexsha": "15f10774898f2d5d636641156b8c512f2b5a0006", "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/Eris/Predict/KNNbased.hs", "max_forks_repo_name": "emmettng/eris", "max_forks_repo_head_hexsha": "15f10774898f2d5d636641156b8c512f2b5a0006", "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.2619047619, "max_line_length": 118, "alphanum_fraction": 0.6130990415, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839876, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46544472994322555}}
{"text": "-- This separation exists due to the GHC stage restriction of TH\n\n{-# LANGUAGE TemplateHaskell #-}\n\n{-# OPTIONS_GHC -ddump-splices #-}\n\nmodule Deep.ExampleMain where\n\nimport Deep.Example\n\nimport Data.Complex\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n  print $(thExample1)\n  print ($(thExample2) :: Int)\n  print $(thExample3)\n  print ($(thExample4) :: Int)\n  print $(thExample5)\n  print (thExample6 8)\n  print (thExample6 7)\n  print $(thExample7)\n  print (thExample9 (IntPair 4 1))\n\n  putStrLn \"mandelbrot:\"\n\n  print (mandelbrot_nextZ (1 :+ 1, 0))\n\n  print (mandelbrot_point ((-1) :+ 0))\n  print (mandelbrot_point (1 :+ 0))\n  print (mandelbrot_point (0 :+ 0))\n\n  putStrLn mandelbrotTestAscii\n\n  print (shouldFail (3 :+ 0))\n\n\n  -- print thExample6\n  -- print ($(thExample6) 3)\n\n\nmandelbrotTestAscii :: String\nmandelbrotTestAscii =\n  unlines\n    (map go [0..mandelbrot_height-1])\n  where\n    go y = map (go2 y) [0..mandelbrot_width-1]\n\n    go2 y x =\n      case mandelbrot_point (mandelbrot_toCoord x y) of\n        Just _ -> ' '\n        Nothing -> '*'\n    \n\nmandelbrot_toCoord :: Int -> Int -> Complex Double\nmandelbrot_toCoord x0 y0 =\n    (mandelbrot_xMin + x * mandelbrot_xIncr) :+ (mandelbrot_yMin + y * mandelbrot_yIncr)\n  where\n    x, y :: Double\n    x = fromIntegral x0\n    y = fromIntegral y0\n\nmandelbrot_xIncr :: Double\nmandelbrot_xIncr = (mandelbrot_xMax - mandelbrot_xMin) / (fromIntegral mandelbrot_width - 1)\n\nmandelbrot_yIncr :: Double\nmandelbrot_yIncr = (mandelbrot_yMax - mandelbrot_yMin) / (fromIntegral mandelbrot_height - 1)\n\nmandelbrot_xMin :: Double\nmandelbrot_xMin = -2.5\n\nmandelbrot_xMax :: Double\nmandelbrot_xMax = 1\n\nmandelbrot_yMin :: Double\nmandelbrot_yMin = -1.5\n\nmandelbrot_yMax :: Double\nmandelbrot_yMax = 1\n\nmandelbrot_width :: Int\nmandelbrot_width = 200\n\nmandelbrot_height :: Int\nmandelbrot_height = 40\n\n", "meta": {"hexsha": "fe3001144d0a4202c58ab862928d96237913aa76", "size": 1835, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Deep/ExampleMain.hs", "max_stars_repo_name": "roboguy13/gpu-embed", "max_stars_repo_head_hexsha": "e04cddfcd972dc8087e2621137a1619021eab0eb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-27T03:47:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-27T03:47:16.000Z", "max_issues_repo_path": "src/Deep/ExampleMain.hs", "max_issues_repo_name": "roboguy13/gpu-embed", "max_issues_repo_head_hexsha": "e04cddfcd972dc8087e2621137a1619021eab0eb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Deep/ExampleMain.hs", "max_forks_repo_name": "roboguy13/gpu-embed", "max_forks_repo_head_hexsha": "e04cddfcd972dc8087e2621137a1619021eab0eb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8522727273, "max_line_length": 93, "alphanum_fraction": 0.6975476839, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.46529126668215454}}
{"text": "{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE ConstraintKinds       #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedLabels      #-}\n{-# LANGUAGE OverloadedStrings     #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE UndecidableInstances  #-}\n\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-|\nModule      : Grenade.Layers.Convolution\nMaintainter : Theo Charalambous\nDescription : Convolution layer with support for padding and bias\n\nConvolutions with and without biases are supported, allowing for faster\nimplementation when we know there is no bias.\n-}\n\nmodule Grenade.Layers.Convolution where\n\nimport           Data.Function                       ((&))\nimport           Data.Kind                           (Type)\nimport           Data.List                           (foldl1')\nimport           Data.Maybe\nimport           Data.Proxy\nimport           Data.Serialize\nimport           Data.Singletons.TypeLits            hiding (natVal)\nimport           GHC.TypeLits\nimport           Control.DeepSeq\nimport           Lens.Micro                          ((^.))\n\nimport           Numeric.LinearAlgebra               hiding (R, konst,\n                                                      uniformSample)\nimport qualified Numeric.LinearAlgebra               as LA\nimport           Numeric.LinearAlgebra.Static        hiding (build, toRows, (&),\n                                                      (|||), size)\n\nimport           Grenade.Core\nimport           Grenade.Layers.Internal.Convolution\nimport           Grenade.Layers.Internal.Update\nimport           Grenade.Onnx\nimport           Grenade.Utils.LinearAlgebra\nimport           Grenade.Utils.ListStore\n\ntype OutputShapeIsOkay (input :: Nat) (pad :: Nat) (kernel :: Nat) (strides :: Nat) (output :: Nat)\n  = ( strides * (output - 1) <= (input - kernel + pad)\n    , (input - kernel + pad) <= (output * strides ) - 1 )\n\ndata HasBias = WithBias | WithoutBias\n\ndata ConvPadding = NoPadding | SameUpper | SameLower | Padding Nat Nat Nat Nat\n\ndata Convolution :: HasBias\n                 -> ConvPadding\n                 -> Nat -- Number of channels, for the first layer this could be RGB for instance.\n                 -> Nat -- Number of filters, this is the number of channels output by the layer.\n                 -> Nat -- The number of rows in the kernel filter\n                 -> Nat -- The number of column in the kernel filter\n                 -> Nat -- The row stride of the convolution filter\n                 -> Nat -- The columns stride of the convolution filter\n                 -> Type where\n  Convolution :: ( KnownNat channels\n                 , KnownNat filters\n                 , KnownNat kernelRows\n                 , KnownNat kernelColumns\n                 , KnownNat strideRows\n                 , KnownNat strideColumns\n                 , KnownNat kernelFlattened\n                 , kernelFlattened ~ (kernelRows * kernelColumns * channels))\n              => !(L kernelFlattened filters) -- The kernel filter weights\n              -> !(ListStore (L kernelFlattened filters)) -- The last kernel update (or momentum)\n              -> Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns\n\n  BiasConvolution :: ( KnownNat channels\n                     , KnownNat filters\n                     , KnownNat kernelRows\n                     , KnownNat kernelColumns\n                     , KnownNat strideRows\n                     , KnownNat strideColumns\n                     , KnownNat kernelFlattened\n                     , kernelFlattened ~ (kernelRows * kernelColumns * channels))\n                  => !(L kernelFlattened filters) -- The kernel filter weights\n                  -> !(R filters) -- The bias weights\n                  -> !(ListStore (L kernelFlattened filters)) -- The last kernel update (or momentum)\n                  -> Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns\n\ndata Convolution' :: HasBias\n                  -> ConvPadding\n                  -> Nat -- Number of channels, for the first layer this could be RGB for instance.\n                  -> Nat -- Number of filters, this is the number of channels output by the layer.\n                  -> Nat -- The number of rows in the kernel filter\n                  -> Nat -- The number of column in the kernel filter\n                  -> Nat -- The row stride of the convolution filter\n                  -> Nat -- The columns stride of the convolution filter\n                  -> Type where\n  Convolution' :: ( KnownNat channels\n                  , KnownNat filters\n                  , KnownNat kernelRows\n                  , KnownNat kernelColumns\n                  , KnownNat strideRows\n                  , KnownNat strideColumns\n                  , KnownNat kernelFlattened\n                  , kernelFlattened ~ (kernelRows * kernelColumns * channels))\n               => !(L kernelFlattened filters) -- The kernel filter weights\n               -> Convolution' 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns\n\n  BiasConvolution' :: ( KnownNat channels\n                      , KnownNat filters\n                      , KnownNat kernelRows\n                      , KnownNat kernelColumns\n                      , KnownNat strideRows\n                      , KnownNat strideColumns\n                      , KnownNat kernelFlattened\n                      , kernelFlattened ~ (kernelRows * kernelColumns * channels))\n                   => !(L kernelFlattened filters) -- The kernel filter weights\n                   -> !(R filters) -- The bias weights\n                   -> Convolution' 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns\n\n{---------------------------}\n{--    Layer instances    --}\n{---------------------------}\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat ((kernelRows * kernelColumns) * channels)\n         , KnownNat (filters * ((kernelRows * kernelColumns) * channels))\n         ) => RandomLayer (Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns) where\n  createRandomWith m gen = do\n    wN <- getRandomMatrix i i m gen\n    wB <- getRandomVector i i m gen\n    return $ BiasConvolution wN wB mkListStore\n    where\n      i = natVal (Proxy :: Proxy ((kernelRows * kernelColumns) * channels))\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat ((kernelRows * kernelColumns) * channels)\n         , KnownNat (filters * ((kernelRows * kernelColumns) * channels))\n         ) => RandomLayer (Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns) where\n  createRandomWith m gen = do\n    wN <- getRandomMatrix i i m gen\n    return $ Convolution wN mkListStore\n    where\n      i = natVal (Proxy :: Proxy ((kernelRows * kernelColumns) * channels))\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * channels)\n         , kernelFlattened ~ (kernelRows * kernelColumns * channels)\n         ) => UpdateLayer (Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns) where\n  type Gradient (Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns) = (Convolution' 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns)\n\n  type MomentumStore (Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns)  = ListStore (L (kernelRows * kernelColumns * channels) filters)\n\n  runUpdate opt@OptSGD{} x@(Convolution oldKernel store) (Convolution' kernelGradient) =\n    let  momentum = getData opt x store\n         result = descendMatrix opt (MatrixValuesSGD oldKernel kernelGradient momentum)\n         newStore = setData opt x store (matrixMomentum result)\n    in Convolution (matrixActivations result) newStore\n  runUpdate opt@OptAdam{} x@(Convolution oldKernel store) (Convolution' kernelGradient) =\n    let (m, v) = toTuple $ getData opt x store\n        result = descendMatrix opt (MatrixValuesAdam (getStep store) oldKernel kernelGradient m v)\n        newStore = setData opt x store [matrixM result, matrixV result]\n    in Convolution (matrixActivations result) newStore\n    where toTuple [m ,v] = (m, v)\n          toTuple xs = error $ \"unexpected input of length \" ++ show (length xs) ++ \"in toTuple in Convolution.hs\"\n\n  reduceGradient grads = Convolution' $ dmmap (/ (fromIntegral $ length grads)) (foldl1' add (map (\\(Convolution' x) -> x) grads))\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * channels)\n         , kernelFlattened ~ (kernelRows * kernelColumns * channels)\n         ) => UpdateLayer (Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns) where\n  type Gradient (Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns) = (Convolution' 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns)\n\n  type MomentumStore (Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns)  = ListStore (L (kernelRows * kernelColumns * channels) filters)\n\n  runUpdate      = undefined\n  reduceGradient = undefined\n\n\n{-----------------------------------}\n{--    No Bias Layer instances    --}\n{-----------------------------------}\n\n-- | A three dimensional image (or 2d with many channels) can have\n--   an appropriately sized convolution filter run across it.\n--   Case without bias vector.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , KnownNat channels\n         , OutputShapeIsOkay inputRows 0 kernelRows strideRows outputRows\n         , OutputShapeIsOkay inputCols 0 kernelCols strideCols outputCols\n         ) => Layer (Convolution 'WithoutBias 'NoPadding channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) where\n\n  type Tape (Convolution 'WithoutBias 'NoPadding channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols channels)\n\n  runForwards (Convolution kernel _) (S3D input) =     \n    let ex = extract input\n        ek = extract kernel\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters)\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels)\n\n        out  = forwardConv2d ex cs ix iy ek fs kx ky sx sy ox oy 0 0\n    in  (S3D input, S3D . fromJust . create $ out)\n\n  runBackwards (Convolution kernel _) (S3D input) (S3D dEdy) =     \n    let ex = extract input\n        ek = extract kernel\n        ey = extract dEdy\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters)\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels)\n\n        (dx, dw)  = backwardConv2d ex cs ix iy ek fs kx ky sx sy 0 0 0 0 ey ox oy\n    in  (Convolution' . fromJust . create $ dw, S3D . fromJust . create $ dx)\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , KnownNat channels\n         , KnownNat padt\n         , KnownNat padl\n         , KnownNat padb\n         , KnownNat padr\n         , OutputShapeIsOkay inputRows (padt + padb) kernelRows strideRows outputRows\n         , OutputShapeIsOkay inputCols (padl + padr) kernelCols strideCols outputCols\n         ) => Layer (Convolution 'WithoutBias ('Padding padl padt padr padb) channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) where\n\n  type Tape (Convolution 'WithoutBias ('Padding padl padt padr padb) channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols channels)\n\n  runForwards (Convolution kernel _) (S3D input) =\n    let ex = extract input\n        ek = extract kernel\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters)\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels)\n        pl = fromIntegral $ natVal (Proxy :: Proxy padl)\n        pt = fromIntegral $ natVal (Proxy :: Proxy padt)\n\n        out  = fromJust . create $ forwardConv2d ex cs ix iy ek fs kx ky sx sy ox oy pl pt\n    in  (S3D input, S3D out)\n\n  runBackwards (Convolution kernel _) (S3D input) (S3D dEdy) =     \n    let ex = extract input\n        ek = extract kernel\n        ey = extract dEdy\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows )\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols )\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters   )\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels  )\n        pl = fromIntegral $ natVal (Proxy :: Proxy padl      )\n        pt = fromIntegral $ natVal (Proxy :: Proxy padt      )\n        pr = fromIntegral $ natVal (Proxy :: Proxy padr      )\n        pb = fromIntegral $ natVal (Proxy :: Proxy padb      )\n\n        (dx, dw) = backwardConv2d ex cs ix iy ek fs kx ky sx sy pl pt pr pb ey ox oy\n    in  (Convolution' . fromJust . create $ dw, S3D . fromJust . create $ dx)\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat channels\n         ) => Layer (Convolution 'WithoutBias 'SameUpper channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 inputRows inputCols filters) where\n\n  type Tape (Convolution 'WithoutBias 'SameUpper channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 inputRows inputCols filters) = S ('D3 inputRows inputCols channels)\n\n  runForwards (Convolution kernel _) (S3D input) =\n    let ex = extract input\n        ek = extract kernel\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows )\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols )\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters   )\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels  )\n\n        pady = (ix - 1) * sx + kx - ix\n        padx = (iy - 1) * sy + ky - iy\n\n        padt = div pady 2\n        padl = div padx 2\n\n        out  = fromJust . create $ forwardConv2d ex cs ix iy ek fs kx ky sx sy ix iy padl padt\n    in  (S3D input, S3D out)\n\n  runBackwards (Convolution kernel _) (S3D input) (S3D dEdy) =     \n    let ex = extract input\n        ek = extract kernel\n        ey = extract dEdy\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows )\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols )\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters   )\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels  )\n\n        pady = (ix - 1) * sx + kx - ix\n        padx = (iy - 1) * sy + ky - iy\n\n        padl = div padx 2\n        padt = div pady 2\n        padr = padx - padl\n        padb = pady - padt\n\n        (dx, dw) = backwardConv2d ex cs ix iy ek fs kx ky sx sy padl padt padr padb ey ix iy\n    in  (Convolution' . fromJust . create $ dw, S3D . fromJust . create $ dx)\n\n-- | A three dimensional image (or 2d with many channels) can have\n--   an appropriately sized convolution filter run across it.\n--   Case without bias vector.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat channels\n         ) => Layer (Convolution 'WithoutBias 'SameLower channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 inputRows inputCols filters) where\n\n  type Tape (Convolution 'WithoutBias 'SameLower channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 inputRows inputCols filters) = S ('D3 inputRows inputCols channels)\n\n  runForwards (Convolution kernel _) (S3D input) =\n    let ex = extract input\n        ek = extract kernel\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters)\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels)\n\n        pady = (ix - 1) * sx + kx - ix\n        padx = (iy - 1) * sy + ky - iy\n\n        padt = pady - div pady 2\n        padl = padx - div padx 2\n        out  = fromJust . create $ forwardConv2d ex cs ix iy ek fs kx ky sx sy ix iy padl padt\n\n    in  (S3D input, S3D out)\n\n  runBackwards (Convolution kernel _) (S3D input) (S3D dEdy) =     \n    let ex = extract input\n        ek = extract kernel\n        ey = extract dEdy\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows )\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols )\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters   )\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels  )\n\n        pady = (ix - 1) * sx + kx - ix\n        padx = (iy - 1) * sy + ky - iy\n\n        padt = pady - padb\n        padl = padx - padr\n        padr = div padx 2\n        padb = div pady 2\n\n        (dx, dw) = backwardConv2d ex cs ix iy ek fs kx ky sx sy padl padt padr padb ey ix iy\n    in  (Convolution' . fromJust . create $ dw, S3D . fromJust . create $ dx)\n\n{--------------------------------}\n{--    Bias Layer instances    --}\n{--------------------------------}\n\n-- | A three dimensional image (or 2d with many channels) can have\n--   an appropriately sized convolution filter run across it.\n--   Case with bias vector\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , KnownNat channels\n         , OutputShapeIsOkay inputRows 0 kernelRows strideRows outputRows\n         , OutputShapeIsOkay inputCols 0 kernelCols strideCols outputCols\n         ) => Layer (Convolution 'WithBias 'NoPadding channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) where\n\n  type Tape (Convolution 'WithBias 'NoPadding channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols channels)\n\n  runForwards (BiasConvolution kernel biases _) (S3D input) =\n    let ex = extract input\n        ek = extract kernel\n        eb = extract biases\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters)\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels)\n\n        out  = fromJust . create $ forwardBiasConv2d ex cs ix iy eb ek fs kx ky sx sy ox oy 0 0\n\n    in  (S3D input, S3D out)\n\n  runBackwards (BiasConvolution kernel _ _) (S3D input) (S3D dEdy) =     \n    let ex = extract input\n        ek = extract kernel\n        ey = extract dEdy\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters)\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels)\n        \n        (dx', dw', db') = backwardBiasConv2d ex cs ix iy ek fs kx ky sx sy 0 0 0 0 ey ox oy\n        dx              = fromJust . create $ dx'\n        dw              = fromJust . create $ dw'\n        db              = fromJust . create $ db'\n    in  (BiasConvolution' dw db, S3D dx)\n\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , KnownNat channels\n         , KnownNat padt\n         , KnownNat padl\n         , KnownNat padb\n         , KnownNat padr\n         , OutputShapeIsOkay inputRows (padt + padb) kernelRows strideRows outputRows\n         , OutputShapeIsOkay inputCols (padl + padr) kernelCols strideCols outputCols\n         ) => Layer (Convolution 'WithBias ('Padding padl padt padr padb) channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) where\n\n  type Tape (Convolution 'WithBias ('Padding padl padt padr padb) channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols channels)\n\n  runForwards (BiasConvolution kernel biases _) (S3D input) =\n    let ex = extract input\n        ek = extract kernel\n        eb = extract biases\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows )\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols )\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters   )\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels  )\n        pl = fromIntegral $ natVal (Proxy :: Proxy padl      )\n        pt = fromIntegral $ natVal (Proxy :: Proxy padt      )\n\n        out  = fromJust . create $ forwardBiasConv2d ex cs ix iy eb ek fs kx ky sx sy ox oy pl pt\n\n    in  (S3D input, S3D out)\n\n  runBackwards (BiasConvolution kernel _ _) (S3D input) (S3D dEdy) =     \n    let ex = extract input\n        ek = extract kernel\n        ey = extract dEdy\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows )\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols )\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters   )\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels  )\n        pl = fromIntegral $ natVal (Proxy :: Proxy padl      )\n        pt = fromIntegral $ natVal (Proxy :: Proxy padt      )\n        pr = fromIntegral $ natVal (Proxy :: Proxy padr      )\n        pb = fromIntegral $ natVal (Proxy :: Proxy padb      )\n\n        (dx', dw', db') = backwardBiasConv2d ex cs ix iy ek fs kx ky sx sy pl pt pr pb ey ox oy\n        dx              = fromJust . create $ dx'\n        dw              = fromJust . create $ dw'\n        db              = fromJust . create $ db'\n    in  (BiasConvolution' dw db, S3D dx)\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat channels\n         ) => Layer (Convolution 'WithBias 'SameUpper channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 inputRows inputCols filters) where\n\n  type Tape (Convolution 'WithBias 'SameUpper channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 inputRows inputCols filters) = S ('D3 inputRows inputCols channels)\n\n  runForwards (BiasConvolution kernel bias _) (S3D input) =\n    let ex = extract input\n        ek = extract kernel\n        eb = extract bias\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters)\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels)\n\n        pady = (ix - 1) * sx + kx - ix\n        padx = (iy - 1) * sy + ky - iy\n\n        padt = div pady 2\n        padl = div padx 2\n\n        out  = fromJust . create $ forwardBiasConv2d ex cs ix iy eb ek fs kx ky sx sy ix iy padl padt\n\n    in  (S3D input, S3D out)\n\n  runBackwards (BiasConvolution kernel _ _) (S3D input) (S3D dEdy) =     \n    let ex = extract input\n        ek = extract kernel\n        ey = extract dEdy\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows )\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols )\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters   )\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels  )\n\n        pady = (ix - 1) * sx + kx - ix\n        padx = (iy - 1) * sy + ky - iy\n\n        padl = div padx 2\n        padt = div pady 2\n        padr = padx - padl\n        padb = pady - padt\n\n        (dx', dw', db') = backwardBiasConv2d ex cs ix iy ek fs kx ky sx sy padl padt padr padb ey ix iy\n        dx              = fromJust . create $ dx'\n        dw              = fromJust . create $ dw'\n        db              = fromJust . create $ db'\n    in  (BiasConvolution' dw db, S3D dx)\n\n-- | A three dimensional image (or 2d with many channels) can have\n--   an appropriately sized convolution filter run across it.\n--   Case without bias vector.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat channels\n         ) => Layer (Convolution 'WithBias 'SameLower channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 inputRows inputCols filters) where\n\n  type Tape (Convolution 'WithBias 'SameLower channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 inputRows inputCols filters) = S ('D3 inputRows inputCols channels)\n\n  runForwards (BiasConvolution kernel bias _) (S3D input) =\n    let ex = extract input\n        ek = extract kernel\n        eb = extract bias\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters)\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels)\n\n        pady = (ix - 1) * sx + kx - ix\n        padx = (iy - 1) * sy + ky - iy\n\n        padt = pady - div pady 2\n        padl = padx - div padx 2\n\n        out  = fromJust . create $ forwardBiasConv2d ex cs ix iy eb ek fs kx ky sx sy ix iy padl padt\n    in  (S3D input, S3D out)\n\n  runBackwards (BiasConvolution kernel _ _) (S3D input) (S3D dEdy) =     \n    let ex = extract input\n        ek = extract kernel\n        ey = extract dEdy\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows )\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols )\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        fs = fromIntegral $ natVal (Proxy :: Proxy filters   )\n        cs = fromIntegral $ natVal (Proxy :: Proxy channels  )\n\n        pady = (ix - 1) * sx + kx - ix\n        padx = (iy - 1) * sy + ky - iy\n\n        padr = div padx 2\n        padb = div pady 2\n        padl = padx - padr\n        padt = pady - padb\n\n        (dx', dw', db') = backwardBiasConv2d ex cs ix iy ek fs kx ky sx sy padl padt padr padb ey ix iy\n        dx              = fromJust . create $ dx'\n        dw              = fromJust . create $ dw'\n        db              = fromJust . create $ db'\n    in  (BiasConvolution' dw db, S3D dx)\n\n\n{---------------------------------}\n{--    Other Layer instances    --}\n{---------------------------------}\n\n-- | A two dimentional image may have a convolution filter applied to it.\n--   Case without bias vector\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , OutputShapeIsOkay inputRows 0 kernelRows strideRows outputRows\n         , OutputShapeIsOkay inputCols 0 kernelCols strideCols outputCols\n         ) => Layer (Convolution 'WithoutBias 'NoPadding 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 outputRows outputCols filters) where\n  type Tape (Convolution 'WithoutBias 'NoPadding 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    runForwards c (S3D input :: S ('D3 inputRows inputCols 1))\n\n  runBackwards c tape grads =\n    case runBackwards c tape grads of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) ->  (c', S2D back)\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         ) => Layer (Convolution 'WithoutBias 'SameUpper 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 inputRows inputCols filters) where\n  type Tape (Convolution 'WithoutBias 'SameUpper 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 inputRows inputCols filters) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    runForwards c (S3D input :: S ('D3 inputRows inputCols 1))\n\n  runBackwards c tape grads =\n    case runBackwards c tape grads of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) ->  (c', S2D back)\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         ) => Layer (Convolution 'WithoutBias 'SameLower 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 inputRows inputCols filters) where\n  type Tape (Convolution 'WithoutBias 'SameLower 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 inputRows inputCols filters) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    runForwards c (S3D input :: S ('D3 inputRows inputCols 1))\n\n  runBackwards c tape grads =\n    case runBackwards c tape grads of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) ->  (c', S2D back)\n\n-- | A two dimentional image may have a convolution filter applied to it.\n--   Case with bias vector.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , OutputShapeIsOkay inputRows 0 kernelRows strideRows outputRows\n         , OutputShapeIsOkay inputCols 0 kernelCols strideCols outputCols\n         ) => Layer (Convolution 'WithBias 'NoPadding 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 outputRows outputCols filters) where\n  type Tape (Convolution 'WithBias 'NoPadding 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    runForwards c (S3D input :: S ('D3 inputRows inputCols 1))\n\n  runBackwards c tape grads =\n    case runBackwards c tape grads of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) ->  (c', S2D back)\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         ) => Layer (Convolution 'WithBias 'SameUpper 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 inputRows inputCols filters) where\n  type Tape (Convolution 'WithBias 'SameUpper 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 inputRows inputCols filters) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    runForwards c (S3D input :: S ('D3 inputRows inputCols 1))\n\n  runBackwards c tape grads =\n    case runBackwards c tape grads of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) ->  (c', S2D back)\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         ) => Layer (Convolution 'WithBias 'SameLower 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 inputRows inputCols filters) where\n  type Tape (Convolution 'WithBias 'SameLower 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 inputRows inputCols filters) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    runForwards c (S3D input :: S ('D3 inputRows inputCols 1))\n\n  runBackwards c tape grads =\n    case runBackwards c tape grads of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) ->  (c', S2D back)\n\n-- | A two dimensional image may have a convolution filter applied to it producing\n--   a two dimensional image if both channels and filters is 1.\n--   Case without bias vector.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputCols\n         , KnownNat outputRows\n         , OutputShapeIsOkay inputRows 0 kernelRows strideRows outputRows\n         , OutputShapeIsOkay inputCols 0 kernelCols strideCols outputCols\n         ) => Layer (Convolution 'WithoutBias 'NoPadding 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 outputRows outputCols) where\n  type Tape (Convolution 'WithoutBias 'NoPadding 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 outputRows outputCols) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    case runForwards c (S3D input :: S ('D3 inputRows inputCols 1)) of\n      (tps, S3D back :: S ('D3 outputRows outputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    case runBackwards c tape (S3D grads :: S ('D3 outputRows outputCols 1)) of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) -> (c', S2D back)\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         ) => Layer (Convolution 'WithoutBias 'SameUpper 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 inputRows inputCols) where\n  type Tape (Convolution 'WithoutBias 'SameUpper 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 inputRows inputCols) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    case runForwards c (S3D input :: S ('D3 inputRows inputCols 1)) of\n      (tps, S3D back :: S ('D3 inputRows inputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    case runBackwards c tape (S3D grads :: S ('D3 inputRows inputCols 1)) of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) -> (c', S2D back)\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         ) => Layer (Convolution 'WithoutBias 'SameLower 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 inputRows inputCols) where\n  type Tape (Convolution 'WithoutBias 'SameLower 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 inputRows inputCols) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    case runForwards c (S3D input :: S ('D3 inputRows inputCols 1)) of\n      (tps, S3D back :: S ('D3 inputRows inputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    case runBackwards c tape (S3D grads :: S ('D3 inputRows inputCols 1)) of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) -> (c', S2D back)\n\n-- | A two dimensional image may have a convolution filter applied to it producing\n--   a two dimensional image if both channels and filters is 1.\n--   Case with bias vector.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputCols\n         , KnownNat outputRows\n         , OutputShapeIsOkay inputRows 0 kernelRows strideRows outputRows\n         , OutputShapeIsOkay inputCols 0 kernelCols strideCols outputCols\n         ) => Layer (Convolution 'WithBias 'NoPadding 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 outputRows outputCols) where\n  type Tape (Convolution 'WithBias 'NoPadding 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 outputRows outputCols) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    case runForwards c (S3D input :: S ('D3 inputRows inputCols 1)) of\n      (tps, S3D back :: S ('D3 outputRows outputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    case runBackwards c tape (S3D grads :: S ('D3 outputRows outputCols 1)) of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) -> (c', S2D back)\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         ) => Layer (Convolution 'WithBias 'SameUpper 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 inputRows inputCols) where\n  type Tape (Convolution 'WithBias 'SameUpper 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 inputRows inputCols) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    case runForwards c (S3D input :: S ('D3 inputRows inputCols 1)) of\n      (tps, S3D back :: S ('D3 inputRows inputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    case runBackwards c tape (S3D grads :: S ('D3 inputRows inputCols 1)) of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) -> (c', S2D back)\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         ) => Layer (Convolution 'WithBias 'SameLower 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 inputRows inputCols) where\n  type Tape (Convolution 'WithBias 'SameLower 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 inputRows inputCols) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    case runForwards c (S3D input :: S ('D3 inputRows inputCols 1)) of\n      (tps, S3D back :: S ('D3 inputRows inputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    case runBackwards c tape (S3D grads :: S ('D3 inputRows inputCols 1)) of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) -> (c', S2D back)\n\n-- | A three dimensional image can produce a 2D image from a convolution with 1 filter\n--   Case without bias vector.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputCols\n         , KnownNat outputRows\n         , KnownNat channels\n         , OutputShapeIsOkay inputRows 0 kernelRows strideRows outputRows\n         , OutputShapeIsOkay inputCols 0 kernelCols strideCols outputCols\n         ) => Layer (Convolution 'WithoutBias 'NoPadding channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 outputRows outputCols) where\n  type Tape (Convolution 'WithoutBias 'NoPadding channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 outputRows outputCols) = S ('D3 inputRows inputCols channels)\n  runForwards c input =\n    case runForwards c input of\n      (tps, S3D back :: S ('D3 outputRows outputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    runBackwards c tape (S3D grads :: S ('D3 outputRows outputCols 1))\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat channels\n         ) => Layer (Convolution 'WithoutBias 'SameUpper channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 inputRows inputCols) where\n  type Tape (Convolution 'WithoutBias 'SameUpper channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 inputRows inputCols) = S ('D3 inputRows inputCols channels)\n  runForwards c input =\n    case runForwards c input of\n      (tps, S3D back :: S ('D3 inputRows inputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    runBackwards c tape (S3D grads :: S ('D3 inputRows inputCols 1))\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat channels\n         ) => Layer (Convolution 'WithoutBias 'SameLower channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 inputRows inputCols) where\n  type Tape (Convolution 'WithoutBias 'SameLower channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 inputRows inputCols) = S ('D3 inputRows inputCols channels)\n  runForwards c input =\n    case runForwards c input of\n      (tps, S3D back :: S ('D3 inputRows inputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    runBackwards c tape (S3D grads :: S ('D3 inputRows inputCols 1))\n\n-- | A three dimensional image can produce a 2D image from a convolution with 1 filter\n--   Case with bias vector.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputCols\n         , KnownNat outputRows\n         , KnownNat channels\n         , OutputShapeIsOkay inputRows 0 kernelRows strideRows outputRows\n         , OutputShapeIsOkay inputCols 0 kernelCols strideCols outputCols\n         ) => Layer (Convolution 'WithBias 'NoPadding channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 outputRows outputCols) where\n  type Tape (Convolution 'WithBias 'NoPadding channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 outputRows outputCols) = S ('D3 inputRows inputCols channels)\n  runForwards c input =\n    case runForwards c input of\n      (tps, S3D back :: S ('D3 outputRows outputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    runBackwards c tape (S3D grads :: S ('D3 outputRows outputCols 1))\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat channels\n         ) => Layer (Convolution 'WithBias 'SameUpper channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 inputRows inputCols) where\n  type Tape (Convolution 'WithBias 'SameUpper channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 inputRows inputCols) = S ('D3 inputRows inputCols channels)\n  runForwards c input =\n    case runForwards c input of\n      (tps, S3D back :: S ('D3 inputRows inputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    runBackwards c tape (S3D grads :: S ('D3 inputRows inputCols 1))\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat channels\n         ) => Layer (Convolution 'WithBias 'SameLower channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 inputRows inputCols) where\n  type Tape (Convolution 'WithBias 'SameLower channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 inputRows inputCols) = S ('D3 inputRows inputCols channels)\n  runForwards c input =\n    case runForwards c input of\n      (tps, S3D back :: S ('D3 inputRows inputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    runBackwards c tape (S3D grads :: S ('D3 inputRows inputCols 1))\n\n{--------------------}\n{-- ONNX Instances --}\n{--------------------}\n\ninstance OnnxOperator (Convolution 'WithBias padding channels filters kernelRows kernelCols strideRows strideCols) where\n  onnxOpTypeNames _ = [\"Conv\"]\n\ninstance OnnxOperator (Convolution 'WithoutBias padding channels filters kernelRows kernelCols strideRows strideCols) where\n  onnxOpTypeNames _ = [\"Conv\"]\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat channels\n         , KnownNat (kernelRows * kernelCols * channels)\n         ) => OnnxLoadable (Convolution 'WithoutBias 'NoPadding channels filters kernelRows kernelCols strideRows strideCols) where\n  loadOnnxNode inits node = do\n    node `doesNotHaveAttribute` \"auto_pad\"\n\n    node & hasSupportedDilations\n    node & hasSupportedGroup\n\n    (node `hasMatchingShape` \"kernel_shape\") kernelShape\n    (node `hasMatchingShape` \"strides\"     ) strideShape\n    hasCorrectPadding node (Proxy :: Proxy 0) (Proxy :: Proxy 0) (Proxy :: Proxy 0) (Proxy :: Proxy 0)\n\n    case node ^. #input of\n      [_, w] -> do\n        filterWeights <- tr <$> readInitializerTensorIntoMatrix inits w\n        return (Convolution filterWeights mkListStore)\n      _ -> onnxIncorrectNumberOfInputs\n      where\n        kernelShape = [natVal (Proxy :: Proxy kernelRows), natVal (Proxy :: Proxy kernelCols)]\n        strideShape = [natVal (Proxy :: Proxy strideRows), natVal (Proxy :: Proxy strideCols)]\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat channels\n         , KnownNat (kernelRows * kernelCols * channels)\n         ) => OnnxLoadable (Convolution 'WithoutBias 'SameUpper channels filters kernelRows kernelCols strideRows strideCols) where\n  loadOnnxNode inits node = do\n    node `doesNotHaveAttribute` \"auto_pad\"\n\n    node & hasSupportedDilations\n    node & hasSupportedGroup\n\n    (node `hasMatchingShape` \"kernel_shape\") kernelShape\n    (node `hasMatchingShape` \"strides\"     ) strideShape\n\n    case node ^. #input of\n      [_, w] -> do\n        filterWeights <- tr <$> readInitializerTensorIntoMatrix inits w\n        return (Convolution filterWeights mkListStore)\n      _ -> onnxIncorrectNumberOfInputs\n      where\n        kernelShape = [natVal (Proxy :: Proxy kernelRows), natVal (Proxy :: Proxy kernelCols)]\n        strideShape = [natVal (Proxy :: Proxy strideRows), natVal (Proxy :: Proxy strideCols)]\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat channels\n         , KnownNat padl, KnownNat padt, KnownNat padr, KnownNat padb\n         ) => OnnxLoadable (Convolution 'WithoutBias ('Padding padl padt padr padb) channels filters kernelRows kernelCols strideRows strideCols) where\n  loadOnnxNode inits node = do\n    node `doesNotHaveAttribute` \"auto_pad\"\n\n    node & hasSupportedDilations\n    node & hasSupportedGroup\n\n    (node `hasMatchingShape` \"kernel_shape\") kernelShape\n    (node `hasMatchingShape` \"strides\"     ) strideShape\n\n    hasCorrectPadding node (Proxy :: Proxy padl) (Proxy :: Proxy padr) (Proxy :: Proxy padt) (Proxy :: Proxy padb)\n\n    case node ^. #input of\n      [_, w] -> do\n        filterWeights <- tr <$> readInitializerTensorIntoMatrix inits w\n        return (Convolution filterWeights mkListStore)\n      _ -> onnxIncorrectNumberOfInputs\n      where\n        kernelShape = [natVal (Proxy :: Proxy kernelRows), natVal (Proxy :: Proxy kernelCols)]\n        strideShape = [natVal (Proxy :: Proxy strideRows), natVal (Proxy :: Proxy strideCols)]\n\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat channels\n         , KnownNat (kernelRows * kernelCols * channels)\n         ) => OnnxLoadable (Convolution 'WithBias padding channels filters kernelRows kernelCols strideRows strideCols) where\n  loadOnnxNode inits node = do\n    node & hasSupportedDilations\n    node & hasSupportedGroup\n\n    (node `hasMatchingShape` \"kernel_shape\") kernelShape\n    (node `hasMatchingShape` \"strides\"     ) strideShape\n\n    -- todo: proper checking to see if auto_pad attribute is valid\n\n    case node ^. #input of\n      [_, w, b] -> do\n        filterWeights <- tr <$> readInitializerTensorIntoMatrix inits w\n        filterBias    <- readInitializerVector inits b\n        return (BiasConvolution filterWeights filterBias mkListStore)\n      _ -> onnxIncorrectNumberOfInputs\n      where\n        kernelShape = [natVal (Proxy :: Proxy kernelRows), natVal (Proxy :: Proxy kernelCols)]\n        strideShape = [natVal (Proxy :: Proxy strideRows), natVal (Proxy :: Proxy strideCols)]\n\n{--------------------}\n{-- Misc Instances --}\n{--------------------}\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         ) =>\n         LayerOptimizerData (Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'SGD) where\n  type MomentumExpOptResult (Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'SGD) = L (kernelRows * kernelColumns * channels) filters\n  type MomentumDataType (Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'SGD) = L (kernelRows * kernelColumns * channels) filters\n  getData opt x store = head $ getListStore opt x store\n  setData opt x store = setListStore opt x store . return\n  newData _ _ = konst 0\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         ) =>\n         LayerOptimizerData (Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'SGD) where\n  type MomentumExpOptResult (Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'SGD) = L (kernelRows * kernelColumns * channels) filters\n  type MomentumDataType (Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'SGD) = L (kernelRows * kernelColumns * channels) filters\n  getData = undefined\n  setData = undefined\n  newData = undefined\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         ) => LayerOptimizerData (Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'Adam) where\n  type MomentumExpOptResult (Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'Adam)  = [L (kernelRows * kernelColumns * channels) filters]\n  type MomentumDataType (Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'Adam) = L (kernelRows * kernelColumns * channels) filters\n  getData = getListStore\n  setData = setListStore\n  newData _ _ = konst 0\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * channels)\n         ) => LayerOptimizerData (Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'Adam) where\n  type MomentumExpOptResult (Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'Adam)  = [L (kernelRows * kernelColumns * channels) filters]\n  type MomentumDataType (Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'Adam) = L (kernelRows * kernelColumns * channels) filters\n  getData = undefined\n  setData = undefined\n  newData = undefined\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns) => FoldableGradient (Convolution' hasBias padding channels filters kernelRows kernelColumns strideRows strideColumns) where\n  mapGradient f (Convolution' kernelGradient) = Convolution' (dmmap f kernelGradient)\n  mapGradient f (BiasConvolution' kernelGradient biasGradient) = BiasConvolution' (dmmap f kernelGradient) (dvmap f biasGradient)\n  squaredSums (Convolution' kernelGradient) = [sumM . squareM $ kernelGradient]\n  squaredSums (BiasConvolution' kernelGradient biasGradient) = [sumM . squareM $ kernelGradient, sumV . squareV $ biasGradient ]\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * channels)\n         ) => Serialize (Convolution 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns) where\n  put (Convolution w store) = do\n    putListOf put . toList . flatten . extract $ w\n    put (fmap (toList . flatten . extract) store)\n  get = do\n      let f  = fromIntegral $ natVal (Proxy :: Proxy filters)\n      wN    <- maybe (fail \"Vector of incorrect size\") return . create . reshape f . LA.fromList =<< getListOf get\n      store <- fmap (fromMaybe (error \"Vector of incorrect size\") . create . reshape f . LA.fromList)  <$> get\n      return $ Convolution wN store\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * channels)\n         ) => Serialize (Convolution 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns) where\n  put (BiasConvolution w b store) = do\n    putListOf put . toList . flatten . extract $ w\n    putListOf put . toList . extract $ b\n    put (fmap (toList . flatten . extract) store)\n  get = do\n      let f  = fromIntegral $ natVal (Proxy :: Proxy filters)\n      wN    <- maybe (fail \"Vector of incorrect size\") return . create . reshape f . LA.fromList =<< getListOf get\n      wB    <- maybe (fail \"Vector of incorrect size\") return . create . LA.fromList =<< getListOf get\n      store <- fmap (fromMaybe (error \"Vector of incorrect size\") . create . reshape f . LA.fromList)  <$> get\n      return $ BiasConvolution wN wB store\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * channels)\n         ) => Serialize (Convolution' 'WithoutBias padding channels filters kernelRows kernelColumns strideRows strideColumns) where\n  put (Convolution' w) = do\n    putListOf put . toList . flatten . extract $ w\n  get = do\n      let f  = fromIntegral $ natVal (Proxy :: Proxy filters)\n      wN    <- maybe (fail \"Vector of incorrect size\") return . create . reshape f . LA.fromList =<< getListOf get\n      return $ Convolution' wN\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * channels)\n         ) => Serialize (Convolution' 'WithBias padding channels filters kernelRows kernelColumns strideRows strideColumns) where\n  put (BiasConvolution' w b) = do\n    putListOf put . toList . flatten . extract $ w\n    putListOf put . toList . extract $ b\n  get = do\n      let f  = fromIntegral $ natVal (Proxy :: Proxy filters)\n      wN    <- maybe (fail \"Vector of incorrect size\") return . create . reshape f . LA.fromList =<< getListOf get\n      wB    <- maybe (fail \"Vector of incorrect size\") return . create . LA.fromList =<< getListOf get\n      return $ BiasConvolution' wN wB\n\ninstance NFData (Convolution hasBias padding channels filters kernelRows kernelColumns strideRows strideColumns) where\n  rnf (BiasConvolution a b c) = rnf a `seq` rnf b `seq` rnf c\n  rnf (Convolution a b)       = rnf a `seq` rnf b\n\ninstance NFData (Convolution' hasBias padding channels filters kernelRows kernelColumns strideRows strideColumns) where\n  rnf (BiasConvolution' a b) = rnf a `seq` rnf b\n  rnf (Convolution' a)       = rnf a\n\ninstance Show (Convolution hasBias padding c f k k' s s') where\n  show (BiasConvolution _ _ _) = \"Bias Convolution\"\n  show (Convolution _ _)       = \"Convolution\"\n", "meta": {"hexsha": "9b8f4b670b78701990b63375acdfd56b2d5838e1", "size": 64123, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Convolution.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/Convolution.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Convolution.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4776234568, "max_line_length": 240, "alphanum_fraction": 0.6569561624, "num_tokens": 16129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4647116781305008}}
{"text": "{-|\nModule      : MachineLearning.Model.Regression\nDescription : TIR expression data structures\nCopyright   : (c) Fabricio Olivetti de Franca, 2022\nLicense     : GPL-3\nMaintainer  : fabricio.olivetti@gmail.com\nStability   : experimental\nPortability : POSIX\n\nFitting functions for the coefficients.\n-}\nmodule MachineLearning.Model.Regression \n  ( fitTask\n  , predictTask\n  , evalPenalty\n  , applyMeasures\n  , nonlinearFit\n  , tirToMatrix\n  ) where\n\nimport Data.Bifunctor\nimport           Data.SRTree                   (evalFun, Function(..), OptIntPow(..), evalFun, inverseFunc)\nimport MachineLearning.TIR       (TIR(..),  Individual(..), Dataset, Constraint, assembleTree, replaceConsts)\nimport qualified Data.Vector           as V\nimport qualified Data.Vector.Storable  as VS\nimport Data.Vector           ((!))\nimport           Data.List                     (nub)\nimport           Data.Vector.Storable          (Vector, splitAt)\nimport           Numeric.LinearAlgebra         ((<\\>), Matrix)\nimport           Numeric.GSL.Fitting           (nlFitting, FittingMethod(..))\nimport           Prelude               hiding  (splitAt)\n\nimport qualified Numeric.LinearAlgebra                     as LA\n\nimport MachineLearning.TIR (Individual(..))\nimport MachineLearning.Utils.Config (Task(..), Penalty(..))\nimport MachineLearning.Model.Measure (Measure(..))\n\n-- * IT specific stuff\n\ncreateQ :: Vector Double -> LA.Matrix Double -> LA.Matrix Double\ncreateQ ys = LA.fromColumns . map (*ys) . LA.toColumns\n{-# INLINE createQ #-}\n\navg :: Vector Double -> Vector Double\navg ys = LA.fromList [LA.sumElements ys / fromIntegral (LA.size ys)]\n{-# INLINE avg #-}\n\n-- | transform a data matrix using a TIR expression. This function returns\n-- a tuple with the transformed data of the numerator and denominator, respectivelly.\n-- Each column of the transformed data represents one term of the TIR expression.\ntirToMatrix :: Dataset Double -> TIR -> (LA.Matrix Double, LA.Matrix Double)\ntirToMatrix xss (TIR _ p q) = bimap (LA.fromColumns . (bias:)) LA.fromColumns (p', q')\n  where\n    bias      = V.head xss\n    xss'      = V.tail xss\n    sigma2mtx = map (\\(_, g, ps) -> evalFun g $ evalPi ps)\n    evalPi    = foldr (\\(ix, k) acc -> acc * (xss' ! ix ^^ k)) 1\n    p'        = sigma2mtx p\n    q'        = sigma2mtx q\n{-# INLINE tirToMatrix #-}\n\n-- | Fits a linear model using l2-penalty\nridge :: Matrix Double -> Vector Double -> Matrix Double\nridge a b = oA <\\> oB\n  where\n   mu = 0.01\n\n   a' = LA.tr a\n   b' = LA.tr $ LA.asColumn b\n   oA = (a' <> LA.tr a') + (mu * LA.ident (LA.rows a'))\n   oB = a' <> LA.tr b'\n{-# INLINE ridge #-}\n\n-- | Predicts a linear model\npredict :: Matrix Double -> Vector Double -> Vector Double \npredict xs w | LA.cols xs == LA.size w = xs LA.#> w\n             | otherwise = error $ \"predict: \" ++ show (LA.size xs) ++ show (LA.size w)\n{-# INLINE predict #-}\n\n-- | Solve the OLS *zss*w = ys*\nsolveOLS :: Matrix Double -> Vector Double -> Vector Double \nsolveOLS zss ys = zss <\\> ys\n{-# INLINE solveOLS #-}\n\n-- | Applies OLS and returns a Solution\n-- if the expression is invalid, it returns Infinity as a fitness\n--regress :: Matrix Double -> Vector Double -> [Vector Double]\nregress :: TIR -> Dataset Double -> Vector Double -> [Vector Double]\nregress tir xss ys = [ws]\n  where\n    (zssP, zssQ) = tirToMatrix xss tir\n    ys'          = evalFun (inverseFunc $ _funY tir) ys\n    zssQy        = createQ ys' zssQ\n    zss          = if LA.cols zssQ >= 1\n                       then zssP LA.||| negate zssQy \n                       else zssP\n    ws             = if LA.cols zss == 1\n                       then avg ys'\n                       else solveOLS zss ys'\n-- regress zss ys = [solveOLS zss ys]\n{-# INLINE regress #-}\n\n-- | Applies conjugate gradient for binary classification\n--classify :: Matrix Double -> Vector Double -> [Vector Double]\nclassify :: Int -> TIR -> Dataset Double -> Vector Double -> [Vector Double]\nclassify niter tir xss ys = [ws]\n  where\n    ws           = nonlinearFit niter zssP zssQ ys sigmoid dsigmoid theta0\n    theta0       = LA.konst 0 (LA.cols zssP + LA.cols zssQ)\n    (zssP, zssQ) = tirToMatrix xss tir\n\n-- | Applies conjugate gradient for one-vs-all classification\n--classifyMult :: Matrix Double -> Vector Double -> [Vector Double]\nclassifyMult :: Int -> TIR -> Dataset Double -> Vector Double -> [Vector Double]\nclassifyMult niter tir xss ys = zipWith minimize yss theta0\n  where\n    numLabels    = length $ nub $ LA.toList ys\n    yss          = map f [0 .. numLabels-1]\n    minimize y t = nonlinearFit niter zssP zssQ y sigmoid dsigmoid t\n    theta0       = replicate numLabels $ LA.konst 0 (LA.cols zssP + LA.cols zssQ)\n    (zssP, zssQ) = tirToMatrix xss tir\n    \n    f sample = VS.map (\\a -> if round a == sample then 1 else 0) ys\n\n-- | chooses the appropriate fitting function\n--fitTask :: Task -> Matrix Double -> Vector Double -> [Vector Double]\nfitTask :: Task -> TIR -> Dataset Double -> Vector Double -> [Vector Double]\nfitTask Regression             = regress\nfitTask (RegressionNL niter)   = regressNL niter\nfitTask (Classification niter) = classify niter\nfitTask (ClassMult niter)      = classifyMult niter\n{-# INLINE fitTask #-}\n\n-- | sigmoid function for classification.\nsigmoid :: Floating a => a -> a\nsigmoid z = 1 / (1+exp(-z))\n{-# INLINE sigmoid #-}\n\n-- | derivative sigmoid function for classification.\ndsigmoid :: Floating a => a -> a\ndsigmoid z = sigmoid z * (1 - sigmoid z)\n{-# INLINE dsigmoid #-}\n\n-- | chooses the appropriate prediction function\npredictTask :: Task -> [Vector Double] -> Vector Double\npredictTask _ []                   = error \"predictTask: empty coefficients matrix\"\npredictTask Regression yss         = head yss\npredictTask (RegressionNL _) yss   = head yss\npredictTask (Classification _) yss = sigmoid $ head yss\npredictTask (ClassMult _) yss      = LA.vector $ map (fromIntegral . LA.maxIndex) $ LA.toRows $ LA.fromColumns $ map sigmoid yss\n{-# INLINE predictTask #-}\n\n-- | evals the penalty function\nevalPenalty :: Penalty -> Int -> Double -> Double\nevalPenalty NoPenalty _   _   = 0.0\nevalPenalty (Len c)   len _   = fromIntegral len * c\nevalPenalty (Shape c) _   val = val*c\n{-# INLINE evalPenalty #-}\n\n-- | applies a list of performance measures\napplyMeasures :: [Measure] -> Vector Double -> Vector Double -> [Double]\napplyMeasures measures ys ysHat = map ((`uncurry` (ys, ysHat)) . _fun) measures\n{-# INLINE applyMeasures #-}\n\nregressNL :: Int -> TIR -> Dataset Double -> Vector Double -> [Vector Double]\nregressNL niter tir xss ys = [ws]\n  where\n    ws           = nonlinearFit niter zssP zssQ ys f f' theta0\n    f            = evalFun $ _funY tir\n    f'           = derivative $ _funY tir\n    --theta0       = LA.konst 1 (LA.cols zssP + LA.cols zssQ)\n    theta0       = head $ regress tir xss ys\n    (zssP, zssQ) = tirToMatrix xss tir\n\n-- | Non-linear optimization using Levenberg-Marquardt method.\n--nonlinearFit :: Monad m => Vector Double -> Matrix Double -> Matrix Double -> Vector Double -> m (Vector Double)\nnonlinearFit :: Int\n             -> Matrix Double \n             -> Matrix Double \n             -> Vector Double \n             -> (Vector Double -> Vector Double) \n             -> (Vector Double -> Vector Double) \n             -> Vector Double \n             -> Vector Double\nnonlinearFit niter zssP zssQ ys f f' theta0 = fst $ nlFitting LevenbergMarquardtScaled 1e-6 1e-6 niter model' jacob' theta0\n  where\n    model'       = model f ys zssP zssQ\n    jacob'       = jacob f' zssP zssQ    \n\n-- | calculates the error given the parameter vector beta\nmodel :: (Vector Double -> Vector Double) -> Vector Double -> Matrix Double -> Matrix Double -> Vector Double -> Vector Double\nmodel f ys zssP zssQ beta \n  | LA.cols zssQ == 0 = f ysHat_P - ys\n  | otherwise         = f ysHat - ys\n  where\n    (betaP, betaQ) = splitAt (LA.cols zssP) beta\n    ysHat_P        = predict zssP betaP\n    ysHat_Q        = if LA.cols zssQ == 0 then 0 else predict zssQ betaQ\n    ysHat          = ysHat_P / (1 + ysHat_Q)\n\n-- | calculates the Jacobian given the parameter vector beta. Doesn't support\n-- the outer transformation function.\njacob :: (Vector Double -> Vector Double) -> Matrix Double -> Matrix Double -> Vector Double -> Matrix Double\njacob f zssP zssQ beta | LA.cols zssQ == 0 = zssP\n                       | otherwise         = LA.fromColumns $ pjac <> qjac\n  where\n    (betaP, betaQ) = splitAt (LA.cols zssP) beta\n    ysHat_P        = predict zssP betaP\n    ysHat_Q        = predict zssQ betaQ\n    ysHat          = f $ ysHat_P / (1 + ysHat_Q)\n    pjac           = [ysHat * c / ysHat_Q | c <- LA.toColumns zssP]\n    qjac           = [-ysHat * c * (ysHat_P / (1 + ysHat_Q)^2) | c <- LA.toColumns zssQ]\n\nderivative :: (Eq val, Floating val) => Function -> val -> val\nderivative Id      = const 1\nderivative Abs     = \\x -> x / abs x\nderivative Sin     = cos\nderivative Cos     = negate.sin\nderivative Tan     = recip . (**2.0) . cos\nderivative Sinh    = cosh\nderivative Cosh    = sinh\nderivative Tanh    = (1-) . (**2.0) . tanh\nderivative ASin    = recip . sqrt . (1-) . (^2)\nderivative ACos    = negate . recip . sqrt . (1-) . (^2)\nderivative ATan    = recip . (1+) . (^2)\nderivative ASinh   = recip . sqrt . (1+) . (^2)\nderivative ACosh   = \\x -> 1 / (sqrt (x-1) * sqrt (x+1))\nderivative ATanh   = recip . (1-) . (^2)\nderivative Sqrt    = recip . (2*) . sqrt\nderivative Square  = (2*)\nderivative Exp     = exp\nderivative Log     = recip\n{-# INLINE derivative #-}\n-- (w1 * p1 + w2 * p2) / (1 + w3 * p3 + w4 * p4)\n-- d/dw1 = p1 / (1 + w3 * p3 + w4 * p4)\n-- d/dw2 = p2 / (1 + w3 * p3 + w4 * p4)\n-- d/dw3 = -p3 * (w1 * p2 + w2 * p2) / (1 + w3 * p3 + w4 * p4)^2\n{-\ntoEv :: SRTree Int Double -> (V.Vector Double -> Double)\ntoEv (Var !ix) = (`V.unsafeIndex` ix)\ntoEv (Const !val) = const val\ntoEv (Add !l !r) = jn (+) (toEv l) (toEv r)\ntoEv (Mul !l !r) = jn (*) (toEv l) (toEv r)\ntoEv (Fun Exp !t) = exp . toEv t\n{-# INLINE toEv #-}\n\njn :: (Double -> Double -> Double) -> (V.Vector Double -> Double) -> (V.Vector Double -> Double) -> (V.Vector Double -> Double)\njn op f g = \\x -> op (f x) (g x)\n{-# INLINE jn #-}\n-}\n", "meta": {"hexsha": "bc17a77216ba9a604d754938afa0841a6c8bcedc", "size": 10104, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/Model/Regression.hs", "max_stars_repo_name": "folivetti/tir", "max_stars_repo_head_hexsha": "5db7c8fa62975f7ce901fce68a560156b2dc6745", "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/MachineLearning/Model/Regression.hs", "max_issues_repo_name": "folivetti/tir", "max_issues_repo_head_hexsha": "5db7c8fa62975f7ce901fce68a560156b2dc6745", "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/MachineLearning/Model/Regression.hs", "max_forks_repo_name": "folivetti/tir", "max_forks_repo_head_hexsha": "5db7c8fa62975f7ce901fce68a560156b2dc6745", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0952380952, "max_line_length": 128, "alphanum_fraction": 0.6178741093, "num_tokens": 2922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.46471166981921214}}
{"text": "module PNN where\n\nimport Data.Complex\nimport qualified Data.Vector as V\nimport Data.Matrix\nimport Data.Random.Normal\nimport Data.List (sortBy)\nimport Data.Number.BigFloat\nimport Math.NumberTheory.Zeta\n\ntype BF = BigFloat Prec50\n\nn = 40 :: Int\nk = 1 :: Int\n\ns = 2.1 :: Double\nsd = 1 / sqrt(s * (fromIntegral n))\nseed = 1\n\nmakeComplex (x:y:xs) = (x :+ y) : makeComplex xs\n\nmkBigNormals' :: (Double,Double) -> Int -> [BF]\nmkBigNormals' (u,sd) seed = map (fromRational . toRational)\n   (mkNormals' (u,sd) seed)\n\ncomplexes = makeComplex (mkBigNormals' (0,sd) seed)\n\nw_res = fromList (n-k) (n-k) complexes\nw_in = fromList (n-k) k $ drop (nrows w_res * ncols w_res) complexes\nx_res = V.fromList $ take (n-k) $ drop (nrows w_res * ncols w_res +\n                                        nrows w_in * ncols w_in) complexes\n\n-- function to predict\n-- vector should have length k\nepsilon = 1e-40 :: BF\nzetas' = zetas epsilon\nzs = [z :+ 0 | z <- zetas']\nas c = V.singleton (zs !! (c+2))\n{-\nas c = let c' = 0.01 * (fromIntegral c) in\n  V.fromList [sin c' + 0.1,\n              cos (2*c'+1),\n              3*(sin (c'+1)) - cos (3*c' + 2)]\n-}\n\n-- matrix / vector multiply\n(*:) mat vec = getCol 1 (multStd mat (colVector vec))\n\n-- vector addition\n(=+=) va vb = V.zipWith (+) va vb\n\n-- vector addition\n(=-=) va vb = V.zipWith (-) va vb\n\nfromVectors vs = fromLists (map V.toList vs)\n\nmat_a = fromVectors (zipWith (V.++) (map as [0..])\n                     (take n (map snd mat_a_gen)))\n\nmat_a_gen = iterate f (0, x_res) where\n  f (i, x_res') = (i+1, (w_in *: (as i)) =+= (w_res *: x_res'))\n\n{-\n-- not sure why this doesn't work\nw_out =\n  let m = mat_a <|> (fromVectors (map as [1..n]))\n      Right m' = rref m\n  in m' --submatrix 1 (n+1) (n+1) (n+k) m'\n-}\n\nsolve m = backsub (triangular m)\n where\n   sortRows = sortBy (\\(r:_) (s:_) -> compare (realPart$abs s) (realPart$abs r))\n   triangular = triangular' . sortRows\n\n   downsub (u:us) (v:vs) = zipWith (-) (map ((v / u) *) us) vs\n\n   triangular' [] = []\n   triangular' rs | all (0 ==) (map head rs) = error \"underdetermined\"\n   triangular' ((p:xs):rs) =\n     let r = 1 : map (/ p) xs\n         ss = map (downsub r) rs\n     in r :  (triangular' ss)\n\n   backsubOne (u:us) (1:vs) = zipWith (-) us (map (u *) vs)\n   backsub' us [] = us\n   backsub' us (v:vs) = backsub' ((tail v) : map (flip backsubOne v) us) vs\n   backsub rs = reverse (backsub' [] rs)\n\n{-\nsolve' m =\n let rows = length m\n     a = map (take rows) m\n     b = map (drop rows) m\n in L.transpose (O.many_kets_solution (L.transpose a) (L.transpose b))\n-}\n\nw_out = let m = mat_a <|> (fromVectors (map as [1..n]))\n        in fromLists (solve (toLists m))\n\nm = (transpose w_out) <-> (w_in <|> w_res)\n\nguesses = map (V.take k) (iterate (m *:) ((as 0) V.++ x_res))\n\nnorm1 mat = maximum [V.sum (V.map (realPart . abs) (getCol c mat)) |\n   c <- [1 .. ncols mat]]\n\nnumber_of_guesses = 10\nerr = norm1 (fromVectors ((zipWith (=-=) (map as [0..]) (take (n+number_of_guesses) guesses))))\n\nsomeFunc :: IO ()\nsomeFunc = do\n   let a = fromList 3 4 [1,6,2,8,9,3,9,0,1,5,2,7]\n   let Right ra = rref a\n   print (getDiag ra)\n   print (getCol 4 ra)\n", "meta": {"hexsha": "4a2c973df0050b3f6083bd55bb9e6ecbcc0c6d1e", "size": 3116, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "DeepLearning/PNN/PNN-Haskell/src/PNN.hs", "max_stars_repo_name": "rzil/honours", "max_stars_repo_head_hexsha": "7f890698192fee2f7aae535835ebba569edb26d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-16T16:42:43.000Z", "max_issues_repo_path": "DeepLearning/PNN/PNN-Haskell/src/PNN.hs", "max_issues_repo_name": "rzil/honours", "max_issues_repo_head_hexsha": "7f890698192fee2f7aae535835ebba569edb26d2", "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": "DeepLearning/PNN/PNN-Haskell/src/PNN.hs", "max_forks_repo_name": "rzil/honours", "max_forks_repo_head_hexsha": "7f890698192fee2f7aae535835ebba569edb26d2", "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": 26.6324786325, "max_line_length": 95, "alphanum_fraction": 0.5856867779, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.46461016754150386}}
{"text": "{- |\nDescription :  Boundary mutation model Markov process\nCopyright   :  (c) Dominik Schrempf 2017\nLicense     :  GPLv3\n\nMaintainer  :  dominik.schrempf@gmail.com\nStability   :  unstable\nPortability :  non-portable (not tested)\n\nThis module defines the transition rate matrix of the boundary mutation model.\n\n-}\n\nmodule BndModel\n  ( BMModel(..)\n  , MutModel\n  , Heterozygosity\n  , createBMM\n  , createBMMNormalized\n  , scaleTreeToBMM\n  , getBMMInfoStr\n  ) where\n\nimport           BndState\nimport           Data.Maybe\nimport           DNAModel              hiding (rateMatrix)\nimport           Numeric.LinearAlgebra\nimport           RateMatrix            hiding (State)\nimport           RTree\nimport           Tools\n\n-- | The boundary mutation models uses an underlying mutation model.\ntype MutModel = DNAModel\n\n-- | Define a heterozygosity to make function definitions clearer.\ntype Heterozygosity = Double\n\n-- | A boundary mutation model is defined by its rate matrix. However, it is\n-- convenient to keep the underlying mutation model, the population size the\n-- heterozygosity and the stationary distribution at hand.\ndata BMModel = BMModel { bmmRateMatrix     :: RateMatrix\n                       , bmmMutModel       :: MutModel\n                       , bmmPopSize        :: PopSize\n                       , bmmHeterozygosity :: Heterozygosity\n                       , bmmStationaryDist :: StationaryDist }\n\n-- Get the mutation rate from one allele to another.\nmutRate :: MutModel -> Allele -> Allele -> Double\nmutRate (DNAModel m _) a b = m ! i ! j\n  where i = fromEnum a\n        j = fromEnum b\n\n-- Get state frequency for specific allele.\nstationaryFreq :: StationaryDist -> Allele -> Double\nstationaryFreq f a = f ! fromEnum a\n\n-- Calculate the rate of frequency shifts.\nmoranCoef :: PopSize -> Int -> Double\nmoranCoef n i = iD * (nD - iD) / nD\n  where iD = fromIntegral i\n        nD = fromIntegral n\n\n-- The transition rate from one boundary state to another.\nrate :: MutModel -> State -> State -> Double\nrate m s t\n  | not $ connected s t = 0.0\n  | otherwise           = rate' s t\n  where rate' (Ply n i _ _) _ = moranCoef n i\n        rate' (Bnd _ a) (Ply _ _ b c)\n          | a == b    = mutRate m a c\n          | a == c    = mutRate m a b\n          | otherwise = error \"Cannot compute rate between states.\"\n        rate' _ _ = error \"Cannot compute rate between states.\"\n\n-- The transition rate from one state (index) to another.\nrateById :: MutModel -> PopSize -> Int -> Int -> Double\nrateById m n i j = rate m s t\n  where s = idToState n i\n        t = idToState n j\n\n-- The build function (see below) has a weird way of assigning entries to\n-- indices. The indices have to be the same data type as the entries. This is\n-- just a helper function that changes the indices from Double to Int.\nrateByDouble :: MutModel -> PopSize -> Double -> Double -> Double\nrateByDouble m n x y = rateById m n (round x) (round y)\n\n-- The rate matrix of the boundary mutation model. The dimension with four\n-- alleles will be 4 + 6*(N-1).\nrateMatrix :: MutModel -> PopSize -> RateMatrix\nrateMatrix m n = setDiagonal $ build (s,s) (rateByDouble m n)\n  where s = stateSpaceSize n\n\n-- Normalize the rate matrix such that on average one event happens per unit\n-- time.\nnormalizedRateMatrix :: MutModel -> PopSize -> RateMatrix\nnormalizedRateMatrix m n = normalizeRates f' m'\n  where m' = rateMatrix m n\n        -- f  = dnaModelSpecGetStateFreqVec (dnaModelSpec m)\n        f' = stationaryDist m n\n\n-- Calculate the heterozygosity at stationarity.\ntheta :: MutModel -> Heterozygosity\ntheta (DNAModel m s) = f <.> rDiagZero #> f\n  where f         = dnaModelSpecGetStateFreqVec s\n        e         = toExchMatrix m f\n        (r, _)    = matrixSeparateSymSkew e\n        -- The summation excludes the diagonal (a /= b).\n        rDiagZero = matrixSetDiagToZero r\n\n-- The normalization constant of the stationary distribution.\nnorm :: MutModel -> PopSize -> Double\nnorm m n = 1.0 + harmonic (n-1) * theta m\n\n-- Get entries of the stationary measure (not normalized) for a boundary model state.\nstationaryMeasEntry :: MutModel -> State -> Double\nstationaryMeasEntry m s =\n  let f   = dnaModelSpecGetStateFreqVec (dnaModelSpec m) in\n  case s of\n    (Bnd _ a)     -> f ! fromEnum a\n    (Ply n i a b) -> piA * mAB / (fromIntegral n - fromIntegral i)\n                                      + piB * mBA / fromIntegral i\n      where piA = stationaryFreq f a\n            mAB = mutRate m a b\n            piB = stationaryFreq f b\n            mBA = mutRate m b a\n\nstationaryMeasEntryById :: MutModel -> PopSize -> Int -> Double\nstationaryMeasEntryById m n i = stationaryMeasEntry m s\n  where s = idToState n i\n\nstationaryMeasEntryByDouble :: MutModel -> PopSize -> Double -> Double\nstationaryMeasEntryByDouble m n x = stationaryMeasEntryById m n (round x)\n\n-- Get the stationary distribution of a boundary mutation model.\nstationaryDist :: MutModel -> PopSize -> StationaryDist\nstationaryDist m n = scale (1.0/norm m n) $\n  build s (stationaryMeasEntryByDouble m n)\n  where s = stateSpaceSize n\n\n-- Normalize the mutation coefficients such that the heterozygosity matches a\n-- given level (see Eq. 12.14 in my thesis).\nnormalizeToTheta :: MutModel -> PopSize -> Heterozygosity -> MutModel\nnormalizeToTheta mo@(DNAModel m _) n h =\n  mo { dnaRateMatrix = scale (h / (t * (1.0 - c * h))) m }\n  where\n    -- The heterozygosity of the boundary mutation model.\n    t = theta mo\n    -- The branch length multiplicative factor introduced by the coalescent.\n    c = harmonic (n-1)\n\n-- | Create a boundary mutation model using the minimal number of necessary\n-- ingredients.\ncreateBMM :: DNAModel -> PopSize -> Heterozygosity -> BMModel\ncreateBMM m n h = BMModel rm m' n h f\n  where m' = normalizeToTheta m n h\n        rm = normalizedRateMatrix m' n\n        f  = stationaryDist m n\n\n-- | Create a boundary mutation model without providing a heterozygosity. This\n-- means that the mutation model has to be normalized already.\ncreateBMMNormalized :: DNAModel -> PopSize -> BMModel\ncreateBMMNormalized m n = BMModel rm m n h f\n  where rm = normalizedRateMatrix m n\n        h  = theta m\n        f  = stationaryDist m n\n\n-- | The branch lengths of threes in the boundary mutation model are not\n-- measured in average number of substitutions per site but in average number of\n-- mutations or frequency shifts per site. The conversion factor is just the\n-- square of the population size. This function converts the branch lengths of a\n-- tree.\nscaleTreeToBMM :: BMModel -> RTree a Double -> RTree a Double\nscaleTreeToBMM bmm = fmap (* nSq)\n  where nSq = fromIntegral (bmmPopSize bmm) ** 2\n\n-- | Report the boundary mutation model specifications.\ngetBMMInfoStr :: BMModel\n              -> Maybe Double\n              -> Maybe [Double]\n              -> String\ngetBMMInfoStr bmm ma mrs = unlines $\n  [ \"Population size: \" ++ show (bmmPopSize bmm)\n  , \"Heterozygosity: \" ++ show (bmmHeterozygosity bmm)\n  , \"Mutation model:\"\n  , getDNAModelInfoStr (bmmMutModel bmm)\n  , \"Gamma rate heterogeneity: \" ++ show (isJust ma) ] ++\n  gammaShape ++ gammaMeans\n  where\n    gammaShape = maybe [] (\\a -> [\"Shape parameter: \" ++ show a]) ma\n    gammaMeans = maybe [] (\\rs -> [\"This corresponds to uniformly distributed rates: \" ++ show rs]) mrs\n", "meta": {"hexsha": "02cdc6b12fe5f6fff19fef98967ea92a83610351", "size": 7281, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/BndModel.hs", "max_stars_repo_name": "dschrempf/bmm-simulate", "max_stars_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-14T15:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T15:53:08.000Z", "max_issues_repo_path": "src/BndModel.hs", "max_issues_repo_name": "pomo-dev/bmm-simulate", "max_issues_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BndModel.hs", "max_forks_repo_name": "pomo-dev/bmm-simulate", "max_forks_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1204188482, "max_line_length": 103, "alphanum_fraction": 0.6710616674, "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.46443552603445704}}
{"text": "{-# OPTIONS_GHC -fno-warn-orphans #-}\n{-# LANGUAGE FlexibleInstances, OverlappingInstances, ScopedTypeVariables,\n    ViewPatterns #-}\nmodule Tests.Distribution (tests) where\n\nimport Control.Applicative ((<$), (<$>), (<*>))\nimport Data.Binary (Binary, decode, encode)\nimport Data.List (find)\nimport Data.Typeable (Typeable)\nimport Statistics.Distribution\nimport Statistics.Distribution.Beta (BetaDistribution, betaDistr)\nimport Statistics.Distribution.Binomial (BinomialDistribution, binomial)\nimport Statistics.Distribution.CauchyLorentz\nimport Statistics.Distribution.ChiSquared (ChiSquared, chiSquared)\nimport Statistics.Distribution.Exponential (ExponentialDistribution, exponential)\nimport Statistics.Distribution.FDistribution (FDistribution, fDistribution)\nimport Statistics.Distribution.Gamma (GammaDistribution, gammaDistr)\nimport Statistics.Distribution.Geometric\nimport Statistics.Distribution.Hypergeometric\nimport Statistics.Distribution.Normal (NormalDistribution, normalDistr)\nimport Statistics.Distribution.Poisson (PoissonDistribution, poisson)\nimport Statistics.Distribution.StudentT\nimport Statistics.Distribution.Transform (LinearTransform, linTransDistr)\nimport Statistics.Distribution.Uniform (UniformDistribution, uniformDistr)\nimport Test.Framework (Test, testGroup)\nimport Test.Framework.Providers.QuickCheck2 (testProperty)\nimport Test.QuickCheck as QC\nimport Test.QuickCheck.Monadic as QC\nimport Tests.ApproxEq (ApproxEq(..))\nimport Tests.Helpers (T(..), testAssertion, typeName)\nimport Tests.Helpers (monotonicallyIncreasesIEEE)\nimport Text.Printf (printf)\nimport qualified Control.Exception as E\nimport qualified Numeric.IEEE as IEEE\n\n\n-- | Tests for all distributions\ntests :: Test\ntests = testGroup \"Tests for all distributions\"\n  [ contDistrTests (T :: T BetaDistribution        )\n  , contDistrTests (T :: T CauchyDistribution      )\n  , contDistrTests (T :: T ChiSquared              )\n  , contDistrTests (T :: T ExponentialDistribution )\n  , contDistrTests (T :: T GammaDistribution       )\n  , contDistrTests (T :: T NormalDistribution      )\n  , contDistrTests (T :: T UniformDistribution     )\n  , contDistrTests (T :: T StudentT                )\n  , contDistrTests (T :: T (LinearTransform StudentT) )\n  , contDistrTests (T :: T FDistribution           )\n\n  , discreteDistrTests (T :: T BinomialDistribution       )\n  , discreteDistrTests (T :: T GeometricDistribution      )\n  , discreteDistrTests (T :: T GeometricDistribution0     )\n  , discreteDistrTests (T :: T HypergeometricDistribution )\n  , discreteDistrTests (T :: T PoissonDistribution        )\n\n  , unitTests\n  ]\n\n----------------------------------------------------------------\n-- Tests\n----------------------------------------------------------------\n\n-- Tests for continous distribution\ncontDistrTests :: (Param d, ContDistr d, QC.Arbitrary d, Typeable d, Show d, Binary d, Eq d) => T d -> Test\ncontDistrTests t = testGroup (\"Tests for: \" ++ typeName t) $\n  cdfTests t ++\n  [ testProperty \"PDF sanity\"              $ pdfSanityCheck     t\n  , testProperty \"Quantile is CDF inverse\" $ quantileIsInvCDF   t\n  , testProperty \"quantile fails p<0||p>1\" $ quantileShouldFail t\n  , testProperty \"log density check\"       $ logDensityCheck    t\n  ]\n\n-- Tests for discrete distribution\ndiscreteDistrTests :: (Param d, DiscreteDistr d, QC.Arbitrary d, Typeable d, Show d, Binary d, Eq d) => T d -> Test\ndiscreteDistrTests t = testGroup (\"Tests for: \" ++ typeName t) $\n  cdfTests t ++\n  [ testProperty \"Prob. sanity\"         $ probSanityCheck       t\n  , testProperty \"CDF is sum of prob.\"  $ discreteCDFcorrect    t\n  , testProperty \"Discrete CDF is OK\"   $ cdfDiscreteIsCorrect  t\n  , testProperty \"log probabilty check\" $ logProbabilityCheck   t\n  ]\n\n-- Tests for distributions which have CDF\ncdfTests :: (Param d, Distribution d, QC.Arbitrary d, Show d, Binary d, Eq d) => T d -> [Test]\ncdfTests t =\n  [ testProperty \"C.D.F. sanity\"        $ cdfSanityCheck         t\n  , testProperty \"CDF limit at +inf\"    $ cdfLimitAtPosInfinity  t\n  , testProperty \"CDF limit at -inf\"    $ cdfLimitAtNegInfinity  t\n  , testProperty \"CDF at +inf = 1\"      $ cdfAtPosInfinity       t\n  , testProperty \"CDF at -inf = 1\"      $ cdfAtNegInfinity       t\n  , testProperty \"CDF is nondecreasing\" $ cdfIsNondecreasing     t\n  , testProperty \"1-CDF is correct\"     $ cdfComplementIsCorrect t\n  , testProperty \"Binary OK\"            $ p_binary t\n  ]\n\n\n----------------------------------------------------------------\n\n-- CDF is in [0,1] range\ncdfSanityCheck :: (Distribution d) => T d -> d -> Double -> Bool\ncdfSanityCheck _ d x = c >= 0 && c <= 1\n  where c = cumulative d x\n\n-- CDF never decreases\ncdfIsNondecreasing :: (Distribution d) => T d -> d -> Double -> Double -> Bool\ncdfIsNondecreasing _ d = monotonicallyIncreasesIEEE $ cumulative d\n\n-- cumulative d +\u221e = 1\ncdfAtPosInfinity :: (Param d, Distribution d) => T d -> d -> Bool\ncdfAtPosInfinity _ d\n  = cumulative d (1/0) == 1\n\n-- cumulative d - \u221e = 0\ncdfAtNegInfinity :: (Param d, Distribution d) => T d -> d -> Bool\ncdfAtNegInfinity _ d\n  = cumulative d (-1/0) == 0\n\n-- CDF limit at +\u221e is 1\ncdfLimitAtPosInfinity :: (Param d, Distribution d) => T d -> d -> Property\ncdfLimitAtPosInfinity _ d =\n  okForInfLimit d ==> counterexample (\"Last elements: \" ++ show (drop 990 probs))\n                    $ Just 1.0 == (find (>=1) probs)\n  where\n    probs = take 1000 $ map (cumulative d) $ iterate (*1.4) 1000\n\n-- CDF limit at -\u221e is 0\ncdfLimitAtNegInfinity :: (Param d, Distribution d) => T d -> d -> Property\ncdfLimitAtNegInfinity _ d =\n  okForInfLimit d ==> counterexample (\"Last elements: \" ++ show (drop 990 probs))\n                    $ case find (< IEEE.epsilon) probs of\n                        Nothing -> False\n                        Just p  -> p >= 0\n  where\n    probs = take 1000 $ map (cumulative d) $ iterate (*1.4) (-1)\n\n-- CDF's complement is implemented correctly\ncdfComplementIsCorrect :: (Distribution d) => T d -> d -> Double -> Bool\ncdfComplementIsCorrect _ d x = (eq 1e-14) 1 (cumulative d x + complCumulative d x)\n\n-- CDF for discrete distribution uses <= for comparison\ncdfDiscreteIsCorrect :: (DiscreteDistr d) => T d -> d -> Property\ncdfDiscreteIsCorrect _ d\n  = counterexample (unlines badN)\n  $ null badN\n  where\n    -- We are checking that:\n    --\n    -- > CDF(i) - CDF(i-e) = P(i)\n    --\n    -- Apporixmate equality is tricky here. Scale is set by maximum\n    -- value of CDF and probability. Case when all proabilities are\n    -- zero should be trated specially.\n    badN = [ printf \"N=%3i    p[i]=%g\\tp[i+1]=%g\\tdP=%g\\trelerr=%g\" i p p1 dp ((p1-p-dp) / max p1 dp)\n           | i <- [0 .. 100]\n           , let p      = cumulative d $ fromIntegral i - 1e-6\n                 p1     = cumulative d $ fromIntegral i\n                 dp     = probability d i\n                 relerr = ((p1 - p) - dp) / max p1 dp\n           ,  not (p == 0 && p1 == 0 && dp == 0)\n           && relerr > 1e-14\n           ]\n\nlogDensityCheck :: (ContDistr d) => T d -> d -> Double -> Property\nlogDensityCheck _ d x\n  = counterexample (printf \"density    = %g\" p)\n  $ counterexample (printf \"logDensity = %g\" logP)\n  $ counterexample (printf \"log p      = %g\" (log p))\n  $ counterexample (printf \"eps        = %g\" (abs (logP - log p) / max (abs (log p)) (abs logP)))\n  $ or [ p == 0     && logP == (-1/0)\n       , p < 1e-308 && logP < 609\n       , eq 1e-14 (log p) logP\n       ]\n  where\n    p    = density d x\n    logP = logDensity d x\n\n-- PDF is positive\npdfSanityCheck :: (ContDistr d) => T d -> d -> Double -> Bool\npdfSanityCheck _ d x = p >= 0\n  where p = density d x\n\n-- Quantile is inverse of CDF\nquantileIsInvCDF :: (Param d, ContDistr d) => T d -> d -> Double -> Property\nquantileIsInvCDF _ d (snd . properFraction -> p) =\n  p > 0 && p < 1  ==> ( counterexample (printf \"Quantile     = %g\" q )\n                      $ counterexample (printf \"Probability  = %g\" p )\n                      $ counterexample (printf \"Probability' = %g\" p')\n                      $ counterexample (printf \"Error        = %e\" (abs $ p - p'))\n                      $ abs (p - p') < invQuantilePrec d\n                      )\n  where\n    q  = quantile   d p\n    p' = cumulative d q\n\n-- Test that quantile fails if p<0 or p>1\nquantileShouldFail :: (ContDistr d) => T d -> d -> Double -> Property\nquantileShouldFail _ d p =\n  p < 0 || p > 1 ==> QC.monadicIO $ do r <- QC.run $ E.catch\n                                              (False <$ (return $! quantile d p))\n                                              (\\(_ :: E.SomeException) -> return True)\n                                       QC.assert r\n\n\n-- Probability is in [0,1] range\nprobSanityCheck :: (DiscreteDistr d) => T d -> d -> Int -> Bool\nprobSanityCheck _ d x = p >= 0 && p <= 1\n  where p = probability d x\n\n-- Check that discrete CDF is correct\ndiscreteCDFcorrect :: (DiscreteDistr d) => T d -> d -> Int -> Int -> Property\ndiscreteCDFcorrect _ d a b\n  = counterexample (printf \"CDF   = %g\" p1)\n  $ counterexample (printf \"Sum   = %g\" p2)\n  $ counterexample (printf \"Delta = %g\" (abs (p1 - p2)))\n  $ abs (p1 - p2) < 3e-10\n  -- Avoid too large differeneces. Otherwise there is to much to sum\n  --\n  -- Absolute difference is used guard againist precision loss when\n  -- close values of CDF are subtracted\n  where\n    n  = min a b\n    m  = n + (abs (a - b) `mod` 100)\n    p1 = cumulative d (fromIntegral m + 0.5) - cumulative d (fromIntegral n - 0.5)\n    p2 = sum $ map (probability d) [n .. m]\n\nlogProbabilityCheck :: (DiscreteDistr d) => T d -> d -> Int -> Property\nlogProbabilityCheck _ d x\n  = counterexample (printf \"probability    = %g\" p)\n  $ counterexample (printf \"logProbability = %g\" logP)\n  $ counterexample (printf \"log p          = %g\" (log p))\n  $ counterexample (printf \"eps            = %g\" (abs (logP - log p) / max (abs (log p)) (abs logP)))\n  $ or [ p == 0     && logP == (-1/0)\n       , p < 1e-308 && logP < 609\n       , eq 1e-14 (log p) logP\n       ]\n  where\n    p    = probability d x\n    logP = logProbability d x\n\n\np_binary :: (Eq a, Show a, Binary a) => T a -> a -> Bool\np_binary _ a = a == (decode . encode) a\n\n\n\n----------------------------------------------------------------\n-- Arbitrary instances for ditributions\n----------------------------------------------------------------\n\ninstance QC.Arbitrary BinomialDistribution where\n  arbitrary = binomial <$> QC.choose (1,100) <*> QC.choose (0,1)\ninstance QC.Arbitrary ExponentialDistribution where\n  arbitrary = exponential <$> QC.choose (0,100)\ninstance QC.Arbitrary GammaDistribution where\n  arbitrary = gammaDistr <$> QC.choose (0.1,10) <*> QC.choose (0.1,10)\ninstance QC.Arbitrary BetaDistribution where\n  arbitrary = betaDistr <$> QC.choose (1e-3,10) <*> QC.choose (1e-3,10)\ninstance QC.Arbitrary GeometricDistribution where\n  arbitrary = geometric <$> QC.choose (0,1)\ninstance QC.Arbitrary GeometricDistribution0 where\n  arbitrary = geometric0 <$> QC.choose (0,1)\ninstance QC.Arbitrary HypergeometricDistribution where\n  arbitrary = do l <- QC.choose (1,20)\n                 m <- QC.choose (0,l)\n                 k <- QC.choose (1,l)\n                 return $ hypergeometric m l k\ninstance QC.Arbitrary NormalDistribution where\n  arbitrary = normalDistr <$> QC.choose (-100,100) <*> QC.choose (1e-3, 1e3)\ninstance QC.Arbitrary PoissonDistribution where\n  arbitrary = poisson <$> QC.choose (0,1)\ninstance QC.Arbitrary ChiSquared where\n  arbitrary = chiSquared <$> QC.choose (1,100)\ninstance QC.Arbitrary UniformDistribution where\n  arbitrary = do a <- QC.arbitrary\n                 b <- QC.arbitrary `suchThat` (/= a)\n                 return $ uniformDistr a b\ninstance QC.Arbitrary CauchyDistribution where\n  arbitrary = cauchyDistribution\n                <$> arbitrary\n                <*> ((abs <$> arbitrary) `suchThat` (> 0))\ninstance QC.Arbitrary StudentT where\n  arbitrary = studentT <$> ((abs <$> arbitrary) `suchThat` (>0))\ninstance QC.Arbitrary (LinearTransform StudentT) where\n  arbitrary = studentTUnstandardized\n           <$> ((abs <$> arbitrary) `suchThat` (>0))\n           <*> ((abs <$> arbitrary))\n           <*> ((abs <$> arbitrary) `suchThat` (>0))\ninstance QC.Arbitrary FDistribution where\n  arbitrary =  fDistribution\n           <$> ((abs <$> arbitrary) `suchThat` (>0))\n           <*> ((abs <$> arbitrary) `suchThat` (>0))\n\n\n\n-- Parameters for distribution testing. Some distribution require\n-- relaxing parameters a bit\nclass Param a where\n  -- Precision for quantileIsInvCDF\n  invQuantilePrec :: a -> Double\n  invQuantilePrec _ = 1e-14\n  -- Distribution is OK for testing limits\n  okForInfLimit :: a -> Bool\n  okForInfLimit _ = True\n\n\ninstance Param a\n\ninstance Param StudentT where\n  invQuantilePrec _ = 1e-13\n  okForInfLimit   d = studentTndf d > 0.75\n\ninstance Param (LinearTransform StudentT) where\n  invQuantilePrec _ = 1e-13\n  okForInfLimit   d = (studentTndf . linTransDistr) d > 0.75\n\ninstance Param FDistribution where\n  invQuantilePrec _ = 1e-12\n\n\n\n----------------------------------------------------------------\n-- Unit tests\n----------------------------------------------------------------\n\nunitTests :: Test\nunitTests = testGroup \"Unit tests\"\n  [ testAssertion \"density (gammaDistr 150 1/150) 1 == 4.883311\" $\n      4.883311418525483 =~ (density (gammaDistr 150 (1/150)) 1)\n    -- Student-T\n  , testStudentPDF 0.3  1.34  0.0648215  -- PDF\n  , testStudentPDF 1    0.42  0.27058\n  , testStudentPDF 4.4  0.33  0.352994\n  , testStudentCDF 0.3  3.34  0.757146   -- CDF\n  , testStudentCDF 1    0.42  0.626569\n  , testStudentCDF 4.4  0.33  0.621739\n    -- Student-T General\n  , testStudentUnstandardizedPDF 0.3    1.2  4      0.45 0.0533456  -- PDF\n  , testStudentUnstandardizedPDF 4.3  (-2.4) 3.22 (-0.6) 0.0971141\n  , testStudentUnstandardizedPDF 3.8    0.22 7.62   0.14 0.0490523\n  , testStudentUnstandardizedCDF 0.3    1.2  4      0.45 0.458035   -- CDF\n  , testStudentUnstandardizedCDF 4.3  (-2.4) 3.22 (-0.6) 0.698001\n  , testStudentUnstandardizedCDF 3.8    0.22 7.62   0.14 0.496076\n    -- F-distribution\n  , testFdistrPDF  1  3   3     (1/(6 * pi)) -- PDF\n  , testFdistrPDF  2  2   1.2   0.206612\n  , testFdistrPDF  10 12  8     0.000385613179281892790166\n  , testFdistrCDF  1  3   3     0.81830988618379067153 -- CDF\n  , testFdistrCDF  2  2   1.2   0.545455\n  , testFdistrCDF  10 12  8     0.99935509863451408041\n  ]\n  where\n    -- Student-T\n    testStudentPDF ndf x exact\n      = testAssertion (printf \"density (studentT %f) %f ~ %f\" ndf x exact)\n      $ eq 1e-5  exact  (density (studentT ndf) x)\n    testStudentCDF ndf x exact\n      = testAssertion (printf \"cumulative (studentT %f) %f ~ %f\" ndf x exact)\n      $ eq 1e-5  exact  (cumulative (studentT ndf) x)\n    -- Student-T General\n    testStudentUnstandardizedPDF ndf mu sigma x exact\n      = testAssertion (printf \"density (studentTUnstandardized %f %f %f) %f ~ %f\" ndf mu sigma x exact)\n      $ eq 1e-5  exact  (density (studentTUnstandardized ndf mu sigma) x)\n    testStudentUnstandardizedCDF ndf mu sigma x exact\n      = testAssertion (printf \"cumulative (studentTUnstandardized %f %f %f) %f ~ %f\" ndf mu sigma x exact)\n      $ eq 1e-5  exact  (cumulative (studentTUnstandardized ndf mu sigma) x)\n    -- F-distribution\n    testFdistrPDF n m x exact\n      = testAssertion (printf \"density (fDistribution %i %i) %f ~ %f [got %f]\" n m x exact d)\n      $ eq 1e-5  exact d\n      where d = density (fDistribution n m) x\n    testFdistrCDF n m x exact\n      = testAssertion (printf \"cumulative (fDistribution %i %i) %f ~ %f [got %f]\" n m x exact d)\n      $ eq 1e-5  exact d\n      where d = cumulative (fDistribution n m) x\n", "meta": {"hexsha": "b2ff38dda36ad1cf6271563b9b3e9a9e7d44623a", "size": 15567, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Tests/Distribution.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "tests/Tests/Distribution.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Tests/Distribution.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4015957447, "max_line_length": 115, "alphanum_fraction": 0.62375538, "num_tokens": 4596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4642434924644378}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n-- | Mixed-radix FFT calculation.\n--\n-- Arbitrary input vector lengths are handled using a mixed-radix\n-- Cooley-Tukey decimation in time algorithm with residual prime\n-- length vectors being treated using Rader's algorithm or hand-coded\n-- codelets for small primes.\nmodule Numeric.FFT\n       ( fft, ifft, fftWith, ifftWith\n       , plan, planFromFactors, execute\n       , Plan (..), Direction (..), BaseTransform (..)\n       ) where\n\nimport Prelude hiding (length, map, sum, zipWith)\nimport Data.Vector.Generic\nimport Data.Complex\n\nimport Numeric.FFT.Types\nimport Numeric.FFT.Plan\nimport Numeric.FFT.Execute\n\n\n-- | Forward FFT with embedded plan calculation.  For an input vector\n-- /h/ of length /N/, with entries numbered from 0 to /N - 1/,\n-- calculates the entries in /H/, the discrete Fourier transform of\n-- /h/, as:\n--\n-- <<doc-formulae/fft-formula.svg>>\nfft :: Vector v (Complex Double) =>\n       v (Complex Double) -> IO (v (Complex Double))\nfft xs = do\n  p <- plan $ length xs\n  return $ fftWith p xs\n\n-- | Inverse FFT with embedded plan calculation.  For an input vector\n-- /H/ of length /N/, with entries numbered from 0 to /N - 1/,\n-- representing Fourier amplitudes of a signal, calculates the entries\n-- in /h/, the inverse discrete Fourier transform of /H/, as:\n--\n-- <<doc-formulae/ifft-formula.svg>>\nifft :: Vector v (Complex Double) =>\n        v (Complex Double) -> IO (v (Complex Double))\nifft xs = do\n  p <- plan $ length xs\n  return $ ifftWith p xs\n\n-- | Forward FFT with pre-computed plan.\nfftWith :: Vector v (Complex Double) =>\n           Plan -> v (Complex Double) -> v (Complex Double)\nfftWith p = convert . execute p Forward . convert\n\n-- | Inverse FFT with pre-computed plan.\nifftWith :: Vector v (Complex Double) =>\n            Plan -> v (Complex Double) -> v (Complex Double)\nifftWith p = convert . execute p Inverse . convert\n", "meta": {"hexsha": "0c06ce138ecc1eee8337d901e699adbff1825ad6", "size": 1894, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/FFT.hs", "max_stars_repo_name": "ian-ross/arb-fft", "max_stars_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-06-15T09:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-08T13:14:27.000Z", "max_issues_repo_path": "Numeric/FFT.hs", "max_issues_repo_name": "ian-ross/arb-fft", "max_issues_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-03-08T20:31:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T20:32:09.000Z", "max_forks_repo_path": "Numeric/FFT.hs", "max_forks_repo_name": "ian-ross/arb-fft", "max_forks_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-11-25T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-06T22:54:26.000Z", "avg_line_length": 33.8214285714, "max_line_length": 70, "alphanum_fraction": 0.6800422386, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46407483497469076}}
{"text": "\n{-# LANGUAGE DuplicateRecordFields     #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE RankNTypes                #-}\n{-# LANGUAGE ScopedTypeVariables       #-}\n{-# LANGUAGE TemplateHaskell           #-}\n\nmodule Minimizer(module Minimizer) where\n\nimport           Brain\nimport           Control.Arrow\nimport           Control.Lens\nimport           Control.Monad.Random\nimport           Convenience\nimport qualified Data.Vector.Storable           as V\nimport           GHC.TypeLits\nimport           Numeric.GSL.Minimization\nimport           Numeric.GSL.SimulatedAnnealing\nimport           Simulator\nimport qualified Graphics.Rendering.Chart.Easy  as E\nimport qualified Graphics.Rendering.Chart.Gtk   as C\nimport           Numeric.LinearAlgebra.Data\nimport           System.IO.Unsafe\nimport qualified Numeric.AD as AD\n\ntype Minimizer n = (forall a. Floating a => Weights n a -> a) -> Weights n Double -> Weights n Double\n\n\nnewtype NelderMeadsParams = NelderMeadsParams Int\n\ninstance Default NelderMeadsParams where\n  auto = NelderMeadsParams 1000\n\n\ninstance Default SimulatedAnnealingParams where\n  auto = SimulatedAnnealingParams 100 100 1.0 1.0 100 1.5 10\n\n\nnewtype AutoDiffParams = AutoDiffParams Int\n\ninstance Default AutoDiffParams where\n  auto = AutoDiffParams 10\n\n\ndata MinSettings = Annealing SimulatedAnnealingParams | NelderMeads NelderMeadsParams | AutoDiff AutoDiffParams\n\n\ninstance Default MinSettings where\n  auto = AutoDiff auto\n\n\ndata Settings = Settings {\n    _minSettings      :: MinSettings,\n    _seed             :: Int,\n    _systems          :: Int,\n    _groupedBy        :: Int,\n    _iterRange        :: (Int,Int),\n    _numMinimizations :: Int\n}\nmakeLenses ''Settings\n\ninstance Default Settings where\n  auto = Settings {\n    _minSettings = auto,\n    _seed = 4374653543,\n    _systems = 3,\n    _groupedBy = 30,\n    _iterRange = (400,400),\n    _numMinimizations = 5\n  }\n\ndata NeuralSim system enabled all f = NeuralSim {\n    _settings   :: Settings,\n    _weights    :: Weights enabled f,\n    _restorer   :: Restorer enabled all f,\n    _setWeights :: forall a . Floating a => Weights enabled a -> system a -> system a\n}\nmakeLenses ''NeuralSim\n\nminimizeS :: (KnownNat n) => NelderMeadsParams -> Minimizer n\nminimizeS (NelderMeadsParams iterations) cost xi =\n  minimizeV NMSimplex2 0.0001 iterations (V.replicate (ssize xi) 0.2) (fromVec &. cost) (toVec xi)\n  -- & chartify\n  & fst & fromVec\n\nchartify :: (a, Matrix Double) -> (a, ())\nchartify = second (toColumns &. (!!1)\n            &. Numeric.LinearAlgebra.Data.toList\n            &. zip [1::Int ..]\n            &. (:[]) &. E.line \"30\" &. E.plot\n            &. C.toWindow 500 500 &. unsafePerformIO)\n            &. (\\t -> seq (snd t) t)\n\nannealing :: (KnownNat n) => SimulatedAnnealingParams -> Minimizer n\nannealing anParams cost xi = simanSolve 123 (ssize xi) anParams xi cost metricDist stepFunction (Just $ const \"\")\n  where metricDist a1 a2 = sZipWith (\\x1 x2 -> (x1-x2)*(x1-x2)) a1 a2 & ssum & sqrt\n        stepFunction rands stepSize current = rands & fromVec &> (\\x -> x*2*stepSize - stepSize) & sZipWith (+) current\n\n\nautomaticDiff :: (KnownNat n) => AutoDiffParams -> Minimizer n\nautomaticDiff (AutoDiffParams iterations) cost (Sized weights) = AD.conjugateGradientDescent (Sized &. cost) weights & take iterations & last & Sized\n\ntoMinimizer :: KnownNat n => MinSettings -> Minimizer n\ntoMinimizer (NelderMeads pars) = minimizeS pars\ntoMinimizer (Annealing pars)   = annealing pars\ntoMinimizer (AutoDiff pars)    = automaticDiff pars\n\nminimizer :: (KnownNat all,KnownNat enabled,Simulator system) => NeuralSim system enabled all Double -> IO ()\nminimizer n = print (evalRand (minimizeRand n) (mkStdGen $ n^.settings.seed))\n\n\nminimizeRand :: (KnownNat all, KnownNat enabled, Simulator system) =>\n                    NeuralSim system enabled all Double -> Rand StdGen ([(Double,Double)], Weights all Double)\nminimizeRand n = composeN (n^.settings.numMinimizations) episodic ([], n^.weights)\n                 &> second (n^.restorer)\n  where\n    episodic (costs,weights) =\n      episodicM (toMinimizer (n^.settings.minSettings)) (n^.settings) (n^.setWeights) weights\n      &> first (:costs)\n\n\nepisodicM :: forall s enabled. (Simulator s)\n          => Minimizer enabled\n          -> Settings \n          -> (forall a . (Floating a) => Weights enabled a -> s a -> s a)\n          -> Weights enabled Double\n          -> Rand StdGen ((Double,Double), Weights enabled Double)\nepisodicM optimizer settins weightSetter initialWeights = do\n  iters <- getRandomR (settins^.iterRange)\n  randSystems <- getRandoms &> take (settins^.systems)\n\n  let episodeSize = settins^.groupedBy\n\n  let simsEpisode :: Floating a => [s a] -> [s a]\n      simsEpisode = apply episodeSize simsStep\n\n  let episodes = iters `div` episodeSize\n\n  let episodedSystems :: Floating a => [[s a]]\n      episodedSystems = randSystems\n                        &> realToFracSim\n                        &  iterate simsEpisode\n                        &  take episodes\n\n  let costOfWeights :: (Floating a) => Weights enabled a -> a\n      costOfWeights ws = episodedSystems\n                         &>>weightSetter ws\n                         &> simsEpisode\n                         &> simsCost\n                         &  sum\n\n  let resultWeights = optimizer costOfWeights initialWeights\n  return ((costOfWeights initialWeights,costOfWeights resultWeights), resultWeights)\n\n\n-- inputRecreator :: _ => Brain n n numWeights -> Minimizer numWeights -> g (Weights numWeights)\n-- inputRecreator (Brain feed) optimizer =\n--   getRandoms &>> randWeights\n--              &> (\\inputs -> optimizer (\\w -> let outputs = inputs &> feed w\n--                                              in zipWith hamming inputs outputs & sum)\n--                                       (randWeights 23423))\n--   where\n--     hamming :: Weights n -> Weights n -> Double\n--     hamming w1 w2 = sZipWith (\\x y -> (x-y)**2) w1 w2 & sum\n", "meta": {"hexsha": "bc724bece99f8a341cbf76b7923ebddbfb95a59a", "size": 5940, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Minimizer.hs", "max_stars_repo_name": "bmabsout/neural-swarm", "max_stars_repo_head_hexsha": "8b5ce288ced6f0c6700a515c52aec561c680fe03", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-11-29T08:58:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T03:52:00.000Z", "max_issues_repo_path": "src/Minimizer.hs", "max_issues_repo_name": "bmabsout/neural-swarm", "max_issues_repo_head_hexsha": "8b5ce288ced6f0c6700a515c52aec561c680fe03", "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/Minimizer.hs", "max_forks_repo_name": "bmabsout/neural-swarm", "max_forks_repo_head_hexsha": "8b5ce288ced6f0c6700a515c52aec561c680fe03", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0, "max_line_length": 149, "alphanum_fraction": 0.6439393939, "num_tokens": 1538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126792, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46407482251985827}}
{"text": "module STCR2Z2T0S0EdgeBinary where\n\nimport           Control.Arrow\nimport           Control.Monad\nimport           Data.Array.Repa         as R\nimport           Data.Binary             (encodeFile, decodeFile)\nimport           Data.Complex\nimport           Data.List               as L\nimport           DFT.Plan\nimport           Filter.Utils\nimport           FokkerPlanck.MonteCarlo\nimport           FokkerPlanck.Pinwheel\nimport           Image.Edge\nimport           Image.IO\nimport           STC\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Text.Printf\nimport           Types\nimport           Utils.Array\nimport           Utils.Parallel\n\n\nmain = do\n  args@(numPointStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:taoStr:numTrailStr:maxTrailStr:thetaFreqsStr:scaleFreqsStr:hollowRadiusStr:cutoffRadiusStr:histFilePath:filterFileFolder:numIterationStr:writeSourceFlagStr:saveEdgeDataFlagStr:loadEdgeDataFlagStr:edgeFilePath:numNoisePointStr:scaleFactorStr:useFFTWWisdomFlagStr:fftwWisdomFileName:batchSizeStr:numThreadStr:_) <-\n    getArgs\n  print args\n  let numPoint = read numPointStr :: Int\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      maxScale = read maxScaleStr :: Double\n      tao = read taoStr :: Double\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      thetaFreq = read thetaFreqsStr :: Double\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      scaleFreq = read scaleFreqsStr :: Double\n      scaleFreqs = [-scaleFreq .. scaleFreq]\n      hollowRadius = read hollowRadiusStr :: Double\n      cutoffRadius = read cutoffRadiusStr :: Double\n      numIteration = read numIterationStr :: Int\n      writeSourceFlag = read writeSourceFlagStr :: Bool\n      saveEdgeDataFlag = read saveEdgeDataFlagStr :: Bool\n      loadEdgeDataFlag = read loadEdgeDataFlagStr :: Bool\n      numNoisePoint = read numNoisePointStr :: Int\n      scaleFactor = read scaleFactorStr :: Double\n      useFFTWWisdomFlag = read useFFTWWisdomFlagStr :: Bool\n      batchSize = read batchSizeStr :: Int\n      numThread = read numThreadStr :: Int\n      parallelParams = ParallelParams numThread batchSize\n      folderPath = \"output/test/STCR2Z2T0S0EdgeBinary\"\n      fftwWisdomFilePath = folderPath </> fftwWisdomFileName\n      filterFileName =\n        printf\n          \"Filter_%.0f_%.0f_%s\"\n          hollowRadius\n          cutoffRadius\n          (takeFileName histFilePath)\n      filterFilePath = filterFileFolder </> filterFileName\n      biasFilePath =\n        printf\n          \"%s/Bias_%s_%d.dat\"\n          filterFileFolder\n          (takeBaseName edgeFilePath)\n          numNoisePoint\n      eigenVecFilePath =\n        printf\n          \"%s/EigenVec_%s_%d.dat\"\n          filterFileFolder\n          (takeBaseName edgeFilePath)\n          numNoisePoint\n  createDirectoryIfMissing True folderPath\n  createDirectoryIfMissing True filterFileFolder\n  plan <-\n    makePlanBinary\n      emptyPlan\n      useFFTWWisdomFlag\n      fftwWisdomFilePath\n      (L.length thetaFreqs)\n      (L.length scaleFreqs)\n      numPoint\n      numPoint\n  filterFlag <- doesFileExist filterFilePath\n  flag <-\n    if filterFlag\n      then do\n        size <- getFileSize filterFilePath\n        return $\n          if size == 0\n            then False\n            else True\n      else return False\n  unless\n    flag\n    (do histFlag <- doesFileExist histFilePath\n        radialArr <-\n          if histFlag\n            then R.map magnitude . getNormalizedHistogramArr <$>\n                 decodeFile histFilePath\n            else do\n              putStrLn\n                \"Couldn't find a Green's function data. Start simulation...\"\n              solveMonteCarloR2Z2T0S0Radial\n                numThread\n                numTrail\n                maxTrail\n                numPoint\n                numPoint\n                thetaSigma\n                scaleSigma\n                maxScale\n                tao\n                thetaFreqs\n                thetaFreqs\n                scaleFreqs\n                scaleFreqs\n                histFilePath\n                (emptyHistogram\n                   [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n                   , L.length scaleFreqs\n                   , L.length thetaFreqs\n                   , L.length scaleFreqs\n                   , L.length thetaFreqs\n                   ]\n                   0)\n        putStrLn \"Write filter to disk...\"\n        writeDFTPinwheel\n          parallelParams\n          plan\n          radialArr\n          hollowRadius\n          cutoffRadius\n          thetaFreqs\n          scaleFreqs\n          maxScale\n          (numPoint, numPoint)\n          filterFilePath)\n  (bias, eigenVec) <-\n    if loadEdgeDataFlag\n      then do\n        bias <- readRepaArray biasFilePath\n        eigenVec <- readRepaArray eigenVecFilePath\n        return (bias, eigenVec)\n      else do\n        xs <- parseEdgeFile edgeFilePath\n        randomPonintSet <-\n          generateRandomPointSet numNoisePoint numPoint numPoint\n        let (centerX, centerY) =\n              join (***) (\\x -> div x . L.length $ xs) .\n              L.foldl'\n                (\\(a, b) (R2S1RPPoint (c, d, _, _)) -> (a + c, b + d))\n                (0, 0) $\n              xs\n            ys =\n              L.map\n                (\\(R2S1RPPoint (a, b, c, d)) ->\n                   (R2S1RPPoint\n                      ( round $ (fromIntegral $ a - centerX) / scaleFactor\n                      , round $ (fromIntegral $ b - centerX) / scaleFactor\n                      , c\n                      , d)))\n                xs\n            zs =\n              L.map\n                (\\(R2S1RPPoint (a, b, c, d)) ->\n                   (R2S1RPPoint (a - center numPoint, b - center numPoint, c, d)))\n                randomPonintSet\n            points = ys L.++ zs\n        let bias =\n              computeBiasR2T0S0 numPoint numPoint thetaFreqs scaleFreqs points\n            eigenVec =\n              computeInitialEigenVectorBinary\n                numPoint\n                numPoint\n                thetaFreqs\n                scaleFreqs\n                points\n        when saveEdgeDataFlag (writeRepaArray biasFilePath bias)\n        return (bias, eigenVec)\n  powerMethodBinary\n    parallelParams\n    plan\n    folderPath\n    numPoint\n    numPoint\n    numOrientation\n    thetaFreqs\n    numScale\n    scaleFreqs\n    maxScale\n    filterFilePath\n    numIteration\n    writeSourceFlag\n    (printf\n       \"_%.2f_%.2f_%d_%d_%d_%d\"\n       thetaSigma\n       scaleSigma\n       (round maxScale :: Int)\n       (round tao :: Int)\n       (round thetaFreq :: Int)\n       (round scaleFreq :: Int))\n    saveEdgeDataFlag\n    eigenVecFilePath\n    bias\n    eigenVec\n", "meta": {"hexsha": "ad08fa2986b5fa4006a994337da4be150d8e41ad", "size": 6874, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2Z2T0S0EdgeBinary/STCR2Z2T0S0EdgeBinary.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/STCR2Z2T0S0EdgeBinary/STCR2Z2T0S0EdgeBinary.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/STCR2Z2T0S0EdgeBinary/STCR2Z2T0S0EdgeBinary.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 32.8899521531, "max_line_length": 402, "alphanum_fraction": 0.5740471341, "num_tokens": 1642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4640748150469582}}
{"text": "{-# LANGUAGE FlexibleContexts     #-}\n{-# LANGUAGE InstanceSigs         #-}\n{-# LANGUAGE TypeFamilies         #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule AI.Network.SOM\n( SOM(..)\n, MapDefinition(..)\n\n, randomNeuron\n, makeVectors\n, reshapeList\n, distance\n) where\n\nimport           AI.Layer\nimport           AI.Network\nimport           AI.Neuron\n\nimport           Numeric.LinearAlgebra\nimport           System.Random\n\n-- | The SOM definition is simple, it only contains a 2-dimensional list of weights\ndata SOM = SOM { neuronMap :: [[Vector Double]] }\n\n-- | A definitution type for the SOM, it contains the dimensions of each layer (x, y)\n--   and the dimension of the input vector (dim)\ndata MapDefinition = MapDefinition { x        :: Int\n                                   , y        :: Int\n                                   , inputDim :: Int\n                                   }\n\ninstance Network SOM where\n  type Parameters SOM g = MapDefinition\n\n  predict :: Vector Double -> SOM -> Vector Double\n  predict inputs network = inputs\n\n  -- | Create a SOM and initialize it with given weights\n  createNetwork :: (RandomGen g) => RandomTransform -> g -> Parameters SOM g -> SOM\n  createNetwork transformation g def = SOM randomVectors\n    where randomVectors = reshapeList (x def) $\n                          makeVectors transformation g (inputDim def)\n                          (x def * y def)\n\n-- | A helper function to reshape a 1D list into a 2D list\nreshapeList :: Int -> [a] -> [[a]]\nreshapeList x [] = [[]]\nreshapeList x lst = h : reshapeList x t\n  where (h, t) = splitAt x lst\n\n-- | Create a random set of weights for a given neuron\nrandomNeuron :: (RandomGen g) => RandomTransform -> g -> Int -> Vector Double\nrandomNeuron transform g inputDim = inputDim |> randomList transform g\n\n-- | Make a 1D list of vectors to be used by the SOM in creating a map of weights\nmakeVectors :: (RandomGen g) => RandomTransform -> g -> Int -> Int -> [Vector Double]\nmakeVectors transform g inputDim 0 = []\nmakeVectors transform g inputDim num = randomNeuron transform g' inputDim :\n                                       makeVectors transform g'' inputDim (num - 1)\n  where (g', g'') = split g\n\n-- | Calculate the distance between a SOM neuron and an input\ndistance :: Vector Double -> Vector Double -> Double\ndistance a b = sqrt $ sum $ map (^2) $ zipWith (-) (toList a) (toList b)\n", "meta": {"hexsha": "70ab953ef0e32c65c98f18a35f5f5a8ec9756b70", "size": 2382, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "AI/Network/SOM.hs", "max_stars_repo_name": "jbarrow/LambdaNet", "max_stars_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 308, "max_stars_repo_stars_event_min_datetime": "2015-01-01T01:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:03:18.000Z", "max_issues_repo_path": "AI/Network/SOM.hs", "max_issues_repo_name": "jbarrow/LambdaNet", "max_issues_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2015-05-23T20:39:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-29T17:04:47.000Z", "max_forks_repo_path": "AI/Network/SOM.hs", "max_forks_repo_name": "jbarrow/LambdaNet", "max_forks_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2015-01-01T07:14:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:33:41.000Z", "avg_line_length": 36.0909090909, "max_line_length": 85, "alphanum_fraction": 0.6221662469, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4640041110418581}}
{"text": "{-# LANGUAGE BangPatterns #-}\n\nmodule School.Types.Decoding\n( binToDouble\n, binToInt\n, getDouble\n, getInt\n, binToMatrixDouble\n, binToListInt\n, runGet\n) where\n\nimport Control.Monad (replicateM)\nimport Data.ByteString (ByteString, length, splitAt, unpack)\nimport Data.Int (Int32)\nimport Data.Serialize.Get (Get, getInt32be, runGet)\nimport Data.Serialize.IEEE754 (getFloat64be)\nimport Numeric.LinearAlgebra ((><), Matrix, I, R)\nimport Prelude hiding (length, splitAt)\nimport School.Types.DataType (DataType(..))\nimport School.Types.Error (Error)\n\ngetDouble :: Get R\ngetDouble = getFloat64be\n\nbinToDouble :: ByteString -> Either Error R\nbinToDouble = runGet getDouble\n\nbinToMatrixDouble :: DataType\n                  -> Int\n                  -> Int\n                  -> (ByteString -> Either Error\n                                           (Matrix R))\nbinToMatrixDouble DBL64B nRows nCols =\n  runGet (getDoubleMatrixDouble nRows nCols)\nbinToMatrixDouble INT08B nRows nCols =\n   Right\n . (nRows >< nCols)\n . map (fromIntegral . fromEnum)\n . unpack\nbinToMatrixDouble dType _ _ = const . Left $\n  \"Decoding to Matrix Double undefined for \" ++ show dType\n\ngetDoubleMatrixDouble :: Int\n                      -> Int\n                      -> Get (Matrix Double)\ngetDoubleMatrixDouble nRows nCols = do\n  let nElements = nRows * nCols\n  list <- replicateM nElements getDouble\n  return $ (nRows >< nCols) list\n\ngetInt :: Get Int32\ngetInt = getInt32be\n\nbinToInt :: ByteString -> Either Error I\nbinToInt = fmap fromIntegral . runGet getInt\n\nbinToListInt :: DataType\n             -> (ByteString -> Either Error [Int])\nbinToListInt DBL64B = const . Left $\n  \"Reject conversion from floating point DBL64B to integral\"\nbinToListInt INT32B = loop [] where\n  loop acc bytes = let len = length bytes in\n    if len < 4\n      then return acc\n      else do\n        let !(next, current) = splitAt (len - 4) bytes\n        int <- fromIntegral <$> binToInt current\n        loop (int:acc) next\nbinToListInt INT08B =\n    Right\n  . map (fromIntegral . fromEnum)\n  . unpack\n", "meta": {"hexsha": "b8e740e0b64664e3a9afd31b69b043dd79e45d59", "size": 2041, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/School/Types/Decoding.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/School/Types/Decoding.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/School/Types/Decoding.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5810810811, "max_line_length": 60, "alphanum_fraction": 0.6702596766, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.4639159027960553}}
{"text": "\nmodule PCA.QModels where\n\nimport PCA.Distribution\nimport Numeric.LinearAlgebra.Data\n       (Matrix, Vector, ident, konst, size, toRows, fromRows, diag, diagl,\n        takeDiag)\nimport qualified Numeric.LinearAlgebra.HMatrix as H\n\n\ninitQtau :: Distr Double Double\ninitQtau = Gamma 1.0e-3 1.0e-3\n\ninitQmu :: Int -> Distr (Vector Double) (Matrix Double)\ninitQmu d = MNormal (konst 0 d) (ident d)\n\ninitQalpha :: Int -> Distr (Vector Double) (Vector Double)\ninitQalpha d = MGamma (konst 1.0e-3 d) (konst 1.0e-3 d)\n\ninitQW :: Int -> Distr (Matrix Double) (Matrix Double)\ninitQW d = MatrixMNormal (ident d) (ident d)\n\ninitQX :: Matrix Double -> Distr (Matrix Double) (Matrix Double)\ninitQX trainT = let (_, d) = size trainT\n                    sigmaX = calcSigmaX d initQtau (initQW d)\n                    mX = calcMX trainT initQtau sigmaX (initQW d) (initQmu d)\n                in MatrixMNormal mX sigmaX\n\ntype QModel = (Matrix Double, Vector Double)  -- ^ Mode of W and \\mu\n\ncalculateQ :: Matrix Double -> QModel\ncalculateQ trainT =\n    go 5 initQtau (initQmu d) (initQalpha d) (initQW d) (initQX trainT) trainT\n  where\n    (n,d) = size trainT\n    go 0 _ mu _ w _ _ = (mean w, mean mu)\n    go k (Gamma aTau bTau) mu (MGamma aAlpha bAlpha) w x t =\n        go (k - 1) ntau nmu nalpha nw nx t\n      where\n        ntau = Gamma (calcAtau n d aTau) (calcBtau bTau t mu w x)\n        nalpha = MGamma (calcAalpha d aAlpha) (calcBalpha bAlpha w)\n        nSigmaMu = calcSigmaMu n ntau mu\n        nmu = MNormal (calcMMu t ntau nSigmaMu w x) nSigmaMu\n        nSigmaW = calcSigmaW ntau nalpha x\n        nw = MatrixMNormal (calcMW ntau nSigmaW x t nmu) nSigmaW\n        nSigmaX = calcSigmaX d ntau nw\n        nx = MatrixMNormal (calcMX t ntau nSigmaX nw nmu) nSigmaX\n\n\ncalcSigmaX\n    :: Int\n    -> Distr Double Double\n    -> Distr (Matrix Double) (Matrix Double)\n    -> Matrix Double\ncalcSigmaX d tau w = H.inv (ident d + mean tau `H.scale` wSquareMean)\n  where\n    mW = mean w\n    wSquareMean = variance w + (H.tr mW H.<> mW)\n\ncalcMX\n    :: Matrix Double\n    -> Distr Double Double\n    -> Matrix Double\n    -> Distr (Matrix Double) (Matrix Double)\n    -> Distr (Vector Double) (Matrix Double)\n    -> Matrix Double\ncalcMX trainT tau sigmaX w mu =\n    H.tr\n        (mean tau `H.scale` sigmaX H.<> H.tr (mean w) H.<>\n         H.tr\n             (fromRows\n                  (map\n                       (\\r ->\n                             r - mean mu)\n                       (toRows trainT))))\n\ncalcSigmaMu\n    :: Int\n    -> Distr Double Double\n    -> Distr (Vector Double) (Matrix Double)\n    -> Matrix Double\ncalcSigmaMu n tau mu =\n    vMu + 1 / (fromIntegral n * mean tau) `H.scale` ident d\n  where\n    vMu = variance mu\n    (_,d) = size vMu\n\ncalcMMu\n    :: Matrix Double\n    -> Distr Double Double\n    -> Matrix Double\n    -> Distr (Matrix Double) (Matrix Double)\n    -> Distr (Matrix Double) (Matrix Double)\n    -> Vector Double\ncalcMMu trainT tau sigmaMu w x =\n    (mean tau `H.scale` sigmaMu) H.#>\n    foldr\n         (flip (+))\n         (konst 0 d)\n         (toRows (trainT - H.tr (mW H.<> H.tr mX)))\n  where\n    mW = mean w\n    mX = mean x\n    (_, d) = size trainT\n\n\ncalcSigmaW\n    :: Distr Double Double\n    -> Distr (Vector Double) (Vector Double)\n    -> Distr (Matrix Double) (Matrix Double)\n    -> Matrix Double\ncalcSigmaW tau alpha x =\n    H.inv\n        (diag (mean alpha) +\n         mean tau `H.scale`\n         (fromIntegral n `H.scale` variance x + H.tr mX H.<> mX))\n  where\n    mX = mean x\n    (n,_) = size mX\n\ncalcMW\n    :: Distr Double Double\n    -> Matrix Double\n    -> Distr (Matrix Double) (Matrix Double)\n    -> Matrix Double\n    -> Distr (Vector Double) (Matrix Double)\n    -> Matrix Double\ncalcMW tau sigmaW x trainT mu =\n    (mean tau `H.scale` sigmaW) H.<>\n    (H.tr mX H.<>\n     (fromRows\n          (map\n               (\\tn ->\n                     tn - mMu)\n               (toRows trainT))))\n  where\n    mX = mean x\n    mMu = mean mu\n\n\ncalcAalpha :: Int -> Vector Double -> Vector Double\ncalcAalpha d = H.cmap (+ fromIntegral d / 2)\n\ncalcBalpha :: Vector Double\n           -> Distr (Matrix Double) (Matrix Double)\n           -> Vector Double\ncalcBalpha b w = b + 0.5 `H.scale` (takeDiag (H.tr mW H.<> mW))\n  where\n    mW = mean w\n\ncalcAtau :: Int -> Int -> Double -> Double\ncalcAtau n d a = a + fromIntegral (n * d) / 2\n\n\n-- | TODO: Formula is not correct.\n-- Skip part Tr (\\langle W^TW \\rangle \\langle x_n x^T_n 'rangle')\n-- because i think it is not correct in that result must be number\ncalcBtau\n    :: Double\n    -> Matrix Double\n    -> Distr (Vector Double) (Matrix Double)\n    -> Distr (Matrix Double) (Matrix Double)\n    -> Distr (Matrix Double) (Matrix Double)\n    -> Double\ncalcBtau b trainT mu w x =\n    b +\n    0.5 *\n    (fromIntegral n * norm mMu +\n     H.sumElements (takeDiag (trainT H.<> H.tr trainT)) +\n     2 * (H.sumElements (H.tr (mW H.<> H.tr mX) H.#> mMu)) -\n     2 * (H.sumElements (takeDiag (trainT H.<> mW H.<> H.tr mX))) -\n     2 * (H.sumElements (trainT H.#> mMu)))\n  where\n    (n,_) = size trainT\n    norm v = v `H.dot` v\n    mMu = mean mu\n    mW = mean w\n    mX = mean x\n", "meta": {"hexsha": "e7a3d8bcf2317e3ee9b70e00ffca97e3634cfea5", "size": 5102, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PCA/QModels.hs", "max_stars_repo_name": "DbIHbKA/vbpca", "max_stars_repo_head_hexsha": "e9c98743b6303436fbfcab360ac7a500183606bf", "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/PCA/QModels.hs", "max_issues_repo_name": "DbIHbKA/vbpca", "max_issues_repo_head_hexsha": "e9c98743b6303436fbfcab360ac7a500183606bf", "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/PCA/QModels.hs", "max_forks_repo_name": "DbIHbKA/vbpca", "max_forks_repo_head_hexsha": "e9c98743b6303436fbfcab360ac7a500183606bf", "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.5027932961, "max_line_length": 78, "alphanum_fraction": 0.5895727166, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4635153931332063}}
{"text": "{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, FlexibleContexts #-}\n-- |\n-- Module    : Statistics.Sample.KernelDensity.Simple\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License   : BSD3\n--\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : portable\n--\n-- Kernel density estimation code, providing non-parametric ways to\n-- estimate the probability density function of a sample.\n--\n-- The techniques used by functions in this module are relatively\n-- fast, but they generally give inferior results to the KDE function\n-- in the main 'Statistics.KernelDensity' module (due to the\n-- oversmoothing documented for 'bandwidth' below).\n\nmodule Statistics.Sample.KernelDensity.Simple\n    {-# DEPRECATED \"Use Statistics.Sample.KernelDensity instead.\" #-}\n    (\n    -- * Simple entry points\n      epanechnikovPDF\n    , gaussianPDF\n    -- * Building blocks\n    -- These functions may be useful if you need to construct a kernel\n    -- density function estimator other than the ones provided in this\n    -- module.\n\n    -- ** Choosing points from a sample\n    , Points(..)\n    , choosePoints\n    -- ** Bandwidth estimation\n    , Bandwidth\n    , bandwidth\n    , epanechnikovBW\n    , gaussianBW\n    -- ** Kernels\n    , Kernel\n    , epanechnikovKernel\n    , gaussianKernel\n    -- ** Low-level estimation\n    , estimatePDF\n    , simplePDF\n    -- * References\n    -- $references\n    ) where\n\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.MathFunctions.Constants (m_1_sqrt_2, m_2_sqrt_pi)\nimport Prelude hiding (sum)\nimport Statistics.Function (minMax)\nimport Statistics.Sample (stdDev)\nimport Statistics.Sample.Internal (sum)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\n\n-- | Points from the range of a 'Sample'.\nnewtype Points = Points {\n      fromPoints :: U.Vector Double\n    } deriving (Eq, Read, Show, Typeable, Data, Generic)\n\n-- | Bandwidth estimator for an Epanechnikov kernel.\nepanechnikovBW :: Double -> Bandwidth\nepanechnikovBW n = (80 / (n * m_2_sqrt_pi)) ** 0.2\n\n-- | Bandwidth estimator for a Gaussian kernel.\ngaussianBW :: Double -> Bandwidth\ngaussianBW n = (4 / (n * 3)) ** 0.2\n\n-- | The width of the convolution kernel used.\ntype Bandwidth = Double\n\n-- | Compute the optimal bandwidth from the observed data for the\n-- given kernel.\n--\n-- This function uses an estimate based on the standard deviation of a\n-- sample (due to Deheuvels), which performs reasonably well for\n-- unimodal distributions but leads to oversmoothing for more complex\n-- ones.\nbandwidth :: G.Vector v Double =>\n             (Double -> Bandwidth)\n          -> v Double\n          -> Bandwidth\nbandwidth kern values = stdDev values * kern (fromIntegral $ G.length values)\n\n-- | Choose a uniform range of points at which to estimate a sample's\n-- probability density function.\n--\n-- If you are using a Gaussian kernel, multiply the sample's bandwidth\n-- by 3 before passing it to this function.\n--\n-- If this function is passed an empty vector, it returns values of\n-- positive and negative infinity.\nchoosePoints :: G.Vector v Double =>\n                Int             -- ^ Number of points to select, /n/\n             -> Double          -- ^ Sample bandwidth, /h/\n             -> v Double        -- ^ Input data\n             -> Points\nchoosePoints n h sample = Points . U.map f $ U.enumFromTo 0 n'\n  where lo     = a - h\n        hi     = z + h\n        (a, z) = minMax sample\n        d      = (hi - lo) / fromIntegral n'\n        f i    = lo + fromIntegral i * d\n        n'     = n - 1\n\n-- | The convolution kernel.  Its parameters are as follows:\n--\n-- * Scaling factor, 1\\//nh/\n--\n-- * Bandwidth, /h/\n--\n-- * A point at which to sample the input, /p/\n--\n-- * One sample value, /v/\ntype Kernel =  Double\n            -> Double\n            -> Double\n            -> Double\n            -> Double\n\n-- | Epanechnikov kernel for probability density function estimation.\nepanechnikovKernel :: Kernel\nepanechnikovKernel f h p v\n    | abs u <= 1 = f * (1 - u * u)\n    | otherwise  = 0\n    where u = (v - p) / (h * 0.75)\n\n-- | Gaussian kernel for probability density function estimation.\ngaussianKernel :: Kernel\ngaussianKernel f h p v = exp (-0.5 * u * u) * g\n    where u = (v - p) / h\n          g = f * 0.5 * m_2_sqrt_pi * m_1_sqrt_2\n\n-- | Kernel density estimator, providing a non-parametric way of\n-- estimating the PDF of a random variable.\nestimatePDF :: G.Vector v Double =>\n               Kernel           -- ^ Kernel function\n            -> Bandwidth        -- ^ Bandwidth, /h/\n            -> v Double         -- ^ Sample data\n            -> Points           -- ^ Points at which to estimate\n            -> U.Vector Double\nestimatePDF kernel h sample\n    | n < 2     = errorShort \"estimatePDF\"\n    | otherwise = U.map k . fromPoints\n  where\n    k p = sum . G.map (kernel f h p) $ sample\n    f   = 1 / (h * fromIntegral n)\n    n   = G.length sample\n{-# INLINE estimatePDF #-}\n\n-- | A helper for creating a simple kernel density estimation function\n-- with automatically chosen bandwidth and estimation points.\nsimplePDF :: G.Vector v Double =>\n             (Double -> Double) -- ^ Bandwidth function\n          -> Kernel             -- ^ Kernel function\n          -> Double             -- ^ Bandwidth scaling factor (3 for a Gaussian kernel, 1 for all others)\n          -> Int                -- ^ Number of points at which to estimate\n          -> v Double           -- ^ sample data\n          -> (Points, U.Vector Double)\nsimplePDF fbw fpdf k numPoints sample =\n    (points, estimatePDF fpdf bw sample points)\n  where points = choosePoints numPoints (bw*k) sample\n        bw     = bandwidth fbw sample\n{-# INLINE simplePDF #-}\n\n-- | Simple Epanechnikov kernel density estimator.  Returns the\n-- uniformly spaced points from the sample range at which the density\n-- function was estimated, and the estimates at those points.\nepanechnikovPDF :: G.Vector v Double =>\n                   Int          -- ^ Number of points at which to estimate\n                -> v Double     -- ^ Data sample\n                -> (Points, U.Vector Double)\nepanechnikovPDF = simplePDF epanechnikovBW epanechnikovKernel 1\n\n-- | Simple Gaussian kernel density estimator.  Returns the uniformly\n-- spaced points from the sample range at which the density function\n-- was estimated, and the estimates at those points.\ngaussianPDF :: G.Vector v Double =>\n               Int              -- ^ Number of points at which to estimate\n            -> v Double         -- ^ Data sample\n            -> (Points, U.Vector Double)\ngaussianPDF = simplePDF gaussianBW gaussianKernel 3\n\nerrorShort :: String -> a\nerrorShort func = error (\"Statistics.KernelDensity.\" ++ func ++\n                        \": at least two points required\")\n\n-- $references\n--\n-- * Deheuvels, P. (1977) Estimation non param\u00e9trique de la densit\u00e9\n--   par histogrammes\n--   g\u00e9n\u00e9ralis\u00e9s. Mhttp://archive.numdam.org/article/RSA_1977__25_3_5_0.pdf>\n", "meta": {"hexsha": "f9e70c84f682916f257cbf0587f403542ba2e5a4", "size": 6955, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Sample/KernelDensity/Simple.hs", "max_stars_repo_name": "vmchale/statistics", "max_stars_repo_head_hexsha": "7f19ba0569ff34891c3ec18293a23ffb7eac8edf", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistics/Sample/KernelDensity/Simple.hs", "max_issues_repo_name": "vmchale/statistics", "max_issues_repo_head_hexsha": "7f19ba0569ff34891c3ec18293a23ffb7eac8edf", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Sample/KernelDensity/Simple.hs", "max_forks_repo_name": "vmchale/statistics", "max_forks_repo_head_hexsha": "7f19ba0569ff34891c3ec18293a23ffb7eac8edf", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4846938776, "max_line_length": 105, "alphanum_fraction": 0.6379583034, "num_tokens": 1723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4632146014843405}}
{"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n#if __GLASGOW_HASKELL__ >= 786\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE ViewPatterns #-}\n#endif\n\nmodule Data.Complex.Polar (\n#if __GLASGOW_HASKELL__ >= 800\n    Polar((:<)),\n#elif __GLASGOW_HASKELL >= 786\n    Polar,\n    pattern (:<),\n#else\n    Polar,\n#endif\n    fromPolar,\n    fromComplex,\n    realPart,\n    imagPart,\n    conjugate,\n    mkPolar,\n    cis,\n    polar,\n    magnitude,\n    phase\n) where\n\nimport           Data.Complex (Complex(..))\nimport qualified Data.Complex as C\n\nimport Data.Typeable\n#ifdef __GLASGOW_HASKELL__\nimport Data.Data (Data)\n#endif\n\n#ifdef __HUGS__\nimport Hugs.Prelude(Num(fromInt), Fractional(fromDouble))\n#endif\n\nimport Text.Read (parens)\nimport Text.ParserCombinators.ReadPrec (prec, step)\nimport Text.Read.Lex (Lexeme (Ident))\n\ninfix 6 :<<\n\n-- -----------------------------------------------------------------------------\n-- The Polar type\n\n-- | Complex numbers are an algebraic type.\n--\n-- For a complex number @z@, @'abs' z@ is a number with the magnitude of @z@,\n-- but oriented in the positive real direction, whereas @'signum' z@\n-- has the phase of @z@, but unit magnitude.\ndata (RealFloat a) => Polar a = !a :<< !a -- ^ forms a complex number from its magnitude\n                                          --   and its phase in radians.\n#if __GLASGOW_HASKELL__\n    deriving (Eq, Data, Typeable)\n#else\n    deriving Eq\n#endif\n\n#if __GLASGOW_HASKELL__ >= 786\ninfix 6 :<\n\n-- | Smart constructor that canonicalizes the magnitude and phase.\npattern r :< theta <-\n  ( \\(r :<< theta) -> Just (r, theta) ->\n      Just (r, theta)\n    )\n  where\n    r :< theta = mkPolar r theta\n#endif\n\ninstance (RealFloat a, Show a) => Show (Polar a) where\n    {-# SPECIALISE instance Show (Polar Float) #-}\n    {-# SPECIALISE instance Show (Polar Double) #-}\n    showsPrec d (r :<< theta) =\n      showParen (d >= 11) (showString \"mkPolar \"\n                           . showsPrec 11 r\n                           . showString \" \"\n                           . showsPrec 11 theta)\n\ninstance (RealFloat a, Read a) => Read (Polar a) where\n    {-# SPECIALISE instance Read (Polar Float) #-}\n    {-# SPECIALISE instance Read (Polar Double) #-}\n    readsPrec d = readParen (d > 10)\n                        (\\s -> do (\"mkPolar\", s2) <- lex s\n                                  (r, s3) <- readsPrec 11 s2\n                                  (theta, s4) <- readsPrec 11 s3\n                                  return (mkPolar r theta, s4))\n\n-- | Wrap phase back in interval @(-'pi', 'pi']@.\nwrap :: (RealFloat a) => a -> a\n{-# SPECIALISE wrap :: Float  -> Float   #-}\n{-# SPECIALISE wrap :: Double -> Double  #-}\nwrap phi | phi <= (-pi) = wrap (phi+2*pi)\nwrap phi | phi > pi     = wrap (phi-2*pi)\nwrap phi                = phi\n    \n-- | Convert to rectangular form.\nfromPolar :: (RealFloat a) => Polar a -> Complex a\n{-# INLINE fromPolar #-}\nfromPolar p = realPart p :+ imagPart p\n\n-- | Convert to polar form.\nfromComplex :: (RealFloat a) => Complex a -> Polar a\n{-# INLINE fromComplex #-}\nfromComplex = uncurry mkPolar_ . C.polar\n\n-- | Extracts the real part of a complex number.\nrealPart :: (RealFloat a) => Polar a -> a\nrealPart (r :<< theta) = r * cos theta\n\n-- | Extracts the imaginary part of a complex number.\nimagPart :: (RealFloat a) => Polar a -> a\nimagPart (r :<< theta) = r * sin theta\n\n-- | The conjugate of a complex number.\nconjugate :: (RealFloat a) => Polar a -> Polar a\n{-# SPECIALISE conjugate :: Polar Float  -> Polar Float #-}\n{-# SPECIALISE conjugate :: Polar Double -> Polar Double #-}\nconjugate (r :<< theta) = mkPolar r (negate theta)\n\n-- | Form a complex number from polar components of magnitude and phase.\n-- The magnitude and phase are expected to be in canonical form.\nmkPolar_ :: RealFloat a => a -> a -> Polar a\n{-# SPECIALISE mkPolar_ :: Float  -> Float  -> Polar Float  #-}\n{-# SPECIALISE mkPolar_ :: Double -> Double -> Polar Double #-}\nmkPolar_ r theta = r :<< theta\n\n-- | Form a complex number from polar components of magnitude and phase.\nmkPolar :: RealFloat a => a -> a -> Polar a\n{-# SPECIALISE mkPolar :: Float  -> Float  -> Polar Float  #-}\n{-# SPECIALISE mkPolar :: Double -> Double -> Polar Double #-}\nmkPolar r theta | r == 0 = 0 :<< 0\nmkPolar r theta | r < 0 = mkPolar (- r) (theta + pi)\nmkPolar r theta = mkPolar_ r (wrap theta)\n\n-- | @'cis' t@ is a complex value with magnitude @1@\n-- and phase @t@ (modulo @2*'pi'@).\ncis :: (RealFloat a) => a -> Polar a\n{-# SPECIALISE cis :: Float  -> Polar Float  #-}\n{-# SPECIALISE cis :: Double -> Polar Double #-}\ncis theta = mkPolar 1 theta\n\n-- | The function 'polar' takes a complex number and\n-- returns a (magnitude, phase) pair in canonical form:\n-- the magnitude is nonnegative, and the phase in the range @(-'pi', 'pi']@;\n-- if the magnitude is zero, then so is the phase.\npolar :: (RealFloat a) => Polar a -> (a,a)\n{-# SPECIALISE polar :: Polar Double -> (Double,Double) #-}\n{-# SPECIALISE polar :: Polar Float  -> (Float,Float)   #-}\npolar (r :<< theta) = (r,theta)\n\n-- | The nonnegative magnitude of a complex number.\nmagnitude :: (RealFloat a) => Polar a -> a\n{-# SPECIALISE magnitude :: Polar Float  -> Float  #-}\n{-# SPECIALISE magnitude :: Polar Double -> Double #-}\nmagnitude (r :<< _) = r\n\n-- | The phase of a complex number, in the range @(-'pi', 'pi']@.\n-- If the magnitude is zero, then so is the phase.\nphase :: (RealFloat a) => Polar a -> a\n{-# SPECIALISE phase :: Polar Float  -> Float  #-}\n{-# SPECIALISE phase :: Polar Double -> Double #-}\nphase (_ :<< theta) = theta\n\ninstance (RealFloat a) => Num (Polar a) where\n    {-# SPECIALISE instance Num (Polar Float)  #-}\n    {-# SPECIALISE instance Num (Polar Double) #-}\n    z + z'           = fromComplex (fromPolar z + fromPolar z')\n    z - z'           = fromComplex (fromPolar z - fromPolar z')\n    z * z'           = mkPolar  (magnitude z * magnitude z') (phase z + phase z')\n    negate z         = mkPolar  (negate (magnitude z)) (phase z)\n    abs z            = mkPolar_ (magnitude z) 0\n    signum (0 :<< _) = 0\n    signum z         = mkPolar_ 1 (phase z)\n    fromInteger      = flip mkPolar 0 . fromInteger\n\ninstance (RealFloat a) => Fractional (Polar a) where\n    {-# SPECIALISE instance Fractional (Polar Float)  #-}\n    {-# SPECIALISE instance Fractional (Polar Double) #-}\n    z / z'          = mkPolar (magnitude z / magnitude z') (phase z - phase z')\n    fromRational r  = mkPolar (fromRational r) 0\n\ninstance  (RealFloat a) => Floating (Polar a)  where\n    {-# SPECIALISE instance Floating (Polar Float) #-}\n    {-# SPECIALISE instance Floating (Polar Double) #-}\n    pi             = mkPolar_ pi 0\n    exp (r :<< theta) = mkPolar (exp (r * cos theta)) (r * sin theta)\n    log (r :<< theta) = fromComplex (log r :+ theta)\n    \n    -- sqrt (0 :<< _)       =  0\n    -- sqrt z@(r :<< theta) =  u :+ (if y < 0 then -v else v)\n    --                           where (u,v) = if x < 0 then (v',u') else (u',v')\n    --                                 v'    = abs y / (u'*2)\n    --                                 u'    = sqrt ((magnitude z + abs x) / 2)\n    sqrt = fromComplex.sqrt.fromPolar\n    \n    -- sin (x:+y)     =  sin x * cosh y :+ cos x * sinh y\n    sin = fromComplex.sin.fromPolar\n    \n    -- cos (x:+y)     =  cos x * cosh y :+ (- sin x * sinh y)\n    cos = fromComplex.cos.fromPolar\n    \n    -- tan (x:+y)     =  (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy))\n    --                   where sinx  = sin x\n    --                         cosx  = cos x\n    --                         sinhy = sinh y\n    --                         coshy = cosh y\n    tan = fromComplex.tan.fromPolar\n    \n    -- sinh (x:+y)    =  cos y * sinh x :+ sin  y * cosh x\n    sinh = fromComplex.sinh.fromPolar\n    \n    -- cosh (x:+y)    =  cos y * cosh x :+ sin y * sinh x\n    cosh = fromComplex.cosh.fromPolar\n    \n    -- tanh (x:+y)    =  (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx)\n    --                   where siny  = sin y\n    --                         cosy  = cos y\n    --                         sinhx = sinh x\n    --                         coshx = cosh x\n    tanh = fromComplex.tanh.fromPolar\n    \n    -- asin z@(x:+y)  =  y':+(-x')\n    --                   where  (x':+y') = log (((-y):+x) + sqrt (1 - z*z))\n    asin = fromComplex.asin.fromPolar\n    \n    -- acos z         =  y'':+(-x'')\n    --                   where (x'':+y'') = log (z + ((-y'):+x'))\n    --                         (x':+y')   = sqrt (1 - z*z)\n    acos = fromComplex.acos.fromPolar\n    \n    -- atan z@(x:+y)  =  y':+(-x')\n    --                   where (x':+y') = log (((1-y):+x) / sqrt (1+z*z))\n    atan = fromComplex.atan.fromPolar\n    \n    asinh z        =  log (z + sqrt (1+z*z))\n    acosh z        =  log (z + (z+1) * sqrt ((z-1)/(z+1)))\n    atanh z        =  log ((1+z) / sqrt (1-z*z))\n", "meta": {"hexsha": "52771d5a0650500fb37132066f6120ea580e5ef4", "size": 8785, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Complex/Polar.hs", "max_stars_repo_name": "kaoskorobase/polar", "max_stars_repo_head_hexsha": "0c7113bdef612237f696f0fbbc2af42556bb7c89", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Data/Complex/Polar.hs", "max_issues_repo_name": "kaoskorobase/polar", "max_issues_repo_head_hexsha": "0c7113bdef612237f696f0fbbc2af42556bb7c89", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-21T22:40:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T22:40:32.000Z", "max_forks_repo_path": "Data/Complex/Polar.hs", "max_forks_repo_name": "kaoskorobase/polar", "max_forks_repo_head_hexsha": "0c7113bdef612237f696f0fbbc2af42556bb7c89", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-18T17:59:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-18T17:59:59.000Z", "avg_line_length": 36.1522633745, "max_line_length": 88, "alphanum_fraction": 0.5452475811, "num_tokens": 2567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46278911859480326}}
{"text": "module Distributions where\n\nimport Control.Monad (replicateM)\nimport qualified Control.Monad.Bayes.Class as B\nimport Control.Monad.Bayes.Class (MonadSample, MonadCond)\nimport Numeric.SpecFunctions (logGamma)\n\nimport qualified Data.Vector as V\nimport qualified Data.Map as M\nimport qualified Data.MultiSet as S\n\nimport Numeric.Log (Log (Exp))\n\nimport SymbolicArithmetic\nimport Util.Numeric (logFact)\nimport Util.Bijection\n\ntype Distr = Distr' Double\n\ndata Distr' d a = Distr\n  { sample :: forall m. MonadSample m => m a\n  , score :: a -> d\n  }\n\nmapOutputDiscrete :: Bijection a b -> Distr' d a -> Distr' d b\nmapOutputDiscrete (Bijection to from) (Distr sample score) =\n  Distr (to <$> sample) (score . from)\n\nfactor :: MonadCond m => Double -> m ()\nfactor = B.score . Numeric.Log.Exp\n\nnegInf :: Double\nnegInf = - 1 / 0\n\nobserve :: MonadCond m => Distr a -> a -> m ()\nobserve d x = factor (score d x)\n\ndata ExpFam a = ExpFam\n  { dim :: Int\n  , suffStats :: [Exp () Double]\n  , logPartition :: [Double] -> Double\n  , logBaseMeas :: Exp () Double\n  , efSample :: forall m. MonadSample m => [Double] -> m a\n  , efRepr :: a -> Double\n  , mle :: [Double] -> [Double]\n  , efDescribe :: [Double] -> String }\n\nbernoulliEF :: ExpFam Bool\nbernoulliEF = ExpFam\n  { dim = 1\n  , suffStats = [Var ()]\n  , logPartition = undefined\n  , logBaseMeas = undefined\n  , efSample = \\[p] -> B.bernoulli p\n  , efRepr = \\x -> if x then 1 else 0\n  , mle = id\n  , efDescribe = \\[eta] -> let z = exp eta in \"Bernoulli(\" ++ show (z / (1 + z)) ++ \")\"\n  }\n\nbetaEF :: ExpFam Double\nbetaEF = ExpFam\n  { dim = 2\n  , suffStats = let x = Var () in  [log x, log (1 - x)]\n  , logPartition = \\[a, b] -> logBeta a b\n  , logBaseMeas = let x = Var () in - log x - log (1 - x)\n  , efSample = \\[a, b] -> B.beta a b\n  , efRepr = id\n  , mle = \\[lx, lox] -> undefined\n  , efDescribe = \\[a, b] -> \"Beta(\" ++ show a ++ \", \" ++ show b ++ \")\"\n  }\n\nlogBeta :: Double -> Double -> Double\nlogBeta a b = logGamma a + logGamma b - logGamma (a + b)\n\nlogChoose :: Int -> Int -> Double\nlogChoose n k = logFact n - logFact k - logFact (n - k)\n\nnormalEF :: ExpFam Double\nnormalEF = ExpFam\n  { dim = 2\n  , suffStats = let x = Var () in [x, x^2]\n  , logPartition = \\[eta1, eta2] -> - eta1^2 / (4 * eta2) - 1 / 2 * log(-2 * eta2)\n  , logBaseMeas = - 1 / 2 * log (2 * pi)\n  , efSample = \\eta -> let (mu, sigma2) = conv eta in\n      B.normal mu (sqrt sigma2)\n  , efRepr = id\n  , mle = \\[mu, ex2] -> let sigma2 = ex2 - mu^2 in normalNatParams mu sigma2\n  , efDescribe = \\eta -> let (mu, sigma2) = conv eta in\n    \"Normal(\" ++ show mu ++ \", \" ++ show sigma2 ++ \")\"\n  }\n  where\n  conv [eta1, eta2] = let sigma2 = - 1 / (2 * eta2) in (sigma2 * eta1, sigma2)\n  conv _ = error \"conv\"\n\n-- indep :: ExpFam a -> ExpFam b -> ExpFam (a, b)\n-- indep efa efb = ExpFam\n--   { dim = dim efa + dim efb\n--   , suffStats = \\(a, b) -> suffStats efa a ++ suffStats efb b\n--   , logPartition = \\eta -> let (eta1, eta2) = split eta in\n--       logPartition efa eta1 + logPartition efb eta2\n--   , logBaseMeas = \\(a, b) -> logBaseMeas efa a + logBaseMeas efb b\n--   , efSample = \\eta -> let (eta1, eta2) = split eta in\n--       (,) <$> efSample efa eta1 <*> efSample efb eta2\n--   , mle = \\ss -> let (ss1, ss2) = split ss in\n--       mle efa ss1 ++ mle efb ss2\n--   , efDescribe = \\eta -> let (eta1, eta2) = split eta in\n--     \"Indep(\" ++ efDescribe efa eta1 ++ \", \" ++ efDescribe efb eta2 ++ \")\"\n--   }\n--   where\n--   split = splitAt (dim efa)\n\nnormalNatParams :: Fractional d => d -> d -> [d]\nnormalNatParams mu sigma2 = [mu / sigma2, -1 / (2 * sigma2)]\n\ndirac :: Eq a => a -> Distr a\ndirac x = Distr (return x) (\\y -> if x == y then 0 else negInf)\n\ndot :: Num d => [d] -> [d] -> d\ndot xs ys = sum (zipWith (*) xs ys)\n\nefToDistr :: ExpFam a -> [Double] -> Distr a\nefToDistr ef naturalParams =\n  Distr (efSample ef naturalParams)\n  (\\x -> let ev = eval (\\_ -> efRepr ef x) in\n    naturalParams `dot` map ev (suffStats ef) - logPartition ef naturalParams + ev (logBaseMeas ef))\n\nbernoulli :: Double -> Distr Bool\nbernoulli p = Distr (B.bernoulli p) (\\b -> bernoulli_ll p (if b then 1 else 0))\n\nbernoulli01 :: Double -> Distr Int\nbernoulli01 p = Distr sam sco where\n  sam :: MonadSample m => m Int\n  sam = do\n    b <- B.bernoulli p\n    return (if b then 1 else 0)\n  sco 1 = log p\n  sco 0 = log (1 - p)\n  sco _ = negInf\n\ncategorical :: [Double] -> Distr Int\ncategorical ps = Distr (B.categorical (V.fromList ps)) (\\i -> log (ps !! i))\n\ncategoricalM :: Ord a => M.Map a Double -> Distr a\ncategoricalM ps = Distr (fmap (\\i -> fst (M.elemAt i ps)) (B.categorical (V.fromList (M.elems ps))))\n  (\\k -> log (ps M.! k))\n\nbernoulli_ll :: Floating a => a -> a -> a\nbernoulli_ll p b = b * log p + (1 - b) * log (1 - p)\n\n-- WARNING: NOT NORMALIZED!\nbeta_ll :: Floating a => a -> a -> a -> a\nbeta_ll a b p = a * log p + b * log (1 - p)\n\nbeta :: Double -> Double -> Distr Double\nbeta a b = Distr (B.beta a b) (\\x -> beta_ll a b x + logPartition betaEF [a, b])\n\ngaussian_ll :: Floating a => a -> a -> a -> a\ngaussian_ll mu sigma2 x = - x^2 / sigma2 + 2 * x * mu / sigma2 - mu^2 / sigma2 - log (2 * pi) - log sigma2\n\ngaussian_ll' :: Floating a => a -> a -> a -> a\ngaussian_ll' mu sigma2 x = - (x - mu)^2 / sigma2 - log (2 * pi) - log sigma2\n\ngaussian :: Double -> Double -> Distr Double\ngaussian mu sigma2 = Distr (B.normal mu (sqrt sigma2)) (gaussian_ll' mu sigma2)\n\nnormal = gaussian\n\npoisson_ll :: Double -> Int -> Double\npoisson_ll lambda k = fromIntegral k * log lambda - lambda - logGamma (fromIntegral k + 1)\n\npoisson :: Double -> Distr Int\npoisson lambda = Distr (B.poisson lambda) (poisson_ll lambda)\n\nuniform :: Double -> Double -> Distr Double\nuniform a b = Distr (B.uniform a b) $ \\x ->\n  if a <= x && x <= b\n    then - log range\n    else negInf\n  where\n  range = b - a\n\nreplicateNIID :: Int -> Distr a -> Distr [a]\nreplicateNIID n d = Distr (replicateM n (sample d)) (\\obs ->\n  if length obs == n\n    then sum (map (score d) obs)\n    else (-1 / 0))\n\nuniformIntRange :: Int -> Distr Int\nuniformIntRange max = Distr (B.uniformD [0 .. max - 1])\n  (\\obs -> if 0 <= obs && obs < max then - log (fromIntegral max) else -1 / 0)\n\nbind :: Distr a -> (a -> Distr b) -> Distr (a, b)\nbind d f = Distr (do {x <- sample d; y <- sample (f x); pure (x, y)})\n                 (\\(x, y) -> score d x + score (f x) y)\n\nreplicateIID :: forall a. Distr Int -> Distr a -> Distr [a]\nreplicateIID howMany d = Distr sam obs where\n  sam :: MonadSample m => m [a]\n  sam = do\n    n <- sample howMany\n    replicateM n (sample d)\n  obs xs = score howMany (length xs) + sum (map (score d) xs)\n\ngeometric' :: MonadSample m => m Int\ngeometric' = do\n  x <- B.bernoulli (0.5 :: Double)\n  if x then return 0 else fmap (+1) geometric'\n\nexponential :: MonadSample m => Double -> m Double\nexponential lambda = do\n  u <- B.random\n  pure (- log u / lambda)\n\npassert :: MonadCond m => Bool -> m ()\npassert True = pure ()\npassert False = B.score 0\n\ndata Some f where\n  Some :: f a -> Some f\n\nexponentialFamilies :: [Some ExpFam]\nexponentialFamilies = [Some betaEF, Some bernoulliEF, Some normalEF]\n\nshuffleWithRepeats' :: forall a. Ord a => M.Map a (Distr Int) -> Distr [a]\nshuffleWithRepeats' countDistrs = Distr sam sco where\n  sam :: MonadSample m => m [a]\n  sam = do\n    counts <- mapM sample countDistrs\n    randomlyInterleave [ replicate n k | (k, n) <- M.toList counts ]\n  sco :: [a] -> Double\n  sco idxes = let ns = mconcat [ S.singleton i | i <- idxes ] in\n    sum (M.mapWithKey (\\k d -> score d (length (filter (== k) idxes))) countDistrs)\n    + randomlyInterleaveLogPDF (map snd (S.toOccurList ns))\n\nshuffleWithRepeats :: [Distr Int] -> Distr [Int]\nshuffleWithRepeats countDistrs = Distr sam sco where\n  sam :: MonadSample m => m [Int]\n  sam = do\n    counts <- mapM sample countDistrs\n    randomlyInterleave [ replicate n i | (i, n) <- zip [0..] counts ]\n  sco :: [Int] -> Double\n  sco idxes = let ns = [ length (filter (== i) idxes) | i <- take (length countDistrs) [0..] ] in\n    sum (zipWith score countDistrs ns) + randomlyInterleaveLogPDF ns\n\nrandomlyInterleave :: MonadSample m => [[a]] -> m [a]\nrandomlyInterleave xs = if ntot == 0\n  then pure []\n  else do\n    i <- sample (categorical [ fromIntegral n / fromIntegral ntot | n <- ns ])\n    let (before, (v : vs) : after) = splitAt i xs\n    (v :) <$> randomlyInterleave (before ++ vs : after)\n  where\n    ns = map length xs\n    ntot = sum ns\n\nlogNumPermutationsWithRepeats :: [Int] -> Double\nlogNumPermutationsWithRepeats ns = logFact (sum ns) - sum [ logFact n | n <- ns ]\n\nrandomlyInterleaveLogPDF :: [Int] -> Double\nrandomlyInterleaveLogPDF ns = - logNumPermutationsWithRepeats ns\n\nshuffleListLogPDF :: Int -> Double\nshuffleListLogPDF n = - logFact n", "meta": {"hexsha": "b3490453af88738c457ee4b5f8389e14c60c6a26", "size": 8682, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/src/Distributions.hs", "max_stars_repo_name": "psg-mit/probzelus-haskell", "max_stars_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-26T13:13:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T19:11:41.000Z", "max_issues_repo_path": "haskell/src/Distributions.hs", "max_issues_repo_name": "psg-mit/probzelus-haskell", "max_issues_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "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": "haskell/src/Distributions.hs", "max_forks_repo_name": "psg-mit/probzelus-haskell", "max_forks_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0114068441, "max_line_length": 106, "alphanum_fraction": 0.6136834831, "num_tokens": 2952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.4625538081521328}}
{"text": "{-# LANGUAGE ConstraintKinds     #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE RankNTypes          #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell     #-}\n{-# LANGUAGE TypeOperators       #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE TypeApplications    #-}\n\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\nmodule Test.Grenade.Batch where\n\nimport           Grenade.Types\nimport           Grenade.Core.Shape\nimport           Grenade.Core.Network\nimport           Grenade.Core.Layer\nimport           Grenade.Layers.FullyConnected\nimport           Grenade.Layers.Convolution\nimport           Grenade.Utils.ListStore\n\nimport           Numeric.LinearAlgebra hiding (uniformSample, konst, (===))\nimport           Numeric.LinearAlgebra.Static as H hiding ((===))\nimport           Numeric.LinearAlgebra.Data as D hiding ((===))\n\nimport           Hedgehog\nimport           GHC.TypeLits\n\ntype FFNetwork = Network '[ FullyConnected 3 5, FullyConnected 5 4 ] '[ 'D1 3, 'D1 5, 'D1 4 ]\n\nprop_networkBatchFeedforward = property $ do\n  let bias  :: H.R 5              = H.fromList [1..5]\n      bias' :: H.R 4              = H.fromList [1..4]\n      acts  :: H.L 5 3            = H.fromList [1..15]\n      acts' :: H.L 4 5            = H.fromList [1..20]\n      fc    :: FullyConnected 3 5 = FullyConnected (FullyConnected' bias  acts)  mkListStore\n      fc'   :: FullyConnected 5 4 = FullyConnected (FullyConnected' bias' acts') mkListStore\n      ins   :: [S ('D1 3)]        = [S1D (H.fromList [1, 2, 3]), S1D (H.fromList [4, 5, 6])]\n      net   :: FFNetwork          = fc :~> fc' :~> NNil\n      (_, outs :: [S ('D1 4)]) = runBatchForwards net ins\n      outs' = map (\\(S1D v) -> (D.toList . H.extract) v) outs\n  outs' === [[986, 2312, 3638, 4964], [2336, 5462, 8588, 11714]]\n\nextractFCGrads :: Gradients '[FullyConnected 3 5, FullyConnected 5 4] -> [(Vector RealNum, Matrix RealNum)]\nextractFCGrads ((FullyConnected' wB wN) :/> ((FullyConnected' wB' wN') :/> GNil))\n  = [(H.extract wB, H.extract wN), (H.extract wB', H.extract wN')]\n\nprop_networkBackpropCalculatesGradients = property $ do\n  let bias  :: H.R 5              = H.fromList [1..5]\n      bias' :: H.R 4              = H.fromList [1..4]\n      acts  :: H.L 5 3            = H.fromList [1..15]\n      acts' :: H.L 4 5            = H.fromList [1..20]\n      fc    :: FullyConnected 3 5 = FullyConnected (FullyConnected' bias acts) mkListStore\n      fc'   :: FullyConnected 5 4 = FullyConnected (FullyConnected' bias' acts') mkListStore\n      ins   :: [S ('D1 3)]        = [S1D (H.fromList [1, 2, 3]), S1D (H.fromList [4, 5, 6])]\n      net   :: FFNetwork          = fc :~> fc' :~> NNil\n      (tapes, outs :: [S ('D1 4)]) = runBatchForwards net ins\n      (grads, vs   :: [S ('D1 3)]) = runBatchBackwards net tapes outs\n      (grad,  v    :: S ('D1 3))   = runBackwards net (tapes!!0) (outs!!0)\n      (grad', v'   :: S ('D1 3))   = runBackwards net (tapes!!1) (outs!!1)\n      grads'                       = map extractFCGrads grads\n      grads''                      = map extractFCGrads [grad, grad']\n      vs'                          = map (\\(S1D vec) -> (D.toList . H.extract) vec) vs\n      vs''                         = map (\\(S1D vec) -> (D.toList . H.extract) vec) [v, v']\n\n  grads' === grads''\n  vs'    === vs''\n\nprop_networkAveragesGradients = property $ do\n  let bias  :: H.R 5                 = H.fromList [1..5]\n      bias' :: H.R 4                 = H.fromList [1..4]\n      acts  :: H.L 5 3               = H.fromList [1..15]\n      acts' :: H.L 4 5               = H.fromList [1..20]\n      fc    :: FullyConnected 3 5    = FullyConnected (FullyConnected' bias acts) mkListStore\n      fc'   :: FullyConnected 5 4    = FullyConnected (FullyConnected' bias' acts') mkListStore\n      ins   :: [S ('D1 3)]           = [S1D (H.fromList [1, 2, 3]), S1D (H.fromList [4, 5, 6])]\n      net   :: FFNetwork             = fc :~> fc' :~> NNil\n      (tapes, outs :: [S ('D1 4)])   = runBatchForwards net ins\n      (grads, _    :: [S ('D1 3)])   = runBatchBackwards net tapes outs\n      (grad,  _    :: S ('D1 3))     = runBackwards net (tapes!!0) (outs!!0)\n      (grad', _    :: S ('D1 3))     = runBackwards net (tapes!!1) (outs!!1)\n      rgrad                          = extractFCGrads (reduceGradient @FFNetwork grads)\n      [(wB, wN), (wB', wN')]         = extractFCGrads grad\n      [(wB'', wN''), (wB''', wN''')] = extractFCGrads grad'\n      rgrad'                         = (0.5 * (wB + wB''), 0.5 * (wN + wN''))\n      rgrad''                        = (0.5 * (wB' + wB'''), 0.5 * (wN' + wN'''))\n\n  rgrad === [rgrad', rgrad'']\n\n\nprop_convolutionCalculatesOutputOfBatches = property $ do\n  let weights :: H.L 25 1 = H.fromList [1..25]\n      convLayer :: Convolution 'WithoutBias 'NoPadding 1 1 5 5 2 2 = Convolution weights mkListStore\n      ins :: [S ('D2 11 11)] = [S2D (H.fromList [1..121]), S2D (H.fromList [2..122])]\n      (_, outs :: [S ('D2 4 4)]) = runBatchForwards convLayer ins\n      outs' = map (\\(S2D v) -> (concat . D.toLists . H.extract) v) outs\n  (take 9 (concat outs')) === [10925, 11575, 12225, 12875, 18075, 18725, 19375, 20025, 25225]\n\nunwrapGradConv :: ( KnownNat c\n              , KnownNat f\n              , KnownNat kR\n              , KnownNat kC\n              , KnownNat sR\n              , KnownNat sC\n              , KnownNat kF\n              , kF ~ (kR * kC * c)) => Convolution' 'WithoutBias 'NoPadding c f kR kC sR sC -> Matrix RealNum\nunwrapGradConv (Convolution' mat) = H.extract mat\n\nprop_convolutionBackprop = property $ do\n  let weights :: H.L 25 1 = H.fromList [1..25]\n      convLayer :: Convolution 'WithoutBias 'NoPadding 1 1 5 5 2 2 = Convolution weights mkListStore\n      ins :: [S ('D2 11 11)] = [S2D (H.fromList [1..121]), S2D (H.fromList [2..122])]\n      (tapes, outs :: [S ('D2 4 4)]) = runBatchForwards convLayer ins\n      (grads, vs   :: [S ('D2 11 11)]) = runBatchBackwards convLayer tapes outs\n      (grad,  v    :: S ('D2 11 11))   = runBackwards convLayer (tapes!!0) (outs!!0)\n      (grad', v'   :: S ('D2 11 11))   = runBackwards convLayer (tapes!!1) (outs!!1)\n      grads'                           = map unwrapGradConv grads\n      grads''                          = map unwrapGradConv [grad, grad']\n      vs'                              = map (\\(S2D u) -> (D.toLists . H.extract) u) vs\n      vs''                             = map (\\(S2D u) -> (D.toLists . H.extract) u) [v, v']\n\n  grads' === grads''\n  vs'    === vs''\n\nprop_convolutionAveragesGradients = property $ do\n  let weights :: H.L 25 1                  = H.fromList (concat (replicate 5 [1, 2, 3, 4, 5]))\n      convLayer :: Convolution 'WithoutBias 'NoPadding 1 1 5 5 2 2 = Convolution weights mkListStore\n      ins :: [S ('D2 11 11)]               = [S2D (H.fromList [1..121]), S2D (H.fromList [2..122])]\n      (tapes, outs :: [S ('D2 4 4)])       = runBatchForwards convLayer ins\n      (grads, _    :: [S ('D2 11 11)])     = runBatchBackwards convLayer tapes outs\n      (grad,  _    :: S ('D2 11 11))       = runBackwards convLayer (tapes!!0) (outs!!0)\n      (grad', _    :: S ('D2 11 11))       = runBackwards convLayer (tapes!!1) (outs!!1)\n      rgrad                                = unwrapGradConv (reduceGradient @(Convolution 'WithoutBias 'NoPadding 1 1 5 5 2 2) grads)\n      w                                    = unwrapGradConv grad\n      w'                                   = unwrapGradConv grad'\n      rgrad'                       = 0.5 * (w + w') \n\n  rgrad === rgrad'\n\n\nprop_fullyConnectedCalculatesOutputOfBatches = property $ do\n  let bias :: H.R 5 = H.fromList [1..5]\n      acts :: H.L 5 3 = H.fromList [1..15]\n      fc :: FullyConnected 3 5 = FullyConnected (FullyConnected' bias acts) mkListStore\n      ins :: [S ('D1 3)] = [S1D (H.fromList [1, 2, 3]), S1D (H.fromList [4, 5, 6])]\n      (_, outs :: [S ('D1 5)]) = runBatchForwards fc ins\n      outs' = map (\\(S1D v) -> (D.toList . H.extract) v) outs\n  outs' === [[15, 34, 53, 72, 91], [33, 79, 125, 171, 217]]\n\nprop_fullyConnectedBackprop = property $ do\n  let bias :: H.R 5 = H.fromList [1..5]\n      acts :: H.L 5 3 = H.fromList [1..15]\n      fc :: FullyConnected 3 5 = FullyConnected (FullyConnected' bias acts) mkListStore\n      ins :: [S ('D1 3)] = [S1D (H.fromList [1, 2, 3]), S1D (H.fromList [4, 5, 6])]\n      (tapes, outs :: [S ('D1 5)]) = runBatchForwards fc ins\n      (grads, vs   :: [S ('D1 3)]) = runBatchBackwards fc tapes outs\n      (grad,  v    :: S ('D1 3))   = runBackwards fc (tapes!!0) (outs!!0)\n      (grad', v'   :: S ('D1 3))   = runBackwards fc (tapes!!1) (outs!!1)\n      unwrapGrad                   = \\(FullyConnected' wB wN) -> (H.extract wB, H.extract wN)\n      grads'                       = map unwrapGrad grads\n      grads''                      = map unwrapGrad [grad, grad']\n      vs'                          = map (\\(S1D vec) -> (D.toList . H.extract) vec) vs\n      vs''                         = map (\\(S1D vec) -> (D.toList . H.extract) vec) [v, v']\n\n  grads' === grads''\n  vs'    === vs''\n\nprop_fullyConnectedAveragesGradients = property $ do\n  let bias :: H.R 5 = H.fromList [1..5]\n      acts :: H.L 5 3 = H.fromList [1..15]\n      fc :: FullyConnected 3 5 = FullyConnected (FullyConnected' bias acts) mkListStore\n      ins :: [S ('D1 3)] = [S1D (H.fromList [1, 2, 3]), S1D (H.fromList [4, 5, 6])]\n      (tapes, outs :: [S ('D1 5)]) = runBatchForwards fc ins\n      (grads, _    :: [S ('D1 3)]) = runBatchBackwards fc tapes outs\n      (grad,  _    :: S ('D1 3))   = runBackwards fc (tapes!!0) (outs!!0)\n      (grad', _    :: S ('D1 3))   = runBackwards fc (tapes!!1) (outs!!1)\n      f                            = \\(FullyConnected' bs ns) -> (H.extract bs, H.extract ns)\n      rgrad                        = f (reduceGradient @(FullyConnected 3 5) grads)\n      (wB, wN)                     = f grad\n      (wB', wN')                   = f grad'\n      rgrad'                       = (0.5 * (wB + wB'), 0.5 * (wN + wN'))\n\n  rgrad === rgrad'\n   \ntests :: IO Bool\ntests = checkParallel $$(discover)\n", "meta": {"hexsha": "8a2e23bb891017b69653248e587609251a7c5d1f", "size": 10117, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Batch.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "test/Test/Grenade/Batch.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Test/Grenade/Batch.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.5291005291, "max_line_length": 133, "alphanum_fraction": 0.5208065632, "num_tokens": 3329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4625185126628938}}
{"text": "module Main where\n\nimport MNIST.Prelude\nimport Control.Monad.Random\nimport qualified Numeric.LinearAlgebra.Static as SA\n\nimport Grenade\n\n\ntype MNIST\n  = Network\n    '[ FullyConnected 784 300, Logit\n     , FullyConnected 300 100, Logit\n     , FullyConnected 100   9, Logit\n     ]\n    '[ 'D1 784, 'D1 300\n     , 'D1 300, 'D1 100\n     , 'D1 100, 'D1 9\n     , 'D1 9\n     ]\n\n\nrandomNet :: MonadRandom m => m MNIST\nrandomNet = randomNetwork\n\n\ntype Input  = S ('D1 784)\ntype Output = S ('D1   9)\ntype DataSet = [(Input, Output)]\n\n\ntrainAll :: LearningParameters -> MNIST -> DataSet -> MNIST\ntrainAll rate net0 dataset = foldl' trainOne net0 dataset\n  where\n  trainOne :: MNIST -> (Input, Output) -> MNIST\n  trainOne !network (i,o) = train rate network i o\n\n\nnetTrain :: MNIST -> LearningParameters -> Int -> IO MNIST\nnetTrain net0 rate n = do\n  inps <- replicateM n randomTrainingData\n  let outs = map randomTrainingLabels inps\n  return $ trainAll rate net0 (zip inps outs)\n  where\n    randomTrainingData :: IO Input\n    randomTrainingData = do\n      s <- getRandom\n      return . S1D $ SA.randomVector s SA.Uniform * 2 - 1\n\n    randomTrainingLabels :: Input -> Output\n    randomTrainingLabels (S1D v) = S1D . fromIntegral $ fromEnum isTrue\n      where\n        isTrue :: Bool\n        isTrue = (v `inCircle` (fromRational    0.33, 0.33))\n              || (v `inCircle` (fromRational (-0.33), 0.33))\n\n    inCircle :: KnownNat n => R n -> (R n, Double) -> Bool\n    inCircle v (o, r) = SA.norm_2 (v - o) <= r\n\n\nnetScore :: MNIST -> IO ()\nnetScore network = putStrLn . unlines $\n  (fmap.fmap) (showNorm . go) testIns\n\n  where\n    testIns :: [[(Double, Double)]]\n    testIns = [ [ (x,y)  | x <- [0..50] ] | y <- [0..20] ]\n\n    go :: (Double, Double) -> Output\n    go (x,y) = runNet network (S1D $ SA.vector [x / 25 - 1, y / 10 - 1])\n\n    showNorm :: Output -> Char\n    showNorm (S1D r) = render $ SA.mean r\n\n    render :: Double -> Char\n    render n | n <= 0.2  = ' '\n             | n <= 0.4  = '.'\n             | n <= 0.6  = '-'\n             | n <= 0.8  = '='\n             | otherwise = '#'\n\n\nmain :: IO ()\nmain = do\n  net0 <- randomNet\n  net  <- netTrain net0 params examples\n  netScore net\n  where\n    examples :: Int\n    examples = 10000\n\n    params :: LearningParameters\n    params = LearningParameters\n      { learningRate = 0.01\n      , learningMomentum = 0.9\n      , learningRegulariser = 0.0005\n      }\n\n", "meta": {"hexsha": "d3b6501256d5f79e2a2ad51f4f4ab911b41f3283", "size": 2400, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/MNIST/Grenade.hs", "max_stars_repo_name": "stites/haskell-mnist-benchmarks", "max_stars_repo_head_hexsha": "00dda97e764d078f9ed6989faf0b8a7f2553260f", "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": "bench/MNIST/Grenade.hs", "max_issues_repo_name": "stites/haskell-mnist-benchmarks", "max_issues_repo_head_hexsha": "00dda97e764d078f9ed6989faf0b8a7f2553260f", "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": "bench/MNIST/Grenade.hs", "max_forks_repo_name": "stites/haskell-mnist-benchmarks", "max_forks_repo_head_hexsha": "00dda97e764d078f9ed6989faf0b8a7f2553260f", "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": 24.2424242424, "max_line_length": 72, "alphanum_fraction": 0.5891666667, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.46246943297913773}}
{"text": "{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE ImpredicativeTypes #-}\n{-# LANGUAGE RankNTypes #-}\n{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}\n\nmodule Data.Histogram.Util where\n\nimport Control.Foldl (fold)\nimport qualified Control.Foldl as L\nimport Data.Histogram (Histogram)\nimport qualified Data.Histogram as H\nimport Data.Histogram.Fill\nimport Data.Monoid\nimport qualified Data.Vector.Unboxed as V\nimport Statistics.Distribution\nimport qualified Statistics.Distribution.Combo as OC\nimport Statistics.Distribution.Exponential\nimport Statistics.Distribution.Gamma\nimport qualified Statistics.Distribution.Laplace as OL\nimport Statistics.Distribution.Normal\nimport Statistics.Distribution.Poisson\n\nbin :: BinD\nbin = binDn (-10.5) 1 10.5\n\nhist :: BinD -> V.Vector Double -> H.Histogram BinD Double\nhist b = \n  fillBuilderVec (forceDouble -<< mkSimple b)\n\n-- | make a percentile histogram\nperc :: Histogram BinD Double -> Histogram BinD Double\nperc h = H.map (\\x -> x / H.sum h) h\n\n-- reversing out mean and stdev\n-- calculating mean using the trick that the Bin boundaries are constructed to be isomorphic to actual values\nmeanH :: Histogram BinD Double -> Double\nmeanH h = \n  let t = H.sum h\n  in H.bfoldl step begin h /\n     t\n  where begin = 0.0\n        step b bv v = b + bv * v\n\nmeanSqH :: Histogram BinD Double -> Double\nmeanSqH h = \n  let t = H.sum h\n  in H.bfoldl step begin h /\n     t\n  where begin = 0.0\n        step b bv v = \n          b +\n          (bv ^\n           (2 :: Int)) *\n          v\n\ntype Pdf = BinD -> [Double] -> V.Vector Double\n\npdfBin :: (Double -> Double) -> BinD -> V.Vector Double\npdfBin cdf h = \n  V.map (\\(x,y) -> cdf y - cdf x) binsV\n  where binsV = \n          binsList h :: V.Vector (Double,Double)\n\npdfBinNormal :: Pdf\npdfBinNormal b [] = \n  pdfBin (cumulative $\n          normalDistr 0.0 1.0)\n         b\npdfBinNormal b [s] = \n  pdfBin (cumulative $\n          normalDistr 0.0 s')\n         b\n  where s' = max 1.0e-5 s\npdfBinNormal b (m:s:_) = \n  pdfBin (cumulative $\n          normalDistr m s')\n         b\n  where s' = max 1.0e-5 s\n\npdfBinLaplace :: Pdf\npdfBinLaplace b (r:l:sl:glue:_) = \n  pdfBin (cumulative $\n          OL.laplace r' l' sl' glue)\n         b\n  where l' = max 1.0e-5 l\n        r' = max 1.0e-5 r\n        sl' = max 1.0e-4 sl\npdfBinLaplace _ _ = mempty\n\npdfBinExponential :: Pdf\npdfBinExponential b (e:_) = \n  pdfBin (cumulative $ exponential e') b\n  where e' = max 1.0e-5 e\npdfBinExponential _ _ = mempty\n\npdfBinPoisson :: Pdf\npdfBinPoisson b (e:_) = \n  pdfBin (cumulative $ poisson e') b\n  where e' = max 1.0e-5 e\npdfBinPoisson _ _ = mempty\n\npdfBinGamma :: Pdf\npdfBinGamma b (m:k:v:_) = \n  V.map (m *) $\n  pdfBin (cumulative $\n          gammaDistr k' v')\n         b\n  where k' = max 1.0e-5 k\n        v' = max 1.0e-5 v\npdfBinGamma _ _ = mempty\n\npdfBinCombo :: Pdf\npdfBinCombo b (split:m:s:r:l:sl:_) = \n  pdfBin (cumulative $\n          OC.combo split' m s' r' l' sl')\n         b\n  where split' = max 1.0e-5 split\n        s' = max 1.0e-5 s\n        l' = max 1.0e-5 l\n        r' = max 1.0e-5 r\n        sl' = max 1.0e-4 sl\npdfBinCombo _ _ = mempty\n\nerr :: Histogram BinD Double -> Pdf -> [Double] -> Double\nerr h pdf p = \n  do let pdfT = pdf (H.bins h) p\n         pdfE = H.histData (perc h)\n         errV = \n           zipWith (-)\n                   (V.toList pdfE)\n                   (V.toList pdfT)\n         err' = fold L.sum (fmap abs errV)\n     err'\n", "meta": {"hexsha": "45d5285f0618704d9d594fb7fcc0187d29a53129", "size": 3408, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Histogram/Util.hs", "max_stars_repo_name": "tonyday567/maths-extended", "max_stars_repo_head_hexsha": "1d4a492f9692238af161637245946267654476bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-04-07T06:58:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T08:20:15.000Z", "max_issues_repo_path": "src/Data/Histogram/Util.hs", "max_issues_repo_name": "tonyday567/maths-extended", "max_issues_repo_head_hexsha": "1d4a492f9692238af161637245946267654476bd", "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/Data/Histogram/Util.hs", "max_forks_repo_name": "tonyday567/maths-extended", "max_forks_repo_head_hexsha": "1d4a492f9692238af161637245946267654476bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4328358209, "max_line_length": 109, "alphanum_fraction": 0.6194248826, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.46239592015176184}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule MLP.Config (\n   readConf,\n   mkDataSet\n) where\n\nimport Data.Aeson (eitherDecode)\nimport Numeric.LinearAlgebra.Data (loadMatrix, (><), Matrix)\nimport Numeric.LinearAlgebra.Static (create, L)\nimport Control.Lens ((^.), foldlOf, (%~), (&))\nimport MLP.DataSet (toPat, normPat)\nimport MLP.Network (AllCon, Net, Learn, MLP)\nimport MLP.Types (trainFile, \n                  testFile,\n                  topology, \n                  normalise, \n                  topoFold,\n                  DataSet(..), \n                  Parameters(..),\n                  State(..),\n                  Topology,\n                  MonadFileSystem(..))\nimport Control.Monad ((=<<))\nimport System.FilePath (splitFileName, takeFileName, (</>))\nimport GHC.TypeLits (KnownNat, Nat)\nimport Control.Monad.Random.Class (MonadRandom)\n\nliftEither :: (MonadFail m) => Either String b -> m b\nliftEither = either fail pure\n\nreadConf :: MonadFileSystem m => FilePath -> m Parameters\nreadConf fl = do\n   s <- liftEither . eitherDecode =<< readFileM fl\n   pure $ s & trainFile %~ absPath\n            & testFile %~ absPath\n\n   where\n      (base,_) = splitFileName fl\n      absPath x = base </> takeFileName x\n   \nmkDataSet :: (KnownNat i, KnownNat o, MonadFileSystem m) => Parameters -> m (DataSet i o)\nmkDataSet p = do\n      trainSet <- mkPat (p ^. trainFile)\n      testSet <- mkPat (p ^. testFile)\n   \n      return $\n         if norm then\n            DataSet (normPat trainSet) (normPat testSet)\n         else\n            DataSet trainSet testSet\n   where\n      mkPat fl = readMatrixM fl >>= liftEither . toPat\n      norm = p ^. normalise ", "meta": {"hexsha": "b0808334b9c0b0ceb07090e1d9e91f341d9b63da", "size": 1738, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MLP/Config.hs", "max_stars_repo_name": "ovanr/Typed-MLP", "max_stars_repo_head_hexsha": "c6cf0d5295048f0aa4bfe9b4628ccb59cb92b80c", "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/MLP/Config.hs", "max_issues_repo_name": "ovanr/Typed-MLP", "max_issues_repo_head_hexsha": "c6cf0d5295048f0aa4bfe9b4628ccb59cb92b80c", "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/MLP/Config.hs", "max_forks_repo_name": "ovanr/Typed-MLP", "max_forks_repo_head_hexsha": "c6cf0d5295048f0aa4bfe9b4628ccb59cb92b80c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4912280702, "max_line_length": 89, "alphanum_fraction": 0.6006904488, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.46239591465864516}}
{"text": "{-# LANGUAGE DataKinds                 #-}\n{-# LANGUAGE DeriveGeneric             #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE FlexibleContexts          #-}\n{-# LANGUAGE FlexibleInstances         #-}\n{-# LANGUAGE GADTs                     #-}\n{-# LANGUAGE LambdaCase                #-}\n{-# LANGUAGE MultiParamTypeClasses     #-}\n{-# LANGUAGE ScopedTypeVariables       #-}\n{-# LANGUAGE StandaloneDeriving        #-}\n{-# LANGUAGE TypeApplications          #-}\n{-# LANGUAGE TypeFamilies              #-}\n{-# LANGUAGE TypeInType                #-}\n{-# LANGUAGE TypeSynonymInstances      #-}\n{-# LANGUAGE UndecidableInstances      #-}\n\nmodule Learn.Neural.Layer.Recurrent.FullyConnected (\n    FullyConnectedR\n  , FullyConnectedR'\n  , CommonMap(..)\n  , MapFunc(..)\n  ) where\n\nimport           Data.Kind\nimport           Data.Proxy\nimport           Data.Reflection\nimport           Data.Singletons.Prelude\nimport           GHC.Generics                   (Generic)\nimport           GHC.TypeLits\nimport           Learn.Neural.Layer\nimport           Learn.Neural.Layer.Mapping\nimport           Numeric.BLAS\nimport           Numeric.Backprop\nimport           Numeric.Backprop.Iso           (iso)\nimport           Numeric.Backprop.Op\nimport           Statistics.Distribution\nimport           Statistics.Distribution.Normal\nimport qualified Generics.SOP                   as SOP\n\ndata FullyConnectedR :: Type\n\nderiving instance Generic (CParam FullyConnectedR b '[i] '[o])\ninstance SOP.Generic (CParam FullyConnectedR b '[i] '[o])\n\ninstance (Num (b '[o,o]), Num (b '[o,i]), Num (b '[o]))\n      => Num (CParam FullyConnectedR b '[i] '[o]) where\n    FCRP wI1 wS1 b1 + FCRP wI2 wS2 b2 = FCRP (wI1 + wI2) (wS1 + wS2) (b1 + b2)\n    FCRP wI1 wS1 b1 - FCRP wI2 wS2 b2 = FCRP (wI1 - wI2) (wS1 - wS2) (b1 - b2)\n    FCRP wI1 wS1 b1 * FCRP wI2 wS2 b2 = FCRP (wI1 * wI2) (wS1 * wS2) (b1 * b2)\n    negate (FCRP wI wS b) = FCRP (negate wI) (negate wS) (negate b)\n    signum (FCRP wI wS b) = FCRP (signum wI) (signum wS) (signum b)\n    abs    (FCRP wI wS b) = FCRP (abs    wI) (abs    wS) (abs    b)\n    fromInteger x = FCRP (fromInteger x) (fromInteger x) (fromInteger x)\n\ninstance (Fractional (b '[o,o]), Fractional (b '[o,i]), Fractional (b '[o]))\n      => Fractional (CParam FullyConnectedR b '[i] '[o]) where\n    FCRP wI1 wS1 b1 / FCRP wI2 wS2 b2 = FCRP (wI1 / wI2) (wS1 / wS2) (b1 / b2)\n    recip (FCRP wI wS b) = FCRP (recip wI) (recip wS) (recip b)\n    fromRational x       = FCRP (fromRational x) (fromRational x) (fromRational x)\n\ninstance (Floating (b '[o,o]), Floating (b '[o,i]), Floating (b '[o]))\n      => Floating (CParam FullyConnectedR b '[i] '[o]) where\n    sqrt (FCRP wI wS b) = FCRP (sqrt wI) (sqrt wS) (sqrt b)\n\ninstance Num (b '[o]) => Num (CState FullyConnectedR b '[i] '[o]) where\n    FCRS s1 + FCRS s2 = FCRS (s1 + s2)\n    FCRS s1 - FCRS s2 = FCRS (s1 - s2)\n    FCRS s1 * FCRS s2 = FCRS (s1 * s2)\n    negate (FCRS s) = FCRS (negate s)\n    signum (FCRS s) = FCRS (signum s)\n    abs    (FCRS s) = FCRS (abs    s)\n    fromInteger x  = FCRS (fromInteger x)\n\ninstance Fractional (b '[o]) => Fractional (CState FullyConnectedR b '[i] '[o]) where\n    FCRS s1 / FCRS s2 = FCRS (s1 / s2)\n    recip (FCRS s)    = FCRS (recip s)\n    fromRational x    = FCRS (fromRational x)\n\ninstance Floating (b '[o]) => Floating (CState FullyConnectedR b '[i] '[o]) where\n    sqrt (FCRS s)    = FCRS (sqrt s)\n\ninstance ( BLAS b\n         , KnownNat i\n         , KnownNat o\n         , Floating (b '[o])\n         , Floating (b '[o,i])\n         , Floating (b '[o,o])\n         )\n        => Component FullyConnectedR b '[i] '[o] where\n    data CParam  FullyConnectedR b '[i] '[o] =\n            FCRP { _fcrInpWeights   :: !(b '[o,i])\n                 , _fcrStateWeights :: !(b '[o,o])\n                 , _fcrBiases       :: !(b '[o])\n                 }\n    data CState  FullyConnectedR b '[i] '[o] = FCRS { _fcrState :: !(b '[o]) }\n    type CConstr FullyConnectedR b '[i] '[o] = (Num (b '[o,i]), Num (b '[o,o]))\n    data CConf   FullyConnectedR b '[i] '[o] = forall d. ContGen d => FCRC d\n\n    componentOp = bpOp . withInps $ \\(x :< p :< s :< \u00d8) -> do\n        wI :< wS :< b :< \u00d8 <- gTuple #<~ p\n        s0 <- opIso (iso _fcrState FCRS) ~$ (s :< \u00d8)\n        y  <- matVecOp ~$ (wI :< x  :< \u00d8)\n        s1 <- matVecOp ~$ (wS :< s0 :< \u00d8)\n        let z = y + s1 + b\n        s' <- opIso (iso FCRS _fcrState) ~$ (s1 :< \u00d8)\n        return $ z :< s' :< \u00d8\n\n    defConf = FCRC (normalDistr 0 0.01)\n    initParam = \\case\n      i `SCons` SNil -> \\case\n        so@(o `SCons` SNil) -> \\(FCRC d) g -> do\n          wI <- genA (o `SCons` (i `SCons` SNil)) $ \\_ ->\n            realToFrac <$> genContVar d g\n          wS <- genA (o `SCons` (o `SCons` SNil)) $ \\_ ->\n            realToFrac <$> genContVar d g\n          b <- genA so $ \\_ ->\n            realToFrac <$> genContVar d g\n          return $ FCRP wI wS b\n        _ -> error \"inaccessible\"\n      _ -> error \"inaccessible\"\n    initState _ so (FCRC d) g =\n        FCRS <$> genA so (\\_ -> realToFrac <$> genContVar d g)\n\ninstance ( BLAS b\n         , KnownNat i\n         , KnownNat o\n         , Floating (b '[o])\n         , Floating (b '[o,i])\n         , Floating (b '[o,o])\n         )\n        => ComponentLayer 'Recurrent FullyConnectedR b '[i] '[o] where\n    componentRunMode = RMNotFF\n\ndata FullyConnectedR' :: k -> Type\n\nderiving instance Generic (CParam (FullyConnectedR' c) b '[i] '[o])\ninstance SOP.Generic (CParam (FullyConnectedR' c) b '[i] '[o])\n\ninstance (Num (b '[o,o]), Num (b '[o,i]), Num (b '[o]))\n      => Num (CParam (FullyConnectedR' s) b '[i] '[o]) where\n    FCRP' wI1 wS1 b1 + FCRP' wI2 wS2 b2 = FCRP' (wI1 + wI2) (wS1 + wS2) (b1 + b2)\n    FCRP' wI1 wS1 b1 - FCRP' wI2 wS2 b2 = FCRP' (wI1 - wI2) (wS1 - wS2) (b1 - b2)\n    FCRP' wI1 wS1 b1 * FCRP' wI2 wS2 b2 = FCRP' (wI1 * wI2) (wS1 * wS2) (b1 * b2)\n    negate (FCRP' wI wS b) = FCRP' (negate wI) (negate wS) (negate b)\n    signum (FCRP' wI wS b) = FCRP' (signum wI) (signum wS) (signum b)\n    abs    (FCRP' wI wS b) = FCRP' (abs    wI) (abs    wS) (abs    b)\n    fromInteger x = FCRP' (fromInteger x) (fromInteger x) (fromInteger x)\n\ninstance (Fractional (b '[o,o]), Fractional (b '[o,i]), Fractional (b '[o]))\n      => Fractional (CParam (FullyConnectedR' s) b '[i] '[o]) where\n    FCRP' wI1 wS1 b1 / FCRP' wI2 wS2 b2 = FCRP' (wI1 / wI2) (wS1 / wS2) (b1 / b2)\n    recip (FCRP' wI wS b) = FCRP' (recip wI) (recip wS) (recip b)\n    fromRational x        = FCRP' (fromRational x) (fromRational x) (fromRational x)\n\ninstance (Floating (b '[o,o]), Floating (b '[o,i]), Floating (b '[o]))\n      => Floating (CParam (FullyConnectedR' s) b '[i] '[o]) where\n    sqrt (FCRP' wI wS b) = FCRP' (sqrt wI) (sqrt wS) (sqrt b)\n\ninstance Num (b '[o]) => Num (CState (FullyConnectedR' s) b '[i] '[o]) where\n    FCRS' s1 + FCRS' s2 = FCRS' (s1 + s2)\n    FCRS' s1 - FCRS' s2 = FCRS' (s1 - s2)\n    FCRS' s1 * FCRS' s2 = FCRS' (s1 * s2)\n    negate (FCRS' s) = FCRS' (negate s)\n    signum (FCRS' s) = FCRS' (signum s)\n    abs    (FCRS' s) = FCRS' (abs    s)\n    fromInteger x  = FCRS' (fromInteger x)\n\ninstance Fractional (b '[o]) => Fractional (CState (FullyConnectedR' s) b '[i] '[o]) where\n    FCRS' s1 / FCRS' s2 = FCRS' (s1 / s2)\n    recip (FCRS' s)     = FCRS' (recip s)\n    fromRational x      = FCRS' (fromRational x)\n\ninstance Floating (b '[o]) => Floating (CState (FullyConnectedR' s) b '[i] '[o]) where\n    sqrt (FCRS' s)     = FCRS' (sqrt s)\n\n\ninstance ( BLAS b\n         , KnownNat i\n         , KnownNat o\n         , Floating (b '[o])\n         , Floating (b '[o,i])\n         , Floating (b '[o,o])\n         , Reifies s MapFunc\n         )\n      => Component (FullyConnectedR' s) b '[i] '[o] where\n    data CParam  (FullyConnectedR' c) b '[i] '[o] =\n            FCRP' { _fcrInpWeights'   :: !(b '[o,i])\n                  , _fcrStateWeights' :: !(b '[o,o])\n                  , _fcrBiases'       :: !(b '[o])\n                  }\n    data CState  (FullyConnectedR' c) b '[i] '[o] = FCRS' { _fcrState' :: !(b '[o]) }\n    type CConstr (FullyConnectedR' c) b '[i] '[o] =\n      ( Num (b '[o,i])\n      , Num (b '[o,o])\n      )\n    data CConf   (FullyConnectedR' c) b '[i] '[o] = forall d. ContGen d => FCRC' d\n\n    componentOp = bpOp . withInps $ \\(x :< p :< s :< \u00d8) -> do\n        wI :< wS :< b :< \u00d8 <- gTuple #<~ p\n        s0 <- opIso (iso _fcrState' FCRS') ~$ (s :< \u00d8)\n        y  <- matVecOp ~$ (wI :< x  :< \u00d8)\n        s1 <- matVecOp ~$ (wS :< s0 :< \u00d8)\n        s2 <- tmapOp (runMapFunc mf) ~$ (s1 :< \u00d8)\n        let z = y + s2 + b\n        s' <- opIso (iso FCRS' _fcrState') ~$ (s2 :< \u00d8)\n        return $ z :< s' :< \u00d8\n      where\n        mf :: MapFunc\n        mf = reflect (Proxy @s)\n\n    defConf = FCRC' (normalDistr 0 0.01)\n\n    initParam = \\case\n      i `SCons` SNil -> \\case\n        so@(o `SCons` SNil) -> \\(FCRC' d) g -> do\n          wI <- genA (o `SCons` (i `SCons` SNil)) $ \\_ ->\n            realToFrac <$> genContVar d g\n          wS <- genA (o `SCons` (o `SCons` SNil)) $ \\_ ->\n            realToFrac <$> genContVar d g\n          b <- genA so $ \\_ ->\n            realToFrac <$> genContVar d g\n          return $ FCRP' wI wS b\n        _ -> error \"inaccessible\"\n      _ -> error \"inaccessible\"\n\n    initState _ so (FCRC' d) g =\n        FCRS' <$> genA so (\\_ -> realToFrac <$> genContVar d g)\n\ninstance ( BLAS b\n         , KnownNat i\n         , KnownNat o\n         , Floating (b '[o])\n         , Floating (b '[o,i])\n         , Floating (b '[o,o])\n         , Reifies s MapFunc\n         )\n      => ComponentLayer 'Recurrent (FullyConnectedR' s) b '[i] '[o] where\n    componentRunMode = RMNotFF\n\n", "meta": {"hexsha": "ca8599a9e7541a5d2a69482095a1448d79844be2", "size": 9560, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "old/src/Learn/Neural/Layer/Recurrent/FullyConnected.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "old/src/Learn/Neural/Layer/Recurrent/FullyConnected.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "old/src/Learn/Neural/Layer/Recurrent/FullyConnected.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 39.8333333333, "max_line_length": 90, "alphanum_fraction": 0.5256276151, "num_tokens": 3483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4622154084631668}}
{"text": "{-# OPTIONS_GHC  -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-}\n{-# LANGUAGE FlexibleInstances, ConstraintKinds, ExistentialQuantification, GADTs, RankNTypes, MultiParamTypeClasses, RankNTypes, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-}\n\n\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n-- | \n-- | Module : Approximate median\n-- | Creator: Xiao Ling\n-- | Created: 12/08/2015\n-- | TODO   : test standard deviation of alpha, beta, and final version\n-- |\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n\nmodule ApproxMedian (\n\n      MaxSize\n    , Store\n\n    , median\n    , median'\n\n  ) where\n\nimport Control.Monad.State\nimport Control.Monad.Random\nimport Control.Monad.Random.Class\n\nimport Data.Conduit\nimport Data.Foldable (toList)\nimport qualified Data.Sequence as S\nimport qualified Data.Conduit.List as Cl\nimport Data.Sequence (Seq,(|>),update,empty,index)\n\nimport Test.QuickCheck\nimport Test.QuickCheck.Random\n\nimport Core\nimport Utils\nimport qualified Statistics as St\n\n\n{-----------------------------------------------------------------------------\n  Types \n------------------------------------------------------------------------------}\n\ntype MaxSize = Float\ntype Store a = (Seq a, MaxSize)\n\n\n-- * the algorithm uses `some m` equipped with state and randomness\n-- * also consider `some'` `a`\ntype Some  m = (MonadState Counter m, MonadRandom m)\ntype Some' a = (Floating a          , Ord a        )\n\n\n{-----------------------------------------------------------------------------\n  Approximate Median \n------------------------------------------------------------------------------}\n\n-- * @Use: test (tMedian (E 0.05, D 0.05)) xs\n-- * compute `tMedian` within accuracy `Eps` and confidence `Delta`\nmedian' :: Some' a => EpsDelta -> Batch a IO a\nmedian' t = median t `using` eval\n\n-- * `tick` up a counter for each item `a` seen and with probability \n-- * min(1, s/i) put item `a` into store `t` of maxSize `s`\nmedian :: (Some m, Some' a) => EpsDelta -> Streaming a m (Store a)\nmedian (ED e d) = Cl.foldM step $ store s\n  where s = 7/(e^2) * log (2/d)\n\n-- * a concrete `eval`uation of `m`\neval :: Some' a => StateT Counter (Rand StdGen) (Store a) -> IO a\neval m = fmap (St.median . toList) . fmap fst . evalRandIO $ evalStateT m 0\n\n{-----------------------------------------------------------------------------\n  Subroutines. Read $|> to understand the actual algorithm\n------------------------------------------------------------------------------}\n\n-- * One step of the algorithm\nstep :: (Some m, Some' a) => Store a -> a -> m (Store a)\nstep t a = tick >> t $|> a\n\n-- * with probability `s/i` uniformly select an item from the store `t` and \n-- * replace it with `a`.\n-- * mnemonic: `|>` is insertion, `$f` means do f probabilistically\ninfixl 7 $|>\n($|>) :: Some m => Store a -> a -> m (Store a)\n($|>) t@(_,s) a = do\n  i <- get\n  if s > i then t $> a else do\n    h <- toss . coin $ s/i\n    if isHead h then t $> a else return t\n\n{-----------------------------------------------------------------------------\n  Utils\n------------------------------------------------------------------------------}\n\n-- * Construct an empty store given max size `s`\nstore :: MaxSize -> Store a\nstore = (,) empty\n\n-- * Probabilistic insertion. If the store is not full, insert item `a` deterministically\n-- * else with uniform probability replace some existing item in store with `a`\n-- * mnemonic: `|>` is insertion, `$f` means do f probabilistically\n($>) :: Some m => Store a -> a -> m (Store a)\n(as,s) $> a | length as < round s = return (as |> a, s)\n            | otherwise           = (\\x -> (update (round x) a as, s)) \n                                  <$> getRandomR (0,s :: MaxSize)\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "5fdc3df81e6d61f94e4051d08f7c30a687aadd8b", "size": 4073, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ApproxMedian.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": "src/ApproxMedian.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": "src/ApproxMedian.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": 32.8467741935, "max_line_length": 194, "alphanum_fraction": 0.480726737, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4622154084631668}}
{"text": "{-# LANGUAGE RankNTypes, BangPatterns, ScopedTypeVariables, FlexibleInstances #-}\n\nmodule Math.Probably.MALA where\n\nimport Math.Probably.MCMC\nimport qualified Math.Probably.PDF as PDF\nimport Math.Probably.RandIO\nimport Math.Probably.FoldingStats\nimport Math.Probably.Sampler\nimport qualified Math.Probably.PDF as PDF\nimport Control.Applicative\n\nimport Numeric.LinearAlgebra\nimport Numeric.AD\nimport Text.Printf\nimport System.IO\nimport Data.Maybe\n\nimport Statistics.Test.KolmogorovSmirnov\nimport Statistics.Test.MannWhitneyU\nimport qualified Data.Vector.Unboxed as U\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Vector.Storable as VS\n\nimport Debug.Trace\nimport Data.IORef\nimport Control.Spoon\n\nclass IsNaN a where\n  isItNaN :: a -> Bool\n\ninstance IsNaN Double where\n  isItNaN = nanOrInf\n\ninstance IsNaN (Vector Double) where\n  isItNaN = any nanOrInf . toList\n\ninstance IsNaN (Matrix Double) where\n  isItNaN = or . (map (any nanOrInf . toList)) . toRows\n\ncheckNaN :: IsNaN a => String -> a -> String\ncheckNaN s x | isItNaN x = \" \"++s++\" \"\n             | otherwise = \"\"\n\nclass Covariance a where\n  mvnSampler :: Vector Double ->  Double -> a -> Sampler (Vector Double)\n  mvnPDF :: Vector Double -> Double -> a -> PDF.PDF (Vector Double)\n  covMul :: a -> Vector Double -> Vector Double\n  restrict :: Vector Int -> a -> a\n\ninstance Covariance (Matrix Double,Matrix Double,Matrix Double) where\n  mvnSampler mu sigma (cov, covInv, covChol) \n     = multiNormalByChol mu (scale (sqrt sigma) covChol)\n  mvnPDF mu sigma (cov, covInv, covChol) \n     = PDF.multiNormalByInvFixCov (scale (recip sigma) covInv) mu\n  covMul (cov, covInv, covChol) v = cov <> v\n\ninstance Covariance (Vector Double) where\n  mvnSampler mu sigma varv \n    = multiNormalIndep (scale sigma varv) mu\n  mvnPDF mu sigma varv\n    = PDF.multiNormalIndep (scale sigma varv) mu\n  covMul varv v = VS.zipWith (*) varv  v\n  restrict vixs v = VS.backpermute v vixs\n\ndata MalaPar = MalaPar { mpXi :: !(Vector Double),\n                         mpPi :: !Double,\n                         mpGradLast :: !(Vector Double),\n                         mpSigma :: !Double,\n                         mpCount :: !Double,\n                         mpAccept :: !Double,\n                         mpFreezeSigma :: !Bool,\n                         mpThin :: !Int,\n                         mpMaxGradLen :: !Double } --,\n--                         mpLastRatio :: !Double }\n  deriving Show\n\ndata Pair a b = Pair !a !b\n\ndata List a = Cons !a !(List a)\n            | Nil\n\nunPair (Pair x y) = (x,y)\nunList (Cons x xs) = x: unList xs\nunList Nil =[]\n\ntrunc t v = scale (t/(max t (norm2 v))) v\n\nmala1 :: Covariance a => a -> (Vector Double -> (Double,Vector Double)) \n         -> Bool \n         -> MalaPar\n         -> Sampler MalaPar\nmala1 cov postgrad useCache\n      (MalaPar xi piCached gradientiCached sigma tr tracc freeze thinn maxGrad) = do\n  let (pi,gradienti) = if useCache \n                          then (piCached, gradientiCached)\n                          else let (p, gr_untr) = postgrad xi\n                               in (p, trunc maxGrad gr_untr)\n  let xstarMean = xi + scale (sigma/2) (cov `covMul` gradienti)\n  xstar <- mvnSampler xstarMean sigma cov\n  u <- unitSample\n  let (!pstar, gradientStarUntrunc) = postgrad xstar\n      gradientStar = trunc maxGrad gradientStarUntrunc\n  let !revJumpMean = xstar + scale (sigma/2) (cov `covMul` gradientStar)\n      ptop = mvnPDF revJumpMean sigma cov xi\n      pbot = mvnPDF xstarMean sigma cov xstar\n      ratio = exp $   pstar -pi + ptop - pbot\n      tr' = max 1 tr\n      sigmaNext = case () of\n         _ | freeze -> sigma\n      accept = tracc / tr    \n      freezeNext = freeze {-| freeze = True\n                 | not freeze = tr > 100 && accept > 0.5 && accept < 0.6  -}\n  if trace (show $ (tr, pstar ,pi , ratio, sigma)) $ u < ratio\n     then return $ MalaPar xstar pstar (gradientStar) \n                           (if freezeNext then sigma else (min 1.4 $ 1+kmala/tr')*sigma) \n                           (tr+1) (tracc+1) freezeNext  thinn maxGrad\n--                           sigma (tr+1) (tracc+1)\n     else return $ MalaPar xi pi ( gradienti) \n                           (if freezeNext then sigma else (max 0.7143 $ 1-kmala/tr')**1.3*sigma) \n                           (tr+1) tracc freezeNext thinn maxGrad\n--                           sigma (tr+1) tracc\n\n\nblockMala1 :: Covariance a => \n  (Vector Double -> (Double,Vector Double)) ->\n  Vector Double -> \n  [(a, MalaPar, Vector Int)] ->\n  Sampler (Vector Double, [(a, MalaPar, Vector Int)])\nblockMala1 postgrad xi blocks = do\n  let go totalV [] accblocks = return (totalV, reverse accblocks)\n      go totalV ((cov, mp0, vixs) : blocks) accblocks = do\n          let myPostGrad vpars \n               = let (p, grad) = postgrad $ VS.update_ totalV vixs vpars\n                 in (p, VS.backpermute grad vixs)             \n          mp1 <- mala1 cov myPostGrad False mp0\n          let newTotalV = VS.update_ totalV vixs (mpXi mp1)\n          go newTotalV blocks $ (cov, mp1, vixs) : accblocks\n  go xi blocks []\n  \nrunMalaBlocks :: Covariance a => a -> (Vector Double -> (Double,Vector Double)) \n         ->  Int -> Double -> Int -> Vector Double -> [Vector Int] \n         -> RIO [Vector Double]\nrunMalaBlocks cov  postgrad nsam truncN thinN init  vixs = go nsam initBlocks init []  where\n  initBlocks = flip map vixs $ \\vix-> \n     (restrict vix cov, \n      MalaPar (VS.backpermute init vix) 0 (fromList [0]) 0.001 0 0 False thinN truncN,\n      vix)\n  go 0 _ _ vs = return vs\n  go n blocks0 v0 vs = do\n        (!v1, blocks1) <- sample $ blockMala1 postgrad v0 blocks0\n        let (_,mpLast,_) = last blocks1 \n        io $ print $ (n, mpPi mpLast, map (\\(_,mp,_) -> mpSigma mp) blocks1)\n        let newChainRes = if thinN == 0 || n `mod` thinN ==0\n                             then v1 : vs\n                             else vs\n        go (n-1) blocks1 v1 newChainRes \n\n\n{-runMala :: Matrix Double -> (Vector Double -> (Double,Vector Double)) \n         ->  Int -> Vector Double -> RIO [(Double,Vector Double)]\nrunMala cov postgrad nsam init = go nsam mp1 [] where\n  go 0 mpar xs = do io $ putStrLn $ \"MALA accept = \"++show (mpAccept mpar/mpCount mpar)\n                    io $ putStrLn $ \"MALA sigma = \"++show (mpSigma mpar)\n                    return xs\n  go n y xs = do y1 <- sample $ mala1 cov postgrad y\n                 go (n-1) y1 $ (mpPi y1, mpXi y1):xs \n  (pi, gradi) = postgrad init\n  mp1 =  MalaPar init pi (gradi)  1 0 0 False -}\n\nrunMalaMP :: Covariance a => a -> (Vector Double -> (Double,Vector Double)) \n         ->  Int -> MalaPar -> [(Double,Vector Double)] -> RIO (MalaPar, [(Double,Vector Double)])\nrunMalaMP cov  pdf nsam init xs0 = go nsam init xs0 where\n  go 0 mpar xs = do io $ putStrLn $ \"MALA accept = \"++show (mpAccept mpar/mpCount mpar)\n                    io $ putStrLn $ \"MALA sigma = \"++show (mpSigma mpar)\n                    return (mpar, xs)\n  go n y xs = do y1 <- sample $ mala1 cov pdf True y\n--                 io $ do putStrLn $ show (mpCount y1, mpPi y1, mpSigma y1)\n--                         hFlush stdout\n                 let newChainRes = if mpThin y1 == 0 || round (mpCount y1) `mod` mpThin y1 ==0\n                                      then let !xi = mpXi y1\n                                               !pi = mpPi y1\n                                               !more = (pi,xi)\n                                           in more:xs \n                                      else xs\n                 go (n-1) y1 newChainRes\n\nrunMalaUntilBetter :: Covariance a => a ->(Vector Double -> (Double,Vector Double)) \n         ->  Int -> MalaPar -> RIO (MalaPar, [(Double,Vector Double)])\nrunMalaUntilBetter cov  pdf nsam init = go nsam init [] where\n  pTarget = mpPi init\n  go 0 mpar xs = do io $ putStrLn $ \"MALA accept = \"++show (mpAccept mpar/mpCount mpar)\n                    io $ putStrLn $ \"MALA sigma = \"++show (mpSigma mpar)\n                    return (mpar, xs)\n  go n y xs = do y1 <- sample $ mala1 cov  pdf True y\n                 io $ do putStrLn $ show (mpCount y1, mpPi y1, mpSigma y1)\n                         hFlush stdout\n                 let newChainRes = if mpThin y1 == 0 || round (mpCount y1) `mod` mpThin y1 ==0\n                                      then (mpPi y1, mpXi y1):xs \n                                      else xs\n                 if mpPi y1 > pTarget \n                    then return (y1, newChainRes)\n                    else go (n-1) y1 $ newChainRes\n\n\n{-runMalaMPaccept' :: Matrix Double -> (Vector Double -> (Double,Vector Double)) \n         ->  Int -> MalaPar -> RIO (MalaPar, [(Double,Vector Double)])\nrunMalaMPaccept'  cov pdf nsam init  = do\n  stseed <- S.get\n  res <- io $ do\n   seedref <- newIORef stseed\n   resRef <- newIORef Nil\n   let go !mpar  \n        | (round $ mpAccept mpar) >= nsam \n          = return mpar\n        | otherwise \n          = do seed <- readIORef seedref\n               putStr ((show (round $ mpAccept mpar)) ++\".\") >> hFlush stdout\n               let (!mpar1, !seed1) = unSam (mala1 cov pdf mpar) seed\n               writeIORef seedref seed1\n               modifyIORef resRef (Cons (Pair (mpPi mpar1) ( mpXi mpar1)))\n               go mpar1\n   mpar <- go init\n   seed <- readIORef seedref\n   reslist <- readIORef resRef\n   return (seed, (mpar,reslist))\n  S.put $ fst res\n  let mp = fst $ snd res\n  return $ (mp, map unPair $ unList $ snd $ snd res)\n \n--  pi = pdf $ toList $ mpXi init -}\n\nrunMalaMPaccept :: Covariance a => a -> (Vector Double -> (Double,Vector Double)) \n         -> Int -> MalaPar ->  RIO (MalaPar, [(Double,Vector Double)])\nrunMalaMPaccept cov pdf nsam init = go init [] where\n  go !mpar !xs\n    | (round $ mpAccept mpar) >= nsam = do\n         io $ putStrLn $ \"MALA accept = \"++show (mpAccept mpar/mpCount mpar)\n         io $ putStrLn $ \"MALA sigma = \"++show (mpSigma mpar)\n         return (mpar, xs)\n    | mpAccept mpar < 0.5 && mpCount mpar > 20 = \n         return (mpar, [])\n    | otherwise = do\n         !mpar1 <- sample $ mala1 cov  pdf True mpar\n         io $ putStr ((show (round $ mpAccept mpar)) ++\".\") >> hFlush stdout\n         go mpar1 $ (mpPi mpar1, mpXi mpar1):xs\n \nkmala = 5\n\n{-runMalaRioESS ::  Matrix Double -> (Vector Double -> (Double,Vector Double)) \n                  ->  Int -> Vector Double -> RIO [Vector Double]\nrunMalaRioESS cov pdf want_ess xi = do\n    let (p0,grad0) = pdf xi\n    let sigma0 = 1.5 / (realToFrac $ dim xi) -- determined empirically\n    let mp0 = MalaPar xi p0 grad0 sigma0 0 0 False\n        nsam0 = want_ess*20\n    io $ putStrLn $ \"initial sigma = \"++show (mpSigma mp0)\n    (mp1, xs1) <- runMalaMP cov pdf nsam0 mp0 []\n    let have_ess = min (mpAccept mp1) $ calcESSprim $ map snd xs1\n    if have_ess > realToFrac want_ess\n       then return $ map snd xs1\n       else do let need_ess =  max 1 $ realToFrac want_ess - have_ess\n                   samples_per_es = realToFrac nsam0/have_ess\n                   to_do = round $ samples_per_es * need_ess \n               (mp2, xs2) <- runMalaMP cov pdf to_do mp1 xs1\n               return  $ map snd  xs2 -}\n\nrunMalaRioCodaESS ::  Covariance a => a-> (Vector Double -> (Double,Vector Double)) \n                  ->  Int -> Double -> Vector Double -> RIO [Vector Double]\nrunMalaRioCodaESS cov pdf want_ess truncN xi = do\n    let (p0,grad0) = pdf xi\n    let sigma0 = 1.5 / (realToFrac $ dim xi) -- determined empirically\n    let mp0 = MalaPar xi p0 (trunc truncN grad0) sigma0 0 0 False 0 truncN\n        nsam0 = want_ess*1\n    let converged mp  xs = do\n         let have_ess = min (mpAccept mp) $ calcESSprim $ map snd xs\n         io $ putStrLn $ \"ESS=\" ++show have_ess\n         if have_ess > realToFrac want_ess\n            then return $ map snd xs\n            else do let need_ess =  max 1 $ realToFrac want_ess - have_ess\n                        samples_per_es = realToFrac nsam0/have_ess\n                        to_do = round $ samples_per_es * need_ess \n                    io $ putStrLn $ \"running converged for \"++show to_do\n                    (mp2, xs2) <- runMalaMP cov pdf to_do (mp {mpFreezeSigma = True}) xs\n                    io $ putStrLn $ \"All done\"\n                    return $ map snd xs2 \n    let go mp  n xs = do\n            (mp2, xs2) <- runMalaMP cov  pdf n mp []\n            let testres = mannWhitneyUtest TwoTailed 0.05 (U.fromList $ map fst xs2)\n                                            (U.fromList $ map fst xs) \n              \n            if testres/= Just NotSignificant\n               then do io$ putStrLn $ \"not converged: \"++show testres++\" at \"++show (mpPi mp2)\n                       go mp2  (round $ realToFrac n*2) xs2\n               else do io$ putStrLn \"converged!\"\n                       converged mp2  (xs2++xs)\n    \n    io $ putStrLn $ \"initial sigma = \"++show (mpSigma mp0)\n    (mp1, xs1) <- runMalaMPaccept cov  pdf nsam0 mp0 \n    case xs1 of\n            [] -> return []\n            _ -> go mp1  (round $ mpCount mp1) xs1\n\n{-    case (spoon (invlndet cov), mbCholSH cov) of\n       (Just (covInv, (lndt,_)), Just covChol) -> go_rest (covInv, covChol)\n       _ -> let cov' = PDF.posdefify cov in \n            case (spoon (invlndet cov'), mbCholSH cov') of\n              (Just (covInv, (lndt,_)), Just covChol) -> go_rest (covInv, covChol)\n              _ ->  do io $ putStrLn \"non-invertible covariance matrix\"\n                       return [] -}\n\nrunMalaRioSimple ::  Covariance a => a -> (Vector Double -> (Double,Vector Double)) \n                  ->  Int -> Double -> Int -> Vector Double -> RIO [Vector Double]\nrunMalaRioSimple cov pdf samples maxGrad thinN xi = do\n    let (p0,grad0) = pdf xi\n    let sigma0 = 2.7e-4 --1.5 / (realToFrac $ dim xi) -- determined empirically\n    let mp0 = MalaPar xi p0 (trunc maxGrad grad0) sigma0 0 0 False thinN maxGrad\n    \n    (mp2, xs2) <- runMalaMP cov  pdf samples mp0 []\n    io $ putStrLn $ \"All done\"\n    return $ map snd xs2 \n\ncalcCovariance :: Vector Double -> \n                  Vector Double -> \n                  (Vector Double -> (Double,Vector Double)) ->\n                  (Vector Double -> Double) -> \n                  Either (Vector Double) (Matrix Double, Matrix Double, Matrix Double)\ncalcCovariance vinit vnear postgrad posterior = finalcov where\n   ndim = dim vinit\n   finalcov \n     | ndim > 0 -- > 20000 --FIXME \n        = Left $ calcFDindepVars vinit vnear posterior --Left $ iCov vinit -- \n     | otherwise \n        = hessToCov (calcFDhess vinit vnear postgrad) Nothing\n\niCov v = VS.replicate (VS.length v) 1 -- in (m,m,m)\n\ncalcFDindepVars v v' post = trace (\"FDVars = \"++show (VS.take 10 vars))  $ vars where\n   hv =  mapVector (*1e-4) v --mapVector (max 1e-9 .  abs) $ v - v'\n   n = dim v\n   postv = post v\n   postPlus i = post $ v VS.// [(i,v @>i + hv @> i)]\n   postMinus i = post $ v VS.// [(i,v @>i - hv@> i)]\n   vars = buildVector n fvar\n   fvar i = negate $ recip $ (postPlus i - 2*postv + postMinus i)/((hv @> i)*(hv @> i))\n\n\ncalcFDhess v v' postgrad = hess2 where\n   grad =  snd . postgrad\n   gradi i = (@>i) . grad\n   hv = mapVector (max 1e-9 . abs) $ v - v'\n   n = dim v\n   gradv = grad v\n   grads =  fromRows $ flip map [0..(n-1)] $ \\i -> \n               grad (v VS.// [(i,v @>i + hv @> i)])\n   fhess (i,j) | i<j = 0\n               | otherwise = (grads @@>(j,i) - (gradv @> i))\n                                       /(2*(hv @> j)) +\n                             (grads @@>(i,j)- (gradv @> j))\n                                       /(2*(hv @> i))\n                 \n--   hess3 = scale (recip $ realToFrac n) $ sum $ map outerSelf $ grads                      \n                             \n   hess1 = buildMatrix n n fhess \n   hess2 = buildMatrix n n $ \\(i,j) -> if i>=j then hess1 @@> (i,j)\n                                               else hess1 @@> (j,i)\n \n\nouterSelf v= v `outer` v\n\nhessToCov hess mOriginal = \n   let mTryPosdefify = case mOriginal of \n            Nothing -> hessToCov (PDF.posdefify hess) (Just hess)\n            Just horiginal -> let ds =  mapVector (negate . recip) \n                                         $ takeDiag horiginal \n                              in trace (\"USING DIAGS\"++show (VS.take 10 ds)) $ Left $ ds\n   in\n   case spoon $ inv $ negate $ hess of\n     Just cov -> case mbCholSH cov of\n                   Just cholm ->  trace (\"invert success:\"++show (VS.take 10 $ takeDiag cov) ++ \"det=\"++show (det cov)) $ Right (cov, negate hess, cholm)\n                   Nothing -> trace (\"chol fail\") mTryPosdefify\n     Nothing -> trace (\"inv fail\") mTryPosdefify\n                  {- Just cov -> case mbCholSH cov of\n                                Just cholm ->  Right (cov, negate hessToCov,cholm)\n                                Nothing -> case mbCholSH $ PDF.posdefify cov of\n                                            Just cholm -> Right (cov, negate hess,cholm)\n                                            Nothing -> vars\n                  Nothing -> vars -}\n\nacceptSM ampar  | mpCount ampar == 0 = \"0/0\"\n               | otherwise = printf \"%.3g\" (rate::Double) ++ \" (\"++show yes++\"/\"++show total++\")\" where\n   rate = realToFrac (yes) / realToFrac (total)\n   yes = mpAccept ampar\n   total = mpCount ampar", "meta": {"hexsha": "64cd3f514ee9d5cade2333f5370f31d4c776bcd8", "size": 17132, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/Probably/MALA.hs", "max_stars_repo_name": "glutamate/probably", "max_stars_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-28T03:19:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:44.000Z", "max_issues_repo_path": "Math/Probably/MALA.hs", "max_issues_repo_name": "glutamate/probably", "max_issues_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "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": "Math/Probably/MALA.hs", "max_forks_repo_name": "glutamate/probably", "max_forks_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4822335025, "max_line_length": 153, "alphanum_fraction": 0.553292085, "num_tokens": 5048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.46199949378637023}}
{"text": "module Statistics.GModeling.Models.LDA\n  (\n  ) where\n\nimport Statistics.GModeling.DSL\n\ndata LDALabels = Alpha | Beta | Topics | Topic\n               | Doc | Symbols | Symbol\n\nlda :: Network LDALabels\nlda =\n  [\n    Only Alpha :-> Topics\n  , Only Beta :-> Symbols\n  , (Topics :@ Doc) :-> Topic\n  , (Symbols :@ Topic) :-> Symbol\n  ]\n", "meta": {"hexsha": "8f27e796f87fb8c2ac09316335b3fb0d826dc017", "size": 330, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/GModeling/Models/LDA.hs", "max_stars_repo_name": "nanonaren/gmodeling", "max_stars_repo_head_hexsha": "befb0f3cca0c212e368497e86f030aa96355be18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/GModeling/Models/LDA.hs", "max_issues_repo_name": "nanonaren/gmodeling", "max_issues_repo_head_hexsha": "befb0f3cca0c212e368497e86f030aa96355be18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/GModeling/Models/LDA.hs", "max_forks_repo_name": "nanonaren/gmodeling", "max_forks_repo_head_hexsha": "befb0f3cca0c212e368497e86f030aa96355be18", "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": 18.3333333333, "max_line_length": 46, "alphanum_fraction": 0.6060606061, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.46176469791825503}}
{"text": "{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies #-}\n\nmodule Lib\n    ( TD(..),\n      start,start',\n      advances,advances',\n      retreats,retreats',\n      stepRandom,stepRandom',\n      rhombus,\n      diaTD\n    ) where\n\nimport qualified Data.Map.Strict as M\nimport Data.Foldable\nimport Control.Monad\nimport Control.Monad.Random.Class\nimport Diagrams.Prelude hiding (conjugate,start)\nimport Data.Complex\nimport Data.Foldable\n\n\ni = 0:+1\nomega = (-1/2) :+ (sqrt 3/2)\nomega' = conjugate omega\n\nvec (x :+ y) = V2 x y\npt (x :+ y) = p2 (x,y)\n\n\ndata TD = TD {\n  volume :: !Int,\n  hXYtoZ :: M.Map (Int,Int) Int,\n  hYZtoX :: M.Map (Int,Int) Int,\n  hZXtoY :: M.Map (Int,Int) Int} deriving (Show,Eq)\n\nstart = TD 0 M.empty M.empty M.empty\n\nstartR :: Int -> Int -> M.Map (Int,Int) Int\nstartR m n = M.fromList [((i,j),0)|i<-[0..m-1],j<-[0..n-1]]\n\nstart' l m n = TD 0 (startR l m) (startR m n) (startR n l)\n\n\nfindC :: Int -> Int -> M.Map (Int,Int) Int -> Int\nfindC u v = M.findWithDefault 0 (u,v)\n\nbound :: M.Map (Int,Int) Int -> Int\nbound x = case (M.toDescList x) of\n  [] -> 0\n  ((a,_),_):_ -> a+1\n\nadv :: Maybe Int -> Maybe Int\nadv Nothing = Just 1\nadv (Just x) = Just (x+1)\n\nadvance :: TD -> Int -> Int -> Int -> TD\nadvance (TD v xyZ yzX zxY) x y z =\n  TD (v+1) (M.alter adv (x,y) xyZ) (M.alter adv (y,z) yzX) (M.alter adv (z,x) zxY)\n\nadvances :: TD -> [TD]\nadvances d@(TD v xyZ yzX zxY) = do\n  x <- [0..bound xyZ]\n  y <- [0..bound yzX]\n  let z = findC x y xyZ\n  guard $ x == findC y z yzX\n  guard $ y == findC z x zxY\n  return $ advance d x y z\n\nadvances' :: TD -> [TD]\nadvances' d@(TD v xyZ yzX zxY) = do\n  ((x,y),z) <- M.toList xyZ\n  guard $ Just x == M.lookup (y,z) yzX\n  guard $ Just y == M.lookup (z,x) zxY\n  return $ advance d x y z\n\nrtr :: Maybe Int -> Maybe Int\nrtr Nothing = Nothing -- shouldn't happen though\nrtr (Just 1) = Nothing\nrtr (Just x) = Just (x-1)\n\nretreat :: TD -> Int -> Int -> Int -> TD\nretreat (TD v xyZ yzX zxY) x y z = \n  TD (v-1) (M.alter rtr (x,y) xyZ) (M.alter rtr (y,z) yzX) (M.alter rtr (z,x) zxY)\n\nretreats :: TD -> [TD]\nretreats d@(TD v xyZ yzX zxY) = do\n  x <- [0..bound xyZ]\n  y <- [0..bound yzX]\n  let z = (findC x y xyZ) - 1\n  guard $ z>=0\n  guard $ x + 1 == findC y z yzX\n  guard $ y + 1 == findC z x zxY\n  return $ retreat d x y z\n\nretreat' :: TD -> Int -> Int -> Int -> TD\nretreat' (TD v xyZ yzX zxY) x y z =\n  TD (v-1) (M.adjust s (x,y) xyZ) (M.adjust s (y,z) yzX) (M.adjust s (z,x) zxY)\n  where s = subtract 1\n\nretreats' :: TD -> [TD]\nretreats' d@(TD v xyZ yzX zxY) = do\n  ((x,y),z') <- M.toList xyZ\n  let z = z'-1\n  guard $ Just (x+1) == M.lookup (y,z) yzX\n  guard $ Just (y+1) == M.lookup (z,x) zxY\n  return $ retreat' d x y z\n\nstepRandom d = uniform $ (advances d ++ retreats d)\nstepRandom' d = uniform $ (advances' d ++ retreats' d)\n\n\nrhombus :: Trail' Loop V2 Double\nrhombus = fromVertices . map pt $ [0, omega, omega+omega', omega',0]\n\nsh :: Int -> Int -> Int -> Complex Double\nsh x y z = fromIntegral x*omega+fromIntegral y*omega'+fromIntegral z\n\nrhombi = foldMap w . M.toList\n  where w ((x,y),z) = strokeLoop rhombus # translate (vec $ sh x y z)\n\ndiaTD (TD _ xyZ yzX zxY) = (fc lightblue (rhombi  xyZ) <>\n                            (rotateBy (1/3) . fc darkblue) (rhombi yzX) <>\n                            (rotateBy (2/3) . fc blue) (rhombi zxY)) # lw thin # rotateBy (1/4) # pad 1.1\n\nsomeFunc :: IO ()\nsomeFunc = putStrLn \"someFunc\"\n", "meta": {"hexsha": "ddb2eb4b197e38563e76380bbd8b2313c1e31448", "size": 3430, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "william42/calissons", "max_stars_repo_head_hexsha": "ae12e3ab1c3270688a3aba9b047506bfda3c5aa9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "william42/calissons", "max_issues_repo_head_hexsha": "ae12e3ab1c3270688a3aba9b047506bfda3c5aa9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lib.hs", "max_forks_repo_name": "william42/calissons", "max_forks_repo_head_hexsha": "ae12e3ab1c3270688a3aba9b047506bfda3c5aa9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5891472868, "max_line_length": 105, "alphanum_fraction": 0.5857142857, "num_tokens": 1317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.46155256557954527}}
{"text": "{-# LANGUAGE RankNTypes, FlexibleContexts, TypeFamilies #-}\nmodule Quipp.Util where\n\nimport Control.Monad (liftM)\nimport Control.Monad.State.Lazy (runState)\nimport Control.Monad.Identity\nimport Debug.Trace\nimport Data.Function (on)\nimport Data.List (groupBy, sortBy)\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.Random (MonadRandom, RandomSource, RVarT, RVar, StdRandom(StdRandom), sampleState, runRVar, runRVarT, runRVarTWith, stdUniform)\nimport qualified Data.Packed.Matrix as Mat\nimport Numeric.LinearAlgebra.Algorithms (linearSolve, pinv)\nimport Numeric.AD (diff, Mode, Scalar)\nimport System.Random (StdGen, mkStdGen)\n\nfst3 (a, _, _) = a\nsnd3 (_, b, _) = b\nthd3 (_, _, c) = c\n\ninsertAll :: Ord k => [(k, v)] -> Map k v -> Map k v\ninsertAll kvs m = foldr (\\(k, v) m -> Map.insert k v m) m kvs\n\ninfixr 9 .:\n(f .: g) x y = f (g x y)\n\ntraced label x = trace (label ++ \" \" ++ show x) x\n\ntakeEvery :: Int -> [a] -> [a]\ntakeEvery _ [] = []\ntakeEvery n (x:xs) = x : takeEvery n (drop (n-1) xs)\n\nsampleRVar :: MonadRandom m => RVar a -> m a\nsampleRVar v = runRVar v StdRandom\n\nsampleRVarT v = runRVarT v StdRandom\n\nsampleRVarTWith :: RandomSource m StdRandom => (forall t. n t -> m t) -> RVarT n a -> m a\nsampleRVarTWith f v = runRVarTWith f v StdRandom\n\ninfinity :: Double\ninfinity = read \"Infinity\"\n\nnegInfinity :: Double\nnegInfinity = read \"-Infinity\"\n\nfunPow :: Int -> (a -> a) -> a -> a\nfunPow n f x = iterate f x !! n\n\nzipWithSameLength f [] [] = []\nzipWithSameLength f (x:xs) (y:ys) = f x y : zipWithSameLength f xs ys\nzipWithSameLength _ _ _ = error \"zipWithSameLength: different lengths\"\n\nzipSameLength = zipWithSameLength (,)\n\niterateM :: Monad m => Int -> (a -> m a) -> a -> m [a]\niterateM 0 _ x = return [x]\niterateM n f x = liftM (x:) (f x >>= iterateM (n-1) f)\n\nstateInfList :: (s -> (a, s)) -> s -> [a]\nstateInfList f s =\n  let (a, s') = f s in a : stateInfList f s'\n\niterateRVar :: (a -> RVar a) -> a -> RVar [a]\niterateRVar f x = do\n  seed <- stdUniform\n  return $ stateInfList (\\(y, gen) -> let (y', gen') = sampleState (f y) gen in (y', (y', gen'))) (x, mkStdGen seed)\n\ngroupAnywhereBy :: Ord b => (a -> b) -> [a] -> [[a]]\ngroupAnywhereBy f = groupBy ((==) `on` f) . sortBy (compare `on` f)\n\nlogSumExp :: RealFloat a => [a] -> a\nlogSumExp lps = mx + log (sum [exp (lp - mx) | lp <- lps])\n  where mx = maximum lps\n\n-- logSumExp :: RealFloat a => [a] -> a\n-- logSumExp lps = log $ sum $ map exp lps\n\nlogProbsToProbs :: [Double] -> [Double]\nlogProbsToProbs lps = [exp (lp - lse) | lp <- lps]\n  where lse = logSumExp lps\n\nrealToDouble :: Real s => s -> Double\nrealToDouble = fromRational . toRational\n\ntype Matrix a = [[a]]\n\ndiagonalEntries :: Matrix a -> [a]\ndiagonalEntries ((x:xs):rows) = x : diagonalEntries (map tail rows)\n\nouterProduct :: Num a => [a] -> [a] -> Matrix a\nouterProduct as bs = [[a*b | b <- bs] | a <- as]\n\nsplitListIntoBlocks :: Int -> [a] -> [[a]]\nsplitListIntoBlocks n lst\n  | blocksize * n /= length lst = undefined\n  | blocksize == 0 = replicate n []\n  | otherwise = go blocksize lst\n  where blocksize = length lst `div` n\n        go _ [] = []\n        go k lst = take k lst : go k (drop k lst)\n\nscaleVec :: Num a => a -> [a] -> [a]\nscaleVec x = map (x *)\n\ntranspose xs = if maximum (map length xs) == 0 then [] else map head xs : transpose (map tail xs)\n\ndotProduct :: Num a => [a] -> [a] -> a\ndotProduct x y = sum (zipWith (*) x y)\n\nsquareMagnitude :: Num a => [a] -> a\nsquareMagnitude x = dotProduct x x\n\nmatMulByVector :: Num a => Matrix a -> [a] -> [a]\nmatMulByVector m v = map (dotProduct v) m\n\nmatMul :: Num a => Matrix a -> Matrix a -> Matrix a\nmatMul m1 m2 = map (matMulByVector m1) (transpose m2)\n\nmatInv :: Matrix Double -> Matrix Double\nmatInv = Mat.toLists . pinv . Mat.fromLists\n\nlinSolve :: Matrix Double -> [Double] -> [Double]\nlinSolve mat d =\n  matMulByVector (Mat.toLists $ pinv $ Mat.fromLists mat) d\n\ndiagEntries :: Matrix a -> [a]\ndiagEntries m\n  | length m == 0 || length m == length (head m) =\n    zipWith (!!) m [0..]\n  | otherwise = error $ \"Cannot get diagonal entries of non-square matrix \" ++ show (length m, length (head m))\n\nfromDouble :: Fractional a => Double -> a\nfromDouble = fromRational . toRational\n\ntoDouble :: Real a => a -> Double\ntoDouble = fromRational . toRational\n\n{- f(x) = ax^2 + bx + c\n - f'(x) = 2ax + b\n - f''(x) = 2a\n - a = f''(x) / 2\n - b = f'(x) - 2ax\n - c = f(x) - bx - ax^2\n -}\nquadApproximation :: (forall a. (Mode a, RealFloat a) => a -> a) -> Double -> (Double, Double, Double)\nquadApproximation f x =\n  let deriv = diff f x\n      deriv2 = diff (diff f :: (forall a. (Mode a, RealFloat a) => a -> a)) x\n      a = deriv2 / 2\n      b = deriv - 2 * a * x\n      c = f x - b * x - a * x * x\n  in (c, b, a)\n\n\nmean xs = sum xs / fromIntegral (length xs)\n\nvariance xs = sum [(x-m)^2 | x <- xs] / fromIntegral (length xs) where m = mean xs\n\ncovariance xys = sum [(x - ux) * (y - uy) | (x, y) <- xys] / fromIntegral (length xys)\n  where ux = mean (map fst xys)\n        uy = mean (map snd xys)\n\n", "meta": {"hexsha": "8b459a0a8673464acbf5e9ca9d920b38724e0381", "size": 4998, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Quipp/Util.hs", "max_stars_repo_name": "jessica-taylor/quipp2", "max_stars_repo_head_hexsha": "e780626d986b98915c6272df60c7cfcd13ee58e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Quipp/Util.hs", "max_issues_repo_name": "jessica-taylor/quipp2", "max_issues_repo_head_hexsha": "e780626d986b98915c6272df60c7cfcd13ee58e3", "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/Quipp/Util.hs", "max_forks_repo_name": "jessica-taylor/quipp2", "max_forks_repo_head_hexsha": "e780626d986b98915c6272df60c7cfcd13ee58e3", "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": 30.2909090909, "max_line_length": 139, "alphanum_fraction": 0.6206482593, "num_tokens": 1678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.4613827221186103}}
{"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\n\n{-|\nModule      : Balanced\nDescription : Amplitude-balanced path sums\nCopyright   : (c) Matthew Amy, 2020\nMaintainer  : matt.e.amy@gmail.com\nStability   : experimental\nPortability : portable\n-}\n\nmodule Feynman.Algebra.Pathsum.Balanced where\n\nimport Data.List\nimport qualified Data.Set as Set\nimport Data.Ratio\nimport Data.Semigroup\nimport Control.Monad (mzero, msum)\nimport Data.Maybe (maybeToList)\nimport Data.Complex (Complex, mkPolar)\nimport Data.Bits (shiftL)\nimport Data.Map (Map, (!))\nimport qualified Data.Map as Map\nimport Data.String (IsString(..))\nimport Data.Tuple (swap)\n\nimport qualified Feynman.Util.Unicode as U\nimport Feynman.Algebra.Base\nimport Feynman.Algebra.Polynomial (degree)\nimport Feynman.Algebra.Polynomial.Multilinear\n\n{-----------------------------------\n Variables\n -----------------------------------}\n\n-- | Variables are either input variables or path variables. The distinction\n--   is due to the binding structure of our pathsum representation, and moreover\n--   improves readability\ndata Var = IVar !Int | PVar !Int | FVar !String deriving (Eq, Ord)\n\ninstance Show Var where\n  show (IVar i) = U.sub \"x\" $ fromIntegral i\n  show (PVar i) = U.sub \"y\" $ fromIntegral i\n  show (FVar x) = x\n\ninstance IsString Var where\n  fromString = FVar\n\n-- | Convenience function for the string representation of the 'i'th input variable\nivar :: Int -> String\nivar = show . IVar\n\n-- | Convenience function for the string representation of the 'i'th path variable\npvar :: Int -> String\npvar = show . PVar\n\n-- | Construct an integer shift for input variables\nshiftI :: Int -> (Var -> Var)\nshiftI i = shiftAll i 0\n\n-- | Construct an integer shift for path variables\nshiftP :: Int -> (Var -> Var)\nshiftP j = shiftAll 0 j\n\n-- | General shift. Constructs a substitution from shift values for I and P\nshiftAll :: Int -> Int -> (Var -> Var)\nshiftAll i j = go\n  where go (IVar i') = IVar (i + i')\n        go (PVar j') = PVar (j + j')\n\n-- | Check if a variable is an input\nisI :: Var -> Bool\nisI (IVar _) = True\nisI _        = False\n\n-- | Check if a variable is a path variable\nisP :: Var -> Bool\nisP (PVar _) = True\nisP _        = False\n\n-- | Check if a variable is a free variable\nisF :: Var -> Bool\nisF (FVar _) = True\nisF _        = False\n\n-- | Get the string of a free variable\nunF :: Var -> String\nunF (FVar s) = s\nunF _        = error \"Not a free variable\"\n\n{-----------------------------------\n Path sums\n -----------------------------------}\n\n-- | Path sums of the form\n--   \\(\\frac{1}{\\sqrt{2}^k}\\sum_{y\\in\\mathbb{Z}_2^m}e^{i\\pi P(x, y)}|f(x, y)\\rangle\\)\ndata Pathsum g = Pathsum {\n  sde       :: !Int,\n  inDeg     :: !Int,\n  outDeg    :: !Int,\n  pathVars  :: !Int,\n  phasePoly :: !(PseudoBoolean Var g),\n  outVals   :: ![SBool Var]\n  } deriving (Eq)\n\ninstance (Show g, Eq g, Periodic g, Real g) => Show (Pathsum g) where\n  show sop = inputstr ++ scalarstr ++ sumstr ++ amplitudestr ++ statestr\n    where inputstr = case inDeg sop of\n            0 -> \"\"\n            1 -> U.ket (ivar 0) ++ \" \" ++ U.mapsto ++ \" \"\n            2 -> U.ket (ivar 0) ++ U.ket (ivar 1) ++ \" \" ++ U.mapsto ++ \" \"\n            j -> U.ket (ivar 0) ++ U.dots ++ U.ket (ivar (j-1)) ++ \" \" ++ U.mapsto ++ \" \"\n          scalarstr = case compare (sde sop) 0 of\n            LT -> U.sup (\"(\" ++ U.rt2 ++ \")\") (fromIntegral . abs $ sde sop)\n            EQ -> if (inDeg sop == 0 && outDeg sop == 0 && phasePoly sop == 0) then \"1\" else \"\"\n            GT -> U.sup (\"1/(\" ++ U.rt2 ++ \")\") (fromIntegral $ sde sop)\n          sumstr = case pathVars sop of\n            0 -> \"\"\n            1 -> U.sum ++ \"[\" ++ pvar 0 ++ \"]\"\n            2 -> U.sum ++ \"[\" ++ pvar 0 ++ pvar 1 ++ \"]\"\n            j -> U.sum ++ \"[\" ++ pvar 0 ++ U.dots ++ pvar (j-1) ++ \"]\"\n          amplitudestr = case order (phasePoly sop) of\n            0 -> U.e ++ \"^\" ++ U.i ++ U.pi ++ \"{\" ++ show (phasePoly sop) ++ \"}\"\n            1 -> \"\"\n            2 -> \"(-1)^{\" ++ show (makeIntegral 1 $ phasePoly sop) ++ \"}\"\n            4 -> U.i ++ \"^{\" ++ show (makeIntegral 2 $ phasePoly sop) ++ \"}\"\n            8 -> U.omega ++ \"^{\" ++ show (makeIntegral 4 $ phasePoly sop) ++ \"}\"\n            j -> U.sub U.zeta j ++ \"^{\" ++ show (makeIntegral j $ phasePoly sop) ++ \"}\"\n          statestr = concatMap (U.ket . show) $ outVals sop\n\n-- | Convenience function for pretty printing\nmakeIntegral :: Real g => Integer -> PseudoBoolean v g -> PseudoBoolean v Integer\nmakeIntegral i = cast (\\a -> numerator $ toRational a * toRational i)\n\n-- | Retrieve the internal path variables\ninternalPaths :: Pathsum g -> [Var]\ninternalPaths sop = [PVar i | i <- [0..pathVars sop - 1]] \\\\ outVars\n  where outVars = Set.toList . Set.unions . map vars $ outVals sop\n\n-- | Retrieve the free variables\nfreeVars :: Pathsum g -> [String]\nfreeVars sop = map unF . Set.toList . Set.filter isF . foldr (Set.union) Set.empty $ xs\n  where xs = (vars $ phasePoly sop):(map vars $ outVals sop)\n\n-- | Checks if the path sum is (trivially) the identity\nisTrivial :: (Eq g, Num g) => Pathsum g -> Bool\nisTrivial sop = sop == identity (inDeg sop)\n\n-- | (To be deprecated) Drops constant term from the phase polynomial\ndropGlobalPhase :: (Eq g, Num g) => Pathsum g -> Pathsum g\ndropGlobalPhase sop = sop { phasePoly = dropConstant $ phasePoly sop }\n\n-- | (To be deprecated) Drops the phase polynomial\ndropPhase :: (Eq g, Num g) => Pathsum g -> Pathsum g\ndropPhase sop = sop { phasePoly = 0 }\n\n-- | (To be deprecated) Drops normalization\ndropAmplitude :: Pathsum g -> Pathsum g\ndropAmplitude sop = sop { sde = 0 }\n\n{----------------------------\n Constructors\n ----------------------------}\n\n-- | Construct an 'n'-qubit identity operator\nidentity :: (Eq g, Num g) => Int -> Pathsum g\nidentity n = Pathsum 0 n n 0 0 [ofVar (IVar i) | i <- [0..n-1]]\n\n-- | Construct a (symbolic) state\nket :: (Eq g, Num g) => [SBool String] -> Pathsum g\nket xs = Pathsum 0 0 (fromIntegral $ length xs) 0 0 $ map (rename FVar) xs\n\n-- | Initialize a fresh ancilla\ninitialize :: (Eq g, Num g) => FF2 -> Pathsum g\ninitialize b = ket [constant b]\n\n{-# INLINE initialize #-}\n\n-- | Construct a uniform superposition of classical states of a given form\nsuperposition :: (Ord v, Eq g, Num g) => [SBool v] -> Pathsum g\nsuperposition xs = Pathsum k 0 n k 0 $ map (rename sub) xs\n  where n   = length xs\n        k   = Set.size fv\n        fv  = Set.unions $ map vars xs\n        sub = ((Map.fromList [(v, PVar i) | (v, i) <- zip (Set.toList fv) [0..]])!)\n\n-- | Construct a classical transformation from the free variables of 'xs' to 'xs'\n--   Effectively binds the free variables in 'state xs'\ncompute :: (Ord v, Eq g, Num g) => [SBool v] -> Pathsum g\ncompute xs = Pathsum 0 (Set.size fv) (length xs) 0 0 $ map (rename sub) xs\n  where fv  = Set.unions $ map vars xs\n        sub = ((Map.fromList [(v, IVar i) | (v, i) <- zip (Set.toList fv) [0..]])!)\n\n-- | Breaks the connection between inputs and outputs by mapping\n--   any input basis state to the maximally mixed state. Non-unitary\ndisconnect :: (Eq g, Num g) => Int -> Pathsum g\ndisconnect n = Pathsum n n n n 0 [ofVar $ PVar i | i <- [0..n-1]]\n\n-- | Construct a permutation\npermutation :: (Eq g, Num g) => [Int] -> Pathsum g\npermutation xs\n  | all (\\i -> i >= 0 && i <= n) xs = Pathsum 0 n n 0 0 (map (ofVar . IVar) xs)\n  | otherwise = error \"permutation: Input not a permutation\"\n  where n = length xs\n\n-- | Construct an n-ary unit\netaN :: (Eq g, Num g) => Int -> Pathsum g\netaN n = Pathsum 0 0 (2*n) n 0 $ xs ++ xs\n  where xs = map (ofVar . PVar) [0..n-1]\n\n{----------------------------\n Dual constructors\n ----------------------------}\n\n-- | Construct a (symbolic) state destructor\nbra :: (Eq g, Abelian g) => [SBool String] -> Pathsum g\nbra xs = Pathsum (2*m) m 0 m (lift $ p) []\n  where m         = fromIntegral $ length xs\n        p         = foldr (+) 0 . map go $ zip [0..] xs\n        go (i, v) = ofVar (PVar i) * (ofVar (IVar i) + (rename fromString v))\n\n-- | Alternate state destructor with fewer paths but a more complicated polynomial\nunstateAlt :: (Eq g, Abelian g) => [SBool String] -> Pathsum g\nunstateAlt xs = Pathsum 2 (fromIntegral $ length xs) 0 1 (lift $ y*(1 + p)) []\n  where y = ofVar (PVar 0)\n        p = foldr (*) 1 . map valF $ zip xs [0..]\n        valF (val, i) = 1 + (rename fromString val) + ofVar (IVar i)\n\n-- | Dagger of initialize -- i.e. unnormalized post-selection\npostselect :: (Eq g, Abelian g) => FF2 -> Pathsum g\npostselect b = bra [constant b]\n\n{-# INLINE postselect #-}\n\n-- | Select on a classical state of a given form\nunsuper :: (Ord v, Eq g, Abelian g) => [SBool v] -> Pathsum g\nunsuper xs = Pathsum (2*m + n) m 0 (m+n) poly []\n  where m    = length xs\n        n    = Set.size fv\n        fv   = Set.unions $ map vars xs\n        sub  = ((Map.fromList [(v, PVar (m + i)) | (v, i) <- zip (Set.toList fv) [0..]])!)\n        poly = foldr (+) zero $ map constructTerm [0..m-1]\n        constructTerm i = lift $ ofVar (PVar i) * (ofVar (IVar i) + rename sub (xs!!i))\n\n-- | Invert a classical transformation\nuncompute :: (Ord v, Eq g, Abelian g) => [SBool v] -> Pathsum g\nuncompute xs = Pathsum (2*m) m n (m+n) poly [ofVar (PVar $ m + i) | i <- [0..n-1]]\n  where m    = length xs\n        n    = Set.size fv\n        fv   = Set.unions $ map vars xs\n        sub  = ((Map.fromList [(v, PVar (m + i)) | (v, i) <- zip (Set.toList fv) [0..]])!)\n        poly = foldr (+) zero $ map constructTerm [0..m-1]\n        constructTerm i = lift $ ofVar (PVar i) * (ofVar (IVar i) + rename sub (xs!!i))\n\n-- | Construct an inverse permutation\nunpermutation :: (Eq g, Num g) => [Int] -> Pathsum g\nunpermutation = permutation . snd . unzip . sort . map swap . zip [0..]\n\n-- | Construct an n-ary co-unit\nepsilonN :: (Eq g, Abelian g) => Int -> Pathsum g\nepsilonN n = Pathsum (2*n) (2*n) 0 n (lift poly) []\n  where poly = sum $ map f [0..n-1]\n        f i  = ofVar (PVar i) * (ofVar (IVar i) + ofVar (IVar $ n+i))\n\n{----------------------------\n Constants & gates\n ----------------------------}\n\n-- | \\(\\sqrt{2}\\)\nroot2 :: (Eq g, Abelian g, Dyadic g) => Pathsum g\nroot2 = Pathsum 0 0 0 1 ((-constant (half * half)) + scale half (lift $ ofVar (PVar 0))) []\n\n-- | \\(1/\\sqrt{2}\\)\nroothalf :: (Eq g, Abelian g, Dyadic g) => Pathsum g\nroothalf = Pathsum 1 0 0 0 0 []\n\n-- | \\(i\\)\niunit :: (Eq g, Abelian g, Dyadic g) => Pathsum g\niunit = Pathsum 0 0 0 0 (constant half) []\n\n-- | \\(e^{i\\pi/4}\\)\nomega :: (Eq g, Abelian g, Dyadic g) => Pathsum g\nomega = Pathsum 0 0 0 0 (constant (half * half)) []\n\n-- | A fresh, 0-valued ancilla\nfresh :: (Eq g, Num g) => Pathsum g\nfresh = Pathsum 0 0 1 0 0 [0]\n\n-- | The dagger of fresh\nunfresh :: (Eq g, Abelian g) => Pathsum g\nunfresh = dagger fresh\n\n-- | The unit, \\(\\eta\\)\neta :: (Eq g, Num g) => Pathsum g\neta = Pathsum 0 0 2 1 0 [ofVar (PVar 0), ofVar (PVar 0)]\n\n-- | The co-unit, \\(\\epsilon\\)\nepsilon :: (Eq g, Abelian g) => Pathsum g\nepsilon = Pathsum 2 2 0 1 p []\n  where p = lift $ ofVar (PVar 0) * (ofVar (IVar 0) + ofVar (IVar 1))\n\n-- | X gate\nxgate :: (Eq g, Num g) => Pathsum g\nxgate = Pathsum 0 1 1 0 0 [1 + ofVar (IVar 0)]\n\n-- | Z gate\nzgate :: (Eq g, Abelian g) => Pathsum g\nzgate = Pathsum 0 1 1 0 p [ofVar (IVar 0)]\n  where p = lift $ ofVar (IVar 0)\n\n-- | Y gate\nygate :: (Eq g, Abelian g, Dyadic g) => Pathsum g\nygate = Pathsum 0 1 1 0 p [1 + ofVar (IVar 0)]\n  where p = constant half + (lift $ ofVar (IVar 0))\n\n-- | S gate\nsgate :: (Eq g, Abelian g, Dyadic g) => Pathsum g\nsgate = Pathsum 0 1 1 0 p [ofVar (IVar 0)]\n  where p = scale half (lift $ ofVar (IVar 0))\n\n-- | S* gate\nsdggate :: (Eq g, Abelian g, Dyadic g) => Pathsum g\nsdggate = Pathsum 0 1 1 0 p [ofVar (IVar 0)]\n  where p = scale (-half) (lift $ ofVar (IVar 0))\n\n-- | T gate\ntgate :: (Eq g, Abelian g, Dyadic g) => Pathsum g\ntgate = Pathsum 0 1 1 0 p [ofVar (IVar 0)]\n  where p = scale (half*half) (lift $ ofVar (IVar 0))\n\n-- | T* gate\ntdggate :: (Eq g, Abelian g, Dyadic g) => Pathsum g\ntdggate = Pathsum 0 1 1 0 p [ofVar (IVar 0)]\n  where p = scale (-half*half) (lift $ ofVar (IVar 0))\n\n-- | R_k gate\nrkgate :: (Eq g, Abelian g, Dyadic g) => Int -> Pathsum g\nrkgate k = Pathsum 0 1 1 0 p [ofVar (IVar 0)]\n  where p = scale (fromDyadic $ dyadic 1 k) (lift $ ofVar (IVar 0))\n\n-- | R_z gate\nrzgate :: (Eq g, Abelian g, Dyadic g) => DyadicRational -> Pathsum g\nrzgate theta = Pathsum 0 1 1 0 p [ofVar (IVar 0)]\n  where p = scale (fromDyadic theta) (lift $ ofVar (IVar 0))\n\n-- | H gate\nhgate :: (Eq g, Abelian g, Dyadic g) => Pathsum g\nhgate = Pathsum 1 1 1 1 p [ofVar (PVar 0)]\n  where p = lift $ (ofVar $ IVar 0) * (ofVar $ PVar 0)\n\n-- | CH gate\nchgate :: (Eq g, Abelian g, Dyadic g) => Pathsum g\nchgate = Pathsum 1 2 2 1 p [x1, x2 + x1*x2 + x1*y]\n  where p = lift $ x1 * x2 * y\n        x1 = ofVar $ IVar 0\n        x2 = ofVar $ IVar 1\n        y = ofVar $ PVar 0\n\n-- | CNOT gate\ncxgate :: (Eq g, Num g) => Pathsum g\ncxgate = Pathsum 0 2 2 0 0 [x0, x0+x1]\n  where x0 = ofVar $ IVar 0\n        x1 = ofVar $ IVar 1\n\n-- | Toffoli gate\nccxgate :: (Eq g, Num g) => Pathsum g\nccxgate = Pathsum 0 3 3 0 0 [x0, x1, x2 + x0*x1]\n  where x0 = ofVar $ IVar 0\n        x1 = ofVar $ IVar 1\n        x2 = ofVar $ IVar 2\n\n-- | k-control Toffoli gate\nmctgate :: (Eq g, Num g) => Int -> Pathsum g\nmctgate k = Pathsum 0 (k+1) (k+1) 0 0 (controls ++ [t + foldr (*) 1 controls])\n  where controls = [ofVar (IVar i) | i <- [0..k-1]]\n        t        = ofVar $ IVar k\n\n-- | SWAP gate\nswapgate :: (Eq g, Num g) => Pathsum g\nswapgate = Pathsum 0 2 2 0 0 [x1, x0]\n  where x0 = ofVar $ IVar 0\n        x1 = ofVar $ IVar 1\n\n{----------------------------\n Channels\n ----------------------------}\n\n-- | Choi matrix of computational basis measurement\nmeasureChoi :: (Eq g, Abelian g) => Pathsum g\nmeasureChoi = Pathsum 2 2 2 1 (lift $ y * (x0 + x1)) [x0, x1]\n  where x0 = ofVar $ IVar 0\n        x1 = ofVar $ IVar 1\n        y  = ofVar $ PVar 0\n\n-- | CPM operator of computational basis measurement\nmeasure :: (Eq g, Abelian g) => Pathsum g\nmeasure = unChoi measureChoi\n\n{----------------------------\n Bind, unbind, and subst\n ----------------------------}\n\n-- | Bind some collection of free variables in a path sum\nbind :: (Foldable f, Eq g, Abelian g) => f String -> Pathsum g -> Pathsum g\nbind = flip (foldr go)\n  where go x sop =\n          let v = IVar $ inDeg sop in\n            sop { inDeg = (inDeg sop) + 1,\n                  phasePoly = subst (FVar x) (ofVar v) (phasePoly sop),\n                  outVals = map (subst (FVar x) (ofVar v)) (outVals sop) }\n\n-- | Close a path sum by binding all free variables\nclose :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\nclose sop = bind (freeVars sop) sop\n\n-- | Unbind (instantiate) some collection of inputs\nunbind :: (Foldable f, Eq g, Abelian g) => f Int -> Pathsum g -> Pathsum g\nunbind xs (Pathsum a b c d e f) = Pathsum a (b - length xs) c d e' f' where\n  e'  = substMany sub e\n  f'  = map (substMany sub) f\n  sub = \\v -> Map.findWithDefault (ofVar v) v tmp\n  tmp = snd $ foldr buildMap (0, Map.empty) [0..b-1]\n  buildMap i (j, acc) = case i `elem` xs of\n    True  -> (j, Map.insert (IVar i) (ofVar . FVar $ \"#\" ++ show (IVar i)) acc)\n    False -> (j+1, Map.insert (IVar i) (ofVar . IVar $ j) acc)\n\n-- | Open a path sum by instantiating all inputs\nopen :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\nopen sop = unbind [0..(inDeg sop) - 1] sop\n\n-- | Substitute a monomial with a symbolic Boolean expression throughout\n--\n--   This is generally not a very safe thing to do. Convenience for certain\n--   local transformations\nsubstitute :: (Eq g, Abelian g) => [Var] -> SBool Var -> Pathsum g -> Pathsum g\nsubstitute xs p (Pathsum a b c d e f) = Pathsum a b c d e' f' where\n  e' = substMonomial xs p e\n  f' = map (substMonomial xs p) f\n\n{----------------------------\n Operators\n ----------------------------}\n\n-- | Return the dual of a path sum\ndualize :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\ndualize sop@(Pathsum a b c d e f) = inSOP .> midSOP .> outSOP\n  where inSOP  = tensor (identity c) (etaN b)\n        midSOP = tensor (tensor (identity c) sop) (identity b)\n        outSOP = tensor (epsilonN c) (identity b)\n\n-- | Return the (column) vectorized path sum. By convention we place the inputs\n--   first (i.e. f : A -> B becomes vectorize f : A* \\otimes B)\nvectorize :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\nvectorize sop@(Pathsum a b c d e f) = etaN b .> tensor (identity b) sop\n\n-- | Return the (row) vectorized path sum. By convention we place the outputs\n--   first (i.e. f : A -> B becomes vectorize f : A* \\otimes B)\ncovectorize :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\ncovectorize sop@(Pathsum a b c d e f) = tensor (identity c) sop .> epsilonN c\n\n-- | Take the dagger of a path sum\ndagger :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\ndagger (Pathsum a b c d e f) = dualize $ Pathsum a b c d (-e) f\n\n-- | Take the conjugate (c.f., lower star) of a path sum\nconjugate :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\nconjugate (Pathsum a b c d e f) = Pathsum a b c d (-e) f\n\n-- | Trace a square morphism. Throws an error if the input and outputs are not\n--   the same size\ntrace :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\ntrace sop@(Pathsum a b c d e f)\n  | b /= c = error \"Can't trace a non-square operator\"\n  | otherwise = etaN b .> tensor (identity b) sop .> epsilonN b\n\n-- | Trace out the first qubit. Throws an error if the input is a vector\nptrace :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\nptrace sop@(Pathsum a b c d e f)\n  | b < 1 || c < 1 = error \"Can't partial trace a vector\"\n  | otherwise = tensor eta (identity $ b-1) .>\n                tensor (identity 1) sop .>\n                tensor epsilon (identity $ c-1)\n\n-- | Turn a pure state into a density matrix. Throws an error if the input is not\n--   a column vector\ndensify :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\ndensify sop@(Pathsum a b c d e f)\n  | b /= 0 = error \"Can't densify an operator \"\n  | otherwise = dagger sop .> sop\n\n-- | Turn a (single-qubit) Choi matrix into a CPM-style linear operator\nunChoi :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\nunChoi sop@(Pathsum a b c d e f)\n  | b /= 2 || c /= 2 = error \"Only single-qubit channels currently supported\"\n  | otherwise        = tensor eta swapgate .>\n                       tensor (identity 1) (tensor sop $ identity 1) .>\n                       tensor swapgate epsilon\n\n-- | Turn a unitary operator into a channel. That is, f becomes f_* \\otimes f\nchannelize :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\nchannelize sop = tensor (conjugate sop) sop\n\n-- | Construct a controlled path sum\ncontrolled :: (Eq g, Abelian g) => Pathsum g -> Pathsum g\ncontrolled sop@(Pathsum a b c d e f) = Pathsum a (b+1) (c+1) d e' f' where\n  shift   = shiftI 1\n  x       = ofVar $ IVar 0\n  e'      = (lift x)*(renameMonotonic shift e)\n  f'      = [lift x] ++ (map g . zip [1..] . map (renameMonotonic shift) $ f)\n  g (i,y) = (ofVar $ IVar i) + x*((ofVar $ IVar i) + y)\n\n-- | Attempt to add two path sums. Only succeeds if the resulting sum is balanced\n--   and the dimensions match.\nplusMaybe :: (Eq g, Abelian g) => Pathsum g -> Pathsum g -> Maybe (Pathsum g)\nplusMaybe sop sop'\n  | inDeg sop  /= inDeg sop'                                       = Nothing\n  | outDeg sop /= outDeg sop'                                      = Nothing\n  | (sde sop) + 2*(pathVars sop') /= (sde sop') + 2*(pathVars sop) = Nothing\n  | otherwise = Just $ Pathsum sde' inDeg' outDeg' pathVars' phasePoly' outVals'\n  where sde'       = (sde sop) + 2*(pathVars sop')\n        inDeg'     = inDeg sop\n        outDeg'    = outDeg sop\n        pathVars'  = (pathVars sop) + (pathVars sop') + 1\n        y          = ofVar $ PVar (pathVars' - 1)\n        phasePoly' = (lift y)*(phasePoly sop) +\n                     (lift (1+y))*(renameMonotonic shift $ phasePoly sop')\n        outVals'   = map (\\(a,b) -> b + y*(a + b)) $\n                       zip (outVals sop) (map (renameMonotonic shift) $ outVals sop')\n        shift x    = case x of\n          PVar i -> PVar $ i + (pathVars sop)\n          _      -> x\n\n-- | Construct the sum of two path sums. Raises an error if the sums are incompatible\nplus :: (Eq g, Abelian g) => Pathsum g -> Pathsum g -> Pathsum g\nplus sop sop' = case plusMaybe sop sop' of\n  Nothing    -> error \"Incompatible path sums\"\n  Just sop'' -> sop''\n\n-- | Compose two path sums in parallel\ntensor :: (Eq g, Num g) => Pathsum g -> Pathsum g -> Pathsum g\ntensor sop sop' = Pathsum sde' inDeg' outDeg' pathVars' phasePoly' outVals'\n  where sde'       = (sde sop) + (sde sop')\n        inDeg'     = (inDeg sop) + (inDeg sop')\n        outDeg'    = (outDeg sop) + (outDeg sop')\n        pathVars'  = (pathVars sop) + (pathVars sop')\n        phasePoly' = (phasePoly sop) + (renameMonotonic shift $ phasePoly sop')\n        outVals'   = (outVals sop) ++ (map (renameMonotonic shift) $ outVals sop')\n        shift x    = case x of\n          IVar i -> IVar $ i + (inDeg sop)\n          PVar i -> PVar $ i + (pathVars sop)\n          _      -> x\n\n-- | Attempt to compose two path sums in sequence. Only succeeds if the dimensions\n--   are compatible (i.e. if the out degree of the former is the in degree of the\n--   latter)\ntimesMaybe :: (Eq g, Abelian g) => Pathsum g -> Pathsum g -> Maybe (Pathsum g)\ntimesMaybe sop sop'\n  | outDeg sop /= inDeg sop' = Nothing\n  | otherwise = Just $ Pathsum sde' inDeg' outDeg' pathVars' phasePoly' outVals'\n  where sde'       = (sde sop) + (sde sop')\n        inDeg'     = inDeg sop\n        outDeg'    = outDeg sop'\n        pathVars'  = (pathVars sop) + (pathVars sop')\n        phasePoly' = (phasePoly sop) +\n                     (substMany sub . renameMonotonic shift $ phasePoly sop')\n        outVals'   = (map (substMany sub . renameMonotonic shift) $ outVals sop')\n        shift x    = case x of\n          PVar i -> PVar $ i + (pathVars sop)\n          _      -> x\n        sub x      = case x of\n          IVar i -> (outVals sop)!!i\n          _      -> ofVar x\n\n-- | Compose two path sums in sequence. Throws an error if the dimensions are\n--   not compatible\ntimes :: (Eq g, Abelian g) => Pathsum g -> Pathsum g -> Pathsum g\ntimes sop sop' = case timesMaybe sop sop' of\n  Nothing    -> error \"Incompatible path sum dimensions\"\n  Just sop'' -> sop''\n\n-- | Left-to-right composition\n(.>) :: (Eq g, Abelian g) => Pathsum g -> Pathsum g -> Pathsum g\n(.>) = times\n\ninfixr 5 .>\n\n-- | Scale the normalization factor\nrenormalize :: Int -> Pathsum g -> Pathsum g\nrenormalize k (Pathsum a b c d e f) = Pathsum (a + k) b c d e f\n\n-- | Embed a path sum into a larger space with a specified input and\n--   output embedding.\nembed :: (Eq g, Abelian g) => Pathsum g -> Int -> (Int -> Int) -> (Int -> Int) -> Pathsum g\nembed sop n embedIn embedOut\n  | n < 0     = error \"Can't embed in smaller space\"\n  | otherwise = inPerm .> tensor (identity n) sop .> outPerm where\n      mIn = inDeg sop\n      ins = map embedIn [0..mIn-1]\n      inPerm  = permutation $ ([0..mIn+n-1] \\\\ ins) ++ ins\n      mOut = outDeg sop\n      outs = map embedOut [0..mOut-1]\n      outPerm = unpermutation $ ([0..mOut+n-1] \\\\ outs) ++ outs\n\n-- | Drop a qubit\ndiscard :: Eq g => Int -> Pathsum g -> Pathsum g\ndiscard i sop@(Pathsum a b c d e f) = Pathsum a b' c' d e f' where\n  b' = if i < b then b-1 else b\n  c' = if i < c then c-1 else c\n  f' = snd . unzip . filter (\\(j,_) -> i /= j) $ zip [0..] f\n\n{--------------------------\n Type class instances\n --------------------------}\n  \ninstance (Eq g, Num g) => Semigroup (Pathsum g) where\n  (<>) = tensor\n\ninstance (Eq g, Num g) => Monoid (Pathsum g) where\n  mempty  = Pathsum 0 0 0 0 0 []\n  mappend = tensor\n\ninstance (Eq g, Abelian g) => Num (Pathsum g) where\n  (+)                          = plus\n  (*)                          = (flip times)\n  negate (Pathsum a b c d e f) = Pathsum a b c d (lift 1 + e) f\n  abs (Pathsum a b c d e f)    = Pathsum a b c d (dropConstant e) f\n  signum sop                   = sop\n  fromInteger                  = identity . fromInteger\n\ninstance Functor Pathsum where\n  fmap g (Pathsum a b c d e f) = Pathsum a b c d (cast g e) f\n\n{--------------------------\n Reduction rules\n --------------------------}\n\n{-\nclass RewriteRule rule g where\n  matchAll :: Pathsum g -> [rule]\n  matchOne :: Pathsum g -> rule\n  apply :: rule -> Pathsum g -> Pathsum g\n\ndata E = E !Var {-# UNBOX #-}\n\ninstance (Eq g, Periodic g) => RewriteRule E g where\n  match = matchElim\n  apply = applyElim\n-}\n\n-- | Maps the order 1 and order 2 elements of a group to FF2\ninjectFF2 :: Periodic g => g -> Maybe FF2\ninjectFF2 a = case order a of\n  1 -> Just 0\n  2 -> Just 1\n  _ -> Nothing\n\n-- | Gives a Boolean polynomial equivalent to the current polynomial, if possible\ntoBooleanPoly :: (Eq g, Periodic g) => PseudoBoolean v g -> Maybe (SBool v)\ntoBooleanPoly = castMaybe injectFF2\n\n-- | Elim rule. \\(\\dots(\\sum_y)\\dots = \\dots 2 \\dots\\)\nmatchElim :: (Eq g, Periodic g) => Pathsum g -> [Var]\nmatchElim sop = msum . (map go) $ internalPaths sop\n  where go v = if Set.member v (vars $ phasePoly sop) then [] else [v]\n\n-- | Generic HH rule. \\(\\dots(\\sum_y (-1)^{y\\cdot f})\\dots = \\dots|_{f = 0}\\)\nmatchHH :: (Eq g, Periodic g) => Pathsum g -> [(Var, SBool Var)]\nmatchHH sop = msum . (map (maybeToList . go)) $ internalPaths sop\n  where go v = toBooleanPoly (quotVar v $ phasePoly sop) >>= \\p -> return (v, p)\n\n-- | Solvable instances of the HH rule.\n--   \\(\\dots(\\sum_y (-1)^{y(z \\oplus f)})\\dots = \\dots[z \\gets f]\\)\nmatchHHSolve :: (Eq g, Periodic g) => Pathsum g -> [(Var, Var, SBool Var)]\nmatchHHSolve sop = do\n  (v, p)   <- matchHH sop\n  (v', p') <- solveForX p\n  case v' of\n    PVar _ -> return (v, v', p')\n    _      -> mzero\n\n-- | Instances of the HH rule with a linear substitution\nmatchHHLinear :: (Eq g, Periodic g) => Pathsum g -> [(Var, Var, SBool Var)]\nmatchHHLinear sop = do\n  (v, p)   <- filter (\\(_, p) -> degree p <= 1) $ matchHH sop\n  (v', p') <- solveForX p\n  return (v, v', p')\n\n-- | Instances of the (\\omega\\) rule\nmatchOmega :: (Eq g, Periodic g, Dyadic g) => Pathsum g -> [(Var, SBool Var)]\nmatchOmega sop = do\n  v <- internalPaths sop\n  p <- maybeToList . toBooleanPoly . addFactor v $ phasePoly sop\n  return (v, p)\n  where addFactor v p = constant (fromDyadic $ dyadic 3 1) + quotVar v p\n\n{--------------------------\n Pattern synonyms\n --------------------------}\n\n-- | Pattern synonym for Elim\npattern Triv :: (Eq g, Num g) => Pathsum g\npattern Triv <- (isTrivial -> True)\n\n-- | Pattern synonym for Elim\npattern Elim :: (Eq g, Periodic g) => Var -> Pathsum g\npattern Elim v <- (matchElim -> (v:_))\n\n-- | Pattern synonym for HH\npattern HH :: (Eq g, Periodic g) => Var -> SBool Var -> Pathsum g\npattern HH v p <- (matchHH -> (v, p):_)\n\n-- | Pattern synonym for solvable HH instances\npattern HHSolved :: (Eq g, Periodic g) => Var -> Var -> SBool Var -> Pathsum g\npattern HHSolved v v' p <- (matchHHSolve -> (v, v', p):_)\n\n-- | Pattern synonym for linear HH instances\npattern HHLinear :: (Eq g, Periodic g) => Var -> Var -> SBool Var -> Pathsum g\npattern HHLinear v v' p <- (matchHHLinear -> (v, v', p):_)\n\n-- | Pattern synonym for HH instances where the polynomial is strictly a\n--   function of input variables\npattern HHKill :: (Eq g, Periodic g) => Var -> SBool Var -> Pathsum g\npattern HHKill v p <- (filter (all (not . isP) . vars . snd) . matchHH -> (v, p):_)\n\n-- | Pattern synonym for Omega instances\npattern Omega :: (Eq g, Periodic g, Dyadic g) => Var -> SBool Var -> Pathsum g\npattern Omega v p <- (matchOmega -> (v, p):_)\n\n{--------------------------\n Applying reductions\n --------------------------}\n\n-- | Apply an elim rule. Does not check if the instance is valid\napplyElim :: Var -> Pathsum g -> Pathsum g\napplyElim (PVar i) (Pathsum a b c d e f) = Pathsum (a-2) b c (d-1) e' f'\n  where e' = renameMonotonic varShift e\n        f' = map (renameMonotonic varShift) f\n        varShift (PVar j)\n          | j > i     = PVar $ j - 1\n          | otherwise = PVar $ j\n        varShift v = v\n\n-- | Apply a (solvable) HH rule. Does not check if the instance is valid\napplyHHSolved :: (Eq g, Abelian g) => Var -> Var -> SBool Var -> Pathsum g -> Pathsum g\napplyHHSolved (PVar i) v p (Pathsum a b c d e f) = Pathsum a b c (d-1) e' f'\n  where e' = renameMonotonic varShift . subst v p . remVar (PVar i) $ e\n        f' = map (renameMonotonic varShift . subst v p) f\n        varShift (PVar j)\n          | j > i     = PVar $ j - 1\n          | otherwise = PVar $ j\n        varShift v = v\n\n-- | Apply an (\\omega\\) rule. Does not check if the instance is valid\napplyOmega :: (Eq g, Abelian g, Dyadic g) => Var -> SBool Var -> Pathsum g -> Pathsum g\napplyOmega (PVar i) p (Pathsum a b c d e f) = Pathsum (a-1) b c (d-1) e' f'\n  where e' = renameMonotonic varShift $ p' + remVar (PVar i) e\n        f' = map (renameMonotonic varShift) f\n        p' = constant (fromDyadic $ dyadic 1 2) + distribute (fromDyadic $ dyadic 3 1) (lift p)\n        varShift (PVar j)\n          | j > i     = PVar $ j - 1\n          | otherwise = PVar $ j\n        varShift v = v\n\n-- | Finds and applies the first elimination instance\nrewriteElim :: (Eq g, Periodic g) => Pathsum g -> Pathsum g\nrewriteElim sop = case sop of\n  Elim v -> applyElim v sop\n  _      -> sop\n\n-- | Finds and applies the first hh instance\nrewriteHH :: (Eq g, Periodic g) => Pathsum g -> Pathsum g\nrewriteHH sop = case sop of\n  HHSolved v v' p -> applyHHSolved v v' p sop\n  _               -> sop\n\n-- | Finds and applies the first omega instance\nrewriteOmega :: (Eq g, Periodic g, Dyadic g) => Pathsum g -> Pathsum g\nrewriteOmega sop = case sop of\n  Omega v p -> applyOmega v p sop\n  _         -> sop\n\n{--------------------------\n Reduction procedures\n --------------------------}\n\n-- | Performs basic simplifications\nsimplify :: (Eq g, Periodic g, Dyadic g) => Pathsum g -> Pathsum g\nsimplify sop = case sop of\n  Elim y         -> grind $ applyElim y sop\n  HHLinear y z p -> grind $ applyHHSolved y z p sop\n  Omega y p      -> grind $ applyOmega y p sop\n  _              -> sop\n\n-- | A complete normalization procedure for Clifford circuits. Originally described in\n--   the paper M. Amy,\n--   / Towards Large-Scaled Functional Verification of Universal Quantum Circuits /, QPL 2018.\ngrind :: (Eq g, Periodic g, Dyadic g) => Pathsum g -> Pathsum g\ngrind sop = case sop of\n  Elim y         -> grind $ applyElim y sop\n  HHSolved y z p -> grind $ applyHHSolved y z p sop\n  Omega y p      -> grind $ applyOmega y p sop\n  _              -> sop\n\n-- | A single step of 'grind'\ngrindStep :: (Eq g, Periodic g, Dyadic g) => Pathsum g -> Pathsum g\ngrindStep sop = case sop of\n  Elim y         -> applyElim y sop\n  HHSolved y z p -> applyHHSolved y z p sop\n  Omega y p      -> applyOmega y p sop\n  _              -> sop\n\n{--------------------------\n Simulation\n --------------------------}\n\n-- | Gets the cofactors of some path variable\nexpand :: (Eq g, Abelian g) => Pathsum g -> Var -> (Pathsum g, Pathsum g)\nexpand (Pathsum a b c d e f) v = (p0, p1) where\n  p0  = Pathsum a b c (d-1) (subst v 0 e) (map (subst v 0) f)\n  p1  = Pathsum a b c (d-1) (subst v 1 e) (map (subst v 1) f)\n\n-- | Simulates a pathsum on a given input\nsimulate :: (Eq g, Periodic g, Dyadic g, Real g, RealFloat f) => Pathsum g -> [FF2] -> Map [FF2] (Complex f)\nsimulate sop xs = go $ sop * ket (map constant xs)\n  where go      = go' . grind\n        go' ps  = case ps of\n          (Pathsum k 0 _ 0 p xs) ->\n            let phase     = fromRational . toRational $ getConstant p\n                base      = case k `mod` 2 of\n                  0 -> fromInteger $ 1 `shiftL` (abs k)\n                  1 -> sqrt(2.0) * (fromInteger $ 1 `shiftL` (abs (k-1)))\n                magnitude = base**(fromIntegral $ signum k)\n            in\n              Map.singleton (map getConstant xs) (mkPolar magnitude (pi * phase))\n          (Pathsum k 0 n i p xs) ->\n            let v     = PVar $ i-1\n                left  = go (Pathsum k 0 n (i-1) (subst v zero p) (map (subst v zero) xs))\n                right = go (Pathsum k 0 n (i-1) (subst v one p) (map (subst v one) xs))\n            in\n              Map.unionWith (+) left right\n          _                      -> error \"Incompatible dimensions\"\n\n-- | Evaluates a pathsum on a given input and output\namplitude :: (Eq g, Periodic g, Dyadic g, Real g, RealFloat f) => [FF2] -> Pathsum g -> [FF2] -> Complex f\namplitude o sop i = (simulate (bra (map constant o) * sop) i)![]\n\n-- | Checks identity by checking inputs iteratively\nisIdentity :: (Eq g, Periodic g, Dyadic g) => Pathsum g -> Bool\nisIdentity sop\n  | isTrivial sop = True\n  | otherwise     = case inDeg sop of\n      0 -> False\n      i -> let p0 = (grind $ identity (i-1) <> ket [0] .> sop .> identity (i-1) <> bra [0])\n               p1 = (grind $ identity (i-1) <> ket [1] .> sop .> identity (i-1) <> bra [1])\n           in\n             isIdentity p0 && isIdentity p1\n\n{--------------------------\n Examples\n --------------------------}\n\n-- | A symbolic state |x>\nsstate :: Pathsum DMod2\nsstate = open $ identity 1\n\n-- | A bell state\nbellstate :: Pathsum DMod2\nbellstate = fresh <> fresh .> hgate <> (identity 1) .> cxgate\n\n-- | Teleportation circuit\nteleport :: Pathsum DMod2\nteleport = (identity 1) <> bellstate .>\n           cxgate <> (identity 1) .>\n           hgate <> cxgate .>\n           swapgate <> hgate .>\n           (identity 1) <> cxgate .>\n           swapgate <> hgate\n\n-- | Teleportation channel\nteleportChannel :: Pathsum DMod2\nteleportChannel = channelize ((identity 1) <> bellstate) .>\n                  channelize (cxgate <> (identity 1)) .>\n                  channelize (hgate <> cxgate) .>\n                  embed measure 4 (* 3) (* 3) .>\n                  embed measure 4 (\\i -> i*3 + 1) (\\j -> j*3 + 1) .>\n                  channelize (swapgate <> hgate) .>\n                  channelize ((identity 1) <> cxgate) .>\n                  channelize (swapgate <> hgate) .>\n                  embed epsilon 4 (* 3) (* 3) .> -- trace out first qubit\n                  embed epsilon 2 (* 2) (* 2)    -- trace out second\n           \n-- | Verify teleportation\nverifyTele :: () -> IO ()\nverifyTele _ = case (densify sstate == grind (ptrace . ptrace . densify $ sstate .> teleport)) of\n  True -> putStrLn \"Identity\"\n  False -> putStrLn \"Not identity\"\n  \n-- | Verify teleportation channel\nverifyTeleC :: () -> IO ()\nverifyTeleC _ = case (rho == grind (rho .> teleportChannel)) of\n  True -> putStrLn \"Identity\"\n  False -> putStrLn \"Not identity\"\n  where rho = grind $ vectorize $ densify sstate\n\n-- | The |A> = T|+> state\naState :: Pathsum DMod2\naState = fresh .> hgate .> tgate\n\n-- | T gate teleportation channel\nteleportTChannel :: Pathsum DMod2\nteleportTChannel = channelize ((identity 1) <> aState) .>\n                   channelize (cxgate) .>\n                   embed measure 2 (\\i -> i*2 + 1) (\\j -> j*2 + 1) .>\n                   channelize (controlled sgate) .>\n                   embed epsilon 2 (\\i -> i*2 + 1) (\\j -> j*2 + 1) -- trace out the resource state\n\n-- | Verify teleportation channel\nverifyTeleT :: () -> IO ()\nverifyTeleT _ = case (channelize tgate == grind (teleportTChannel)) of\n  True -> putStrLn \"Identity\"\n  False -> putStrLn \"No identity\"\n", "meta": {"hexsha": "9a2da938aa3d8adfca2693bc727eb6f2b1d959f7", "size": 35038, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Feynman/Algebra/Pathsum/Balanced.hs", "max_stars_repo_name": "PariaNaghavi/feynman", "max_stars_repo_head_hexsha": "74f3b7694b8883315bf30a6a28b6b70c505f5fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2018-03-09T20:12:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T11:55:36.000Z", "max_issues_repo_path": "src/Feynman/Algebra/Pathsum/Balanced.hs", "max_issues_repo_name": "PariaNaghavi/feynman", "max_issues_repo_head_hexsha": "74f3b7694b8883315bf30a6a28b6b70c505f5fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-16T11:31:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T18:49:56.000Z", "max_forks_repo_path": "src/Feynman/Algebra/Pathsum/Balanced.hs", "max_forks_repo_name": "PariaNaghavi/feynman", "max_forks_repo_head_hexsha": "74f3b7694b8883315bf30a6a28b6b70c505f5fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-08-23T16:58:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T14:08:55.000Z", "avg_line_length": 37.8789189189, "max_line_length": 108, "alphanum_fraction": 0.5780010275, "num_tokens": 11299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.46128941554840447}}
{"text": "{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\nimport Criterion.Main\n\nimport           Grenade\n\nimport           Grenade.Layers.Internal.Convolution\nimport           Grenade.Layers.Internal.Pooling\n\nimport           Numeric.LinearAlgebra\n\nmain :: IO ()\nmain = do\n  x    :: S ('D2 60 60  )  <- randomOfShape\n  y    :: S ('D3 60 60 1)  <- randomOfShape\n\n  defaultMain [\n      bgroup \"im2col\" [ bench \"im2col 3x4\"     $ whnf (im2col 2 2 1 1)   ((3><4) [1..])\n                      , bench \"im2col 28x28\"   $ whnf (im2col 5 5 1 1)   ((28><28) [1..])\n                      , bench \"im2col 100x100\" $ whnf (im2col 10 10 1 1) ((100><100) [1..])\n                      ]\n    , bgroup \"col2im\" [ bench \"col2im 3x4\"      $ whnf (col2im 2 2 1 1 3 4)       ((6><4) [1..])\n                      , bench \"col2im 28x28\"    $ whnf (col2im 5 5 1 1 28 28)     ((576><25) [1..])\n                      , bench \"col2im 100x100\"  $ whnf (col2im 10 10 1 1 100 100) ((8281><100) [1..])\n                      ]\n    , bgroup \"poolfw\" [ bench \"poolforwards 3x4\"      $ whnf (poolForward 1 3 4 2 2 1 1)     ((3><4) [1..])\n                      , bench \"poolforwards 28x28\"    $ whnf (poolForward 1 28 28 5 5 1 1)    ((28><28) [1..])\n                      , bench \"poolforwards 100x100\"  $ whnf (poolForward 1 100 100 10 10 1 1) ((100><100) [1..])\n                      ]\n    , bgroup \"poolbw\" [ bench \"poolbackwards 3x4\"      $ whnf (poolBackward 1 3 4 2 2 1 1   ((3><4) [1..]))     ((2><3) [1..])\n                      , bench \"poolbackwards 28x28\"    $ whnf (poolBackward 1 28 28 5 5 1 1   ((28><28) [1..]))   ((24><24) [1..])\n                      , bench \"poolbackwards 100x100\"  $ whnf (poolBackward 1 100 100 10 10 1 1 ((100><100) [1..])) ((91><91) [1..])\n                      ]\n    , bgroup \"padcrop\" [ bench \"pad 2D 60x60\"    $ whnf (testRun2D Pad) x\n                       , bench \"pad 3D 60x60\"    $ whnf (testRun3D Pad) y\n                       , bench \"crop 2D 60x60\"   $ whnf (testRun2D' Crop) x\n                       , bench \"crop 3D 60x60\"   $ whnf (testRun3D' Crop) y\n                       ]\n    ]\n\n\ntestRun2D :: Pad 1 1 1 1 -> S ('D2 60 60) -> S ('D2 62 62)\ntestRun2D = snd ... runForwards\n\ntestRun3D :: Pad 1 1 1 1 -> S ('D3 60 60 1) -> S ('D3 62 62 1)\ntestRun3D = snd ... runForwards\n\ntestRun2D' :: Crop 1 1 1 1 -> S ('D2 60 60) -> S ('D2 58 58)\ntestRun2D' = snd ... runForwards\n\ntestRun3D' :: Crop 1 1 1 1 -> S ('D3 60 60 1) -> S ('D3 58 58 1)\ntestRun3D' = snd ... runForwards\n\n(...) :: (a -> b) -> (c -> d -> a) -> c -> d -> b\n(...) = (.) . (.)\n", "meta": {"hexsha": "6d1a5e1a98b727d99116cf5a3b79b8c5b96778e9", "size": 2571, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/bench.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1527, "max_stars_repo_stars_event_min_datetime": "2016-06-23T13:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T05:22:00.000Z", "max_issues_repo_path": "bench/bench.hs", "max_issues_repo_name": "Alien-Inc/grenade", "max_issues_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 69, "max_issues_repo_issues_event_min_datetime": "2016-06-27T22:16:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-20T17:50:09.000Z", "max_forks_repo_path": "bench/bench.hs", "max_forks_repo_name": "Alien-Inc/grenade", "max_forks_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2016-06-28T02:24:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:17:29.000Z", "avg_line_length": 45.9107142857, "max_line_length": 132, "alphanum_fraction": 0.4729677168, "num_tokens": 1013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46103494631713404}}
{"text": "{-# LANGUAGE UndecidableInstances,\n             FlexibleInstances,\n             FlexibleContexts,\n             TypeFamilies,\n             ScopedTypeVariables #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Numeric.Signal.Multichannel\n-- Copyright   :  (c) Alexander Vivian Hugh McPhail 2010, 2014, 2015, 2016\n-- License     :  BSD3\n--\n-- Maintainer  :  haskell.vivian.mcphail <at> gmail <dot> com\n-- Stability   :  provisional\n-- Portability :  uses Concurrency\n--\n-- Signal processing functions, multichannel datatype\n--\n-- link with '-threaded' and run with +RTS -Nn, where n is the number of CPUs\n--\n-----------------------------------------------------------------------------\n\n--             IncoherentInstances,\n\n\nmodule Numeric.Signal.Multichannel (\n                       Multichannel,readMultichannel,writeMultichannel,\n                       createMultichannel,\n                       sampling_rate,precision,channels,samples,\n                       detrended,filtered,\n                       getChannel,getChannels,\n                       toMatrix,\n                       mapConcurrently,\n                       detrend,filter,\n                       slice,\n                       histograms,\n                       entropy_delta_phase,mi_phase\n                ) where\n\n-----------------------------------------------------------------------------\n\nimport qualified Numeric.Signal as S\n\n--import Complex\n\nimport qualified Data.Array.IArray as I\nimport Data.Ix\n\n--import Data.Word\n\nimport Control.Concurrent\n--import Control.Concurrent.MVar\n\nimport System.IO.Unsafe(unsafePerformIO)\n\n--import qualified Data.List as L\n\nimport Data.Binary\nimport Data.Maybe\n\nimport Foreign.Storable\n\nimport Numeric.LinearAlgebra hiding(range)\n\nimport qualified Data.Vector.Generic as GV\n\n--import qualified Numeric.GSL.Fourier as F\n\nimport qualified Numeric.GSL.Histogram as H\nimport qualified Numeric.GSL.Histogram2D as H2\n\nimport qualified Numeric.Statistics.Information as SI\n\nimport Prelude hiding(filter)\n\nimport Control.Monad(replicateM)\n\n\n{-\n-------------------------------------------------------------------\n\ninstance (Binary a, Storable a) => Binary (Vector a) where\n    put v = do\n            let d = GV.length v\n            put d\n            mapM_ (\\i -> put $ v @> i) [0..(d-1)]\n    get = do\n          d <- get\n          xs <- replicateM d get\n          return $ fromList xs\n\n-------------------------------------------------------------------\n-}\n\n-----------------------------------------------------------------------------\n\n-- | data type with multiple channels\ndata Multichannel a = MC {\n                          _sampling_rate :: Int             -- ^ sampling rate\n                          , _precision   :: Int             -- ^ bits of precision\n                          , _channels    :: Int             -- ^ number of channels\n                          , _length      :: Int             -- ^ length in samples\n                          , _detrended   :: Bool            -- ^ was the data detrended?\n                          , _filtered    :: Maybe (Int,Int) -- ^ if filtered the passband\n                          , _data        :: I.Array Int (Vector a) -- ^ data\n                         }\n\n-----------------------------------------------------------------------------\n\ninstance Binary (Multichannel Double) where\n    put (MC s p c l de f d) = do\n                              put s\n                              put p\n                              put c\n                              put l\n                              put de\n                              put f\n                              put $! fmap convert d\n        where convert v = let (mi,ma) = (minElement v,maxElement v)\n                              v' = GV.map (\\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word64))) v\n                          in (mi,ma,v' :: Vector Word64) \n\n    get = do\n          s <- get\n          p <- get\n          c <- get\n          l <- get\n          de <- get\n          f <- get\n          (d :: I.Array Int (Double,Double,Vector Word64)) <- get\n          return $! (MC s p c l de f (seq d (fmap convert) d))\n              where convert (mi,ma,v) = GV.map (\\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word64)) * (ma - mi) + mi) v\n\ninstance Binary (Multichannel Float) where\n    put (MC s p c l de f d) = do\n                              put s\n                              put p\n                              put c\n                              put l\n                              put de\n                              put f\n                              put $! fmap convert d\n        where convert v = let (mi,ma) = (minElement v,maxElement v)\n                              v' = GV.map (\\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word64))) v\n                          in (mi,ma,v' :: Vector Word64) \n\n    get = do\n          s <- get\n          p <- get\n          c <- get\n          l <- get\n          de <- get\n          f <- get\n          (d :: I.Array Int (Float,Float,Vector Word32)) <- get\n          return $! (MC s p c l de f (seq d (fmap convert) d))\n              where convert (mi,ma,v) = GV.map (\\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word32)) * (ma - mi) + mi) v\n\ninstance Binary (Multichannel (Complex Double)) where\n    put (MC s p c l de f d) = do\n                              put s\n                              put p\n                              put c\n                              put l\n                              put de\n                              put f\n                              put $! fmap ((\\(r,j) -> (convert r, convert j)) . fromComplex) d\n        where convert v = let (mi,ma) = (minElement v,maxElement v)\n                              v' = GV.map (\\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word64))) v\n                          in (mi,ma,v' :: Vector Word64) \n\n    get = do\n          s <- get\n          p <- get\n          c <- get\n          l <- get\n          de <- get\n          f <- get\n          (d :: I.Array Int ((Double,Double,Vector Word64),(Double,Double,Vector Word64))) <- get\n          return $! (MC s p c l de f (seq d (fmap (\\(r,j) -> toComplex (convert r,convert j)) d)))\n              where convert (mi,ma,v) = GV.map (\\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word64)) * (ma - mi) + mi) v\n\n\n\ninstance Binary (Multichannel (Complex Float)) where\n    put (MC s p c l de f d) = do\n                              put s\n                              put p\n                              put c\n                              put l\n                              put de\n                              put f\n                              put $! fmap ((\\(r,j) -> (convert r, convert j)) . fromComplex) d\n        where convert v = let (mi,ma) = (minElement v,maxElement v)\n                              v' = GV.map (\\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word32))) v\n                          in (mi,ma,v' :: Vector Word32) \n\n    get = do\n          s <- get\n          p <- get\n          c <- get\n          l <- get\n          de <- get\n          f <- get\n          (d :: I.Array Int ((Float,Float,Vector Word32),(Float,Float,Vector Word32))) <- get\n          return $! (MC s p c l de f (seq d (fmap (\\(r,j) -> toComplex (convert r,convert j)) d)))\n              where convert (mi,ma,v) = GV.map (\\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word32)) * (ma - mi) + mi) v\n\n\n\n-----------------------------------------------------------------------------\n\nreadMultichannel :: (Binary (Multichannel a)) => FilePath -> IO (Multichannel a)\nreadMultichannel = decodeFile\n\nwriteMultichannel :: (Binary (Multichannel a)) => FilePath -> Multichannel a -> IO ()\nwriteMultichannel = encodeFile\n\n-----------------------------------------------------------------------------\n\n-- | create a multichannel data type\ncreateMultichannel :: Storable a \n                   => Int               -- ^ sampling rate\n                   -> Int               -- ^ bits of precision\n                   -> [Vector a]        -- ^ data\n                   -> Multichannel a    -- ^ datatype\ncreateMultichannel s p d = let c = length d\n                 in MC s p c (GV.length $ head d) False Nothing (I.listArray (1,c) d)\n\n-- | the sampling rate\nsampling_rate :: Multichannel a -> Int\nsampling_rate = _sampling_rate\n\n-- | the bits of precision\nprecision :: Multichannel a -> Int\nprecision = _precision\n\n-- | the number of channels\nchannels :: Multichannel a -> Int\nchannels = _channels\n\n-- | the length, in samples\nsamples :: Multichannel a -> Int\nsamples = _length\n\n-- | extract one channel\ngetChannel :: Int -> Multichannel a -> Vector a\ngetChannel c d = (_data d) I.! c\n\n-- | extract all channels\ngetChannels :: Multichannel a -> I.Array Int (Vector a)\ngetChannels d = _data d\n\n-- | convert the data to a matrix with channels as rows\ntoMatrix :: Element a => Multichannel a -> Matrix a\ntoMatrix = fromRows . I.elems . _data\n\n-- | was the data detrended?\ndetrended :: Multichannel a -> Bool\ndetrended = _detrended\n\n-- | was the data filtered?\nfiltered :: Multichannel a -> Maybe (Int,Int)\nfiltered = _filtered\n\n-----------------------------------------------------------------------------\n\n-- | map a function executed concurrently\nmapArrayConcurrently :: Ix i => (a -> b)    -- ^ function to map\n                     -> I.Array i a         -- ^ input\n                     -> (I.Array i b)     -- ^ output\nmapArrayConcurrently f d = unsafePerformIO $ do\n  let b = I.bounds d\n  results <- replicateM (rangeSize b) newEmptyMVar\n  mapM_ (forkIO . applyFunction f) $ zip results (I.assocs d)\n  vectors <- mapM takeMVar results\n  return $ I.array b vectors\n    where applyFunction f' (m,(j,e)) = putMVar m (j,f' e)\n\n{-\n-- | map a function executed concurrently\nmapListConcurrently :: (a -> b)             -- ^ function to map\n                    -> [a]                  -- ^ input\n                    -> [b]                  -- ^ output\nmapListConcurrently f d = unsafePerformIO $ do\n                                            results <- replicateM (length d) newEmptyMVar\n                                            mapM_ (forkIO . applyFunction f) zip results d\n                                            mapM takeMVar results\n    where applyFunction f' (m,e) = putMVar m (f' e)\n-}\n\n-- | map a function executed concurrently\nmapConcurrently :: Storable b \n                => (Vector a -> Vector b)      -- ^ the function to be mapped \n                -> Multichannel a              -- ^ input data\n                -> Multichannel b              -- ^ output data\nmapConcurrently f (MC sr p c _ de fi d) = let d' = mapArrayConcurrently f d\n                                          in MC sr p c (GV.length $ d' I.! 1) de fi d'\n\n-- | map a function\nmapMC :: Storable b \n      => (Vector a -> Vector b)                -- ^ the function to be mapped \n      -> Multichannel a                        -- ^ input data\n      -> Multichannel b                        -- ^ output data\nmapMC f (MC sr p c _ de fi d) = let d' = fmap f d\n                                in MC sr p c (GV.length $ d' I.! 1) de fi d'\n                                    \n-----------------------------------------------------------------------------\n\n-- | detrend the data with a specified window size\ndetrend :: Int -> Multichannel Double -> Multichannel Double\ndetrend w m = let m' = mapConcurrently (S.detrend w) m\n              in m' { _detrended = True }\n\n\n-- | filter the data with the given passband\nfilter :: (S.Filterable a, Double ~ DoubleOf a) => \n         (Int,Int) -> Multichannel a -> Multichannel a\nfilter pb m = let m' = mapConcurrently (S.broadband_filter (_sampling_rate m) pb) m\n              in m' { _filtered = Just pb }\n\n-----------------------------------------------------------------------------\n\n-- | extract a slice of the data\nslice :: Storable a \n      => Int                 -- ^ starting sample number\n      -> Int                 -- ^ length\n      -> Multichannel a \n      -> Multichannel a\nslice j w m = let m' = mapConcurrently (subVector j w) m\n              in m' { _length = w }\n\n-----------------------------------------------------------------------------\n\n-- | calculate histograms\nhistograms :: (S.Filterable a, Double ~ DoubleOf a) =>\n            I.Array Int (Vector a)\n          -> Int -> (Double,Double) \n          -> Int -> Int -> (Double,Double) -> (Double,Double) -- ^ bins and ranges\n          -> (I.Array Int H.Histogram,I.Array (Int,Int) H2.Histogram2D)\nhistograms d' b (l,u) bx by (lx,ux) (ly,uy) \n  = let d = fmap double d'\n        (bl,bu) = I.bounds d\n        br = ((bl,bl),(bu,bu))\n        histarray = mapArrayConcurrently (H.fromLimits b (l,u)) d\n        pairs = I.array br $ map (\\(m,n) -> ((m,n),(d I.! m,d I.! n))) (range br)\n        hist2array = mapArrayConcurrently (\\(x,y) -> (H2.addVector (H2.emptyLimits bx by (lx,ux) (ly,uy)) x y)) pairs\n    in (histarray,hist2array)\n\n-----------------------------------------------------------------------------\n\n-- | calculate the entropy of the phase difference between pairs of channels (fills upper half of matrix)\nentropy_delta_phase :: (S.Filterable a, Double ~ DoubleOf a) =>\n                Multichannel a      -- ^ input data\n              -> Matrix Double\nentropy_delta_phase m = let d = _data m\n                            c = _channels m\n                            b = ((1,1),(c,c))\n                            r = I.range b\n                            diff = I.listArray b (map (\\j@(x,y) -> (j,if x <= y then Just (double $ (d I.! y)-(d I.! x)) else Nothing)) r) :: I.Array (Int,Int) ((Int,Int),Maybe (Vector Double))\n                            h = mapArrayConcurrently (maybe Nothing (\\di -> Just $ H.fromLimits 128 ((-2)*pi,2*pi) di)) (fmap snd diff)\n                            ent = mapArrayConcurrently (\\(j,difvec) -> case difvec of \n                                                        Nothing -> 0 :: Double\n                                                        Just da -> SI.entropy (fromJust (h I.! j)) da) diff\n                        in fromArray2D ent\n\n-----------------------------------------------------------------------------\n\n-- | calculate the mutual information of the phase between pairs of channels (fills upper half of matrix)\nmi_phase :: (S.Filterable a, Double ~ DoubleOf a) =>\n           Multichannel a      -- ^ input data\n         -> Matrix Double\nmi_phase m = let d = _data m\n                 (histarray,hist2array) = histograms d 128 (-pi,pi) 128 128 (-pi,pi) (-pi,pi)\n                 indhist = I.listArray (I.bounds hist2array) (I.assocs hist2array)\n                 mi = mapArrayConcurrently (doMI histarray (fmap double d)) indhist\n             in fromArray2D mi\n    where doMI histarray d ((x,y),h2) \n              | x <= y     = SI.mutual_information h2 (histarray I.! x) (histarray I.! y) (d I.! x,d I.! y)\n              | otherwise = 0\n\n-----------------------------------------------------------------------------\n", "meta": {"hexsha": "b4a029baada8eec302d171ca1b323df035038211", "size": 15032, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/Signal/Multichannel.hs", "max_stars_repo_name": "amcphail/hsignal", "max_stars_repo_head_hexsha": "94bb05e77053a9284be98c281e0a21544437072b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-05-27T06:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T23:12:53.000Z", "max_issues_repo_path": "lib/Numeric/Signal/Multichannel.hs", "max_issues_repo_name": "amcphail/hsignal", "max_issues_repo_head_hexsha": "94bb05e77053a9284be98c281e0a21544437072b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-10-30T11:41:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-30T23:38:57.000Z", "max_forks_repo_path": "lib/Numeric/Signal/Multichannel.hs", "max_forks_repo_name": "amcphail/hsignal", "max_forks_repo_head_hexsha": "94bb05e77053a9284be98c281e0a21544437072b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4540682415, "max_line_length": 193, "alphanum_fraction": 0.4572245875, "num_tokens": 3474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46103494063172207}}
{"text": "{-# Language BangPatterns #-}\n{-# Language ScopedTypeVariables #-}\n\nmodule Neuralnetwork where\n\nimport           Data.Bifunctor                 ( bimap )\nimport           Data.Functor.Identity\nimport           Data.IDX\nimport           Data.Maybe                     ( fromMaybe )\n-- import           Debug.Trace\nimport           Control.Monad.Random\nimport qualified Data.Vector.Unboxed           as V\nimport           Numeric.LinearAlgebra          ( Matrix\n                                                , Vector\n                                                , (<>)\n                                                , (#>)\n                                                , (><)\n                                                , (|>)\n                                                )\nimport qualified Numeric.LinearAlgebra         as LA\n\n-- The main crux of my flaw seems to be that my weights increase without bound.\n--\n-- I've run into this issue _every_ single time I have written up this neural\n-- network.  I've rewritten the weight updates countless times now and it's\n-- starting to get to the point where my being past the deadline is a bit\n-- ridiculous and if I keep it up I won't even get to the second programming\n-- assignment at all.\n--\n-- See the delta functions and the weight update function for the most likely\n-- causes of me screwing up.\n\n-- Weights :\n--   - biases = n vector of length = num of inputs to that layer\n--   - nodes  = n x m where m = num of outputs to that layer\n--   => m -> n layer\ndata Weights = W\n  { wBiases :: !(Vector Double) -- length = num of inputs\n  , wNodes  :: !(Matrix Double)\n  } deriving Show\n\n-- Type aliases offer no type safety but help make type signatures more\n-- readable.\ntype Network    = [Weights]\ntype Input      = Vector Double\ntype Target     = Vector Double\ntype Output     = Vector Double\ntype Activation = Vector Double\ntype Prev a     = a -- Cute trick to help make type signatures more readable\ntype Diff a     = a\n\n-- Here we see that we have, behold, dreaded globals.\n-- However, this is fine because\n--  a) I don't care\n--  b) The reader pattern is overly complicated for this particular usecase\n\u03b7 :: Double -- Learning Rate\n\u03b7 = 0.1\n\n\u03b1 :: Double -- Momentum Rate\n\u03b1 = 0.9\n\n-- Layer + Network generation\n-- Generates a layer of random numbers between -0.05 and 0.05\nrandLayer :: MonadRandom m => Int -> Int -> m Weights\nrandLayer i o = do\n  r1 :: Int <- getRandom\n  r2 :: Int <- getRandom\n  let bias    = (LA.randomVector r1 LA.Uniform o - 0.5) / 10\n      weights = LA.uniformSample r2 o (replicate i (-0.05, 0.05))\n  pure $ W bias weights\n\n-- Generates a layer consisting of all zeroed weights\nzeroLayer :: Int -> Int -> Identity Weights\nzeroLayer i o = pure $ W (o |> repeat 0) (o >< i $ repeat 0)\n\n-- A network is a list of layers; this simply steps through the list\nrandNet :: MonadRandom m => Int -> [Int] -> Int -> m Network\nrandNet i []       o = (:) <$> randLayer i o <*> pure []\nrandNet i (h : hs) o = (:) <$> randLayer i h <*> randNet h hs o\n\nzeroNet :: Int -> [Int] -> Int -> Identity Network\nzeroNet i []       o = (:) <$> zeroLayer i o <*> pure []\nzeroNet i (h : hs) o = (:) <$> zeroLayer i h <*> zeroNet h hs o\n\n-- Forward propagate a neural network\n-- a #> b is matrix vector product where vector b is Nx1 dimensional\n-- i : a 784 length vector\n-- wN : (20,784) shaped matrix\nrunLayer :: Weights -> Input -> Activation\nrunLayer (W !wB !wN) !i = (wN #> i) + wB\n-- runLayer (W !wB !wN) !i = trace \"runLayer\" $ (wN #> i) + wB\n\n-- Gets the answer from a neural network by propagating the input forward\nrunNet :: Network -> Input -> Output\nrunNet !n !i = last $ runNet' n i\n-- runNet !n !i = trace \"runNet\" $ last $ runNet' n i\n\n-- Collects all intermediate activations into a list of activations\nrunNet' :: Network -> Input -> [Activation]\nrunNet' []        !i = [i]\nrunNet' (w : net) !i = i : runNet' net \u03b1 where \u03b1 = activation w i\n-- runNet' (w : net) !i = trace \"runNet'\" $ i : runNet' net \u03b1 where \u03b1 = activation w i\n\n-- Runs the neural network over a list of inputs and collects every \"answer\"\ncollectOutputs :: Network -> [Input] -> [Output]\ncollectOutputs net = fmap (runNet net)\n\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n\nlogistic' :: Floating a => a -> a\nlogistic' x = o * (1 - o) where o = logistic x\n\nactivation :: Weights -> Input -> Activation\nactivation !w !v = logistic $ runLayer w v\n\n-- (Not used when actually running the neural network. The slides didn't\n-- mention using a loss function at all to update the weights...)\n-- Target -> Output -> Error\nloss :: Target -> Output -> Double\nloss = (* 0.5) ... LA.sumElements ... (^ 2) ... (-)\n\n-- Not used anywhere in the codebase\nlossO :: Floating a => a -> a -> a -> a\nlossO t y \u03b1 = logistic' y * (\u03b1 - t)\n\n-- If there's an error in this code, it is likely to be in the delta functions\n-- or the weight updates\n\u03b4o :: Target -> Output -> Vector Double\n\u03b4o !t !\u03b1 = \u03b1 * (1 - \u03b1) * (t - \u03b1)\n-- \u03b4o !t !\u03b1 = trace \"\u03b4o\" $ \u03b1 * (1 - \u03b1) * (t - \u03b1)\n\n\u03b4h :: Weights -> Activation -> Vector Double -> Vector Double\n\u03b4h (W !wB !wN) !h !\u03b4' = h * (1 - h) * (LA.tr' wN #> \u03b4')\n-- \u03b4h (W !wB !wN) !h !\u03b4' = trace \"\u03b4h\" $ h * (1 - h) * (LA.tr' wN #> \u03b4')\n-- Can't be this because it's not an inconsistent matrix error...\n\n-- The error terms; algorithm for this and the deltas given by the slides\nerrors :: Network -> Target -> [Input] -> [Vector Double]\nerrors [!ih, !ho] !t [!\u03b1H, !\u03b1O] = [\u03b4hidden, \u03b4output]\n-- errors [!ih, !ho] !t [!\u03b1H, !\u03b1O] = trace \"errors\" [\u03b4hidden, \u03b4output]\n where\n  \u03b4output = \u03b4o t \u03b1O\n  \u03b4hidden = \u03b4h ho \u03b1H \u03b4output\n\n-- Weight deltas with momentum (only the deltas, not the actual change)\n-- scalar is a function that allows me to multiply a matrix (or vector) by a single number\n-- \u03b4 and i need to be the same size. \u03b4 should be 20\n-- if wN\u0394 is (n,m) size, LA.asRow \u03b4*i needs to be (x,m), LA.asColumn \u03b4*i needs to be (n,x)\nweight\u0394 :: Vector Double -> Input -> Prev (Diff Weights) -> (Weights, Diff Weights)\nweight\u0394 !\u03b4 !i w@(W !wB\u0394 !wN\u0394) = (w, W w\u0394b w\u0394n)\n-- weight\u0394 !\u03b4 !i w@(W !wB\u0394 !wN\u0394) = trace \"weight\u0394\" (w, W w\u0394b w\u0394n)\n where\n  w\u0394b = LA.scalar \u03b7 * \u03b4 + LA.scalar \u03b1 * wB\u0394\n  w\u0394n = LA.asColumn (LA.scalar \u03b7 * \u03b4 * i) + LA.scalar \u03b1 * wN\u0394\n  -- tracePrint = \"\u03b4: \"      ++ show (LA.size \u03b4)\n  --           ++ \" i: \"     ++ show (LA.size i)\n  --           ++ \" wN\u0394: \"   ++ show (LA.size wN\u0394)\n  --           ++ \" wB\u0394: \"   ++ show (LA.size wB\u0394)\n            -- ++ \" asCol: \" ++ show (LA.size $ LA.scalar \u03b7 * \u03b4 * i)\n            -- \u03b4: 20 i: 784 wN\u0394: (20,784) wB\u0394: 20\n            -- passing in wrong \u03b4?\n\nwgtUpd :: Weights -> Diff Weights -> Weights\nwgtUpd (W wB wN) (W wB' wN') = W (wB + wB') (wN + wN')\n-- wgtUpd (W wB wN) (W wB' wN') = trace \"wgtUpd\" $ W (wB + wB') (wN + wN')\n\nbackprop -- Given the list of prev diff weights for every layer as well\n  :: (Prev Network, Network)\n  -> Target\n  -> Input\n  -> [Prev (Diff Weights)]\n  -> ([Diff Weights], Network)\nbackprop (net', net) !target !input w' = (w\u0394s, zipWith wgtUpd net w\u0394s)\n-- backprop (net', net) !target !input w' = trace \"Backprop\" (w\u0394s, zipWith wgtUpd net w\u0394s)\n where\n  \u03b1s  = tail $ runNet' net input -- the activations, excluding the input vector\n  \u03b4s  = errors net target \u03b1s     -- length 2 lst\n  w\u0394s = snd <$> zipWith3 weight\u0394 \u03b4s \u03b1s w'\n\n-- Iterate through a list of inputs (and list of targets) and successively\n-- train on those inputs.\nepoch\n  :: (Prev Network, Network)   -- Old network (zeros in first run), current network\n  -> [Target]                  -- List of input vectors\n  -> [Input]                   -- List of target vectors\n  -> [Diff Weights]\n  -> ([Diff Weights], Network) -- Resulting network\nepoch (_    , net ) []       []       w\u0394s   = (w\u0394s, net)\nepoch (!net', !net) (t : ts) (i : is) !w\u0394s' = epoch (net, next) ts is w\u0394s\n-- epoch (!net', !net) (t : ts) (i : is) !w\u0394s' = trace \"Epoch happening\" $ epoch (net, next) ts is w\u0394s\n  where (w\u0394s, next) = backprop (net', net) t i w\u0394s'\n\ntrain\n  :: Int -- Epochs to train for\n  -> (Prev Network, Network) -- (Rest of params are identical to epoch)\n  -> ([Target], [Target])\n  -> ([Input], [Input])\n  -> [Diff Weights]\n  -> IO ()\ntrain 0 nets (tstT, t) (tstI, i) w\u0394s' = do\n  let final    = snd $ epoch nets t i w\u0394s'\n      outputs  = collectOutputs final i\n      oTest    = collectOutputs final tstI\n      accuracy = totalError (t, outputs)\n      tstAcc   = totalError (tstT, oTest)\n  print $ \"Epoch 50 accuracy: \" ++ show accuracy\n  print $ \"Epoch 50 test accuracy: \" ++ show tstAcc\n  -- print out stuff\ntrain n (net', net) t'@(tstT, t) i'@(tstI, i) w\u0394s' = do\n  let (w\u0394s, next) = epoch (net', net) t i w\u0394s'\n      outputs     = collectOutputs next i\n      oTest       = collectOutputs next tstI\n      accuracy    = totalError (t, outputs)\n      tstAcc      = totalError (tstT, oTest)\n  print $ \"Epoch \" ++ show (50-n) ++ \" accuracy: \"      ++ show accuracy\n  print $ \"Epoch \" ++ show (50-n) ++ \" test accuracy: \" ++ show tstAcc\n  train (n - 1) (net, next) t' i' w\u0394s\n\n-- Simple debugging function that tells me the shape of a particular network.\n-- Useful for ensuring my matrices are the right shape\nsizeOf :: Network -> [(Int, (Int, Int))]\nsizeOf [W hB hN, W oB oN] = [(LA.size hB, LA.size hN), (LA.size oB, LA.size oN)]\n\ntotalError :: ([Target], [Output]) -> Double\ntotalError (!ts, !os) = sum (zipWith loss ts os) / fromIntegral (length ts)\n\nmain :: IO ()\nmain = do\n  -- Yes, this is slightly ugly...\n  !file <- fromMaybe (error \"file decoding failed\")\n    <$> decodeIDXFile \"/home/jaredweakly/Documents/Classes/CS445/train-images-idx3-ubyte\"\n  !labels <- fromMaybe (error \"label decoding failed\") <$> decodeIDXLabelsFile\n    \"/home/jaredweakly/Documents/Classes/CS445/train-labels-idx1-ubyte\"\n  !testFile <- fromMaybe (error \"test file decoding failed\")\n    <$> decodeIDXFile \"/home/jaredweakly/Documents/Classes/CS445/t10k-images-idx3-ubyte\"\n  !testLabels <- fromMaybe (error \"test label decoding failed\") <$> decodeIDXLabelsFile\n    \"/home/jaredweakly/Documents/Classes/CS445/t10k-labels-idx1-ubyte\"\n\n  -- mnist : 60_000 [(target, Vector 784 Double)]\n  let !mnist = fromMaybe (error \"labeling failed\") $ labeledDoubleData labels file\n      !mnist' =\n        fromMaybe (error \"labeling failed\") $ labeledDoubleData testLabels testFile\n      !initN20   = runIdentity $ zeroNet 784 [20] 10\n      !initN50   = runIdentity $ zeroNet 784 [50] 10\n      !initN100  = runIdentity $ zeroNet 784 [100] 10\n      !testset = mnist' ++ mnist\n\n  print \"Loaded up data\"\n  -- inputs : (60000><785) Matrix Double\n  -- targets : Vector 10 Double. 0.1 everywhere but target which is 0.9\n  let mkSparseVectors [] = [] :: [Vector Double]\n      mkSparseVectors (x : xs) =\n        LA.assoc 10 0.1 [(x, 0.9)] : mkSparseVectors xs :: [Vector Double]\n\n      normalize :: V.Vector Double -> Vector Double\n      normalize            = (/ 255) . V.convert\n\n      !(!targets, !inputs) = bimap mkSparseVectors id . unzip $ normalize <$$> mnist\n      !(!tstT   , !tstI  ) = bimap mkSparseVectors id . unzip $ normalize <$$> testset\n\n  !weights20  <- randNet 784 [20] 10\n  !weights50  <- randNet 784 [50] 10\n  !weights100 <- randNet 784 [100] 10\n\n  print \"Beginning training with n=20\"\n  train 50 (initN20, weights20) (tstT, targets) (tstI, inputs) initN20\n\n  print \"Beginning training with n=50\"\n  train 50 (initN50, weights50) (tstT, targets) (tstI, inputs) initN50\n\n  print \"Beginning training with n=100\"\n  train 100 (initN100, weights100) (tstT, targets) (tstI, inputs) initN100\n\n\n\n\n\n-- Helper functions I was too lazy to import\n-- These are not essential to understanding any of the actual code.\n\n-- Lets me write pointfree code using functions that takes two arguments\n-- instead of just one\ninfixr 9 ...\n(...) :: (b -> c) -> (a1 -> a2 -> b) -> a1 -> a2 -> c\n(...) = (.) . (.)\n\n-- Lets me map over something inside another structure.\n-- eg: (+1) <$$> [[a]] would map over all of the inner lists\ninfixl 4 <$$>\n(<$$>) :: (Functor f2, Functor f1) => (a -> b) -> f1 (f2 a) -> f1 (f2 b)\n(<$$>) = fmap fmap fmap\n\nboth :: (a -> b) -> (a, a) -> (b, b)\nboth f (a, a') = (f a, f a')\n", "meta": {"hexsha": "f9b03bde6204315b3bb5bec392cc20d917a8ad9f", "size": 12018, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Neuralnetwork.hs", "max_stars_repo_name": "jared-w/Haskell-MNIST", "max_stars_repo_head_hexsha": "0136911620dd4b2227bd86fe9cb1b9db18d203b4", "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/Neuralnetwork.hs", "max_issues_repo_name": "jared-w/Haskell-MNIST", "max_issues_repo_head_hexsha": "0136911620dd4b2227bd86fe9cb1b9db18d203b4", "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/Neuralnetwork.hs", "max_forks_repo_name": "jared-w/Haskell-MNIST", "max_forks_repo_head_hexsha": "0136911620dd4b2227bd86fe9cb1b9db18d203b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6013513514, "max_line_length": 102, "alphanum_fraction": 0.6055916126, "num_tokens": 3733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893322710965, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.46092475926128085}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n\n-- | 'Graphable' Instances for lists of real or complex floating point numbers.\n--   Users FlexibleInstances.\nmodule System.Console.Ansigraph.Internal.FlexInstances where\n\nimport System.Console.Ansigraph.Core\n\nimport Data.Complex\n\n\n-- | 1-dimensional real vector graph.\ninstance Graphable [Double] where\n  graphWith = displayRV\n  graphHeight _ = 2\n\n-- | 1-dimensional complex vector graph.\ninstance Graphable [Complex Double] where\n  graphWith = displayCV\n  graphHeight _ = 4\n\n-- | 2-dimensional real matrix graph.\ninstance Graphable [[Double]] where\n  graphWith = displayMat\n  graphHeight = length\n\n-- | 2-dimensional complex matrix graph.\ninstance Graphable [[Complex Double]] where\n  graphWith = displayCMat\n  graphHeight = length\n", "meta": {"hexsha": "0b1f262e5d5c28c2cce0d9b9a3a51894aec16bdb", "size": 770, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/System/Console/Ansigraph/Internal/FlexInstances.hs", "max_stars_repo_name": "fieldstrength/ansigraph", "max_stars_repo_head_hexsha": "a0d246428036ab5733f3b6c77122386e7d50bfe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-15T05:48:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-15T05:48:24.000Z", "max_issues_repo_path": "src/System/Console/Ansigraph/Internal/FlexInstances.hs", "max_issues_repo_name": "fieldstrength/ansigraph", "max_issues_repo_head_hexsha": "a0d246428036ab5733f3b6c77122386e7d50bfe6", "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/System/Console/Ansigraph/Internal/FlexInstances.hs", "max_forks_repo_name": "fieldstrength/ansigraph", "max_forks_repo_head_hexsha": "a0d246428036ab5733f3b6c77122386e7d50bfe6", "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.8387096774, "max_line_length": 79, "alphanum_fraction": 0.761038961, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4609014328858591}}
{"text": "{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nmodule Scheme.Types where\n\nimport Control.Exception (Exception, throw)\nimport Control.Monad.Except (ExceptT)\nimport Data.Array (Array, elems)\nimport qualified Data.ByteString as BS\nimport Data.Complex (Complex ((:+)), imagPart, realPart)\nimport Data.IORef (IORef)\nimport Data.Ratio (denominator, numerator)\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Typeable (Typeable)\nimport System.IO (Handle)\nimport Text.Pretty.Simple (pPrint, pPrintLightBg)\nimport Text.Show.Functions ()\n\ntype Env = IORef [(Text, IORef SchemeVal)]\n\ntype SchemeResult = Either SchemeError\n\ntype IOSchemeResult = ExceptT SchemeError IO\n\nextractValue :: Either a p -> p\nextractValue (Right val) = val\nextractValue _ = error \"Called with Left\"\n\ndata Number\n  = Integer Integer\n  | Real Double\n  | Rational Rational\n  | Complex (Complex Double)\n  deriving (Show, Typeable, Eq)\n\nshowNum :: Number -> Text\nshowNum (Integer i) = T.pack $ show i\nshowNum (Real d) = T.pack $ show d\nshowNum (Rational r) = T.pack $ show (numerator r) <> \"/\" <> show (denominator r)\nshowNum (Complex p) = T.pack $ show (realPart p) <> \"+\" <> show (imagPart p) <> \"i\"\n\ninstance Ord Number where\n  compare (Integer x) (Integer y) = compare x y\n  compare (Integer x) (Real y) = compare (fromInteger x) y\n  compare (Integer x) (Rational y) = compare (fromInteger x) y\n  compare (Real x) (Integer y) = compare x (fromInteger y)\n  compare (Rational x) (Integer y) = compare x (fromInteger y)\n  compare (Real x) (Real y) = compare x y\n  compare (Real x) (Rational y) = compare (toRational x) y\n  compare (Rational x) (Real y) = compare x (toRational y)\n  compare (Rational x) (Rational y) = compare x y\n  compare _ _ = throw $ InvalidOperation \"Cannot compare complex numbers\"\n\ninstance Num Number where\n  fromInteger x = Integer x\n\n  (Integer x) + (Integer y) = Integer (x + y)\n  (Integer x) + (Real y) = Real (fromInteger x + y)\n  (Integer x) + (Rational y) = Rational (fromInteger x + y)\n  (Integer x) + (Complex y) = Complex (fromInteger x + y)\n  (Real x) + (Integer y) = Real (x + fromInteger y)\n  (Rational x) + (Integer y) = Rational (x + fromInteger y)\n  (Complex x) + (Integer y) = Complex (x + fromInteger y)\n  (Real x) + (Real y) = Real (x + y)\n  (Real x) + (Rational y) = Rational (toRational x + y)\n  (Real x) + (Complex y) = Complex ((x :+ 0.0) + y)\n  (Rational x) + (Real y) = Rational (x + toRational y)\n  (Complex x) + (Real y) = Complex (x + (y :+ 0.0))\n  (Rational x) + (Rational y) = Rational (x + y)\n  (Complex x) + (Complex y) = Complex (x + y)\n  _ + _ = throw $ InvalidOperation \"Cannot add rationals and complex numbers\"\n\n  (Integer x) * (Integer y) = Integer (x * y)\n  (Integer x) * (Real y) = Real (fromInteger x * y)\n  (Integer x) * (Rational y) = Rational (fromInteger x * y)\n  (Integer x) * (Complex y) = Complex (fromInteger x * y)\n  (Real x) * (Integer y) = Real (x * fromInteger y)\n  (Rational x) * (Integer y) = Rational (x * fromInteger y)\n  (Complex x) * (Integer y) = Complex (x * fromInteger y)\n  (Real x) * (Real y) = Real (x * y)\n  (Real x) * (Rational y) = Rational (toRational x * y)\n  (Real x) * (Complex y) = Complex ((x :+ 0.0) * y)\n  (Rational x) * (Real y) = Rational (x * toRational y)\n  (Complex x) * (Real y) = Complex (x * (y :+ 0.0))\n  (Rational x) * (Rational y) = Rational (x * y)\n  (Complex x) * (Complex y) = Complex (x * y)\n  _ * _ = throw $ InvalidOperation \"Cannot multiply rationals and complex numbers\"\n\n  (Integer x) - (Integer y) = Integer (x - y)\n  (Integer x) - (Real y) = Real (fromInteger x - y)\n  (Integer x) - (Rational y) = Rational (fromInteger x - y)\n  (Integer x) - (Complex y) = Complex (fromInteger x - y)\n  (Real x) - (Integer y) = Real (x - fromInteger y)\n  (Rational x) - (Integer y) = Rational (x - fromInteger y)\n  (Complex x) - (Integer y) = Complex (x - fromInteger y)\n  (Real x) - (Real y) = Real (x - y)\n  (Real x) - (Rational y) = Rational (toRational x - y)\n  (Real x) - (Complex y) = Complex ((x :+ 0.0) - y)\n  (Rational x) - (Real y) = Rational (x - toRational y)\n  (Complex x) - (Real y) = Complex (x - (y :+ 0.0))\n  (Rational x) - (Rational y) = Rational (x - y)\n  (Complex x) - (Complex y) = Complex (x - y)\n  _ - _ = throw $ InvalidOperation \"Cannot subtract rationals and complex numbers\"\n\n  negate (Integer x) = Integer (negate x)\n  negate (Real x) = Real (negate x)\n  negate (Rational x) = Rational (negate x)\n  negate (Complex x) = Complex (negate x)\n\n  abs (Integer x) = Integer (abs x)\n  abs (Real x) = Real (abs x)\n  abs (Rational x) = Rational (abs x)\n  abs (Complex x) = Complex (abs x)\n\n  signum (Integer x) = Integer (signum x)\n  signum (Real x) = Real (signum x)\n  signum (Rational x) = Rational (signum x)\n  signum (Complex x) = Complex (signum x)\n\ninstance Fractional Number where\n  fromRational x = Rational x\n\n  (Integer x) / (Integer y) = Rational (fromInteger x / fromInteger y)\n  (Integer x) / (Real y) = Real (fromInteger x / y)\n  (Integer x) / (Rational y) = Rational (fromInteger x / y)\n  (Integer x) / (Complex y) = Complex (fromInteger x / y)\n  (Real x) / (Integer y) = Real (x / fromInteger y)\n  (Rational x) / (Integer y) = Rational (x / fromInteger y)\n  (Complex x) / (Integer y) = Complex (x / fromInteger y)\n  (Real x) / (Real y) = Real (x / y)\n  (Real x) / (Rational y) = Rational (toRational x / y)\n  (Real x) / (Complex y) = Complex ((x :+ 0.0) / y)\n  (Rational x) / (Real y) = Rational (x / toRational y)\n  (Complex x) / (Real y) = Complex (x / (y :+ 0.0))\n  (Rational x) / (Rational y) = Rational (x / y)\n  (Complex x) / (Complex y) = Complex (x / y)\n  _ / _ = throw $ InvalidOperation \"Cannot divide rationals and complex numbers\"\n\n  recip (Integer x) = Real (recip $ fromInteger x)\n  recip (Real x) = Real (recip x)\n  recip (Rational x) = Rational (recip x)\n  recip (Complex x) = Complex (recip x)\n\ndata Fn = Fn {macro :: Bool, params :: [Text], vararg :: Maybe Text, body :: [SchemeVal], closure :: Env}\n\ninstance Show Fn where\n  show _ = \"<fn>\"\n\ndata SchemeVal\n  = List [SchemeVal]\n  | PairList [SchemeVal] SchemeVal\n  | Vector (Array Int SchemeVal)\n  | Bytevector BS.ByteString\n  | String Text\n  | Character Char\n  | Symbol Text\n  | Boolean Bool\n  | Number Number\n  | Nil\n  | Primitive ([SchemeVal] -> SchemeResult SchemeVal)\n  | Fun Fn\n  | IOFun ([SchemeVal] -> IOSchemeResult SchemeVal)\n  | Port Handle\n  deriving (Show, Typeable)\n\ninstance Eq SchemeVal where\n  (==) (List x) (List y) = length x == length y && all (uncurry (==)) (zip x y)\n  (==) (PairList xs x) (PairList ys y) = List (xs ++ [x]) == List (ys ++ [y])\n  (==) (Vector x) (Vector y) = x == y\n  (==) (Bytevector x) (Bytevector y) = x == y\n  (==) (String x) (String y) = x == y\n  (==) (Character x) (Character y) = x == y\n  (==) (Symbol x) (Symbol y) = x == y\n  (==) (Boolean x) (Boolean y) = x == y\n  (==) (Number x) (Number y) = x == y\n  (==) _ _ = False\n\nunwordVals :: [SchemeVal] -> Text\nunwordVals xs = T.unwords $ showVal <$> xs\n\nshowVal :: SchemeVal -> Text\nshowVal (List (Symbol \"quote\" : xs)) = \"'\" <> unwordVals xs\nshowVal (List (Symbol \"quasiquote\" : xs)) = \"`\" <> unwordVals xs\nshowVal (List (Symbol \"unquote\" : xs)) = \",\" <> unwordVals xs\nshowVal (List (Symbol \"unquote-splicing\" : xs)) = \",@\" <> unwordVals xs\nshowVal (List contents) = \"(\" <> unwordVals contents <> \")\"\nshowVal (PairList contents cdr) = \"(\" <> unwordVals contents <> \" . \" <> showVal cdr <> \")\"\nshowVal (Vector vec) = T.pack $ \"#(\" <> unwords (map show $ elems vec) <> \")\"\nshowVal (Bytevector vec) = T.pack $ \"#u8(\" <> unwords (map show $ BS.unpack vec) <> \")\"\nshowVal (String s) = \"\\\"\" <> s <> \"\\\"\"\nshowVal (Character a) = T.pack $ \"#\\\\\" <> [a]\nshowVal (Symbol s) = s\nshowVal (Boolean True) = \"#t\"\nshowVal (Boolean False) = \"#f\"\nshowVal (Number n) = showNum n\nshowVal Nil = \"nil\"\nshowVal Primitive {} = \"<prim>\"\nshowVal Fun {} = \"<fun>\"\nshowVal IOFun {} = \"<io>\"\nshowVal (Port _) = \"<port>\"\n\ndumpAST :: SchemeVal -> IO ()\ndumpAST = dumpAST' True\n\ndumpAST' :: Bool -> SchemeVal -> IO ()\ndumpAST' True = pPrint\ndumpAST' False = pPrintLightBg\n\ndata SchemeError\n  = Generic Text\n  | ArgumentLengthMismatch Int [SchemeVal]\n  | TypeMismatch Text SchemeVal\n  | UnboundSymbol Text\n  | ParserError Text\n  | NotFunction SchemeVal\n  | InvalidOperation Text\n  | ReservedName Text\n  | EmptyList\n  deriving (Show)\n\ninstance Exception SchemeError\n\nshowError :: SchemeError -> Text\nshowError (TypeMismatch err vap) = \"Invalid type: expected \" <> err <> \", but found \" <> T.pack (show vap)\nshowError (Generic err) = \"Unexpectec error: \" <> err\nshowError (UnboundSymbol sym) = \"Unbound symbol: \" <> sym\nshowError (ArgumentLengthMismatch ex act) = \"Expected \" <> T.pack (show ex) <> \" but found \" <> T.pack (show $ length act)\nshowError (ParserError err) = \"Parsing error, could not parse input: \" <> err\nshowError (NotFunction err) = \"Attempt at calling \" <> showVal err <> \" as a function\"\nshowError (InvalidOperation err) = \"Invalid: \" <> err\nshowError (ReservedName err) = \"Cannot define : \" <> err <> \" because it is a reserved name\"\nshowError EmptyList = \"Empty list is not allowed\"\n", "meta": {"hexsha": "9302a7ed7f0f5d0ceb52f8a1558d30be9e00bf3a", "size": 9127, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Scheme/Types.hs", "max_stars_repo_name": "sondr3/scheme-hs", "max_stars_repo_head_hexsha": "8bf2481ff617a7103f93b12e112b643fb5a8f173", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-04T10:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T10:40:57.000Z", "max_issues_repo_path": "lib/Scheme/Types.hs", "max_issues_repo_name": "sondr3/scheme-hs", "max_issues_repo_head_hexsha": "8bf2481ff617a7103f93b12e112b643fb5a8f173", "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": "lib/Scheme/Types.hs", "max_forks_repo_name": "sondr3/scheme-hs", "max_forks_repo_head_hexsha": "8bf2481ff617a7103f93b12e112b643fb5a8f173", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8382978723, "max_line_length": 122, "alphanum_fraction": 0.6362441109, "num_tokens": 2929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4606796658671747}}
{"text": "#!/usr/bin/env stack\n-- stack runghc --package reanimate\n{-# LANGUAGE OverloadedStrings #-}\nmodule Main (main) where\n\nimport           Data.Complex\nimport           Graphics.SvgTree\nimport           Linear.V2\nimport           Reanimate\nimport           Reanimate.Ease\nimport           Codec.Picture\n\n-- layer 3\nmain :: IO ()\nmain = reanimate $ setDuration 30 $ sceneAnimation $ do\n    _ <- newSpriteSVG $ mkBackgroundPixel (PixelRGBA8 252 252 252 0xFF)\n    play $ fourierA (fromToS 0 5)      -- Rotate 15 times\n      # setDuration 50\n      # signalA (reverseS . powerS 2 . reverseS) -- Start fast, end slow\n      # pauseAtEnd 2\n    play $ fourierA (constantS 0)       -- Don't rotate at all\n      # setDuration 10\n      # reverseA\n      # signalA (powerS 2)                       -- Start slow, end fast\n      # pauseAtEnd 2\n\n-- layer 2\nfourierA :: (Double -> Double) -> Animation\nfourierA genPhi = animate $ \\t ->\n    let circles = setFourierLength (t*piFourierLen) piFourier\n        coeffs = fourierCoefficients $ rotateFourier (genPhi t) circles\n    in mkGroup\n    [ drawCircles coeffs\n    , withStrokeColor \"green\" $\n      withStrokeLineJoin JoinRound $\n      withFillOpacity 0 $\n      withStrokeWidth (defaultStrokeWidth*2) $\n      mkLinePath $ mkFourierOutline circles\n    , let x :+ y = sum coeffs in\n      translate x y $ withFillColor \"red\" $ mkCircle (defaultStrokeWidth*3)\n    ]\n\ndrawCircles :: [Complex Double] -> SVG\ndrawCircles [] = mkGroup []\ndrawCircles ( x :+ y : xs) =\n  translate x y $ drawCircles' xs\n\ndrawCircles' :: [Complex Double] -> SVG\ndrawCircles' circles = mkGroup\n    [ worker circles\n    , withStrokeColor \"black\" $\n      withStrokeLineJoin JoinRound $\n      withFillOpacity 0 $\n      mkLinePath [ (x, y) | x :+ y <- scanl (+) 0 circles ]]\n  where\n    worker [] = None\n    worker (x :+ y : rest) =\n      let radius = sqrt(x*x+y*y) in\n      mkGroup\n      [ withStrokeColor \"dimgrey\" $\n        withFillOpacity 0 $\n        mkCircle radius\n      , translate x y $ worker rest ]\n\n-- layer 1\nnewtype Fourier = Fourier {fourierCoefficients :: [Complex Double]}\n\npiFourier :: Fourier\npiFourier = mkFourier $ lineToPoints 500 $\n  toLineCommands $ extractPath $ scale 15 $\n  center $ latexAlign \"\\\\pi\"\n\npiFourierLen :: Double\npiFourierLen = sum $ map magnitude $ drop 1 $ take 500 $ fourierCoefficients piFourier\n\npointAtFourier :: Fourier -> Complex Double\npointAtFourier = sum . fourierCoefficients\n\nmkFourier :: [RPoint] -> Fourier\nmkFourier points = Fourier $ findCoefficient 0 :\n    concat [ [findCoefficient n, findCoefficient (-n)] | n <- [1..] ]\n  where\n    findCoefficient :: Int -> Complex Double\n    findCoefficient n =\n        sum [ toComplex point * exp (negate (fromIntegral n) * 2 *pi * i*t) * deltaT\n            | (idx, point) <- zip [0::Int ..] points, let t = fromIntegral idx/nPoints ]\n    i = 0 :+ 1\n    toComplex (V2 x y) = x :+ y\n    deltaT = recip nPoints\n    nPoints = fromIntegral (length points)\n\nsetFourierLength :: Double -> Fourier -> Fourier\nsetFourierLength _ (Fourier []) = Fourier []\nsetFourierLength len0 (Fourier (first:lst)) = Fourier $ first : worker len0 lst\n  where\n    worker _len [] = []\n    worker len (c:cs) =\n      if magnitude c < len\n        then c : worker (len - magnitude c) cs\n        else [c * realToFrac (len / magnitude c)]\n\nrotateFourier :: Double -> Fourier -> Fourier\nrotateFourier phi (Fourier coeffs) =\n    Fourier $ worker coeffs (0::Integer)\n  where\n    worker [] _ = []\n    worker (x:rest) 0 = x : worker rest 1\n    worker [left] n = worker [left,0] n\n    worker (left:right:rest) n =\n      let n' = fromIntegral n in\n      left * exp (negate n' * 2 * pi * i * phi') :\n      right * exp (n' * 2 * pi * i * phi') :\n      worker rest (n+1)\n    i = 0 :+ 1\n    phi' = realToFrac phi\n\nmkFourierOutline :: Fourier -> [(Double, Double)]\nmkFourierOutline fourier =\n    [ (x, y)\n    | idx <- [0 .. granularity]\n    , let x :+ y = pointAtFourier $ rotateFourier (idx/granularity) fourier\n    ]\n  where\n    granularity = 500\n", "meta": {"hexsha": "566e3d4b9f40fb092b83d97a533c62c02205bf90", "size": 3995, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/tut_glue_fourier.hs", "max_stars_repo_name": "TristanCacqueray/reanimate", "max_stars_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tut_glue_fourier.hs", "max_issues_repo_name": "TristanCacqueray/reanimate", "max_issues_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tut_glue_fourier.hs", "max_forks_repo_name": "TristanCacqueray/reanimate", "max_forks_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.96, "max_line_length": 88, "alphanum_fraction": 0.6260325407, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4606796658671747}}
{"text": "{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators       #-}\n\nmodule Grenade.Layers.Internal.BLAS\n    ( -- easy interface\n      matXVec\n    , outerV\n    , checkVectors\n    , unsafeMemCopyVectorFromTo\n    , memCopyVectorFromTo\n    , unsafeMemZero\n    , memZero\n      -- more complicated, but direct, function calls\n    , BlasTranspose (..)\n    , swapTranspose\n    , dgemmUnsafe\n    , dgemvUnsafe\n    , dgerUnsafe\n    ) where\n\nimport           Control.Monad\nimport           Data.IORef\nimport           Data.Proxy\nimport qualified Data.Vector.Storable         as V\nimport           Foreign                      (withForeignPtr)\nimport           Foreign.C.Types\nimport           Foreign.Ptr\nimport           Foreign.Storable             (sizeOf)\nimport           GHC.IO.Handle.Text           (memcpy)\nimport           GHC.TypeLits\nimport qualified Numeric.LinearAlgebra        as LA\nimport qualified Numeric.LinearAlgebra.Static as LAS\nimport           System.IO.Unsafe             (unsafePerformIO)\n\nimport           Grenade.Layers.Internal.CUDA\nimport           Grenade.Types\nimport           Grenade.Utils.Vector\n\nimport           Debug.Trace\n\n#define USE_DGEMM_ONLY 0\n\n-- | Computes vec2 <- mat * vec1 + beta * vec2.\nmatXVec :: BlasTranspose -> V.Vector RealNum -> V.Vector RealNum -> RealNum -> V.Vector RealNum -> IO (V.Vector RealNum)\nmatXVec trMat mat vec1 beta vec2 =\n#if USE_DGEMM_ONLY\n  dgemmUnsafe trMat BlasNoTranspose (m, k) (ay, 1) 1.0 mat vec1 beta vec2\n# else\n  dgemvUnsafe trMat (m, k) 1.0 mat vec1 beta vec2\n#endif\n  where\n    ay = V.length vec1\n    ax = V.length vec2\n    (m, k) = swapTranspose trMat (ax, ay)\n\n\n-- | Computes the outer product of two vectors: mat <- vec1 `outer` vec2\nouterV :: V.Vector RealNum -> V.Vector RealNum -> IO (V.Vector RealNum)\nouterV vec1 vec2 =\n#if USE_DGEMM_ONLY\n  dgemmUnsafe BlasNoTranspose BlasNoTranspose (o, 1) (1, i) 1.0 vec1 vec2 0 (createVectorUnsafe (i * o)) -- beta = 0 initialises the matrix\n#else\n  createVector (i * o) >>= memZero >>= dgerUnsafe (o, i) 1.0 vec1 vec2\n#endif\n  where o = V.length vec1\n        i = V.length vec2\n\n\n-- | Check two vectors if they are equal. For testing purposes.\ncheckVectors :: V.Vector RealNum -> V.Vector RealNum -> Bool\ncheckVectors v1 v2 = V.length v1 == V.length v2 && and (zipWith (==) (toStr v1) (toStr v2))\n  where\n    toStr :: V.Vector RealNum -> [String]\n    toStr v = map (show . round . (*10^5)) $ V.toList v\n{-# INLINE checkVectors #-}\n\n-- | Newtype holding CINT for Transpose values.\nnewtype CBLAS_TRANSPOSET =\n  CBLAS_TransposeT CInt\n  deriving (Eq, Show)\n\n-- | Transpose values\ndata BlasTranspose\n  = BlasNoTranspose\n  | BlasTranspose\n  | BlasConjTranspose\n  | BlasConjNoTranspose\n  deriving (Eq, Show)\n\nencodeTransposeIntBool :: BlasTranspose -> Int\nencodeTransposeIntBool BlasNoTranspose     = 0\nencodeTransposeIntBool BlasTranspose       = 1\nencodeTransposeIntBool BlasConjTranspose   = 1\nencodeTransposeIntBool BlasConjNoTranspose = 0\n{-# INLINE encodeTransposeIntBool #-}\n\nswapTranspose :: BlasTranspose -> (Int, Int) -> (Int, Int)\nswapTranspose BlasNoTranspose x        = x\nswapTranspose BlasTranspose (a, b)     = (b, a)\nswapTranspose BlasConjNoTranspose x    = x\nswapTranspose BlasConjTranspose (a, b) = (b, a)\n{-# INLINE swapTranspose #-}\n\n-- | Error text\nmkDimText :: (Show a1, Show a2, Show a3, Show a4, Show a5, Show a6) => (a1, a2) -> (a3, a4) -> (a5, a6) -> String\nmkDimText (ax, ay) (bx, by) (cx, cy) = \"resulting dimensions: [\" ++ show ax ++ \"x\" ++ show ay ++ \"]*[\" ++ show bx ++ \"x\" ++ show by ++ \"]=[\" ++ show cx ++ \"x\" ++ show cy ++ \"]\"\n\n\n-- | Computes: C <- alpha*op( A )*op( B ) + beta*C, where op(X) may transpose the matrix X\n--\n-- dgemm, see http://www.netlib.org/lapack/explore-html/d1/d54/group__double__blas__level3_gaeda3cbd99c8fb834a60a6412878226e1.html for the documentation.\n--\n-- void cblas_dgemm (\n--              const CBLAS_LAYOUT      layout,\n--              const CBLAS_TRANSPOSE   TransA,\n--              const CBLAS_TRANSPOSE   TransB,\n--              const int       M,\n--              const int       N,\n--              const int       K,\n--              const double    alpha,\n--              const double *          A,\n--              const int       lda,\n--              const double *          B,\n--              const int       ldb,\n--              const double    beta,\n--              double *        C,\n--              const int       ldc\n-- \t)\n{-# NOINLINE dgemmUnsafe #-}\ndgemmUnsafe :: BlasTranspose    -- ^ Transpose Matrix A\n            -> BlasTranspose    -- ^ Transpose Matrix B\n            -> (Int, Int)       -- ^ Rows and cols of A on entry (not transposed)\n            -> (Int, Int)       -- ^ Rows and Cols of B on entry (not transposed)\n            -> RealNum           -- ^ Alpha\n            -> V.Vector RealNum  -- ^ A\n            -> V.Vector RealNum  -- ^ B\n            -> RealNum           -- ^ Beta\n            -> V.Vector RealNum  -- ^ C\n            -> IO (V.Vector RealNum)  -- ^ Return new C\ndgemmUnsafe trA trB (axIn, ayIn) (bxIn, byIn) alpha matrixA matrixB beta matrixC\n  | isBadGemm =\n    error $!\n    \"bad dimension args to dgemmUnsafe: ax ay bx by cx cy: \" ++\n    show [ax, ay, bx, by, ax, by] ++ \" matrix C length: \" ++ show (V.length matrixC) ++ \"\\n\\t\" ++ mkDimText (ax, ay) (bx, by) (ax, by)\n  | otherwise = do\n      V.unsafeWith matrixA $ \\aPtr' ->\n        V.unsafeWith matrixB $ \\bPtr' ->\n          V.unsafeWith matrixC $ \\cPtr' ->  do\n#ifdef USE_FLOAT\n            sgemm_direct\n#else\n            dgemm_direct\n#endif\n              (encodeTransposeIntBool trA) -- transpose A\n              (encodeTransposeIntBool trB) -- transpose B\n              (fromIntegral ax)     -- rows of C = rows of A transposed\n              (fromIntegral by)     -- cols of C = cols of B transposed\n              (fromIntegral ay)     -- k = cols of A transposed = rows of B transposed\n              alpha\n              aPtr'\n              (fromIntegral axIn) -- LDA\n              bPtr'\n              (fromIntegral bxIn) -- LDB\n              beta\n              cPtr'\n              (fromIntegral ax)   -- LDC\n            return matrixC\n  where\n    (ax, ay) = swapTranspose trA (axIn, ayIn)\n    (bx, by) = swapTranspose trB (bxIn, byIn)\n    isBadGemm = minimum [ax, ay, bx, by] <= 0 || not (ax * by == V.length matrixC && ay == bx)\n\n\n-- | Computes: Y <- alpha*op( A )*X + beta*Y, where op(A) may transpose the matrix A\n--\n-- dgemv, see http://www.netlib.org/lapack/explore-html/d7/d15/group__double__blas__level2_gadd421a107a488d524859b4a64c1901a9.html#gadd421a107a488d524859b4a64c1901a9\n--\n-- void cblas_dgemv \t(\n--              const CBLAS_LAYOUT  \tlayout,\n-- \t\tconst CBLAS_TRANSPOSE  \tTransA,\n-- \t\tconst int  \tM,\n-- \t\tconst int  \tN,\n-- \t\tconst double  \talpha,\n-- \t\tconst double *  \tA,\n-- \t\tconst int  \tlda,\n-- \t\tconst double *  \tX,\n-- \t\tconst int  \tincX,\n-- \t\tconst double  \tbeta,\n-- \t\tdouble *  \tY,\n-- \t\tconst int  \tincY\n-- \t)\n{-# NOINLINE dgemvUnsafe #-}\ndgemvUnsafe :: BlasTranspose    -- ^ Transpose Matrix\n            -> (Int, Int)       -- ^ rows and cols of A on entry (not transposed)\n            -> RealNum           -- ^ Alpha\n            -> V.Vector RealNum  -- ^ A\n            -> V.Vector RealNum  -- ^ X\n            -> RealNum           -- ^ Beta\n            -> V.Vector RealNum  -- ^ C\n            -> IO (V.Vector RealNum)  -- ^ Return new C\ndgemvUnsafe trA (m, k) alpha matrixA vecX beta vecY\n  | ax /= V.length vecY || ay /= V.length vecX =\n    error $!\n    \"bad dimension args to dgemvUnsafe: ax ay (length vecX) (length vecY): \" ++\n    show [ax, ay, V.length vecX, V.length vecY] ++ \" \\n\\t\" ++ mkDimText (ax, ay) (V.length vecX, 1) (m, 1)\n  | otherwise = do\n      V.unsafeWith matrixA $ \\aPtr' ->\n        V.unsafeWith vecX $ \\xPtr' ->\n          V.unsafeWith vecY $ \\yPtr' -> do\n#ifdef USE_FLOAT\n            sgemv_direct\n#else\n            dgemv_direct\n#endif\n              (encodeTransposeIntBool trA)      -- transpose A\n              (fromIntegral m)\n              (fromIntegral k)\n              alpha\n              aPtr'\n              (fromIntegral m)\n              xPtr'\n              1\n              beta\n              yPtr'\n              1\n            return vecY\n  where\n    (ax, ay) = swapTranspose trA (m, k)\n\n-- | Computes: A <- alpha*X*Y^T + A\n--\n-- dger, see http://www.netlib.org/lapack/explore-html/d7/d15/group__double__blas__level2_ga458222e01b4d348e9b52b9343d52f828.html#ga458222e01b4d348e9b52b9343d52f828\n--\n-- void cblas_dger \t(\n--              const CBLAS_LAYOUT  \tlayout,\n-- \t\tconst int  \tM,\n-- \t\tconst int  \tN,\n-- \t\tconst double  \talpha,\n-- \t\tconst double *  \tX,\n-- \t\tconst int  \tincX,\n-- \t\tconst double *  \tY,\n-- \t\tconst int  \tincY,\n-- \t\tdouble *  \tA,\n-- \t\tconst int  \tlda\n-- \t)\n{-# NOINLINE dgerUnsafe #-}\ndgerUnsafe :: (Int, Int)           -- ^ Dimensions of matrix A\n           -> RealNum               -- ^ Alpha\n           -> V.Vector RealNum      -- ^ X\n           -> V.Vector RealNum      -- ^ C\n           -> V.Vector RealNum      -- ^ A\n           -> IO (V.Vector RealNum)  -- ^ Return new C\ndgerUnsafe (ax, ay) alpha vecX vecY matrixA\n  | ax /= len || ay /= V.length vecY =\n    error $! \"bad dimension args to dgerUnsafe: X Y ax ay: \" ++ show [len, V.length vecY, ax, ay] ++ \" \\n\\t\" ++ mkDimText (ax, ay) (V.length vecX, 1) (V.length vecY, 1)\n  | otherwise = do\n      V.unsafeWith matrixA $ \\aPtr' ->\n        V.unsafeWith vecX $ \\xPtr' ->\n          V.unsafeWith vecY $ \\yPtr' -> do\n#ifdef USE_FLOAT\n            sger_direct\n#else\n            dger_direct\n#endif\n              (fromIntegral ax)\n              (fromIntegral ay)\n              alpha\n              xPtr'\n              1\n              yPtr'\n              1\n              aPtr'\n              (fromIntegral ax)\n            return matrixA\n  where\n    len = V.length vecX\n\n\n-- |  Matrix mult for general dense matrices\ntype BLASGemmFunFFI scale el\n  =  Int -- transpose A: 1, not transpose A: 0\n  -> Int -- transpose B: 1, not transpose B: 0\n  -> CInt -- m\n  -> CInt -- n\n  -> CInt -- k\n  -> {- scal A * B -} scale  -- alpha\n  -> {- Matrix A-} Ptr el    -- A\n  -> CInt                    -- LDA\n  -> {- B -} Ptr el\n  -> CInt\n  -> scale                   -- beta\n  -> {- C -}  Ptr el\n  -> CInt\n  -> IO ()\n\nforeign import ccall unsafe \"dgemm_direct\" dgemm_direct :: BLASGemmFunFFI Double Double\nforeign import ccall unsafe \"sgemm_direct\" sgemm_direct :: BLASGemmFunFFI Float Float\n\n\n-- |  Matrix mult for general dense matrices\ntype BLASGemvFunFFI scale el\n  =  Int    -- transpose A: 1, not transpose A: 0\n  -> CInt   -- m\n  -> CInt   -- n\n  -> scale  -- alpha\n  -> Ptr el -- Matrix A\n  -> CInt   -- LDA\n  -> Ptr el\n  -> CInt\n  -> scale -- beta\n  -> Ptr el\n  -> CInt\n  -> IO ()\n\nforeign import ccall unsafe \"dgemv_direct\" dgemv_direct :: BLASGemvFunFFI Double Double\nforeign import ccall unsafe \"sgemv_direct\" sgemv_direct :: BLASGemvFunFFI Float Float\n\n\ntype BlasGerxFunFFI scale el\n  =  CInt\n  -> CInt\n  -> scale\n  -> Ptr el\n  -> CInt\n  -> Ptr el\n  -> CInt\n  -> Ptr el\n  -> CInt\n  -> IO ()\n\nforeign import ccall unsafe \"dger_direct\" dger_direct :: BlasGerxFunFFI Double Double\nforeign import ccall unsafe \"sger_direct\" sger_direct :: BlasGerxFunFFI Float Float\n\n\n-- toRows :: Int -> V.Vector Double -> [V.Vector Double]\n-- toRows m vec = LA.toRows . reshapeF m . LA.vector . V.toList $ vec\n--   where reshapeF r = LA.tr' . LA.reshape r\n\n-- vec1 :: LAS.R 10\n-- vec1 = LAS.vector [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.34868882831497655, 0.0, 1.4026932193043212e-2]\n\n-- -- dEdy:\n-- -- mmCheck : [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-4.8711473950841355e-2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-1.9595481318788644e-3]\n-- -- mm' : [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.24602759633121374,-1.2277801012906878e-2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-9.89711206989971e-3,-4.939070836308897e-4,0.0,0.0]\n\n-- vec3 :: V.Vector Double\n-- vec3 = (\n--   V.fromList [0.0, 0.0, 0.0, 0.0, (-0.13969898085418284)])\n\n-- vec2 :: LAS.R 5\n-- vec2 = LAS.vector [0.0, 0.0, 0.0, 0.0, -0.13969898085418284]\n\n-- res = vec1 `LAS.outer` vec2\n\n-- test =\n--   toRows 10 $\n--   outerV (LAS.extract vec1) (LAS.extract vec2) (V.replicate (LAS.size vec1 * LAS.size vec2) 10)\n", "meta": {"hexsha": "5e463b6e0cb8875109833d4e87ccf415645e783f", "size": 12496, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Internal/BLAS.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Layers/Internal/BLAS.hs", "max_issues_repo_name": "schnecki/grenade", "max_issues_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Internal/BLAS.hs", "max_forks_repo_name": "schnecki/grenade", "max_forks_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-02T01:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:08:47.000Z", "avg_line_length": 34.5193370166, "max_line_length": 284, "alphanum_fraction": 0.5701024328, "num_tokens": 4120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4606796658671746}}
{"text": "{-# LANGUAGE RankNTypes, BangPatterns, ScopedTypeVariables, FlexibleInstances #-}\n\nmodule Math.Probably.MALA where\n\nimport qualified Math.Probably.PDF as PDF\nimport Math.Probably.Sampler\nimport qualified Math.Probably.PDF as PDF\nimport Control.Applicative\n\nimport Numeric.LinearAlgebra\nimport Text.Printf\nimport System.IO\nimport Data.Maybe\n\nimport Statistics.Test.KolmogorovSmirnov\nimport Statistics.Test.MannWhitneyU\nimport qualified Data.Vector.Unboxed as U\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Vector.Storable as VS\n\nimport Debug.Trace\nimport Data.IORef\nimport Control.Spoon\n\n\ndata MalaPar = MalaPar { mpXi :: !(Vector Double),\n                         mpPi :: !Double,\n                         mpGradLast :: !(Vector Double),\n                         mpSigma :: !Double,\n                         mpCount :: !Double,\n                         mpAccept :: !Double,\n                         mpFreezeSigma :: !Bool,\n                         mpThin :: !Int,\n                         mpMaxGradLen :: !Double } --,\n--                         mpLastRatio :: !Double }\n  deriving Show\n\ntrunc t v = scale (t/(max t (norm2 v))) v\n\nmala1 :: Covariance a => a -> (Vector Double -> (Double,Vector Double)) \n         -> Bool \n         -> MalaPar\n         -> Sampler MalaPar\nmala1 cov postgrad useCache\n      (MalaPar xi piCached gradientiCached sigma tr tracc freeze thinn maxGrad) = do\n  let (pi,gradienti) = if useCache \n                          then (piCached, gradientiCached)\n                          else let (p, gr_untr) = postgrad xi\n                               in (p, trunc maxGrad gr_untr)\n  let xstarMean = xi + scale (sigma/2) (cov `covMul` gradienti)\n  xstar <- mvnSampler xstarMean sigma cov\n  u <- unitSample\n  let (!pstar, gradientStarUntrunc) = postgrad xstar\n      gradientStar = trunc maxGrad gradientStarUntrunc\n  let !revJumpMean = xstar + scale (sigma/2) (cov `covMul` gradientStar)\n      ptop = mvnPDF revJumpMean sigma cov xi\n      pbot = mvnPDF xstarMean sigma cov xstar\n      ratio = exp $   pstar -pi + ptop - pbot\n      tr' = max 1 tr\n      sigmaNext = case () of\n         _ | freeze -> sigma\n      accept = tracc / tr    \n      freezeNext = freeze {-| freeze = True\n                 | not freeze = tr > 100 && accept > 0.5 && accept < 0.6  -}\n  if trace (show $ (tr, pstar ,pi , ratio, sigma)) $ u < ratio\n     then return $ MalaPar xstar pstar (gradientStar) \n                           (if freezeNext then sigma else (min 1.4 $ 1+kmala/tr')*sigma) \n                           (tr+1) (tracc+1) freezeNext  thinn maxGrad\n--                           sigma (tr+1) (tracc+1)\n     else return $ MalaPar xi pi ( gradienti) \n                           (if freezeNext then sigma else (max 0.7143 $ 1-kmala/tr')**1.3*sigma) \n                           (tr+1) tracc freezeNext thinn maxGrad\n--                           sigma (tr+1) tracc\n\n\nrunMalaMP :: Covariance a => a -> (Vector Double -> (Double,Vector Double)) \n         ->  Int -> MalaPar -> [(Double,Vector Double)] -> RIO (MalaPar, [(Double,Vector Double)])\nrunMalaMP cov  pdf nsam init xs0 = go nsam init xs0 where\n  go 0 mpar xs = do io $ putStrLn $ \"MALA accept = \"++show (mpAccept mpar/mpCount mpar)\n                    io $ putStrLn $ \"MALA sigma = \"++show (mpSigma mpar)\n                    return (mpar, xs)\n  go n y xs = do y1 <- sample $ mala1 cov pdf True y\n--                 io $ do putStrLn $ show (mpCount y1, mpPi y1, mpSigma y1)\n--                         hFlush stdout\n                 let newChainRes = if mpThin y1 == 0 || round (mpCount y1) `mod` mpThin y1 ==0\n                                      then let !xi = mpXi y1\n                                               !pi = mpPi y1\n                                               !more = (pi,xi)\n                                           in more:xs \n                                      else xs\n                 go (n-1) y1 newChainRes\n\nrunMalaUntilBetter :: Covariance a => a ->(Vector Double -> (Double,Vector Double)) \n         ->  Int -> MalaPar -> RIO (MalaPar, [(Double,Vector Double)])\nrunMalaUntilBetter cov  pdf nsam init = go nsam init [] where\n  pTarget = mpPi init\n  go 0 mpar xs = do io $ putStrLn $ \"MALA accept = \"++show (mpAccept mpar/mpCount mpar)\n                    io $ putStrLn $ \"MALA sigma = \"++show (mpSigma mpar)\n                    return (mpar, xs)\n  go n y xs = do y1 <- sample $ mala1 cov  pdf True y\n                 io $ do putStrLn $ show (mpCount y1, mpPi y1, mpSigma y1)\n                         hFlush stdout\n                 let newChainRes = if mpThin y1 == 0 || round (mpCount y1) `mod` mpThin y1 ==0\n                                      then (mpPi y1, mpXi y1):xs \n                                      else xs\n                 if mpPi y1 > pTarget \n                    then return (y1, newChainRes)\n                    else go (n-1) y1 $ newChainRes\n\n\n{-runMalaMPaccept' :: Matrix Double -> (Vector Double -> (Double,Vector Double)) \n         ->  Int -> MalaPar -> RIO (MalaPar, [(Double,Vector Double)])\nrunMalaMPaccept'  cov pdf nsam init  = do\n  stseed <- S.get\n  res <- io $ do\n   seedref <- newIORef stseed\n   resRef <- newIORef Nil\n   let go !mpar  \n        | (round $ mpAccept mpar) >= nsam \n          = return mpar\n        | otherwise \n          = do seed <- readIORef seedref\n               putStr ((show (round $ mpAccept mpar)) ++\".\") >> hFlush stdout\n               let (!mpar1, !seed1) = unSam (mala1 cov pdf mpar) seed\n               writeIORef seedref seed1\n               modifyIORef resRef (Cons (Pair (mpPi mpar1) ( mpXi mpar1)))\n               go mpar1\n   mpar <- go init\n   seed <- readIORef seedref\n   reslist <- readIORef resRef\n   return (seed, (mpar,reslist))\n  S.put $ fst res\n  let mp = fst $ snd res\n  return $ (mp, map unPair $ unList $ snd $ snd res)\n \n--  pi = pdf $ toList $ mpXi init -}\n\nrunMalaMPaccept :: Covariance a => a -> (Vector Double -> (Double,Vector Double)) \n         -> Int -> MalaPar ->  RIO (MalaPar, [(Double,Vector Double)])\nrunMalaMPaccept cov pdf nsam init = go init [] where\n  go !mpar !xs\n    | (round $ mpAccept mpar) >= nsam = do\n         io $ putStrLn $ \"MALA accept = \"++show (mpAccept mpar/mpCount mpar)\n         io $ putStrLn $ \"MALA sigma = \"++show (mpSigma mpar)\n         return (mpar, xs)\n    | mpAccept mpar < 0.5 && mpCount mpar > 20 = \n         return (mpar, [])\n    | otherwise = do\n         !mpar1 <- sample $ mala1 cov  pdf True mpar\n         io $ putStr ((show (round $ mpAccept mpar)) ++\".\") >> hFlush stdout\n         go mpar1 $ (mpPi mpar1, mpXi mpar1):xs\n \nkmala = 5\n\n{-runMalaRioESS ::  Matrix Double -> (Vector Double -> (Double,Vector Double)) \n                  ->  Int -> Vector Double -> RIO [Vector Double]\nrunMalaRioESS cov pdf want_ess xi = do\n    let (p0,grad0) = pdf xi\n    let sigma0 = 1.5 / (realToFrac $ dim xi) -- determined empirically\n    let mp0 = MalaPar xi p0 grad0 sigma0 0 0 False\n        nsam0 = want_ess*20\n    io $ putStrLn $ \"initial sigma = \"++show (mpSigma mp0)\n    (mp1, xs1) <- runMalaMP cov pdf nsam0 mp0 []\n    let have_ess = min (mpAccept mp1) $ calcESSprim $ map snd xs1\n    if have_ess > realToFrac want_ess\n       then return $ map snd xs1\n       else do let need_ess =  max 1 $ realToFrac want_ess - have_ess\n                   samples_per_es = realToFrac nsam0/have_ess\n                   to_do = round $ samples_per_es * need_ess \n               (mp2, xs2) <- runMalaMP cov pdf to_do mp1 xs1\n               return  $ map snd  xs2 -}\n\nrunMalaRioCodaESS ::  Covariance a => a-> (Vector Double -> (Double,Vector Double)) \n                  ->  Int -> Double -> Vector Double -> RIO [Vector Double]\nrunMalaRioCodaESS cov pdf want_ess truncN xi = do\n    let (p0,grad0) = pdf xi\n    let sigma0 = 1.5 / (realToFrac $ dim xi) -- determined empirically\n    let mp0 = MalaPar xi p0 (trunc truncN grad0) sigma0 0 0 False 0 truncN\n        nsam0 = want_ess*1\n    let converged mp  xs = do\n         let have_ess = min (mpAccept mp) $ calcESSprim $ map snd xs\n         io $ putStrLn $ \"ESS=\" ++show have_ess\n         if have_ess > realToFrac want_ess\n            then return $ map snd xs\n            else do let need_ess =  max 1 $ realToFrac want_ess - have_ess\n                        samples_per_es = realToFrac nsam0/have_ess\n                        to_do = round $ samples_per_es * need_ess \n                    io $ putStrLn $ \"running converged for \"++show to_do\n                    (mp2, xs2) <- runMalaMP cov pdf to_do (mp {mpFreezeSigma = True}) xs\n                    io $ putStrLn $ \"All done\"\n                    return $ map snd xs2 \n    let go mp  n xs = do\n            (mp2, xs2) <- runMalaMP cov  pdf n mp []\n            let testres = mannWhitneyUtest TwoTailed 0.05 (U.fromList $ map fst xs2)\n                                            (U.fromList $ map fst xs) \n              \n            if testres/= Just NotSignificant\n               then do io$ putStrLn $ \"not converged: \"++show testres++\" at \"++show (mpPi mp2)\n                       go mp2  (round $ realToFrac n*2) xs2\n               else do io$ putStrLn \"converged!\"\n                       converged mp2  (xs2++xs)\n    \n    io $ putStrLn $ \"initial sigma = \"++show (mpSigma mp0)\n    (mp1, xs1) <- runMalaMPaccept cov  pdf nsam0 mp0 \n    case xs1 of\n            [] -> return []\n            _ -> go mp1  (round $ mpCount mp1) xs1\n\n{-    case (spoon (invlndet cov), mbCholSH cov) of\n       (Just (covInv, (lndt,_)), Just covChol) -> go_rest (covInv, covChol)\n       _ -> let cov' = PDF.posdefify cov in \n            case (spoon (invlndet cov'), mbCholSH cov') of\n              (Just (covInv, (lndt,_)), Just covChol) -> go_rest (covInv, covChol)\n              _ ->  do io $ putStrLn \"non-invertible covariance matrix\"\n                       return [] -}\n\nrunMalaRioSimple ::  Covariance a => a -> (Vector Double -> (Double,Vector Double)) \n                  ->  Int -> Double -> Int -> Vector Double -> RIO [Vector Double]\nrunMalaRioSimple cov pdf samples maxGrad thinN xi = do\n    let (p0,grad0) = pdf xi\n    let sigma0 = 2.7e-4 --1.5 / (realToFrac $ dim xi) -- determined empirically\n    let mp0 = MalaPar xi p0 (trunc maxGrad grad0) sigma0 0 0 False thinN maxGrad\n    \n    (mp2, xs2) <- runMalaMP cov  pdf samples mp0 []\n    io $ putStrLn $ \"All done\"\n    return $ map snd xs2 \n\ncalcCovariance :: Vector Double -> \n                  Vector Double -> \n                  (Vector Double -> (Double,Vector Double)) ->\n                  (Vector Double -> Double) -> \n                  Either (Vector Double) (Matrix Double, Matrix Double, Matrix Double)\ncalcCovariance vinit vnear postgrad posterior = finalcov where\n   ndim = dim vinit\n   finalcov \n     | ndim > 0 -- > 20000 --FIXME \n        = Left $ calcFDindepVars vinit vnear posterior --Left $ iCov vinit -- \n     | otherwise \n        = hessToCov (calcFDhess vinit vnear postgrad) Nothing\n\niCov v = VS.replicate (VS.length v) 1 -- in (m,m,m)\n\ncalcFDindepVars v v' post = trace (\"FDVars = \"++show (VS.take 10 vars))  $ vars where\n   hv =  mapVector (*1e-4) v --mapVector (max 1e-9 .  abs) $ v - v'\n   n = dim v\n   postv = post v\n   postPlus i = post $ v VS.// [(i,v @>i + hv @> i)]\n   postMinus i = post $ v VS.// [(i,v @>i - hv@> i)]\n   vars = buildVector n fvar\n   fvar i = negate $ recip $ (postPlus i - 2*postv + postMinus i)/((hv @> i)*(hv @> i))\n\n\ncalcFDhess v v' postgrad = hess2 where\n   grad =  snd . postgrad\n   gradi i = (@>i) . grad\n   hv = mapVector (max 1e-9 . abs) $ v - v'\n   n = dim v\n   gradv = grad v\n   grads =  fromRows $ flip map [0..(n-1)] $ \\i -> \n               grad (v VS.// [(i,v @>i + hv @> i)])\n   fhess (i,j) | i<j = 0\n               | otherwise = (grads @@>(j,i) - (gradv @> i))\n                                       /(2*(hv @> j)) +\n                             (grads @@>(i,j)- (gradv @> j))\n                                       /(2*(hv @> i))\n                 \n--   hess3 = scale (recip $ realToFrac n) $ sum $ map outerSelf $ grads                      \n                             \n   hess1 = buildMatrix n n fhess \n   hess2 = buildMatrix n n $ \\(i,j) -> if i>=j then hess1 @@> (i,j)\n                                               else hess1 @@> (j,i)\n \n\nouterSelf v= v `outer` v\n\nhessToCov hess mOriginal = \n   let mTryPosdefify = case mOriginal of \n            Nothing -> hessToCov (PDF.posdefify hess) (Just hess)\n            Just horiginal -> let ds =  mapVector (negate . recip) \n                                         $ takeDiag horiginal \n                              in trace (\"USING DIAGS\"++show (VS.take 10 ds)) $ Left $ ds\n   in\n   case spoon $ inv $ negate $ hess of\n     Just cov -> case mbCholSH cov of\n                   Just cholm ->  trace (\"invert success:\"++show (VS.take 10 $ takeDiag cov) ++ \"det=\"++show (det cov)) $ Right (cov, negate hess, cholm)\n                   Nothing -> trace (\"chol fail\") mTryPosdefify\n     Nothing -> trace (\"inv fail\") mTryPosdefify\n                  {- Just cov -> case mbCholSH cov of\n                                Just cholm ->  Right (cov, negate hessToCov,cholm)\n                                Nothing -> case mbCholSH $ PDF.posdefify cov of\n                                            Just cholm -> Right (cov, negate hess,cholm)\n                                            Nothing -> vars\n                  Nothing -> vars -}\n\nacceptSM ampar  | mpCount ampar == 0 = \"0/0\"\n               | otherwise = printf \"%.3g\" (rate::Double) ++ \" (\"++show yes++\"/\"++show total++\")\" where\n   rate = realToFrac (yes) / realToFrac (total)\n   yes = mpAccept ampar\n   total = mpCount ampar", "meta": {"hexsha": "8efd5dee89260b0098b6dc0228062816c0ff12fe", "size": 13521, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Probably/MALA.hs", "max_stars_repo_name": "glutamate/probably-baysig", "max_stars_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-02-12T05:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:37.000Z", "max_issues_repo_path": "src/Math/Probably/MALA.hs", "max_issues_repo_name": "silky/probably-baysig", "max_issues_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/Probably/MALA.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 45.220735786, "max_line_length": 153, "alphanum_fraction": 0.5355373123, "num_tokens": 3910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.460479244163892}}
{"text": "    \nmodule Tools\n( randomMatrix\n, makeBatchList\n, encorderForDat2\n, encorderForDat\n, length'\n, pickUpNum\n, setElem\n, oneHotEncoder\n, oneHotEncoder'\n) where\n\n-------------------------------------------------------------\n--module\n-------------------------------------------------------------\n\nimport Numeric.LinearAlgebra\nimport System.Random\nimport Data.List\n\n\nimport Durstenfeld\n\n------------------------------------------------\n\n-------------------------------------------------------------\n--Tools\n-------------------------------------------------------------\n\n--\u91cd\u307f\u306e\u521d\u671f\u5316\u7528\n--\u8981\u7d20\u304c0\u30020\u304b\u30891.0\u306e\u9593\u306e\u6570\u3067\u3001\u6307\u5b9a\u3057\u305f\u884c\u6570\u3001\u5217\u6570\u306eMatrix\u3092\u751f\u6210\u3059\u308b\u3002\nrandomMatrix :: RandomGen g => Int -> Int -> g -> Matrix Double\nrandomMatrix row col g = matrix col $ take (row*col) $ randomRs (0.0, 0.01) g\n\n--ex) randomMatrix 3 4 (mkStdGen 100)\n\nmakeBatchList :: (Eq t, Num t) => Int -> t -> Int -> Int -> [[Int]]\nmakeBatchList _ 0 _ _ = []\nmakeBatchList g num ds bs = batch' : makeBatchList (g - 1) (num - 1) ds bs\n    where data_size = ds\n          batch_size = bs\n          batch' = randomChoice data_size batch_size (mkStdGen g )\n\n--\u6570\u5b57\u306e\u30ea\u30b9\u30c8\u306e\u30ea\u30b9\u30c8\u3092\u30d5\u30a1\u30a4\u30eb\u306b\u66f8\u304d\u8fbc\u3080\u305f\u3081\u306b\u3001\u826f\u3044\u611f\u3058\u306b\u3044\u3058\u3063\u3066\u3044\u308b\u3002\nencorderForDat :: Show a => [[a]] -> [Char]\nencorderForDat xs = intercalate \"\\n\" $  fmap (intercalate \" \" . fmap show) xs\n\n--\u30ea\u30b9\u30c8\u3092\u66f8\u304d\u8fbc\u3080\u7528\nencorderForDat2 :: Show a => [a] -> [Char]\nencorderForDat2 xs = intercalate \"\\n\" $  fmap show xs \n\nlength' :: [a] -> Double\nlength' [] = 0.0\nlength' (x:xs) = 1.0 + length' xs\n\npickUpNum :: [Int] -> [a] -> [a]\npickUpNum [] _ = []\npickUpNum (x:xs) list = number : pickUpNum xs list\n    where number = list !! x\n\nsetElem1 :: Matrix R -> (Int, Int) -> Int -> Int -> R -> Matrix R\nsetElem1 m (row, col) maxrow maxcol newElem = newM\n    where v  = flatten m\n          num = row * maxcol + (col+1) --\u8981\u7d20\u304c\u4f55\u756a\u76ee\u304b\n          v1 = subVector 0 (num-1) v\n          v2 = subVector (num) (maxcol*maxrow-num) v\n          v3 = vector [newElem]\n          newV = vjoin [v1,v3,v2]\n          newM = reshape maxcol newV\n\n--\u3007\nsetElem :: Matrix R -> (Int, Int) -> R -> Matrix R\nsetElem m (row, col) newElem = setElem1 m (row, col) maxrow maxcol newElem\n    where maxrow = rows m\n          maxcol = cols m\n\n--\u30e9\u30d9\u30eb(0~9)\u3092One-Hot\u8868\u73fe\u306eMatrix(1\u884c10\u5217)\u306b\u5909\u63db\n--ex) 9 --> 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 \noneHotEncoder :: Int -> Matrix Double\noneHotEncoder num = setElem zeroM (0 ,num) 1.0 \n    where zeroM = row [0.0,0,0,0,0,0,0,0,0,0]\n\n-- =============================================\n\n--setElem1' :: Matrix R -> (Int, Int) -> Int -> Int -> R -> Matrix R\nsetElem' v col newElem = newV\n    where v1 = subVector 0 (col-1) v\n          v2 = subVector col (10-col) v\n          v3 = vector [newElem]\n          newV = vjoin [v1,v3,v2]\n\noneHotEncoder' :: Int -> Vector R\noneHotEncoder' num = setElem' zeroV (num+1) 1.0 \n    where zeroV = fromList [0.0,0,0,0,0,0,0,0,0,0]\n\n\n------------------------------------------------", "meta": {"hexsha": "5dea963aa728af7dd1077c30782282a342f35299", "size": 2840, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Tools.hs", "max_stars_repo_name": "llbxg/Fukami", "max_stars_repo_head_hexsha": "28e5cb963e372db7f2fe532043092a4bbc4c0101", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-08T10:00:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-08T10:00:17.000Z", "max_issues_repo_path": "src/Tools.hs", "max_issues_repo_name": "llbxg/Fukami", "max_issues_repo_head_hexsha": "28e5cb963e372db7f2fe532043092a4bbc4c0101", "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/Tools.hs", "max_forks_repo_name": "llbxg/Fukami", "max_forks_repo_head_hexsha": "28e5cb963e372db7f2fe532043092a4bbc4c0101", "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.9795918367, "max_line_length": 77, "alphanum_fraction": 0.5316901408, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.46035733510692567}}
{"text": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\nmodule Sam where\n\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal (normalDistr)\nimport Statistics.Distribution.Beta (betaDistr)\nimport Statistics.Distribution.Gamma (gammaDistr)\nimport qualified Statistics.Distribution.Poisson as Poisson\nimport Data.List\nimport Data.Map (empty,lookup,insert,size,keys)\nimport Data.IORef\nimport Control.Monad\nimport Control.Monad.Extra\nimport System.IO.Unsafe\nimport Control.Monad.State.Lazy (State, state , put, get, runState, MonadTrans (lift))\nimport Debug.Trace\nimport Control.Monad.Trans.Writer\nimport Numeric.Log\nimport System.Random hiding (uniform)\nimport Data.Monoid (Product (Product))\n\n\n{--\n    This file defines\n    * Two monads: Prob (for probabilities) and Meas (for unnormalized probabilities)\n    * Two inference methods: lwis and mh\n--}\n\n-- A \"Tree\" is a lazy, infinitely wide and infinitely deep tree, labelled by Doubles\n-- Our source of randomness will be a Tree, populated by uniform [0,1] choices for each label.\n-- Often people would just use a list or stream instead of a tree.\n-- But a tree allows us to be lazy about how far we are going all the time.\ndata Tree = Tree Double [Tree]\n\n-- A probability distribution over a is a state transformer over trees\n-- ie a function Tree -> (a , Tree)\n-- The idea is that it uses up bits of the tree as it runs\nnewtype Prob a = Prob (State Tree a)\n\n-- Two key things to do with trees:\n-- Split tree splits a tree in two (bijectively)\n-- Get the label at the head of the tree and discard the rest\nsplitTree :: Tree -> (Tree , Tree)\nsplitTree (Tree r (t : ts)) = (t , Tree r ts)\n\nuniform :: Prob Double\nuniform = Prob $\n      do ~(Tree r (t:ts)) <- get\n         put t\n         return r\n\n\n-- Probabilities for a monad.\n-- Sequencing is done by splitting the tree\n-- and using different bits for different computations.\ninstance Monad Prob where\n  return a = Prob $ return a\n  (Prob m) >>= f = Prob $\n                        do g <- get\n                           let (g1,g2) = splitTree g\n                           put g1\n                           x <- m\n                           put g2\n                           let (Prob m') = f x\n                           m'\ninstance Functor Prob where fmap = liftM\ninstance Applicative Prob where {pure = return ; (<*>) = ap}\n\n{-- An unnormalized measure is represented by a probability distribution over pairs of a weight and a result --}\nnewtype Meas a = Meas (WriterT (Product (Log Double)) Prob a)\n  deriving(Functor, Applicative, Monad)\n\n{-- The two key methods for Meas are sample (from a probability) and score (aka factor, weight) --}\nscore :: Double -> Meas ()\nscore r = Meas $ tell $ Product $ (Exp . log) $ (if r==0 then exp(-300) else r)\n\nscorelog :: Double -> Meas ()\nscorelog r = Meas $ tell $ Product $ Exp $ (if r==0 then exp(-300) else r)\n\nsample :: Prob a -> Meas a\nsample p = Meas $ lift p\n\n{-- Preliminaries for the simulation methods. Generate a tree with uniform random labels\n    This uses SPLIT to split a random seed --}\nrandomTree :: RandomGen g => g -> Tree\nrandomTree g = let (a,g') = random g in Tree a (randomTrees g')\nrandomTrees :: RandomGen g => g -> [Tree]\nrandomTrees g = let (g1,g2) = split g in (randomTree g1) : (randomTrees g2)\n\n{-- Run prob runs a probability deterministically, given a source of randomness --}\nrunProb :: Prob a -> Tree -> a\nrunProb (Prob a) rs = fst $ runState a rs\n\nnormal :: Double -> Double -> Prob Double\nnormal m s = do quantile (normalDistr m s) <$> uniform\n\nnormalPdf :: Double -> Double -> Double -> Double\nnormalPdf m s = density $ normalDistr m s\n\nexponential :: Double -> Prob Double\nexponential rate =\n  do x <- uniform\n     return $ - (log x / rate)\n\nexpPdf :: Double -> Double -> Double\nexpPdf rate x = exp (-rate*x) * rate\n\ngamma :: Double -> Double -> Prob Double\ngamma a b = do\n  quantile (gammaDistr a b) <$> uniform\n\nbeta :: Double -> Double -> Prob Double\nbeta a b = do\n  quantile (betaDistr a b) <$> uniform\n\npoisson :: Double -> Prob Integer\npoisson lambda = do\n  x <- uniform\n  let cmf = scanl1 (+) $ map (probability $ Poisson.poisson lambda) [0,1..]\n  let (Just n) = findIndex (> x) cmf\n  return $ fromIntegral n\n\npoissonPdf :: Double -> Integer -> Double\npoissonPdf rate n = probability (Poisson.poisson rate) (fromIntegral n)\n\ndirichlet :: [Double] -> Prob[Double]\ndirichlet as = do\n  xs <- mapM exponential as\n  let s = Prelude.sum xs\n  let ys = map (/ s) xs\n  return ys\n\nuniformbounded :: Double -> Double -> Prob Double\nuniformbounded lower upper = do\n  x <- uniform\n  return $ (upper - lower) * x + lower\n\nbernoulli :: Double -> Prob Bool\nbernoulli r = do\n  x <- uniform\n  return $ x < r\n\n{-\n uniform distribution on [0, ..., n-1]\n-}\nuniformdiscrete :: Int -> Prob Int\nuniformdiscrete n =\n  do\n    let upper = fromIntegral n\n    r <- uniformbounded 0 upper\n    return $ floor r\n\n{-- Categorical distribution: takes a list of k numbers that sum to 1, \n    and returns a number between 0 and (k-1) --}\ncategorical :: [Double] -> Prob Int\ncategorical xs = do\n  r <- uniform\n  let (Just i) = findIndex (>r) $ tail $ scanl (+) 0 xs\n  return i\n\n{-- Stochastic memoization.\n    We use unsafePerformIO to maintain\n    a table of calls that have already been made.\n    If a is finite, we could just sample all values of a in advance\n    and avoid unsafePerformIO.\n    If it is countably infinite, there probably also are implementation tricks.\n--}\nmemoize :: Ord a => (a -> Prob b) -> Prob (a -> b)\nmemoize f =  Prob $ do g <- get\n                       let ( Tree _ gs, g2) = splitTree g\n                       put g2\n                       return $ unsafePerformIO $ do\n                                ref <- newIORef Data.Map.empty\n                                return $ \\x -> unsafePerformIO $ do\n                                          m <- fmap (Data.Map.lookup x) (readIORef ref)\n                                          case m of\n                                              Just y -> return y\n                                              Nothing -> do\n                                                            let (Prob k) = f x\n                                                            n <- readIORef ref\n                                                            let (y,_) = runState k (gs !! (1 + size n))\n                                                            modifyIORef' ref (Data.Map.insert x y)\n                                                            return y\n\n\n\n\n\n\n{-- Stochastic memoization for recursive functions.\n    Applying 'memoize' to a recursively defined function only memoizes at the\n    top-level: recursive calls are calls to the non-memoized function.\n    'memrec' is an alternative implementation which resolves recursion and\n    memoization at the same time, so that recursive calls are also memoized.\n--}\nmemrec :: Ord a => Show a => ((a -> b) -> (a -> Prob b)) -> Prob (a -> b)\nmemrec f =\n   Prob $ do\n    g <- get\n    let ( Tree _ gs, g2) = splitTree g\n    put g2\n    return $ unsafePerformIO $ do\n                  ref <- newIORef Data.Map.empty\n                  let memoized_fixpoint = \\x -> unsafePerformIO $ do\n                                m <- fmap (Data.Map.lookup x) (readIORef ref)\n                                case m of\n                                      Just y -> return y\n                                      Nothing -> do\n                                                  n <- readIORef ref\n                                                  let fix = f memoized_fixpoint\n                                                  let Prob k = fix x\n                                                  let (y, _) = runState k (gs !! (1 + size n))\n                                                  modifyIORef' ref (Data.Map.insert x y)\n                                                  return y\n                  return memoized_fixpoint\n", "meta": {"hexsha": "b33d4e5ac12e07dba9d413d3542e53404b08c972", "size": 7923, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Sam.hs", "max_stars_repo_name": "kai-pischke/ppl", "max_stars_repo_head_hexsha": "f98efe5ffd494a8f7955866a16bc25c5bb8bc835", "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/Sam.hs", "max_issues_repo_name": "kai-pischke/ppl", "max_issues_repo_head_hexsha": "f98efe5ffd494a8f7955866a16bc25c5bb8bc835", "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/Sam.hs", "max_forks_repo_name": "kai-pischke/ppl", "max_forks_repo_head_hexsha": "f98efe5ffd494a8f7955866a16bc25c5bb8bc835", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5115207373, "max_line_length": 112, "alphanum_fraction": 0.5759182128, "num_tokens": 1882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4603305592516979}}
{"text": "-- program: S.A.R.A.H. jam simulator\n-- author: Maur\u00edcio C. Antunes\n-- e-mail: mauricio.antunes@gmail.com\n-- license: public domain\n\nmodule Main where\n\nimport Control.Applicative\nimport Prelude\n\nimport Data.Maybe\nimport Graphics.UI.Gtk\nimport Graphics.Rendering.Cairo\nimport Control.Monad\nimport Data.IORef\nimport Data.List\nimport Data.Time\nimport Data.Complex\n\n-- Constants\n\naccelerator = 0.7*carSize :: Double\nbrake = 10*accelerator:: Double\ncarSize = 2*pi/59 :: Double\nresponseTime = 0.24 :: Double\ndrawSide = 5/2 :: Double\n\n-- A few conveniences\n\neventWindowSize = do\n    dr <- eventWindow\n    w <- liftIO $ drawWindowGetWidth dr\n    h <- liftIO $ drawWindowGetHeight dr\n    return $ if w*h > 1\n        then (fromIntegral w, fromIntegral h)\n        else (1,1)\n\neventPolarCoordinates = do\n    (w,h) <- eventWindowSize\n    (x,y) <- eventCoordinates\n    let (origX, origY) = (w/2, h/2)\n    let (scaleX, scaleY) = (drawSide/w, drawSide/h)\n    let (x',y') = (scaleX*(x-origX), scaleY*(y-origY))\n    let (radius,theta) = polar $ x' :+ y'\n    return $ (radius,theta)\n\ngetAndSet :: a -> IO (IO a, a -> IO ())\ngetAndSet a = do\n    ior <- newIORef a\n    let get = readIORef ior\n    let set = writeIORef ior\n    return (get,set)\n\ndiffTime :: UTCTime -> UTCTime -> Double\ndiffTime = (realToFrac .) . diffUTCTime\n\nmoveToLineTo :: Double -> Double\n -> Double -> Double -> Render ()\nmoveToLineTo a b c d = moveTo a b >> lineTo c d\n\n-- Car list handling\n\n-- Each car is represented by a pair of Doubles. The first\n-- Double is its position in a circular road, represented by\n-- an angle. The second is its angular velocity. The general\n-- idea behind the simulation is that in a list of cars each\n-- one will try to keep a safe speed to avoid a crash in the\n-- event of a sudden brake of the next car.\n\nnewCarList nCars = take nCars $ zip [0,2*pi/nCars'..] (repeat 0)\n    where nCars' = fromIntegral nCars\n\n-- This resizes car lists by copying or keeping those\n-- at lower speeds.\n\nnewCarListFromList nCars [] = newCarListFromList nCars [(0,0)]\nnewCarListFromList nCars list = sortBy ((. fst).(compare . fst)) $\n    take nCars $ cycle $ sortBy ((. snd).(compare . snd)) list\n\n-- Safe speed for car, given data from itself and the next\n-- and, possibly, a forced (by the user) jam. Speed changes\n-- are limited by accelerator and brake maxima.\n\nnewSpeed dt jam (p1,s1) (p2,s2) = min cv $ max bv $ ds - br\n    where\n        pd = (p2-p1-carSize) - responseTime*(s2-s1)\n        pj = maybe pd ((subtract $ carSize/2)\n         . (until (>0) (+2*pi)) . (subtract p1)) jam\n        dd = brake*(max 0 $ min pd pj)\n        br = brake*responseTime\n        ds = sqrt $ br^2 + 2*dd\n        cv = s1 + accelerator*dt\n        bv = s1 - brake*dt\n\n-- Update positions and speeds based on a timestep and maybe\n-- taking a forced congestion into account\n\nupdateCarList _ _ [] = []\nupdateCarList timestep jam list = zip newPositions' newSpeeds\n    where\n        fakeCar = (p+2*pi,s) where (p,s) = head list\n        newSpeeds = zipWith ns list (tail list ++ [fakeCar])\n            where ns = newSpeed timestep jam\n        newPositions = zipWith3 mean fsts snds newSpeeds\n            where\n                mean a b c = a + timestep*(b+c)/2\n                fsts = map fst list\n                snds = map snd list\n        newPositions' = map (subtract base) newPositions\n        base = (*(2*pi)) $ fromIntegral $ floor $ (/ (2*pi)) $\n            head newPositions\n\nabout = do\n    ad <- aboutDialogNew\n    set ad [ aboutDialogName := \"S.A.R.A.H.\"\n           , aboutDialogVersion := \"1.0\"\n           , aboutDialogAuthors := [\"Maur\u00edcio C. Antunes \"\n                                ++ \"<mauricio.antunes@gmail.com>\"]\n           , aboutDialogComments := \"Software Automation of \"\n                                ++ \"Road Automobile Headache\"]\n    dialogRun ad\n    widgetDestroy ad\n\nmain :: IO ()\nmain = do\n\n    initGUI\n\n    mainWindow <- windowNew\n    drawingArea <- drawingAreaNew\n\n    (getTimeStamp,setTimeStamp) <- getCurrentTime >>= getAndSet\n    (getCars,setCars) <- getAndSet $ newCarList 20\n    (getJam,setJam) <- getAndSet Nothing\n    (getTimeoutId,setTimeoutId) <- getAndSet Nothing\n\n    -- If 'resume' is called, 'step' will be called at small\n    -- timesteps to update car data. If 'pause' is called, 'step'\n    -- calls are stoped.  'resume' is called at program startup,\n    -- and then the pause button alternates 'resume' and 'pause'.\n\n    let step = do\n         time <- getCurrentTime\n         dt <- getTimeStamp >>= return . (diffTime time)\n         setTimeStamp time\n         liftM2 (updateCarList dt) getJam getCars >>= setCars\n    let pause = do\n         maybe (return ()) timeoutRemove =<< getTimeoutId\n         setTimeoutId Nothing\n    let resume = do\n         setTimeoutId . Just =<< flip timeoutAdd 33\n          (step >> widgetQueueDraw drawingArea >> return True)\n         getCurrentTime >>= setTimeStamp\n\n    -- The elements of the graphic interface are the set of\n    -- buttons, the scale to set the number of cars and the\n    -- car track. They are named as 'buttons', 'howMany' and\n    -- 'track'. Each of them contains other widgets inside, but\n    -- there's no reason to expose their names to the main IO.\n\n    buttons <- do\n\n        qr <- buttonNewFromStock stockClear\n        on qr buttonActivated $ do\n            (liftM length) getCars >>= setCars . newCarList\n            getCurrentTime >>= setTimeStamp\n            widgetQueueDraw drawingArea\n\n        qp <- toggleButtonNewWithLabel stockMediaPause\n        buttonSetUseStock qp True\n        on qp toggled $ do\n            p <- toggleButtonGetActive qp\n            case p of\n                True -> pause\n                False -> resume\n\n        qa <- buttonNewFromStock stockAbout\n        on qa buttonActivated $ about\n\n        qq <- buttonNewFromStock stockQuit\n        on qq buttonActivated (do\n                       widgetDestroy mainWindow\n                       mainQuit)\n\n        bb <- hButtonBoxNew\n        containerAdd bb qr\n        containerAdd bb qp\n        containerAdd bb qa\n        containerAdd bb qq\n        return bb\n\n    howMany <- do\n\n        sc <- vScaleNewWithRange 1 40 1\n        after sc valueChanged $ do\n            v <- liftM floor $ rangeGetValue sc\n            c <- getCars\n            setCars $ newCarListFromList v c\n            widgetQueueDraw drawingArea\n\n        scaleSetValuePos sc PosTop\n        scaleSetDigits sc 0\n--        rangeSetUpdatePolicy sc UpdateDiscontinuous\n        rangeSetValue sc =<< liftM (fromIntegral . length) getCars\n\n        al <- alignmentNew 0.5 0.5 0 1\n        alignmentSetPadding al 15 15 15 15\n        containerAdd al sc\n        return al\n\n    track <- do\n\n        let dr = drawingArea\n        widgetAddEvents dr [PointerMotionMask]\n\n        on dr motionNotifyEvent $ do\n            (r,t) <- eventPolarCoordinates\n            liftIO $ if (0.8<r && r<1.2)\n                then setJam (Just t)\n                else setJam Nothing\n            liftIO $ widgetQueueDraw dr\n            return True\n\n        on dr leaveNotifyEvent $ liftIO $\n            setJam Nothing >> return True\n\n        on dr draw $ do\n            w <- liftIO $ (fromIntegral <$> widgetGetAllocatedWidth dr)\n            h <- liftIO $ (fromIntegral <$> widgetGetAllocatedHeight dr)\n            jam <- liftIO getJam\n            cars <- liftIO getCars\n            translate (w/2) (h/2)\n            scale (w/drawSide) (h/drawSide)\n            road2render jam cars\n            -- return True\n\n        af <- aspectFrameNew 0.5 0.5 (Just 1)\n        frameSetShadowType af ShadowNone\n        containerAdd af dr\n        return af\n\n    -- 'layout' is a widget that contains all interface elements\n    -- properly arranged.\n\n    layout <- do\n        vb <- vBoxNew False 0\n        hb <- hBoxNew False 0\n        boxPackStart vb track PackGrow 0\n        boxPackStart vb buttons PackNatural 0\n        boxPackStart hb howMany PackNatural 0\n        boxPackStart hb vb PackGrow 0\n        return hb\n\n    set mainWindow [ windowTitle := \"S.A.R.A.H.\"\n                   , windowDefaultWidth := 400\n                   , windowDefaultHeight := 400 ]\n    on mainWindow objectDestroy mainQuit\n    containerAdd mainWindow layout\n    widgetShowAll mainWindow\n\n    resume\n\n    mainGUI\n\n-- As the name says, this takes road info, in the form of a\n-- possible jam and a list of cars, and make it into a Cairo\n-- render.  Road will have radius 1.\n\nroad2render :: Maybe Double -> [(Double,Double)] -> Render ()\nroad2render jam cars = do\n    newPath\n    setSourceRGB 0 0 0\n    drawRoad\n    when (isJust jam) drawJam\n    setSourceRGBA 0 0 0 0.55\n    let cars' = map fst cars\n    let rotations = zipWith subtract (0:cars') cars'\n    sequence_ $ map ((>> drawCar) . rotate) rotations\n where\n    drawRoad = setLineWidth 0.01 >> setDash [2*pi/34,2*pi/34]\n     (pi/34) >> arc 0.0 0.0 1.0 0.0 (2*pi) >> stroke\n    drawJam = setLineWidth 0.005 >> setDash [0.03,0.02] 0.04 >>\n     save >> rotate (fromJust jam) >> moveToLineTo 0.8 0 1.2\n     0 >> stroke >> setDash [] 0 >> moveToLineTo 0.8 (-0.015)\n     0.8 0.015 >> moveToLineTo 1.2 (-0.015) 1.2 0.015 >> stroke\n     >> restore\n    drawCar = arc 1 0 (carSize/2) 0 (2*pi) >> fill\n", "meta": {"hexsha": "c325d13d33da88daa238d61208932da40b319c85", "size": 9160, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": ".cabal-sandbox/x86_64-windows-ghc-7.8.3/gtk3-0.13.8/carsim/CarSim.hs", "max_stars_repo_name": "SwiftsNamesake/Leopardy", "max_stars_repo_head_hexsha": "27de74fe64fa3b131c35b8a6a6ddfb2d60db658b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": ".cabal-sandbox/x86_64-windows-ghc-7.8.3/gtk3-0.13.8/carsim/CarSim.hs", "max_issues_repo_name": "SwiftsNamesake/Leopardy", "max_issues_repo_head_hexsha": "27de74fe64fa3b131c35b8a6a6ddfb2d60db658b", "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": ".cabal-sandbox/x86_64-windows-ghc-7.8.3/gtk3-0.13.8/carsim/CarSim.hs", "max_forks_repo_name": "SwiftsNamesake/Leopardy", "max_forks_repo_head_hexsha": "27de74fe64fa3b131c35b8a6a6ddfb2d60db658b", "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": 31.8055555556, "max_line_length": 72, "alphanum_fraction": 0.6136462882, "num_tokens": 2504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4602446497797666}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n\n-- |\n-- Module      :  Test.Opcount\n-- Copyright   :  (c) 2016-2020 Drexel University\n-- License     :  BSD-style\n-- Maintainer  :  mainland@drexel.edu\n\nmodule Test.Opcount (\n    opCountTests,\n    splitRadixOpcountTests,\n    difOpcountTests,\n    opcountRegressionTests\n  ) where\n\nimport Control.Monad (mzero)\nimport Data.Complex\nimport Data.Typeable (Typeable)\nimport Test.HUnit (Assertion,\n                   (@?=),\n                   assertEqual)\nimport Test.Hspec\n\nimport qualified Data.FlagSet as FS\n\nimport Spiral (Config(..))\nimport Spiral.Config\nimport Spiral.Driver\nimport Spiral.Exp\nimport Spiral.FFT.CooleyTukey\nimport Spiral.Monad\nimport Spiral.OpCount\nimport Spiral.SPL\nimport Spiral.SPL.Run\nimport Spiral.Search\nimport Spiral.Search.FFTBreakdowns\nimport Spiral.Search.OpCount\n\nimport Test.Instances ()\n\nopCountTests :: Spec\nopCountTests =\n    describe \"Opcount\" $ do\n    splitRadixOpcountTests\n    difOpcountTests\n\n-- The number of multiplies and additions for spit radix decomposition of size n\n-- when using three-multiply form of complex multiply. Taken from Table II of\n-- Heideman and Burrus.\nsplitRadixOpcounts :: [(Int, Int, Int)]\nsplitRadixOpcounts = [ (4,    0,     16)\n                     , (8,    4,     52)\n                     , (16,   20,    148)\n                     , (32,   68,    388)\n                     , (64,   196,   964)\n                     , (128,  516,   2308)\n                     , (256,  1284,  5380)\n                     --, (512,  3076,  12292)\n                     --, (1024, 7172,  27652)\n                     --, (2048, 16388, 61444)\n                     --, (4096, 36868, 135172)\n                     ]\n\nsplitRadixOpcountTests :: Spec\nsplitRadixOpcountTests =\n    describe \"Split radix opcounts\" $\n    sequence_ [mkTest n (muls + adds) | (n, muls, adds) <- splitRadixOpcounts]\n  where\n    mkTest :: Int -> Int -> Spec\n    mkTest n nops =\n      mkOpCountTest (\"Split radix \" ++ show n) fs nops (runSearch () f (DFT n))\n      where\n        fs :: [DynFlag]\n        fs = [ StoreIntermediate\n             , SplitComplex\n             , CSE\n             , Rewrite\n             ]\n\n    f :: (Typeable a, Typed a, MonadSpiral m)\n      => SPL (Exp a)\n      ->\u00a0S s m (SPL (Exp a))\n    f (F n w) = splitRadixBreakdown n w\n    f _       = mzero\n\n-- The DIF form should have the same operation count as split radix when the\n-- DifRewrite flag is enabled.\ndifOpcountTests :: Spec\ndifOpcountTests =\n    describe \"DIF opcounts\" $\n    sequence_ [mkTest n (muls + adds) | (n, muls, adds) <- splitRadixOpcounts]\n  where\n    mkTest :: Int -> Int -> Spec\n    mkTest n nops =\n      mkOpCountTest (\"DIF \" ++ show n) fs nops (return $ dif n)\n      where\n        fs :: [DynFlag]\n        fs = [ StoreIntermediate\n             , SplitComplex\n             , CSE\n             , Rewrite\n             , DifRewrite\n             ]\n\nmkOpCountTest :: String\n              -> [DynFlag]\n              -> Int\n              -> Spiral (SPL (Exp (Complex Double)))\n              -> Spec\nmkOpCountTest desc fs nops gen =\n    it desc $ do\n    ops <- runSpiralWith mempty $ withOpcountFlags fs $ do\n           f   <- gen\n           toProgram \"f\" (Re f) >>= countProgramOps\n    return $ mulOps ops + addOps ops @?= nops\n\nwithOpcountFlags :: MonadConfig m => [DynFlag] -> m a -> m a\nwithOpcountFlags fs =\n    localConfig $ \\env -> env { dynFlags  = FS.fromList fs\n                              , maxUnroll = 256\n                              }\n\nopcountRegressionTests :: Int -> Spec\nopcountRegressionTests max_size = do\n    text <- runIO $ readFile rEGRESSION_FILE\n    let opcounts = (map parseCSV . drop 1 . lines) text\n    mapM_ test [(n,totalOps,mulOps,addOps) | [n,totalOps,mulOps,addOps] <- opcounts, n <= max_size]\n  where\n    rEGRESSION_FILE :: FilePath\n    rEGRESSION_FILE = \"benchmark/data/search-opcount.csv\"\n\n    parseCSV :: String -> [Int]\n    parseCSV = map read . splitOn (== ',')\n\n    test :: (Int,Int,Int,Int) -> Spec\n    test (n, allOps0, mulOps0, addOps0) = it (\"Regression(\" ++ show n ++ \")\") $ do\n        ops <- runSpiralWith config $ do\n               e    <- searchOpCount (Re (DFT n) :: SPL (Exp Double))\n               prog <- toProgram \"dft\" e\n               countProgramOps prog\n        return $ checkOps (allOps ops, mulOps ops, addOps ops) (allOps0, mulOps0, addOps0)\n\n    checkOps :: (Int, Int, Int) -> (Int, Int, Int) -> Assertion\n    checkOps ops@(total, _, _) ops'@(total', _, _)\n      | total < total' = assertEqual \"IMPROVED!\" ops' ops\n      | otherwise      = ops @?= ops'\n\n    config :: Config\n    config = mempty { dynFlags  = FS.fromList fs\n                    , maxUnroll = 256\n                    }\n\n    fs :: [DynFlag]\n    fs = [ StoreIntermediate\n         , SplitComplex\n         , CSE\n         , Rewrite\n         ]\n\nsplitOn :: (Char -> Bool) -> String -> [String]\nsplitOn p s = case dropWhile p s of\n                  \"\" -> []\n                  s' -> w : splitOn p s''\n                        where (w, s'') = break p s'\n", "meta": {"hexsha": "680e379a20f2539d78b64614bacdd3cd339812e7", "size": 5161, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/test/Test/Opcount.hs", "max_stars_repo_name": "mainland/hspiral", "max_stars_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-05-21T21:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T04:48:25.000Z", "max_issues_repo_path": "src/test/Test/Opcount.hs", "max_issues_repo_name": "mainland/hspiral", "max_issues_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "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/test/Test/Opcount.hs", "max_forks_repo_name": "mainland/hspiral", "max_forks_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3588235294, "max_line_length": 99, "alphanum_fraction": 0.5580313893, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6477982179521105, "lm_q1q2_score": 0.45930133135993234}}
{"text": "{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}\n{-# LANGUAGE FlexibleContexts #-}\nmodule Neural.Network\n  ( Network(..)\n  , weights\n  , biases\n  , newNetwork\n  , randomNetwork\n  , feedforwards\n  , feedforward\n  )\nwhere\n\nimport           System.Random\nimport           Foreign.Storable               ( Storable )\nimport           Control.Monad.State\nimport qualified Data.Semigroup                as Semigroup\nimport           Numeric.LinearAlgebra\nimport           GHC.Generics                   ( Generic )\nimport           Control.DeepSeq\n\nimport           Neural.Activation              ( ActivationFunction(..) )\nimport           Neural.Layer            hiding ( weights\n                                                , biases\n                                                )\nimport qualified Neural.Layer                  as Layer\n\n-- | Simple feed-forward network.\nnewtype Network a = Network [Layer a]\n    deriving (Show, Generic, NFData)\n\n-- | Get the weights of the network.\nweights :: Network a -> [Matrix a]\nweights (Network layers) = map Layer.weights layers\n\n-- | Get the biases of the network.\nbiases :: Network a -> [Vector a]\nbiases (Network layers) = map Layer.biases layers\n\n-- | Construct a new network from a list of weigth matricws and bias vectors.\nnewNetwork :: [Matrix a] -> [Vector a] -> Network a\nnewNetwork ws bs = Network $ zipWith newLayer ws bs\n\n-- | Construct a new random network given the sizes of the layers\n-- Each bias and weight is given a random value normally\n-- distributed with mean 0 and standard deviation 1.\nrandomNetwork\n  :: (RandomGen g, Random a, Element a, Floating a)\n  => [Int]    -- ^ The sizes of the layers\n  -> State g (Network a)\nrandomNetwork sizes = do\n  let sizes' = zip (init sizes) (tail sizes)\n  layers <- mapM (uncurry randomLayer) sizes'\n  return $ Network layers\n\n-- | Propagate an input through the network and return every intermediate\n-- activation and weighted input along the way.\nfeedforwards\n  :: (Numeric a, Num (Vector a))\n  => ActivationFunction a   -- ^ The activation function\n  -> Vector a               -- ^ The network input\n  -> Network a              -- ^ The network\n  -> [(Vector a, Vector a)] -- ^ The activations of all the layers\nfeedforwards \u03c3 x (Network layers) = tail $ scanl (feed \u03c3 . fst) (x, x) layers\n\n-- | Propagate an input through the network\n-- and return the activation and weighted input of the last layer.\nfeedforward\n  :: (Numeric a, Num (Vector a))\n  => ActivationFunction a  -- ^ The activation function\n  -> Vector a              -- ^ The network input\n  -> Network a             -- ^ The network\n  -> (Vector a, Vector a)  -- ^ The activations of the last layer\nfeedforward \u03c3 x = last . feedforwards \u03c3 x\n", "meta": {"hexsha": "60841af7f87d725805be01cf720b78ff3115fa8e", "size": 2711, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Neural/Network.hs", "max_stars_repo_name": "cornelius-sevald/nnhd", "max_stars_repo_head_hexsha": "b952830829d81f2ec8c4050128abceb1e6c15b48", "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/Neural/Network.hs", "max_issues_repo_name": "cornelius-sevald/nnhd", "max_issues_repo_head_hexsha": "b952830829d81f2ec8c4050128abceb1e6c15b48", "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/Neural/Network.hs", "max_forks_repo_name": "cornelius-sevald/nnhd", "max_forks_repo_head_hexsha": "b952830829d81f2ec8c4050128abceb1e6c15b48", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1466666667, "max_line_length": 77, "alphanum_fraction": 0.6281814828, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4590503908847137}}
{"text": "{-# LANGUAGE BangPatterns, DeriveDataTypeable, RecordWildCards #-}\n-- |\n-- Module      : Criterion.Analysis\n-- Copyright   : (c) 2009-2014 Bryan O'Sullivan\n--\n-- License     : BSD-style\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : GHC\n--\n-- Analysis code for benchmarks.\n\nmodule Criterion.Analysis\n    (\n      Outliers(..)\n    , OutlierEffect(..)\n    , OutlierVariance(..)\n    , SampleAnalysis(..)\n    , analyseSample\n    , scale\n    , analyseMean\n    , countOutliers\n    , classifyOutliers\n    , noteOutliers\n    , outlierVariance\n    , resolveAccessors\n    , validateAccessors\n    , regress\n    ) where\n\n-- Temporary: to support pre-AMP GHC 7.8.4:\nimport Data.Monoid \n\nimport Control.Arrow (second)\nimport Control.Monad (unless, when)\nimport Control.Monad.Reader (ask)\nimport Control.Monad.Trans\nimport Control.Monad.Trans.Except\nimport Criterion.IO.Printf (note, prolix)\nimport Criterion.Measurement (secs, threshold)\nimport Criterion.Monad (Criterion, getGen, getOverhead)\nimport Criterion.Types\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Statistics.Function (sort)\nimport Statistics.Quantile (weightedAvg)\nimport Statistics.Regression (bootstrapRegress, olsRegress)\nimport Statistics.Resampling (resample)\nimport Statistics.Sample (mean)\nimport Statistics.Sample.KernelDensity (kde)\nimport Statistics.Types (Estimator(..), Sample)\nimport System.Random.MWC (GenIO)\nimport qualified Data.List as List\nimport qualified Data.Map as Map\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\nimport qualified Statistics.Resampling.Bootstrap as B\nimport Prelude\n\n-- | Classify outliers in a data set, using the boxplot technique.\nclassifyOutliers :: Sample -> Outliers\nclassifyOutliers sa = U.foldl' ((. outlier) . mappend) mempty ssa\n    where outlier e = Outliers {\n                        samplesSeen = 1\n                      , lowSevere = if e <= loS && e < hiM then 1 else 0\n                      , lowMild = if e > loS && e <= loM then 1 else 0\n                      , highMild = if e >= hiM && e < hiS then 1 else 0\n                      , highSevere = if e >= hiS && e > loM then 1 else 0\n                      }\n          !loS = q1 - (iqr * 3)\n          !loM = q1 - (iqr * 1.5)\n          !hiM = q3 + (iqr * 1.5)\n          !hiS = q3 + (iqr * 3)\n          q1   = weightedAvg 1 4 ssa\n          q3   = weightedAvg 3 4 ssa\n          ssa  = sort sa\n          iqr  = q3 - q1\n\n-- | Compute the extent to which outliers in the sample data affect\n-- the sample mean and standard deviation.\noutlierVariance :: B.Estimate  -- ^ Bootstrap estimate of sample mean.\n                -> B.Estimate  -- ^ Bootstrap estimate of sample\n                               --   standard deviation.\n                -> Double      -- ^ Number of original iterations.\n                -> OutlierVariance\noutlierVariance \u00b5 \u03c3 a = OutlierVariance effect desc varOutMin\n  where\n    ( effect, desc ) | varOutMin < 0.01 = (Unaffected, \"no\")\n                     | varOutMin < 0.1  = (Slight,     \"slight\")\n                     | varOutMin < 0.5  = (Moderate,   \"moderate\")\n                     | otherwise        = (Severe,     \"severe\")\n    varOutMin = (minBy varOut 1 (minBy cMax 0 \u00b5gMin)) / \u03c3b2\n    varOut c  = (ac / a) * (\u03c3b2 - ac * \u03c3g2) where ac = a - c\n    \u03c3b        = B.estPoint \u03c3\n    \u00b5a        = B.estPoint \u00b5 / a\n    \u00b5gMin     = \u00b5a / 2\n    \u03c3g        = min (\u00b5gMin / 4) (\u03c3b / sqrt a)\n    \u03c3g2       = \u03c3g * \u03c3g\n    \u03c3b2       = \u03c3b * \u03c3b\n    minBy f q r = min (f q) (f r)\n    cMax x    = fromIntegral (floor (-2 * k0 / (k1 + sqrt det)) :: Int)\n      where\n        k1    = \u03c3b2 - a * \u03c3g2 + ad\n        k0    = -a * ad\n        ad    = a * d\n        d     = k * k where k = \u00b5a - x\n        det   = k1 * k1 - 4 * \u03c3g2 * k0\n\n-- | Count the total number of outliers in a sample.\ncountOutliers :: Outliers -> Int64\ncountOutliers (Outliers _ a b c d) = a + b + c + d\n{-# INLINE countOutliers #-}\n\n-- | Display the mean of a 'Sample', and characterise the outliers\n-- present in the sample.\nanalyseMean :: Sample\n            -> Int              -- ^ Number of iterations used to\n                                -- compute the sample.\n            -> Criterion Double\nanalyseMean a iters = do\n  let \u00b5 = mean a\n  _ <- note \"mean is %s (%d iterations)\\n\" (secs \u00b5) iters\n  noteOutliers . classifyOutliers $ a\n  return \u00b5\n\n-- | Multiply the 'Estimate's in an analysis by the given value, using\n-- 'B.scale'.\nscale :: Double                 -- ^ Value to multiply by.\n      -> SampleAnalysis -> SampleAnalysis\nscale f s@SampleAnalysis{..} = s {\n                                 anMean = B.scale f anMean\n                               , anStdDev = B.scale f anStdDev\n                               }\n\n-- | Perform an analysis of a measurement.\nanalyseSample :: Int            -- ^ Experiment number.\n              -> String         -- ^ Experiment name.\n              -> V.Vector Measured -- ^ Sample data.\n              -> ExceptT String Criterion Report\nanalyseSample i name meas = do\n  Config{..} <- ask\n  overhead <- lift getOverhead\n  let ests      = [Mean,StdDev]\n      -- The use of filter here throws away very-low-quality\n      -- measurements when bootstrapping the mean and standard\n      -- deviations.  Without this, the numbers look nonsensical when\n      -- very brief actions are measured.\n      stime     = measure (measTime . rescale) .\n                  G.filter ((>= threshold) . measTime) . G.map fixTime .\n                  G.tail $ meas\n      fixTime m = m { measTime = measTime m - overhead / 2 }\n      n         = G.length meas\n      s         = G.length stime\n  _ <- lift $ prolix \"bootstrapping with %d of %d samples (%d%%)\\n\"\n              s n ((s * 100) `quot` n)\n  gen <- lift getGen\n  rs <- mapM (\\(ps,r) -> regress gen ps r meas) $\n        (([\"iters\"],\"time\"):regressions)\n  resamps <- liftIO $ resample gen ests resamples stime\n  let [estMean,estStdDev] = B.bootstrapBCA confInterval stime ests resamps\n      ov = outlierVariance estMean estStdDev (fromIntegral n)\n      an = SampleAnalysis {\n               anRegress    = rs\n             , anOverhead   = overhead\n             , anMean       = estMean\n             , anStdDev     = estStdDev\n             , anOutlierVar = ov\n             }\n  return Report {\n      reportNumber   = i\n    , reportName     = name\n    , reportKeys     = measureKeys\n    , reportMeasured = meas\n    , reportAnalysis = an\n    , reportOutliers = classifyOutliers stime\n    , reportKDEs     = [uncurry (KDE \"time\") (kde 128 stime)]\n    }\n\n-- | Regress the given predictors against the responder.\n--\n-- Errors may be returned under various circumstances, such as invalid\n-- names or lack of needed data.\n--\n-- See 'olsRegress' for details of the regression performed.\nregress :: GenIO\n        -> [String]             -- ^ Predictor names.\n        -> String               -- ^ Responder name.\n        -> V.Vector Measured\n        -> ExceptT String Criterion Regression\nregress gen predNames respName meas = do\n  when (G.null meas) $\n    throwE \"no measurements\"\n  accs <- ExceptT . return $ validateAccessors predNames respName\n  let unmeasured = [n | (n, Nothing) <- map (second ($ G.head meas)) accs]\n  unless (null unmeasured) $\n    throwE $ \"no data available for \" ++ renderNames unmeasured\n  let (r:ps)      = map ((`measure` meas) . (fromJust .) . snd) accs\n  Config{..} <- ask\n  (coeffs,r2) <- liftIO $\n                 bootstrapRegress gen resamples confInterval olsRegress ps r\n  return Regression {\n      regResponder = respName\n    , regCoeffs    = Map.fromList (zip (predNames ++ [\"y\"]) (G.toList coeffs))\n    , regRSquare   = r2\n    }\n\nsingleton :: [a] -> Bool\nsingleton [_] = True\nsingleton _   = False\n\n-- | Given a list of accessor names (see 'measureKeys'), return either\n-- a mapping from accessor name to function or an error message if\n-- any names are wrong.\nresolveAccessors :: [String]\n                 -> Either String [(String, Measured -> Maybe Double)]\nresolveAccessors names =\n  case unresolved of\n    [] -> Right [(n, a) | (n, Just (a,_)) <- accessors]\n    _  -> Left $ \"unknown metric \" ++ renderNames unresolved\n  where\n    unresolved = [n | (n, Nothing) <- accessors]\n    accessors = flip map names $ \\n -> (n, Map.lookup n measureAccessors)\n\n-- | Given predictor and responder names, do some basic validation,\n-- then hand back the relevant accessors.\nvalidateAccessors :: [String]   -- ^ Predictor names.\n                  -> String     -- ^ Responder name.\n                  -> Either String [(String, Measured -> Maybe Double)]\nvalidateAccessors predNames respName = do\n  when (null predNames) $\n    Left \"no predictors specified\"\n  let names = respName:predNames\n      dups = map head . filter (not . singleton) .\n             List.group . List.sort $ names\n  unless (null dups) $\n    Left $ \"duplicated metric \" ++ renderNames dups\n  resolveAccessors names\n\nrenderNames :: [String] -> String\nrenderNames = List.intercalate \", \" . map show\n\n-- | Display a report of the 'Outliers' present in a 'Sample'.\nnoteOutliers :: Outliers -> Criterion ()\nnoteOutliers o = do\n  let frac n = (100::Double) * fromIntegral n / fromIntegral (samplesSeen o)\n      check :: Int64 -> Double -> String -> Criterion ()\n      check k t d = when (frac k > t) $\n                    note \"  %d (%.1g%%) %s\\n\" k (frac k) d\n      outCount = countOutliers o\n  when (outCount > 0) $ do\n    _ <- note \"found %d outliers among %d samples (%.1g%%)\\n\"\n         outCount (samplesSeen o) (frac outCount)\n    check (lowSevere o) 0 \"low severe\"\n    check (lowMild o) 1 \"low mild\"\n    check (highMild o) 1 \"high mild\"\n    check (highSevere o) 0 \"high severe\"\n", "meta": {"hexsha": "eb1adfa735fd501809ab1c356cde831e089d810e", "size": 9688, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Criterion/Analysis.hs", "max_stars_repo_name": "Shimuuar/criterion", "max_stars_repo_head_hexsha": "fcc27f0f2d2046019de9d783f0a3ce6f65e44357", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Criterion/Analysis.hs", "max_issues_repo_name": "Shimuuar/criterion", "max_issues_repo_head_hexsha": "fcc27f0f2d2046019de9d783f0a3ce6f65e44357", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Criterion/Analysis.hs", "max_forks_repo_name": "Shimuuar/criterion", "max_forks_repo_head_hexsha": "fcc27f0f2d2046019de9d783f0a3ce6f65e44357", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5503875969, "max_line_length": 78, "alphanum_fraction": 0.5951692816, "num_tokens": 2641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4590503811543571}}
{"text": "{-# LANGUAGE NamedFieldPuns, TemplateHaskell #-}\n\nmodule School.Train.Test.ForwardPass\n( forwardPassTest ) where\n\nimport Conduit ((.|), yield, liftIO, sinkList, await)\nimport Data.Either (isLeft)\nimport Numeric.LinearAlgebra (R)\nimport School.TestUtils (doCost, fromRight, randomAffineParams, randomMatrix, testState, weight1)\nimport School.Train.AppTrain (AppTrain)\nimport School.Train.ForwardPass\nimport School.Train.TrainState (TrainState(..), def)\nimport School.Types.PingPong (pingPongSingleton, reversePingPong, toPingPong)\nimport School.Types.Slinky (Slinky(..))\nimport School.Unit.Affine (affine)\nimport School.Unit.CostFunction (CostFunction)\nimport School.Unit.RecLin (recLin)\nimport School.Unit.Unit (Unit(..))\nimport School.Unit.UnitActivation (UnitActivation(..))\nimport School.Unit.UnitBackward (BackwardStack)\nimport School.Unit.UnitParams (UnitParams(..))\nimport Test.Tasty (TestTree)\nimport Test.Tasty.QuickCheck hiding ((><))\nimport Test.Tasty.TH\nimport Test.QuickCheck.Monadic (assert, monadicIO)\n\nweight :: CostFunction R (AppTrain R)\nweight = weight1\n\nprop_no_units :: Property\nprop_no_units = monadicIO $ do\n  let forward = forwardPass [] weight\n  let source = yield ([], SNil)\n  let pass = source .| forward .| sinkList\n  result <- testState pass def\n  assert $ isLeft result\n\nprop_single_recLin :: (Positive Int) -> (Positive Int) -> Property\nprop_single_recLin (Positive bSize) (Positive fSize) = monadicIO $ do\n  let forward = forwardPass [recLin] weight\n  input <- liftIO $ BatchActivation <$> (randomMatrix bSize fSize)\n  let source = yield ([input], SNil)\n  let pass = source .| forward .| await\n  result <- testState pass def\n  let out = apply recLin EmptyParams input\n  let (cost, grad) = doCost weight out SNil\n  let bParams = reversePingPong . paramList $ def\n  let state = def { paramList = bParams }\n  let stack = ([input], grad, cost)\n  let check = Right $ (Just stack, state) :: Either String (Maybe (BackwardStack R), TrainState R)\n  assert $ result == check\n\nprop_aff_rl_aff_rl :: (Positive Int) -> (Positive Int) -> (Positive Int) -> (Positive Int) -> Property\nprop_aff_rl_aff_rl (Positive b) (Positive f) (Positive h) (Positive o) = monadicIO $ do\n  let units = [affine, recLin, affine, recLin]\n  let forward = forwardPass units weight\n  input <- liftIO $ BatchActivation <$> (randomMatrix b f)\n  let source = yield ([input], SNil)\n  let pass = source .| forward .| await\n  params1 <- liftIO $ randomAffineParams f h\n  params2 <- liftIO $ randomAffineParams h o\n  let allParams = toPingPong [ params1\n                             , EmptyParams\n                             , params2\n                             , EmptyParams\n                             ]\n  let paramList = fromRight (pingPongSingleton EmptyParams) allParams\n  let initState = def { paramList }\n  result <- testState pass initState\n  let out1 = apply affine params1 input\n  let out2 = apply recLin EmptyParams out1\n  let out3 = apply affine params2 out2\n  let out4 = apply recLin EmptyParams out3\n  let (cost, grad) = doCost weight out4 SNil\n  let bParams = reversePingPong paramList\n  let state = def { paramList = bParams }\n  let stack = ([out3, out2, out1, input], grad, cost)\n  let check = Right $ (Just stack, state) :: Either String (Maybe (BackwardStack R), TrainState R)\n  assert $ result == check\n\nforwardPassTest:: TestTree\nforwardPassTest = $(testGroupGenerator)\n", "meta": {"hexsha": "cfd649f0d7549731b9b61202b1f21871064b5828", "size": 3383, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/School/Train/Test/ForwardPass.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/School/Train/Test/ForwardPass.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/School/Train/Test/ForwardPass.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7590361446, "max_line_length": 102, "alphanum_fraction": 0.7117942654, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.4588378547343551}}
{"text": "{-# LANGUAGE CPP                                      #-}\n{-# LANGUAGE DataKinds                                #-}\n{-# LANGUAGE DeriveFoldable                           #-}\n{-# LANGUAGE DeriveFunctor                            #-}\n{-# LANGUAGE FlexibleContexts                         #-}\n{-# LANGUAGE FlexibleInstances                        #-}\n{-# LANGUAGE GADTs                                    #-}\n{-# LANGUAGE LambdaCase                               #-}\n{-# LANGUAGE OverloadedStrings                        #-}\n{-# LANGUAGE PatternSynonyms                          #-}\n{-# LANGUAGE RecordWildCards                          #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE StandaloneDeriving                       #-}\n{-# LANGUAGE TupleSections                            #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# LANGUAGE TypeSynonymInstances                     #-}\n{-# LANGUAGE ViewPatterns                             #-}\n{-# OPTIONS_GHC -fno-warn-orphans                     #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n-- | Hamilton example suite\n--\n-- See: https://github.com/mstksg/hamilton#example-app-runner\n--\n-- Or just run with:\n--\n-- > $ hamilton-examples --help\n-- > $ hamilton-examples [EXAMPLE] --help\n--\n\nimport           Control.Concurrent\nimport           Control.Monad\nimport           Data.Bifunctor\nimport           Data.Finite\nimport           Data.Foldable\nimport           Data.IORef\nimport           Data.List\nimport           Data.Semigroup                      ((<>))\nimport           GHC.TypeLits\nimport           Graphics.Vty hiding                 (Config, (<|>))\nimport           Numeric.Hamilton\nimport           Numeric.LinearAlgebra.Static hiding (dim, (<>))\nimport           Numeric.LinearAlgebra.Static.Vector\nimport           Options.Applicative\nimport           System.Exit\nimport           Text.Printf\nimport           Text.Read\nimport qualified Data.List.NonEmpty                  as NE\nimport qualified Data.Map.Strict                     as M\nimport qualified Data.Vector                         as VV\nimport qualified Data.Vector.Sized                   as V\nimport qualified Data.Vector.Storable.Sized          as VS\nimport qualified Text.PrettyPrint.ANSI.Leijen        as PP\n\ndata SysExample where\n    SE :: (KnownNat m, KnownNat n)\n       => { seName   :: String\n          , seCoords :: V.Vector n String\n          , seSystem :: System m n\n          , seDraw   :: R m -> [V2 Double]\n          , seInit   :: Phase n\n          }\n       -> SysExample\n\npendulum :: Double -> Double -> SysExample\npendulum \u03b80 \u03c90 = SE \"Single pendulum\" (V1 \"\u03b8\") s f (toPhase s c0)\n  where\n    s :: System 2 1\n    s = mkSystem' (vec2 1 1                             )     -- masses\n                  (\\(V1 \u03b8)   -> V2 (sin \u03b8) (0.5 - cos \u03b8))     -- coordinates\n                  (\\(V2 _ y) -> y                       )     -- potential\n    f :: R 2 -> [V2 Double]\n    f xs = [grVec xs]\n    c0 :: Config 1\n    c0 = Cfg (konst \u03b80 :: R 1) (konst \u03c90 :: R 1)\n\ndoublePendulum :: Double -> Double -> SysExample\ndoublePendulum m1 m2 = SE \"Double pendulum\" (V2 \"\u03b81\" \"\u03b82\") s f (toPhase s c0)\n  where\n    s :: System 4 2\n    s = mkSystem' (vec4 m1 m1 m2 m2)     -- masses\n                  (\\(V2 \u03b81 \u03b82)     -> V4 (sin \u03b81)            (1 - cos \u03b81)\n                                         (sin \u03b81 + sin \u03b82/2) (1 - cos \u03b81 - cos \u03b82/2)\n                  )                      -- coordinates\n                  (\\(V4 _ y1 _ y2) -> 5 * (realToFrac m1 * y1 + realToFrac m2 * y2))\n                                         -- potential\n    f :: R 4 -> [V2 Double]\n    f (split->(xs,ys))= grVec <$> [xs, ys]\n    c0 :: Config 2\n    c0 = Cfg (vec2 (pi/2) 0) (vec2 0 0)\n\nroom :: Double -> SysExample\nroom \u03b8 = SE \"Room\" (V2 \"x\" \"y\") s f (toPhase s c0)\n  where\n    s :: System 2 2\n    s = mkSystem (vec2 1 1)         -- masses\n                 id                 -- coordinates\n                 (\\(V2 x y) -> sum [ 2 * y                      -- gravity\n                                   , 1 - logistic (-1) 10 0.1 y  -- bottom wall\n                                   ,     logistic 1 10 0.1 y     -- top wall\n                                   , 1 - logistic (-2) 10 0.1 x  -- left wall\n                                   ,     logistic 2 10 0.1 x     -- right wall\n                                   ]\n                 )                  -- potential\n    f :: R 2 -> [V2 Double]\n    f xs = [grVec xs]\n    c0 :: Config 2\n    c0 = Cfg (vec2 (-1) 0.25) (vec2 (cos \u03b8) (sin \u03b8))\n\ntwoBody :: Double -> Double -> Double -> SysExample\ntwoBody m1 m2 \u03c90 = SE \"Two-Body\" (V2 \"r\" \"\u03b8\") s f (toPhase s c0)\n  where\n    mT :: Double\n    mT = m1 + m2\n    s :: System 4 2\n    s = mkSystem (vec4 m1 m1 m2 m2) -- masses\n                 -- positions are calculated assuming (0,0) is the center\n                 -- of mass\n                 (\\(V2 r \u03b8) -> let r1 = r * realToFrac (-m2 / mT)\n                                   r2 = r * realToFrac (m1 / mT)\n                               in  V4 (r1 * cos \u03b8) (r1 * sin \u03b8)\n                                      (r2 * cos \u03b8) (r2 * sin \u03b8)\n                 )                 -- coordinates\n                 (\\(V2 r _) -> - realToFrac (m1 * m2) / r)  -- potential\n    f :: R 4 -> [V2 Double]\n    f (split->(xs,ys))= grVec <$> [xs, ys]\n    c0 :: Config 2\n    c0 = Cfg (vec2 2 0) (vec2 0 \u03c90)\n\nspring\n    :: Double -> Double -> Double -> Double -> SysExample\nspring mB mW k x0 = SE \"Spring hanging from block\" (V3 \"r\" \"x\" \"\u03b8\") s f (toPhase s c0)\n  where\n    s :: System 3 3\n    s = mkSystem (vec3 mB mW mW)                                                  -- masses\n                 (\\(V3 r x \u03b8)  -> V3 r (r + (1 + x) * sin \u03b8) ((1 + x) * (-cos \u03b8))) -- coordinates\n                 (\\(V3 r x \u03b8) -> realToFrac k * x**2 / 2        -- spring\n                              + (1 - logistic (-1.5) 25 0.1 r)  -- left rail wall\n                              + (    logistic   1.5  25 0.1 r)  -- right rail wall\n                              + realToFrac mB * ((1 + x) * (-cos \u03b8))  -- gravity\n                 )\n    f :: R 3 -> [V2 Double]\n    f (headTail->(b,w)) = [V2 b 1, V2 0 1 + grVec w]\n    c0 :: Config 3\n    c0 = Cfg (vec3 0 x0 0) (vec3 1 0 (-0.5))\n\nbezier\n    :: forall n. KnownNat (1 + n)\n    => V.Vector (1 + n) (V2 Double)\n    -> SysExample\nbezier ps = SE \"Bezier\" (V1 \"t\") s f (toPhase s c0)\n  where\n    s :: System 2 1\n    s = mkSystem (vec2 1 1)                                             -- masses\n                 (\\(V1 t) -> bezierCurve (fmap realToFrac <$> ps) t)    -- coordinates\n                 (\\(V1 t) -> (1 - logistic 0 5 0.05 t)           -- left wall\n                           +      logistic 1 5 0.05 t            -- right wall\n                 )\n    f :: R 2 -> [V2 Double]\n    f xs = [grVec xs]\n    c0 :: Config 1\n    c0 = Cfg (0.5 :: R 1) (0.25 :: R 1)\n\n\ndata ExampleOpts = EO { eoChoice :: SysExampleChoice }\n\ndata SysExampleChoice =\n        SECDoublePend Double Double\n      | SECPend Double Double\n      | SECRoom Double\n      | SECTwoBody Double Double Double\n      | SECSpring Double Double Double Double\n      | SECBezier (NE.NonEmpty (V2 Double))\n\nparseEO :: Parser ExampleOpts\nparseEO = EO <$> (parseSEC <|> pure (SECDoublePend 1 1))\n\nparseSEC :: Parser SysExampleChoice\nparseSEC = subparser . mconcat $\n    [ command \"doublepend\" $\n        info (helper <*> parseDoublePend)\n             (progDesc \"Double pendulum (default)\")\n    , command \"pend\"       $\n        info (helper <*> parsePend      )\n             (progDesc \"Single pendulum\")\n    , command \"room\"       $\n        info (helper <*> parseRoom      )\n        (progDesc \"Ball in room, bouncing off of walls\")\n    , command \"twobody\"    $\n        info (helper <*> parseTwoBody    )\n        (progDesc \"Two-body graviational simulation.  Note that bodies will only orbit if H < 0.\")\n    , command \"spring\"    $\n        info (helper <*> parseSpring    )\n        (progDesc \"A spring hanging from a block on a rail, holding up a mass.  Block is constrained to bounce between -1.5 and 1.5.\")\n    , command \"bezier\"     $\n        info (helper <*> parseBezier    )\n        (progDesc \"Particle moving along a parameterized bezier curve\")\n    , metavar \"EXAMPLE\"\n    ]\n  where\n    parsePend\n      = SECPend       <$> option auto ( long \"angle\"\n                                     <> short 'a'\n                                     <> metavar \"ANGLE\"\n                                     <> help \"Intitial rightward angle (in degrees) of bob\"\n                                     <> value 0\n                                     <> showDefault\n                                      )\n                      <*> option auto ( long \"vel\"\n                                     <> short 'v'\n                                     <> metavar \"VELOCITY\"\n                                     <> help \"Initial rightward angular velocity of bob\"\n                                     <> value 1\n                                     <> showDefault\n                                      )\n    parseDoublePend\n      = SECDoublePend <$> option auto ( long \"m1\"\n                                     <> metavar \"MASS\"\n                                     <> help \"Mass of first bob\"\n                                     <> value 1\n                                     <> showDefault\n                                      )\n                      <*> option auto ( long \"m2\"\n                                     <> metavar \"MASS\"\n                                     <> help \"Mass of second bob\"\n                                     <> value 1\n                                     <> showDefault\n                                      )\n    parseRoom\n      = SECRoom    <$> option auto ( long \"angle\"\n                                  <> short 'a'\n                                  <> metavar \"ANGLE\"\n                                  <> help \"Initial upward launch angle (in degrees) of object\"\n                                  <> value 45\n                                  <> showDefault\n                                   )\n    parseTwoBody\n      = SECTwoBody <$> option auto ( long \"m1\"\n                                  <> metavar \"MASS\"\n                                  <> help \"Mass of first body\"\n                                  <> value 5\n                                  <> showDefault\n                                   )\n                   <*> option auto ( long \"m2\"\n                                  <> metavar \"MASS\"\n                                  <> help \"Mass of second body\"\n                                  <> value 0.5\n                                  <> showDefault\n                                   )\n                   <*> option auto ( long \"vel\"\n                                  <> short 'v'\n                                  <> metavar \"VELOCITY\"\n                                  <> help \"Initial angular velocity of system\"\n                                  <> value 0.5\n                                  <> showDefault\n                                   )\n    parseSpring\n      = SECSpring <$> option auto ( long \"block\"\n                                 <> short 'b'\n                                 <> metavar \"MASS\"\n                                 <> help \"Mass of block on rail\"\n                                 <> value 2\n                                 <> showDefault\n                                  )\n                  <*> option auto ( long \"weight\"\n                                 <> short 'w'\n                                 <> metavar \"MASS\"\n                                 <> help \"Mass of weight hanging from spring\"\n                                 <> value 1\n                                 <> showDefault\n                                  )\n                  <*> option auto ( short 'k'\n                                 <> metavar \"NUM\"\n                                 <> help \"Spring constant / stiffness of spring\"\n                                 <> value 10\n                                 <> showDefault\n                                  )\n                  <*> option auto ( short 'x'\n                                 <> metavar \"DIST\"\n                                 <> help \"Initial displacement of spring\"\n                                 <> value 0.1\n                                 <> showDefault\n                                  )\n    parseBezier\n      = SECBezier <$> option f ( long \"points\"\n                              <> short 'p'\n                              <> metavar \"POINTS\"\n                              <> help \"List of control points (at least one), as tuples\"\n                              <> value (V2 (-1) (-1) NE.:| [V2 (-2) 1, V2 0 1, V2 1 (-1), V2 2 1])\n                              <> showDefaultWith (show . map (\\(V2 x y) -> (x, y)) . toList)\n                               )\n      where f = eitherReader $ \\s -> do\n              ps  <- maybe (Left \"Bad parse\") Right\n                  $ readMaybe s\n              maybe (Left \"At least one control point required\") Right\n                  $ NE.nonEmpty (uncurry V2 <$> ps)\n\ndata SimOpts = SO { soZoom :: Double\n                  , soRate :: Double\n                  , soHist :: Int\n                  }\n  deriving (Show)\n\ndata SimEvt = SEQuit\n            | SEZoom Double\n            | SERate Double\n            | SEHist Int\n\nmain :: IO ()\nmain = do\n    EO{..} <- execParser $ info (helper <*> parseEO)\n        ( fullDesc\n       <> header \"hamilton-examples - hamilton library example suite\"\n       <> progDescDoc (Just descr)\n        )\n\n    vty <- mkVty =<< standardIOConfig\n\n    opts <- newIORef $ SO 0.5 1 25\n\n    t <- forkIO . loop vty opts $ case eoChoice of\n      SECDoublePend m1 m2        -> doublePendulum m1 m2\n      SECPend       d0 \u03c90        -> pendulum (d0 / 180 * pi) \u03c90\n      SECRoom       d0           -> room (d0 / 180 * pi)\n      SECTwoBody    m1 m2 \u03c90     -> twoBody m1 m2 \u03c90\n      SECSpring     mB mW k x0   -> spring mB mW k x0\n      SECBezier     (p NE.:| ps) -> V.withSized (VV.fromList ps)\n                                      (bezier . V.cons p)\n\n\n    forever $ do\n      e <- nextEvent vty\n      forM_ (processEvt e) $ \\case\n        SEQuit -> do\n          killThread t\n          shutdown vty\n          exitSuccess\n        SEZoom s ->\n          modifyIORef opts $ \\o -> o { soZoom = soZoom o * s }\n        SERate r ->\n          modifyIORef opts $ \\o -> o { soRate = soRate o * r }\n        SEHist h ->\n          modifyIORef opts $ \\o -> o { soHist = soHist o + h }\n  where\n    fps :: Double\n    fps = 12\n    screenRatio :: Double\n    screenRatio = 2.1\n    ptAttrs :: [(Char, Color)]\n    ptAttrs  = ptChars `zip` ptColors\n      where\n        ptColors = cycle [white,yellow,blue,red,green]\n        ptChars  = cycle \"o*+~\"\n    loop :: Vty -> IORef SimOpts -> SysExample -> IO ()\n    loop vty oRef SE{..} = go M.empty seInit\n      where\n        qVec = intercalate \",\" . V.toList $ seCoords\n        go hists p = do\n          SO{..} <- readIORef oRef\n          let p'   = stepHam (soRate / fps) seSystem p  -- progress the simulation\n              xb   = (- recip soZoom, recip soZoom)\n              infobox = vertCat . map (string defAttr) $\n                  [ printf \"[ %s ]\" seName\n                  , printf \" <%s>   : <%s>\" qVec . intercalate \", \"\n                     . map (printf \"%.4f\") . VS.toList . rVec . phsPositions $ p\n                  , printf \"d<%s>/dt: <%s>\" qVec . intercalate \", \"\n                     . map (printf \"%.4f\") . VS.toList . rVec . velocities seSystem $ p\n                  , printf \"KE: %.4f\" . keP seSystem           $ p\n                  , printf \"PE: %.4f\" . pe seSystem . phsPositions $ p\n                  , printf \"H : %.4f\" . hamiltonian seSystem   $ p\n                  , \" \"\n                  , printf \"rate: x%.2f <>\" $ soRate\n                  , printf \"hist: % 5d []\" $ soHist\n                  , printf \"zoom: x%.2f -+\" $ soZoom\n                  ]\n              pts  = (`zip` ptAttrs) . seDraw . underlyingPos seSystem . phsPositions\n                   $ p\n              hists' = foldl' (\\h (r, a) -> M.insertWith (addHist soHist) a [r] h) hists pts\n          dr <- displayBounds $ outputIface vty\n          update vty . picForLayers . (infobox:) . plot dr (PX xb (RR 0.5 screenRatio)) $\n               ((second . second) (defAttr `withForeColor`) <$> pts)\n            ++ (map (\\((_,c),r) -> (r, ('.', defAttr `withForeColor` c)))\n                  . concatMap sequence\n                  . M.toList\n                  $ hists'\n               )\n          threadDelay (round (1000000 / fps))\n          go hists' p'\n    addHist hl new old = take hl (new ++ old)\n    descr :: PP.Doc\n    descr = PP.vcat\n      [ \"Run examples from the hamilton library example suite.\"\n      , \"Use with [EXAMPLE] --help for more per-example options.\"\n      , \"\"\n      , \"To adjust rate/history/zoom, use keys <>/[]/-+, respectively.\"\n      , \"\"\n      , \"See: https://github.com/mstksg/hamilton#example-app-runner\"\n      ]\n\nprocessEvt\n    :: Event -> Maybe SimEvt\nprocessEvt = \\case\n    EvKey KEsc        []      -> Just SEQuit\n    EvKey (KChar 'c') [MCtrl] -> Just SEQuit\n    EvKey (KChar 'q') []      -> Just SEQuit\n    EvKey (KChar '+') []      -> Just $ SEZoom (sqrt 2)\n    EvKey (KChar '-') []      -> Just $ SEZoom (sqrt 0.5)\n    EvKey (KChar '>') []      -> Just $ SERate (sqrt 2)\n    EvKey (KChar '<') []      -> Just $ SERate (sqrt (1/2))\n    EvKey (KChar ']') []      -> Just $ SEHist 5\n    EvKey (KChar '[') []      -> Just $ SEHist (-5)\n    _                         -> Nothing\n\ndata RangeRatio = RR { -- | Where on the screen (0 to 1) to place the other axis\n                       rrZero  :: Double\n                       -- | Ratio of height of a terminal character to width\n                     , rrRatio :: Double\n                     }\n                deriving (Show)\n\ndata PlotRange = PXY (Double, Double) (Double, Double)\n               | PX  (Double, Double) RangeRatio\n               | PY  RangeRatio       (Double, Double)\n\nplot\n    :: (Int, Int)               -- ^ display bounds\n    -> PlotRange\n    -> [(V2 Double, (Char, Attr))]   -- ^ points to plot\n    -> [Image]\nplot (wd,ht) pr = map (crop wd ht)\n                . (++ bgs)\n                . map (\\(p, (c, a)) -> place EQ EQ p $ char a c)\n  where\n    wd' = fromIntegral wd\n    ht' = fromIntegral ht\n    ((xmin, xmax), (ymin, ymax)) = mkRange (wd', ht') pr\n    origin = place EQ EQ (V2 0 0) $ char defAttr '+'\n    xaxis  = place EQ EQ (V2 0 0) $ charFill defAttr '-' wd 1\n    yaxis  = place EQ EQ (V2 0 0) $ charFill defAttr '|' 1 ht\n    xrange = xmax - xmin\n    yrange = ymax - ymin\n    bg     = backgroundFill wd ht\n    scale (V2 pX pY) = V2 x y\n      where\n        x = round $ (pX - xmin) * (wd' / xrange)\n        y = round $ (pY - ymin) * (ht' / yrange)\n    place aX aY p i = case scale p of\n      V2 pX pY -> translate (fAlign aX (imageWidth  i))\n                            (fAlign aY (imageHeight i))\n                . translate pX pY\n                $ i\n    labels = [ place LT EQ (V2 xmin 0) . string defAttr $ printf \"%.2f\" xmin\n             , place GT EQ (V2 xmax 0) . string defAttr $ printf \"%.2f\" xmax\n             , place EQ LT (V2 0 ymin) . string defAttr $ printf \"%.2f\" ymin\n             , place EQ GT (V2 0 ymax) . string defAttr $ printf \"%.2f\" ymax\n             ]\n    bgs    = labels ++ [origin, xaxis, yaxis, bg]\n    fAlign = \\case\n      LT -> const 0\n      EQ -> negate . (`div` 2)\n      GT -> negate\n\nmkRange\n    :: (Double, Double)\n    -> PlotRange\n    -> ((Double, Double), (Double, Double))\nmkRange (wd, ht) = \\case\n    PXY xb     yb     -> (xb, yb)\n    PX  xb     RR{..} ->\n      let yr = (uncurry (-) xb) * ht / wd * rrRatio\n          y0 = (rrZero - 1) * yr\n      in  (xb, (y0, y0 + yr))\n    PY  RR{..} yb ->\n      let xr = (uncurry (-) yb) * wd / ht / rrRatio\n          x0 = (rrZero - 1) * xr\n      in  ((x0, x0 + xr), yb)\n\npattern V1 :: a -> V.Vector 1 a\npattern V1 x <- (V.head->x)\n  where\n    V1 x = V.singleton x\n#if __GLASGOW_HASKELL__ >= 802\n{-# COMPLETE V1 #-}\n#endif\n\ntype V2 = V.Vector 2\npattern V2 :: a -> a -> V2 a\npattern V2 x y <- (V.toList->[x,y])\n  where\n    V2 x y = V.fromTuple (x, y)\n#if __GLASGOW_HASKELL__ >= 802\n{-# COMPLETE V2 #-}\n#endif\n\npattern V3 :: a -> a -> a -> V.Vector 3 a\npattern V3 x y z <- (V.toList->[x,y,z])\n  where\n    V3 x y z = V.fromTuple (x, y, z)\n#if __GLASGOW_HASKELL__ >= 802\n{-# COMPLETE V3 #-}\n#endif\n\npattern V4 :: a -> a -> a -> a -> V.Vector 4 a\npattern V4 x y z a <- (V.toList->[x,y,z,a])\n  where\n    V4 x y z a = V.fromTuple (x, y, z, a)\n#if __GLASGOW_HASKELL__ >= 802\n{-# COMPLETE V4 #-}\n#endif\n\nlogistic\n    :: Floating a => a -> a -> a -> a -> a\nlogistic pos ht width = \\x -> ht / (1 + exp (- beta * (x - pos)))\n  where\n    beta = log (0.9 / (1 - 0.9)) / width\n\n\nbezierCurve\n    :: forall n f a. (KnownNat (1 + n), Applicative f, Num a)\n    => V.Vector (1 + n) (f a)\n    -> a\n    -> f a\nbezierCurve ps t =\n      foldl' (liftA2 (+)) (pure 0)\n    . V.imap (\\i -> let i' = fromIntegral i\n                    in  fmap (* (fromIntegral (n' `choose` i') * (1 - t)^(n' - i') * t^i))\n             )\n    $ ps\n  where\n    n' :: Int\n    n' = fromIntegral (maxBound :: Finite (1 + n))\n    choose :: Int -> Int -> Int\n    n `choose` k = factorial n `div` (factorial (n - k) * factorial k)\n    factorial :: Int -> Int\n    factorial m = product [1..m]\n\nderiving instance Ord Color\n\n", "meta": {"hexsha": "e0981d9fc89d41ad1d87f11758fb8c8e27e327ca", "size": 21433, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Examples.hs", "max_stars_repo_name": "mstksg/hamilton", "max_stars_repo_head_hexsha": "3ba45860466a25de2933c61dd6f3eefa84725c29", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 136, "max_stars_repo_stars_event_min_datetime": "2016-11-22T15:07:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T22:08:07.000Z", "max_issues_repo_path": "app/Examples.hs", "max_issues_repo_name": "mstksg/hamilton", "max_issues_repo_head_hexsha": "3ba45860466a25de2933c61dd6f3eefa84725c29", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2016-12-05T09:41:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-06T03:24:53.000Z", "max_forks_repo_path": "app/Examples.hs", "max_forks_repo_name": "mstksg/hamilton", "max_forks_repo_head_hexsha": "3ba45860466a25de2933c61dd6f3eefa84725c29", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-11-24T21:59:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:15.000Z", "avg_line_length": 39.6907407407, "max_line_length": 134, "alphanum_fraction": 0.4278915691, "num_tokens": 5638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45874608469291084}}
{"text": "{-# OPTIONS_GHC -fno-warn-unticked-promoted-constructors #-}\n\nmodule Noether.Algebra.Linear.Module where\n\nimport           Data.Complex\n\nimport           Noether.Lemmata.Prelude\nimport           Noether.Lemmata.TypeFu\n\nimport           Noether.Algebra.Actions\nimport           Noether.Algebra.Multiple\nimport           Noether.Algebra.Single\n\nimport           Noether.Algebra.Tags\n\ndata LeftModuleE\n  = LeftModule_Ring_AbelianGroup_Linear_Compatible\n    { leftModule_ring           :: RingE\n    , leftModule_abelianGroup   :: AbelianGroupE\n    , leftModule_actorLinearity :: ActorLinearE\n    , leftModule_acteeLinearity :: ActeeLinearE\n    , leftModule_compatibility  :: CompatibleE}\n  | LeftModule_Named Symbol\n                     LeftModuleE\n\n-- | A left module (v, a) over the ring (r, p, m).\nclass LeftModuleK op p m r a v s\n\ntype family LeftModuleS (op :: k0) (p :: k1) (m :: k2) r (a :: k3) v :: LeftModuleE\n\ntype LeftModuleC op p m r a v = LeftModuleK op p m r a v (LeftModuleS op p m r a v)\n\ninstance ( RingK p m r zr\n         , AbelianGroupK a v zag\n         , ActorLinearK L m p r a v zor\n         , ActeeLinearK L m r a v zee\n         , CompatibleK L op m r v zlc\n         ) =>\n         LeftModuleK op p m r a v\n           (LeftModule_Ring_AbelianGroup_Linear_Compatible zr zag zor zee zlc)\n\ntype LeftModule op p m r a v =\n  ( LeftModuleC op p m r a v\n  , Ring p m r\n  , AbelianGroup a v\n  , LinearActsOn L m p r a v\n  , LeftCompatible op m r v\n  )\n\ndata RightModuleE\n  = RightModule_Ring_AbelianGroup_Linear_Compatible\n    { rightModule_ring           :: RingE\n    , rightModule_abelianGroup   :: AbelianGroupE\n    , rightModule_actorLinearity :: ActorLinearE\n    , rightModule_acteeLinearity :: ActeeLinearE\n    , rightModule_compatibility  :: CompatibleE}\n  | RightModule_Named Symbol\n                     RightModuleE\n\n-- | A right module (v, a) over the ring (r, p, m).\nclass RightModuleK op p m r a v s\n\ntype family RightModuleS (op :: k0) (p :: k1) (m :: k2) r (a :: k3) v :: RightModuleE\n\ntype RightModuleC op p m r a v = RightModuleK op p m r a v (RightModuleS op p m r a v)\n\ninstance ( RingK p m r zr\n         , AbelianGroupK a v zag\n         , ActorLinearK 'R m p r a v zor\n         , ActeeLinearK 'R m r a v zee\n         , CompatibleK 'R op m r v zrc\n         ) => RightModuleK op p m r a v\n           (RightModule_Ring_AbelianGroup_Linear_Compatible zr zag zor zee zrc)\n\ntype RightModule op p m r a v =\n  ( RightModuleC op p m r a v\n  , Ring p m r\n  , AbelianGroup a v\n  , LinearActsOn 'R m p r a v\n  , RightCompatible op m r v\n  )\n", "meta": {"hexsha": "b3aa198260d40a5a517471e8a2348f3bc7d3b54b", "size": 2557, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "library/Noether/Algebra/Linear/Module.hs", "max_stars_repo_name": "evertedsphere/noether", "max_stars_repo_head_hexsha": "c4223f64b9df5b0dbbeec1fea726bfff7f5810f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "library/Noether/Algebra/Linear/Module.hs", "max_issues_repo_name": "evertedsphere/noether", "max_issues_repo_head_hexsha": "c4223f64b9df5b0dbbeec1fea726bfff7f5810f5", "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": "library/Noether/Algebra/Linear/Module.hs", "max_forks_repo_name": "evertedsphere/noether", "max_forks_repo_head_hexsha": "c4223f64b9df5b0dbbeec1fea726bfff7f5810f5", "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": 31.1829268293, "max_line_length": 86, "alphanum_fraction": 0.6464606961, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45802684503187374}}
{"text": "{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE PolyKinds           #-}\n{-# LANGUAGE RankNTypes          #-}\n-- |\n-- Module      : Bench.HMatrix\n-- Copyright   : [2017..2020] Trevor L. McDonell\n-- License     : BSD3\n--\n-- Maintainer  : Trevor L. McDonell <trevor.mcdonell@gmail.com>\n-- Stability   : experimental\n-- Portability : non-portable (GHC extensions)\n--\n\nmodule Bench.HMatrix ( bench_hmatrix )\n  where\n\nimport Bench.Util\n\nimport Control.DeepSeq\nimport Criterion.Main\nimport Data.Proxy\nimport Foreign.Storable\nimport Numeric.LinearAlgebra                                        hiding ( randomVector )\nimport Prelude                                                      hiding ( (<>) )\nimport System.Random.MWC\nimport Text.Printf\n\n\nbench_hmatrix :: [Benchmark]\nbench_hmatrix =\n  [ bench_level2\n  , bench_level3\n  ]\n\nbench_level2 :: Benchmark\nbench_level2 =\n  bgroup \"matrix-vector\"\n    [ bgroup \"(#>)\"\n      [ gemv  200  400\n      , gemv  500 1000\n      , gemv 1000 2000\n      , gemv 2000 3000\n      ]\n    , bgroup \"(<#)\"\n      [ gevm  200  400\n      , gevm  500 1000\n      , gevm 1000 2000\n      , gevm 2000 3000\n      ]\n    ]\n  where\n    gemv :: Int -> Int -> Benchmark\n    gemv m n =\n      let setup :: (Variate e, Storable e) => proxy e -> IO (Matrix e, Vector e)\n          setup _ = withSystemRandom $ \\gen -> do\n            matA <- randomMatrix gen m n\n            vecx <- randomVector gen n\n            return (matA, vecx)\n\n          go :: (Variate e, Numeric e, NFData e, Show (ArgType e)) => proxy e -> Benchmark\n          go t = env (setup t)\n               $ \\ ~(matA, vecx) -> bench (showType t)\n               $ whnf (matA #>) vecx\n      in\n      bgroup (printf \"%dx%d\" m n) (sdcz go)\n\n    gevm :: Int -> Int -> Benchmark\n    gevm m n =\n      let setup :: (Variate e, Storable e) => proxy e -> IO (Matrix e, Vector e)\n          setup _ = withSystemRandom $ \\gen -> do\n            matA <- randomMatrix gen m n\n            vecx <- randomVector gen m\n            return (matA, vecx)\n\n          go :: (Variate e, Numeric e, NFData e, Show (ArgType e)) => proxy e -> Benchmark\n          go t = env (setup t)\n               $ \\ ~(matA, vecx) -> bench (showType t)\n               $ whnf (vecx <#) matA\n      in\n      bgroup (printf \"%dx%d\" m n) (sdcz go)\n\nbench_level3 :: Benchmark\nbench_level3 =\n  bgroup \"matrix-matrix\"\n    [ bgroup \"(<>)\"\n      [ gemm  100  100  100\n      , gemm  250  250  250\n      , gemm  500  500  500\n      , gemm 1000 1000 1000\n      ]\n    ]\n  where\n    gemm :: Int -> Int -> Int -> Benchmark\n    gemm m n k =\n      let\n          setup :: (Variate e, Storable e) => proxy e -> IO (Matrix e, Matrix e)\n          setup _ = withSystemRandom $ \\gen -> do\n            matA <- randomMatrix gen m k\n            matB <- randomMatrix gen k n\n            return (matA, matB)\n\n          go :: (Variate e, Numeric e, NFData e, Show (ArgType e)) => proxy e -> Benchmark\n          go t = env (setup t)\n               $ \\ ~(matA, matB) -> bench (showType t)\n               $ whnf (matA <>) matB\n      in\n      bgroup (printf \"%dx%dx%d\" m n k) (sdcz go)\n\n\nrandomVector :: (Variate e, Storable e) => GenIO -> Int -> IO (Vector e)\nrandomVector = uniformVector\n\nrandomMatrix :: (Variate e, Storable e) => GenIO -> Int -> Int -> IO (Matrix e)\nrandomMatrix gen m n = do\n  v <- uniformVector gen (m * n)\n  return $ reshape n v\n\nsdcz :: (forall (e :: *). (Variate e, Numeric e, NFData e, Show (ArgType e)) => Proxy e -> Benchmark)\n     -> [Benchmark]\nsdcz go =\n  [ go (Proxy :: Proxy Float)\n  , go (Proxy :: Proxy Double)\n  , go (Proxy :: Proxy (Complex Float))\n  , go (Proxy :: Proxy (Complex Double))\n  ]\n\n", "meta": {"hexsha": "f123b1b98e650d104e976118abc788f6adf8341d", "size": 3664, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/Bench/HMatrix.hs", "max_stars_repo_name": "statusfailed/accelerate-blas", "max_stars_repo_head_hexsha": "4e59e73f8545db76ea5d4570fb118af4080b0385", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-07-01T06:41:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T04:28:37.000Z", "max_issues_repo_path": "bench/Bench/HMatrix.hs", "max_issues_repo_name": "statusfailed/accelerate-blas", "max_issues_repo_head_hexsha": "4e59e73f8545db76ea5d4570fb118af4080b0385", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-07-17T02:23:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-26T16:52:28.000Z", "max_forks_repo_path": "bench/Bench/HMatrix.hs", "max_forks_repo_name": "statusfailed/accelerate-blas", "max_forks_repo_head_hexsha": "4e59e73f8545db76ea5d4570fb118af4080b0385", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-16T03:06:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T15:49:28.000Z", "avg_line_length": 28.625, "max_line_length": 101, "alphanum_fraction": 0.5409388646, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4580268334526936}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ScopedTypeVariables #-}\nmodule Day12 where\n\nimport Control.Lens\nimport Control.Lens.TH\n\nimport qualified Data.ByteString as BS\nimport Data.Attoparsec.ByteString (Parser)\nimport qualified Data.Attoparsec.ByteString as DAB\nimport qualified Data.Attoparsec.ByteString.Char8 as DABC8\nimport Data.Attoparsec.ByteString.Char8 (decimal, inClass, digit, endOfLine, char, anyChar, letter_ascii, notChar)\n\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\nimport qualified Data.List as DL\nimport qualified Data.List.Split as DLS\n\nimport Debug.Trace\n\nimport Control.Arrow\n\nimport Data.Array.IArray (Array)\nimport qualified Data.Array.IArray as IA\n\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Either (isRight)\nimport Data.Maybe (mapMaybe, catMaybes)\nimport Data.Bool (bool)\n\nimport Data.Vector (Vector, (!))\nimport qualified Data.Vector as Vec\n\nimport Data.Function (on)\n\nimport Control.Monad.State.Strict (State)\nimport qualified Control.Monad.State.Strict as State\n\nimport qualified Control.Monad as CM\n\n-- import qualified Control.Foldl as L\n\nimport Data.Bifunctor (bimap)\n\nimport Data.Complex\n\n--type Input = (IA.Array Int (IA.Array Int Char))\ntype Input = (Char, Int)\n\n-- >>> solver [('F', 10),\n\nsolver input =\n\tuncurry (+) $\n\t(abs . realPart &&& abs . imagPart) $ snd $\n\tDL.foldl' (\\x y -> traceShow (x, y) (navigate y x)) (10 :+ 1, 0 :+ 0) input\n\twhere\n\tnavigate :: Input -> (Complex Float, Complex Float) -> (Complex Float, Complex Float)\n\tnavigate ('N', n) = first (+ imag n)\n\tnavigate ('S', n) = first (dec (imag n))\n\tnavigate ('E', n) = first (+ real n)\n\tnavigate ('W', n) = first (dec (real n))\n\n\tnavigate ('L', 90) = first (* (0 :+ 1))\n\tnavigate ('L', 180) = first $ fmap round' . (* (0 :+ 1) ** 2)\n\tnavigate ('L', 270) = first $ fmap round' . (* (0 :+ 1) ** 3)\n\n\tnavigate ('R', 90) = first $ fmap round' . (* (0 :+ (-1)))\n\tnavigate ('R', 180) = first $ fmap round' . (* (0 :+ (-1)) ** 2)\n\tnavigate ('R', 270) = first $ fmap round' . (* (0 :+ (-1)) ** 3)\n\tnavigate ('F', n) = uncurry (CM.liftM2 (.) (,) ((+) . (real n *)))\n\n\tnavigate (c, n) = error $ show (c, n)\n\n\tnorm :: Complex Float -> Complex Float\n\tnorm x = x / abs x\n\n\treal n = fromIntegral n :+ 0\n\timag n = 0 :+ fromIntegral n\n\tdec n x = x - n\n\n\tround' :: Float -> Float\n\tround' = fromIntegral . round\n\nparseInput :: Parser [Input]\nparseInput =\n\t((,) <$> anyChar <*> decimal) `DAB.sepBy1'` endOfLine\n\nrunSolution :: FilePath -> IO ()\nrunSolution filePath = do\n\tcontents <- BS.readFile filePath\n\tlet parseResult = DAB.parseOnly parseInput contents\n\tcase parseResult of\n\t\tLeft err -> putStrLn err\n\t\tRight input -> do\n\t\t\tprint $ solver input\n\n-- 1526 wrong\n-- part ii\n-- 1463 wrong\n", "meta": {"hexsha": "a66de27e0cae85411832be00c486aee5f540db29", "size": 2760, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src-lib/Day12.hs", "max_stars_repo_name": "argent0/adventOfCode2020", "max_stars_repo_head_hexsha": "e3c81ce3db38490bcfd5de230f605086cc3df06c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src-lib/Day12.hs", "max_issues_repo_name": "argent0/adventOfCode2020", "max_issues_repo_head_hexsha": "e3c81ce3db38490bcfd5de230f605086cc3df06c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src-lib/Day12.hs", "max_forks_repo_name": "argent0/adventOfCode2020", "max_forks_repo_head_hexsha": "e3c81ce3db38490bcfd5de230f605086cc3df06c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7961165049, "max_line_length": 114, "alphanum_fraction": 0.6692028986, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4580150165582799}}
{"text": "{-# OPTIONS_GHC -Wall #-}\n{-# LANGUAGE Trustworthy #-}\n{-# LANGUAGE CPP #-}\n\n{- | \nModule      :  Physics.Learn.BeamStack\nCopyright   :  (c) Scott N. Walck 2016-2018\nLicense     :  BSD3 (see LICENSE)\nMaintainer  :  Scott N. Walck <walck@lvc.edu>\nStability   :  experimental\n\nSplitters, recombiners, and detectors for Stern-Gerlach\nexperiments.\n-}\n\n-- Spin-1/2 mixed states.\n\nmodule Physics.Learn.BeamStack\n    (\n    -- * Core laboratory components\n      BeamStack()\n    , randomBeam\n    , split\n    , recombine\n    , applyBField\n    , dropBeam\n    , flipBeams\n    , numBeams\n    , detect\n    -- * Standard splitters\n    , splitX\n    , splitY\n    , splitZ\n    -- * Standard magnetic fields\n    , applyBFieldX\n    , applyBFieldY\n    , applyBFieldZ\n    -- * Standard combiners\n    , recombineX\n    , recombineY\n    , recombineZ\n    -- * Filters\n    , xpFilter\n    , xmFilter\n    , zpFilter\n    , zmFilter\n    )\n    where\n\nimport Physics.Learn.QuantumMat\n    ( zp\n    , zm\n    , nm\n    , np\n    , couter\n    , oneQubitMixed\n    )\nimport Numeric.LinearAlgebra\n    ( C\n    , Vector\n    , Matrix\n    , iC\n    , (<>)\n    , kronecker\n    , fromLists\n    , toList\n    , toLists\n    , scale\n    , size\n    , takeDiag\n    , ident\n    , tr\n    )\nimport Data.Complex\n    ( Complex(..)\n    , realPart\n    , imagPart\n    )\nimport Data.List\n    ( intercalate\n    )\n#if MIN_VERSION_base(4,11,0)\nimport Prelude hiding ((<>))\n#endif\n\ndata BeamStack = BeamStack (Matrix C)\n\nshowOneBeam :: Double -> String\nshowOneBeam r = \"Beam of intensity \" ++ show r\n\ninstance Show BeamStack where\n    show b = intercalate \"\\n\" $ map showOneBeam (detect b)\n\n{-\nunBeamStack :: BeamStack -> Matrix C\nunBeamStack (BeamStack m) = m\n-}\n\n--------------------\n-- Core functions --\n--------------------\n\n-- | A beam of randomly oriented spin-1/2 particles.\nrandomBeam :: BeamStack\nrandomBeam = BeamStack oneQubitMixed\n\nextendWithZeros :: Matrix C -> Matrix C\nextendWithZeros m\n    = let (_,q) = size m\n          ml = toLists m\n      in fromLists $ map (++ [0,0]) ml\n             ++ [replicate (q+2) 0, replicate (q+2) 0]\n\n-- reduce row and column size by 2\nreduceMat :: Matrix C -> Matrix C\nreduceMat m\n    = let (p,q) = size m\n          ml = toLists m\n      in fromLists $ take (p-2) $ map (take (q-2)) ml\n\ncheckedRealPart :: C -> Double\ncheckedRealPart c\n    = let eps = 1e-14\n      in if imagPart c < eps\n         then realPart c\n         else error $ \"checkRealPart: imagPart = \" ++ show (imagPart c)\n\n-- | Return the intensities of a stack of beams.\ndetect :: BeamStack -> [Double]\ndetect (BeamStack m)\n    = addAlternate $ toList $ takeDiag m\n\naddAlternate :: [C] -> [Double]\naddAlternate [] = []\naddAlternate [_] = error \"addAlternate needs even number of elements\"\naddAlternate (x:y:xs) = checkedRealPart (x+y) : addAlternate xs\n\n-- | Remove the most recent beam from the stack.\ndropBeam :: BeamStack -> BeamStack\ndropBeam (BeamStack m) = BeamStack (reduceMat m)\n\n-- | Return the number of beams in a 'BeamStack'.\nnumBeams :: BeamStack -> Int\nnumBeams (BeamStack m)\n    = let (p,_) = size m\n      in p `div` 2\n\n-- | Interchange the two most recent beams on the stack.\nflipBeams :: BeamStack -> BeamStack\nflipBeams (BeamStack m)\n    = let (d,_) = size m\n          fl = flipMat d\n      in BeamStack $ fl <> m <> tr fl\n\nflipMat :: Int -> Matrix C\nflipMat d = bigM d (fromLists [[0,0,1,0]\n                              ,[0,0,0,1]\n                              ,[1,0,0,0]\n                              ,[0,1,0,0]])\n\n-- Turn a 2x2 into a dxd.\nbigM2 :: Int -> Matrix C -> Matrix C\nbigM2 d m\n    | d < 2      = error \"bigM2 requires d >= 2\"\n    | odd d      = error \"bigM2 requires even d\"\n    | otherwise  = fromLists $ map (++ [0,0]) (toLists (ident (d-2)))\n                   ++ map (replicate (d-2) 0 ++) (toLists m)\n\n-- Turn a 4x4 into a dxd.\nbigM :: Int -> Matrix C -> Matrix C\nbigM d m\n    | d < 4      = error \"bigM requires d >= 4\"\n    | odd d      = error \"bigM requires even d\"\n    | otherwise  = fromLists $ map (++ [0,0,0,0]) (toLists (ident (d-4)))\n                   ++ map (replicate (d-4) 0 ++) (toLists m)\n\ns :: Double -> Double -> Matrix C\ns theta phi = kronecker (u `couter` u) (np theta phi `couter` np theta phi)\n            + kronecker (l `couter` u) (nm theta phi `couter` nm theta phi)\n            + kronecker (u `couter` l) (nm theta phi `couter` nm theta phi)\n            + kronecker (l `couter` l) (np theta phi `couter` np theta phi)\n\nu :: Vector C\nu = zp\n\nl :: Vector C\nl = zm\n\n-- | Given angles describing the orientation of the splitter,\n--   removes an incoming beam from the stack and replaces\n--   it with two beams, a spin-up and a spin-down beam.\n--   The spin-down beam is the most recent beam on the stack.\nsplit :: Double -> Double -> BeamStack -> BeamStack\nsplit theta phi (BeamStack m)\n    = let m' = extendWithZeros m\n          (p,_) = size m'\n          ss = bigM p (s theta phi)\n      in BeamStack $ ss <> m' <> tr ss\n\n-- | Given angles describing the orientation of the recombiner,\n--   returns a single beam from an incoming pair of beams.\nrecombine :: Double -> Double -> BeamStack -> BeamStack\nrecombine theta phi (BeamStack m)\n    = let (d,_) = size m\n          ss = bigM d (s theta phi)\n      in dropBeam $ BeamStack $ ss <> m <> tr ss\n\nmag2x2 :: Double -> Double -> Double -> Matrix C\nmag2x2 theta phi omegaT\n    = let z = iC * (omegaT :+ 0) / 2\n          np' = np theta phi\n          nm' = nm theta phi\n      in scale (exp   z ) (np' `couter` np')\n       + scale (exp (-z)) (nm' `couter` nm')\n\n-- | Given angles describing the direction of a\n--   uniform magnetic field, and given an angle\n--   describing the product of the Larmor frequency\n--   and the time, return an output beam from an\n--   input beam.\napplyBField :: Double -> Double -> Double -> BeamStack -> BeamStack\napplyBField theta phi omegaT (BeamStack m)\n    = let (d,_) = size m\n          uu = bigM2 d (mag2x2 theta phi omegaT)\n      in BeamStack $ uu <> m <> tr uu\n\n-----------------------\n-- Derived functions --\n-----------------------\n\n-- | A Stern-Gerlach splitter in the x direction.\nsplitX :: BeamStack -> BeamStack\nsplitX = split (pi/2) 0\n\n-- | A Stern-Gerlach splitter in the y direction.\nsplitY :: BeamStack -> BeamStack\nsplitY = split (pi/2) (pi/2)\n\n-- | A Stern-Gerlach splitter in the z direction.\nsplitZ :: BeamStack -> BeamStack\nsplitZ = split 0 0\n\n-- | Given an angle in radians\n--   describing the product of the Larmor frequency\n--   and the time, apply a magnetic in the x direction\n--   to the most recent beam on the stack.\napplyBFieldX :: Double -> BeamStack -> BeamStack\napplyBFieldX = applyBField (pi/2) 0\n\n-- | Given an angle in radians\n--   describing the product of the Larmor frequency\n--   and the time, apply a magnetic in the y direction\n--   to the most recent beam on the stack.\napplyBFieldY :: Double -> BeamStack -> BeamStack\napplyBFieldY = applyBField (pi/2) (pi/2)\n\n-- | Given an angle in radians\n--   describing the product of the Larmor frequency\n--   and the time, apply a magnetic in the z direction\n--   to the most recent beam on the stack.\napplyBFieldZ :: Double -> BeamStack -> BeamStack\napplyBFieldZ = applyBField 0 0\n\n-- | A Stern-Gerlach recombiner in the x direction.\nrecombineX :: BeamStack -> BeamStack\nrecombineX = recombine (pi/2) 0\n\n-- | A Stern-Gerlach recombiner in the y direction.\nrecombineY :: BeamStack -> BeamStack\nrecombineY = recombine (pi/2) (pi/2)\n\n-- | A Stern-Gerlach recombiner in the z direction.\nrecombineZ :: BeamStack -> BeamStack\nrecombineZ = recombine 0 0\n\n-- | Filter for spin-up particles in the x direction.\nxpFilter :: BeamStack -> BeamStack\nxpFilter = dropBeam . splitX\n\n-- | Filter for spin-down particles in the x direction.\nxmFilter :: BeamStack -> BeamStack\nxmFilter = dropBeam . flipBeams . splitX\n\n-- | Filter for spin-up particles in the z direction.\nzpFilter :: BeamStack -> BeamStack\nzpFilter = dropBeam . splitZ\n\n-- | Filter for spin-down particles in the z direction.\nzmFilter :: BeamStack -> BeamStack\nzmFilter = dropBeam . flipBeams . splitZ\n", "meta": {"hexsha": "f3bab88422a7b68d89272b1b4933908a52e8963d", "size": 8008, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Physics/Learn/BeamStack.hs", "max_stars_repo_name": "walck/learn-physics", "max_stars_repo_head_hexsha": "99611ca49940b78a0e13402f35082805cc7db294", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 139, "max_stars_repo_stars_event_min_datetime": "2015-11-23T16:40:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:37:24.000Z", "max_issues_repo_path": "src/Physics/Learn/BeamStack.hs", "max_issues_repo_name": "walck/learn-physics", "max_issues_repo_head_hexsha": "99611ca49940b78a0e13402f35082805cc7db294", "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/Physics/Learn/BeamStack.hs", "max_forks_repo_name": "walck/learn-physics", "max_forks_repo_head_hexsha": "99611ca49940b78a0e13402f35082805cc7db294", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2016-09-16T03:54:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T15:44:56.000Z", "avg_line_length": 27.5189003436, "max_line_length": 75, "alphanum_fraction": 0.6195054945, "num_tokens": 2391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4579367197869259}}
{"text": "module Vec where\nimport Linear.Epsilon (nearZero)\nimport qualified Data.Map.Strict as Map\nimport Data.Complex\n\n-- http://blog.sigfpe.com/2007/03/monads-vector-spaces-and-quantum.html\n\n\ndata W b a = W { runW :: [(a,b)] } deriving (Eq,Show,Ord)\ninstance Semigroup (W b a) where\n  (W x) <> (W y) = W (x <> y)\ninstance Monoid (W b a) where\n  mempty = W mempty \nmapW f (W l) = W $ map (\\(a,b) -> (a,f b)) l\ninstance Functor (W b) where\n    fmap f (W a) = W $ map (\\(a,p) -> (f a,p)) a\n\ninstance Num b => Applicative (W b) where\n  pure x = W [(x,1)]\n  (W fs) <*> (W xs) = W [(f x, a * b) | (f, a) <- fs, (x, b) <- xs] \n  -- the fs is a a vector of rows kind of.\n    -- error \"I don't feel like it\"\n\ninstance Num b => Monad (W b) where\n   return x = W [(x,1)]\n   l >>= f = W $ concatMap (\\(W d,p) -> map (\\(x,q)->(x,p*q)) d) (runW $ fmap f l)\n\na .* b = mapW (a*) b\n\ninstance (Eq a,Show a,Num b) => Num (W b a) where\n     W a + W b = W $ (a ++ b)\n     a - b = a + (-1) .* b\n     _ * _ = error \"Num is annoying\"\n     abs _ = error \"Num is annoying\"\n     signum _ = error \"Num is annoying\"\n     fromInteger a = if a==0 then W [] else error \"fromInteger can only take zero argument\"\n\ncollect :: (Ord a, Num b) => W b a -> W b a\ncollect = W . Map.toList . Map.fromListWith (+) . runW\n\ntrimZero = W . filter (\\(k,v) -> not $ nearZero v) . runW\nsimplify :: Ord a => Q a -> Q a\nsimplify = trimZero . collect\n-- filter (not . nearZero . snd)\n\ntype P a = W Double a\n\ntype Q a = W (Complex Double) a\n\nstar :: Num b => W (Complex b) a -> W (Complex b) a\nstar = mapW conjugate\n\nkron :: Num b => W b a -> W b c -> W b (a,c)\nkron (W x) (W y) = W [((a,c), r1 * r2) | (a,r1) <- x , (c,r2) <- y ]", "meta": {"hexsha": "9a05631c1705a95bfe6424396114d64dd31b299e", "size": 1671, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Vec.hs", "max_stars_repo_name": "philzook58/fib-anyon", "max_stars_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-01-14T10:48:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T08:35:00.000Z", "max_issues_repo_path": "src/Vec.hs", "max_issues_repo_name": "philzook58/fib-anyon", "max_issues_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "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/Vec.hs", "max_forks_repo_name": "philzook58/fib-anyon", "max_forks_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-11-15T07:42:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-02T15:15:28.000Z", "avg_line_length": 30.9444444444, "max_line_length": 91, "alphanum_fraction": 0.552962298, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45769072276987033}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes, DataKinds, FlexibleInstances,\n             FunctionalDependencies, QuantifiedConstraints, RankNTypes,\n             TypeFamilies, TypeOperators #-}\n{-# OPTIONS_GHC -fconstraint-solver-iterations=16 #-}\n{-# OPTIONS_GHC -Wno-missing-methods #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n-- | Dual numbers and various operations on them, arithmetic and related\n-- to tensors (vectors, matrices and others). This is the high-level API,\n-- defined using the low-level API in \"HordeAd.Core.DualClass\".\nmodule HordeAd.Core.DualNumber\n  ( module HordeAd.Core.DualNumber\n  , IsScalar, HasDelta, DMode(..)\n  , Domain0, Domain1, Domain2, DomainX, Domains  -- an important re-export\n  ) where\n\nimport Prelude\n\nimport qualified Data.Array.Convert\nimport qualified Data.Array.Dynamic as OTB\nimport qualified Data.Array.DynamicS as OT\nimport           Data.Array.Internal (valueOf)\nimport           Data.Array.Shape (DivRoundUp)\nimport qualified Data.Array.Shaped as OSB\nimport qualified Data.Array.ShapedS as OS\nimport           Data.List.Index (imap)\nimport           Data.MonoTraversable (MonoFunctor (omap))\nimport           Data.Proxy (Proxy (Proxy))\nimport qualified Data.Strict.Vector as Data.Vector\nimport qualified Data.Vector.Generic as V\nimport           GHC.TypeLits (KnownNat, type (+), type (-), type (<=))\nimport           Numeric.LinearAlgebra (Matrix, Numeric, Vector)\nimport qualified Numeric.LinearAlgebra as HM\n\nimport HordeAd.Core.DualClass\nimport HordeAd.Internal.Delta\n  (CodeOut (..), Domain0, Domain1, Domain2, DomainX, Domains)\n\n-- * The main dual number types\n\n-- | Dual numbers with the second type argument being the primal component.\ndata DualNumber (d :: DMode) a = D a (Dual d a)\n\nclass (IsScalar d r, Monad m, Functor m, Applicative m)\n      => DualMonad d r m | m -> d r where\n  returnLet :: IsPrimalWithScalar d a r\n            => DualNumber d a -> m (DualNumber d a)\n\naddParameters :: (Numeric r, Num (Vector r))\n              => Domains r -> Domains r -> Domains r\naddParameters (a0, a1, a2, aX) (b0, b1, b2, bX) =\n  (a0 + b0, V.zipWith (+) a1 b1, V.zipWith (+) a2 b2, V.zipWith (+) aX bX)\n\n-- Dot product and sum respective ranks and sum it all.\ndotParameters :: Numeric r => Domains r -> Domains r -> r\ndotParameters (a0, a1, a2, aX) (b0, b1, b2, bX) =\n  a0 HM.<.> b0\n  + V.sum (V.zipWith (HM.<.>) a1 b1)\n  + V.sum (V.zipWith (HM.<.>) (V.map HM.flatten a2) (V.map HM.flatten b2))\n  + V.sum (V.zipWith (HM.<.>) (V.map OT.toVector aX) (V.map OT.toVector bX))\n\n\n-- * General operations, for any tensor rank\n\n-- These instances are required by the @Real@ instance, which is required\n-- by @RealFloat@, which gives @atan2@. No idea what properties\n-- @Real@ requires here, so let it crash if it's really needed.\ninstance Eq (DualNumber d a) where\n\ninstance Ord (DualNumber d a) where\n\n-- These instances are dangerous due to possible subexpression copies\n-- leading to allocation explosion. Expressions should be wrapped in\n-- the monadic @returnLet@ whenever there is a possibility they can be\n-- used multiple times in a larger expression.\ninstance (Num a, IsPrimal d a) => Num (DualNumber d a) where\n  D u u' + D v v' = D (u + v) (dAdd u' v')\n  D u u' - D v v' = D (u - v) (dAdd u' (dScale (-1) v'))\n  D u u' * D v v' = D (u * v) (dAdd (dScale v u') (dScale u v'))\n  negate (D v v') = D (negate v) (dScale (-1) v')\n  abs (D v v') = D (abs v) (dScale (signum v) v')\n  signum (D v _) = D (signum v) dZero\n  fromInteger = constant . fromInteger\n\ninstance (Real a, IsPrimal d a) => Real (DualNumber d a) where\n  toRational = undefined  -- TODO?\n\ninstance (Fractional a, IsPrimal d a) => Fractional (DualNumber d a) where\n  D u u' / D v v' =\n    let recipSq = recip (v * v)\n    in D (u / v) (dAdd (dScale (v * recipSq) u') (dScale (- u * recipSq) v'))\n  recip (D v v') =\n    let minusRecipSq = - recip (v * v)\n    in D (recip v) (dScale minusRecipSq v')\n  fromRational = constant . fromRational\n\ninstance (Floating a, IsPrimal d a) => Floating (DualNumber d a) where\n  pi = constant pi\n  exp (D u u') = let expU = exp u\n                 in D expU (dScale expU u')\n  log (D u u') = D (log u) (dScale (recip u) u')\n  sqrt (D u u') = let sqrtU = sqrt u\n                  in D sqrtU (dScale (recip (sqrtU + sqrtU)) u')\n  D u u' ** D v v' = D (u ** v) (dAdd (dScale (v * (u ** (v - 1))) u')\n                                      (dScale ((u ** v) * log u) v'))\n  logBase x y = log y / log x\n  sin (D u u') = D (sin u) (dScale (cos u) u')\n  cos (D u u') = D (cos u) (dScale (- (sin u)) u')\n  tan (D u u') = let cosU = cos u\n                 in D (tan u) (dScale (recip (cosU * cosU)) u')\n  asin (D u u') = D (asin u) (dScale (recip (sqrt (1 - u*u))) u')\n  acos (D u u') = D (acos u) (dScale (- recip (sqrt (1 - u*u))) u')\n  atan (D u u') = D (atan u) (dScale (recip (1 + u*u)) u')\n  sinh (D u u') = D (sinh u) (dScale (cosh u) u')\n  cosh (D u u') = D (cosh u) (dScale (sinh u) u')\n  tanh (D u u') = let y = tanh u\n                  in D y (dScale (1 - y * y) u')\n  asinh (D u u') = D (asinh u) (dScale (recip (sqrt (1 + u*u))) u')\n  acosh (D u u') = D (acosh u) (dScale (recip (sqrt (u*u - 1))) u')\n  atanh (D u u') = D (atanh u) (dScale (recip (1 - u*u)) u')\n\ninstance (RealFrac a, IsPrimal d a) => RealFrac (DualNumber d a) where\n  properFraction = undefined\n    -- very low priority, since these are all extremely not continuous\n\ninstance (RealFloat a, IsPrimal d a) => RealFloat (DualNumber d a) where\n  atan2 (D u u') (D v v') =\n    let t = 1 / (u * u + v * v)\n    in D (atan2 u v) (dAdd (dScale (- u * t) v') (dScale (v * t) u'))\n      -- we can be selective here and omit the other methods,\n      -- most of which don't even have a differentiable codomain\n\nconstant :: IsPrimal d a => a -> DualNumber d a\nconstant a = D a dZero\n\nscale :: (Num a, IsPrimal d a) => a -> DualNumber d a -> DualNumber d a\nscale a (D u u') = D (a * u) (dScale a u')\n\ntanhAct :: (DualMonad d r m, IsPrimalAndHasFeatures d a r)\n        => DualNumber d a -> m (DualNumber d a)\ntanhAct = returnLet . tanh\n\nlogistic :: (Floating a, IsPrimal d a) => DualNumber d a -> DualNumber d a\nlogistic (D u u') =\n  let y = recip (1 + exp (- u))\n  in D y (dScale (y * (1 - y)) u')\n\nlogisticAct :: (DualMonad d r m, IsPrimalAndHasFeatures d a r)\n            => DualNumber d a -> m (DualNumber d a)\nlogisticAct = returnLet . logistic\n\n-- Optimized and more clearly written @u ** 2@.\nsquare :: (Num a, IsPrimal d a) => DualNumber d a -> DualNumber d a\nsquare (D u u') = D (u * u) (dScale (2 * u) u')\n\nsquaredDifference :: (Num a, IsPrimal d a)\n                  => a -> DualNumber d a -> DualNumber d a\nsquaredDifference targ res = square $ res - constant targ\n\nlossSquared :: (DualMonad d r m, IsPrimalAndHasFeatures d a r)\n            => a -> DualNumber d a -> m (DualNumber d a)\nlossSquared targ res = returnLet $ squaredDifference targ res\n\nreluAct :: (DualMonad d r m, IsPrimalAndHasFeatures d a r)\n        => DualNumber d a -> m (DualNumber d a)\nreluAct v@(D u _) = do\n  let oneIfGtZero = omap (\\x -> if x > 0 then 1 else 0) u\n  returnLet $ scale oneIfGtZero v\n\nreluLeakyAct :: (DualMonad d r m, IsPrimalAndHasFeatures d a r)\n             => DualNumber d a -> m (DualNumber d a)\nreluLeakyAct v@(D u _) = do\n  let oneIfGtZero = omap (\\x -> if x > 0 then 1 else 0.01) u\n  returnLet $ scale oneIfGtZero v\n\n\n-- * Operations resulting in a scalar\n\nsumElements0 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d r\nsumElements0 (D u u') = D (HM.sumElements u) (dSumElements0 u' (V.length u))\n\nindex0 :: IsScalar d r => DualNumber d (Vector r) -> Int -> DualNumber d r\nindex0 (D u u') ix = D (u V.! ix) (dIndex0 u' ix (V.length u))\n\nminimum0 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d r\nminimum0 (D u u') =\n  D (HM.minElement u) (dIndex0 u' (HM.minIndex u) (V.length u))\n\nmaximum0 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d r\nmaximum0 (D u u') =\n  D (HM.maxElement u) (dIndex0 u' (HM.maxIndex u) (V.length u))\n\n-- If @v'@ is a @Var1@, this is much faster due to the optimization\n-- in @Index0@.\nfoldl'0 :: IsScalar d r\n        => (DualNumber d r -> DualNumber d r -> DualNumber d r)\n        -> DualNumber d r -> DualNumber d (Vector r)\n        -> DualNumber d r\nfoldl'0 f uu' (D v v') =\n  let k = V.length v\n      g !acc ix p = f (D p (dIndex0 v' ix k)) acc\n  in V.ifoldl' g uu' v\n\naltSumElements0 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d r\naltSumElements0 = foldl'0 (+) 0\n\n-- | Dot product.\ninfixr 8 <.>!\n(<.>!) :: IsScalar d r\n       => DualNumber d (Vector r) -> DualNumber d (Vector r) -> DualNumber d r\n(<.>!) (D u u') (D v v') = D (u HM.<.> v) (dAdd (dDot0 v u') (dDot0 u v'))\n\n-- | Dot product with a constant vector.\ninfixr 8 <.>!!\n(<.>!!) :: IsScalar d r\n        => DualNumber d (Vector r) -> Vector r -> DualNumber d r\n(<.>!!) (D u u') v = D (u HM.<.> v) (dDot0 v u')\n\ninfixr 8 <.>$\n(<.>$) :: (IsScalar d r, KnownNat n)\n       => DualNumber d (OS.Array '[n] r) -> DualNumber d (OS.Array '[n] r)\n       -> DualNumber d r\n(<.>$) d e = fromS1 d <.>! fromS1 e\n\nfromX0 :: IsScalar d r => DualNumber d (OT.Array r) -> DualNumber d r\nfromX0 (D u u') = D (OT.unScalar u) (dFromX0 u')\n\nfromS0 :: IsScalar d r => DualNumber d (OS.Array '[] r) -> DualNumber d r\nfromS0 (D u u') = D (OS.unScalar u) (dFromS0 u')\n\nsumElementsVectorOfDual\n  :: IsScalar d r => Data.Vector.Vector (DualNumber d r) -> DualNumber d r\nsumElementsVectorOfDual = V.foldl' (+) 0\n\nsoftMaxAct :: DualMonad d r m\n           => Data.Vector.Vector (DualNumber d r)\n           -> m (Data.Vector.Vector (DualNumber d r))\nsoftMaxAct us = do\n  expUs <- V.mapM (returnLet . exp) us\n  let sumExpUs = sumElementsVectorOfDual expUs\n  -- This has to be let-bound, because it's used many times below.\n  recipSum <- returnLet $ recip sumExpUs\n  V.mapM (\\r -> returnLet $ r * recipSum) expUs\n\n-- In terms of hmatrix: @-(log res <.> targ)@.\nlossCrossEntropy :: forall d r m. DualMonad d r m\n                 => Vector r\n                 -> Data.Vector.Vector (DualNumber d r)\n                 -> m (DualNumber d r)\nlossCrossEntropy targ res = do\n  let f :: DualNumber d r -> Int -> DualNumber d r -> DualNumber d r\n      f !acc i d = acc + scale (targ V.! i) (log d)\n  returnLet $ negate $ V.ifoldl' f 0 res\n\n-- In terms of hmatrix: @-(log res <.> targ)@.\nlossCrossEntropyV :: DualMonad d r m\n                  => Vector r\n                  -> DualNumber d (Vector r)\n                  -> m (DualNumber d r)\nlossCrossEntropyV targ res = returnLet $ negate $ log res <.>!! targ\n\n-- Note that this is equivalent to a composition of softMax and cross entropy\n-- only when @target@ is one-hot. Otherwise, results vary wildly. In our\n-- rendering of the MNIST data all labels are on-hot.\nlossSoftMaxCrossEntropyV\n  :: DualMonad d r m\n  => Vector r -> DualNumber d (Vector r) -> m (DualNumber d r)\nlossSoftMaxCrossEntropyV target (D u u') = do\n  -- The following protects from underflows, overflows and exploding gradients\n  -- and is required by the QuickCheck test in TestMnistCNN.\n  -- See https://github.com/tensorflow/tensorflow/blob/5a566a7701381a5cf7f70fce397759483764e482/tensorflow/core/kernels/sparse_softmax_op.cc#L106\n  -- and https://github.com/tensorflow/tensorflow/blob/5a566a7701381a5cf7f70fce397759483764e482/tensorflow/core/kernels/xent_op.h\n  let expU = exp (u - HM.scalar (HM.maxElement u))\n      sumExpU = HM.sumElements expU\n      recipSum = recip sumExpU\n-- not exposed: softMaxU = HM.scaleRecip sumExpU expU\n      softMaxU = HM.scale recipSum expU\n  returnLet $ D (negate $ log softMaxU HM.<.> target)  -- TODO: avoid: log . exp\n                (dDot0 (softMaxU - target) u')\n\n\n-- * Operations resulting in a vector\n\n-- @1@ means rank one, so the dual component represents a vector.\nseq1 :: IsScalar d r\n     => Data.Vector.Vector (DualNumber d r) -> DualNumber d (Vector r)\nseq1 v = D (V.convert $ V.map (\\(D u _) -> u) v)  -- I hope this fuses\n           (dSeq1 $ V.map (\\(D _ u') -> u') v)\n\nkonst1 :: IsScalar d r => DualNumber d r -> Int -> DualNumber d (Vector r)\nkonst1 (D u u') n = D (HM.konst u n) (dKonst1 u' n)\n\nappend1 :: IsScalar d r\n        => DualNumber d (Vector r) -> DualNumber d (Vector r)\n        -> DualNumber d (Vector r)\nappend1 (D u u') (D v v') = D (u V.++ v) (dAppend1 u' (V.length u) v')\n\nslice1 :: IsScalar d r\n       => Int -> Int -> DualNumber d (Vector r) -> DualNumber d (Vector r)\nslice1 i n (D u u') = D (V.slice i n u) (dSlice1 i n u' (V.length u))\n\nsumRows1 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Vector r)\nsumRows1 (D u u') = D (V.fromList $ map HM.sumElements $ HM.toRows u)\n                      (dSumRows1 u' (HM.cols u))\n\nsumColumns1 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Vector r)\nsumColumns1 (D u u') = D (V.fromList $ map HM.sumElements $ HM.toColumns u)\n                         (dSumColumns1 u' (HM.rows u))\n\n-- If @v'@ is a @Var1@, this is much faster due to the optimization\n-- in @Index0@. The detour through a boxed vector (list probably fuses away)\n-- is costly, but only matters if @f@ is cheap.\nmap1 :: IsScalar d r\n     => (DualNumber d r -> DualNumber d r) -> DualNumber d (Vector r)\n     -> DualNumber d (Vector r)\nmap1 f (D v v') =\n  let k = V.length v\n      g ix p = f $ D p (dIndex0 v' ix k)\n      ds = imap g $ V.toList v\n  in seq1 $ V.fromList ds\n\n-- | Dense matrix-vector product.\ninfixr 8 #>!\n(#>!) :: IsScalar d r\n      => DualNumber d (Matrix r) -> DualNumber d (Vector r)\n      -> DualNumber d (Vector r)\n(#>!) (D u u') (D v v') = D (u HM.#> v) (dAdd (dMD_V1 u' v) (dM_VD1 u v'))\n\n-- | Dense matrix-vector product with a constant vector.\ninfixr 8 #>!!\n(#>!!) :: IsScalar d r\n       => DualNumber d (Matrix r) -> Vector r\n       -> DualNumber d (Vector r)\n(#>!!) (D u u') v = D (u HM.#> v) (dMD_V1 u' v)\n\nfromX1 :: IsScalar d r => DualNumber d (OT.Array r) -> DualNumber d (Vector r)\nfromX1 (D u u') = D (OT.toVector u) (dFromX1 u')\n\nfromS1 :: forall len d r. (KnownNat len, IsScalar d r)\n       => DualNumber d (OS.Array '[len] r) -> DualNumber d (Vector r)\nfromS1 (D u u') = D (OS.toVector u) (dFromS1 u')\n\nreverse1 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d (Vector r)\nreverse1 (D u u') = D (V.reverse u) (dReverse1 u')\n\nflatten1 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Vector r)\nflatten1 (D u u') = let (rows, cols) = HM.size u\n                    in D (HM.flatten u) (dFlatten1 rows cols u')\n\nflattenX1 :: IsScalar d r => DualNumber d (OT.Array r) -> DualNumber d (Vector r)\nflattenX1 (D u u') = let sh = OT.shapeL u\n                     in D (OT.toVector u) (dFlattenX1 sh u')\n\nflattenS1 :: (IsScalar d r, OS.Shape sh)\n          => DualNumber d (OS.Array sh r) -> DualNumber d (Vector r)\nflattenS1 (D u u') = D (OS.toVector u) (dFlattenS1 u')\n\ncorr1 :: IsScalar d r\n      => DualNumber d (Vector r) -> DualNumber d (Vector r)\n      -> DualNumber d (Vector r)\ncorr1 ker@(D u _) vv@(D v _) = case (V.length u, V.length v) of\n  (0, lenV) -> konst1 0 lenV\n  (lenK, lenV) -> if lenK <= lenV\n                  then vectorSlices2 lenK vv #>! ker\n                  else error $ \"corr1: len kernel \" ++ show lenK\n                               ++ \" > len vector \" ++ show lenV\n\n-- This is not optimally implemented: @append1@ is costly compared\n-- to a @mconcat@ counterpart and @z@ is used twice without\n-- assigning it to a variable.\nconv1 :: IsScalar d r\n      => DualNumber d (Vector r) -> DualNumber d (Vector r)\n      -> DualNumber d (Vector r)\nconv1 ker@(D u _) vv@(D v _) =\n  let lenK = V.length u\n      lenV = V.length v\n      kerRev = reverse1 ker\n      z = konst1 0 (lenK - 1)\n      vvPadded = append1 z $ append1 vv z\n  in if lenK == 0\n     then konst1 0 lenV\n     else corr1 kerRev vvPadded\n\n-- No padding; remaining areas ignored.\nmaxPool1 :: IsScalar d r\n         => Int -> Int -> DualNumber d (Vector r) -> DualNumber d (Vector r)\nmaxPool1 ksize stride v@(D u _) =\n  let slices = [slice1 i ksize v | i <- [0, stride .. V.length u - ksize]]\n  in seq1 $ V.fromList $ map maximum0 slices\n\nsoftMaxActV :: DualMonad d r m\n            => DualNumber d (Vector r) -> m (DualNumber d (Vector r))\nsoftMaxActV d@(D u _) = do\n  expU <- returnLet $ exp d\n  let sumExpU = sumElements0 expU\n  -- This has to be let-bound, because it's used many times below.\n  recipSum <- returnLet $ recip sumExpU\n  returnLet $ konst1 recipSum (V.length u) * expU\n\n-- Note that this is equivalent to a composition of softMax and cross entropy\n-- only when @target@ is one-hot. Otherwise, results vary wildly. In our\n-- rendering of the MNIST data all labels are one-hot.\nlossSoftMaxCrossEntropyL\n  :: DualMonad d r m\n  => Matrix r\n  -> DualNumber d (Matrix r)\n  -> m (DualNumber d (Vector r))\nlossSoftMaxCrossEntropyL target (D u u') = do\n  let expU = exp (u - HM.scalar (HM.maxElement u))  -- vs exploding gradients\n      sumExpU = V.fromList $ map HM.sumElements $ HM.toColumns expU\n      recipSum = recip sumExpU\n      softMaxU = HM.asRow recipSum * expU\n                   -- this @asRow@ is safe; multiplied at once\n      scaled = D (negate $ log softMaxU * target)\n                 (dScale (softMaxU - target) u')\n  returnLet $ sumColumns1 scaled\n\n\n-- * Operations resulting in a matrix\n\n-- @2@ means rank two, so the dual component represents a matrix.\nfromRows2 :: IsScalar d r\n          => Data.Vector.Vector (DualNumber d (Vector r))\n          -> DualNumber d (Matrix r)\nfromRows2 v = D (HM.fromRows $ map (\\(D u _) -> u) $ V.toList v)\n                (dFromRows2 $ V.map (\\(D _ u') -> u') v)\n\nfromColumns2 :: IsScalar d r\n             => Data.Vector.Vector (DualNumber d (Vector r))\n             -> DualNumber d (Matrix r)\nfromColumns2 v = D (HM.fromRows $ map (\\(D u _) -> u) $ V.toList v)\n                   (dFromColumns2 $ V.map (\\(D _ u') -> u') v)\n\nkonst2 :: IsScalar d r => DualNumber d r -> (Int, Int) -> DualNumber d (Matrix r)\nkonst2 (D u u') sz = D (HM.konst u sz) (dKonst2 u' sz)\n\ntranspose2 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Matrix r)\ntranspose2 (D u u') = D (HM.tr' u) (dTranspose2 u')\n\n-- | Dense matrix-matrix product.\n--\n-- If @u@ is a m x n (number of rows x number of columns) matrix\n-- and @v@ is a n x p matrix then the result of @u <>! v@ is a m x p matrix.\ninfixr 8 <>!\n(<>!) :: IsScalar d r\n      => DualNumber d (Matrix r) -> DualNumber d (Matrix r)\n      -> DualNumber d (Matrix r)\n(<>!) (D u u') (D v v') = D (u HM.<> v) (dAdd (dMD_M2 u' v) (dM_MD2 u v'))\n\n-- | Dense matrix-matrix product with a constant matrix.\ninfixr 8 <>!!\n(<>!!) :: IsScalar d r\n       => DualNumber d (Matrix r) -> Matrix r\n       -> DualNumber d (Matrix r)\n(<>!!) (D u u') v = D (u HM.<> v) (dMD_M2 u' v)\n\nrowAppend2 :: IsScalar d r\n           => DualNumber d (Matrix r) -> DualNumber d (Matrix r)\n           -> DualNumber d (Matrix r)\nrowAppend2 (D u u') (D v v') =\n  D (u HM.=== v) (dRowAppend2 u' (HM.rows u) v')\n\ncolumnAppend2 :: IsScalar d r\n              => DualNumber d (Matrix r) -> DualNumber d (Matrix r)\n              -> DualNumber d (Matrix r)\ncolumnAppend2 (D u u') (D v v') =\n  D (u HM.||| v) (dColumnAppend2 u' (HM.cols u) v')\n\nrowSlice2 :: IsScalar d r\n          => Int -> Int -> DualNumber d (Matrix r)\n          -> DualNumber d (Matrix r)\nrowSlice2 i n (D u u') = D (HM.subMatrix (i, 0) (n, HM.cols u) u)\n                           (dRowSlice2 i n u' (HM.rows u))\n\ncolumnSlice2 :: IsScalar d r\n             => Int -> Int -> DualNumber d (Matrix r)\n             -> DualNumber d (Matrix r)\ncolumnSlice2 i n (D u u') = D (HM.subMatrix (0, i) (HM.rows u, n) u)\n                              (dColumnSlice2 i n u' (HM.rows u))\n\nasRow2 :: IsScalar d r\n       => DualNumber d (Vector r) -> Int -> DualNumber d (Matrix r)\nasRow2 (D u u') n = D (HM.fromRows $ replicate n u) (dAsRow2 u')\n\nasColumn2 :: IsScalar d r\n          => DualNumber d (Vector r) -> Int -> DualNumber d (Matrix r)\nasColumn2 (D u u') n = D (HM.fromColumns $ replicate n u) (dAsColumn2 u')\n\nfromX2 :: IsScalar d r => DualNumber d (OT.Array r) -> DualNumber d (Matrix r)\nfromX2 (D u u') = case OT.shapeL u of\n  [_, cols] -> D (HM.reshape cols $ OT.toVector u) (dFromX2 u')\n  dims -> error $ \"fromX2: the tensor has wrong dimensions \" ++ show dims\n\nfromS2 :: forall rows cols d r.\n          (KnownNat rows, KnownNat cols, IsScalar d r)\n       => DualNumber d (OS.Array '[rows, cols] r) -> DualNumber d (Matrix r)\nfromS2 (D u u') = D (HM.reshape (valueOf @cols) $ OS.toVector u) (dFromS2 u')\n\nflipud2 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Matrix r)\nflipud2 (D u u') = D (HM.flipud u) (dFlipud2 u')\n\nfliprl2 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Matrix r)\nfliprl2 (D u u') = D (HM.fliprl u) (dFliprl2 u')\n\nvectorSlices2 :: IsScalar d r\n              => Int -> DualNumber d (Vector r) -> DualNumber d (Matrix r)\nvectorSlices2 n vv@(D v _) =\n  fromRows2 $ V.fromList [slice1 i n vv | i <- [0 .. V.length v - n]]\n\nreshape2 :: IsScalar d r\n         => Int -> DualNumber d (Vector r) -> DualNumber d (Matrix r)\nreshape2 cols (D u u') = D (HM.reshape cols u) (dReshape2 cols u')\n\n-- TODO: This has list of matrices result instead of a cube tensor.\nmatrixSlices2 :: DualMonad d r m\n              => Int -> DualNumber d (Matrix r) -> m [DualNumber d (Matrix r)]\nmatrixSlices2 dr m@(D u _) = do\n  let (rows, cols) = HM.size u\n      n = dr * cols\n  v <- returnLet $ flatten1 m  -- used many times below\n  let f k = returnLet $ reshape2 cols $ slice1 (k * cols) n v\n  mapM f [0 .. rows - dr]\n\n-- Not optimal: matrix is constructed and destructed immediately,\n-- which is costly when evaluating delta expressions. The transposes\n-- may not be optimal, either. This goes down to individual deltas\n-- of scalars, which is horrible for performance. Unlike @corr1@\n-- this uses the slow dot product instead of the fast matrix-vector\n-- (or matrix-matrix) multiplication.\ncorr2 :: forall d r m. DualMonad d r m\n      => DualNumber d (Matrix r) -> DualNumber d (Matrix r)\n      -> m (DualNumber d (Matrix r))\ncorr2 ker@(D u _) m@(D v _) = do\n  let (rowsK, colsK) = HM.size u\n      (rowsM, colsM) = HM.size v\n      rr = rowsM - rowsK + 1\n      rc = colsM - colsK + 1\n  if | rowsK <= 0 || colsK <= 0 ->\n       error $ \"corr2: empty kernel not handled: \" ++ show (rowsK, colsK)\n     | rr <= 0 || rc <= 0 ->\n       error $ \"corr2: dim kernel \" ++ show (rowsK, colsK)\n               ++ \" > dim matrix \" ++ show (rowsM, colsM)\n     | otherwise -> do\n       kerTransV <- returnLet $ flatten1 (transpose2 ker)\n       let dotColSlices :: DualNumber d (Matrix r) -> m [DualNumber d r]\n           dotColSlices tm = do\n             ttm <- returnLet $ transpose2 tm\n             colSlices <- matrixSlices2 colsK ttm\n             let f :: DualNumber d (Matrix r) -> DualNumber d r\n                 f sm = kerTransV <.>! flatten1 sm\n             return $ map f colSlices\n       rowSlices <- matrixSlices2 rowsK m\n       dotSlicesOfSlices <- mapM dotColSlices rowSlices\n       returnLet $ reshape2 rc $ seq1 $ V.fromList $ concat dotSlicesOfSlices\n\nconv2 :: forall d r m. DualMonad d r m\n      => DualNumber d (Matrix r) -> DualNumber d (Matrix r)\n      -> m (DualNumber d (Matrix r))\nconv2 ker@(D u _) m@(D v _) = do\n  let (rowsK, colsK) = HM.size u\n      (rowsM, colsM) = HM.size v\n  if | rowsK <= 0 || colsK <= 0 ->\n       returnLet $ konst2 0 (rowsM + rowsK - 1, colsM + colsK - 1)\n     | otherwise -> do\n       let zRow = konst2 0 (rowsK - 1, colsM)\n           rowPadded = rowAppend2 zRow $ rowAppend2 m zRow\n           zCol = konst2 0 (rowsM + 2 * (rowsK - 1), colsK - 1)\n           padded = columnAppend2 zCol $ columnAppend2 rowPadded zCol\n       corr2 (fliprl2 . flipud2 $ ker) padded\n\nconv2' :: IsScalar d r\n       => DualNumber d (Matrix r) -> DualNumber d (Matrix r)\n       -> DualNumber d (Matrix r)\nconv2' (D u u') (D v v') = D (HM.conv2 u v) (dAdd (dConv2 u v') (dConv2 v u'))\n\n-- A variant with limited padding, corresponding to SAME padding\n-- from Tensorflow. Data size does not change with this padding.\n-- It also performs convolution wrt flipped kernel (and so saves\n-- on flipping it here), which makes no practical difference when\n-- the kernel is initialized randomly.\nconvSame2 :: forall d r m. DualMonad d r m\n          => DualNumber d (Matrix r) -> DualNumber d (Matrix r)\n          -> m (DualNumber d (Matrix r))\nconvSame2 ker@(D u _) m@(D v _) = do\n  let (rowsK, colsK) = HM.size u\n      (rowsM, colsM) = HM.size v\n  if | rowsK <= 0 || colsK <= 0 ->\n       returnLet $ konst2 0 (rowsM, colsM)\n     | otherwise -> do\n       let zRow = konst2 0 ((rowsK - 1) `div` 2, colsM)\n           rowPadded = rowAppend2 zRow $ rowAppend2 m zRow\n           zCol = konst2 0 (rowsM + rowsK - 1, (colsK - 1) `div` 2)\n           padded = columnAppend2 zCol $ columnAppend2 rowPadded zCol\n       corr2 ker padded\n\n-- No padding; remaining areas ignored.\nmaxPool2 :: forall d r m. DualMonad d r m\n         => Int -> Int -> DualNumber d (Matrix r) -> m (DualNumber d (Matrix r))\nmaxPool2 ksize stride m@(D u _) = do\n  let (rows, cols) = HM.size u\n      colsOut = cols `div` stride\n      resultRows = [0, stride .. rows - ksize]\n      resultCols = [0, stride .. cols - ksize]\n      resultCoords = [(r, c) | r <- resultRows, c <- resultCols]\n  v <- returnLet $ flatten1 m  -- used many times below\n  let getArea :: (Int, Int) -> DualNumber d (Vector r)\n      getArea (r0, c0) =\n        let getAreaAtRow r1 = append1 (slice1 (r1 * cols + c0) ksize v)\n        in foldr getAreaAtRow (seq1 V.empty) [r0 .. r0 + ksize - 1]\n      mins = map (maximum0 . getArea) resultCoords\n  returnLet $ reshape2 colsOut $ seq1 $ V.fromList mins\n\n\n-- * Operations resulting in an arbitrary untyped tensor\n\nkonstX :: IsScalar d r => DualNumber d r -> OT.ShapeL -> DualNumber d (OT.Array r)\nkonstX (D u u') sh = D (OT.constant sh u) (dKonstX u' sh)\n\nappendX :: IsScalar d r\n        => DualNumber d (OT.Array r) -> DualNumber d (OT.Array r)\n        -> DualNumber d (OT.Array r)\nappendX (D u u') (D v v') =\n  D (u `OT.append` v) (dAppendX u' (head $ OT.shapeL u) v')\n\nsliceX :: IsScalar d r\n       => Int -> Int -> DualNumber d (OT.Array r) -> DualNumber d (OT.Array r)\nsliceX i n (D u u') = D (OT.slice [(i, n)] u)\n                        (dSliceX i n u' (head $ OT.shapeL u))\n\nindexX :: IsScalar d r\n       => DualNumber d (OT.Array r) -> Int -> DualNumber d (OT.Array r)\nindexX (D u u') ix = D (OT.index u ix)\n                       (dIndexX u' ix (head $ OT.shapeL u))\n\nravelFromListX :: IsScalar d r\n               => [DualNumber d (OT.Array r)] -> DualNumber d (OT.Array r)\nravelFromListX ld =\n  let (lu, lu') = unzip $ map (\\(D u u') -> (u, u')) ld\n      sh = case lu of\n        u : _ -> length lu : OT.shapeL u\n        [] -> []\n  in D (OT.ravel $ OTB.fromList sh lu) (dRavelFromListX lu')\n\nunravelToListX :: IsScalar d r\n               => DualNumber d (OT.Array r) -> [DualNumber d (OT.Array r)]\nunravelToListX (D v v') = case OT.shapeL v of\n  k : _ ->\n    let g ix p = D p (dIndexX v' ix k)\n    in imap g $ OTB.toList $ OT.unravel v\n  [] -> error \"unravelToListX: wrong tensor dimensions\"  -- catch early\n\nmapX :: IsScalar d r\n     => (DualNumber d (OT.Array r) -> DualNumber d (OT.Array r))\n     -> DualNumber d (OT.Array r)\n     -> DualNumber d (OT.Array r)\nmapX f = ravelFromListX . map f . unravelToListX\n\nzipWithX :: IsScalar d r\n         => (DualNumber d (OT.Array r) -> DualNumber d (OT.Array r)\n             -> DualNumber d (OT.Array r))\n         -> DualNumber d (OT.Array r) -> DualNumber d (OT.Array r)\n         -> DualNumber d (OT.Array r)\nzipWithX f d e =\n  ravelFromListX $ zipWith f (unravelToListX d) (unravelToListX e)\n\nreshapeX :: IsScalar d r\n         => OT.ShapeL -> DualNumber d (OT.Array r) -> DualNumber d (OT.Array r)\nreshapeX sh' (D u u') = D (OT.reshape sh' u) (dReshapeX (OT.shapeL u) sh' u')\n\nfrom0X :: IsScalar d r => DualNumber d r -> DualNumber d (OT.Array r)\nfrom0X (D u u') = D (OT.scalar u) (dFrom0X u')\n\nfrom1X :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d (OT.Array r)\nfrom1X (D u u') = D (OT.fromVector [V.length u] u) (dFrom1X u')\n\nfrom2X :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (OT.Array r)\nfrom2X (D u u') = D (OT.fromVector [HM.rows u, HM.cols u] $ HM.flatten u)\n                    (dFrom2X u' (HM.cols u))\n\nfromSX :: forall sh d r. (IsScalar d r, OS.Shape sh)\n       => DualNumber d (OS.Array sh r) -> DualNumber d (OT.Array r)\nfromSX (D u u') = D (Data.Array.Convert.convert u) (dFromSX u')\n\n\n-- * Operations resulting in an arbitrary fully typed Shaped tensor\n\nkonstS :: (IsScalar d r, OS.Shape sh)\n       => DualNumber d r -> DualNumber d (OS.Array sh r)\nkonstS (D u u') = D (OS.constant u) (dKonstS u')\n\nappendS :: (KnownNat m, KnownNat n, IsScalar d r, OS.Shape sh)\n        => DualNumber d (OS.Array (m ': sh) r)\n        -> DualNumber d (OS.Array (n ': sh) r)\n        -> DualNumber d (OS.Array ((m + n) ': sh) r)\nappendS (D u u') (D v v') = D (u `OS.append` v) (dAppendS u' v')\n\nsliceS :: forall i n k rest d r.\n          (KnownNat i, KnownNat n, KnownNat k, IsScalar d r, OS.Shape rest)\n       => DualNumber d (OS.Array (i + n + k ': rest) r)\n       -> DualNumber d (OS.Array (n ': rest) r)\nsliceS (D u u') = D (OS.slice @'[ '(i, n) ] u)\n                    (dSliceS (Proxy :: Proxy i) Proxy u')\n\nindexS :: forall ix k rest d r.\n          (KnownNat ix, KnownNat k, IsScalar d r, OS.Shape rest)\n       => DualNumber d (OS.Array (ix + 1 + k ': rest) r)\n       -> DualNumber d (OS.Array rest r)\nindexS (D u u') = D (OS.index u (valueOf @ix))\n                    (dIndexS u' (Proxy :: Proxy ix))\n\nravelFromListS :: forall rest k d r.\n                  (KnownNat k, IsScalar d r, OS.Shape rest)\n               => [DualNumber d (OS.Array rest r)]\n               -> DualNumber d (OS.Array (k : rest) r)\nravelFromListS ld =\n  let (lu, lu') = unzip $ map (\\(D u u') -> (u, u')) ld\n  in D (OS.ravel $ OSB.fromList lu) (dRavelFromListS lu')\n\nunravelToListS :: forall k rest d r.\n                  (KnownNat k, IsScalar d r, OS.Shape rest)\n               => DualNumber d (OS.Array (k : rest) r)\n               -> [DualNumber d (OS.Array rest r)]\nunravelToListS (D v v') =\n  -- @dIndexS@ is rigid, with type-level bound-checking, so we have to switch\n  -- to @dIndexX@ for this function.\n  let g ix p = D p (dFromXS $ dIndexX (dFromSX v') ix (valueOf @k))\n  in imap g $ OSB.toList $ OS.unravel v\n\nmapS :: forall k sh1 sh d r. (KnownNat k, IsScalar d r, OS.Shape sh, OS.Shape sh1)\n     => (DualNumber d (OS.Array sh1 r) -> DualNumber d (OS.Array sh r))\n     -> DualNumber d (OS.Array (k : sh1) r)\n     -> DualNumber d (OS.Array (k : sh) r)\nmapS f = ravelFromListS . map f . unravelToListS\n\nmapMS :: forall k sh1 sh d r m.\n         (Monad m, KnownNat k, IsScalar d r, OS.Shape sh, OS.Shape sh1)\n      => (DualNumber d (OS.Array sh1 r) -> m (DualNumber d (OS.Array sh r)))\n      -> DualNumber d (OS.Array (k : sh1) r)\n      -> m (DualNumber d (OS.Array (k : sh) r))\nmapMS f d = do\n  let ld = unravelToListS d\n  ld2 <- mapM f ld\n  return $! ravelFromListS ld2\n\nzipWithS :: forall k sh1 sh2 sh d r.\n            ( KnownNat k, IsScalar d r, OS.Shape sh, OS.Shape sh1, OS.Shape sh2)\n         => (DualNumber d (OS.Array sh1 r) -> DualNumber d (OS.Array sh2 r)\n             -> DualNumber d (OS.Array sh r))\n         -> DualNumber d (OS.Array (k : sh1) r)\n         -> DualNumber d (OS.Array (k : sh2) r)\n         -> DualNumber d (OS.Array (k : sh) r)\nzipWithS f d e =\n  ravelFromListS $ zipWith f (unravelToListS d) (unravelToListS e)\n\nreshapeS :: (IsScalar d r, OS.Shape sh, OS.Shape sh', OS.Size sh ~ OS.Size sh')\n         => DualNumber d (OS.Array sh r) -> DualNumber d (OS.Array sh' r)\nreshapeS (D u u') = D (OS.reshape u) (dReshapeS u')\n\n-- TODO: generalize as broadcast or stretch\nasRowS :: forall k n d r. (IsScalar d r, KnownNat k, KnownNat n)\n       => DualNumber d (OS.Array '[k] r) -> DualNumber d (OS.Array '[n, k] r)\nasRowS d = from2S $ asRow2 (fromS1 d) (valueOf @n)\n\nasColumnS :: forall k n d r. (IsScalar d r, KnownNat k, KnownNat n)\n          => DualNumber d (OS.Array '[k] r) -> DualNumber d (OS.Array '[k, n] r)\nasColumnS d = from2S $ asColumn2 (fromS1 d) (valueOf @n)\n\nfrom0S :: IsScalar d r => DualNumber d r -> DualNumber d (OS.Array '[] r)\nfrom0S (D u u') = D (OS.scalar u) (dFrom0S u')\n\nfrom1S :: (KnownNat n, IsScalar d r)\n       => DualNumber d (Vector r) -> DualNumber d (OS.Array '[n] r)\nfrom1S (D u u') = D (OS.fromVector u) (dFrom1S u')\n\nfrom2S :: (KnownNat rows, KnownNat cols, IsScalar d r)\n       => DualNumber d (Matrix r) -> DualNumber d (OS.Array '[rows, cols] r)\nfrom2S (D u u') = D (OS.fromVector $ HM.flatten u) (dFrom2S Proxy u')\n\nfromXS :: (IsScalar d r, OS.Shape sh)\n       => DualNumber d (OT.Array r) -> DualNumber d (OS.Array sh r)\nfromXS (D u u') = D (Data.Array.Convert.convert u) (dFromXS u')\n\n-- TODO: generalize to arbitrary permutations of arbitrarily many ranks using https://hackage.haskell.org/package/orthotope/docs/Data-Array-ShapedS.html#v:transpose\ntranspose2S :: (IsScalar d r, KnownNat rows, KnownNat cols)\n            => DualNumber d (OS.Array '[rows, cols] r)\n            -> DualNumber d (OS.Array '[cols, rows] r)\ntranspose2S = from2S . transpose2 . fromS2\n\ninfixr 8 #>$\n(#>$) :: (IsScalar d r, KnownNat rows, KnownNat cols)\n      => DualNumber d (OS.Array '[rows, cols] r)\n      -> DualNumber d (OS.Array '[cols] r)\n      -> DualNumber d (OS.Array '[rows] r)\n(#>$) d e = from1S $ fromS2 d #>! fromS1 e\n\ninfixr 8 <>$\n(<>$) :: (IsScalar d r, KnownNat m, KnownNat n, KnownNat p)\n      => DualNumber d (OS.Array '[m, n] r)\n      -> DualNumber d (OS.Array '[n, p] r)\n      -> DualNumber d (OS.Array '[m, p] r)\n(<>$) d e = from2S $ fromS2 d <>! fromS2 e\n\nconv2S :: forall d r kheight_minus_1 kwidth_minus_1 in_height in_width.\n          ( KnownNat kheight_minus_1, KnownNat kwidth_minus_1\n          , KnownNat in_height, KnownNat in_width\n          , IsScalar d r )\n       => DualNumber d (OS.Array '[kheight_minus_1 + 1, kwidth_minus_1 + 1] r)\n       -> DualNumber d (OS.Array '[in_height, in_width] r)\n       -> DualNumber d (OS.Array '[ in_height + kheight_minus_1\n                                 , in_width + kwidth_minus_1 ] r)\nconv2S ker x = from2S $ conv2' (fromS2 ker) (fromS2 x)\n\n-- Convolution of many matrices at once. Some of the names of dimensions\n-- are from https://www.tensorflow.org/api_docs/python/tf/nn/conv2d\nconv24 :: forall kheight_minus_1 kwidth_minus_1\n                 out_channels in_height in_width batch_size in_channels d r.\n          ( KnownNat kheight_minus_1, KnownNat kwidth_minus_1\n          , KnownNat out_channels, KnownNat in_height, KnownNat in_width\n          , KnownNat batch_size, KnownNat in_channels\n          , IsScalar d r )\n       => DualNumber d (OS.Array '[ out_channels, in_channels\n                                 , kheight_minus_1 + 1, kwidth_minus_1 + 1 ] r)\n       -> DualNumber d (OS.Array '[batch_size, in_channels, in_height, in_width] r)\n       -> DualNumber d (OS.Array '[ batch_size, out_channels\n                                 , in_height + kheight_minus_1\n                                 , in_width + kwidth_minus_1 ] r)\nconv24 ker = mapS conv23 where\n  conv23 :: DualNumber d (OS.Array '[in_channels, in_height, in_width] r)\n         -> DualNumber d (OS.Array '[ out_channels\n                                   , in_height + kheight_minus_1\n                                   , in_width + kwidth_minus_1 ] r)\n  conv23 x = mapS (convFilters x) ker\n  convFilters\n    :: DualNumber d (OS.Array '[in_channels, in_height, in_width] r)\n    -> DualNumber d (OS.Array '[ in_channels\n                              , kheight_minus_1 + 1, kwidth_minus_1 + 1 ] r)\n    -> DualNumber d (OS.Array '[ in_height + kheight_minus_1\n                              , in_width + kwidth_minus_1 ] r)\n  convFilters x ker1 = sumOutermost $ zipWithS conv2S ker1 x\n  sumOutermost :: DualNumber d (OS.Array '[ in_channels\n                                         , in_height + kheight_minus_1\n                                         , in_width + kwidth_minus_1 ] r)\n               -> DualNumber d (OS.Array '[ in_height + kheight_minus_1\n                                         , in_width + kwidth_minus_1 ] r)\n  sumOutermost = sum . unravelToListS\n    -- slow; should go through Tensor2, or the Num instance should when possible\n\nmaxPool24\n  :: forall ksize_minus_1 stride in_height in_width batch_size channels d r m.\n     ( KnownNat ksize_minus_1, KnownNat stride\n     , KnownNat in_height, KnownNat in_width\n     , KnownNat batch_size, KnownNat channels\n     , 1 <= stride\n     , ksize_minus_1 <= in_height\n     , ksize_minus_1 <= in_width\n     , 1 <= in_height - ksize_minus_1 + stride\n     , 1 <= in_width - ksize_minus_1 + stride\n     , DualMonad d r m )\n     => DualNumber d (OS.Array '[batch_size, channels, in_height, in_width] r)\n     -> m (DualNumber d\n             (OS.Array '[ batch_size, channels\n                         , (in_height - ksize_minus_1) `DivRoundUp` stride\n                         , (in_width - ksize_minus_1) `DivRoundUp` stride ] r))\nmaxPool24 d = do\n  res <- mapMS (mapMS (fmap from2S\n                       . maxPool2 (valueOf @ksize_minus_1 + 1)\n                                  (valueOf @stride)\n                       . fromS2)) d\n  returnLet res\n\n\n-- * Operations creating delayed/outlined derivatives\n\n-- | The version of the @D@ constructor lazy in the second argument.\n-- To be used as in\n--\n-- > sinDelayed :: (Floating a, IsPrimal d a) => DualNumber d a -> DualNumber d a\n-- > sinDelayed (D u u') = delayD (sin u) (dScale (cos u) u')\n-- >\n-- > plusDelayed :: (Floating a, IsPrimal d a)\n-- >             => DualNumber d a -> DualNumber d a -> DualNumber d a\n-- > plusDelayed (D u u') (D v v') = delayD (u + v) (dAdd u' v')\n-- >\n-- > x ** (sinDelayed x `plusDelayed` (id2 $ id2 $ id2 $ konst1 (sumElements0 x) 2))\n--\n-- The outlining is lost when serializing or logging, unlike with @Out@,\n-- @Outline0@, etc.\n--\n-- Yet another incomparable variant that can't be serialized would be\n-- (illustrating with an example of a constructor at rank 0)\n--\n-- > FromParams0 (Domains -> Delta0 r)\n--\n-- that expects the initial parameters. But it's more troublesome\n-- than @Delay0@ both in implementation and usage.\ndelayD :: IsPrimal d a => a -> Dual d a -> DualNumber d a\ndelayD u ~u' = D u (dDelay u')\n\n-- | A wrapper type to delay/outline computation of the derivatives of the given\n-- primitive numeric function inside the dual component of the created dual\n-- number. The rule is that if all arguments of a function are wrapped\n-- in @Out@ then the function gets delayed. Inconsistent wrapping,\n-- e.g., only one of the arguments, leads to early type errors.\n--\n-- To be used as in\n--\n-- > x ** unOut (sin (Out x) + Out (id $ id $ id $ konst1 (sumElements0 x) 2))\n--\n-- which delays computing the dual component of sine and of addition\n-- (both in rank 1), but not of power, konst and sumElements. The last two\n-- can't be currently delayed, because only primitive numeric functions\n-- are supported (an attempt would not type-check).\nnewtype Out a = Out {unOut :: a}\n  deriving (Eq, Ord)\n\nreturnOut :: (DualMonad d r m, IsPrimalWithScalar d a r)\n          => Out (DualNumber d a) -> m (Out (DualNumber d a))\nreturnOut dOut = do\n  dvar <- returnLet $ unOut dOut\n  return $ Out dvar\n\ninstance (Num a, IsPrimal 'DModeGradient a, HasVariables a)\n         => Num (Out (DualNumber 'DModeGradient a)) where\n  Out (D u u') + Out (D v v') =\n    Out $ D (u + v) (dOutline PlusOut [u, v] [u', v'])\n  Out (D u u') - Out (D v v') =\n    Out $ D (u - v) (dOutline MinusOut [u, v] [u', v'])\n  Out (D u u') * Out (D v v') =\n    Out $ D (u * v) (dOutline TimesOut [u, v] [u', v'])\n  negate (Out (D v v')) = Out $ D (negate v) (dOutline NegateOut [v] [v'])\n  abs (Out (D v v')) = Out $ D (abs v) (dOutline AbsOut [v] [v'])\n  signum (Out (D v v')) = Out $ D (signum v) (dOutline SignumOut [v] [v'])\n  fromInteger = Out . constant . fromInteger\n\ninstance (Real a, IsPrimal 'DModeGradient a, HasVariables a)\n         => Real (Out (DualNumber 'DModeGradient a)) where\n  toRational = undefined  -- TODO?\n\ninstance (Fractional a, IsPrimal 'DModeGradient a, HasVariables a)\n         => Fractional (Out (DualNumber 'DModeGradient a)) where\n  Out (D u u') / Out (D v v') =\n    Out $ D (u / v) (dOutline DivideOut [u, v] [u', v'])\n  recip (Out (D v v')) = Out $ D (recip v) (dOutline RecipOut [v] [v'])\n  fromRational = Out . constant . fromRational\n\ninstance (Floating a, IsPrimal 'DModeGradient a, HasVariables a)\n         => Floating (Out (DualNumber 'DModeGradient a)) where\n  pi = Out $ constant pi\n  exp (Out (D u u')) = Out $ D (exp u) (dOutline ExpOut [u] [u'])\n  log (Out (D u u')) = Out $ D (log u) (dOutline LogOut [u] [u'])\n  sqrt (Out (D u u')) = Out $ D (sqrt u) (dOutline SqrtOut [u] [u'])\n  Out (D u u') ** Out (D v v') =\n    Out $ D (u ** v) (dOutline PowerOut [u, v] [u', v'])\n  logBase (Out (D u u')) (Out (D v v')) = Out $ D (logBase u v) (dOutline LogBaseOut [u, v] [u', v'])\n  sin (Out (D u u')) = Out $ D (sin u) (dOutline SinOut [u] [u'])\n  cos (Out (D u u')) = Out $ D (cos u) (dOutline CosOut [u] [u'])\n  tan (Out (D u u')) = Out $ D (tan u) (dOutline TanOut [u] [u'])\n  asin (Out (D u u')) = Out $ D (asin u) (dOutline AsinOut [u] [u'])\n  acos (Out (D u u')) = Out $ D (acos u) (dOutline AcosOut [u] [u'])\n  atan (Out (D u u')) = Out $ D (atan u) (dOutline AtanOut [u] [u'])\n  sinh (Out (D u u')) = Out $ D (sinh u) (dOutline SinhOut [u] [u'])\n  cosh (Out (D u u')) = Out $ D (cosh u) (dOutline CoshOut [u] [u'])\n  tanh (Out (D u u')) = Out $ D (tanh u) (dOutline TanhOut [u] [u'])\n  asinh (Out (D u u')) = Out $ D (asinh u) (dOutline AsinhOut [u] [u'])\n  acosh (Out (D u u')) = Out $ D (acosh u) (dOutline AcoshOut [u] [u'])\n  atanh (Out (D u u')) = Out $ D (atanh u) (dOutline AtanhOut [u] [u'])\n\ninstance (RealFrac a, IsPrimal 'DModeGradient a, HasVariables a)\n         => RealFrac (Out (DualNumber 'DModeGradient a)) where\n  properFraction = undefined\n    -- very low priority, since these are all extremely not continuous\n\ninstance (RealFloat a, IsPrimal 'DModeGradient a, HasVariables a)\n         => RealFloat (Out (DualNumber 'DModeGradient a)) where\n  atan2 (Out (D u u')) (Out (D v v')) =\n    Out $ D (atan2 u v) (dOutline Atan2Out [u, v] [u', v'])\n      -- we can be selective here and omit the other methods,\n      -- most of which don't even have a differentiable codomain\n\n\n-- * Busywork to let the derivatives mode ignore all outlining\n\n-- | Note that this should apply only when @d@ is @'DModeDerivative@.\n-- However, GHC can't tell that @d@ has only two cases. Therefore, we need\n-- to overgeneralize these definitions and mark them with @OVERLAPPABLE@\n-- or else GHC complains that not enough instances are given\n-- whenever type-checking code polymorphic on @d@.\ninstance {-# OVERLAPPABLE #-} (Num a, IsPrimal d a)\n                              => Num (Out (DualNumber d a)) where\n  Out d + Out e = Out (d + e)\n  Out d - Out e = Out (d - e)\n  Out d * Out e = Out (d * e)\n  negate (Out e) = Out (negate e)\n  abs (Out e) = Out (abs e)\n  signum (Out e) = Out (signum e)\n  fromInteger = Out . constant . fromInteger\n\ninstance {-# OVERLAPPABLE #-} (Real a, IsPrimal d a)\n                              => Real (Out (DualNumber d a)) where\n  toRational = undefined  -- TODO?\n\ninstance {-# OVERLAPPABLE #-} (Fractional a, IsPrimal d a)\n                              => Fractional (Out (DualNumber d a)) where\n  Out d / Out e = Out (d / e)\n  recip (Out e) = Out (recip e)\n  fromRational = Out . constant . fromRational\n\ninstance {-# OVERLAPPABLE #-} (Floating a, IsPrimal d a)\n                              => Floating (Out (DualNumber d a)) where\n  pi = Out $ constant pi\n  exp (Out d) = Out (exp d)\n  log (Out d) = Out (log d)\n  sqrt (Out d) = Out (sqrt d)\n  Out d ** Out e = Out (d ** e)\n  logBase (Out x) (Out y) = Out (logBase x y)\n  sin (Out d) = Out (sin d)\n  cos (Out d) = Out (cos d)\n  tan (Out d) = Out (tan d)\n  asin (Out d) = Out (asin d)\n  acos (Out d) = Out (acos d)\n  atan (Out d) = Out (atan d)\n  sinh (Out d) = Out (sinh d)\n  cosh (Out d) = Out (cosh d)\n  tanh (Out d) = Out (tanh d)\n  asinh (Out d) = Out (asinh d)\n  acosh (Out d) = Out (acosh d)\n  atanh (Out d) = Out (atanh d)\n\ninstance {-# OVERLAPPABLE #-} (RealFrac a, IsPrimal d a)\n                              => RealFrac (Out (DualNumber d a)) where\n  properFraction = undefined\n    -- very low priority, since these are all extremely not continuous\n\ninstance {-# OVERLAPPABLE #-} (RealFloat a, IsPrimal d a)\n                              => RealFloat (Out (DualNumber d a)) where\n  atan2 (Out d) (Out e) = Out (atan2 d e)\n", "meta": {"hexsha": "d3f2b0d14051e4c71d8db9df177cef3b5c1fc9e0", "size": 44544, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Core/DualNumber.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HordeAd/Core/DualNumber.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "src/HordeAd/Core/DualNumber.hs", "max_forks_repo_name": "Mikolaj/horde-ad", "max_forks_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9546769527, "max_line_length": 164, "alphanum_fraction": 0.6041891164, "num_tokens": 14336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45769072276987033}}
{"text": "module VoiceLeading.Theory where\n\nimport           VoiceLeading.Base\nimport           VoiceLeading.Helpers           ( rotate )\n\nimport           Data.List                      ( elemIndex )\nimport           Data.Maybe                     ( mapMaybe )\nimport           Data.Ratio\nimport           Data.Function.Memoize          ( memoize )\n\nimport           Data.Aeson\nimport qualified Data.Map                      as M\nimport qualified Data.Vector                   as V\nimport qualified Data.Vector.Unboxed           as VU\nimport qualified Data.Vector.Unboxed.Mutable   as VUM\n\nimport           Numeric.SpecFunctions          ( logBeta )\nimport qualified Control.Loop                  as L\n\n-- simple ad-hoc heuristic\n--------------------------\n\nmodal :: Int -> Int -> Int\nmodal i m = [0, 2, 4, 5, 7, 9, 11] !! mod (i + m) 7\n\ncMajor :: [Int]\ncMajor = [2, 2, 1, 2, 2, 2, 1]\n\nscale :: KeySig -> [Int]\nscale = memoize s\n where\n  s (KeySig root mode) =\n    scanl (\\a b -> (a + b) `mod` 12) root (init $ rotate mode cMajor)\n\nleadingTone :: KeySig -> Int\nleadingTone = memoize lt where lt (KeySig root _) = (root - 1) `mod` 12\n\nmajorChord :: [Int]\nmajorChord = [0, 4, 7, 10, 11, 2, 1, 5, 6, 9, 8, 3]\n\nminorChord :: [Int]\nminorChord = [0, 3, 7, 10, 2, 11, 1, 5, 6, 8, 9, 4]\n\n-- | Returns a pair of the estimated root and the \"chordness\" of the given set of pitches\nfindHarm :: [Int] -> (Int, Double)\nfindHarm []      = (0, 0)\nfindHarm pitches = testRoot [0 .. 11]\n where\n  ps = map (`mod` 12) pitches\n  indexVal :: Int -> Rational\n  indexVal i = 1 % (fromIntegral i + 1)\n  testChord chord tps = sum $ map val [0 .. maximum is]\n   where\n    is = mapMaybe (`elemIndex` chord) tps\n    val i = if i `elem` is then indexVal i else negate (indexVal i)\n  testRoot [] = (0, 0) -- just a catchall\n  testRoot (r : rs) =\n    let tps   = map ((`mod` 12) . (\\x -> x - r)) ps\n        score = max (testChord majorChord tps) (testChord minorChord tps)\n    in  testRoot' rs r score\n  testRoot' []       best score = (best, fromRational score)\n  testRoot' (r : rs) best score = if newScore > score\n    then testRoot' rs r newScore\n    else testRoot' rs best score\n   where\n    tps      = map ((`mod` 12) . (\\x -> x - r)) ps\n    newScore = max (testChord majorChord tps) (testChord minorChord tps)\n\n-- chord profiles\n-----------------\n\ntype Profile = (Double, VU.Vector Double)\ntype Profiles = V.Vector Profile\n\nloadProfiles :: FilePath -> IO (Maybe (M.Map String (M.Map Int Double)))\nloadProfiles = decodeFileStrict'\n\n-- | Returns a vector of profiles.\n-- Each profile is a pair of the total counts in the profile and the smoothed count vector.\nvectorizeProfiles :: M.Map String (M.Map Int Double) -> Profiles\nvectorizeProfiles profmap = V.fromList $ profList <$> M.elems profmap\n where\n  profList pm = (VU.sum lst, lst)\n    where lst = VU.fromList [ 1 + pm M.! i | i <- [0 .. 11] ]\n\nlogDirichletMultinomial :: Profile -> VU.Vector Double -> Double -> Double\nlogDirichletMultinomial (a0, as) xs n = num - denom\n where\n  l = VU.length xs\n  entry acc i = if xi > 0 then acc + log xi + logBeta (as VU.! i) xi else acc\n    where xi = xs VU.! i\n  num   = log n + logBeta a0 n\n  denom = L.forLoopFold 0 (< l) (+ 1) 0 entry\n\nmkChord :: Int -> [Int] -> VU.Vector Double\nmkChord r pitches = VU.create $ do\n  chord <- VUM.replicate 12 0\n  mapM_ (VUM.unsafeModify chord (+ 1) . (`mod` 12) . subtract r) pitches\n  pure chord\n\nmatchChordProfiles :: Profiles -> [Int] -> (Int, Double)\nmatchChordProfiles _        []      = (0, 0)\nmatchChordProfiles profiles pitches = (maxRoot, chordness / 0.3) -- normalize by maximum value\n where\n  roots = V.fromListN 12 [0 .. 11]\n  n     = fromIntegral $ length pitches\n  match chord prof = logDirichletMultinomial prof chord n\n  bestMatch r = V.maximum $ match (mkChord r pitches) <$> profiles\n  bestMatches = bestMatch <$> roots\n  maxRoot     = V.maxIndex bestMatches\n  chordness   = exp $ bestMatches V.! maxRoot\n", "meta": {"hexsha": "4a967136119aef1e06c3c97f94a305f978e133a0", "size": 3917, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/VoiceLeading/Theory.hs", "max_stars_repo_name": "DCMLab/part-writing", "max_stars_repo_head_hexsha": "14c1b6ad9e1975fe188291e188061d257ffd28cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-23T20:32:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-23T20:32:20.000Z", "max_issues_repo_path": "src/VoiceLeading/Theory.hs", "max_issues_repo_name": "DCMLab/part-writing", "max_issues_repo_head_hexsha": "14c1b6ad9e1975fe188291e188061d257ffd28cb", "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/VoiceLeading/Theory.hs", "max_forks_repo_name": "DCMLab/part-writing", "max_forks_repo_head_hexsha": "14c1b6ad9e1975fe188291e188061d257ffd28cb", "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.9732142857, "max_line_length": 94, "alphanum_fraction": 0.6142455961, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857831, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.45750981829504656}}
{"text": "{-# LANGUAGE FlexibleContexts, NamedFieldPuns #-}\n\nmodule School.App.CSVReader\n( csvToBinary\n, csvToMatrixDouble\n, parseDoubles\n, readCSV\n) where\n\nimport Conduit ((.|), ConduitM, mapC, mapMC, sourceFileBS)\nimport qualified Data.ByteString as BS\nimport Data.ByteString.Conversion (fromByteString)\nimport Data.Void (Void)\nimport qualified Data.Conduit.Binary as CB\nimport School.FileIO.AppIO (AppIO, maybeToAppIO)\nimport School.FileIO.FileType (FileType(..))\nimport School.FileIO.FileHeader (FileHeader(..))\nimport School.FileIO.MatrixSink (matrixDoubleSink)\nimport School.Utils.Constants (binComma)\nimport Numeric.LinearAlgebra ((><), Matrix)\n\nparseDoubles :: [BS.ByteString] -> Maybe [Double]\nparseDoubles = mapM fromByteString\n\nreadCSV :: FilePath -> ConduitM ()\n                                [BS.ByteString]\n                                AppIO\n                                ()\nreadCSV path = sourceFileBS path\n            .| CB.lines\n            .| mapC (BS.split binComma)\n\ncsvToMatrixDouble :: FileHeader\n                  -> ConduitM [BS.ByteString]\n                              (Matrix Double)\n                              AppIO\n                              ()\ncsvToMatrixDouble FileHeader { cols } =\n    mapC parseDoubles\n .| mapMC (maybeToAppIO \"Could not parse doubles\")\n .| mapC (1 >< cols)\n\ncsvToBinary :: FilePath\n            -> FilePath\n            -> FileHeader\n            -> ConduitM () Void AppIO ()\ncsvToBinary inPath outPath header  =\n    readCSV inPath\n .| csvToMatrixDouble header\n .| matrixDoubleSink SM header outPath\n", "meta": {"hexsha": "9fe8aae67c46d1c661547cf736dfaff2c94a9225", "size": 1550, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/School/App/CSVReader.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/School/App/CSVReader.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/School/App/CSVReader.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3921568627, "max_line_length": 58, "alphanum_fraction": 0.6290322581, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.45720629130793045}}
{"text": "module Main\n( main\n) where\n\nimport Debug.Trace\n\nimport Codec.Wav (importFile)\nimport Data.Audio (Audio(..))\n\nimport Data.Array.Unboxed (elems, assocs)\nimport Data.Array.IArray (Array(..), listArray, array)\nimport Data.Complex (magnitude)\nimport Data.Int (Int64, Int32, Int16, Int8)\n\nimport Common (importantFrequencies, breakChunks, slice)\nimport SongId (ft, mapChunk2Freqs, chunkIdentifier)\n\ntype WordSize = Int32\nchunkSize = 5000\nfile = \"\"\n\nmain :: IO ()\nmain = do\n    input <- importFile file\n    song_dft <- case input :: Either String (Audio WordSize) of\n        Left err -> do\n            putStrLn err\n            return [(array (0,0) [])]\n        Right a@(Audio _ _ samples) -> return (ft chunkSize samples)\n\n    putStrLn $ show (length song_dft) ++ \" \" ++ show (length . elems $ head song_dft)\n\n    let ys = map (mapChunk2Freqs . elems) song_dft\n\n    let freqs = importantFrequencies 5 (8 * chunkSize `quot` 50 `quot` 2)\n    let chunks = map (chunkIdentifier freqs) ys\n    foldl (\\acc x -> acc >> print x) (return ()) $ chunks\n", "meta": {"hexsha": "7f5372dac3ba65a3c9149c1cb320cf3b1a331bcc", "size": 1035, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "stnma7e/msk", "max_stars_repo_head_hexsha": "3f0c8a5c0090da79e743ea3c1f451e1eb7fcdd8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "stnma7e/msk", "max_issues_repo_head_hexsha": "3f0c8a5c0090da79e743ea3c1f451e1eb7fcdd8b", "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/Main.hs", "max_forks_repo_name": "stnma7e/msk", "max_forks_repo_head_hexsha": "3f0c8a5c0090da79e743ea3c1f451e1eb7fcdd8b", "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": 27.2368421053, "max_line_length": 85, "alphanum_fraction": 0.6657004831, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.45699623903433223}}
{"text": "{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}\n{-# OPTIONS_HADDOCK hide #-}\n-- |\n-- Module    : Numeric.SpecFunctions.Internal\n-- Copyright : (c) 2009, 2011, 2012 Bryan O'Sullivan\n-- License   : BSD3\n--\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : portable\n--\n-- Internal module with implementation of special functions.\nmodule Numeric.SpecFunctions.Internal\n    ( module Numeric.SpecFunctions.Internal\n    , Compat.log1p\n    , Compat.expm1\n    ) where\n\nimport Control.Applicative\nimport Data.Bits          ((.&.), (.|.), shiftR)\nimport Data.Int           (Int64)\nimport Data.Word          (Word)\nimport Data.Default.Class\nimport qualified Data.Vector.Unboxed as U\nimport           Data.Vector.Unboxed   ((!))\nimport Text.Printf\n\nimport Numeric.Polynomial.Chebyshev    (chebyshevBroucke)\nimport Numeric.Polynomial              (evaluatePolynomial, evaluatePolynomialL, evaluateEvenPolynomialL\n                                       ,evaluateOddPolynomialL)\nimport Numeric.RootFinding             (Root(..), newtonRaphson, NewtonParam(..), Tolerance(..))\nimport Numeric.Series\nimport Numeric.MathFunctions.Constants\nimport Numeric.SpecFunctions.Compat (log1p)\nimport qualified Numeric.SpecFunctions.Compat as Compat\n\n----------------------------------------------------------------\n-- Error function\n----------------------------------------------------------------\n\n-- | Error function.\n--\n-- \\[\n-- \\operatorname{erf}(x) = \\frac{2}{\\sqrt{\\pi}} \\int_{0}^{x} \\exp(-t^2) dt\n-- \\]\n--\n-- Function limits are:\n--\n-- \\[\n-- \\begin{aligned}\n--  &\\operatorname{erf}(-\\infty) &=& -1 \\\\\n--  &\\operatorname{erf}(0)       &=& \\phantom{-}\\,0 \\\\\n--  &\\operatorname{erf}(+\\infty) &=& \\phantom{-}\\,1 \\\\\n-- \\end{aligned}\n-- \\]\nerf :: Double -> Double\nerf = Compat.erf\n{-# INLINE erf #-}\n\n-- | Complementary error function.\n--\n-- \\[\n-- \\operatorname{erfc}(x) = 1 - \\operatorname{erf}(x)\n-- \\]\n--\n-- Function limits are:\n--\n-- \\[\n-- \\begin{aligned}\n--  &\\operatorname{erf}(-\\infty) &=&\\, 2 \\\\\n--  &\\operatorname{erf}(0)       &=&\\, 1 \\\\\n--  &\\operatorname{erf}(+\\infty) &=&\\, 0 \\\\\n-- \\end{aligned}\n-- \\]\nerfc :: Double -> Double\nerfc = Compat.erfc\n{-# INLINE erfc #-}\n\n-- | Inverse of 'erf'.\ninvErf :: Double -- ^ /p/ \u2208 [-1,1]\n       -> Double\ninvErf p\n  | p ==  1         = m_pos_inf\n  | p == -1         = m_neg_inf\n  | p < 1 && p > -1 = if p > 0 then r else -r\n  | otherwise       = error \"invErf: p must in [-1,1] range\"\n  where\n    -- We solve equation same as in invErfc. We're able to ruse same\n    -- Halley step by solving equation:\n    --   > pp - erf x = 0\n    -- instead of\n    --   > erf x - pp = 0\n    pp     = abs p\n    r      = step $ step $ guessInvErfc $ 1 - pp\n    step x = invErfcHalleyStep (pp - erf x) x\n\n-- | Inverse of 'erfc'.\ninvErfc :: Double -- ^ /p/ \u2208 [0,2]\n        -> Double\ninvErfc p\n  | p == 2        = m_neg_inf\n  | p == 0        = m_pos_inf\n  | p >0 && p < 2 = if p <= 1 then r else -r\n  | otherwise     = modErr $ \"invErfc: p must be in [0,2] got \" ++ show p\n  where\n    pp | p <= 1    = p\n       | otherwise = 2 - p\n    -- We perform 2 Halley steps in order to get to solution\n    r      = step $ step $ guessInvErfc pp\n    step x = invErfcHalleyStep (erfc x - pp) x\n\n-- Initial guess for invErfc & invErf\nguessInvErfc :: Double -> Double\nguessInvErfc p\n  = -0.70711 * ((2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t)\n  where\n    t = sqrt $ -2 * log( 0.5 * p)\n\n-- Halley step for solving invErfc\ninvErfcHalleyStep :: Double -> Double -> Double\ninvErfcHalleyStep err x\n  = x + err / (1.12837916709551257 * exp(-x * x) - x * err)\n\n----------------------------------------------------------------\n-- Gamma function\n----------------------------------------------------------------\n\ndata L = L {-# UNPACK #-} !Double {-# UNPACK #-} !Double\n\n-- | Compute the logarithm of the gamma function, \u0393(/x/).\n--\n-- \\[\n-- \\Gamma(x) = \\int_0^{\\infty}t^{x-1}e^{-t}\\,dt = (x - 1)!\n-- \\]\n--\n-- This implementation uses Lanczos approximation. It gives 14 or more\n-- significant decimal digits, except around /x/ = 1 and /x/ = 2,\n-- where the function goes to zero.\n--\n-- Returns &#8734; if the input is outside of the range (0 < /x/\n-- &#8804; 1e305).\nlogGamma :: Double -> Double\nlogGamma z\n  | z <= 0    = m_pos_inf\n  -- For very small values z we can just use Laurent expansion\n  | z < m_sqrt_eps = log (1/z - m_eulerMascheroni)\n  -- For z<1 we use recurrence. \u0393(z+1) = z\u00b7\u0393(z) Note that in order to\n  -- avoid precision loss we have to compute parameter to\n  -- approximations here:\n  --\n  -- > (z + 1) - 1 = z\n  -- > (z + 1) - 2 = z - 1\n  --\n  -- Simple passing (z + 1) to piecewise approxiations and computing\n  -- difference leads to bad loss of precision near 1.\n  -- This is reason lgamma1_15 & lgamma15_2 have three parameters\n  | z < 0.5   = lgamma1_15 z (z - 1) - log z\n  | z < 1     = lgamma15_2 z (z - 1) - log z\n  -- Piecewise polynomial approximations\n  | z <= 1.5  = lgamma1_15 (z - 1) (z - 2)\n  | z < 2     = lgamma15_2 (z - 1) (z - 2)\n  | z < 15    = lgammaSmall z\n  -- Otherwise we switch to Lanczos approximation\n  | otherwise = lanczosApprox z\n\n\n-- | Synonym for 'logGamma'. Retained for compatibility\nlogGammaL :: Double -> Double\nlogGammaL = logGamma\n{-# DEPRECATED logGammaL \"Use logGamma instead\" #-}\n\n\n\n-- Polynomial expansion used in interval (1,1.5]\n--\n-- > log\u0393(z) = (z-1)(z-2)(Y + R(z-1))\nlgamma1_15 :: Double -> Double -> Double\nlgamma1_15 zm1 zm2\n   = r * y + r * ( evaluatePolynomial zm1 tableLogGamma_1_15P\n                 / evaluatePolynomial zm1 tableLogGamma_1_15Q\n                 )\n   where\n     r = zm1 * zm2\n     y = 0.52815341949462890625\n\ntableLogGamma_1_15P,tableLogGamma_1_15Q :: U.Vector Double\ntableLogGamma_1_15P = U.fromList\n  [  0.490622454069039543534e-1\n  , -0.969117530159521214579e-1\n  , -0.414983358359495381969e0\n  , -0.406567124211938417342e0\n  , -0.158413586390692192217e0\n  , -0.240149820648571559892e-1\n  , -0.100346687696279557415e-2\n  ]\n{-# NOINLINE tableLogGamma_1_15P #-}\ntableLogGamma_1_15Q = U.fromList\n  [ 1\n  , 0.302349829846463038743e1\n  , 0.348739585360723852576e1\n  , 0.191415588274426679201e1\n  , 0.507137738614363510846e0\n  , 0.577039722690451849648e-1\n  , 0.195768102601107189171e-2\n  ]\n{-# NOINLINE tableLogGamma_1_15Q #-}\n\n\n\n-- Polynomial expansion used in interval (1.5,2)\n--\n-- > log\u0393(z) = (2-z)(1-z)(Y + R(2-z))\nlgamma15_2 :: Double -> Double -> Double\nlgamma15_2 zm1 zm2\n   = r * y + r * ( evaluatePolynomial (-zm2) tableLogGamma_15_2P\n                 / evaluatePolynomial (-zm2) tableLogGamma_15_2Q\n                 )\n   where\n     r = zm1 * zm2\n     y = 0.452017307281494140625\n\ntableLogGamma_15_2P,tableLogGamma_15_2Q :: U.Vector Double\ntableLogGamma_15_2P = U.fromList\n  [ -0.292329721830270012337e-1\n  ,  0.144216267757192309184e0\n  , -0.142440390738631274135e0\n  ,  0.542809694055053558157e-1\n  , -0.850535976868336437746e-2\n  ,  0.431171342679297331241e-3\n  ]\n{-# NOINLINE tableLogGamma_15_2P #-}\ntableLogGamma_15_2Q = U.fromList\n  [  1\n  , -0.150169356054485044494e1\n  ,  0.846973248876495016101e0\n  , -0.220095151814995745555e0\n  ,  0.25582797155975869989e-1\n  , -0.100666795539143372762e-2\n  , -0.827193521891290553639e-6\n  ]\n{-# NOINLINE tableLogGamma_15_2Q #-}\n\n\n\n-- Polynomial expansion used in interval (2,3)\n--\n-- > log\u0393(z) = (z - 2)(z + 1)(Y + R(z-2))\nlgamma2_3 :: Double -> Double\nlgamma2_3 z\n  = r * y + r * ( evaluatePolynomial zm2 tableLogGamma_2_3P\n                / evaluatePolynomial zm2 tableLogGamma_2_3Q\n                )\n  where\n    r   = zm2 * (z + 1)\n    zm2 = z - 2\n    y   = 0.158963680267333984375e0\n\n\ntableLogGamma_2_3P,tableLogGamma_2_3Q :: U.Vector Double\ntableLogGamma_2_3P = U.fromList\n  [ -0.180355685678449379109e-1\n  ,  0.25126649619989678683e-1\n  ,  0.494103151567532234274e-1\n  ,  0.172491608709613993966e-1\n  , -0.259453563205438108893e-3\n  , -0.541009869215204396339e-3\n  , -0.324588649825948492091e-4\n  ]\n{-# NOINLINE tableLogGamma_2_3P #-}\ntableLogGamma_2_3Q = U.fromList\n  [  1\n  ,  0.196202987197795200688e1\n  ,  0.148019669424231326694e1\n  ,  0.541391432071720958364e0\n  ,  0.988504251128010129477e-1\n  ,  0.82130967464889339326e-2\n  ,  0.224936291922115757597e-3\n  , -0.223352763208617092964e-6\n  ]\n{-# NOINLINE tableLogGamma_2_3Q #-}\n\n\n\n-- For small z we can just use Gamma function recurrence and reduce\n-- problem to interval [2,3] and use polynomial approximation\n-- there. Surpringly it gives very good precision\nlgammaSmall :: Double -> Double\nlgammaSmall = go 0\n  where\n    go acc z | z < 3     = acc + lgamma2_3 z\n             | otherwise = go (acc + log zm1) zm1\n             where\n               zm1 = z - 1\n\n\n-- Lanczos approximation for gamma function.\n--\n-- > \u0393(z) = sqrt(2\u03c0)(z + g - 0.5)^(z - 0.5)\u00b7exp{-(z + g - 0.5)}\u00b7A_g(z)\n--\n-- Coeffients are taken from boost. Constants are absorbed into\n-- polynomial's coefficients.\nlanczosApprox :: Double -> Double\nlanczosApprox z\n  = (log (z + g - 0.5) - 1) * (z - 0.5)\n  + log (evalRatio tableLanczos z)\n  where\n    g = 6.024680040776729583740234375\n\ntableLanczos :: U.Vector (Double,Double)\n{-# NOINLINE tableLanczos #-}\ntableLanczos = U.fromList\n  [ (56906521.91347156388090791033559122686859    , 0)\n  , (103794043.1163445451906271053616070238554    , 39916800)\n  , (86363131.28813859145546927288977868422342    , 120543840)\n  , (43338889.32467613834773723740590533316085    , 150917976)\n  , (14605578.08768506808414169982791359218571    , 105258076)\n  , (3481712.15498064590882071018964774556468     , 45995730)\n  , (601859.6171681098786670226533699352302507    , 13339535)\n  , (75999.29304014542649875303443598909137092    , 2637558)\n  , (6955.999602515376140356310115515198987526    , 357423)\n  , (449.9445569063168119446858607650988409623    , 32670)\n  , (19.51992788247617482847860966235652136208    , 1925)\n  , (0.5098416655656676188125178644804694509993   , 66)\n  , (0.006061842346248906525783753964555936883222 , 1)\n  ]\n\n-- Evaluate rational function. Polynomials in both numerator and\n-- denominator must have same order. Function seems to be too specific\n-- so it's not exposed\n--\n-- Special care taken in order to avoid overflow for large values of x\nevalRatio :: U.Vector (Double,Double) -> Double -> Double\nevalRatio coef x\n  | x > 1     = fini $ U.foldl' stepL (L 0 0) coef\n  | otherwise = fini $ U.foldr' stepR (L 0 0) coef\n  where\n    fini (L num den) = num / den\n    stepR (a,b) (L num den) = L (num * x  + a) (den * x  + b)\n    stepL (L num den) (a,b) = L (num * rx + a) (den * rx + b)\n    rx = recip x\n\n\n\n-- |\n-- Compute the log gamma correction factor for Stirling\n-- approximation for @x@ &#8805; 10.  This correction factor is\n-- suitable for an alternate (but less numerically accurate)\n-- definition of 'logGamma':\n--\n-- \\[\n-- \\log\\Gamma(x) = \\frac{1}{2}\\log(2\\pi) + (x-\\frac{1}{2})\\log x - x + \\operatorname{logGammaCorrection}(x)\n-- \\]\nlogGammaCorrection :: Double -> Double\nlogGammaCorrection x\n    | x < 10    = m_NaN\n    | x < big   = chebyshevBroucke (t * t * 2 - 1) coeffs / x\n    | otherwise = 1 / (x * 12)\n  where\n    big    = 94906265.62425156\n    t      = 10 / x\n    coeffs = U.fromList [\n               0.1666389480451863247205729650822e+0,\n              -0.1384948176067563840732986059135e-4,\n               0.9810825646924729426157171547487e-8,\n              -0.1809129475572494194263306266719e-10,\n               0.6221098041892605227126015543416e-13,\n              -0.3399615005417721944303330599666e-15,\n               0.2683181998482698748957538846666e-17\n             ]\n\n\n\n-- | Compute the normalized lower incomplete gamma function\n-- \u03b3(/z/,/x/). Normalization means that \u03b3(/z/,\u221e)=1\n--\n-- \\[\n-- \\gamma(z,x) = \\frac{1}{\\Gamma(z)}\\int_0^{x}t^{z-1}e^{-t}\\,dt\n-- \\]\n--\n-- Uses Algorithm AS 239 by Shea.\nincompleteGamma :: Double       -- ^ /z/ \u2208 (0,\u221e)\n                -> Double       -- ^ /x/ \u2208 (0,\u221e)\n                -> Double\n-- Notation used:\n--  + P(a,x) - regularized lower incomplete gamma\n--  + Q(a,x) - regularized upper incomplete gamma\nincompleteGamma a x\n  | a <= 0 || x < 0 = error\n     $ \"incompleteGamma: Domain error z=\" ++ show a ++ \" x=\" ++ show x\n  | x == 0          = 0\n  | x == m_pos_inf  = 1\n  -- For very small x we use following expansion for P:\n  --\n  -- See http://functions.wolfram.com/GammaBetaErf/GammaRegularized/06/01/05/01/01/\n  | x < sqrt m_epsilon && a > 1\n    = x**a / a / exp (logGamma a) * (1 - a*x / (a + 1))\n  | x < 0.5 = case () of\n    _| (-0.4)/log x < a  -> taylorSeriesP\n     | otherwise         -> taylorSeriesComplQ\n  | x < 1.1 = case () of\n    _| 0.75*x < a        -> taylorSeriesP\n     | otherwise         -> taylorSeriesComplQ\n  | a > 20 && useTemme    = uniformExpansion\n  | x - (1 / (3 * x)) < a = taylorSeriesP\n  | otherwise             = contFraction\n  where\n    mu = (x - a) / a\n    useTemme = (a > 200 && 20/a > mu*mu)\n            || (abs mu < 0.4)\n    -- Gautschi's algorithm.\n    --\n    -- Evaluate series for P(a,x). See [Temme1994] Eq. 5.5 and [NOTE:\n    -- incompleteGamma.taylorP]\n    factorP\n      | a < 10     = x ** a\n                   / (exp x * exp (logGamma (a + 1)))\n      | a < 1182.5 = (x * exp 1 / a) ** a\n                   / exp x\n                   / sqrt (2*pi*a)\n                   / exp (logGammaCorrection a)\n      | otherwise  = (x * exp 1 / a * exp (-x/a)) ** a\n                   / sqrt (2*pi*a)\n                   / exp (logGammaCorrection a)\n    taylorSeriesP\n      = sumPowerSeries x (scanSequence (/) 1 $ enumSequenceFrom (a+1))\n      * factorP\n    -- Series for 1-Q(a,x). See [Temme1994] Eq. 5.5\n    taylorSeriesComplQ\n      = sumPowerSeries (-x) (scanSequence (/) 1 (enumSequenceFrom 1) / enumSequenceFrom a)\n      * x**a / exp(logGamma a)\n    -- Legendre continued fractions\n    contFraction = 1 - ( exp ( log x * a - x - logGamma a )\n                       / evalContFractionB frac\n                       )\n      where\n        frac = (\\k -> (k*(a-k), x - a + 2*k + 1)) <$> enumSequenceFrom 0\n    -- Evaluation based on uniform expansions. See [Temme1994] 5.2\n    uniformExpansion =\n      let -- Coefficients f_m in paper\n          fm :: U.Vector Double\n          fm = U.fromList [ 1.00000000000000000000e+00\n                          ,-3.33333333333333370341e-01\n                          , 8.33333333333333287074e-02\n                          ,-1.48148148148148153802e-02\n                          , 1.15740740740740734316e-03\n                          , 3.52733686067019369930e-04\n                          ,-1.78755144032921825352e-04\n                          , 3.91926317852243766954e-05\n                          ,-2.18544851067999240532e-06\n                          ,-1.85406221071515996597e-06\n                          , 8.29671134095308545622e-07\n                          ,-1.76659527368260808474e-07\n                          , 6.70785354340149841119e-09\n                          , 1.02618097842403069078e-08\n                          ,-4.38203601845335376897e-09\n                          , 9.14769958223679020897e-10\n                          ,-2.55141939949462514346e-11\n                          ,-5.83077213255042560744e-11\n                          , 2.43619480206674150369e-11\n                          ,-5.02766928011417632057e-12\n                          , 1.10043920319561347525e-13\n                          , 3.37176326240098513631e-13\n                          ]\n          y   = - log1pmx mu\n          eta = sqrt (2 * y) * signum mu\n          -- Evaluate S_\u03b1 (Eq. 5.9)\n          loop !_  !_  u 0 = u\n          loop bm1 bm0 u i = let t  = (fm ! i) + (fromIntegral i + 1)*bm1 / a\n                                 u' = eta * u + t\n                             in  loop bm0 t u' (i-1)\n          s_a = let n = U.length fm\n                in  loop (fm ! (n-1)) (fm ! (n-2)) 0 (n-3)\n                  / exp (logGammaCorrection a)\n      in 1/2 * erfc(-eta*sqrt(a/2)) - exp(-(a*y)) / sqrt (2*pi*a) * s_a\n\n\n\n-- Adapted from Numerical Recipes \u00a76.2.1\n\n-- | Inverse incomplete gamma function. It's approximately inverse of\n--   'incompleteGamma' for the same /z/. So following equality\n--   approximately holds:\n--\n-- > invIncompleteGamma z . incompleteGamma z \u2248 id\ninvIncompleteGamma :: Double    -- ^ /z/ \u2208 (0,\u221e)\n                   -> Double    -- ^ /p/ \u2208 [0,1]\n                   -> Double\ninvIncompleteGamma a p\n  | a <= 0         =\n      modErr $ printf \"invIncompleteGamma: a must be positive. a=%g p=%g\" a p\n  | p < 0 || p > 1 =\n      modErr $ printf \"invIncompleteGamma: p must be in [0,1] range. a=%g p=%g\" a p\n  | p == 0         = 0\n  | p == 1         = 1 / 0\n  | otherwise      = loop 0 guess\n  where\n    -- Solve equation \u03b3(a,x) = p using Halley method\n    loop :: Int -> Double -> Double\n    loop i x\n      | i >= 12           = x'\n      -- For small s derivative becomes approximately 1/x*exp(-x) and\n      -- skyrockets for small x. If it happens correct answer is 0.\n      | isInfinite f'     = 0\n      | abs dx < eps * x' = x'\n      | otherwise         = loop (i + 1) x'\n      where\n        -- Value of \u03b3(a,x) - p\n        f    = incompleteGamma a x - p\n        -- d\u03b3(a,x)/dx\n        f'   | a > 1     = afac * exp( -(x - a1) + a1 * (log x - lna1))\n             | otherwise = exp( -x + a1 * log x - gln)\n        u    = f / f'\n        -- Halley correction to Newton-Rapson step\n        corr = u * (a1 / x - 1)\n        dx   = u / (1 - 0.5 * min 1.0 corr)\n        -- New approximation to x\n        x'   | x < dx    = 0.5 * x -- Do not go below 0\n             | otherwise = x - dx\n    -- Calculate inital guess for root\n    guess\n      --\n      | a > 1   =\n         let t  = sqrt $ -2 * log(if p < 0.5 then p else 1 - p)\n             x1 = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t\n             x2 = if p < 0.5 then -x1 else x1\n         in max 1e-3 (a * (1 - 1/(9*a) - x2 / (3 * sqrt a)) ** 3)\n      -- For a <= 1 use following approximations:\n      --   \u03b3(a,1) \u2248 0.253a + 0.12a\u00b2\n      --\n      --   \u03b3(a,x) \u2248 \u03b3(a,1)\u00b7x^a                               x <  1\n      --   \u03b3(a,x) \u2248 \u03b3(a,1) + (1 - \u03b3(a,1))(1 - exp(1 - x))    x >= 1\n      | otherwise =\n         let t = 1 - a * (0.253 + a*0.12)\n         in if p < t\n            then (p / t) ** (1 / a)\n            else 1 - log( 1 - (p-t) / (1-t))\n    -- Constants\n    a1   = a - 1\n    lna1 = log a1\n    afac = exp( a1 * (lna1 - 1) - gln )\n    gln  = logGamma a\n    eps  = 1e-8\n\n\n\n----------------------------------------------------------------\n-- Beta function\n----------------------------------------------------------------\n\n-- | Compute the natural logarithm of the beta function.\n--\n-- \\[\n-- B(a,b) = \\int_0^1 t^{a-1}(1-t)^{b-1}\\,dt = \\frac{\\Gamma(a)\\Gamma(b)}{\\Gamma(a+b)}\n-- \\]\nlogBeta\n  :: Double                     -- ^ /a/ > 0\n  -> Double                     -- ^ /b/ > 0\n  -> Double\nlogBeta a b\n  | p < 0     = m_NaN\n  | p == 0    = m_pos_inf\n  | p >= 10   = allStirling\n  | q >= 10   = twoStirling\n  -- This order of summands marginally improves precision\n  | otherwise = logGamma p + (logGamma q - logGamma pq)\n  where\n    p   = min a b\n    q   = max a b\n    ppq = p / pq\n    pq  = p + q\n    -- When both parameters are large than 10 we can use Stirling\n    -- approximation with correction. It's more precise than sum of\n    -- logarithms of gamma functions\n    allStirling\n      = log q * (-0.5)\n      + m_ln_sqrt_2_pi\n      + logGammaCorrection p\n      + (logGammaCorrection q - logGammaCorrection pq)\n      + (p - 0.5) * log ppq\n      + q * log1p(-ppq)\n    -- Otherwise only two of three gamma functions use Stirling\n    -- approximation\n    twoStirling\n      = logGamma p\n      + (logGammaCorrection q - logGammaCorrection pq)\n      + p\n      - p * log pq\n      + (q - 0.5) * log1p(-ppq)\n\n\n-- | Regularized incomplete beta function.\n--\n-- \\[\n-- I(x;a,b) = \\frac{1}{B(a,b)} \\int_0^x t^{a-1}(1-t)^{b-1}\\,dt\n-- \\]\n--\n-- Uses algorithm AS63 by Majumder and Bhattachrjee and quadrature\n-- approximation for large /p/ and /q/.\nincompleteBeta :: Double -- ^ /a/ > 0\n               -> Double -- ^ /b/ > 0\n               -> Double -- ^ /x/, must lie in [0,1] range\n               -> Double\nincompleteBeta p q = incompleteBeta_ (logBeta p q) p q\n\n-- | Regularized incomplete beta function. Same as 'incompleteBeta'\n-- but also takes logarithm of beta function as parameter.\nincompleteBeta_ :: Double -- ^ logarithm of beta function for given /p/ and /q/\n                -> Double -- ^ /a/ > 0\n                -> Double -- ^ /b/ > 0\n                -> Double -- ^ /x/, must lie in [0,1] range\n                -> Double\nincompleteBeta_ beta p q x\n  | p <= 0 || q <= 0            =\n      modErr $ printf \"incompleteBeta_: p <= 0 || q <= 0. p=%g q=%g x=%g\" p q x\n  | x <  0 || x >  1 || isNaN x =\n      modErr $ printf \"incompleteBeta_: x out of [0,1] range. p=%g q=%g x=%g\" p q x\n  | x == 0 || x == 1            = x\n  | p >= (p+q) * x   = incompleteBetaWorker beta p q x\n  | otherwise        = 1 - incompleteBetaWorker beta q p (1 - x)\n\n\n-- Approximation of incomplete beta by quandrature.\n--\n-- Note that x =< p/(p+q)\nincompleteBetaApprox :: Double -> Double -> Double -> Double -> Double\nincompleteBetaApprox beta p q x\n  | ans > 0   = 1 - ans\n  | otherwise = -ans\n  where\n    -- Constants\n    p1    = p - 1\n    q1    = q - 1\n    mu    = p / (p + q)\n    lnmu  = log     mu\n    lnmuc = log1p (-mu)\n    -- Upper limit for integration\n    xu = max 0 $ min (mu - 10*t) (x - 5*t)\n       where\n         t = sqrt $ p*q / ( (p+q) * (p+q) * (p + q + 1) )\n    -- Calculate incomplete beta by quadrature\n    go y w = let t = x + (xu - x) * y\n             in  w * exp( p1 * (log t - lnmu) + q1 * (log(1-t) - lnmuc) )\n    s   = U.sum $ U.zipWith go coefY coefW\n    ans = s * (xu - x) * exp( p1 * lnmu + q1 * lnmuc - beta )\n\n\n-- Worker for incomplete beta function. It is separate function to\n-- avoid confusion with parameter during parameter swapping\nincompleteBetaWorker :: Double -> Double -> Double -> Double -> Double\nincompleteBetaWorker beta p q x\n  -- For very large p and q this method becomes very slow so another\n  -- method is used.\n  | p > 3000 && q > 3000 = incompleteBetaApprox beta p q x\n  | otherwise            = loop (p+q) (truncate $ q + cx * (p+q)) 1 1 1\n  where\n    -- Constants\n    eps = 1e-15\n    cx  = 1 - x\n    -- Common multiplies for expansion. Accurate calculation is a bit\n    -- tricky. Performing calculation in log-domain leads to slight\n    -- loss of precision for small x, while using ** prone to\n    -- underflows.\n    --\n    -- If either beta function of x**p\u00b7(1-x)**(q-1) underflows we\n    -- switch to log domain. It could waste work but there's no easy\n    -- switch criterion.\n    factor\n      | beta < m_min_log || prod < m_tiny = exp( p * log x + (q - 1) * log cx - beta)\n      | otherwise                         = prod / exp beta\n      where\n        prod =  x**p * cx**(q - 1)\n    -- Soper's expansion of incomplete beta function\n    loop !psq (ns :: Int) ai term betain\n      | done      = betain' * factor / p\n      | otherwise = loop psq' (ns - 1) (ai + 1) term' betain'\n      where\n        -- New values\n        term'   = term * fact / (p + ai)\n        betain' = betain + term'\n        fact | ns >  0   = (q - ai) * x/cx\n             | ns == 0   = (q - ai) * x\n             | otherwise = psq * x\n        -- Iterations are complete\n        done = db <= eps && db <= eps*betain' where db = abs term'\n        psq' = if ns < 0 then psq + 1 else psq\n\n\n\n-- | Compute inverse of regularized incomplete beta function. Uses\n-- initial approximation from AS109, AS64 and Halley method to solve\n-- equation.\ninvIncompleteBeta :: Double     -- ^ /a/ > 0\n                  -> Double     -- ^ /b/ > 0\n                  -> Double     -- ^ /x/ \u2208 [0,1]\n                  -> Double\ninvIncompleteBeta p q a\n  | p <= 0 || q <= 0 =\n      modErr $ printf \"invIncompleteBeta p <= 0 || q <= 0.  p=%g q=%g a=%g\" p q a\n  | a <  0 || a >  1 =\n      modErr $ printf \"invIncompleteBeta x must be in [0,1].  p=%g q=%g a=%g\" p q a\n  | a == 0 || a == 1 = a\n  | otherwise        = invIncompleteBetaWorker (logBeta p q) p q  a\n\n\ninvIncompleteBetaWorker :: Double -> Double -> Double -> Double -> Double\ninvIncompleteBetaWorker beta a b p = loop (0::Int) (invIncBetaGuess beta a b p)\n  where\n    a1 = a - 1\n    b1 = b - 1\n    -- Solve equation using Halley method\n    loop !i !x\n      -- We cannot continue at this point so we simply return `x'\n      | x == 0 || x == 1             = x\n      -- When derivative becomes infinite we cannot continue\n      -- iterations. It can only happen in vicinity of 0 or 1. It's\n      -- hardly possible to get good answer in such circumstances but\n      -- `x' is already reasonable.\n      | isInfinite f'                = x\n      -- Iterations limit reached. Most of the time solution will\n      -- converge to answer because of discreteness of Double. But\n      -- solution have good precision already.\n      | i >= 10                      = x\n      -- Solution converges\n      | abs dx <= 16 * m_epsilon * x = x'\n      | otherwise                    = loop (i+1) x'\n      where\n        -- Calculate Halley step.\n        f   = incompleteBeta_ beta a b x - p\n        f'  = exp $ a1 * log x + b1 * log1p (-x) - beta\n        u   = f / f'\n        -- We bound Halley correction to Newton-Raphson to (-1,1) range\n        corr | d > 1     = 1\n             | d < -1    = -1\n             | isNaN d   = 0\n             | otherwise = d\n          where\n            d = u * (a1 / x - b1 / (1 - x))\n        dx  = u / (1 - 0.5 * corr)\n        -- Next approximation. If Halley step leads us out of [0,1]\n        -- range we revert to bisection.\n        x'  | z < 0     = x / 2\n            | z > 1     = (x + 1) / 2\n            | otherwise = z\n            where z = x - dx\n\n\n-- Calculate initial guess for inverse incomplete beta function.\ninvIncBetaGuess :: Double -> Double -> Double -> Double -> Double\n-- Calculate initial guess. for solving equation for inverse incomplete beta.\n-- It's really hodgepodge of different approximations accumulated over years.\n--\n-- Equations are referred to by name of paper and number e.g. [AS64 2]\n-- In AS64 papers equations are not numbered so they are refered to by\n-- number of appearance starting from definition of incomplete beta.\ninvIncBetaGuess beta a b p\n  -- If both a and b are less than 1 incomplete beta have inflection\n  -- point.\n  --\n  -- > x = (1 - a) / (2 - a - b)\n  --\n  -- We approximate incomplete beta by neglecting one of factors under\n  -- integral and then rescaling result of integration into [0,1]\n  -- range.\n  | a < 1 && b < 1 =\n    let x_infl = (1 - a) / (2 - a - b)\n        p_infl = incompleteBeta a b x_infl\n        x | p < p_infl = let xg = (a * p     * exp beta) ** (1/a) in xg / (1+xg)\n          | otherwise  = let xg = (b * (1-p) * exp beta) ** (1/b) in 1 - xg/(1+xg)\n    in x\n  -- If both a and b larger or equal that 1 but not too big we use\n  -- same approximation as above but calculate it a bit differently\n  | a+b <= 6 && a>1 && b>1 =\n    let x_infl = (a - 1) / (a + b - 2)\n        p_infl = incompleteBeta a b x_infl\n        x | p < p_infl = exp ((log(p * a) + beta) / a)\n          | otherwise  = 1 - exp((log((1-p) * b) + beta) / b)\n    in x\n  -- For small a and not too big b we use approximation from boost.\n  | b < 5 && a <= 1 =\n    let x | p**(1/a) < 0.5 = (p * a * exp beta) ** (1/a)\n          | otherwise      = 1 - (1 - p ** (b * exp beta))**(1/b)\n    in x\n  -- When a>>b and both are large approximation from [Temme1992],\n  -- section 4 \"the incomplete gamma function case\" used. In this\n  -- region it greatly improves over other approximation (AS109, AS64,\n  -- \"Numerical Recipes\")\n  --\n  -- FIXME: It could be used when b>>a too but it require inverse of\n  --        upper incomplete gamma to be precise enough. In current\n  --        implementation it loses precision in horrible way (40\n  --        order of magnitude off for sufficiently small p)\n  | a+b > 5 &&  a/b > 4 =\n    let -- Calculate initial approximation to eta using eq 4.1\n        eta0 = invIncompleteGamma b (1-p) / a\n        mu   = b / a            -- Eq. 4.3\n        -- A lot of helpers for calculation of\n        w    = sqrt(1 + mu)     -- Eq. 4.9\n        w_2  = w * w\n        w_3  = w_2 * w\n        w_4  = w_2 * w_2\n        w_5  = w_3 * w_2\n        w_6  = w_3 * w_3\n        w_7  = w_4 * w_3\n        w_8  = w_4 * w_4\n        w_9  = w_5 * w_4\n        w_10 = w_5 * w_5\n        d    = eta0 - mu\n        d_2  = d * d\n        d_3  = d_2 * d\n        d_4  = d_2 * d_2\n        w1   = w + 1\n        w1_2 = w1 * w1\n        w1_3 = w1 * w1_2\n        w1_4 = w1_2 * w1_2\n        -- Evaluation of eq 4.10\n        e1 = (w + 2) * (w - 1) / (3 * w)\n           + (w_3 + 9 * w_2 + 21 * w + 5) * d\n             / (36 * w_2 * w1)\n           - (w_4 - 13 * w_3 + 69 * w_2 + 167 * w + 46) * d_2\n             / (1620 * w1_2 * w_3)\n           - (7 * w_5 + 21 * w_4 + 70 * w_3 + 26 * w_2 - 93 * w - 31) * d_3\n             / (6480 * w1_3 * w_4)\n           - (75 * w_6 + 202 * w_5 + 188 * w_4 - 888 * w_3 - 1345 * w_2 + 118 * w + 138) * d_4\n             / (272160 * w1_4 * w_5)\n        e2 = (28 * w_4 + 131 * w_3 + 402 * w_2 + 581 * w + 208) * (w - 1)\n             / (1620 * w1 * w_3)\n           - (35 * w_6 - 154 * w_5 - 623 * w_4 - 1636 * w_3 - 3983 * w_2 - 3514 * w - 925) * d\n             / (12960 * w1_2 * w_4)\n           - ( 2132 * w_7 + 7915 * w_6 + 16821 * w_5 + 35066 * w_4 + 87490 * w_3\n             + 141183 * w_2 + 95993 * w + 21640\n             ) * d_2\n             / (816480 * w_5 * w1_3)\n           - ( 11053 * w_8 + 53308 * w_7 + 117010 * w_6 + 163924 * w_5 + 116188 * w_4\n             - 258428 * w_3 - 677042 * w_2 - 481940 * w - 105497\n             ) * d_3\n             / (14696640 * w1_4 * w_6)\n        e3 = -( (3592 * w_7 + 8375 * w_6 - 1323 * w_5 - 29198 * w_4 - 89578 * w_3\n                - 154413 * w_2 - 116063 * w - 29632\n                ) * (w - 1)\n              )\n              / (816480 * w_5 * w1_2)\n           - ( 442043 * w_9 + 2054169 * w_8 + 3803094 * w_7 + 3470754 * w_6 + 2141568 * w_5\n             - 2393568 * w_4 - 19904934 * w_3 - 34714674 * w_2 - 23128299 * w - 5253353\n             ) * d\n             / (146966400 * w_6 * w1_3)\n           - ( 116932 * w_10 + 819281 * w_9 + 2378172 * w_8 + 4341330 * w_7 + 6806004 * w_6\n             + 10622748 * w_5 + 18739500 * w_4 + 30651894 * w_3 + 30869976 * w_2\n             + 15431867 * w + 2919016\n             ) * d_2\n             / (146966400 * w1_4 * w_7)\n        eta = evaluatePolynomialL (1/a) [eta0, e1, e2, e3]\n        -- Now we solve eq 4.2 to recover x using Newton iterations\n        u       = eta - mu * log eta + (1 + mu) * log(1 + mu) - mu\n        cross   = 1 / (1 + mu);\n        lower   = if eta < mu then cross else 0\n        upper   = if eta < mu then 1     else cross\n        x_guess = (lower + upper) / 2\n        func x  = ( u + log x + mu*log(1 - x)\n                  , 1/x - mu/(1-x)\n                  )\n        Root x0 = newtonRaphson def{newtonTol=RelTol 1e-8} (lower, x_guess, upper) func\n    in x0\n  -- For large a and b approximation from AS109 (Carter\n  -- approximation). It's reasonably good in this region\n  | a > 1 && b > 1 =\n      let r = (y*y - 3) / 6\n          s = 1 / (2*a - 1)\n          t = 1 / (2*b - 1)\n          h = 2 / (s + t)\n          w = y * sqrt(h + r) / h - (t - s) * (r + 5/6 - 2 / (3 * h))\n      in a / (a + b * exp(2 * w))\n  -- Otherwise we revert to approximation from AS64 derived from\n  -- [AS64 2] when it's applicable.\n  --\n  -- It slightly reduces average number of iterations when `a' and\n  -- `b' have different magnitudes.\n  | chi2 > 0 && ratio > 1 = 1 - 2 / (ratio + 1)\n  -- If all else fails we use approximation from \"Numerical\n  -- Recipes\". It's very similar to approximations [AS64 4,5] but\n  -- it never goes out of [0,1] interval.\n  | otherwise = case () of\n      _| p < t / w  -> (a * p * w) ** (1/a)\n       | otherwise  -> 1 - (b * (1 - p) * w) ** (1/b)\n       where\n         lna = log $ a / (a+b)\n         lnb = log $ b / (a+b)\n         t   = exp( a * lna ) / a\n         u   = exp( b * lnb ) / b\n         w   = t + u\n  where\n    -- Formula [AS64 2]\n    ratio = (4*a + 2*b - 2) / chi2\n    -- Quantile of chi-squared distribution. Formula [AS64 3].\n    chi2 = 2 * b * (1 - t + y * sqrt t) ** 3\n      where\n        t   = 1 / (9 * b)\n    -- `y' is Hasting's approximation of p'th quantile of standard\n    -- normal distribution.\n    y   = r - ( 2.30753 + 0.27061 * r )\n              / ( 1.0 + ( 0.99229 + 0.04481 * r ) * r )\n      where\n        r = sqrt $ - 2 * log p\n\n\n\n----------------------------------------------------------------\n-- Sinc function\n----------------------------------------------------------------\n\n-- | Compute sinc function @sin(x)\\/x@\nsinc :: Double -> Double\nsinc x\n  | ax < eps_0 = 1\n  | ax < eps_2 = 1 - x2/6\n  | ax < eps_4 = 1 - x2/6 + x2*x2/120\n  | otherwise  = sin x / x\n  where\n    ax    = abs x\n    x2    = x*x\n    -- For explanation of choice see `doc/sinc.hs'\n    eps_0 = 1.8250120749944284e-8 -- sqrt (6\u03b5/4)\n    eps_2 = 1.4284346431400855e-4 --   (30\u03b5)**(1/4) / 2\n    eps_4 = 4.043633626430947e-3  -- (1206\u03b5)**(1/6) / 2\n\n\n----------------------------------------------------------------\n-- Logarithm\n----------------------------------------------------------------\n\n-- | Compute log(1+x)-x:\nlog1pmx :: Double -> Double\nlog1pmx x\n  | x <  -1        = error \"Domain error\"\n  | x == -1        = m_neg_inf\n  | ax > 0.95      = log(1 + x) - x\n  | ax < m_epsilon = -(x * x) /2\n  | otherwise      = - x * x * sumPowerSeries (-x) (recip <$> enumSequenceFrom 2)\n  where\n   ax = abs x\n\n-- | /O(log n)/ Compute the logarithm in base 2 of the given value.\nlog2 :: Int -> Int\nlog2 v0\n    | v0 <= 0   = modErr $ \"log2: nonpositive input, got \" ++ show v0\n    | otherwise = go 5 0 v0\n  where\n    go !i !r !v | i == -1        = r\n                | v .&. b i /= 0 = let si = U.unsafeIndex sv i\n                                   in go (i-1) (r .|. si) (v `shiftR` si)\n                | otherwise      = go (i-1) r v\n    b = U.unsafeIndex bv\n    !bv = U.fromList [ 0x02, 0x0c, 0xf0, 0xff00\n                     , fromIntegral (0xffff0000 :: Word)\n                     , fromIntegral (0xffffffff00000000 :: Word)]\n    !sv = U.fromList [1,2,4,8,16,32]\n\n\n----------------------------------------------------------------\n-- Factorial\n----------------------------------------------------------------\n\n-- | Compute the factorial function /n/!.  Returns +\u221e if the input is\n--   above 170 (above which the result cannot be represented by a\n--   64-bit 'Double').\nfactorial :: Int -> Double\nfactorial n\n  | n < 0     = error \"Numeric.SpecFunctions.factorial: negative input\"\n  | n > 170   = m_pos_inf\n  | otherwise = U.unsafeIndex factorialTable n\n\n-- | Compute the natural logarithm of the factorial function.  Gives\n--   16 decimal digits of precision.\nlogFactorial :: Integral a => a -> Double\nlogFactorial n\n  | n <  0    = error \"Numeric.SpecFunctions.logFactorial: negative input\"\n  -- For smaller inputs we just look up table\n  | n <= 170  = log $ U.unsafeIndex factorialTable (fromIntegral n)\n  -- Otherwise we use asymptotic Stirling's series. Number of terms\n  -- necessary depends on the argument.\n  | n < 1500  = stirling + rx * ((1/12) - (1/360)*rx*rx)\n  | otherwise = stirling + (1/12)*rx\n  where\n    stirling = (x - 0.5) * log x - x + m_ln_sqrt_2_pi\n    x        = fromIntegral n + 1\n    rx       = 1 / x\n{-# SPECIALIZE logFactorial :: Int -> Double #-}\n\n\n-- | Calculate the error term of the Stirling approximation.  This is\n-- only defined for non-negative values.\n--\n-- \\[\n-- \\operatorname{stirlingError}(n) = \\log(n!) - \\log(\\sqrt{2\\pi n}\\frac{n}{e}^n)\n-- \\]\nstirlingError :: Double -> Double\nstirlingError n\n  | n <= 15.0   = case properFraction (n+n) of\n                    (i,0) -> sfe `U.unsafeIndex` i\n                    _     -> logGamma (n+1.0) - (n+0.5) * log n + n -\n                             m_ln_sqrt_2_pi\n  | n > 500     = evaluateOddPolynomialL (1/n) [s0,-s1]\n  | n > 80      = evaluateOddPolynomialL (1/n) [s0,-s1,s2]\n  | n > 35      = evaluateOddPolynomialL (1/n) [s0,-s1,s2,-s3]\n  | otherwise   = evaluateOddPolynomialL (1/n) [s0,-s1,s2,-s3,s4]\n  where\n    s0 = 0.083333333333333333333        -- 1/12\n    s1 = 0.00277777777777777777778      -- 1/360\n    s2 = 0.00079365079365079365079365   -- 1/1260\n    s3 = 0.000595238095238095238095238  -- 1/1680\n    s4 = 0.0008417508417508417508417508 -- 1/1188\n    sfe = U.fromList [ 0.0,\n                0.1534264097200273452913848,   0.0810614667953272582196702,\n                0.0548141210519176538961390,   0.0413406959554092940938221,\n                0.03316287351993628748511048,  0.02767792568499833914878929,\n                0.02374616365629749597132920,  0.02079067210376509311152277,\n                0.01848845053267318523077934,  0.01664469118982119216319487,\n                0.01513497322191737887351255,  0.01387612882307074799874573,\n                0.01281046524292022692424986,  0.01189670994589177009505572,\n                0.01110455975820691732662991,  0.010411265261972096497478567,\n                0.009799416126158803298389475, 0.009255462182712732917728637,\n                0.008768700134139385462952823, 0.008330563433362871256469318,\n                0.007934114564314020547248100, 0.007573675487951840794972024,\n                0.007244554301320383179543912, 0.006942840107209529865664152,\n                0.006665247032707682442354394, 0.006408994188004207068439631,\n                0.006171712263039457647532867, 0.005951370112758847735624416,\n                0.005746216513010115682023589, 0.005554733551962801371038690 ]\n\n\n----------------------------------------------------------------\n-- Combinatorics\n----------------------------------------------------------------\n\n-- |\n-- Quickly compute the natural logarithm of /n/ @`choose`@ /k/, with\n-- no checking.\n--\n-- Less numerically stable:\n--\n-- > exp $ lg (n+1) - lg (k+1) - lg (n-k+1)\n-- >   where lg = logGamma . fromIntegral\nlogChooseFast :: Double -> Double -> Double\nlogChooseFast n k = -log (n + 1) - logBeta (n - k + 1) (k + 1)\n\n-- | Calculate binomial coefficient using exact formula\nchooseExact :: Int -> Int -> Double\nn `chooseExact` k\n  = U.foldl' go 1 $ U.enumFromTo 1 k\n  where\n    go a i      = a * (nk + j) / j\n        where j = fromIntegral i :: Double\n    nk = fromIntegral (n - k)\n\n-- | Compute logarithm of the binomial coefficient.\nlogChoose :: Int -> Int -> Double\nn `logChoose` k\n    | k  > n    = (-1) / 0\n      -- For very large N exact algorithm overflows double so we\n      -- switch to beta-function based one\n    | k' < 50 && (n < 20000000) = log $ chooseExact n k'\n    | otherwise                 = logChooseFast (fromIntegral n) (fromIntegral k)\n  where\n    k' = min k (n-k)\n\n-- | Compute the binomial coefficient /n/ @\\``choose`\\`@ /k/. For\n-- values of /k/ > 50, this uses an approximation for performance\n-- reasons.  The approximation is accurate to 12 decimal places in the\n-- worst case\n--\n-- Example:\n--\n-- > 7 `choose` 3 == 35\nchoose :: Int -> Int -> Double\nn `choose` k\n    | k  > n         = 0\n    | k' < 50        = chooseExact n k'\n    | approx < max64 = fromIntegral . round64 $ approx\n    | otherwise      = approx\n  where\n    k'             = min k (n-k)\n    approx         = exp $ logChooseFast (fromIntegral n) (fromIntegral k')\n    max64          = fromIntegral (maxBound :: Int64)\n    round64 x      = round x :: Int64\n\n-- | Compute \u03c8(/x/), the first logarithmic derivative of the gamma\n--   function.\n--\n-- \\[\n-- \\psi(x) = \\frac{d}{dx} \\ln \\left(\\Gamma(x)\\right) = \\frac{\\Gamma'(x)}{\\Gamma(x)}\n-- \\]\n--\n-- Uses Algorithm AS 103 by Bernardo, based on Minka's C implementation.\ndigamma :: Double -> Double\ndigamma x\n    | isNaN x || isInfinite x                  = m_NaN\n    -- FIXME:\n    --   This is ugly. We are testing here that number is in fact\n    --   integer. It's somewhat tricky question to answer. When \u03b5 for\n    --   given number becomes 1 or greater every number is represents\n    --   an integer. We also must make sure that excess precision\n    --   won't bite us.\n    | x <= 0 && fromIntegral (truncate x :: Int64) == x = m_neg_inf\n    -- Jeffery's reflection formula\n    | x < 0     = digamma (1 - x) + pi / tan (negate pi * x)\n    | x <= 1e-6 = - \u03b3 - 1/x + trigamma1 * x\n    | x' < c    = r\n    -- De Moivre's expansion\n    | otherwise = let s = 1/x'\n                  in  evaluateEvenPolynomialL s\n                        [   r + log x' - 0.5 * s\n                        , - 1/12\n                        ,   1/120\n                        , - 1/252\n                        ,   1/240\n                        , - 1/132\n                        ,  391/32760\n                        ]\n  where\n    \u03b3  = m_eulerMascheroni\n    c  = 12\n    -- Reduce to digamma (x + n) where (x + n) >= c\n    (r, x') = reduce 0 x\n      where\n        reduce !s y\n          | y < c     = reduce (s - 1 / y) (y + 1)\n          | otherwise = (s, y)\n\n\n\n----------------------------------------------------------------\n-- Constants\n----------------------------------------------------------------\n\n-- Coefficients for 18-point Gauss-Legendre integration. They are\n-- used in implementation of incomplete gamma and beta functions.\ncoefW,coefY :: U.Vector Double\ncoefW = U.fromList [ 0.0055657196642445571, 0.012915947284065419, 0.020181515297735382\n                   , 0.027298621498568734,  0.034213810770299537, 0.040875750923643261\n                   , 0.047235083490265582,  0.053244713977759692, 0.058860144245324798\n                   , 0.064039797355015485,  0.068745323835736408, 0.072941885005653087\n                   , 0.076598410645870640,  0.079687828912071670, 0.082187266704339706\n                   , 0.084078218979661945,  0.085346685739338721, 0.085983275670394821\n                   ]\ncoefY = U.fromList [ 0.0021695375159141994, 0.011413521097787704, 0.027972308950302116\n                   , 0.051727015600492421,  0.082502225484340941, 0.12007019910960293\n                   , 0.16415283300752470,   0.21442376986779355,  0.27051082840644336\n                   , 0.33199876341447887,   0.39843234186401943,  0.46931971407375483\n                   , 0.54413605556657973,   0.62232745288031077,  0.70331500465597174\n                   , 0.78649910768313447,   0.87126389619061517,  0.95698180152629142\n                   ]\n{-# NOINLINE coefW #-}\n{-# NOINLINE coefY #-}\n\ntrigamma1 :: Double\ntrigamma1 = 1.6449340668482264365 -- pi**2 / 6\n\nmodErr :: String -> a\nmodErr msg = error $ \"Numeric.SpecFunctions.\" ++ msg\n\nfactorialTable :: U.Vector Double\n{-# NOINLINE factorialTable #-}\nfactorialTable = U.fromListN 171\n  [ 1.0\n  , 1.0\n  , 2.0\n  , 6.0\n  , 24.0\n  , 120.0\n  , 720.0\n  , 5040.0\n  , 40320.0\n  , 362880.0\n  , 3628800.0\n  , 3.99168e7\n  , 4.790016e8\n  , 6.2270208e9\n  , 8.71782912e10\n  , 1.307674368e12\n  , 2.0922789888e13\n  , 3.55687428096e14\n  , 6.402373705728e15\n  , 1.21645100408832e17\n  , 2.43290200817664e18\n  , 5.109094217170944e19\n  , 1.1240007277776077e21\n  , 2.5852016738884974e22\n  , 6.204484017332394e23\n  , 1.5511210043330984e25\n  , 4.032914611266056e26\n  , 1.0888869450418352e28\n  , 3.0488834461171384e29\n  , 8.841761993739702e30\n  , 2.6525285981219103e32\n  , 8.222838654177922e33\n  , 2.631308369336935e35\n  , 8.683317618811886e36\n  , 2.9523279903960412e38\n  , 1.0333147966386144e40\n  , 3.719933267899012e41\n  , 1.3763753091226343e43\n  , 5.23022617466601e44\n  , 2.0397882081197442e46\n  , 8.159152832478977e47\n  , 3.3452526613163803e49\n  , 1.4050061177528798e51\n  , 6.041526306337383e52\n  , 2.6582715747884485e54\n  , 1.1962222086548019e56\n  , 5.5026221598120885e57\n  , 2.5862324151116818e59\n  , 1.2413915592536073e61\n  , 6.082818640342675e62\n  , 3.0414093201713376e64\n  , 1.5511187532873822e66\n  , 8.065817517094388e67\n  , 4.2748832840600255e69\n  , 2.308436973392414e71\n  , 1.2696403353658275e73\n  , 7.109985878048634e74\n  , 4.0526919504877214e76\n  , 2.3505613312828785e78\n  , 1.386831185456898e80\n  , 8.32098711274139e81\n  , 5.075802138772247e83\n  , 3.146997326038793e85\n  , 1.9826083154044399e87\n  , 1.2688693218588415e89\n  , 8.24765059208247e90\n  , 5.44344939077443e92\n  , 3.647111091818868e94\n  , 2.4800355424368305e96\n  , 1.711224524281413e98\n  , 1.197857166996989e100\n  , 8.504785885678623e101\n  , 6.1234458376886085e103\n  , 4.470115461512684e105\n  , 3.307885441519386e107\n  , 2.4809140811395396e109\n  , 1.88549470166605e111\n  , 1.4518309202828586e113\n  , 1.1324281178206297e115\n  , 8.946182130782974e116\n  , 7.15694570462638e118\n  , 5.797126020747368e120\n  , 4.753643337012841e122\n  , 3.9455239697206583e124\n  , 3.314240134565353e126\n  , 2.81710411438055e128\n  , 2.422709538367273e130\n  , 2.1077572983795275e132\n  , 1.8548264225739844e134\n  , 1.650795516090846e136\n  , 1.4857159644817613e138\n  , 1.352001527678403e140\n  , 1.2438414054641305e142\n  , 1.1567725070816416e144\n  , 1.087366156656743e146\n  , 1.0329978488239058e148\n  , 9.916779348709496e149\n  , 9.619275968248211e151\n  , 9.426890448883246e153\n  , 9.332621544394413e155\n  , 9.332621544394415e157\n  , 9.425947759838358e159\n  , 9.614466715035125e161\n  , 9.902900716486179e163\n  , 1.0299016745145626e166\n  , 1.0813967582402908e168\n  , 1.1462805637347082e170\n  , 1.2265202031961378e172\n  , 1.3246418194518288e174\n  , 1.4438595832024934e176\n  , 1.5882455415227428e178\n  , 1.7629525510902446e180\n  , 1.974506857221074e182\n  , 2.2311927486598134e184\n  , 2.543559733472187e186\n  , 2.9250936934930154e188\n  , 3.393108684451898e190\n  , 3.9699371608087206e192\n  , 4.68452584975429e194\n  , 5.574585761207606e196\n  , 6.689502913449126e198\n  , 8.094298525273443e200\n  , 9.875044200833601e202\n  , 1.214630436702533e205\n  , 1.5061417415111406e207\n  , 1.8826771768889257e209\n  , 2.372173242880047e211\n  , 3.0126600184576594e213\n  , 3.856204823625804e215\n  , 4.974504222477286e217\n  , 6.466855489220473e219\n  , 8.471580690878819e221\n  , 1.1182486511960041e224\n  , 1.4872707060906857e226\n  , 1.9929427461615188e228\n  , 2.6904727073180504e230\n  , 3.6590428819525483e232\n  , 5.012888748274991e234\n  , 6.917786472619488e236\n  , 9.615723196941088e238\n  , 1.3462012475717523e241\n  , 1.898143759076171e243\n  , 2.6953641378881624e245\n  , 3.8543707171800725e247\n  , 5.5502938327393044e249\n  , 8.047926057471992e251\n  , 1.1749972043909107e254\n  , 1.7272458904546386e256\n  , 2.5563239178728654e258\n  , 3.808922637630569e260\n  , 5.713383956445854e262\n  , 8.62720977423324e264\n  , 1.3113358856834524e267\n  , 2.0063439050956823e269\n  , 3.0897696138473508e271\n  , 4.789142901463393e273\n  , 7.471062926282894e275\n  , 1.1729568794264143e278\n  , 1.8532718694937346e280\n  , 2.946702272495038e282\n  , 4.714723635992061e284\n  , 7.590705053947218e286\n  , 1.2296942187394494e289\n  , 2.0044015765453023e291\n  , 3.287218585534296e293\n  , 5.423910666131589e295\n  , 9.003691705778436e297\n  , 1.5036165148649988e300\n  , 2.526075744973198e302\n  , 4.269068009004705e304\n  , 7.257415615307998e306\n  ]\n\n\n-- [NOTE: incompleteGamma.taylorP]\n--\n-- Incompltete gamma uses several algorithms for different parts of\n-- parameter space. Most troublesome is P(a,x) Taylor series\n-- [Temme1994,Eq.5.5] which requires to evaluate rather nasty\n-- expression:\n--\n--       x^a             x^a\n--  ------------- = -------------\n--  exp(x)\u00b7\u0393(a+1)   exp(x)\u00b7a\u00b7\u0393(a)\n--\n--  Conditions:\n--    | 0.5<x<1.1  = x < 4/3*a\n--    | otherwise  = x < a\n--\n-- For small `a` computation could be performed directly. However for\n-- largish values of `a` it's possible some of factor in the\n-- expression overflow. Values below take into account ranges for\n-- Taylor P approximation:\n--\n--  \u00b7 a > 155    - x^a could overflow\n--  \u00b7 a > 1182.5 - exp(x) could overflow\n--\n-- Usual way to avoid overflow problem is to perform calculations in\n-- the log domain. It however doesn't work very well in this case\n-- since we encounter catastrophic cancellations and could easily lose\n-- up to 6(!) digits for large `a`.\n--\n-- So we take another approach and use Stirling approximation with\n-- correction (logGammaCorrection).\n--\n--              x^a               / x\u00b7e \\^a         1\n--  \u2248 ------------------------- = | --- | \u00b7 ----------------\n--    exp(x)\u00b7sqrt(2\u03c0a)\u00b7(a/e)^a)   \\  a  /   exp(x)\u00b7sqrt(2\u03c0a)\n--\n-- We're using this approach as soon as logGammaCorrection starts\n-- working (a>10) because we don't have implementation for gamma\n-- function and exp(logGamma z) results in errors for large a.\n--\n-- Once we get into region when exp(x) could overflow we rewrite\n-- expression above once more:\n--\n--  / x\u00b7e            \\^a     1\n--  | --- \u00b7 e^(-x/a) | \u00b7 ---------\n--  \\  a             /   sqrt(2\u03c0a)\n--\n-- This approach doesn't work very well but it's still big improvement\n-- over calculations in the log domain.\n", "meta": {"hexsha": "37df3c009ca9547bf0988fd55b524021faa97782", "size": 48399, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/SpecFunctions/Internal.hs", "max_stars_repo_name": "Shimuuar/math-functions", "max_stars_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numeric/SpecFunctions/Internal.hs", "max_issues_repo_name": "Shimuuar/math-functions", "max_issues_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numeric/SpecFunctions/Internal.hs", "max_forks_repo_name": "Shimuuar/math-functions", "max_forks_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9703757225, "max_line_length": 107, "alphanum_fraction": 0.561871113, "num_tokens": 17170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45653367371364684}}
{"text": "{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TemplateHaskell #-} \n{-# LANGUAGE TypeFamilies #-}\n\nmodule Lib\n    ( someFunc\n    ) where\n\nimport Data.Functor.Foldable\nimport Data.Functor.Foldable.TH\nimport Data.List (intercalate, partition, foldl1', foldl', sort, sortOn)\nimport Data.Sparse.SpMatrix\nimport Data.Sparse.SpVector\nimport Numeric.LinearAlgebra.Sparse\n\na' :: SpMatrix Double\na' = fromListDenseSM 2 [ 1, 3\n                      , 1, 1]\n\nb' :: SpVector Double\nb' = mkSpVR 2 [1, 3]\n\ndata Exp a = Add [Exp a]\n           | Mul [Exp a]\n           | Lit a\n           | Var Char\n           deriving (Show, Eq, Ord)\n\ninstance (Num a) => Num (Exp a) where\n    negate x = (Lit (-1) * x)\n    (+) x y = Add [x, y]\n    (*) x y = Mul [x, y]\n    fromInteger = Lit . fromInteger\n    abs = id\n    signum = id\n\nmakeBaseFunctor ''Exp\n\nsimp :: (Num a, Ord a) => Exp a -> Exp a\nsimp e = cata order . cata dist . cata flatten $ e\n    where flatten (MulF as) = let (ms, bs) = partition isMul as\n                               in Mul $ concat [ms' | (Mul ms') <- ms ] ++ bs\n          flatten (AddF as) = let (ms, bs) = partition isAdd as\n                               in Add $ concat [ms' | (Add ms') <- ms ] ++ bs\n          flatten x = embed x\n\n          dist (MulF as) = foldl1' (\\l r -> Add $ (\\l' r' -> flatten $ MulF [l', r']) <$> unAdd l <*> unAdd r) as\n          dist (AddF as) = flatten (AddF as)\n          dist x = embed x\n\n          order (MulF as) = let (ls, ns) = partition isLit as\n                             in Mul $ sort ((Lit $ product [ x | (Lit x) <- ls]) : ns)\n          order (AddF as) = let adds = sortOn (filter (not . isLit) . unMul) as\n                                x = foldl' (\\((pl:pns):ps) (al:ans) -> if pns == ans then ((addLit pl al):pns):ps else (al:ans):(pl:pns):ps) [(unMul . head $ adds)] (unMul <$> tail adds)\n                             in Add (Mul <$> x)\n          order x = embed x\n\n          unAdd (Add as) = as\n          unAdd x = [x]\n\n          unMul (Mul as) = as\n          unMul x = [x]\n\n          isMul (Mul _) = True\n          isMul _ = False\n\n          isAdd (Add _) = True\n          isAdd _ = False\n\n          isLit (Lit _) = True\n          isLit _ = False\n\n          addLit (Lit l) (Lit r) = Lit (l + r) \n\np :: (Show a) => [Exp a] -> String\np es = intercalate \"\\n\" (pretty <$> es)\n\npretty :: (Show a) => Exp a -> String\npretty (Add as) = intercalate \" + \" (pretty <$> as)\npretty (Mul ms) = concat $ (\\m -> case m of\n                                     Add _ -> \"(\" ++ pretty m ++ \")\"\n                                     _ -> pretty m) <$> ms\npretty (Var c) = [c]\npretty (Lit a) = show a\n\na = Var 'a'\nb = Var 'b'\nc = Var 'c'\nd = Var 'd'\ne = Var 'e'\nf = Var 'f'\n\ntest = (a + 1)^5\n\nsomeFunc :: IO ()\nsomeFunc = do\n    putStrLn (show test)\n", "meta": {"hexsha": "76bdad7b1ac6379bacde8a4d9a602e4f429decfe", "size": 2812, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "micahhahn/calculus-helpers", "max_stars_repo_head_hexsha": "75b22c4b63c13152578cfea5080a212c78a6b38e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "micahhahn/calculus-helpers", "max_issues_repo_head_hexsha": "75b22c4b63c13152578cfea5080a212c78a6b38e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lib.hs", "max_forks_repo_name": "micahhahn/calculus-helpers", "max_forks_repo_head_hexsha": "75b22c4b63c13152578cfea5080a212c78a6b38e", "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.404040404, "max_line_length": 186, "alphanum_fraction": 0.4864864865, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.45652759507059987}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Trade.Report.SparkLine where\n\nimport Data.Time.Clock (diffUTCTime)\n\n\nimport qualified Data.Vector as Vec\n\nimport qualified Statistics.Sample as Sample\n\n\nimport qualified Text.Blaze.Html5 as H5\nimport Text.Blaze.Html5 ((!))\nimport qualified Text.Blaze.Html5.Attributes as H5A\n\nimport Text.Blaze.Svg11 (mkPath, l, m)\nimport qualified Text.Blaze.Svg11 as S\nimport qualified Text.Blaze.Svg11.Attributes as A\n\nimport Trade.Type.Step.Algorithm\n\nimport Trade.Type.DeltaSignal (DeltaSignal(..))\nimport Trade.Type.Equity (Equity(..))\nimport Trade.Type.Signal (Timeseries, Signal(..))\nimport qualified Trade.Type.Signal as Signal\n\n\ndata Config = Config {\n  width :: Int\n  , height :: Int\n  }\n\ndefConfig :: Config\ndefConfig = Config 120 80\n  \ntype Range = Double -> Double\n\ntoRange :: Config -> Timeseries Equity -> Range\ntoRange conf sig =\n  let (_, Equity mi) = Signal.minimum sig\n      (_, Equity ma) = Signal.maximum sig\n      h = fromIntegral (height conf)\n      (lower, upper) = if ma == mi then (0.8, 1.2) else (mi, ma)\n      stepH = h / (upper - lower)\n  in \\y -> (upper-y) * stepH\n\n\ntype Domain = Double -> Double\n\ntoDomain :: Config -> [Timeseries Equity] -> (Double, Double, Domain)\ntoDomain conf sigs =\n  let ts = map (\\s -> realToFrac (fst (Signal.last s) `diffUTCTime` fst (Signal.head s))) sigs\n      tmax = maximum ts\n      vs = Vec.fromList ts\n      mean = Sample.mean vs\n      stdDev = Sample.stdDev vs\n      w = fromIntegral (width conf)\n  in (mean, stdDev, \\x -> x * w / tmax)\n\n\nsvg :: Config -> S.Svg -> S.Svg\nsvg conf inner =\n  S.docTypeSvg\n  ! A.version \"1.1\"\n  ! A.width (S.toValue (width conf+1))\n  ! A.height (S.toValue (height conf+1))\n  $ inner\n\n\nspark :: Config -> (Double, Double, Domain) -> Timeseries Equity -> S.Svg\nspark conf (mean, stdDev, dom) sig@(Signal xs) =\n  let t0 = fst (Signal.head sig)\n      ran = toRange conf sig\n      as = Vec.map (\\(t, e) -> (realToFrac (t `diffUTCTime` t0), unEquity e)) xs\n      f acc (t, x) =  acc >> l (dom t) (ran x)\n      sty = H5A.style (H5.stringValue \"stroke:#4444ff;stroke-width:1px;fill:none;\")\n\n      coord = do\n\n        S.rect\n          ! H5A.style (H5.stringValue \"stroke:0px;fill:#ff0000;opacity:0.05;shape-rendering:crispedges;\")\n          ! A.x (S.toValue (dom (mean - stdDev)))\n          ! A.y (S.toValue (0 :: Double))\n          ! A.width (S.toValue (dom (2 * stdDev)))\n          ! A.height (S.toValue (height conf))\n\n        S.line\n          ! H5A.style (H5.stringValue \"stroke:#00aa00;shape-rendering:crispedges;\")\n          ! A.x1 (S.toValue (dom mean))\n          ! A.y1 (S.toValue (0 :: Double))\n          ! A.x2 (S.toValue (dom mean))\n          ! A.y2 (S.toValue (height conf))\n        \n        S.line\n          ! H5A.style (H5.stringValue \"stroke:#000000;shape-rendering:crispedges;\")\n          ! A.x1 (S.toValue (0 :: Double))\n          ! A.y1 (S.toValue (ran 1))\n          ! A.x2 (S.toValue (width conf))\n          ! A.y2 (S.toValue (ran 1))\n          \n        S.line\n          ! H5A.style (H5.stringValue \"stroke:#000000;shape-rendering:crispedges;\")\n          ! A.x1 (S.toValue (0 :: Double))\n          ! A.y1 (S.toValue (0 :: Double))\n          ! A.x2 (S.toValue (0 :: Double))\n          ! A.y2 (S.toValue (height conf))\n          \n{-\n        S.circle\n          ! H5A.style (H5.stringValue \"fill:#000000;\")\n          ! A.cx (S.toValue (dom (32914.28571428572)))\n          ! A.cy (S.toValue (ran 1))\n          ! A.r (S.toValue (5 :: Double))\n\n        (S.text_ (H5.preEscapedToHtml (show lst)))\n          ! H5A.style (H5.stringValue \"fill:#000000;\")\n          ! A.x (S.toValue (dom 0))\n          ! A.y (S.toValue (ran 1))\n          -}\n          \n  in svg conf $ do\n    coord\n    S.path ! sty ! A.d (mkPath (Vec.foldl' f (m 0 (ran 1)) as))\n\n\ntoSparkLine ::\n  (Functor f, StepFunction step) =>\n  step -> f [DeltaSignal ohlc] -> f [S.Svg]\ntoSparkLine step mp =\n  let eqty = Equity 1\n      us = fmap (map (stepFunction step eqty)) mp\n\n      f ss =\n        let dom = toDomain defConfig ss\n        in map (spark defConfig dom) ss\n\n  in fmap f us\n\n", "meta": {"hexsha": "34762dcdd94814b0ec3ac29840e1b267d6425f80", "size": 4136, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Trade/Report/SparkLine.hs", "max_stars_repo_name": "fphh/trade", "max_stars_repo_head_hexsha": "4957fe6c5a709f6f7df01dc56c77a015fb69b298", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-09T10:41:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-09T10:41:11.000Z", "max_issues_repo_path": "src/Trade/Report/SparkLine.hs", "max_issues_repo_name": "fphh/trade", "max_issues_repo_head_hexsha": "4957fe6c5a709f6f7df01dc56c77a015fb69b298", "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/Trade/Report/SparkLine.hs", "max_forks_repo_name": "fphh/trade", "max_forks_repo_head_hexsha": "4957fe6c5a709f6f7df01dc56c77a015fb69b298", "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.1267605634, "max_line_length": 105, "alphanum_fraction": 0.5911508704, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.45645187172091983}}
{"text": "{-# LANGUAGE Strict, StrictData #-}\n{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}\n{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}\n\n------------------------------------------------\n-- |\n-- Module    :  Text.TeXout\n-- Copyright :  (c) Jun Yoshida 2019\n-- License   :  BSD3\n--\n-- Export TeX codes.\n--\n------------------------------------------------\n\nmodule Text.TeXout where\n\nimport GHC.Generics (Generic)\nimport Control.DeepSeq (NFData)\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.STRef\n\nimport Data.Text (Text)\nimport qualified Data.Text as T\n\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\nimport Numeric (showFFloat)\n\nimport Numeric.LinearAlgebra (Z)\nimport Numeric.F2 (F2)\nimport Numeric.Algebra.FreeModule\nimport Numeric.Algebra.Frobenius\n\n-- | Class of types which are exhibited in LaTeX display maths.\nclass TeXMathShow a where\n  texMathShow :: a -> Text\n\n-- * Instances\ninstance (TeXMathShow a) => TeXMathShow (Maybe a) where\n  texMathShow = maybe T.empty texMathShow\n\ninstance TeXMathShow String where\n  texMathShow = T.pack\n\ninstance TeXMathShow Int where\n  texMathShow = T.pack . show\n\ninstance TeXMathShow Double where\n  texMathShow x = T.pack $ showFFloat (Just 4) x \"\"\n\ninstance TeXMathShow Z where\n  texMathShow = T.pack . show\n\ninstance TeXMathShow F2 where\n  texMathShow = T.pack . show\n\ninstance TeXMathShow SL2B where\n  texMathShow SLI = T.singleton '1'\n  texMathShow SLX = T.singleton 'X'\n\ninstance (TeXMathShow a, TeXMathShow b) => TeXMathShow (a,b) where\n  texMathShow (x,y)\n    = T.pack \"\\\\left(\" <>\n      texMathShow x <> T.pack \",\" <> texMathShow y <>\n      T.pack \"\\\\right)\"\n\ninstance (TeXMathShow a, Ord b, TeXMathShow b) => TeXMathShow (FreeMod a b) where\n  texMathShow fm\n    = case Map.toList (termMap fm) of\n        [] -> texMathShow (0 :: Int)\n        ts -> T.intercalate (T.singleton '+') (fmap showProd ts)\n    where\n      showProd (term,coeff) = texMathShow coeff <> texMathShow term\n\ninstance (TeXMathShow a) => TeXMathShow (Map (Int,Int) a) where\n  texMathShow mp\n    = case foldl rangeFinder Nothing (Map.keys mp) of\n        Nothing -> T.empty\n        (Just (imin,imax,jmin,jmax))\n          -> runST $ do\n          stTeX <- newSTRef T.empty\n          writeSTRef stTeX $ beginEnvLn \"array\" [FixArg (\"r|\" ++ replicate (jmax-jmin+1) 'c')]\n          modifySTRef' stTeX (<> mkArrayLn \"i\\\\backslash j\" [jmin..jmax])\n          modifySTRef' stTeX (<> T.pack \"\\\\\\\\\\\\hline\\n\")\n          forM_ [imin..imax] $ \\i -> do\n            let arrayLn = mkArrayLn i (fmap (\\j-> mp Map.!?(i,j)) [jmin..jmax])\n            modifySTRef stTeX (<> arrayLn)\n            if i < imax\n              then (modifySTRef' stTeX (<> T.pack \"\\\\\\\\\\n\"))\n              else (modifySTRef' stTeX (<> T.singleton '\\n'))\n          modifySTRef' stTeX (<> endEnv \"array\")\n          readSTRef stTeX\n    where\n      rangeFinder Nothing (i,j) = Just (i,i,j,j)\n      rangeFinder (Just (imin,imax,jmin,jmax)) (i,j) =\n        let imin' = if i < imin then i else imin\n            imax' = if i > imax then i else imax\n            jmin' = if j < jmin then j else jmin\n            jmax' = if j > jmax then j else jmax\n        in Just (imin',imax',jmin',jmax')\n\n------------------------------\n-- * Macros argment control\n------------------------------\nembrace :: String -> Text\nembrace str = '{' `T.cons` T.pack str `T.snoc` '}'\n\ndata TeXArg = OptArg String | FixArg String\n  deriving (Eq, Ord, Generic, NFData)\n\nencloseArg :: TeXArg -> Text\nencloseArg (OptArg arg)\n  = case arg of\n      []        -> T.empty\n      otherwise -> '[' `T.cons` T.pack arg `T.snoc` ']'\nencloseArg (FixArg arg) = embrace arg\n\nencloseArgs :: (Foldable t) => t TeXArg -> Text\nencloseArgs = foldl (\\enc arg -> enc <> encloseArg arg) T.empty\n\n\n----------------------------\n-- * Headers on TeX source\n----------------------------\nargEnclose :: String -> Text\nargEnclose arg = '{' `T.cons` T.pack arg `T.snoc` '}'\n\noptArgEnclose :: String -> Text\noptArgEnclose []  = T.empty\noptArgEnclose arg = '[' `T.cons` T.pack arg `T.snoc` ']'\n\ndocumentClass :: String -> String -> Text\ndocumentClass opts cls\n  = T.pack \"\\\\documentclass\" <> optArgEnclose opts <> argEnclose cls\n\nusePackage :: String -> String -> Text\nusePackage opts pkg\n  = T.pack \"\\\\usepackage\" <> optArgEnclose opts <> argEnclose pkg\n\n------------------------------\n-- * Macros and Environments\n------------------------------\nmacro :: (Foldable t) => String -> t TeXArg -> Text\nmacro csname args\n  = '\\\\' `T.cons` T.pack csname <> encloseArgs args\n\nbeginEnv :: (Foldable t) => String -> t TeXArg -> Text\nbeginEnv env args\n  = T.pack \"\\\\begin\" <> encloseArg (FixArg env) <> encloseArgs args\n\nbeginEnvLn :: (Foldable t) => String -> t TeXArg -> Text\nbeginEnvLn env args = beginEnv env args `T.snoc` '\\n'\n\nendEnv :: String -> Text\nendEnv env\n  = T.pack \"\\\\end\" <> encloseArg (FixArg env)\n\nendEnvLn :: String -> Text\nendEnvLn env\n  = endEnv env `T.snoc` '\\n'\n\n---------------------\n-- * Miscellaneous\n---------------------\nhorizontalLine :: Text\nhorizontalLine\n  = T.pack \"\\\\leavevmode\\n\\\\\\n\\\\noindent\\\\makebox[\\\\linewidth]{\\\\rule{\\\\paperwidth}{0.4pt}}\\n\"\n\nmkArrayLn :: (TeXMathShow a, TeXMathShow b) => a -> [b] -> Text\nmkArrayLn x ys\n  = T.intercalate (T.pack \" & \") (texMathShow x: fmap texMathShow ys)\n\nmathBB :: String -> Text\nmathBB c = macro \"mathbb\" [FixArg c]\n\ncyclicGrp :: (Integral a) => a -> Text\ncyclicGrp n =\n  mathBB \"Z\" <> T.singleton '/' <> texMathShow (fromIntegral n :: Int)\n\nofRank :: (Integral a, TeXMathShow a) => Text -> a -> Text\nofRank txt 1 = txt\nofRank txt n = txt <> T.pack \"^{\\\\oplus \" <> texMathShow n `T.snoc` '}'\n\nflatZip :: Eq a => [a] -> [(Int,a)]\nflatZip [] = []\nflatZip xs@(_:_) = uncurry (:) $ foldr bin ((1,last xs),[]) (init xs)\n  where\n    bin y ((n,z),zs)\n      | y==z      = ((n+1,z),zs)\n      | otherwise = ((1,y),(n,z):zs)\n\nfinAbGroup :: (Integral a, Integral a') => a -> [a'] -> Text\nfinAbGroup freeRk torsions =\n  let dsum = if freeRk > 0 && not (null torsions)\n             then T.pack \"\\\\oplus \"\n             else T.empty\n      freepart = if freeRk > 0\n                 then mathBB \"Z\" `ofRank` (fromIntegral freeRk :: Int)\n                 else T.empty\n      torGrps = fmap (\\tor -> cyclicGrp (snd tor) `ofRank` fst tor) (flatZip torsions)\n      torpart = T.intercalate (T.pack \"\\\\oplus \") torGrps\n  in freepart <> dsum <> torpart\n", "meta": {"hexsha": "0985868a376ca6262d6ae3bc92eda3ec8373d7fb", "size": 6334, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Text/TeXout.hs", "max_stars_repo_name": "Junology/linkedgram", "max_stars_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-21T06:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:54:21.000Z", "max_issues_repo_path": "src/Text/TeXout.hs", "max_issues_repo_name": "Junology/linkedgram", "max_issues_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "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/Text/TeXout.hs", "max_forks_repo_name": "Junology/linkedgram", "max_forks_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7475728155, "max_line_length": 94, "alphanum_fraction": 0.5966214083, "num_tokens": 1885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.45643801867307815}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule AI.Visualizations\n( networkHistogram\n, weightList\n, biasList\n) where\n\nimport           AI.Layer\nimport           AI.Network\nimport           AI.Network.FeedForwardNetwork\nimport           AI.Neuron\nimport           Numeric.LinearAlgebra\n\nimport           Data.Foldable                      (foldMap)\nimport           GHC.Float\nimport           Graphics.Histogram\nimport           AI.Trainer\n\nweightList :: FeedForwardNetwork -> [Double]\nweightList = toList . flatten . weightMatrix <=< layers\n\nbiasList :: FeedForwardNetwork -> [Double]\nbiasList = toList . biasVector <=< layers\n\nnetworkHistogram :: FilePath -> (FeedForwardNetwork -> [Double]) -> FeedForwardNetwork -> IO ()\nnetworkHistogram filename listFunction n = do\n  let hist = histogram binSturges (listFunction n)\n  plot filename hist\n  return ()\n", "meta": {"hexsha": "eaec40f731ae4644841e4e4cc6fc5e08bdd5a49b", "size": 848, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "AI/Visualizations.hs", "max_stars_repo_name": "jbarrow/LambdaNet", "max_stars_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 308, "max_stars_repo_stars_event_min_datetime": "2015-01-01T01:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:03:18.000Z", "max_issues_repo_path": "AI/Visualizations.hs", "max_issues_repo_name": "jbarrow/LambdaNet", "max_issues_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2015-05-23T20:39:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-29T17:04:47.000Z", "max_forks_repo_path": "AI/Visualizations.hs", "max_forks_repo_name": "jbarrow/LambdaNet", "max_forks_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2015-01-01T07:14:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:33:41.000Z", "avg_line_length": 27.3548387097, "max_line_length": 95, "alphanum_fraction": 0.6698113208, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45637474620900365}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n\n-- |\n-- Module    : Statistics.Sample.Internal\n-- Copyright : (c) 2013 Bryan O'Sullivan\n-- License   : BSD3\n--\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : portable\n--\n-- Internal functions for computing over samples.\nmodule Statistics.Sample.Internal\n    (\n      robustSumVar\n    , sum\n    ) where\n\nimport Numeric.Sum (kbn, sumVector)\nimport Prelude hiding (sum)\nimport Statistics.Function (square)\nimport qualified Data.Vector.Generic as G\n\nrobustSumVar :: (G.Vector v Double) => Double -> v Double -> Double\nrobustSumVar m = sum . G.map (square . subtract m)\n{-# INLINE robustSumVar #-}\n\nsum :: (G.Vector v Double) => v Double -> Double\nsum = sumVector kbn\n{-# INLINE sum #-}\n", "meta": {"hexsha": "53c9a97a337e19c563c27c7bfbdc7bb600264de7", "size": 752, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Sample/Internal.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:39:40.000Z", "max_issues_repo_path": "Statistics/Sample/Internal.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T14:21:32.000Z", "max_forks_repo_path": "Statistics/Sample/Internal.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2015-02-13T00:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:19:16.000Z", "avg_line_length": 24.2580645161, "max_line_length": 67, "alphanum_fraction": 0.6861702128, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4562764603604894}}
{"text": "-- Building blocks for making fully connected neural networks (FCNs).\n--\n-- Original author: David Banas <capn.freako@gmail.com>\n-- Original date:   January 18, 2018\n--\n-- Copyright (c) 2018 David Banas; all rights reserved World wide.\n\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -Wno-unused-top-binds #-}\n\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeOperators #-}\n\n\n{-|\nModule      : Haskell_ML.FCN\nDescription : Allows: creation, training, running, saving, and loading,\n              of multi-layer, fully connected neural networks.\nCopyright   : (c) David Banas, 2018\nLicense     : BSD-3\nMaintainer  : capn.freako@gmail.com\nStability   : experimental\nPortability : ?\n-}\nmodule Haskell_ML.FCN\n  ( FCNet(), TrainEvo(..)\n  , randNet, runNet, runNet', netTest, hiddenStruct\n  , getWeights, getBiases\n  , trainNTimes, classificationAccuracy\n  ) where\n\nimport Control.Monad.Random\nimport Data.Binary\nimport Data.List\nimport Data.Singletons.Prelude\nimport Data.Singletons.TypeLits\nimport Data.Vector.Storable (toList, maxIndex)\nimport GHC.Generics (Generic)\nimport Numeric.LinearAlgebra.Static hiding (mean)  -- ^ @R@ & @L@ come from here.\n-- import Internal.Static (lift1F)  -- Doesn't work; module is hidden.\n\nimport Haskell_ML.Util  hiding (classificationAccuracy, maxIndex, getWeights, getBiases)\n\n-- | A fully connected, multi-layer network with fixed input/output\n-- widths, but variable (and existentially hidden!) internal structure.\ndata FCNet :: Nat -> Nat -> * where\n  FCNet :: Network i hs o -> FCNet i o\n\n-- | Returns a value of type `FCNet`, filled with random weights\n-- ready for training, tucked inside the appropriate Monad, which must\n-- be an instance of `MonadRandom` . (IO is such an instance.)\n--\n-- The input/output widths are determined by the compiler automatically,\n-- via type inferencing.\n--\n-- The internal structure of the network is determined by the list of\n-- integers passed in. Each integer in the list indicates the output\n-- width of one hidden layer, with the first entry in the list\n-- corresponding to the hidden layer nearest to the input layer.\nrandNet :: (KnownNat i, KnownNat o, MonadRandom m)\n        => [Integer]\n        -> m (FCNet i o)\nrandNet hs = withSomeSing hs (fmap FCNet . randNetwork')\n\n\n-- | Data type for holding training evolution data.\ndata TrainEvo = TrainEvo\n  { accs  :: [Double]                   -- ^ training accuracies\n  , diffs :: [([[Double]],[[Double]])]  -- ^ differences of weights/biases, by layer\n  }\n\n-- | Train a network on several epochs of the training data, keeping\n-- track of accuracy and weight/bias changes per layer, after each.\ntrainNTimes :: (KnownNat i, KnownNat o)\n            => Int           -- ^ Number of epochs\n            -> Double        -- ^ learning rate\n            -> FCNet i o     -- ^ the network to be trained\n            -> [(R i, R o)]  -- ^ the training pairs\n            -> (FCNet i o, TrainEvo)\ntrainNTimes = trainNTimes' [] []\n\ntrainNTimes' :: (KnownNat i, KnownNat o)\n             => [Double]                    -- accuracies\n             -> [([[Double]], [[Double]])]  -- weight/bias differences\n             -> Int -> Double -> FCNet i o -> [(R i, R o)] -> (FCNet i o, TrainEvo)\ntrainNTimes' accs diffs 0 _    net _   = (net, TrainEvo accs diffs)\ntrainNTimes' accs diffs n rate net prs = trainNTimes' (accs ++ [acc]) (diffs ++ [diff]) (n-1) rate net' prs\n  where net'  = trainNet rate net prs\n        acc   = classificationAccuracy res ref\n        res   = runNet net' $ map fst prs\n        ref   = map snd prs\n        diff  = ( zipWith (zipWith (-)) (getWeights net') (getWeights net)\n                , zipWith (zipWith (-)) (getBiases  net') (getBiases  net) )\n\n\n-- | Calculate the classification accuracy, given:\n--\n--   - a list of results vectors, and\n--   - a list of reference vectors.\nclassificationAccuracy :: (KnownNat n) => [R n] -> [R n] -> Double\nclassificationAccuracy us vs = mean $ cmpr us vs\n  where cmpr :: (KnownNat n) => [R n] -> [R n] -> [Double]\n        cmpr xs ys = for (zipWith maxComp xs ys) $ \\case\n                       True  -> 1.0\n                       False -> 0.0\n\n        maxComp :: (KnownNat n) => R n -> R n -> Bool\n        maxComp u v = maxIndex (extract u) == maxIndex (extract v)\n\n\n-- | Run a network on a list of inputs.\nrunNet :: (KnownNat i, KnownNat o)\n       => FCNet i o  -- ^ the network to run\n       -> [R i]      -- ^ the list of inputs\n       -> [R o]      -- ^ the list of outputs\nrunNet (FCNet n) = map (runNetwork n)\n\n\n-- | Run a network on a list of inputs,\n-- enforcing 4-bit precision for activation outputs.\nrunNet' :: (KnownNat i, KnownNat o)\n       => FCNet i o  -- ^ the network to run\n       -> [R i]      -- ^ the list of inputs\n       -> [R o]      -- ^ the list of outputs\nrunNet' (FCNet n) = map (runNetwork' n)\n\n\n-- | `Binary` instance definition for `FCNet`.\n--\n-- With this definition, the user of our library is able to use standard\n-- `put` and `get` calls, to serialize his created/trained network for\n-- future use. And we don't need to provide auxilliary `saveNet` and\n-- `loadNet` functions in the API.\ninstance (KnownNat i, KnownNat o) => Binary (FCNet i o) where\n    put = putFCNet\n    get = getFCNet\n\n\n-- | Basic sanity test of our code, taken from Justin's repository.\n--\n-- Printed output should contain two offset solid circles.\nnetTest :: MonadRandom m => Double -> Int -> m String\nnetTest rate n = do\n    inps <- replicateM n $ do\n      s <- getRandom\n      return $ randomVector s Uniform * 2 - 1\n    let outs = flip map inps $ \\v ->\n                 if v `inCircle` (fromRational 0.33, 0.33)\n                      || v `inCircle` (fromRational (-0.33), 0.33)\n                   then fromRational 1\n                   else fromRational 0\n    net0 :: Network 2 '[16, 8] 1 <- randNetwork\n    let trained = sgd rate (zip inps outs) net0\n\n        outMat = [ [ render (norm_2 (runNetwork trained (vector [x / 25 - 1,y / 10 - 1])))\n                   | x <- [0..50] ]\n                 | y <- [0..20] ]\n\n        render r | r <= 0.2  = ' '\n                 | r <= 0.4  = '.'\n                 | r <= 0.6  = '-'\n                 | r <= 0.8  = '='\n                 | otherwise = '#'\n\n    return $ unlines outMat\n  where\n    inCircle :: KnownNat n => R n -> (R n, Double) -> Bool\n    v `inCircle` (o, r) = norm_2 (v - o) <= r\n\n\n-- | Returns a list of integers corresponding to the widths of the hidden\n-- layers of a `FCNet`.\nhiddenStruct :: FCNet i o -> [Integer]\nhiddenStruct (FCNet net) = hiddenStruct' net\n\nhiddenStruct' :: Network i hs o -> [Integer]\nhiddenStruct' = \\case\n    W _    -> []\n    _ :&~ (n' :: Network h hs' o)\n           -> natVal (Proxy @h)\n            : hiddenStruct' n'\n\n\n-- | Returns a list of lists of Doubles, each containing the weights of\n-- one layer of the network.\ngetWeights :: (KnownNat i, KnownNat o) => FCNet i o -> [[Double]]\ngetWeights (FCNet net) = getWeights' net\n\ngetWeights' :: (KnownNat i, KnownNat o) => Network i hs o -> [[Double]]\ngetWeights' (W Layer{..})       = [concatMap (toList . extract) (toRows nodes)]\ngetWeights' (Layer{..} :&~ net) = concatMap (toList . extract) (toRows nodes) : getWeights' net\n\n\n-- | Returns a list of lists of Doubles, each containing the biases of\n-- one layer of the network.\ngetBiases :: (KnownNat i, KnownNat o) => FCNet i o -> [[Double]]\ngetBiases (FCNet net) = getBiases' net\n\ngetBiases' :: (KnownNat i, KnownNat o) => Network i hs o -> [[Double]]\ngetBiases' (W Layer{..})       = [toList $ extract biases]\ngetBiases' (Layer{..} :&~ net) = toList (extract biases) : getBiases' net\n\n\n-----------------------------------------------------------------------\n-- All following functions are for internal library use only!\n-- They are not exported through the API.\n-----------------------------------------------------------------------\n\n\n-- A single network layer mapping an input of width `i` to an output of\n-- width `o`, via simple matrix/vector mult.\ndata Layer i o = Layer { biases :: !(R o)\n                       , nodes  :: !(L o i)\n                       }\n  deriving (Show, Generic)\n\ninstance (KnownNat i, KnownNat o) => Binary (Layer i o)\n\n\n-- Generates a value of type `Layer i o`, filled with uniformly\n-- distributed random values, tucked inside the appropriate Monad, which\n-- must be an instance of `MonadRandom`.\n--\n-- Note: normally distributed values were tried (See commented code, below.)\n--       and found not to perform as well as uniformly distributed values.\n--\n--       This could be due to my use of `logistic`, as opposed to `relu`,\n--       as my activation function; I'm not sure.\n--       (See code and comments near end of this file.)\nrandLayer :: forall m i o. (MonadRandom m, KnownNat i, KnownNat o)\n          => m (Layer i o)\nrandLayer = do\n  s1 :: Int <- getRandom\n  s2 :: Int <- getRandom\n  let b = randomVector  s1 Uniform * 2 - 1  -- Need to change to Gaussian equivalent.\n      n = uniformSample s2 (-1) 1           -- Need to change to Gaussian equivalent.\n  -- PLEASE, KEEP THIS COMMENTED OUT CODE!\n  -- let m = eye\n  --     b = randomVector s2 Gaussian\n  --     n = gaussianSample s1 (takeDiag m) (sym m)\n  return $ Layer b n\n\n\n-- This is the network structure that `FCNet i o` wraps, hiding its\n-- internal structure existentially, outside of the library.\ndata Network :: Nat -> [Nat] -> Nat -> * where\n  W     :: !(Layer i o)\n        -> Network i '[] o\n\n  (:&~) :: KnownNat h\n        => !(Layer i h)\n        -> !(Network h hs o)\n        -> Network i (h ': hs) o\n\ninfixr 5 :&~\n\n\n-- Generates a value of type `Network i hs o`\n-- filled with random weights, ready to begin training.\n--\n-- Note: `hs` is determined explicitly, via the first argument, while\n--       `i` and `o` are determined implicitly, via type inference.\nrandNetwork :: forall m i hs o. (MonadRandom m, KnownNat i, SingI hs, KnownNat o)\n            => m (Network i hs o)\nrandNetwork = randNetwork' sing\n\nrandNetwork' :: forall m i hs o. (MonadRandom m, KnownNat i, KnownNat o)\n             => Sing hs -> m (Network i hs o)\nrandNetwork' = \\case\n  SNil            -> W     <$> randLayer\n  SNat `SCons` ss -> (:&~) <$> randLayer <*> randNetwork' ss\n\n\n-- Binary instance definition for `Network i hs o`.\nputNet :: (KnownNat i, KnownNat o)\n       => Network i hs o\n       -> Put\nputNet = \\case\n    W w    -> put w\n    w :&~ n -> put w *> putNet n\n\ngetNet :: forall i hs o. (KnownNat i, KnownNat o)\n       => Sing hs\n       -> Get (Network i hs o)\ngetNet = \\case\n    SNil            -> W    <$> get\n    SNat `SCons` ss -> (:&~) <$> get <*> getNet ss\n\ninstance (KnownNat i, SingI hs, KnownNat o) => Binary (Network i hs o) where\n    put = putNet\n    get = getNet sing\n\n\nputFCNet :: (KnownNat i, KnownNat o)\n         => FCNet i o\n         -> Put\nputFCNet (FCNet net) = do\n  put (hiddenStruct' net)\n  putNet net\n\ngetFCNet :: (KnownNat i, KnownNat o)\n         => Get (FCNet i o)\ngetFCNet = do\n  hs <- get\n  withSomeSing hs (fmap FCNet . getNet)\n\nrunLayer :: (KnownNat i, KnownNat o)\n         => Layer i o\n         -> R i\n         -> R o\nrunLayer (Layer b n) v = b + n #> v\n\nrunNetwork :: (KnownNat i, KnownNat o)\n           => Network i hs o\n           -> R i\n           -> R o\nrunNetwork = \\case\n  W w        -> \\(!v) -> logistic (runLayer w v)\n  (w :&~ n') -> \\(!v) -> let v' = logistic (runLayer w v)\n                         in runNetwork n' v'\n\n-- 4-bit quantization experiment\nrunNetwork' :: (KnownNat i, KnownNat o)\n            => Network i hs o\n            -> R i\n            -> R o\nrunNetwork' = \\case\n  -- W w -> \\(!v) ->\n  W Layer{..} -> \\(!v) ->\n    let vq = quantizeV v\n        wq = Layer (quantizeV biases) (quantizeM nodes)\n     in quantizeV $ logistic (runLayer wq vq)\n  -- (w :&~ n') -> \\(!v) ->\n  (Layer{..} :&~ n') -> \\(!v) ->\n    let v' = quantizeV $ logistic (runLayer wq vq)\n        vq = quantizeV v\n        wq = Layer (quantizeV biases) (quantizeM nodes)\n     in runNetwork' n' v'\n\nquantizeV :: KnownNat n => R n -> R n\nquantizeV v = dvmap (fromIntegral . floor) (abs v' * 15 + 0.5) / 15\n  where v' = dvmap (max 0 . min 1) v\n\nquantizeM :: (KnownNat i, KnownNat o) => L o i -> L o i\nquantizeM m = dmmap (fromIntegral . floor) (abs m' * 15 + 0.5) / 15\n  where m' = dmmap (max 0 . min 1) m\n\n-- Trains a value of type `FCNet i o`, using the supplied list of\n-- training pairs (i.e. - matched input/output vectors).\ntrainNet :: (KnownNat i, KnownNat o)\n         => Double        -- learning rate\n         -> FCNet i o     -- the network to be trained\n         -> [(R i, R o)]  -- the training pairs\n         -> FCNet i o     -- the trained network\ntrainNet rate (FCNet net) trn_prs = FCNet $ sgd rate trn_prs net\n\n\n-- Train a network of type `Network i hs o` using a list of training\n-- pairs and the Stochastic Gradient Descent (SGD) approach.\nsgd :: forall i hs o. (KnownNat i, KnownNat o)\n    => Double           -- learning rate\n    -> [(R i, R o)]     -- training pairs\n    -> Network i hs o   -- network to train\n    -> Network i hs o   -- trained network\nsgd rate trn_prs net = foldl' (sgdStep rate) net trn_prs\n\n\n-- Train a network of type `Network i hs o` using a single training pair.\n--\n-- This code was taken directly from Justin Le's public GitHub archive:\n-- https://github.com/mstksg/inCode/blob/43adae31b5689a95be83a72866600033fcf52b50/code-samples/dependent-haskell/NetworkTyped.hs#L77\n-- and modified only slightly.\nsgdStep :: forall i hs o. (KnownNat i, KnownNat o)\n         => Double           -- learning rate\n         -> Network i hs o   -- network to train\n         -> (R i, R o)       -- training pair\n         -> Network i hs o   -- trained network\nsgdStep rate net trn_pr = fst $ go x0 net\n  where\n    x0     = fst trn_pr\n    target = snd trn_pr\n    go  :: forall j js. KnownNat j\n        => R j              -- input vector\n        -> Network j js o   -- network to train\n        -> (Network j js o, R j)\n    go !x (W w@(Layer wB wN))\n        = let y    = runLayer w x\n              o    = logistic y\n              -- the gradient (how much y affects the error)\n              --   (logistic' is the derivative of logistic)\n              dEdy = logistic' y * (o - target)\n              -- new bias weights and node weights\n              wB'  = wB - konst rate * dEdy\n              wN'  = wN - konst rate * (dEdy `outer` x)\n              w'   = Layer wB' wN'\n              -- bundle of derivatives for next step\n              dWs  = tr wN #> dEdy\n          in  (W w', dWs)\n    -- Handle the inner layers.\n    go !x (w@(Layer wB wN) :&~ n)\n        = let y          = runLayer w x\n              o          = logistic y\n              -- get dWs', bundle of derivatives from rest of the net\n              (n', dWs') = go o n\n              -- the gradient (how much y affects the error)\n              dEdy       = logistic' y * dWs'\n              -- new bias weights and node weights\n              wB'  = wB - konst rate * dEdy\n              wN'  = wN - konst rate * (dEdy `outer` x)\n              w'   = Layer wB' wN'\n              -- bundle of derivatives for next step\n              dWs  = tr wN #> dEdy\n          in  (w' :&~ n', dWs)\n\n\n-- Doesn't work, because the \"constructors of R are not in scope.\"\n-- What am I to do, here?!\n-- Orphan `Ord` instance, for R n.\n-- deriving instance (KnownNat n) => Ord (R n)\n\n\n-- | Normalize a vector to a probability vector, via softmax.\n-- softMax :: (KnownNat n)\n--         => R n  -- ^ vector to be normalized\n--         -> R n\n-- softMax v = exp v / norm_0 v\n\n\n-- Rectified Linear Unit\n-- relu :: (KnownNat n)\n--      => R n\n--      -> R n\n-- relu = max 0\n\n\n-- relu' :: (KnownNat n)\n--       => R n\n--       -> R n\n-- relu' v = if v > 0 then 1\n--                    else 0\n\n\n-- Logistic non-linear activation function.\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n\nlogistic' :: Floating a => a -> a\nlogistic' x = logix * (1 - logix)\n  where\n    logix = logistic x\n\n", "meta": {"hexsha": "7557d322136068d6ea87825fe8e1ec727fba13bc", "size": 16168, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Haskell_ML/FCN.hs", "max_stars_repo_name": "capn-freako/Haskell_ML", "max_stars_repo_head_hexsha": "c7605b2d1ff063d590d156b1de2579382938322b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2018-08-04T19:33:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T07:35:01.000Z", "max_issues_repo_path": "src/Haskell_ML/FCN.hs", "max_issues_repo_name": "capn-freako/Haskell_ML", "max_issues_repo_head_hexsha": "c7605b2d1ff063d590d156b1de2579382938322b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2018-01-27T18:09:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-10T21:44:32.000Z", "max_forks_repo_path": "src/Haskell_ML/FCN.hs", "max_forks_repo_name": "capn-freako/Haskell_ML", "max_forks_repo_head_hexsha": "c7605b2d1ff063d590d156b1de2579382938322b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-22T21:44:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T00:01:10.000Z", "avg_line_length": 34.9200863931, "max_line_length": 132, "alphanum_fraction": 0.5813953488, "num_tokens": 4625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45600275151399894}}
{"text": "-- |\n-- Module      : Occlusion.Core\n-- Description :\n-- Copyright   : (c) Jonatan H Sundqvist, 2015\n-- License     : MIT\n-- Maintainer  : Jonatan H Sundqvist\n-- Stability   : experimental|stable\n-- Portability : POSIX (not sure)\n--\n\n-- Created September 20 2015\n\n-- TODO | - Angles utilities, units, normalise angles\n--        -\n\n-- SPEC | -\n--        -\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- GHC Pragmas\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- {-# LANGUAGE ScopedTypeVariables #-}\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- API\n--------------------------------------------------------------------------------------------------------------------------------------------\nmodule Occlusion.Core where\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- We'll need these\n--------------------------------------------------------------------------------------------------------------------------------------------\nimport Data.Complex\nimport Data.Function\nimport Data.Fixed\nimport Data.List (minimumBy, maximumBy)\nimport Data.Ord  (comparing)\n\nimport Southpaw.Math.Constants\nimport Southpaw.Utilities.Utilities (pairwise)\n\nimport Occlusion.Types\nimport Occlusion.Lenses\nimport Occlusion.Vector\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- |\nangles :: RealFloat f => Complex f -> Polygon f -> [f]\nangles = map . angle\n\n\n-- |\nangle :: RealFloat f => Complex f -> Complex f -> f\nangle a = snd . polar . subtract a\n\n\n-- | Finds the minimum and maximum value in a list, by some arbitrary criterion.\n-- TODO: Strictness, performance, move to library\nminmaxBy :: (a -> a -> Ordering) -> [a] -> Maybe ((Int, a), (Int, a))\nminmaxBy _ []     = Nothing\nminmaxBy f (x:xs) = Just . foldr (\\n (mini, maxi) -> (minBy f n mini, maxBy f n maxi)) ((0, x), (0, x)) $ zip [1..] xs\n  where\n    minBy f n mini = maximumBy (f `on` snd) [n, mini]\n    maxBy f n maxi = minimumBy (f `on` snd) [n, maxi]\n\n\n-- |\n-- TODO: Rename (?)\n-- TODO: Maybe it would be a good idea if a function called 'anglespan' actually returned some angles.\n-- TODO: Think radar\nanglespan :: RealFloat f => Complex f -> Polygon f -> Maybe ((Int, Complex f), (Int, Complex f))\nanglespan p shape = minmaxBy (comparing $ normalise . angle p) shape\n\n\n-- |\nnormalise :: RealFloat f => f -> f\nnormalise = flip mod' $ 2*\u03c0\n\n\n-- |\n-- TODO: Rename (eg. occlusionEdge, frontEdge, near/far, cover, etc.) (?)\nnearestEdge :: RealFloat f => Complex f -> Polygon f -> Edge f\nnearestEdge p poly = error \"Function 'nearestEdge' is currently on holiday\"\n\n\n-- |\n-- TODO: Rename (eg. distant, etc.) (?)\n-- TODO: Rigorous algorithm\n-- TODO: I could solve this with intersect testing...\n-- TODO: Or comparing (ai < bi) to (\u03b1 < \u03b2)\ndistantEdge :: (RealFloat f, Ord f) => Complex f -> Polygon f -> Maybe (Edge f)\ndistantEdge p shape = case span' of\n  -- Just ((ai, \u03b1), (bi, \u03b2)) -> Just $ slice (min ai bi) (max ai bi) shape -- TODO: This line needs some love and attention\n  -- Just ((ai, \u03b1), (bi, \u03b2)) -> Just $ slice (max ai bi) (max ai bi+length shape - min ai bi) $ cycle shape -- TODO: This line needs some love and attention\n  Just ((ai, a), (bi, b)) -> Just $ slice (max ai bi) (length shape + max ai bi - 1) $ cycle shape\n  -- Just ((ai, fr), (bi, to)) -> Just $ if (ai < bi) == (normalise (angle p fr) < normalise (angle p to))\n  --                                       then slice (max ai bi) (min ai bi + length shape) (cycle shape)\n  --                                       else slice (min ai bi) (max ai bi) (shape)\n  Nothing                 -> Nothing\n  where\n    span' = anglespan p shape\n    -- gap   =\n    -- from = _\n    -- to   = _\n\n\n-- |\n-- TODO: Cyclic slice\nslice :: Int -> Int -> [a] -> [a]\nslice fr to = take (to-fr) . drop fr\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n-- |\n-- TODO: Cyclic (?)\n-- TODO: Caching, performance, drop path segments as we walk past them\n-- TODO: Arbitrary paths (not just straight lines)\n-- TODO: Refactor, simplify\n-- TODO: Invariants, tests, QuickCheck\nwalkalong :: RealFloat f => [Complex f] -> f -> Maybe (Complex f)\nwalkalong []   _         = Nothing\nwalkalong path progress' = case which of\n  []     -> Nothing                    -- We've walked off the beaten path and now we're lost.\n  (pl:_) -> Just $ uncurry walkline pl --\n  where\n    progress = mod' progress' (sum lengths) -- TODO: Remove this\n    lengths  = pairwise distance path       -- The length of each segment, in order\n    segments = pairwise (,) path            -- A list of consecutive endpoints\n    which    = dropWhile ((<progress) . snd) $ zip segments (scanl1 (+) lengths)           -- Drops segments that have already been passed (leaving us with the line we're on as the first value)\n    distance = (realPart . abs) .: (-)                                                     -- Distance (as a real number) between two points\n    walkline (fr, to) l = fr + (to-fr) * (((progress-l+distance fr to)/distance fr to):+0) --\n    (.:) f g = (f .) . g\n", "meta": {"hexsha": "a01db7fdc6e340a0617e42067b04b150a44b2e60", "size": 5661, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Occlusion/Core.hs", "max_stars_repo_name": "SwiftsNamesake/Occlusion", "max_stars_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Occlusion/Core.hs", "max_issues_repo_name": "SwiftsNamesake/Occlusion", "max_issues_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Occlusion/Core.hs", "max_forks_repo_name": "SwiftsNamesake/Occlusion", "max_forks_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8661971831, "max_line_length": 193, "alphanum_fraction": 0.4698816464, "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4559171923261746}}
{"text": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Data.Vector.Storable as V\nimport Data.Vector.Storable.Mutable as M\nimport Numeric.FFT.Vector.Unnormalized as U\nimport Numeric.FFT.Vector.Plan\nimport Data.Numskell.Vector as N\nimport Criterion.Main\nimport Data.Complex\n\nimport System.Environment\n\nmain = do\n    [n] <- fmap (fmap Prelude.read) getArgs\n    let numIters = 1000 * 10\n    vIn <- M.unsafeNew n\n    vOut <- M.unsafeNew n\n    N.write vIn =: pure n 17\n    let !p = plan dft n\n    N.sequence_ $ pure numIters $ executeM p vIn vOut\n", "meta": {"hexsha": "dcf355bc1ca2f1a59b99275a0ee89a17be728bc2", "size": 542, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/timing/TimeFFTW.hs", "max_stars_repo_name": "TravisWhitaker/vector-fftw", "max_stars_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-12-02T12:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T17:52:00.000Z", "max_issues_repo_path": "tests/timing/TimeFFTW.hs", "max_issues_repo_name": "TravisWhitaker/vector-fftw", "max_issues_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-06-16T18:17:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-14T19:29:13.000Z", "max_forks_repo_path": "tests/timing/TimeFFTW.hs", "max_forks_repo_name": "TravisWhitaker/vector-fftw", "max_forks_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-08-29T13:35:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T23:04:18.000Z", "avg_line_length": 24.6363636364, "max_line_length": 53, "alphanum_fraction": 0.7195571956, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4558081754702719}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE Strict           #-}\nmodule FourierPinwheel.GaussianEnvelopePinwheel where\n\nimport           Data.Array.Repa             as R\nimport           Data.Complex\nimport           Data.Vector.Generic         as VG\nimport           Data.Vector.Unboxed         as VU\nimport           FourierPinwheel.Hypergeo1F1\nimport           Math.Gamma\nimport           Pinwheel.FourierSeries2D\nimport           Utils.Distribution\nimport           Utils.Parallel\n\n-- The Fourier coefficients of e^{-a^2 r^2} r^\\mu\n{-# INLINE gaussianPinwheelFourierCoefficients #-}\ngaussianPinwheelFourierCoefficients ::\n     (RealFloat a, Gamma (Complex a), Enum a)\n  => Int\n  -> a\n  -> a\n  -> a\n  -> Int\n  -> Int\n  -> a\n  -> a\n  -> a\n  -> Complex a\ngaussianPinwheelFourierCoefficients numR2Freqs periodR2 a sigma angularFreq radialFreq periodEnv phi rho =\n  let periodConst = (-2) * pi / log periodEnv\n      piRhoPConst = pi * rho / periodR2\n      real = pi / periodR2 ^ 2 * piRhoPConst ^ abs angularFreq\n      mu =\n        (2 + sigma + fromIntegral (abs angularFreq)) :+\n        (periodConst * fromIntegral radialFreq)\n      alpha = mu / 2\n      beta = fromIntegral (1 + abs angularFreq) :+ 0\n      z = ((-1) * (piRhoPConst / a) ^ 2) :+ 0\n      img =\n        (0 :+ (-1)) ^ abs angularFreq * cis (fromIntegral (-angularFreq) * phi) *\n        gamma alpha /\n        gamma beta *\n        (a :+ 0) ** (-mu) *\n        hypergeom alpha beta z\n   in (real :+ 0) * img\n\ngaussianPinwheel ::\n     ( RealFloat a\n     , Gamma (Complex a)\n     , Enum a\n     , Unbox a\n     , VG.Vector vector (Complex a)\n     , NFData (vector (Complex a))\n     )\n  => Int\n  -> a\n  -> a\n  -> a\n  -> Int\n  -> Int\n  -> a\n  -> a\n  -> a\n  -> vector (Complex a)\ngaussianPinwheel numR2Freqs periodR2 stdR2 sigma thetaFreq rFreq periodEnv stdTheta stdR =\n  let zeroVec = VG.replicate (numR2Freqs ^ 2) 0\n      a = 1 / (stdR2 * sqrt 2)\n   in VG.concat .\n      parMap\n        rdeepseq\n        (\\(radialFreq, angularFreq) ->\n           if angularFreq == 0\n             then let pinwheel =\n                        centerHollowArray numR2Freqs $\n                        createFrequencyArray\n                          numR2Freqs\n                          (gaussianPinwheelFourierCoefficients\n                             numR2Freqs\n                             periodR2\n                             a\n                             sigma\n                             angularFreq\n                             radialFreq\n                             periodEnv)\n                      arr =\n                        R.map\n                          (* ((gaussian1DFourierCoefficients\n                                 (fromIntegral radialFreq)\n                                 (log periodEnv)\n                                 stdR) :+\n                              0)) $\n                        centerHollowArray numR2Freqs pinwheel\n                   in VG.convert . toUnboxed . computeS $ arr\n             else zeroVec) $\n      [ (radialFreq, angularFreq)\n      | radialFreq <- [-rFreq .. rFreq]\n      , angularFreq <- [-thetaFreq .. thetaFreq]\n      ]\n      \n\n-- This one has a orientation preference at 0 degree. It is used for Koffka cross problem.\ngaussianPinwheel1 ::\n     ( RealFloat a\n     , Gamma (Complex a)\n     , Enum a\n     , Unbox a\n     , VG.Vector vector (Complex a)\n     , NFData (vector (Complex a))\n     )\n  => Int\n  -> a\n  -> a\n  -> a\n  -> Int\n  -> Int\n  -> a\n  -> a\n  -> a\n  -> vector (Complex a)\ngaussianPinwheel1 numR2Freqs periodR2 stdR2 sigma thetaFreq rFreq periodEnv stdTheta stdR =\n  let a = 1 / (stdR2 * sqrt 2)\n   in VG.concat .\n      parMap\n        rdeepseq\n        (\\(radialFreq, angularFreq) ->\n           let pinwheel =\n                 centerHollowArray numR2Freqs $\n                 createFrequencyArray\n                   numR2Freqs\n                   (gaussianPinwheelFourierCoefficients\n                      numR2Freqs\n                      periodR2\n                      a\n                      sigma\n                      0\n                      radialFreq\n                      periodEnv)\n               arr =\n                 R.map\n                   (* ((gaussian1DFreq (fromIntegral angularFreq) stdTheta *\n                        gaussian1DFourierCoefficients\n                          (fromIntegral radialFreq)\n                          (log periodEnv)\n                          stdR) :+\n                       0)) $\n                 centerHollowArray numR2Freqs pinwheel\n            in VG.convert . toUnboxed . computeS $ arr) $\n      [ (radialFreq, angularFreq)\n      | radialFreq <- [-rFreq .. rFreq]\n      , angularFreq <- [-thetaFreq .. thetaFreq]\n      ]\n", "meta": {"hexsha": "06d0546d85be435bb68334e287519e43b1d3b696", "size": 4665, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FourierPinwheel/GaussianEnvelopePinwheel.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FourierPinwheel/GaussianEnvelopePinwheel.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/FourierPinwheel/GaussianEnvelopePinwheel.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 30.6907894737, "max_line_length": 106, "alphanum_fraction": 0.4911039657, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.9111797100118213, "lm_q2_score": 0.5, "lm_q1q2_score": 0.45558985500591065}}
{"text": "import Data.Complex\n\nmain = do\n  print $ 0 ^ 0\n  print $ 0.0 ^ 0\n  print $ 0 ^^ 0\n  print $ 0 ** 0\n  print $ (0 :+ 0) ^ 0\n  print $ (0 :+ 0) ** (0 :+ 0)\n", "meta": {"hexsha": "0e8698f348cc59000993b372f5802a3f93b0ed2a", "size": 153, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lang/Haskell/zero-to-the-zero-power.hs", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "lang/Haskell/zero-to-the-zero-power.hs", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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": "lang/Haskell/zero-to-the-zero-power.hs", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 15.3, "max_line_length": 30, "alphanum_fraction": 0.4509803922, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.45536702321864403}}
{"text": "{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Main where\n\n-- import Prelude hidint (until)\nimport Control.Monad.State\n-- import Control.Monad.Trans.Class\nimport Numeric.LinearAlgebra.HMatrix hiding (scale, (!))\nimport qualified Graphics.Rendering.OpenGL as GL\n-- import Foreign.Storable\nimport GLCode\nimport Sketch\nimport Points\n-- import Lines\n-- import Triangles\nimport Data.Array\n-- import Debug.Trace\nimport Turtle\nimport Triangles\n\nex5 :: IO ()\nex5 = do\n    mainLoopState 512 512 16 (ident @Float 4) $ \\time -> do\n\n        put (ident @Float 4)\n\n    --         let t = 5*realToFrac time :: Float\n\n        GL.clearColor GL.$= GL.Color4 1.0 1.0 1.0 1\n        GL.clearAccum GL.$= GL.Color4 1.0 1.0 1.0 1\n        io $ GL.clear [GL.ColorBuffer, GL.AccumBuffer]\n\n        GL.lineSmooth GL.$= GL.Enabled\n        GL.lineWidth GL.$= 4\n        GL.hint GL.LineSmooth GL.$= GL.Nicest\n        GL.multisample GL.$= GL.Enabled\n        GL.depthFunc GL.$= Just GL.Always\n \n        let p = array ((0, 0), (19, 19)) [((ix, iy), 0.25*cos (-0.75*time+2.0*pi*fromIntegral (ix+iy)/10)+\n                                                     0.25*sin (0.5*time+3.0*2*pi*(fromIntegral (ix-iy)/20))) |\n                                          ix <- [0..19],\n                                          iy <- [0..19]]\n                          \n        translate (-1.0) (-1.0) 0.0\n        drawDensityField (coolwarm (-0.45) 0.45) 20 20 0.1 0.1 p\n        let (vx, vy) = grad p\n--         let vel = fmap (\\(x, y) -> (0.1*x, 0.1*y)) $ interpVelocity vx vy\n--         drawVectorField 20 20 0.1 0.1 vx vy\n\n--         lift $ drawPath [(x, y) | i <- [0..10], let x = 0.1*fromIntegral i, let y = x*x]\n\n--         let f t = (t, 0.25*t*t)\n--         let time' = 0.3*time\n--         let d = 3*(time'-fromIntegral @Int (floor time'))\n--         lift $ plotPath 100 f 0 d\n--        let curve = integrate (\\x y ->let (u,v)=interpVelocityField vx vy x y in (10*u,10*v)) 0 0 100 0.01\n--         let curve = integrate (\\x y ->let (u,v)=interpVelocityField vx vy x y in (u,v)) 1.0 1.0 300 0.01\n        duringAndAfter time 5 10 $ \\_ ->\n            forM_ [-5.0, -3.0..5.0] $ \\x -> do\n                forM_ [-5.0, -3.0..5.0] $ \\y -> do\n                    let curve = integrate (interpVelocityField vx vy) (10+x) (10+y) 500 0.1\n                    lift $ drawPath (0.0, 0.0, 0.0) [(0.1*u, 0.1*v) | (u, v) <- curve]\n\n        return ()\n\nimage1 = do\n    mainLoopState 768 768 16 (ident @Float 4) $ \\time -> do\n--     mainGifLoopState \"euler_or_lagrange.gif\" 12 768 768 16 1 100 (ident @Float 4) $ \\time -> do\n\n--         let time = fromIntegral 46/12\n\n        put (ident @Float 4)\n\n        GL.clearColor GL.$= GL.Color4 1.0 1.0 1.0 1\n        io $ GL.clear [GL.ColorBuffer]\n\n        GL.lineSmooth GL.$= GL.Enabled\n        GL.lineWidth GL.$= 3\n        GL.hint GL.LineSmooth GL.$= GL.Nicest\n        GL.multisample GL.$= GL.Enabled\n\n        translate (-0.95) (-0.90) 0.0\n--         let vfield x y = (0.01*cos x+0.01*(y-cos 2*y+0.2*sin(2*x)), -0.02*(sin x-1+0.5*sin (5*y)))\n        let vfield x y = (0.01*(y-1)+0.01*(sin y-1), -0.01*(x-1)-0.01*sin (3*x))\n        beforeAndDuring time 14 16 $ \\time ->\n            drawVectorField' (arrow (1-time, 1-time, 1-time) 0.007 0.03 0.03) 13 13 0.15 0.15 $ \\i j ->\n                let x = 0.15*fromIntegral i\n                    y = 0.15*fromIntegral j\n                in vfield x y\n--         let curve = integrate vfield 0.2 0.1 200 0.2\n--         lift $ drawPath (0.0, 0.0, 0.0) (take 100 curve)\n--         lift $ drawPath (0.0, 0.0, 0.0) (drop 99 curve)\n        duringAndAfter time 5 12 $ \\time' -> do\n            forM_ [-0.5, -0.4..2.9] $ \\starty -> do\n                forM_ [-0.5, -0.4..2.9] $ \\startx -> do\n                    let curve = integrate vfield startx starty (floor (400*time')) 0.2\n--                     beforeAndDuring time 14 16 $ \\time ->\n--                             lift $ drawPath (1-time, 1-time, 1-time) curve\n                    when (length curve > 0) $ do\n                        lift $ setUniform \"turtle_point\" \"pointSize\" (12.0 :: Float)\n                        setTransformPoint\n                        lift $ drawPoint \"turtle_point\"\n                                   \"vPosition\" ((\\(x, y) -> v2f x y) (last curve))\n                                   \"color\" (v4f 0.0 0.2 0.9 1.0)\n\nmain :: IO ()\nmain = image1\n", "meta": {"hexsha": "e8efa9bfb4737b52409254d0ee8c13c3a4b6cb7b", "size": 4363, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/ex5/Main.hs", "max_stars_repo_name": "dpiponi/SketchBox", "max_stars_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-23T01:58:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-23T01:58:44.000Z", "max_issues_repo_path": "examples/ex5/Main.hs", "max_issues_repo_name": "dpiponi/SketchBox", "max_issues_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "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/ex5/Main.hs", "max_forks_repo_name": "dpiponi/SketchBox", "max_forks_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0275229358, "max_line_length": 110, "alphanum_fraction": 0.5083658033, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.45519271721024746}}
{"text": "{-# LANGUAGE DataKinds, RankNTypes, TypeFamilies #-}\nmodule TestCommon ((+\\), (*\\), (**\\),\n                   listsToParameters,\n                   cmpTwo, cmpTwoSimple,\n                   qcPropDom, quickCheckTest0, fquad, quad\n                  ) where\n\nimport Prelude\n\nimport qualified Data.Array.DynamicS as OT\nimport qualified Data.Array.ShapedS as OS\nimport qualified Data.Vector.Generic as V\nimport           Numeric.LinearAlgebra (Vector)\nimport qualified Numeric.LinearAlgebra as HM\nimport           Test.Tasty\nimport           Test.Tasty.QuickCheck\n\nimport HordeAd hiding (sumElementsVectorOfDual)\nimport HordeAd.Core.DualClass (Dual)\n\n(+\\) :: DualMonad d r m\n     => DualNumber d r -> DualNumber d r -> m (DualNumber d r)\n(+\\) u v = returnLet $ u + v\n\n(*\\) :: DualMonad d r m\n     => DualNumber d r -> DualNumber d r -> m (DualNumber d r)\n(*\\) u v = returnLet $ u * v\n\n(**\\) :: DualMonad d r m\n      => DualNumber d r -> DualNumber d r -> m (DualNumber d r)\n(**\\) u v = returnLet $ u ** v\n\n-- Checks if 2 numbers are close enough.\nclose1 :: forall r. (Ord r, Fractional r)\n          => r -> r -> Bool\nclose1 a b = abs (a - b) <= 1e-4\n\n-- Checks if 2 number pairs are close enough.\nclose2 :: forall r. (Ord r, Fractional r)\n          => (r,r) -> (r,r) -> Property\nclose2 (a1, b1) (a2, b2) = close1 a1 a2 .&&. close1 b1 b2\n\nquad :: DualMonad d r m\n     => DualNumber d r -> DualNumber d r -> m (DualNumber d r)\nquad x y = do\n  x2 <- returnLet $ square x\n  y2 <- y *\\ y\n  tmp <- x2 +\\ y2\n  tmp +\\ 5\n\nfquad :: forall r d m. DualMonad d r m\n      => DualNumberVariables d r -> m (DualNumber d r)\nfquad variables = do\n  let x = var0 variables 0\n      y = var0 variables 1\n  quad x y\n\nlistsToParameters :: forall r. (OT.Storable r)\n                  => ([r], [r]) -> Domains r\nlistsToParameters (a0, a1) =\n  (V.fromList a0, V.singleton $ V.fromList a1, V.empty, V.empty)\n\nlistsToParameters4 :: ([Double], [Double], [Double], [Double]) -> Domains Double\nlistsToParameters4 (a0, a1, a2, aX) =\n  ( V.fromList a0\n  , V.singleton $ V.fromList a1\n  , if null a2 then V.empty else V.singleton $ HM.matrix 1 a2\n  , if null aX then V.empty else V.singleton $ OT.fromList [length aX] aX )\n\nquickCheckTest0 :: TestName\n       -> (forall d r m. ( DualMonad d r m\n                         , Floating (Out (DualNumber d (Vector r)))\n                         , Floating (Out (DualNumber d (OS.Array '[2] r))) )\n           => DualNumberVariables d r -> m (DualNumber d r))\n       -> ((Double, Double, Double) -> ([Double], [Double], [Double], [Double]))\n       -> TestTree\nquickCheckTest0 txt f fArg =\n  qcTestRanges txt f (listsToParameters4 . fArg) ((-2, -2, -2), (2, 2, 2)) ((-1e-7, -1e-7, -1e-7), (1e-7, 1e-7, 1e-7)) (-10, 10)\n\n-- A quick check to compare the derivatives and values of 2 given functions.\ncmpTwo\n  :: ( m ~ DualMonadForward r, d ~ 'DModeDerivative, Dual d r ~ r\n     , DualMonad d r m )\n  => (DualNumberVariables d r -> m (DualNumber d r))\n  -> (DualNumberVariables d r -> m (DualNumber d r))\n  -> Domains r\n  -> Domains r\n  -> Domains r\n  -> Domains r\n  -> Property\ncmpTwo f1 f2 params1 params2 ds1 ds2 =\n  close2 (dFastForward f1 params1 ds1) (dFastForward f2 params2 ds2)\n\n-- A quick check to compare the derivatives and values of 2 given functions.\ncmpTwoSimple\n  :: ( m ~ DualMonadForward r, d ~ 'DModeDerivative, Dual d r ~ r\n     , DualMonad d r m )\n  => (DualNumberVariables d r -> m (DualNumber d r))\n  -> (DualNumberVariables d r -> m (DualNumber d r))\n  -> Domains r\n  -> Domains r\n  -> Property\ncmpTwoSimple f1 f2 parameters ds =\n  cmpTwo f1 f2 parameters parameters ds ds\n\n-- A quick consistency check of all the kinds of derivatives and gradients\n-- and all kinds of computing the value of the objective function.\nqcPropDom :: (forall d r m. ( DualMonad d r m\n                            , r ~ Double\n                            , Floating (Out (DualNumber d (Vector r)))\n                            , Floating (Out (DualNumber d (OS.Array '[2] r))) )\n              => DualNumberVariables d r -> m (DualNumber d r))\n       -> Domains Double\n       -> Domains Double\n       -> Domains Double\n       -> Double\n       -> Property\nqcPropDom f args ds perturbation dt =\n      let ff@(derivative, ffValue) = dFastForward f args ds\n          (derivativeAtPerturbation, valueAtPerturbation) = dFastForward f args perturbation\n          (gradient, revValue) = dReverse dt f args\n      in -- Two forward derivative implementations agree fully:\n         dForward f args ds === ff\n         -- Objective function value from gradients is the same.\n         .&&. ffValue == revValue\n         -- Gradients and derivatives agree.\n         .&&. close1 (dt * derivative)\n                     (dotParameters gradient ds)\n         -- Objective function value is unaffected by perturbation.\n         .&&. ffValue == valueAtPerturbation\n         -- Derivative approximates the perturbation of value.\n         .&&. close1 (primalValue\n                                  f (addParameters\n                                                   args perturbation))\n                     (ffValue + derivativeAtPerturbation)\n\n-- A quick consistency check of all the kinds of derivatives and gradients\n-- and all kinds of computing the value of the objective function.\nqcPropFArg :: (forall d r m. ( DualMonad d r m\n                         , Floating (Out (DualNumber d (Vector r)))\n                         , Floating (Out (DualNumber d (OS.Array '[2] r))) )\n               => DualNumberVariables d r -> m (DualNumber d r))\n       -> ((Double, Double, Double) -> Domains Double)\n       -> (Double, Double, Double)\n       -> (Double, Double, Double)\n       -> (Double, Double, Double)\n       -> Double\n       -> Property\nqcPropFArg f fArgDom xyz dsRaw perturbationRaw dt =\n      let args = fArgDom xyz\n          ds = fArgDom dsRaw\n          perturbation = fArgDom perturbationRaw\n      in qcPropDom f args ds perturbation dt\n\n-- A quick consistency check of all the kinds of derivatives and gradients\n-- and all kinds of computing the value of the objective function.\nqcTestRanges :: TestName\n       -> (forall d r m. ( DualMonad d r m\n                         , Floating (Out (DualNumber d (Vector r)))\n                         , Floating (Out (DualNumber d (OS.Array '[2] r))) )\n           => DualNumberVariables d r -> m (DualNumber d r))\n       -> ((Double, Double, Double) -> Domains Double)\n       -> ((Double, Double, Double), (Double, Double, Double))\n       -> ((Double, Double, Double), (Double, Double, Double))\n       -> (Double, Double)\n       -> TestTree\nqcTestRanges txt f fArgDom dsRange perturbationRange dtRange =\n  testProperty txt $\n  forAll (choose dsRange) $ \\xyz dsRaw ->\n  forAll (choose perturbationRange) $ \\perturbationRaw ->\n  forAll (choose dtRange) $ \\dt ->\n  qcPropFArg f fArgDom xyz dsRaw perturbationRaw dt\n", "meta": {"hexsha": "44c68c3e62fd76c6a72397cfaac41948f3bb895a", "size": 6828, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/common/TestCommon.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/common/TestCommon.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "test/common/TestCommon.hs", "max_forks_repo_name": "Mikolaj/horde-ad", "max_forks_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4682080925, "max_line_length": 128, "alphanum_fraction": 0.6013473931, "num_tokens": 1881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4549877534055699}}
{"text": "{-# LANGUAGE ConstraintKinds #-}\n\nmodule Element\n( Element\n, StructElem(..)\n, getElementNodes\n, getNumNodes\n, getConnectivity\n, getElementNumber\n, computeJacobian\n, computeJacobianDet\n, dndx\n) where\n\nimport qualified Numeric.LinearAlgebra         as L\nimport qualified Numeric.LinearAlgebra.HMatrix as HMat\n\nimport           Basis\nimport           Node\nimport           Quadrature\nimport           ShapeFcns\n\n-- Utility functions\nallCombinations :: [Int] -> [[Int]]\nallCombinations x = mapM (const x) [1..(length x)]\n\n-- Synonym for types required by HMatrix\ntype FracElNum a = (Fractional a, L.Element a, L.Numeric a)\n\n-- Element types\ndata StructElem a = StructElem [Node a] Int deriving (Show,Eq)\ndata Simplex a    = Simplex    [Node a] Int deriving (Show,Eq)\n\n-- This typeclass defines which functions operate for any element.  Different\n-- element types are defined as instances of this typeclass.\nclass Element e where\n  getElementNodes    :: (Fractional a) => e a -> [Node a]\n  getNumNodes        :: (Fractional a) => e a -> Int\n  getConnectivity    :: (Fractional a) => e a -> [Int]\n  getElementNumber   :: (Fractional a) => e a -> Int\n  faceNormals        :: (Fractional a) => e a -> Int -> [a]\n  computeJacobian    :: (Basis b,ShapeFcn s,FracElNum a) => e a -> s b -> [a] -> L.Matrix a\n  computeJacobianDet :: (Basis b,ShapeFcn s,FracElNum a,L.Field a) => e a -> s b -> [a] -> a\n  dndx               :: (Basis b,ShapeFcn s,FracElNum a,L.Field a) => e a -> s b -> [a] -> Int -> L.Vector a\n\ninstance Element StructElem where\n\n  getElementNodes  (StructElem nodes _)   = nodes\n  getNumNodes      (StructElem nodes _)   = length nodes\n  getConnectivity  (StructElem nodes _)   = map nodeNumber nodes\n  getElementNumber (StructElem _ elemNum) = elemNum\n\n  computeJacobian  (StructElem nodes elemNum) shpFcn coords = HMat.mul matA matB\n    where\n      dim  = getDimension shpFcn\n      matA = L.tr $ L.fromLists $ map (dndXi shpFcn coords) [0..(getShapeFcnOrder shpFcn + 1)^dim - 1]\n      matB = L.fromLists $ map nodeCoordinates nodes\n\n  computeJacobianDet (StructElem nodes elemNum) shpFcn coords = L.det $ computeJacobian (StructElem nodes elemNum) shpFcn coords\n  dndx elem shpFcn coords idx = HMat.app (HMat.inv (computeJacobian elem shpFcn coords)) (L.fromList $ dndXi shpFcn coords idx)\n\n  faceNormals (StructElem nodes elemNum) 1 = [-1.0, 1.0]  -- Specialized for linear elements\n  faceNormals _ _ = error \"Face normals can only be computed for 1D elements for now.\"\n", "meta": {"hexsha": "74cfa914867d8f17d9b0a3a59185864269aecf49", "size": 2478, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Element.hs", "max_stars_repo_name": "jgrisham4/hfem", "max_stars_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "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/Element.hs", "max_issues_repo_name": "jgrisham4/hfem", "max_issues_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "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/Element.hs", "max_forks_repo_name": "jgrisham4/hfem", "max_forks_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.71875, "max_line_length": 128, "alphanum_fraction": 0.6844229217, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4549641120529289}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# OPTIONS -Wall #-}\nmodule NN.NeuralNetwork\n  (\n    NN (..)\n  , NNVars\n  , createNetworkW\n  , Net (..)\n  , module Util.Vars\n  ) where\n\nimport AI.HNN.FF.Network\nimport Numeric.LinearAlgebra.HMatrix hiding (corr)\nimport System.Random (RandomGen, random)\nimport qualified Data.Vector as V\nimport Control.Monad.Reader\nimport RandomUtil.Random\nimport Util.Vars\n\nimport Matrix.Traversable\nimport Data.Traversable\n\ntype NNVars = Vars\n\nclass NN n where\n  create :: NNVars -> IO n\n  get :: n -> Vector Double -> Vector Double\n  train :: n -> Sample Double -> n\n  train net samp = trainV net [samp]\n  trainV :: n -> Samples Double -> n\n  randomize :: (RandomGen g) => g -> n -> (g,n)\n  getWeights :: n -> V.Vector (Matrix Double)\n  getVars :: n -> NNVars\n\ndata Net = Net\n  {\n    _network :: Network Double\n  , _vars    :: NNVars\n  }\n\ninstance NN Net where\n  create vars = do\n    n <- createNetworkW vars\n    return $ Net n vars\n  get net input = getNetwork (_vars net) (_network net) input\n  trainV net io = let vars = _vars net in Net (trainNetwork vars (_network net) io) vars\n  randomize g net = let vars = _vars net\n                        (g',n) = randomizeNetwork vars g (_network net)\n                    in (g', Net n vars)\n  getWeights (Net (Network m) _) = m\n  getVars (Net _ vars) = vars\n\ncreateNetworkW :: NNVars -> IO (Network Double)\ncreateNetworkW env = runReader createNetworkReader env\n\ncreateNetworkReader :: Reader NNVars (IO (Network Double))\ncreateNetworkReader = do\n  numInput      <- asks (getVar numberInputsS)\n  numHidden     <- asks (getVar numberHiddenS)\n  numOutput     <- asks (getVar numberOutputsS)\n  return $ createNetwork (round numInput) [(round numHidden)] (round numOutput)\n\ngetNetwork :: NNVars -> Network Double -> Vector Double -> Vector Double\ngetNetwork vars net input = runReader (getNetworkReader net input) vars\n\ngetNetworkReader :: Network Double -> Vector Double -> Reader NNVars (Vector Double)\ngetNetworkReader net input = do\n  sigOrTanh <- asks (getVar sigmoidTanS)\n  let (act, _) = getActivationFunctions sigOrTanh\n  return $ output net act input\n\ntrainNetwork :: NNVars -> Network Double -> Samples Double -> Network Double\ntrainNetwork vars net samples = runReader (trainNetworkReader net samples) vars\n\ntrainNetworkReader :: Network Double -> Samples Double -> Reader NNVars (Network Double)\ntrainNetworkReader net samples = do\n  timesToTrain  <- asks (getVar timesToTrainS)\n  learningRate  <- asks (getVar learningRateS)\n  sigOrTanh     <- asks (getVar sigmoidTanS)\n  let (act, act') = getActivationFunctions sigOrTanh\n  return $ trainNTimes (round timesToTrain) learningRate act act' net samples\n\ntype RandNet g = g -> Network Double -> (g, Network Double)\n\nrandomizeNetwork :: RandomGen g => NNVars -> RandNet g\nrandomizeNetwork vars g net = runReader (randomizeNetworkReader g net) vars\n\nrandomizeNetworkReader :: RandomGen g\n  => g -> Network Double -> Reader NNVars (g, Network Double)\nrandomizeNetworkReader g net@(Network weights) = do\n  mean <- asks (getVar meanS)\n  std  <- asks (getVar stddevS)\n  rate <- asks (getVar mutationRate)\n  let mutF = probApply rate (addNormalNoise mean std)\n      (g', weights') = mapAccumL (matrixTraverse mutF) g weights \n  return $ (g',fromWeightMatrices weights')\n\n\ntype MutateElementF g a b = (g -> a -> (g, b))\n\n-- With a probability of the provided double, apply the random function\n-- Otherwise, apply nothing\nprobApply :: RandomGen g\n  => Double -> MutateElementF g a a -> MutateElementF g a a\nprobApply p rF g a = let (r,g') = random g\n                     in if r > p then randomID g' a else rF g' a\n\nrandomID :: MutateElementF g a a\nrandomID g a = (g,a)\n                       \ngetActivationFunctions :: (Floating a) => Double -> (ActivationFunction a, ActivationFunctionDerivative a)\ngetActivationFunctions inp = let asInt :: Integer\n                                 asInt = round inp\n                             in case asInt of\n                                  1 -> (sigmoid, sigmoid')\n                                  _ -> (tanh, tanh')\n", "meta": {"hexsha": "facfea48fc229912516ef45a09fd57f0729f834f", "size": 4075, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NN/NeuralNetwork.hs", "max_stars_repo_name": "eklinkhammer/neural-algorithms", "max_stars_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "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/NN/NeuralNetwork.hs", "max_issues_repo_name": "eklinkhammer/neural-algorithms", "max_issues_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "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/NN/NeuralNetwork.hs", "max_forks_repo_name": "eklinkhammer/neural-algorithms", "max_forks_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "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.8290598291, "max_line_length": 106, "alphanum_fraction": 0.6750920245, "num_tokens": 1049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4548182404722819}}
{"text": "module Quantum where\n\n--import Data.Kind\n--import Control.Applicative\n--import Data.Typeable\nimport Prelude hiding ((^))\n--import Data.Singletons\n--import Numeric.LinearAlgebra hiding (toInt) -- hmatrix library\nimport GHC.TypeLits\n\n\nimport Prelim hiding (One)\nimport Types\nimport Interface\nimport DeepEmbedding\n\nimport LinTrans2 hiding (cnot)\n\n-- Signature\ndata QuantumSig exp = MkQubit\ntype Qubit = MkLType MkQubit\n\n\nclass HasMILL exp => HasQuantum exp where\n  new :: Bool -> exp '[] Qubit\n  meas :: exp \u03b3 Qubit -> exp \u03b3 (Lower Bool)\n  unitary :: KnownType \u03c3 => Unitary \u03c3 -> exp \u03b3 \u03c3 -> exp \u03b3 \u03c3\n\ncontrolBy :: (HasQuantum exp,KnownType \u03c3) \n          => Unitary \u03c3 -> exp \u03b3 (Qubit \u2297 \u03c3) -> exp \u03b3 (Qubit \u2297 \u03c3)\ncontrolBy u e = unitary (control u) e\n\n-- -- first element is the control\ncnot :: HasQuantum exp\n     => exp \u03b3 (Qubit \u2297 Qubit) -> exp \u03b3 (Qubit \u2297 Qubit)\ncnot = controlBy PauliX\n\n\n\n-------------------------------------------------------\n-- Deep embedding -------------------------------------\n-------------------------------------------------------\n\ntype instance Effect Deep = DensityMonad\ndata instance LVal Deep Qubit = QId Int\n\n  \ndata QuantumExp :: Sig where\n  New     :: Bool -> QuantumExp '[] Qubit\n  Meas    :: Deep \u03b3 Qubit -> QuantumExp \u03b3 (Lower Bool)\n  Unitary :: KnownType \u03c3 => Unitary \u03c3 -> Deep \u03b3 \u03c3 -> QuantumExp \u03b3 \u03c3\n\ninstance HasQuantum Deep where\n  new = Dom . New\n  meas = Dom . Meas\n  unitary u = Dom . Unitary u\n\ninstance Domain QuantumExp where\n  evalDomain (New b) _ = QId <$> newM b\n  evalDomain (Meas e) \u03c1 = do QId i <- eval e \u03c1\n                             VPut <$> measM i\n  evalDomain (Unitary u e) \u03c1 = do v <- eval e \u03c1\n                                  applyU u v\n                                  return v\n\napplyU :: forall \u03c3. KnownType \u03c3 => Unitary \u03c3 -> LVal Deep \u03c3 -> DensityMonad ()\napplyU u v = applyMatrix (interpU u) (valToQubits v)\n\nclass KnownType \u03c3 where\n  numQubits :: Int\n  valToQubits :: LVal Deep \u03c3 -> [Int]\ninstance KnownType Qubit where\n  numQubits = 1\n  valToQubits (QId i) = [i]\ninstance KnownType One where\n  numQubits = 1\n  valToQubits VUnit = []\ninstance (KnownType \u03c31,KnownType \u03c32) => KnownType (\u03c31 \u2297 \u03c32) where\n  numQubits = numQubits @\u03c31 + numQubits @\u03c32\n  valToQubits (VPair v1 v2) = valToQubits v1 ++ valToQubits v2\ninstance KnownType (Lower \u03b1) where\n  numQubits = 0\n  valToQubits (VPut _) = []\n\n\n\ninstance Show (Unitary \u03c3) where\n  show Identity = \"I\"\n  show Hadamard = \"H\"\n  show PauliX   = \"X\"\n  show PauliY   = \"Y\"\n  show PauliZ   = \"Z\"\n  show (R m)    = \"R \" ++ show m\n  show (Alt u0 u1) = \"(\" ++ show u0 ++ \" \u2295 \" ++ show u1 ++ \")\"\n  show (Transpose u) = show u ++ \"\u2020\"\n-- instance Show (QuantumLExp lang g \u03c4) where\n--   show (New b)  = \"New(\" ++ show b ++ \")\"\n--   show (Meas q) = \"Meas(\" ++ show q ++ \")\"\n--   show (Unitary u e) = \"Unitary (\" ++ show u ++ \") \" ++ show e\n-- --  show (ControlBy _ e e') = show e ++ \"`ControlBy`\" ++ show e'\n\n-- Quantum Data\n\n-- Add more?\ndata Unitary (\u03c3 :: LType) where\n  Identity  :: KnownType \u03c3 => Unitary \u03c3\n  Hadamard  :: Unitary Qubit\n  PauliX    :: Unitary Qubit -- (NOT)\n  PauliY    :: Unitary Qubit\n  PauliZ    :: Unitary Qubit\n  R         :: Int -> Unitary Qubit\n  Alt       :: KnownType \u03c3 => Unitary \u03c3 -> Unitary \u03c3 -> Unitary (Qubit \u2297 \u03c3)\n  Transpose :: Unitary \u03c3 -> Unitary \u03c3\n\ncontrol :: KnownType \u03c3  => Unitary \u03c3 -> Unitary (Qubit \u2297 \u03c3)\ncontrol = Alt Identity\n\n{-\ntype KnownQubits \u03c3 = SingI (NumQubits \u03c3)\n\nunitarySing :: forall \u03c3. Unitary \u03c3 -> Sing (NumQubits \u03c3)\nunitarySing Identity = sing\nunitarySing Hadamard = one\nunitarySing PauliX   = one\nunitarySing PauliY   = one\nunitarySing PauliZ   = one\nunitarySing (R _)    = one\nunitarySing (Alt u0 _)    = SS $ unitarySing u0\nunitarySing (Transpose u) = unitarySing u\n-}\n\n\n\n\n\n\n-- instance HasQuantumEffect ('Sig DensityMonad sigs) where\n-- --  type QUnitary ('Sig DensityMonad sigs) = Density\n--type QUnitary \u03c3 = Squared (NumQubits \u03c3)\n\ninterpU :: forall \u03c3. KnownType \u03c3 => Unitary \u03c3 -> Matrix\ninterpU Identity = ident $ numQubits @\u03c3\ninterpU Hadamard = hadamard\ninterpU PauliX   = pauliX\ninterpU PauliY   = pauliY\ninterpU PauliZ   = pauliZ\ninterpU (R m)    = undefined -- rotation about the z axis by 2\u03c0i/2^m?\ninterpU (Alt (u0 :: Unitary \u03c3') u1) =\n    (newD False `kron` interpU u0) + (newD True `kron` interpU u1)\ninterpU (Transpose u) = transpose $ interpU u\n\ntype family   NumQubits (\u03c4 :: LType) :: Nat \ntype instance NumQubits One            = 0\ntype instance NumQubits Qubit          = 1\ntype instance NumQubits (\u03c41 \u2297 \u03c42) = NumQubits \u03c41 + NumQubits \u03c42\n\n{-\ninstance HasQuantumDom lang => Domain QuantumDom (lang :: Lang sig) where\n\n  evalDomain _ (New b)   = do\n    i <- newQubit @sig b\n    return $ vqubit i\n  evalDomain \u03c1 (Meas e)  = do\n    VQubit i <- toDomain @QuantumDom <$> eval' \u03c1 e\n    b <- measQubit @sig i\n    return $ vput b\n  evalDomain \u03c1 (Unitary u e) = do\n    v  <- eval' \u03c1 e\n    qs <- valToQubits @sig v\n    applyU @sig u qs\n    return v \n    \ntype Qubits (\u03c4 :: LType sig) = [QId]\n\nvalToQubits :: forall sig (lang :: Lang sig) \u03c4.\n              HasQuantumDom lang => LVal lang \u03c4 -> SigEffect sig (Qubits \u03c4)\nvalToQubits v = case toDomain' @QuantumDom v of\n    Just (VQubit i) -> return [i]\n    Nothing -> case toDomain' @OneDom v of\n      Just VUnit -> return []\n      Nothing -> case toDomain' @TensorDom v of\n        Just (VPair v1 v2) -> liftA2 (++) (valToQubits v1) (valToQubits v2)\n        Nothing -> return [] \n--        case fromLVal' proxyLower v of\n--          Just (VPut _) -> return []\n--          Nothing       -> error \"Cannot extract qubits from the given value\"\n\ntype family   NumQubits (\u03c4 :: LType sig) :: Nat \ntype instance NumQubits ('LType _ 'OneSig)            = 'Z\ntype instance NumQubits ('LType _ 'QubitSig)          = 'S 'Z\ntype instance NumQubits ('LType _ ('TensorSig \u03c41 \u03c42)) = NumQubits \u03c41 `Plus` NumQubits \u03c42\n-}\n\n--type instance NumQubits ('LType _ ('PlusSig \u03c41 \u03c42))   = NumQubits \u03c41 `Plus` NumQubits \u03c42\ntype instance NumQubits (Lower _)      = 0\n  \n-- EXAMPLES\n\n\n-- Flip -------------------------------------------\n\n\nqflip :: Lin Deep Bool\nqflip = suspend $ meas (unitary Hadamard (new False))\n\n-- ----------------------------------------------------\n-- -- Teleportation -----------------------------------\n-- ----------------------------------------------------\n\nplus_minus :: HasQuantum exp => Bool -> Lift exp Qubit\nplus_minus b = suspend $ unitary Hadamard $ new b\n\nshare :: HasQuantum exp => Lift exp (Qubit \u22b8 Qubit \u2297 Qubit)\nshare = suspend . \u03bb $ \\q -> cnot (q \u2297 new False)\n\nbell00 :: HasQuantum exp => Lift exp (Qubit \u2297 Qubit)\nbell00 = suspend $ force (plus_minus False) `letin` \\a ->\n                   force share ^ a\n\nalice :: HasQuantum exp => Lift exp (Qubit \u22b8 Qubit \u22b8 Lower (Bool,Bool))\nalice = suspend . \u03bb $ \\q -> \u03bb $ \\a ->\n            cnot (q \u2297 a) `letPair` \\(q,a) ->\n            meas (unitary Hadamard q) >! \\x ->\n            meas a >! \\y ->\n            put (x,y)\n    \nbob :: HasQuantum exp => Bool -> Bool -> Lift exp (Qubit \u22b8 Qubit)\nbob x y = suspend . \u03bb $ \\b ->\n    if y then unitary PauliX b else b `letin` \\b ->\n    if x then unitary PauliZ b else b\n\nteleport :: HasQuantum exp => Lift exp (Qubit \u22b8 Qubit)\nteleport = suspend . \u03bb $ \\q ->\n    force bell00 `letPair` \\(a,b) ->\n    force alice ^ q ^ a >! \\(x,y) ->\n    force (bob x y) ^ b\n\nteleport0 :: Lin Deep Bool\nteleport0 = suspend . meas $ force teleport ^ new False\n\n\nmain' :: Lin Deep Bool\nmain' = suspend $ force bell00 `letPair` \\(q1,q2) ->\n                 meas q1 >! \\x ->\n                 meas q2 >! \\y ->\n                 put (x == y)\n\nmain :: IO ()\nmain = print $ run main'\n\n\n-- Dependent fourier transform\n\ntype family (\u03c3 :: LType) \u2297\u2297 (n :: Nat) :: LType where\n    \u03c3 \u2297\u2297 n = CompareOrd (CmpNat n 1)\n                        One                -- n = 0\n                        \u03c3                  -- n = 1\n                        (\u03c3 \u2297 (\u03c3 \u2297\u2297 (n-1))) -- n >= 2\n--  \u03c3 \u2297\u2297 Z = One\n--  \u03c3 \u2297\u2297 S Z = \u03c3\n--  \u03c3 \u2297\u2297 (S (S n)) = \u03c3 \u2297 (\u03c3 \u2297\u2297 S n)\n\n\n{- TODO: fix\nrotations :: forall (m :: Nat) (n :: Nat) exp. (HasQuantum exp)\n          => Sing m -> Sing n -> Lift exp (Qubit \u2297\u2297 S n \u22b8 Qubit \u2297\u2297 S n)\nrotations _ SZ      = idL\nrotations _ (SS SZ) = idL\nrotations m (SS n'@(SS _)) = suspend . \u03bbpair $ \\(c,qs) -> qs `letPair` \\(q,qs') ->\n    force (rotations m n') ^ (c \u2297 qs') `letPair` \\(c,qs') ->\n    controlBy (R $ 2 + toInt m - toInt n') (c \u2297 q) `letPair` \\(c,q) ->\n    c \u2297 (q \u2297 qs')\n\nfourier :: forall n exp. (HasQuantum exp)\n        => Sing n -> Lift exp (Qubit \u2297\u2297 n \u22b8 Qubit \u2297\u2297 n)\nfourier SZ = idL\nfourier (SS SZ) = suspend . \u03bb $ unitary Hadamard\nfourier (SS n'@(SS _)) = Suspend . \u03bbpair $ \\(q,w) ->\n        force (fourier n') ^ w `letin` \\w -> \n        force (rotations (SS n') n') ^ (q \u2297 w)\n-}\n", "meta": {"hexsha": "b5e8b47b5ab5e6fc348f4d0a153d277266b3e233", "size": 8646, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/examples/Quantum.hs", "max_stars_repo_name": "jpaykin/LNLHaskell", "max_stars_repo_head_hexsha": "7c3e3880d2702b5456326870ba4863f27a8606b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2016-10-23T18:46:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T06:00:45.000Z", "max_issues_repo_path": "src/examples/Quantum.hs", "max_issues_repo_name": "jpaykin/LNLHaskell", "max_issues_repo_head_hexsha": "7c3e3880d2702b5456326870ba4863f27a8606b4", "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/examples/Quantum.hs", "max_forks_repo_name": "jpaykin/LNLHaskell", "max_forks_repo_head_hexsha": "7c3e3880d2702b5456326870ba4863f27a8606b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-29T12:57:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-29T14:22:00.000Z", "avg_line_length": 30.6595744681, "max_line_length": 90, "alphanum_fraction": 0.5706685172, "num_tokens": 2802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4548182364051085}}
{"text": "{-# LANGUAGE DataKinds, TypeApplications, RankNTypes, FlexibleContexts, \n             PartialTypeSignatures, TypeFamilies, TypeOperators, ScopedTypeVariables #-}\n\nimport qualified Control.Foldl as L\nimport qualified Numeric.LinearAlgebra.Static as H\nimport Numeric.LinearAlgebra.Data\nimport GHC.TypeNats\nimport Data.List\nimport Numeric.Backprop\nimport System.Random\nimport System.Random.Shuffle\nimport Networks\nimport Optimierung\nimport MNIST\nimport Tuple \nimport Data.Proxy\n\nmain :: IO ()\nmain = testDigits\n\nantwort :: KnownNat n => H.R n -> Int\nantwort = maxIndex . H.extract \n\nnormalizeInput :: (KnownNat n, KnownNat m) \n               => (H.R n, H.R m)\n               -> (H.R n, H.R m)\nnormalizeInput (x, y) = (x / 255, y)\n\nmultilayerPerceptron :: forall i o. KN i o => Modell _ (H.R i) (H.R o)\nmultilayerPerceptron = sigmoidNoBias @30 <~ sigmoid \n\nthreeLayer :: forall i o n. (KN i o, KnownNat n) => Proxy n -> Modell _ (H.R i) (H.R o)\nthreeLayer _ = sigmoid @n <~ sigmoid \n\nmP' :: (KN i o) => Modell _ (H.R i) (H.R o)\nmP' = leakyReLU @30 <~ leakyReLU\n\nemptyLn = putStr \"\\n\"\n\nrandomOS :: (Fractional a, Random a) => a -> a -> IO a \nrandomOS x y = (* y) . subtract x <$> randomIO \n\ntrainableRBM s p0 = makeFoldAll (Minibatch (10, L2 (1.0, 0.000))) (rbmcd1 s) p0 \n\ntestDigits :: IO ()\ntestDigits = do\n    let importImage l i = fmap normalizeInput <$> unsafeGetBoth l i\n    let inDownloads = (++) \"/home/julian/Downloads/\"\n    let lpath  = inDownloads \"train-labels-idx1-ubyte\"\n    let ipath  = inDownloads \"train-images-idx3-ubyte\"\n    let tlpath = inDownloads \"t10k-labels-idx1-ubyte\"\n    let tipath = inDownloads \"t10k-images-idx3-ubyte\"\n\n    test  <- importImage tlpath tipath\n    train <- importImage lpath  ipath\n    trainData <- concat <$> (mapM shuffleM $ replicate 30 train)\n\n    p0 <- randomIO \n\n    let trained = L.fold (uberwachtesFold (Minibatch (10, SGD 1.5)) multilayerPerceptron \n                          se' p0) trainData\n\n    emptyLn\n    print $ (/ 100) . sum . map (\\(x, l) -> \n        if ((== antwort l) . antwort . prediction trained $ x) \n        then 1 \n        else 0) $ test\n    \n    print $ auswerten (antwort . evalBP2 multilayerPerceptron trained) \n        (==) (map (\\(x, a) -> (x, antwort a)) test)\n    \n    where pred p x i l = (antwort l == x) && ((== x) . antwort . prediction p $ i)\n          prediction p i = evalBP2 multilayerPerceptron p i\n\n\ntestAND :: IO ()\ntestAND = do \n    -- mische 100000 Samples \n    daten <- shuffleM . take 100000 . cycle $ samps              \n    -- zuf\u00e4lliger Anfangswert, der resultierende Vektor von randomIO \n    -- ist standard normal verteilt\n    p0 <- (* 0.1) <$> randomIO\n    -- Netz wird trainiert und optimiert mit SGD und der Lernrate 0.1\n    let trainiert = L.fold (uberwachtesFold (SGD 0.1) linear2 se p0) daten\n    -- Hilfsfunktion f\u00fcr Ausgabe\n    let disp = printLogicOpWith (evalBP2 linear2 trainiert) \n    \n    emptyLn\n    disp 0 0\n    disp 1 0\n    disp 0 1\n    disp 1 1\n\n    print $ auswerten (evalBP2 linear2 trainiert) (\\x y -> round x == round y) daten\n    \n-- Die vier (Eingabe, Ziel) Paare, die gelernt werden\n-- diese entsprechen dem logischen UND.\nsamps :: [(H.R 2, Double)]\nsamps = [(H.vec2 0 0, 0), (H.vec2 1 0, 0), (H.vec2 0 1, 0), (H.vec2 1 1, 1)]\n\nprintLogicOpWith :: (H.R 2 -> Double) -> Double -> Double -> IO ()\nprintLogicOpWith f a b = print $ disp (show . f $ H.vec2 a b) \n    where disp ans = \"[\" ++ show a ++ \", \" ++ show b  ++ \"]: \" ++ ans\n    \nauswerten :: Ord b\n          => (a -> b) \n          -> (b -> b -> Bool) \n          -> [(a, b)] \n          -> [Int] \nauswerten f pred xs = map (foldr sumCorrect 0) . groupBy sndEq . sortBy comp $ xs \n    where sndEq (_, b1) (_, b2) = b1 == b2 \n          comp  (_, b1) (_, b2) = compare b1 b2\n          sumCorrect x n        = if (eval x) then n+1 else n\n          eval (a, b)           = pred (f a) b\n", "meta": {"hexsha": "1c3a2265d592d91803d65e7bd46ce7313175e3e9", "size": 3849, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Zahlen.hs", "max_stars_repo_name": "QQMBR/BLL-FP-NN", "max_stars_repo_head_hexsha": "be952cd338113de358297772a56d61ed74b665fe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Zahlen.hs", "max_issues_repo_name": "QQMBR/BLL-FP-NN", "max_issues_repo_head_hexsha": "be952cd338113de358297772a56d61ed74b665fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Zahlen.hs", "max_forks_repo_name": "QQMBR/BLL-FP-NN", "max_forks_repo_head_hexsha": "be952cd338113de358297772a56d61ed74b665fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4695652174, "max_line_length": 89, "alphanum_fraction": 0.6087295401, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.45471311454396557}}
{"text": "module Main where\n\nimport Math.FFT (dftRC)\nimport Data.Array.IArray (listArray, amap, elems)\nimport Data.Array.CArray (CArray)\nimport Data.Complex (Complex, magnitude)\n\nimport Sound.Pulse.Simple\n\nimport GHC.Conc (TVar,writeTVar,atomically,newTVar,forkIO,readTVar)\nimport Control.Monad (forever)\n\nimport Graphics.Gloss.Interface.IO.Animate (animateIO)\nimport Graphics.Gloss.Data.Color (black,white)\nimport Graphics.Gloss.Data.Controller (Controller)\nimport Graphics.Gloss.Data.Display (Display(..))\nimport Graphics.Gloss.Data.Picture\n\nsource = \"alsa_output.usb-AudioQuest_AudioQuest_DragonFly_Black_v1.5_AQDFBL0100116667-00.analog-stereo.monitor\"\n\nsampleWindow = 1024\n\n\n-- Copy samples from source into a TVar indefinitely\ncapture :: Maybe String -> TVar [Float] -> IO ()\ncapture source sink = do\n    s <- simpleNew Nothing \"spectraled\" Record source \"capture\" sampleSpec Nothing bufferAttr\n    forever $ copySamples s\n    where\n        bufferAttr = Just $ BufferAttr Nothing Nothing Nothing Nothing (Just $ sampleWindow * 4)\n        sampleSpec = SampleSpec (F32 LittleEndian) 44100 1\n\n        copySamples s = do\n            samples <- simpleRead s sampleWindow :: IO [Float]\n            atomically $ writeTVar sink samples\n\nrender :: TVar [Float] -> IO ()\nrender samples = \n    animateIO display white renderFrame callback\n    where\n        display = InWindow \"spectraled\" (sampleWindow, 200) (0, 0)\n\n        renderFrame :: Float -> IO Picture\n        renderFrame _ = do\n            ss <- atomically $ readTVar samples\n            --return $ line $ samplesToPath (-256) $ fmap log $ fft ss\n            return $ Pictures $ samplesToBars (-256) $ fft ss\n\n        fft :: [Float] -> [Float]\n        fft ss = elems $ amap magnitude $ dftRC $ listArray (0, (length ss - 1)) ss\n\n        samplesToPath :: Float -> [Float] -> [Point]\n        samplesToPath _ [] = []\n        samplesToPath i (s:ss) = (i, s * 10) : samplesToPath (i + 1) ss\n\n        samplesToBars :: Float -> [Float] -> [Picture]\n        samplesToBars _ [] = []\n        samplesToBars i (s:ss) = bin : samplesToBars (i + 1) ss\n            where\n                bin = translate (i * 6) (s * 5) $ rectangleSolid 5 (s * 10)\n\n        callback :: Controller -> IO ()\n        callback _ = return ()\n\nmain :: IO ()\nmain = do\n    samples <- atomically $ newTVar $ take sampleWindow $ repeat 0\n    captureTID <- forkIO $ capture (Just source) samples\n    render samples\n", "meta": {"hexsha": "27c830b0cf979b86bf7c23ce2a2048285318465d", "size": 2415, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "awh/spectraled-hs", "max_stars_repo_head_hexsha": "510a492c56ca70b626f123149213b0a41507947f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "awh/spectraled-hs", "max_issues_repo_head_hexsha": "510a492c56ca70b626f123149213b0a41507947f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "awh/spectraled-hs", "max_forks_repo_head_hexsha": "510a492c56ca70b626f123149213b0a41507947f", "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.5, "max_line_length": 111, "alphanum_fraction": 0.6575569358, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4546066343016437}}
{"text": "{-|\nModule      : Example.Mnist\nDescription : MNIST traning example\nCopyright   : (c) Anatoly Yakovenko, 2015-2016\nLicense     : MIT\nMaintainer  : aeyakovenko@gmail.com\nStability   : experimental\nPortability : POSIX\n\nThis module implements an example traning the MNIST data set.  Using\nthe dataset parsing code from:\n<https://github.com/mhwombat/backprop-example/blob/master/Mnist.hs>\n-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\nmodule Examples.Mnist (generateTrainBatches\n                      ,generateTrainLabels\n                      ,generateTestBatches\n                      ,mnist\n                      )where\n\nimport Control.Applicative((<|>))\nimport Control.Monad.Trans(liftIO)\nimport Control.Monad(when,forever,forM_, foldM_)\nimport qualified Data.ByteString.Lazy as BL\nimport Data.Binary.Get hiding(label)\nimport qualified Data.Binary as B\nimport Data.Word\nimport qualified Data.List.Split as S\nimport qualified Data.Array.Repa as R\nimport Codec.Compression.GZip as GZ\nimport Data.List.Split(chunksOf)\nimport Statistics.LinearRegression as S\n\nimport qualified Data.DNN.Trainer as T\nimport qualified Data.RBM as RB\nimport qualified Data.Matrix as M\nimport qualified Data.ImageUtils as I\nimport Data.Matrix(Matrix(..)\n                  ,U\n                  ,B\n                  ,I\n                  ,H\n                  )\n{-|\nTrain a network to recognize digits from the MNIST dataset.  Start by training\neach layer as an RBM with the Contrastive Divergence algorithm.  Then finish\nup the traning with Back-propagation.  Animate the weights as the traning\nprogresses.\n-}\nmnist :: IO ()\nmnist = do\n   let r1 = RB.new 0 785 530 --dimentions include the bias node\n       r2 = RB.new 0 530 530 --sqrt(529) == 23\n       r3 = RB.new 0 530 11\n\n   -- train the first layer\n   tr1 <- B.decodeFile \"dist/rbm1\" --decode if this layer is already been trained\n      <|> do tr1 <- snd <$> (T.run [r1] $ trainCD \"dist/rbm1.gif\" 0.01)\n             B.encodeFile \"dist/rbm1\" tr1 --save the layer to a file\n             return tr1\n\n   -- train the second layer\n   tr2 <- B.decodeFile \"dist/rbm2\"\n      <|> do tr2 <- snd <$> (T.run (tr1++[r2]) $ trainCD \"dist/rbm2.gif\" 0.001)\n             B.encodeFile \"dist/rbm2\" tr2\n             return tr2\n\n   -- train the third layer\n   tr3 <- B.decodeFile \"dist/rbm3\"\n      <|> do tr3 <- snd <$> (T.run (tr2++[r3]) $ trainCD \"dist/rbm3.gif\" 0.001)\n             B.encodeFile \"dist/rbm3\" tr3\n             return tr3\n\n   -- backprop\n   let train pbp xx = do\n            let name = \"dist/bp\" ++ (show xx)\n                gif = name ++ \".gif\"\n            bp <- B.decodeFile name\n               <|> do bp <- snd <$> (T.run pbp $ trainBP gif 0.01 0.001)\n                      B.encodeFile name bp\n                      return bp\n            mapM_ (testBatch bp) [0..9] --print how well our network recognizes the images\n            return bp\n   foldM_ train tr3 [1::Int ..]  --train forever\n\n-- max number of minibatches\nmaxCount :: Int\nmaxCount = 25000\n-- how often to check the progress\ntestCount :: Int\ntestCount = 1000\n-- size of the minibatch\nrowCount :: Int\nrowCount = 5\n\n-- |train the last layer in the DNN via the CD algorithm\ntrainCD :: String -> Double ->  T.Trainer IO ()\ntrainCD file mine = forever $ do\n  T.setLearnRate 0.001\n  let batchids = [0..468::Int]\n  forM_ batchids $ \\ ix -> do\n     big <- liftIO $ readBatch ix\n     small <- mapM M.d2u $ M.splitRows rowCount big\n     forM_ small $ \\ batch -> do\n        T.contraDiv batch\n        cnt <- T.getCount\n        when (0 == cnt `mod` testCount) $ do\n           nns <- T.getDNN\n           ww <- M.cast1 <$> M.transpose (last nns)\n           liftIO $ I.appendGIF file ww\n        when (0 == cnt `mod` testCount) $ do\n           err <- T.reconErr big\n           liftIO $ print (cnt, err)\n           when (cnt >= maxCount || err < mine) $ T.finish_\n\n-- |train the entire DNN via backprop\ntrainBP :: String -> Double -> Double -> T.Trainer IO ()\ntrainBP file lr mine = forever $ do\n  T.setLearnRate lr\n  let batchids = [0..468::Int]\n  forM_ batchids $ \\ ix -> do\n     bbatch <- liftIO $ readBatch ix\n     blabel <- liftIO $ readLabel ix\n     sbatch <- mapM M.d2u $ M.splitRows rowCount bbatch\n     slabel <- mapM M.d2u $ M.splitRows rowCount blabel\n     forM_ (zip sbatch slabel) $ \\ (batch,label) -> do\n        T.backProp batch label\n        cnt <- T.getCount\n        when (0 == cnt `mod` testCount) $ do\n           gen <- T.backward (Matrix $ toLabelM [0..9])\n           liftIO $ I.appendGIF file gen\n        when (0 == cnt `mod` testCount) $ do\n           err <- T.forwardErr bbatch blabel\n           liftIO $ print (cnt, err)\n           when (cnt >= maxCount || err < mine) $ T.finish_\n\n-- |compute the correlation between the labels and the DNN output\ntestBatch :: [Matrix U I H] -> Int -> IO ()\ntestBatch nns ix = do\n   let name = \"dist/test\" ++ (show ix)\n   bxi <- Matrix <$> readArray name\n   let bxh = M.fromList (M.row bxi, 11) $ concat $ replicate (M.row bxi) $ labelVector ix\n   (bxh',_) <- T.run nns $ T.feedForward bxi\n   let cor = S.correl (M.toUnboxed bxh') (M.toUnboxed bxh)\n   print (ix, cor)\n\n-- |Generate a batch of images with bias values for training.\ngenerateTrainBatches :: IO ()\ngenerateTrainBatches = do\n   images <- readImages \"dist/train-images-idx3-ubyte.gz\"\n   let batches = map toMatrix $ chunksOf 128 images\n   (flip mapM_) (zip [0::Integer ..] batches) $ \\ (ix, bb) -> do\n      let name = \"dist/train\" ++ (show ix)\n      writeArray name bb\n\n-- |Generate a batch of of matching labels with bias values.\ngenerateTrainLabels :: IO ()\ngenerateTrainLabels = do\n   labels <- readLabels \"dist/train-labels-idx1-ubyte.gz\"\n   let batches = map toLabelM $ chunksOf 128 labels\n   (flip mapM_) (zip [0::Integer ..] batches) $ \\ (ix, bb) -> do\n      let name = \"dist/label\" ++ (show ix)\n      writeArray name bb\n\n-- |Generate a the test images with bias values sorted by label.\ngenerateTestBatches :: IO ()\ngenerateTestBatches = do\n   images <- readImages \"dist/t10k-images-idx3-ubyte.gz\"\n   labels <- readLabels \"dist/t10k-labels-idx1-ubyte.gz\"\n   (flip mapM_) ([0..9]) $ \\ ix -> do\n      let name = \"dist/test\" ++ (show ix)\n      let batch = filter (((==) ix) . fst) $ zip labels images\n      let bb = toMatrix $ snd $ unzip batch\n      writeArray name bb\n\n-- |generate a 2d array from the list of images\n-- |add the bias node as the first node to each image\ntoMatrix :: [Image] -> R.Array R.U R.DIM2 Double\ntoMatrix images = m\n  where\n        m = R.fromListUnboxed (R.Z R.:. len R.:. maxsz) (concatMap pixels images)\n        maxsz = 1 + (maximum $ map (\\ ii -> (iRows ii) * (iColumns ii)) images)\n        len = length images\n        pixels im = take maxsz $ 1:((normalisedData im) ++ [0..])\n\n-- |file IO utils\nreadImages :: FilePath -> IO [Image]\nreadImages filename = do\n  content <- GZ.decompress <$> BL.readFile filename\n  let (_, _, r, c, unpackedData) = runGet deserialiseHeader content\n  return (map (Image (fromIntegral r) (fromIntegral c)) unpackedData)\n\nwriteArray :: String -> R.Array R.U R.DIM2 Double -> IO ()\nwriteArray fileName array = do\n   let (R.Z R.:. r R.:. c) = R.extent array\n   B.encodeFile fileName (r,c,R.toList array)\n\nreadArray ::String -> IO (R.Array R.U R.DIM2 Double)\nreadArray fileName = do\n   (r,c,ls) <- B.decodeFile fileName\n   return $ R.fromListUnboxed  (R.Z R.:. r R.:. c) ls\n\n\nreadBatch :: Int -> IO (Matrix U B I)\nreadBatch ix = Matrix <$> readArray name\n   where name = \"dist/train\" ++ (show ix)\n\nreadLabel :: Int -> IO (Matrix U B H)\nreadLabel ix = Matrix <$> readArray name\n   where name = \"dist/label\" ++ (show ix)\n\n\n-- |MNIST image parsing code\n-- |from https://github.com/mhwombat/backprop-example/blob/master/Mnist.hs\ndata Image = Image {\n      iRows :: Int\n    , iColumns :: Int\n    , iPixels :: [Word8]\n    } deriving (Eq, Show)\n\nnormalisedData :: Image -> [Double]\nnormalisedData image = map normalisePixel (iPixels image)\n\nnormalisePixel :: Word8 -> Double\nnormalisePixel p = (fromIntegral p) / 255.0\n\ntoLabelM :: [Int] -> R.Array R.U R.DIM2 Double\ntoLabelM labels = m\n  where\n        m = R.fromListUnboxed (R.Z R.:. len R.:. 11) (concatMap labelVector labels)\n        len = length labels\n\nlabelVector :: Int -> [Double]\nlabelVector ll = take 11 $ 1.0:(start ++ end)\n   where start = take ll $ repeat 0.0\n         end = 1.0 : repeat 0.0\n\n\n{-|\nMNIST label file format\n\n[offset] [type]          [value]          [description]\n0000     32 bit integer  0x00000801(2049) magic number (MSB first)\n0004     32 bit integer  10000            number of items\n0008     unsigned byte   ??               label\n0009     unsigned byte   ??               label\n........\nxxxx     unsigned byte   ??               label\n\nThe labels values are 0 to 9.\n-}\ndeserialiseLabels :: Get (Word32, Word32, [Word8])\ndeserialiseLabels = do\n  magicNumber <- getWord32be\n  count <- getWord32be\n  labelData <- getRemainingLazyByteString\n  let labels = BL.unpack labelData\n  return (magicNumber, count, labels)\n\nreadLabels :: FilePath -> IO [Int]\nreadLabels filename = do\n  content <- GZ.decompress <$> BL.readFile filename\n  let (_, _, labels) = runGet deserialiseLabels content\n  return (map fromIntegral labels)\n\n{-|\nMNIST Image file format\n\n[offset] [type]          [value]          [description]\n0000     32 bit integer  0x00000803(2051) magic number\n0004     32 bit integer  ??               number of images\n0008     32 bit integer  28               number of rows\n0012     32 bit integer  28               number of columns\n0016     unsigned byte   ??               pixel\n0017     unsigned byte   ??               pixel\n........\nxxxx     unsigned byte   ??               pixel\n\nPixels are organized row-wise. Pixel values are 0 to 255. 0 means background (white), 255\nmeans foreground (black).\n-}\ndeserialiseHeader :: Get (Word32, Word32, Word32, Word32, [[Word8]])\ndeserialiseHeader = do\n  magicNumber <- getWord32be\n  imageCount <- getWord32be\n  r <- getWord32be\n  c <- getWord32be\n  packedData <- getRemainingLazyByteString\n  let len = fromIntegral (r * c)\n  let unpackedData = S.chunksOf len (BL.unpack packedData)\n  return (magicNumber, imageCount, r, c, unpackedData)\n\n\n", "meta": {"hexsha": "b1d949bb23923458f68616bb54ce500e96c504bc", "size": 10131, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Examples/Mnist.hs", "max_stars_repo_name": "sakridge/rbm", "max_stars_repo_head_hexsha": "e1767257ba7499e09b31b34b1ec76c14272ba127", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2015-10-17T03:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T02:07:30.000Z", "max_issues_repo_path": "Examples/Mnist.hs", "max_issues_repo_name": "sakridge/rbm", "max_issues_repo_head_hexsha": "e1767257ba7499e09b31b34b1ec76c14272ba127", "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": "Examples/Mnist.hs", "max_forks_repo_name": "sakridge/rbm", "max_forks_repo_head_hexsha": "e1767257ba7499e09b31b34b1ec76c14272ba127", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-04-05T17:56:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:35:25.000Z", "avg_line_length": 34.3423728814, "max_line_length": 90, "alphanum_fraction": 0.6276774257, "num_tokens": 2905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45427639859562935}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes, ConstraintKinds #-}\n\nmodule PCA.GaussianProcess\n       ( GaussianProcess (..)\n       , GPTrainingData (..)\n       , PosteriorSample (..)\n       , gpToPosteriorSample\n       , kernelGP\n       ) where\n\nimport Universum hiding (transpose, Vector)\n\nimport Control.Lens (makeLenses)\n\nimport Data.Array.Repa\nimport Data.Array.Repa.Repr.Unboxed (Unbox)\nimport Numeric.LinearAlgebra.Repa hiding (Matrix, Vector)\nimport System.Random (Random, mkStdGen)\n\nimport PCA.Types (InputObservations(..), Matrix, Vector)\nimport PCA.Util\n\ndata GaussianProcess a = GaussianProcess\n    { -- | we define the gaussian process by some kernel function\n      _kernelGP :: Vector D a -> Vector D a -> Matrix D a\n    }\n\ndata GPTrainingData a = GPTrainingData\n    { _inputTrain  :: Vector D a  -- ^ an input training data\n    , _outputTrain :: Vector D a  -- ^ an output training data\n    }\n\nmakeLenses ''GaussianProcess\nmakeLenses ''GPTrainingData\n\nnewtype PosteriorSample a = PosteriorSample\n    { unSample :: Matrix D a  -- ^ an posterior sample\n    }\n\n-- | The constraint kind required for getting a posterior sample by a given GP\ntype GPConstraint a =\n  ( Field a\n  , Random a\n  , Unbox a\n  , Floating a\n  , Eq a\n  )\n\n-- | The Main GP function: get a posterior sample by some kernel function, input observations and the training data\n\ngpToPosteriorSample\n  :: GPConstraint a\n  => InputObservations a        -- ^ input observations\n  -> GaussianProcess a          -- ^ a kernel function\n  -> GPTrainingData a           -- ^ a training data\n  -> Int                        -- ^ the number of samples\n  -> Maybe (PosteriorSample a)  -- ^ a posterior functional prior\ngpToPosteriorSample (InputObservations observe@(ADelayed (Z :. len) _)) gP trainingData sampleNumber = do\n  -- | The kernel applied to input test points (so-called K_ss)\n  let covarianceMatrix = kernel observe observe\n\n  -- | The kernel applied to input training points (so-called K)\n  let trainingKernel = kernel inputTrain' inputTrain'\n\n  -- | The Cholesky decomposition applied to kernel of training points (:), so-called L\n  let cholK = cholSH $ trainingKernel +^\n                (smap (* 0.00005) . identD . size . extent $ inputTrain')\n\n  -- | a covariance between test points and input training points (so-called K_s)\n  let testPointMean = kernel observe inputTrain'\n\n  -- | (the roots of L * x = K_s)\n  cholKSolve <- delay <$> linearSolveS cholK testPointMean\n\n  -- | Here we solve  alinear system for output training points\n  cholKSolveOut <- delay <$> linearSolveS cholK (transposeMatrix $ toMatrix outputTrain' len)\n\n  -- | Here we compute a mean\n  let mean = (transposeMatrix cholKSolveOut) `mulD` cholKSolve\n\n  -- | A posterior\n  let postF' = cholSH $\n                     covarianceMatrix +^\n                     ((smap (* 1.0e-6) (identD len)) -^\n                     (transposeMatrix cholKSolve) `mulD` cholKSolve)\n\n  -- | A posterior sample\n  return $ (PosteriorSample $ mean +^ (functionalPrior postF' sampleNumber))\n    where\n       kernel = gP ^. kernelGP\n       inputTrain' = trainingData ^. inputTrain\n       outputTrain' = trainingData ^. outputTrain\n       mulD m n = delay $ m `mulS` n\n       functionalPrior matrix@(ADelayed (Z :. rows :. _) _) numberSample =\n         delay $ matrix `mulS` randomCoeffs\n         where\n           randomCoeffs = randomMatrixD (mkStdGen (-4)) (rows, numberSample)\n", "meta": {"hexsha": "e70d260cb56428ffbed3e18bc59132708f4a11a2", "size": 3395, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PCA/GaussianProcess.hs", "max_stars_repo_name": "serokell/PCA", "max_stars_repo_head_hexsha": "2f71ebd4b3bb06308eaf761cc710df0955a5067c", "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/PCA/GaussianProcess.hs", "max_issues_repo_name": "serokell/PCA", "max_issues_repo_head_hexsha": "2f71ebd4b3bb06308eaf761cc710df0955a5067c", "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/PCA/GaussianProcess.hs", "max_forks_repo_name": "serokell/PCA", "max_forks_repo_head_hexsha": "2f71ebd4b3bb06308eaf761cc710df0955a5067c", "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.6428571429, "max_line_length": 115, "alphanum_fraction": 0.6677466863, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4542763933986685}}
{"text": "{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE ImplicitParams      #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications    #-}\n\nmodule Main ( main ) where\n\nimport           Data.Int\nimport           Data.List (sort)\nimport           Data.List.NonEmpty (NonEmpty(..))\nimport           Data.Massiv.Array (getComp, index')\nimport qualified Data.Set as S\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Storable as VS\nimport qualified Data.Vector.Unboxed as U\nimport           Data.Word\nimport           Geography.MapAlgebra\nimport qualified Numeric.LinearAlgebra as LA\nimport           Prelude as P\nimport           Test.HUnit.Approx\nimport qualified Test.QuickCheck.Arbitrary as QC\nimport           Test.Tasty\nimport           Test.Tasty.HUnit\nimport           Test.Tasty.QuickCheck\n\n---\n\nmain :: IO ()\nmain = do\n  img <- fromRight <$> fromGray \"data/gray512.tif\"\n  defaultMain $ suite img\n\nsuite :: Raster S p 512 512 Word8 -> TestTree\nsuite r = testGroup \"Unit Tests\"\n  [ testGroup \"Raster Creation\"\n    [ testCase \"constant (256x256)\"     $ length (lazy small) @?= 65536\n    , testCase \"constant (2^16 x 2^16)\" $ length lazybig @?= 4294967296\n    , testCase \"Image Reading (RGBA)\"   $ do\n        i <- fileRGBA\n        fmap (getComp . _array . _red) i @?= Right Par\n    ]\n  , testGroup \"Typeclass Ops\"\n    [ testCase \"(==)\" $ assertBool \"(==) doesn't work\" (small == small)\n    , testCase \"(+)\"  $ strict P (lazy one + lazy one) @?= two\n    ]\n  , testGroup \"Folds\"\n    [ testCase \"sum (small)\" $ P.sum (lazy small) @?= 327680\n    -- , testCase \"sum (large)\" $ P.sum lazybig @?= 21474836480\n    ]\n  , testGroup \"Local Ops\"\n    [ testCase \"(+)\"       $ P.sum (lazy small + lazy small) @?= (327680 * 2)\n    , testCase \"lmin\"      $ strict P (lmin one two) @?= one\n    , testCase \"lvariety\"  $ (strict P . lvariety . fmap lazy $ one :| [two]) @?= two\n    , testCase \"lmajority\" $ (strict P . lmajority . fmap lazy $ one :| [one, two]) @?= one\n    , testCase \"lminority\" $ (strict P . lminority . fmap lazy $ one :| [one, two]) @?= two\n    -- , testCase \"(+) big\"   $ strict P (lazy big + lazy big) @?= bog\n    ]\n  , testGroup \"Focal Ops\"\n    [ testCase \"fvariety\" $ strict P (fvariety one) @?= one\n    , testCase \"fmax\"     $ strict P (fmax one) @?= one\n    , testCase \"fmin\"     $ strict P (fmin one) @?= one\n    , testGroup \"flinkage\"\n      [ testCase \"single point\" singlePoint\n      , testCase \"2x2 same\" twoByTwoSame\n      , testCase \"2x2 diff\" twoByTwoDiff\n      , testCase \"3x3\" threeByThree\n      ]\n    , testCase \"flength\" flengthTest\n    , testCase \"fpartition\" fpartitionTest\n    , testCase \"fshape\" fshapeTest\n    , testCase \"ffrontage\" ffrontageTest\n    , testGroup \"farea\"\n      [ testCase \"3x3 Open\" fareaOpen\n      , testCase \"3x3 Centre\" fareaCentre\n      , testCase \"4x4 Complex\" fareaComplex\n      ]\n    , testGroup \"fvolume\"\n      [ testCase \"3x3 Flat\" fvolumeFlat\n      , testCase \"3x3 Hill\" fvolumeHill\n      ]\n    , testProperty \"Least Squares\" leastSquares\n    , testGroup \"fgradient\"\n      [ testCase \"3x3 Flat\" fgradientFlat\n      , testCase \"3x3 (tau/8)\" fgradient45\n      ]\n    , testGroup \"faspect\"\n      [ testCase \"3x3 Flat\" faspectFlat\n      , testCase \"3x3 East\" faspectEast\n      , testCase \"3x3 South\" faspect45\n      ]\n    , testGroup \"fdownstream\"\n      [ testCase \"3x3 Spikey\" fdownstream4\n      , testCase \"3x3 Flat\" fdownstreamFlat\n      , testCase \"3x3 Peak\" fdownstreamPeak\n      , testCase \"3x3 Pit\"  fdownstreamPit\n      ]\n    , testGroup \"fupstream\"\n      [ testCase \"3x3 Peak\" fupstreamPeak\n      , testCase \"3x3 Flat\" fupstreamFlat\n      ]\n    ]\n  , testGroup \"Histograms\"\n    [ testCase \"Total Sum\"     $ VS.sum (_histogram $ histogram r) @?= 262144\n    , testCase \"10 Breaks\"     $ length (breaks $ histogram r) @?= 10\n    , testCase \"Sorted Breaks\" $ do\n        let bs = breaks $ histogram r\n        sort bs @?= bs\n    ]\n  ]\n\nfromRight :: Either a b -> b\nfromRight (Right b) = b\nfromRight _         = error \"Was Left\"\n\none :: Raster P p 7 7 Word\none = constant P Seq 1\n\ntwo :: Raster P p 7 7 Word\ntwo = constant P Seq 2\n\nsmall :: Raster P p 256 256 Int\nsmall = constant P Seq 5\n\nlazybig :: Raster D p 65536 65536 Int\nlazybig = constant D Par 5\n\n-- big :: Raster P p 65536 65536 Word8\n-- big = constant P Par 5\n\n-- bog :: Raster P p 65536 65536 Word8\n-- bog = constant P Par 10\n\n-- indices :: Raster S p 512 512 Word8\n-- indices = fromFunction S Par (\\(r :. c) -> fromIntegral $ r + c)\n\nfileRGBA :: IO (Either String (RGBARaster p 512 512 Word8))\nfileRGBA = fromRGBA \"data/512x512.tif\"\n\nsinglePoint :: Assertion\nsinglePoint = actual @?= expected\n  where expected :: Raster B p 1 1 Line\n        expected = constant B Seq (Line 0)\n        actual :: Raster B p 1 1 Line\n        actual = strict B . flinkage $ constant P Seq (1 :: Int)\n\ntwoByTwoSame :: Assertion\ntwoByTwoSame = actual @?= expected\n  where expected :: Raster S p 2 2 Line\n        expected = fromRight . fromVector Seq . VS.fromList\n          $ P.map (Line . _drain . drainage . S.fromList) [ [ East, South ]\n                                                          , [ West, South ]\n                                                          , [ North,East ]\n                                                          , [ West, North ] ]\n        actual :: Raster S p 2 2 Line\n        actual = fromRight . fmap (strict S . flinkage) . fromVector Seq $ U.fromList ([1,1,1,1] :: [Int])\n\ntwoByTwoDiff :: Assertion\ntwoByTwoDiff = actual @?= expected\n  where expected :: Raster S p 2 2 Line\n        expected = fromRight . fromVector Seq . VS.fromList\n          $ P.map (Line . _drain . drainage . S.fromList) [ [ SouthEast ]\n                                                          , [ SouthWest ]\n                                                          , [ NorthEast ]\n                                                          , [ NorthWest ] ]\n        actual :: Raster S p 2 2 Line\n        actual = fromRight . fmap (strict S . flinkage) . fromVector Seq $ U.fromList ([1,2,2,1] :: [Int])\n\nthreeByThree :: Assertion\nthreeByThree = actual @?= expected\n  where expected :: Raster S p 3 3 Line\n        expected = fromRight . fromVector Seq . VS.fromList\n          $ P.map (Line . _drain . drainage . S.fromList) [ [ ]\n                                                          , [ South ]\n                                                          , [ ]\n                                                          , [ East ]\n                                                          , [ North, West, South, East ]\n                                                          , [ West ]\n                                                          , [ ]\n                                                          , [ North ]\n                                                          , [ ] ]\n        actual :: Raster S p 3 3 Line\n        actual = fromRight . fmap (strict S . flinkage) . fromVector Seq $ U.fromList ([1,2,1,2,2,2,1,2,1] :: [Int])\n\nflengthTest :: Assertion\nflengthTest = actual @?= expected\n  where actual :: Raster U p 3 3 Double\n        actual = strict U . flength . flinkage . fromRight . fromVector Seq $ VS.fromList ([1,2,1,2,2,2,1,2,1] :: [Int])\n        expected :: Raster U p 3 3 Double\n        expected = fromRight . fromVector Seq $ U.fromList [ 0, 0.5, 0, 0.5, 2, 0.5, 0, 0.5, 0 ]\n\nfpartitionTest :: Assertion\nfpartitionTest = actual @?= expected\n  where expected :: Raster B p 2 2 Corners\n        expected = fromRight . fromVector Seq $ V.fromList [ Corners Open Open Open Open\n                                                           , Corners Open Open Open Open\n                                                           , Corners OneSide Open OneSide Complete\n                                                           , Corners Open Open Open Open ]\n        actual :: Raster B p 2 2 Corners\n        actual = strict B . fpartition . fromRight . fromVector Seq $ U.fromList ([1,1,2,1] :: [Int])\n\nfshapeTest :: Assertion\nfshapeTest = actual @?= expected\n where expected :: Raster B p 3 3 Corners\n       expected = fromRight . fromVector Seq $ V.fromList [ Corners Open Open OutFlow Open\n                                                          , Corners Open Open Open Open\n                                                          , Corners Open OutFlow Open Open\n                                                          , Corners Open Open Open Open\n                                                          , Corners Complete Complete Complete Complete\n                                                          , Corners Open Open Open Open\n                                                          , Corners Open Open Open OutFlow\n                                                          , Corners Open Open Open Open\n                                                          , Corners OutFlow Open Open Open ]\n       actual :: Raster B p 3 3 Corners\n       actual = strict B . fshape . fromRight . fromVector Seq $ U.fromList ([1,1,1,1,0,1,1,1,1] :: [Int])\n\nffrontageTest :: Assertion\nffrontageTest = let ?epsilon = 0.001 in actual @?~ expected\n  where expected :: Double\n        expected = 1 + (1 / sqrt 2)\n        actual :: Double\n        actual = flip index' (1 :. 1) . _array . strict S $ ffrontage rast\n        rast :: Raster DW p 4 4 Corners\n        rast = fshape . fromRight . fromVector Seq $ U.fromList ( [1,1,1,0\n                                                                  ,1,0,0,0\n                                                                  ,1,0,0,1\n                                                                  ,1,0,1,1] :: [Int] )\n\nfareaOpen :: Assertion\nfareaOpen = actual @?= expected\n  where expected :: Raster U p 3 3 Double\n        expected = fromRight . fromVector Seq $ U.fromList [1,1,1,1,1,1,1,1,1]\n        actual :: Raster U p 3 3 Double\n        actual = strict U . farea . fshape . fromRight . fromVector Seq $ U.fromList ([0,0,0,0,0,0,0,0,0] :: [Int])\n\nfareaCentre :: Assertion\nfareaCentre = actual @?= expected\n  where expected :: Raster U p 3 3 Double\n        expected = fromRight . fromVector Seq $ U.fromList [ 1 + 1/8, 1, 1 + 1/8\n                                                           , 1, 1/2, 1\n                                                           , 1 + 1/8, 1, 1 + 1/8 ]\n        actual :: Raster U p 3 3 Double\n        actual = strict U . farea . fshape . fromRight . fromVector Seq $ U.fromList ([0,0,0,0,1,0,0,0,0] :: [Int])\n\nfareaComplex :: Assertion\nfareaComplex = let ?epsilon = 0.001 in actual @?~ (7 / 8)\n  where actual :: Double\n        actual = flip index' (1 :. 1) . _array . strict P $ farea rast\n        rast :: Raster DW p 4 4 Corners\n        rast = fshape . fromRight . fromVector Seq $ U.fromList ( [1,1,1,0\n                                                                  ,1,0,0,0\n                                                                  ,1,0,0,1\n                                                                  ,1,0,1,1] :: [Int] )\n\nfvolumeFlat :: Assertion\nfvolumeFlat = strict U (fvolume expected) @?= expected\n  where expected :: Raster U p 3 3 Double\n        expected = fromRight . fromVector Seq $ U.fromList [8,8,8,8,8,8,8,8,8]\n\nfvolumeHill :: Assertion\nfvolumeHill = index' (_array actual) (1 :. 1) @?= expected\n  where expected :: Double\n        expected = P.sum [20,20,16,20,16,16,16,16,12,16,12,12] / 12\n        actual :: Raster U p 3 3 Double\n        actual = strict U . fvolume @Double . fromRight . fromVector Seq $ U.fromList [24,24,24\n                                                                                      ,16,16,16\n                                                                                      ,8,8,8]\n\nnewtype Vec = Vec [Double] deriving (Show)\n\ninstance Arbitrary Vec where\n  arbitrary = Vec <$> QC.vector 9\n\n-- | A QuickCheck property to test whether my custom Least Squares is as\n-- accurate as the one provided by HMatrix.\nleastSquares :: Vec -> Bool\nleastSquares (Vec vs) = f 0 && f 1 && f 2\n  where m = head . LA.toColumns $ LA.linearSolveLS zing (LA.col vs)\n        v = leftPseudo LA.#> LA.vector vs\n        f i = (m LA.! i) =~ (v LA.! i)\n\n-- | Approximate Equality.\n(=~) :: Double -> Double -> Bool\na =~ b = abs (a - b) < 0.0001\n\nzing :: LA.Matrix Double\nzing = LA.matrix 3 [ -0.5, -0.5, 1\n                   , -0.5, 0, 1\n                   , -0.5, 0.5, 1\n                   , 0, -0.5, 1\n                   , 0, 0, 1\n                   , 0, 0.5, 1\n                   , 0.5, -0.5, 1\n                   , 0.5, 0, 1\n                   , 0.5, 0.5, 1 ]\n\nfgradientFlat :: Assertion\nfgradientFlat = actual @?= expected\n  where expected :: Raster U p 3 3 Double\n        expected = fromRight . fromVector Seq $ U.fromList [0,0,0,0,0,0,0,0,0]\n        actual :: Raster U p 3 3 Double\n        actual = strict U . fgradient . fromRight . fromVector Seq $ U.fromList ([1,1,1,1,1,1,1,1,1] :: [Double])\n\nfgradient45 :: Assertion\nfgradient45 = let ?epsilon = 0.0001 in index' (_array actual) (1 :. 1) @?~ (tau / 8)\n  where actual :: Raster U p 3 3 Double\n        actual = strict U . fgradient . fromRight . fromVector Seq $ U.fromList ([3,3,3,2,2,2,1,1,1] :: [Double])\n\nfaspectFlat :: Assertion\nfaspectFlat = index' (_array actual) (1 :. 1) @?= Nothing\n  where actual :: Raster B p 3 3 (Maybe Double)\n        actual = strict B . faspect . fromRight . fromVector Seq $ U.fromList ([1,1,1,1,1,1,1,1,1] :: [Double])\n\nfaspect45 :: Assertion\nfaspect45 = index' (_array actual) (1 :. 1) @?= Just (tau / 2)\n  where actual :: Raster B p 3 3 (Maybe Double)\n        actual = strict B . faspect . fromRight . fromVector Seq $ U.fromList ([3,3,3,2,2,2,1,1,1] :: [Double])\n\nfaspectEast :: Assertion\nfaspectEast = let ?epsilon = 0.0001 in index' (_array actual) (1 :. 1) @?~ (tau / 4)\n  where actual :: Raster B p 3 3 Double\n        actual = strict B . faspect' . fromRight . fromVector Seq $ U.fromList ([3,2,1,3,2,1,3,2,1] :: [Double])\n\nfdownstream4 :: Assertion\nfdownstream4 = index' (_array actual) (1 :. 1) @?= drainage (S.fromList [North,South,East,West])\n  where actual :: Raster S p 3 3 Drain\n        actual = strict S . fdownstream . fromRight . fromVector Seq $ U.fromList ([3,1,3,1,2,1,3,1,3] :: [Double])\n\nfdownstreamFlat :: Assertion\nfdownstreamFlat = index' (_array actual) (1 :. 1) @?= drainage (S.fromList [East ..])\n  where actual :: Raster S p 3 3 Drain\n        actual = strict S . fdownstream . fromRight . fromVector Seq $ U.fromList ([1,1,1,1,1,1,1,1,1] :: [Double])\n\nfdownstreamPeak :: Assertion\nfdownstreamPeak = index' (_array actual) (1 :. 1) @?= drainage (S.fromList [NorthEast, NorthWest, SouthWest, SouthEast])\n  where actual :: Raster S p 3 3 Drain\n        actual = strict S . fdownstream . fromRight . fromVector Seq $ U.fromList ([1,1,1,1,3,1,1,1,1] :: [Double])\n\nfdownstreamPit :: Assertion\nfdownstreamPit = index' (_array actual) (1 :. 1) @?= Drain 0\n  where actual :: Raster S p 3 3 Drain\n        actual = strict S . fdownstream . fromRight . fromVector Seq $ U.fromList ([2,2,2,2,1,2,2,2,2] :: [Double])\n\nfupstreamFlat :: Assertion\nfupstreamFlat = index' (_array actual) (1 :. 1) @?= drainage (S.fromList [East ..])\n  where actual :: Raster S p 3 3 Drain\n        actual = strict S . fupstream . strict S . fdownstream . fromRight . fromVector Seq $ U.fromList ([1,1,1,1,1,1,1,1,1] :: [Double])\n\nfupstreamPeak :: Assertion\nfupstreamPeak = index' (_array actual) (1 :. 1) @?= Drain 0\n  where actual :: Raster S p 3 3 Drain\n        actual = strict S . fupstream . strict S . fdownstream . fromRight . fromVector Seq $ U.fromList ([1,1,1,1,3,1,1,1,1] :: [Double])\n\n{-\nhists :: Raster S p 512 512 Word8 -> Assertion\nhists r = do\n  u  <- histU r\n  um <- histMut r\n  histU' r @?= u\n  histMut' r @?= um\n  histMut'' r @?= um\n  histMut'' r @?= u\n  um @?= u\n-}\n", "meta": {"hexsha": "1d8dbfdcb95a4dd13160b5cfc7b87e4c5116e230", "size": 15789, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test.hs", "max_stars_repo_name": "fosskers/mapalgebra", "max_stars_repo_head_hexsha": "093ceb3f7d2b22e0eb47f5cad016f50c32cc43a8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2017-06-30T07:09:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-16T18:21:09.000Z", "max_issues_repo_path": "test/Test.hs", "max_issues_repo_name": "fosskers/mapalgebra", "max_issues_repo_head_hexsha": "093ceb3f7d2b22e0eb47f5cad016f50c32cc43a8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2017-11-03T17:47:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-21T17:13:26.000Z", "max_forks_repo_path": "test/Test.hs", "max_forks_repo_name": "fosskers/mapalgebra", "max_forks_repo_head_hexsha": "093ceb3f7d2b22e0eb47f5cad016f50c32cc43a8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-09-11T01:06:54.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-23T10:58:26.000Z", "avg_line_length": 43.2575342466, "max_line_length": 138, "alphanum_fraction": 0.5311292672, "num_tokens": 4564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.61878043374385, "lm_q1q2_score": 0.45425879927512525}}
{"text": "-- |\n-- Module      :  Test.FFTW\n-- Copyright   :  (c) 2016 Drexel University\n-- License     :  BSD-style\n-- Maintainer  :  mainland@drexel.edu\n\nmodule Test.FFTW (\n    fft\n  ) where\n\nimport Data.Complex\nimport qualified Data.Vector.Storable as V\nimport Numeric.FFT.Vector.Unnormalized as FFTW\n\nfft :: Int -> V.Vector (Complex Double) -> V.Vector (Complex Double)\nfft n = FFTW.execute $ FFTW.plan FFTW.dft n\n", "meta": {"hexsha": "5bd0cc42b23f390be4afea7bdfa47b810bf16b32", "size": 407, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/test/Test/FFTW.hs", "max_stars_repo_name": "mainland/hspiral", "max_stars_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-05-21T21:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T04:48:25.000Z", "max_issues_repo_path": "src/test/Test/FFTW.hs", "max_issues_repo_name": "mainland/hspiral", "max_issues_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "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/test/Test/FFTW.hs", "max_forks_repo_name": "mainland/hspiral", "max_forks_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9411764706, "max_line_length": 68, "alphanum_fraction": 0.683046683, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4541643259426368}}
{"text": "module Main (main) where\n\nimport Neural.Matrix\nimport Data.Ord (comparing)\nimport Data.List (scanl, foldl', maximumBy)\nimport Numeric.LinearAlgebra (toList, vector)\nimport Control.Monad (forM_)\nimport Codec.Compression.GZip (decompress)\nimport qualified Data.ByteString.Lazy as BS\n\ngetImage s n = fromIntegral . BS.index s . (n*28^2 + 16 +) <$> [0..28^2 - 1]\ngetX     s n = (vector (getImage s n)) / 256\ngetLabel s n = fromIntegral $ BS.index s (n + 8)\ngetY     s n = vector $ fromIntegral . fromEnum . (getLabel s n ==) <$> [0..9]\n\nprintImage imgs = putStrLn . unlines . take 28 . map (take 28) . iterate (drop 28)\n                           . map pixel2Char . getImage imgs\n  where pixel2Char n = let s = \" \u00b7:o\u25cdO0@\" in s !! (fromIntegral n * length s `div` 256)\n\ndisplay d prob = show d ++ \": \" ++ show prob\n\nbestOf :: [Float] -> Int\nbestOf = fst . maximumBy (comparing snd) . zip [0..]\n\nsmall = [[0..99], [100..299], [300..599], [600..999]]\nmedium = [[0..299], [300..999], [1000..2199], [2200..4599]]\nlarge = [[0..999], [1000..2999], [3000..5999], [6000..9999]]\nrapid = [[0..299], [300..599], [600..899], [900..1199], [1200..1499], [1500..1799], [1800..2099]]\n\nmain :: IO ()\nmain = do\n  [trainI, trainL, testI, testL] <- mapM ((decompress  <$>) . BS.readFile . (\"examples/mnistData/\"++))\n                                    [\"train-images-idx3-ubyte.gz\"\n                                    ,\"train-labels-idx1-ubyte.gz\"\n                                    ,\"t10k-images-idx3-ubyte.gz\"\n                                    ,\"t10k-labels-idx1-ubyte.gz\"]\n  net <- initNet 1 [784, 30, 10] [relu, relu]\n  let n = 42\n  printImage testI n\n\n  let\n    example = getX testI n\n    randomUpdate net x = updateNet categoricalCrossEntropy 0.002 (getX trainI x) (getY trainL x) net\n    trainingNet = scanl (foldl' randomUpdate) net large\n    trainedNet = last trainingNet\n  forM_ trainingNet $ putStrLn . unlines . zipWith display [0..9] . softmax\n                               . toList . snd . last . forwardPass example\n", "meta": {"hexsha": "832c49403b8784fc34b6907c8cebfcefc8ed87a6", "size": 2010, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/Mnist.hs", "max_stars_repo_name": "Ultramann/hnet", "max_stars_repo_head_hexsha": "1105c44b7a138707e284e2e1694a8dd24141d4ef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-03-27T05:57:49.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-27T05:57:49.000Z", "max_issues_repo_path": "examples/Mnist.hs", "max_issues_repo_name": "Ultramann/hnet", "max_issues_repo_head_hexsha": "1105c44b7a138707e284e2e1694a8dd24141d4ef", "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/Mnist.hs", "max_forks_repo_name": "Ultramann/hnet", "max_forks_repo_head_hexsha": "1105c44b7a138707e284e2e1694a8dd24141d4ef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.875, "max_line_length": 102, "alphanum_fraction": 0.5845771144, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4541566480141732}}
{"text": "module MNIST.DataSet where\n\nimport MNIST.Prelude\n\nimport qualified Codec.Compression.GZip  as GZip\nimport qualified Data.ByteString.Lazy    as L\nimport qualified Data.Vector.Generic     as G\nimport qualified Numeric.LinearAlgebra   as HM\nimport qualified Numeric.LinearAlgebra.Static  as SM\n\nrows :: Int\nrows = 28\n\ncols :: Int\ncols = 28\n\nnPixels :: Int\nnPixels = cols * rows\n\nnLabels :: Int\nnLabels = 10\n\n\n_loadMNIST\n    :: FilePath\n    -> FilePath\n    -> IO [(Int, UVector Int)]\n_loadMNIST dataPath labelPath =\n  runMaybeT (do\n    i <- MaybeT . fmap (decodeIDX       . GZip.decompress) . L.readFile $ dataPath\n    l <- MaybeT . fmap (decodeIDXLabels . GZip.decompress) . L.readFile $ labelPath\n    d <- MaybeT . pure $ labeledIntData l i\n    return d)\n  >>= \\case\n    Just mnist -> return mnist\n    Nothing    -> throwString $\n      \"couldn't read gzipped MNIST at data file \" <> dataPath\n      <> \" and label file \" <> labelPath\n\nloadMNISTTf :: FilePath -> FilePath -> IO [(Int, Vector Int)]\nloadMNISTTf dp lp = _loadMNIST dp lp\n  >>= pure . fmap (identity *** G.convert)\n\ntrainingDataTf :: IO [(Int, Vector Int)]\ntrainingDataTf =\n  loadMNISTTf\n    \"data/train-images-idx3-ubyte.gz\"\n    \"data/train-labels-idx1-ubyte.gz\"\n\ntestDataTf :: IO [(Int, Vector Int)]\ntestDataTf =\n  loadMNISTTf\n    \"data/t10k-images-idx3-ubyte.gz\"\n    \"data/t10k-labels-idx1-ubyte.gz\"\n\n-- ========================================================================= --\n\nloadMNISTBp\n    :: FilePath\n    -> FilePath\n    -> IO [(R 784, R 9)]\nloadMNISTBp dp lp = _loadMNIST dp lp\n  >>= pure . fmap ((fromJust . mkImage *** fromJust . mkLabel) . swap)\n\n  where\n    mkImage :: UVector Int -> Maybe (R 784)\n    mkImage u = SM.create . G.convert . G.map (\\i -> fromIntegral i / 255) $ u\n\n    mkLabel :: Int -> Maybe (R 9)\n    mkLabel n = SM.create $ HM.build 9 (fromIntegral . fromEnum . (== n) . round)\n\n\ntrainingDataBp :: IO [(R 784, R 9)]\ntrainingDataBp =\n  loadMNISTBp\n    \"data/train-images-idx3-ubyte.gz\"\n    \"data/train-labels-idx1-ubyte.gz\"\n\ntestDataBp :: IO [(R 784, R 9)]\ntestDataBp =\n  loadMNISTBp\n    \"data/t10k-images-idx3-ubyte.gz\"\n    \"data/t10k-labels-idx1-ubyte.gz\"\n\n\n\n", "meta": {"hexsha": "fa2a77bc7c318422d6674d82c65e5367b6cc4d9a", "size": 2152, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MNIST/DataSet.hs", "max_stars_repo_name": "stites/haskell-mnist-benchmarks", "max_stars_repo_head_hexsha": "00dda97e764d078f9ed6989faf0b8a7f2553260f", "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/MNIST/DataSet.hs", "max_issues_repo_name": "stites/haskell-mnist-benchmarks", "max_issues_repo_head_hexsha": "00dda97e764d078f9ed6989faf0b8a7f2553260f", "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/MNIST/DataSet.hs", "max_forks_repo_name": "stites/haskell-mnist-benchmarks", "max_forks_repo_head_hexsha": "00dda97e764d078f9ed6989faf0b8a7f2553260f", "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": 24.7356321839, "max_line_length": 83, "alphanum_fraction": 0.6342936803, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.45385086368185595}}
{"text": "-- This file is part of Quipper. Copyright (C) 2011-2014. Please see the\n-- file COPYRIGHT for a list of authors, copyright holders, licensing,\n-- and other details. All rights reserved.\n-- \n-- ======================================================================\n\n-- | This module provides the Jordan-Wigner transformation and\n-- symbolic derivation of circuit templates for second quantized\n-- interaction terms. It is essentially a fully automated version of\n-- the calculations from\n-- \n-- * James D. Whitfield, Jacob Biamonte, and Al\u00e1n\n-- Aspuru-Guzik. \\\"Simulation of electronic structure Hamiltonians\n-- using quantum computers.\\\" \n-- /Molecular Physics/ 109(5):735\u2013750, 2011.\n-- See also <http://arxiv.org/abs/1001.3855v3>.\n\n\nmodule Algorithms.GSE.JordanWigner where\n\nimport Quipper\n\nimport QuipperLib.Decompose\n\nimport Data.Complex\nimport qualified Data.Map as Map\nimport Data.Map (Map)\n\nimport Libraries.Auxiliary (sequence_right_)\n\nimport Text.Printf\n\n-- ----------------------------------------------------------------------\n-- * Overview\n\n-- $ For a given tuple of orbital indices, (/p/,/q/) in case of\n-- one-electron interactions, or (/p/,/q/,/r/,/s/) in case of two-electron\n-- interactions, we first calculate the Jordan-Wigner transformation\n-- of the second quantized hermitian interaction terms\n-- \n-- /a/[sub /p/][sup \u2020]/a/[sub /p/], \n-- \n-- /a/[sub /p/][sup \u2020]/a/[sub /q/] + /a/[sub /q/][sup \u2020]/a/[sub /p/],\n-- \n-- /a/[sub /p/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /q/]/a/[sub /p/],\n-- \n-- /a/[sub /p/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /r/]/a/[sub /s/] + \n-- /a/[sub /s/][sup \u2020]/a/[sub /r/][sup \u2020]/a/[sub /q/]/a/[sub /p/].\n-- \n-- Next, we decompose each operator into a linear combination /H/ =\n-- \u03bb[sub 1]/M/[sub 1] + ... + \u03bb[sub /n/]/M/[sub /n/] of mutually\n-- commuting hermitian tensors. At this point, each summand /M/[sub /j/]\n-- in the linear combination will be a tensor product of the following\n-- operators (not necessarily in this order):\n-- \n-- * an even number (possibly zero) of Pauli /X/ operators;\n-- \n-- * an even number (possibly zero) of Pauli /Y/ operators;\n-- \n-- * zero or more Pauli /Z/ operators, and\n-- \n-- * zero or more /D/ operators, where /D/ = \u03c3[sup \u2212]\u03c3[sup +] = (/I/\u2212/Z/)\\/2.\n-- \n-- Note that there may be zero terms in the summation; this happens,\n-- for example, for \n-- /a/[sub /p/][sup \u2020]/a/[sub /p/][sup \u2020]/a/[sub /r/]/a/[sub /s/],\n-- because two electrons cannot occupy the same spin orbital due to\n-- their fermionic nature. In this case, /H/ = 0 and [exp -/i/\u03b8/H/] = /I/.\n-- \n-- Next, we calculate [exp -/i/\u03b8/H/]. Because the summands /M/[sub /j/]\n-- commute, we can exponentiate each summand separately, using the formula\n-- [exp -/i/\u03b8/H/] = [exp -/i/\u03b8\u03bb[sub 1]/M/[sub 1]]\u22ef[exp -/i/\u03b8\u03bb[sub /n/]/M/[sub /n/]].\n-- \n-- We then generate the circuit for [exp -/i/\u03b8\u03bb[sub /j/]/M/[sub /j/]]\n-- by applying a sequence of basis changes until the problem is\n-- reduced to a controlled rotation. The basis changes are, in this\n-- order:\n-- \n-- 1. Change each Pauli /X/ operator in /M/[sub /j/] to a Pauli /Z/\n-- operator, and apply a Hadamard basis change to the corresponding\n-- qubit. This uses the relation /HXH/ = /Z/.\n-- \n-- 2. Change each Pauli /Y/ operator in /M/[sub /j/] to a Pauli /Z/\n-- operator, and apply a [bold Y] basis change to the corresponding\n-- qubit. Note: the [bold Y] basis change operator is defined in\n-- [Whitfield et al.] as /R/[sub /x/](-\u03c0\\/2) = (/I/+/iX/)\\/\u221a2, or\n-- equivalently [bold Y] = /SHS/, and satisfies [bold Y][super \u2020]/Y/[bold Y] =\n-- /Z/. It should not be confused with the Pauli /Y/ operator.\n-- \n-- 3. If the operator /M/[sub /j/] contains one or more Pauli /Z/ operators\n-- (including those obtained in steps 1 and 2), then do a basis change\n-- by a cascade of controlled-not gates to reduce this to a single /Z/\n-- operator. This uses the relation /CNot/ (/Z/\u2297/Z/) /CNot/ = /I/\u2297/Z/.\n-- \n-- After these basis changes, the operator /M/[sub /j/] consists of\n-- exactly zero or one Pauli /Z/ operator, together with zero or more\n-- /D/ operators.  To see how to translate this into a controlled\n-- rotation, note that for any operator /A/, we have\n-- \n-- \\[image expDA.png]\n-- \n-- Therefore, each /D/ operator in /M/[sub /j/] turns into a control\n-- after exponentiation. The final rotation is then computed by\n-- distinguishing two cases:\n-- \n-- * If /M/[sub /j/] contains a Pauli /Z/ operator, then use the\n-- relation [exp -/i/\u03b8/Z/] = /R/[sub /z/](2\u03b8). In this case, the circuit\n-- for [exp -/i/\u03b8/M/[sub /j/]] is a controlled /R/[sub /z/](2\u03b8) gate in\n-- the position of the /Z/ operator, with zero or more controls in the\n-- positions of any /D/ operators.\n-- \n-- * If /M/[sub /j/] does not contain a Pauli /Z/ operator, then the\n-- operation to be performed is a phase change [exp -/i/\u03b8], controlled\n-- by the qubits in the positions of the /D/ operators. Note that\n-- there must be at least one /D/ operator in this case. Also note\n-- that a controlled [exp -/i/\u03b8] gate is identical to a /T/(\u03b8) gate.\n\n-- ----------------------------------------------------------------------\n-- * Correctness of the templates\n\n-- $ As outlined above, the functions in this module generate each\n-- circuit from first principles, based on the Jordan-Wigner\n-- representation of operators and on algebraic transformations. They\n-- do not rely on pre-fabricated circuit templates.\n-- \n-- Based on the automated calculations provided by this module, we\n-- have found small typos in the 5 templates provided by [Whitfield\n-- et al.] (Table 3, or Table A1 in the arXiv version). \n-- \n-- * The template for the number-excitation operator is missing a\n-- control on its rotation gate. \n-- \n-- * In the template for the Coulomb operator, the angles are wrong. \n-- Moreover, this program finds a simpler template.\n-- \n-- * In the template for the double excitation operator, the angles\n-- are wrong; they should be \u00b1\u03b8\\/4 instead of \u03b8.\n-- \n-- The corrected templates generated by our code are as follows:\n-- \n-- * Number operator /h/[sub /pp/] /a/[sub /p/][sup \u2020]/a/[sub /p/].\n-- \n-- > [image b0-template.png]\n-- \n-- * Excitation operator /h/[sub /pq/] /a/[sub /p/][sup \u2020]/a/[sub /q/].\n-- \n-- > [image b1-template.png]\n-- \n-- * Coulomb and exchange operators /h/[sub /pqqp/]\n-- /a/[sub /p/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /q/]/a/[sub /p/].\n-- \n-- > [image b2-template.png]\n-- \n-- * Number-excitation operator /h/[sub /pqqr/]\n-- (/a/[sub /p/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /q/]/a/[sub /r/] +\n-- /a/[sub /r/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /q/]/a/[sub /p/]).\n-- The sign of \u00b1\u03b8 depends on the relative ordering of the indices /p,q,r/.\n-- \n-- > [image b3-template.png]\n-- \n-- * Double excitation operator \n-- /h/[sub /pqrs/]\n-- (/a/[sub /p/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /r/]/a/[sub /s/] +\n-- /a/[sub /s/][sup \u2020]/a/[sub /r/][sup \u2020]/a/[sub /q/]/a/[sub /p/]).\n-- The sign of \u00b1\u03b8\\/4 in each of the eight terms depends on the relative ordering of the indices /p,q,r,s/.\n-- \n-- > [image b4-template.png] \n\n-- ----------------------------------------------------------------------\n-- * Alternate Coulomb templates\n\n-- $ As noted above, our algorithm found the following template for the\n-- Coulomb operator \n-- /a/[sub /p/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /q/]/a/[sub /p/]:\n-- \n-- > [image b2-template.png]\n-- \n-- This is simpler than the template given in [Whitfield et al.], even\n-- after one accounts for the cost of decomposing the additional\n-- controlled /T/(\u03b8) gate into elementary gates. However, an\n-- equivalent circuit can also be given that is more similar to the\n-- one in [Whitfield et al.] (but with corrected rotation angles):\n-- \n-- > [image b2-orthodox.png]\n-- \n-- We call this the \\\"orthodox\\\" template, because it is closer to the\n-- one specified by Whitfield et al. The program will use the orthodox\n-- template if the command line option @--orthodox@ is given, and it\n-- will use the simplified template otherwise.\n\n-- ----------------------------------------------------------------------\n-- * General-purpose auxiliary functions\n\n-- | Construct a list consisting of /n/ repetitions of some element.\npower :: Int -> a -> [a]\npower n x = take n $ repeat x\n\n-- | Extract a list of /n/-1 consecutive pairs from an /n/-element list:\n-- \n-- > consecutive_pairs [] = []\n-- > consecutive_pairs [1] = []\n-- > consecutive_pairs [1,2] = [(1,2)]\n-- > consecutive_pairs [1,2,3] = [(1,2),(2,3)]\n-- > consecutive_pairs [1,2,3,4] = [(1,2),(2,3),(3,4)]\nconsecutive_pairs :: [a] -> [(a,a)]\nconsecutive_pairs [] = []\nconsecutive_pairs [h] = []\nconsecutive_pairs (h1:h2:t) = (h1,h2) : consecutive_pairs (h2:t)\n\n-- ----------------------------------------------------------------------\n-- * Scalars          \n          \n-- | The type of complex numbers. Here, we use a floating point\n-- representation, although a symbolic representation would also be\n-- possible. Since for the purpose of this algorithm, all denominators\n-- are powers of 2, the floating point representation is in fact exact.\ntype Scalar = Complex Double\n\n-- | The complex number /i/.\ni :: Scalar\ni = 0 :+ 1\n\n-- ----------------------------------------------------------------------\n-- * Basic Gates\n\n-- | Apply a /R/[sub z](\u03b8)=[exp -/i/\u03b8/Z/\\/2] gate. The parameter \u03b8 is a\n-- Bloch sphere angle.\n-- \n-- \\[image Rz.png]\nrotZ_at :: Double -> Qubit -> Circ ()\nrotZ_at theta q = named_rotation_at \"Rz(%)\" theta q\n\n-- | Apply a /G/(\u03b8) gate. This is a global phase change of [exp -/i/\u03b8],\n-- so this gate only \\\"does\\\" something when it is controlled.\n-- Although it is logically a 0-ary gate, we give it a qubit argument\n-- to specify where the gate can be drawn in circuit diagrams.\n-- \n-- \\[image G.png]\ngse_G_at :: Double -> Qubit -> Circ ()\ngse_G_at theta q = named_rotation_at \"G(%)\" theta q\n\n-- | Apply a /T/(\u03b8) gate. This is a /Z/-rotation, but differs\n-- from /R/[sub z](-\u03b8) by a global phase.\n-- \n-- \\[image T.png]\ngse_T_at :: Double -> Qubit -> Circ ()\ngse_T_at theta q = named_rotation_at \"T(%)\" theta q\n\n-- | Apply a [bold Y] basis change gate. This is defined as [bold Y] = /SHS/, \n-- or equivalently,\n-- \n-- \\[image Y.png]\n-- \n-- This should not be confused with the Pauli /Y/ gate.\ngse_Y_at :: Qubit -> Circ ()\ngse_Y_at q = named_gate_at \"YY\" q\n\n-- ----------------------------------------------------------------------\n-- * Basic operators\n\n-- | This type provides a symbolic representation of certain\n-- operators, generated by the Pauli operators, /P/ = \u03c3[sup +], and\n-- /M/ = \u03c3[sup \u2212]. For lack of a better term, we call these the\n-- \\\"basic\\\" operators. Note that apart from /P/ and /M/, all of these\n-- are hermitian.\ndata Op = \n  I -- ^ Identity operator.\n  | X  -- ^ Pauli /X/ operator.  \n  | Y  -- ^ Pauli /Y/ operator.\n  | Z  -- ^ Pauli /Z/ operator.\n  | P  -- ^ \u03c3[sup +] operator = (0,1;0,0).\n  | M  -- ^ \u03c3[sup \u2212] operator = (0,0;1,0).\n  | A  -- ^ \u03c3[sup +]\u03c3[sup \u2212] operator = (1,0;0,0).\n  | D  -- ^ \u03c3[sup \u2212]\u03c3[sup +] operator = (0,0;0,1).\n  deriving (Show, Eq, Ord)\n\n-- | A type to represent scalar multiples. An element of ('Scaled'\n-- /a/) is a pair (\u03bb, /x/) of a complex scalar \u03bb and an element /x/ \u2208\n-- /a/. \ndata Scaled a = Scaled Scalar a\n\n-- | Multiplication of basic operators. Note that the product of two\n-- basic operators is not usually itself a basic operator, but a\n-- scalar multiple thereof. This multiplication encodes the algebraic\n-- laws of basic operators in symbolic form.\n          \n-- Implementation note: the multiplication laws are currently\n-- implemented as a long case distinction. Perhaps it could be done\n-- more cleverly.\nmult :: Op -> Op -> Scaled Op\n\n-- The Pauli group\nmult I x = Scaled 1 x\nmult x I = Scaled 1 x\n\nmult X X = Scaled 1 I\nmult X Y = Scaled i Z\nmult X Z = Scaled (-i) Y\n\nmult Y X = Scaled (-i) Z\nmult Y Y = Scaled 1 I\nmult Y Z = Scaled i X\n\nmult Z X = Scaled i Y\nmult Z Y = Scaled (-i) X\nmult Z Z = Scaled 1 I\n\n-- P, M, D, and A\nmult X P = Scaled 1 D\nmult X M = Scaled 1 A\nmult X A = Scaled 1 M\nmult X D = Scaled 1 P\n\nmult Y P = Scaled i D\nmult Y M = Scaled (-i) A\nmult Y A = Scaled i M\nmult Y D = Scaled (-i) P\n\nmult Z P = Scaled 1 P\nmult Z M = Scaled (-1) M\nmult Z A = Scaled 1 A\nmult Z D = Scaled (-1) D\n\nmult P X = Scaled 1 A\nmult M X = Scaled 1 D\nmult A X = Scaled 1 P\nmult D X = Scaled 1 A\n\nmult P Y = Scaled i A\nmult M Y = Scaled (-i) D\nmult A Y = Scaled (-i) P\nmult D Y = Scaled i M\n\nmult P Z = Scaled (-1) P\nmult M Z = Scaled 1 M\nmult A Z = Scaled 1 A\nmult D Z = Scaled (-1) D\n\nmult P P = Scaled 0 I\nmult P M = Scaled 1 A\nmult P A = Scaled 0 I\nmult P D = Scaled 1 P\n  \nmult M P = Scaled 1 D\nmult M M = Scaled 0 I\nmult M A = Scaled 1 M\nmult M D = Scaled 0 I\n  \nmult A P = Scaled 1 P\nmult A M = Scaled 0 I\nmult A A = Scaled 1 A\nmult A D = Scaled 0 I\n  \nmult D P = Scaled 0 I\nmult D M = Scaled 1 M\nmult D A = Scaled 0 I\nmult D D = Scaled 1 D\n  \n-- ----------------------------------------------------------------------\n-- * Tensors of basic operators\n\n-- | We use a list of basic operators to represent a tensor\n-- product. The convention is that infinitely many identity operators\n-- are implicitly appended at the end of the list.\ntype Tensor = [Op]\n\n-- | Normalize a tensor, by stripping away trailing identities.\nnormalize_tensor :: Tensor -> Tensor\nnormalize_tensor [] = []\nnormalize_tensor (h:t) =\n  if h == I && null n \n  then [] \n  else (h:n)\n    where n = normalize_tensor t\n\n-- | The identity tensor.\ntensor_id :: Tensor\ntensor_id = []\n\n-- | Multiply two tensors. This returns a scaled tensor.\nmult_tensor :: Tensor -> Tensor -> Scaled Tensor\nmult_tensor [] bs = Scaled 1 bs\nmult_tensor as [] = Scaled 1 as\nmult_tensor (a:as) (b:bs) = Scaled (x*y) (c:cs) where\n  Scaled x c = mult a b\n  Scaled y cs = mult_tensor as bs\n\n-- | Multiply two scaled tensors.\nmult_scaled_tensor :: Scaled Tensor -> Scaled Tensor -> Scaled Tensor\nmult_scaled_tensor (Scaled x a) (Scaled y b) = Scaled (x*y*z) c where\n  Scaled z c = a `mult_tensor` b\n\n-- ----------------------------------------------------------------------\n-- * Linear combinations of tensors\n\n-- | A type to represent complex linear combinations of tensors. \ntype TensorLC = Map Tensor Scalar\n\n-- | The origin.\nlc_zero :: TensorLC\nlc_zero = Map.empty\n\n-- | Add a tensor to a linear combination.\nlc_insert :: TensorLC -> Scaled Tensor -> TensorLC\nlc_insert lc (Scaled lambda t) =\n  if newvalue == 0\n  then\n    Map.delete m lc\n  else\n    Map.insert m newvalue lc\n      where\n        m = normalize_tensor t\n        newvalue = case Map.lookup m lc of\n          Nothing -> lambda\n          Just x -> lambda + x\n    \n-- | Turn a list of scaled tensors into a 'TensorLC'.\nlc_from_list :: [Scaled Tensor] -> TensorLC    \nlc_from_list = foldl lc_insert lc_zero\n\n-- | Turn a 'TensorLC' into a list of scaled tensors.\nlc_to_list :: TensorLC -> [Scaled Tensor]\nlc_to_list lc = [Scaled x y | (y,x) <- Map.toList lc]\n\n-- ----------------------------------------------------------------------\n-- * Jordan-Wigner representation\n\n-- $ The next two functions provide the Jordan-Wigner representation of\n-- (Fock-space) annihilation and creation operators.\n\n-- | Construct the Jordan-Wigner annihilation operator /a/[sub /p/] =\n-- /IIIIPZZZZZ.../ for spin-orbital index /p/. The first parameter is\n-- /p/, and the second one is /M/ (the number of spin-orbitals).\n-- Precondition: 0 \u2264 /p/ < /M/.\njw :: Int -> Int -> Scaled Tensor\njw p m = Scaled 1 (power p I ++ [P] ++ power (m-p-1) Z)\n\n-- | Construct the Jordan-Wigner creation operator /a/[sub /p/][sup \u2020]\n-- = /IIIIMZZZZ.../ for spin-orbital index /p/.  The first parameter\n-- is /p/, and the second one is /M/ (the number of spin-orbitals).\n-- Precondition: 0 \u2264 /p/ < /M/.\njw_dagger :: Int -> Int -> Scaled Tensor\njw_dagger p m = Scaled 1 (power p I ++ [M] ++ power (m-p-1) Z)\n\n-- ----------------------------------------------------------------------\n-- * Second quantized interaction terms\n\n-- ** Simple interaction terms\n\n-- | Construct the one-electron second quantized non-hermitianized\n-- interaction term /a/[sub /p/][sup \u2020]/a/[sub /q/].  The parameters\n-- are /p,q/.\none_electron_operator_simple :: Int -> Int -> Scaled Tensor\none_electron_operator_simple p q = ap * aq\n  where\n    ap = jw_dagger p m    \n    aq = jw q m\n    m = maximum [p,q] + 1\n    (*) = mult_scaled_tensor\n\n-- | Construct the two-electron second quantized non-hermitianized\n-- interaction term\n-- /a/[sub /p/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /r/]/a/[sub /s/].\n-- The parameters are /p,q,r,s/.\ntwo_electron_operator_simple :: Int -> Int -> Int -> Int -> Scaled Tensor\ntwo_electron_operator_simple p q r s = ap * aq * ar * as\n  where\n    ap = jw_dagger p m \n    aq = jw_dagger q m \n    ar = jw r m \n    as = jw s m\n    m = maximum [p,q,r,s] + 1\n    (*) = mult_scaled_tensor\n\n-- ** Hermitian interaction terms\n\n-- | Construct\n-- /a/[sub /p/][sup \u2020]/a/[sub /q/] \n-- if /p/ = /q/, and \n-- /a/[sub /p/][sup \u2020]/a/[sub /q/] + /a/[sub /q/][sup \u2020]/a/[sub /p/] \n-- otherwise.\none_electron_operator :: Int -> Int -> TensorLC    \none_electron_operator p q =\n  if p == q\n  then lc_from_list [a_pq]\n  else lc_from_list [a_pq, a_qp]\n    where  \n      a_pq = one_electron_operator_simple p q \n      a_qp = one_electron_operator_simple q p\n       \n-- | Construct\n-- /a/[sub /p/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /r/]/a/[sub /s/]\n-- if (/p/,/q/) = (/s/,/r/), and \n-- /a/[sub /p/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /r/]/a/[sub /s/] +\n-- /a/[sub /s/][sup \u2020]/a/[sub /r/][sup \u2020]/a/[sub /q/]/a/[sub /p/]\n-- otherwise.\ntwo_electron_operator :: Int -> Int -> Int -> Int -> TensorLC\ntwo_electron_operator p q r s =\n  if (p,q) == (s,r)\n  then lc_from_list [a_pqrs]\n  else lc_from_list [a_pqrs, a_srqp]\n    where\n    a_pqrs = two_electron_operator_simple p q r s \n    a_srqp = two_electron_operator_simple s r q p\n\n-- ----------------------------------------------------------------------\n-- * /XYZD/ decomposition\n\n-- | Decompose a basic operator into linear combinations of hermitian basic operators.\n-- This uses the relations /P/ = 1\\/2 /X/ + /i/\\/2 /Y/ and \n-- /M/ = 1\\/2 /X/ - /i/\\/2 /Y/.\ndecompose_basis :: Op -> [Scaled Op]\ndecompose_basis P = [Scaled (1/2) X, Scaled (i/2) Y]\ndecompose_basis M = [Scaled (1/2) X, Scaled (-i/2) Y]\ndecompose_basis x = [Scaled 1 x]  -- default case: the remaining operators are already hermitian\n\n-- | Decompose a tensor into a linear combination of hermitian\n-- tensors. Due to sign alternation, the individual tensors all come\n-- out to commute with each other.\ndecompose_tensor :: Tensor -> TensorLC\ndecompose_tensor [] = lc_from_list [Scaled 1 tensor_id]\ndecompose_tensor (h:t) =\n  lc_from_list [Scaled (x*y) (g:gs) | \n                Scaled x g <- decompose_basis h, \n                Scaled y gs <- lc_to_list (decompose_tensor t)]\n\n-- | Decompose a linear combination of tensors into a linear\n-- combination of hermitian tensors.\ndecompose_tensor_lc :: TensorLC -> TensorLC\ndecompose_tensor_lc lc =                 \n  lc_from_list [ Scaled (x*y) g | \n                 Scaled x gs <- lc_to_list lc,\n                 Scaled y g <- lc_to_list (decompose_tensor gs)]\n\n-- ----------------------------------------------------------------------\n-- * Exponentiation and circuit generation\n\n-- | Given a simple hermitian tensor /H/ and an angle \u03b8, generate a\n-- circuit for [exp -/i/\u03b8/H/].  The given list of input qubits is in\n-- the same order as the operators in /H/. Precondition: /H/ is made\n-- up of zero or more identity operators and one or more of the\n-- operators /X/, /Y/, /Z/, and /D/. The last parameter is a list of\n-- additional controls.\n\nexponentiate_simple :: Scaled Tensor -> Double -> [Qubit] -> [Qubit] -> Circ ()\nexponentiate_simple (Scaled s ms) theta qs ctl = do\n  -- First analyze the tensor:\n  let\n    -- Find all X positions\n    xs = [ i | (m, i) <- zip ms [0,1..], m == X ]\n    -- Find all Y positions\n    ys = [ i | (m, i) <- zip ms [0,1..], m == Y ]\n    -- Find all X, Y, Z positions\n    zs = [ i | (m, i) <- zip ms [0,1..], m `elem` [X, Y, Z] ]\n    -- Find all D positions\n    ds = [ i | (m, i) <- zip ms [0,1..], m == D ]\n  basischange xs ys zs qs\n  rotation alpha ds zs `controlled` ctl\n  reverse_generic_imp (basischange xs ys zs) qs\n  where\n    alpha = theta * realPart s\n    basischange :: [Int] -> [Int] -> [Int] -> [Qubit] -> Circ ()\n    basischange xs ys zs qs = do\n      -- for every X or Y in the operator, apply the appropriate basis\n      -- change to change it to Z.\n      sequence_ [ hadamard_at (qs !! i) | i <- xs ]\n      sequence_ [ gse_Y_at (qs !! i) | i <- ys ]      \n      -- apply a cascade of c-not operators to all X, Y, or Z in the\n      -- operator\n      sequence_right_ [ qnot_at (qs !! i0) `controlled` (qs !! i1) | (i0,i1) <- consecutive_pairs zs]\n    rotation :: Timestep -> [Int] -> [Int] -> Circ ()\n    rotation alpha ds zs = do\n      case zs of\n        [] -> -- if there are no Z operators, produce a controlled\n              -- e^{-i\u03b1} gate.\n          case ds of\n            [] -> error \"exponentiate_simple: precondition violated\"\n            d:ds' -> gse_T_at alpha (qs !! d) `controlled` [qs !! d' | d' <- ds']\n        z:zs' -> -- if there are Z operators, produce a controlled\n                 -- e^{-i\u03b1Z} gate.\n          rotZ_at (2*alpha) (qs !! z) `controlled` [qs !! d | d <- ds]\n\n-- | Given a tensor /H/ (already decomposed into commuting simple\n-- tensors) and an angle \u03b8, generate a circuit for [exp -/i/\u03b8/H/].\n-- The given list of input qubits is in the same order as the\n-- operators in /H/.\nexponentiate :: TensorLC -> Double -> [Qubit] -> [Qubit] -> Circ ()\nexponentiate lc theta qs ctl =\n  sequence_ [ exponentiate_simple a theta qs ctl | a <- lc_to_list lc ]\n\n-- ----------------------------------------------------------------------\n-- * Generate top-level templates\n\n-- | @'one_electron_circuit' theta p q@: Generate the circuit for the\n-- hermitianized one-electron interaction with spin-orbital indices\n-- /p/, /q/. More precisely, generate [exp -/i/\u03b8/H/], where\n-- /H/ = /a/[sub /p/][sup \u2020]/a/[sub /q/] if /p/ = /q/ and \n-- /H/ = /a/[sub /p/][sup \u2020]/a/[sub /q/] \n-- + /a/[sub /q/][sup \u2020]/a/[sub /p/] otherwise.\n-- \n-- This function recognizes an important special case: if \u03b8=0.0, don't\n-- generate any gates at all. The case \u03b8=0.0 frequently arises because\n-- of the conversion from spatial orbitals to spin orbitals.\none_electron_circuit :: Double -> Int -> Int -> [Qubit] -> [Qubit] -> Circ ()\none_electron_circuit 0.0 p q qs ctl = return ()\none_electron_circuit theta p q qs ctl = do\n  comment_with_label (printf \"ENTER: one_electron_circuit (theta=%.3e, p=%d, q=%d)\" theta p q) (qs,ctl) (\"qs\",\"ctl\")\n  exponentiate op theta qs ctl\n  comment_with_label \"EXIT: one_electron_circuit\" (qs,ctl) (\"qs\",\"ctl\")\n  where\n    op = decompose_tensor_lc (one_electron_operator p q)\n      \n-- | @'two_electron_circuit' theta p q r s@:\n-- Generate the circuit for the hermitianized two-electron interaction\n-- with spin-orbital indices /p/, /q/, /r/, /s/. More precisely, generate \n-- [exp -/i/\u03b8/H/], where \n-- /H/ = /a/[sub /p/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /r/]/a/[sub /s/] if \n-- (/p/,/q/) = (/s/,/r/) and /H/ =\n-- /a/[sub /p/][sup \u2020]/a/[sub /q/][sup \u2020]/a/[sub /r/]/a/[sub /s/] +\n-- /a/[sub /s/][sup \u2020]/a/[sub /r/][sup \u2020]/a/[sub /q/]/a/[sub /p/]\n-- otherwise.\n-- \n-- This function recognizes an important special case: if \u03b8=0.0, don't\n-- generate any gates at all. The case \u03b8=0.0 frequently arises because\n-- of the conversion from spatial orbitals to spin orbitals.\ntwo_electron_circuit :: Double -> Int -> Int -> Int -> Int -> [Qubit] -> [Qubit] -> Circ ()\ntwo_electron_circuit 0.0 p q r s qs ctl = return ()\ntwo_electron_circuit theta p q r s qs ctl = do\n  comment_with_label (printf \"ENTER: two_electron_circuit (theta=%.3e, p=%d, q=%d, r=%d, s=%d)\" theta p q r s) (qs,ctl) (\"qs\",\"ctl\")\n  exponentiate op theta qs ctl\n  comment_with_label \"EXIT: two_electron_circuit\" (qs,ctl) (\"qs\",\"ctl\")\n  where\n    op = decompose_tensor_lc (two_electron_operator p q r s)\n      \n-- | Like 'two_electron_circuit', but use the \\\"orthodox\\\" circuit\n-- template for the Coulomb operator /a/[sub /p/][sup \u2020]/a/[sub\n-- /q/][sup \u2020]/a/[sub /q/]/a/[sub /p/]. This generates a circuit using\n-- three rotations, similar to [Whitfield et al.], but with corrected\n-- angles,\n--     \n-- > [image b2-orthodox.png]\n-- \n-- instead of the simpler circuit that 'two_electron_circuit' would\n-- normally generate:\n-- \n-- > [image b2-template.png]\n\ntwo_electron_circuit_orthodox :: Double -> Int -> Int -> Int -> Int -> [Qubit] -> [Qubit] -> Circ ()\ntwo_electron_circuit_orthodox 0.0 p q r s qs ctl = return ()\ntwo_electron_circuit_orthodox theta p q r s qs ctl | q==r && p==s && p/=q = do\n  comment_with_label (printf \"ENTER: two_electron_circuit_orthodox(theta=%.3e, p=%d, q=%d, r=%d, s=%d)\" theta p q r s) (qs,ctl) (\"qs\",\"ctl\")\n  let pp = qs !! p\n      qq = qs !! q\n  gse_G_at (theta/4) pp `controlled` ctl\n  rotZ_at (-theta/2) pp `controlled` ctl\n  rotZ_at (-theta/2) qq `controlled` ctl\n  qnot_at qq `controlled` pp  -- control ctl is not needed\n  rotZ_at (theta/2) qq `controlled` ctl\n  qnot_at qq `controlled` pp  -- control ctl is not needed\n  comment_with_label \"EXIT: two_electron_circuit_orthodox\" (qs,ctl) (\"qs\",\"ctl\")\n                                                                         \n-- all other cases aren't Coulomb operators, so fall back to\n-- two_electron_circuit.\ntwo_electron_circuit_orthodox theta p q r s qs ctl = do\n  two_electron_circuit theta p q r s qs ctl\n  \n-- ----------------------------------------------------------------------\n-- * Testing\n\n-- $ We provide two functions, accessible via command line options,\n-- that allow the user to display individual templates. \n\n-- | Display the circuit for the hermitianized one-electron interaction,\n-- with \u03b8=1.\nshow_one_electron :: Format -> GateBase -> Int -> Int -> IO ()\nshow_one_electron format gatebase p q = \n  print_generic format (decompose_generic gatebase circuit) (replicate (n-m) qubit) where\n    circuit qs = one_electron_circuit 1.0 (p-m) (q-m) qs []\n    n = maximum [p,q] + 1\n    m = minimum [p,q]\n\n-- | Display the circuit for the hermitianized two-electron interaction, \n-- with \u03b8=1. \nshow_two_electron :: Format -> GateBase -> Int -> Int -> Int -> Int -> IO ()\nshow_two_electron format gatebase p q r s = \n  print_generic format (decompose_generic gatebase circuit) (replicate (n-m) qubit) where\n    circuit qs = two_electron_circuit 1.0 (p-m) (q-m) (r-m) (s-m) qs []\n    n = maximum [p,q,r,s] + 1\n    m = minimum [p,q,r,s]\n\n-- | Like 'show_two_electron', but use the \\\"orthodox\\\" template for\n-- the Coulomb operator.\nshow_two_electron_orthodox :: Format -> GateBase -> Int -> Int -> Int -> Int -> IO ()\nshow_two_electron_orthodox format gatebase p q r s = \n  print_generic format (decompose_generic gatebase circuit) (replicate (n-m) qubit) where\n    circuit qs = two_electron_circuit_orthodox 1.0 (p-m) (q-m) (r-m) (s-m) qs []\n    n = maximum [p,q,r,s] + 1\n    m = minimum [p,q,r,s]\n", "meta": {"hexsha": "e04ab1e7a06013a552b47b580fa104b1d0f37ebd", "size": 26823, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Algorithms/GSE/JordanWigner.hs", "max_stars_repo_name": "fritzo/quipper", "max_stars_repo_head_hexsha": "b1f1e49cede91c4869b4d849a263aa6acacc55c2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 81, "max_stars_repo_stars_event_min_datetime": "2015-03-04T00:30:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T18:00:04.000Z", "max_issues_repo_path": "Algorithms/GSE/JordanWigner.hs", "max_issues_repo_name": "fritzo/quipper", "max_issues_repo_head_hexsha": "b1f1e49cede91c4869b4d849a263aa6acacc55c2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-06-17T17:39:28.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-11T18:44:16.000Z", "max_forks_repo_path": "Algorithms/GSE/JordanWigner.hs", "max_forks_repo_name": "fritzo/quipper", "max_forks_repo_head_hexsha": "b1f1e49cede91c4869b4d849a263aa6acacc55c2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2015-11-29T03:46:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T02:27:40.000Z", "avg_line_length": 38.3733905579, "max_line_length": 140, "alphanum_fraction": 0.6102225702, "num_tokens": 8258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.453677255512245}}
{"text": "{-# LANGUAGE NamedFieldPuns, TemplateHaskell #-}\n\nmodule School.Unit.Test.UnitBackward\n( unitBackwardTest) where\n\nimport Conduit ((.|), sinkList, yield)\nimport Control.Monad.IO.Class (liftIO)\nimport Data.Either (isLeft)\nimport Numeric.LinearAlgebra (ident)\nimport School.TestUtils (assertRight, fromRight, randomAffineParams, randomMatrix, testState)\nimport School.Train.TrainState (TrainState(..), def)\nimport School.Types.FloatEq ((~=))\nimport School.Types.PingPong (pingPongSingleton, reversePingPong, toPingPong)\nimport School.Unit.Affine (affine)\nimport School.Unit.RecLin (recLin)\nimport School.Unit.Unit (Unit(..))\nimport School.Unit.UnitActivation (UnitActivation(..))\nimport School.Unit.UnitBackward\nimport School.Unit.UnitGradient (UnitGradient(..), isGradientFail)\nimport School.Unit.UnitParams (UnitParams(..))\nimport School.Utils.Tuple (snd3)\nimport Test.Tasty (TestTree)\nimport Test.Tasty.QuickCheck\nimport Test.Tasty.TH\nimport Test.QuickCheck.Monadic (assert, monadicIO)\n\nprop_affine_input_fail :: Property\nprop_affine_input_fail = monadicIO $ do\n  let backward = unitBackward affine\n  let acts = [ApplyFail \"init\"]\n  let inGrad = BatchGradient $ ident 1\n  let network =  yield (acts, inGrad, 0)\n              .| backward\n              .| sinkList\n  result <- testState network def\n  assert $ isLeft result\n\nprop_affine_gradient_fail :: Property\nprop_affine_gradient_fail = monadicIO $ do\n  let backward = unitBackward affine\n  let acts = [BatchActivation $ ident 1]\n  let inGrad = GradientFail \"init\"\n  let network =  yield (acts, inGrad, 0)\n              .| backward\n              .| sinkList\n  result <- testState network def\n  assert $ isLeft result\n\nprop_affine_param_fail :: Positive Int -> Positive Int -> Property\nprop_affine_param_fail (Positive fSize) (Positive oSize) = monadicIO $ do\n  let backward = unitBackward affine\n  actMat <- liftIO $ randomMatrix oSize fSize\n  gradMat <- liftIO $ randomMatrix oSize fSize\n  let acts = [BatchActivation actMat]\n  let fStack = (acts, BatchGradient gradMat, 0)\n  let network =  yield fStack\n              .| backward\n              .| sinkList\n  result <- testState network def\n  assertRight (isGradientFail . snd3 . head . fst)\n              result\n\nprop_reclin_gradient :: Positive Int -> Positive Int -> Property\nprop_reclin_gradient (Positive bSize) (Positive fSize) = monadicIO $ do\n  let backward = unitBackward recLin\n  actMat <- liftIO $ randomMatrix bSize fSize\n  let input = BatchActivation actMat\n  gradMat <- liftIO $ randomMatrix bSize fSize\n  let inGrad = BatchGradient gradMat\n  let fStack = ([input], inGrad, 0)\n  let network =  yield fStack\n              .| backward\n              .| sinkList\n  result <- testState network def\n  let (check, _) = deriv recLin EmptyParams inGrad input\n  assertRight (((~=) check) . snd3 . head . fst)\n              result\n\nprop_affine_derivs :: Positive Int -> Positive Int -> Positive Int -> Property\nprop_affine_derivs (Positive bSize) (Positive fSize) (Positive oSize) = monadicIO $ do\n  let backward = unitBackward affine\n  actMat <- liftIO $ randomMatrix bSize fSize\n  let input = BatchActivation actMat\n  gradMat <- liftIO $ randomMatrix bSize oSize\n  let inGrad = BatchGradient gradMat\n  let fStack = ([input], inGrad, 0)\n  let network =  yield fStack\n              .| backward\n              .| sinkList\n  params <- liftIO $ randomAffineParams fSize oSize\n  let paramList = pingPongSingleton params\n  let initState = def { paramList }\n  result <- testState network initState\n  let (_, check) = deriv affine params inGrad input\n  assertRight (((~=) check) . head . paramDerivs . snd)\n              result\n\nprop_deriv_aff_rl_aff_rl :: Positive Int\n                         -> Positive Int\n                         -> Positive Int\n                         -> Positive Int\n                         -> Property\nprop_deriv_aff_rl_aff_rl (Positive b)\n                         (Positive f)\n                         (Positive h)\n                         (Positive o) = monadicIO $ do\n  inMat <- liftIO $ randomMatrix b f\n  act1Mat <- liftIO $ randomMatrix b h\n  act2Mat <- liftIO $ randomMatrix b h\n  act3Mat <- liftIO $ randomMatrix b o\n  let acts = BatchActivation <$> [ act3Mat\n                                 , act2Mat\n                                 , act1Mat\n                                 , inMat\n                                 ]\n  gradMat <- liftIO $ randomMatrix b o\n  let inGrad = BatchGradient gradMat\n  let network =  yield (acts, inGrad, 0)\n              .| unitBackward recLin\n              .| unitBackward affine\n              .| unitBackward recLin\n              .| unitBackward affine\n              .| sinkList\n  params1 <- liftIO $ randomAffineParams f h\n  params2 <- liftIO $ randomAffineParams h o\n  let allParams = toPingPong [ params1\n                             , EmptyParams\n                             , params2\n                             , EmptyParams\n                             ]\n  let paramList = reversePingPong $ fromRight (pingPongSingleton EmptyParams) allParams\n  let initState = def { paramList }\n  result <- testState network initState\n  let (grad1, _) = deriv recLin EmptyParams inGrad (head acts)\n  let (grad2, dParams2) = deriv affine params2 grad1 (acts!!1)\n  let (grad3, _) = deriv recLin EmptyParams grad2 (acts!!2)\n  let (_, dParams1) = deriv affine params1 grad3 (last acts)\n  let check = [ dParams1\n              , EmptyParams\n              , dParams2\n              , EmptyParams\n              ]\n  assertRight (((~=) check) . paramDerivs . snd)\n              result\n\nunitBackwardTest :: TestTree\nunitBackwardTest = $(testGroupGenerator)\n", "meta": {"hexsha": "06ed07e43778ec71f7cf3b5d321eb6c3c165edff", "size": 5605, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/School/Unit/Test/UnitBackward.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/School/Unit/Test/UnitBackward.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/School/Unit/Test/UnitBackward.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8716216216, "max_line_length": 93, "alphanum_fraction": 0.6456735058, "num_tokens": 1412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45341704053094123}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE Arrows, FlexibleContexts #-}\n\nmodule Examples.MultiTargetTracking where\n\nimport Control.Arrow (returnA)\nimport Control.Monad (forM)\nimport Control.Monad.Bayes.Class (MonadSample, MonadInfer)\n\nimport qualified Data.Map as M\nimport Data.Maybe (fromJust)\n\nimport Numeric.LinearAlgebra.Static hiding ((<>))\n\nimport Inference (zdsparticles)\nimport DelayedSampling (DelayedSample, DelayedInfer, Result (..))\nimport qualified SymbolicDistr as DS\nimport DSProg (DeepForce (..), Expr' (..), Expr, marginal, zdeepForce, deepForce', forgetE)\nimport Distributions\nimport Util.ZStream (ZStream)\nimport qualified Util.ZStream as ZS\nimport Metaprob ((~~), Gen, lift, (|->), obs)\nimport qualified Metaprob as MP\nimport Examples.Demo (Sampler, Delayed, Weighted)\n\ndata ObsType = Clutter | NewTrack | Track Int\n  deriving (Eq, Show, Ord)\n\nfilterM :: Monad m => (k -> v -> m Bool) -> M.Map k v -> m (M.Map k v)\nfilterM f = M.traverseMaybeWithKey $ \\k v -> do\n  b <- f k v\n  return (if b then Just v else Nothing)\n\ntype TrackMap = M.Map Int (Expr (R 4))\n\ntdiff, birthRate, deathRate, clutterLambda, newTrackLambda, pd, survivalProb :: Double\ntdiff = 1\nbirthRate = 0.1\ndeathRate = 0.02\nclutterLambda = 3\nnewTrackLambda = birthRate * tdiff\npd = 0.8\nsurvivalProb = exp (- tdiff * deathRate)\n\nclutterDistr :: DS.Distr (Expr (R 2))\nclutterDistr = DS.mvNormal (Const (0 :: R 2)) (10 * sym eye)\n\nnewTrackD :: DelayedSample m => m (Expr (R 4))\nnewTrackD = DS.sample (DS.mvNormal (Const mu) cov)\n  where\n  mu = 0 :: R 4\n  cov = sym (((5 * eye :: Sq 2) ||| (0 :: Sq 2))\n            ===\n            ((0 :: Sq 2) ||| (0.1 * eye :: Sq 2)))\n\ntrackMotion :: DelayedSample m => Double -> Expr (R 4) -> m (Expr (R 4))\ntrackMotion tdiff track = DS.sample (DS.mvNormal (MVMul (Const motionMatrix) track) motionCov)\n  where\n  motionMatrix :: Sq 4\n  motionMatrix = eye + konst tdiff *\n    (((0 :: Sq 2) ||| (eye :: Sq 2))\n    ===\n    ((- 1 / 100 * eye :: Sq 2) ||| (-0.1 * eye :: Sq 2)))\n  motionCov :: Sym 4\n  motionCov = sym $ konst tdiff * (((0.01 * eye :: Sq 2) ||| (0 :: Sq 2))\n                                  ===\n                                  ((0 :: Sq 2) ||| (0.1 * eye :: Sq 2)))\n\ntrackMeasurement :: Expr (R 4) -> DS.Distr (Expr (R 2))\ntrackMeasurement posvel = DS.mvNormal (MVMul (Const posFromPosVel) posvel) (sym eye)\n  where\n  posFromPosVel :: L 2 4\n  posFromPosVel = (eye :: Sq 2) ||| (0 :: Sq 2)\n\nupdateWithAssocs :: DelayedSample m => Int -> TrackMap -> [ObsType] -> m ((TrackMap, Int), [DS.Distr (Expr (R 2))])\nupdateWithAssocs nextTrackID updatedOldTracks assocs = do\n  (obsDists, newTrackPVs) <- fmap mconcat . forM assocs $ \\k -> case k of\n    Clutter -> return ([clutterDistr], [])\n    NewTrack -> do\n      newTrackPV <- newTrackD\n      return ([trackMeasurement newTrackPV], [newTrackPV])\n    Track i -> return ([trackMeasurement (updatedOldTracks M.! i)], [])\n  coasted <- filterM (\\_ _ -> sample (bernoulli ((1 - pd) / (1 - survivalProb * pd)))) notObserved\n  return ((mconcat (observed : coasted : zipWith M.singleton [nextTrackID..] newTrackPVs),\n           nextTrackID + length newTrackPVs), obsDists)\n  where\n  (observed, notObserved) = M.partitionWithKey (\\i _ -> Track i `elem` assocs) updatedOldTracks\n\nsampleStep :: DelayedSample m => (TrackMap, Int) -> Gen m ((TrackMap, Int), [Expr (R 2)])\nsampleStep (allOldTracks, nextTrackID) = do\n  updatedOldTracks <- lift (mapM (trackMotion tdiff) allOldTracks)\n  assocs <- \"assocs\" ~~ MP.prim (shuffleWithRepeats' countDistrs)\n  (newTrackInfo, obsDists) <- lift (updateWithAssocs nextTrackID updatedOldTracks assocs)\n  observations <- \"observations\" ~~ MP.isequence (map MP.dsPrim obsDists)\n  return (newTrackInfo, observations)\n  where\n  countDistrs = M.singleton Clutter (poisson clutterLambda)\n             <> M.singleton NewTrack (poisson newTrackLambda)\n             <> M.mapKeys Track (fmap (\\_ -> bernoulli01 (survivalProb * pd)) allOldTracks)\n\nobserveStep :: DelayedInfer m => (TrackMap, Int) -> [R 2] -> m ((TrackMap, Int), [Expr (R 2)])\nobserveStep (allOldTracks, nextTrackID) observations = do\n  updatedOldTracks <- mapM (trackMotion tdiff) allOldTracks\n  -- assocs <- proposeAssocs observations updatedOldTracks\n  MP.observingWithProposal\n    (\"observations\" |-> MP.trList observations) (sampleStep (allOldTracks, nextTrackID))\n    \"assocs\" (proposeAssocs 0 observations updatedOldTracks)\n\n\n\nproposeAssocs :: DelayedInfer m => Int -> [R 2] -> TrackMap -> Gen m [ObsType]\nproposeAssocs j (obs : observations) remainingTracks = do\n  newTrack <- lift $ newTrackD\n  let distrs = M.singleton Clutter (clutterLambda, clutterDistr)\n        <> M.singleton NewTrack (newTrackLambda, trackMeasurement newTrack)\n        <> M.mapKeys Track (fmap (\\t -> (survivalProb * pd, trackMeasurement t)) remainingTracks)\n  likes <- lift $ mapM (\\(intensity, d) -> (\\ll -> intensity * exp ll) <$> DS.score d obs) distrs\n  let assocDistr = let probs = fmap (/ sum likes) likes in categoricalM probs\n  i <- (\"assoc\" ++ show j) ~~ MP.prim assocDistr\n  let remainingTracks' = case i of\n        Track k -> M.delete k remainingTracks\n        _ -> remainingTracks\n  (i :) <$> proposeAssocs (j + 1) observations remainingTracks'\nproposeAssocs _ [] remainingTracks = return []\n\ngenerateGroundTruth :: DelayedSample m => ZStream m () (TrackMap, [Expr (R 2)])\ngenerateGroundTruth = ZS.fromStep stepf initState where\n  initState = (mempty, 0)\n  stepf state () = do\n    (newState@(tracks', _), observations) <- MP.sim (sampleStep state)\n    return (newState, (tracks', observations))\n\nprocessObservations :: DelayedInfer m => ZStream m [R 2] (M.Map Int (Result (R 4)))\nprocessObservations = ZS.fromStep stepf initState where\n  initState = (mempty, 0)\n  stepf state obs = do\n    (newState@(tracks', _), _) <- observeStep state obs\n    marginalTracks <- mapM (fmap fromJust . marginal) tracks'\n    return (newState, marginalTracks)\n\nrunMTTPF :: Int -> ZStream Sampler () ([(Int, R 4)], [[(Int, Result (R 4))]], [R 2])\nrunMTTPF numParticles = proc () -> do\n  (groundTruth, obs) <- zdeepForce generateGroundTruth -< ()\n  particles <- zdsparticles numParticles processObservations -< obs\n  returnA -< (M.assocs groundTruth, map M.assocs particles, obs)", "meta": {"hexsha": "dba47e1b62538da475d70e0bbf847dc95294a8a9", "size": 6202, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/src/Examples/MultiTargetTracking.hs", "max_stars_repo_name": "psg-mit/probzelus-haskell", "max_stars_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-26T13:13:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T19:11:41.000Z", "max_issues_repo_path": "haskell/src/Examples/MultiTargetTracking.hs", "max_issues_repo_name": "psg-mit/probzelus-haskell", "max_issues_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "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": "haskell/src/Examples/MultiTargetTracking.hs", "max_forks_repo_name": "psg-mit/probzelus-haskell", "max_forks_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "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": 42.7724137931, "max_line_length": 115, "alphanum_fraction": 0.6681715576, "num_tokens": 1884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45332089995486746}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RecordWildCards  #-}\n\nmodule Network.Layer\n( LayerDefinition(..)\n, Layer(..)\n, Connectivity\n, RandomTransform\n\n, showableToLayer\n\n, createLayer\n, scaleLayer\n, connectFully\n\n, randomList\n, boxMuller\n, normals\n, uniforms\n, boundedUniforms\n) where\n\nimport           Data.Binary           (Binary (..), decode, encode)\nimport           Network.Neuron\nimport           Numeric.LinearAlgebra\nimport           System.Random\n\n-- | The LayerDefinition type is an intermediate type initialized by the\n--   library user to define the different layers of the network.\ndata LayerDefinition = LayerDefinition { neuronDef   :: Neuron\n                                       , neuronCount :: Int\n                                       , connect     :: Connectivity\n                                       }\n\n-- | The Layer type, which stores the weight matrix, the bias matrix, and\n--   a neuron type.\ndata Layer = Layer { weightMatrix :: Matrix Double\n                   , biasVector   :: Vector Double\n                   , neuron       :: Neuron\n                   } deriving Show\n\ninstance Binary (Layer) where\n  put Layer{..} = do put weightMatrix; put biasVector\n  get = do weightMatrix <- get; biasVector <- get; return Layer{..}\n\n-- | Connectivity is the type alias for a function that defines the connective\n--   matrix for two layers (fully connected, convolutionally connected, etc.)\ntype Connectivity = Int -> Int -> Matrix Double\n\n-- | A random transformation type alias. It is a transformation defined on an\n--   infinite list of uniformly distributed random numbers, and returns a list\n--   distributed on the transforming distribution.\ntype RandomTransform = [Double] -> [Double]\n\n-- | The createLayer function takes in a random transformation on an infinite\n--   stream of uniformly generated numbers, a source of entropy, and two\n--   layer definitions, one for the previous layer and one for the next layer.\n--   It returns a layer defined by the Layer type -- a weight matrix, a bias\n--   vector, and a neuron type.\ncreateLayer :: (RandomGen g)\n  => RandomTransform -> g -> LayerDefinition -> LayerDefinition -> Layer\ncreateLayer t g layerDef layerDef' =\n  Layer (randomMatrix * (connectivity i j))\n        (randomVector * bias)\n        (neuronDef layerDef)\n  where randomMatrix = (i >< j) (randomList t g')\n        randomVector = i |> (randomList t g'')\n        i = neuronCount layerDef'\n        j = neuronCount layerDef\n        connectivity = connect layerDef'\n        bias = i |> (repeat 1) -- bias connectivity (full)\n        (g', g'') = split g\n\nscaleLayer :: Double -> Layer -> Layer\nscaleLayer factor l =\n  Layer (factor `scale` (weightMatrix l)) (factor `scale` (biasVector l)) (neuron l)\n\n-- | The connectFully function takes the number of input neurons for a layer, i,\n--   and the number of output neurons of a layer, j, and returns an i x j\n--   connectivity matrix for a fully connected network.\nconnectFully :: Int -> Int -> Matrix Double\nconnectFully i j = (i >< j) (repeat 1)\n\n-- | To go from a showable to a layer, we also need a neuron type,\n--   which is an unfortunate restriction owed to Haskell's inability to\n--   serialize functions.\nshowableToLayer :: (Layer, LayerDefinition) -> Layer\nshowableToLayer (s, d) = Layer (weightMatrix s) (biasVector s) (neuronDef d)\n\n-- | Initialize an infinite random list given a random transform and a source\n--   of entroy.\nrandomList :: RandomGen g => RandomTransform -> g -> [Double]\nrandomList transform = transform . randoms\n\n-- | Define a transformation on the uniform distribution to generate\n--   normally distributed numbers in Haskell (the Box-Muller transform)\nboxMuller :: Double -> Double -> (Double, Double)\nboxMuller x1 x2 = (z1, z2)\n  where z1 = sqrt ((-2) * log x1) * cos (2 * pi * x2)\n        z2 = sqrt ((-2) * log x1) * sin (2 * pi * x2)\n\n-- | This is a function of type RandomTransform that transforms a list of\n--   uniformly distributed numbers to a list of normally distributed numbers.\nnormals :: [Double] -> [Double]\nnormals (x1:x2:xs) = z1:z2:(normals xs)\n  where (z1, z2) = boxMuller x1 x2\nnormals _ = []\n\n-- | A non-transformation to return a list of uniformly distributed numbers\n--   from a list of uniformly distributed numbers. It's really a matter of\n--   naming consistency. It generates numbers on the range (0, 1]\nuniforms :: [Double] -> [Double]\nuniforms xs = xs\n\n-- | An affine transformation to return a list of uniforms on the range\n--   (a, b]\nboundedUniforms :: (Double, Double) -> [Double] -> [Double]\nboundedUniforms (lower, upper) xs = map affine xs\n  where affine x = lower + x * (upper - lower)\n", "meta": {"hexsha": "73663741e7fdc379783be11b5a907b590de28c40", "size": 4648, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Network/Layer.hs", "max_stars_repo_name": "mckeankylej/hwRecog", "max_stars_repo_head_hexsha": "b5c9f5f74d47254c4a88347207917bbcdc50a2f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Network/Layer.hs", "max_issues_repo_name": "mckeankylej/hwRecog", "max_issues_repo_head_hexsha": "b5c9f5f74d47254c4a88347207917bbcdc50a2f5", "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": "Network/Layer.hs", "max_forks_repo_name": "mckeankylej/hwRecog", "max_forks_repo_head_hexsha": "b5c9f5f74d47254c4a88347207917bbcdc50a2f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7333333333, "max_line_length": 84, "alphanum_fraction": 0.6688898451, "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.453212462928032}}
{"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module    : Statistics.Types\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License   : BSD3\n--\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : portable\n--\n-- Data types common used in statistics\nmodule Statistics.Types\n    ( -- * Confidence level\n      CL\n      -- ** Accessors\n    , confidenceLevel\n    , significanceLevel\n      -- ** Constructors\n    , mkCL\n    , mkCLE\n    , mkCLFromSignificance\n    , mkCLFromSignificanceE\n      -- ** Constants and conversion to n\u03c3\n    , cl90\n    , cl95\n    , cl99\n      -- *** Normal approximation\n    , nSigma\n    , nSigma1\n    , getNSigma\n    , getNSigma1\n      -- * p-value\n    , PValue\n      -- ** Accessors\n    , pValue\n      -- ** Constructors\n    , mkPValue\n    , mkPValueE\n      -- * Estimates and upper/lower limits\n    , Estimate(..)\n    , NormalErr(..)\n    , ConfInt(..)\n    , UpperLimit(..)\n    , LowerLimit(..)\n      -- ** Constructors\n    , estimateNormErr\n    , (\u00b1)\n    , estimateFromInterval\n    , estimateFromErr\n      -- ** Accessors\n    , confidenceInterval\n    , asymErrors\n    , Scale(..)\n      -- * Other\n    , Sample\n    , WeightedSample\n    , Weights\n    ) where\n\nimport Control.Monad                ((<=<), liftM2, liftM3)\nimport Control.DeepSeq              (NFData(..))\nimport Data.Aeson                   (FromJSON(..), ToJSON)\nimport Data.Binary                  (Binary(..))\nimport Data.Data                    (Data,Typeable)\nimport Data.Maybe                   (fromMaybe)\nimport Data.Vector.Unboxed          (Unbox)\nimport Data.Vector.Unboxed.Deriving (derivingUnbox)\nimport GHC.Generics                 (Generic)\n\n#if __GLASGOW_HASKELL__ == 704\nimport qualified Data.Vector.Generic\nimport qualified Data.Vector.Generic.Mutable\n#endif\n\nimport Statistics.Internal\nimport Statistics.Types.Internal\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal\n\n\n----------------------------------------------------------------\n-- Data type for confidence level\n----------------------------------------------------------------\n\n-- |\n-- Confidence level. In context of confidence intervals it's\n-- probability of said interval covering true value of measured\n-- value. In context of statistical tests it's @1-\u03b1@ where \u03b1 is\n-- significance of test.\n--\n-- Since confidence level are usually close to 1 they are stored as\n-- @1-CL@ internally. There are two smart constructors for @CL@:\n-- 'mkCL' and 'mkCLFromSignificance' (and corresponding variant\n-- returning @Maybe@). First creates @CL@ from confidence level and\n-- second from @1 - CL@ or significance level.\n--\n-- >>> cl95\n-- mkCLFromSignificance 0.05\n--\n-- Prior to 0.14 confidence levels were passed to function as plain\n-- @Doubles@. Use 'mkCL' to convert them to @CL@.\nnewtype CL a = CL a\n               deriving (Eq, Typeable, Data, Generic)\n\ninstance Show a => Show (CL a) where\n  showsPrec n (CL p) = defaultShow1 \"mkCLFromSignificance\" p n\ninstance (Num a, Ord a, Read a) => Read (CL a) where\n  readPrec = defaultReadPrecM1 \"mkCLFromSignificance\" mkCLFromSignificanceE\n\ninstance (Binary a, Num a, Ord a) => Binary (CL a) where\n  put (CL p) = put p\n  get        = maybe (fail errMkCL) return . mkCLFromSignificanceE =<< get\n\ninstance (ToJSON a)                 => ToJSON   (CL a)\ninstance (FromJSON a, Num a, Ord a) => FromJSON (CL a) where\n  parseJSON = maybe (fail errMkCL) return . mkCLFromSignificanceE <=< parseJSON\n\ninstance NFData   a => NFData   (CL a) where\n  rnf (CL a) = rnf a\n\n-- |\n-- >>> cl95 > cl90\n-- True\ninstance Ord a => Ord (CL a) where\n  CL a <  CL b = a >  b\n  CL a <= CL b = a >= b\n  CL a >  CL b = a <  b\n  CL a >= CL b = a <= b\n  max (CL a) (CL b) = CL (min a b)\n  min (CL a) (CL b) = CL (max a b)\n\n\n-- | Create confidence level from probability \u03b2 or probability\n--   confidence interval contain true value of estimate. Will throw\n--   exception if parameter is out of [0,1] range\n--\n-- >>> mkCL 0.95    -- same as cl95\n-- mkCLFromSignificance 0.05\nmkCL :: (Ord a, Num a) => a -> CL a\nmkCL\n  = fromMaybe (error \"Statistics.Types.mkCL: probability is out if [0,1] range\")\n  . mkCLE\n\n-- | Same as 'mkCL' but returns @Nothing@ instead of error if\n--   parameter is out of [0,1] range\n--\n-- >>> mkCLE 0.95    -- same as cl95\n-- Just (mkCLFromSignificance 0.05)\nmkCLE :: (Ord a, Num a) => a -> Maybe (CL a)\nmkCLE p\n  | p >= 0 && p <= 1 = Just $ CL (1 - p)\n  | otherwise        = Nothing\n\n-- | Create confidence level from probability \u03b1 or probability that\n--   confidence interval does not contain true value of estimate. Will\n--   throw exception if parameter is out of [0,1] range\n--\n-- >>> mkCLFromSignificance 0.05    -- same as cl95\n-- mkCLFromSignificance 0.05\nmkCLFromSignificance :: (Ord a, Num a) => a -> CL a\nmkCLFromSignificance = fromMaybe (error errMkCL) . mkCLFromSignificanceE\n\n-- | Same as 'mkCLFromSignificance' but returns @Nothing@ instead of error if\n--   parameter is out of [0,1] range\n--\n-- >>> mkCLFromSignificanceE 0.05    -- same as cl95\n-- Just (mkCLFromSignificance 0.05)\nmkCLFromSignificanceE :: (Ord a, Num a) => a -> Maybe (CL a)\nmkCLFromSignificanceE p\n  | p >= 0 && p <= 1 = Just $ CL p\n  | otherwise        = Nothing\n\nerrMkCL :: String\nerrMkCL = \"Statistics.Types.mkPValCL: probability is out if [0,1] range\"\n\n\n-- | Get confidence level. This function is subject to rounding\n--   errors. If @1 - CL@ is needed use 'significanceLevel' instead\nconfidenceLevel :: (Num a) => CL a -> a\nconfidenceLevel (CL p) = 1 - p\n\n-- | Get significance level.\nsignificanceLevel :: CL a -> a\nsignificanceLevel (CL p) = p\n\n\n\n-- | 90% confidence level\ncl90 :: Fractional a => CL a\ncl90 = CL 0.10\n\n-- | 95% confidence level\ncl95 :: Fractional a => CL a\ncl95 = CL 0.05\n\n-- | 99% confidence level\ncl99 :: Fractional a => CL a\ncl99 = CL 0.01\n\n\n\n----------------------------------------------------------------\n-- Data type for p-value\n----------------------------------------------------------------\n\n-- | Newtype wrapper for p-value.\nnewtype PValue a = PValue a\n               deriving (Eq,Ord, Typeable, Data, Generic)\n\ninstance Show a => Show (PValue a) where\n  showsPrec n (PValue p) = defaultShow1 \"mkPValue\" p n\ninstance (Num a, Ord a, Read a) => Read (PValue a) where\n  readPrec = defaultReadPrecM1 \"mkPValue\" mkPValueE\n\ninstance (Binary a, Num a, Ord a) => Binary (PValue a) where\n  put (PValue p) = put p\n  get            = maybe (fail errMkPValue) return . mkPValueE =<< get\n\ninstance (ToJSON a)                 => ToJSON   (PValue a)\ninstance (FromJSON a, Num a, Ord a) => FromJSON (PValue a) where\n  parseJSON = maybe (fail errMkPValue) return . mkPValueE <=< parseJSON\n\ninstance NFData a => NFData (PValue a) where\n  rnf (PValue a) = rnf a\n\n\n-- | Construct PValue. Throws error if argument is out of [0,1] range.\n--\nmkPValue :: (Ord a, Num a) => a -> PValue a\nmkPValue = fromMaybe (error errMkPValue) . mkPValueE\n\n-- | Construct PValue. Returns @Nothing@ if argument is out of [0,1] range.\nmkPValueE :: (Ord a, Num a) => a -> Maybe (PValue a)\nmkPValueE p\n  | p >= 0 && p <= 1 = Just $ PValue p\n  | otherwise        = Nothing\n\n-- | Get p-value\npValue :: PValue a -> a\npValue (PValue p) = p\n\n\n-- | P-value expressed in sigma. This is convention widely used in\n--   experimental physics. N sigma confidence level corresponds to\n--   probability within N sigma of normal distribution.\n--\n--   Note that this correspondence is for normal distribution. Other\n--   distribution will have different dependency. Also experimental\n--   distribution usually only approximately normal (especially at\n--   extreme tails).\nnSigma :: Double -> PValue Double\nnSigma n\n  | n > 0     = PValue $ 2 * cumulative standard (-n)\n  | otherwise = error \"Statistics.Extra.Error.nSigma: non-positive number of sigma\"\n\n-- | P-value expressed in sigma for one-tail hypothesis. This correspond to\n--   probability of obtaining value less than @N\u00b7\u03c3@.\nnSigma1 :: Double -> PValue Double\nnSigma1 n\n  | n > 0     = PValue $ cumulative standard (-n)\n  | otherwise = error \"Statistics.Extra.Error.nSigma1: non-positive number of sigma\"\n\n-- | Express confidence level in sigmas\ngetNSigma :: PValue Double -> Double\ngetNSigma (PValue p) = negate $ quantile standard (p / 2)\n\n-- | Express confidence level in sigmas for one-tailed hypothesis.\ngetNSigma1 :: PValue Double -> Double\ngetNSigma1 (PValue p) = negate $ quantile standard p\n\n\n\nerrMkPValue :: String\nerrMkPValue = \"Statistics.Types.mkPValue: probability is out if [0,1] range\"\n\n\n\n----------------------------------------------------------------\n-- Point estimates\n----------------------------------------------------------------\n\n-- |\n-- A point estimate and its confidence interval. It's parametrized by\n-- both error type @e@ and value type @a@. This module provides two\n-- types of error: 'NormalErr' for normally distributed errors and\n-- 'ConfInt' for error with normal distribution. See their\n-- documentation for more details.\n--\n-- For example @144 \u00b1 5@ (assuming normality) could be expressed as\n--\n-- > Estimate { estPoint = 144\n-- >          , estError = NormalErr 5\n-- >          }\n--\n-- Or if we want to express @144 + 6 - 4@ at CL95 we could write:\n--\n-- > Estimate { estPoint = 144\n-- >          , estError = ConfInt\n-- >                       { confIntLDX = 4\n-- >                       , confIntUDX = 6\n-- >                       , confIntCL  = cl95\n-- >                       }\n--\n-- Prior to statistics 0.14 @Estimate@ data type used following definition:\n--\n-- > data Estimate = Estimate {\n-- >      estPoint           :: {-# UNPACK #-} !Double\n-- >    , estLowerBound      :: {-# UNPACK #-} !Double\n-- >    , estUpperBound      :: {-# UNPACK #-} !Double\n-- >    , estConfidenceLevel :: {-# UNPACK #-} !Double\n-- >    }\n--\n-- Now type @Estimate ConfInt Double@ should be used instead. Function\n-- 'estimateFromInterval' allow to easily construct estimate from same inputs.\ndata Estimate e a = Estimate\n    { estPoint           :: !a\n      -- ^ Point estimate.\n    , estError           :: !(e a)\n      -- ^ Confidence interval for estimate.\n    } deriving (Eq, Read, Show, Generic\n#if __GLASGOW_HASKELL__ >= 708\n               , Typeable, Data\n#endif\n               )\n\ninstance (Binary   (e a), Binary   a) => Binary   (Estimate e a) where\n  get = liftM2 Estimate get get\n  put (Estimate ep ee) = put ep >> put ee\ninstance (FromJSON (e a), FromJSON a) => FromJSON (Estimate e a)\ninstance (ToJSON   (e a), ToJSON   a) => ToJSON   (Estimate e a)\ninstance (NFData   (e a), NFData   a) => NFData   (Estimate e a) where\n    rnf (Estimate x dx) = rnf x `seq` rnf dx\n\n\n\n-- |\n-- Normal errors. They are stored as 1\u03c3 errors which corresponds to\n-- 68.8% CL. Since we can recalculate them to any confidence level if\n-- needed we don't store it.\nnewtype NormalErr a = NormalErr\n  { normalError :: a\n  }\n  deriving (Eq, Read, Show, Typeable, Data, Generic)\n\ninstance Binary   a => Binary   (NormalErr a) where\n  get = fmap NormalErr get\n  put = put . normalError\ninstance FromJSON a => FromJSON (NormalErr a)\ninstance ToJSON   a => ToJSON   (NormalErr a)\ninstance NFData   a => NFData   (NormalErr a) where\n    rnf (NormalErr x) = rnf x\n\n\n-- | Confidence interval. It assumes that confidence interval forms\n--   single interval and isn't set of disjoint intervals.\ndata ConfInt a = ConfInt\n  { confIntLDX :: !a\n    -- ^ Lower error estimate, or distance between point estimate and\n    --   lower bound of confidence interval.\n  , confIntUDX :: !a\n    -- ^ Upper error estimate, or distance between point estimate and\n    --   upper bound of confidence interval.\n  , confIntCL  :: !(CL Double)\n    -- ^ Confidence level corresponding to given confidence interval.\n  }\n  deriving (Read,Show,Eq,Typeable,Data,Generic)\n\ninstance Binary   a => Binary   (ConfInt a) where\n  get = liftM3 ConfInt get get get\n  put (ConfInt l u cl) = put l >> put u >> put cl \ninstance FromJSON a => FromJSON (ConfInt a)\ninstance ToJSON   a => ToJSON   (ConfInt a)\ninstance NFData   a => NFData   (ConfInt a) where\n    rnf (ConfInt x y _) = rnf x `seq` rnf y\n\n\n\n----------------------------------------\n-- Constructors\n\n-- | Create estimate with normal errors\nestimateNormErr :: a            -- ^ Point estimate\n                -> a            -- ^ 1\u03c3 error\n                -> Estimate NormalErr a\nestimateNormErr x dx = Estimate x (NormalErr dx)\n\n-- | Synonym for 'estimateNormErr'\n(\u00b1) :: a      -- ^ Point estimate\n    -> a      -- ^ 1\u03c3 error\n    -> Estimate NormalErr a\n(\u00b1) = estimateNormErr\n\n-- | Create estimate with asymmetric error.\nestimateFromErr\n  :: a                     -- ^ Central estimate\n  -> (a,a)                 -- ^ Lower and upper errors. Both should be\n                           --   positive but it's not checked.\n  -> CL Double             -- ^ Confidence level for interval\n  -> Estimate ConfInt a\nestimateFromErr x (ldx,udx) cl = Estimate x (ConfInt ldx udx cl)\n\n-- | Create estimate with asymmetric error.\nestimateFromInterval\n  :: Num a\n  => a                     -- ^ Point estimate. Should lie within\n                           --   interval but it's not checked.\n  -> (a,a)                 -- ^ Lower and upper bounds of interval\n  -> CL Double             -- ^ Confidence level for interval\n  -> Estimate ConfInt a\nestimateFromInterval x (lx,ux) cl\n  = Estimate x (ConfInt (x-lx) (ux-x) cl)\n\n\n----------------------------------------\n-- Accessors\n\n-- | Get confidence interval\nconfidenceInterval :: Num a => Estimate ConfInt a -> (a,a)\nconfidenceInterval (Estimate x (ConfInt ldx udx _))\n  = (x - ldx, x + udx)\n\n-- | Get asymmetric errors\nasymErrors :: Estimate ConfInt a -> (a,a)\nasymErrors (Estimate _ (ConfInt ldx udx _)) = (ldx,udx)\n\n\n\n-- | Data types which could be multiplied by constant.\nclass Scale e where\n  scale :: (Ord a, Num a) => a -> e a -> e a\n\ninstance Scale NormalErr where\n  scale a (NormalErr e) = NormalErr (abs a * e)\n\ninstance Scale ConfInt where\n  scale a (ConfInt l u cl) | a >= 0    = ConfInt  (a*l)  (a*u) cl\n                           | otherwise = ConfInt (-a*u) (-a*l) cl\n\ninstance Scale e => Scale (Estimate e) where\n  scale a (Estimate x dx) = Estimate (a*x) (scale a dx)\n\n\n\n----------------------------------------------------------------\n-- Upper/lower limit\n----------------------------------------------------------------\n\n-- | Upper limit. They are usually given for small non-negative values\n--   when it's not possible detect difference from zero.\ndata UpperLimit a = UpperLimit\n    { upperLimit        :: !a\n      -- ^ Upper limit\n    , ulConfidenceLevel :: !(CL Double)\n      -- ^ Confidence level for which limit was calculated\n    } deriving (Eq, Read, Show, Typeable, Data, Generic)\n\n\ninstance Binary   a => Binary   (UpperLimit a) where\n  get = liftM2 UpperLimit get get\n  put (UpperLimit l cl) = put l >> put cl\ninstance FromJSON a => FromJSON (UpperLimit a)\ninstance ToJSON   a => ToJSON   (UpperLimit a)\ninstance NFData   a => NFData   (UpperLimit a) where\n    rnf (UpperLimit x cl) = rnf x `seq` rnf cl\n\n\n\n-- | Lower limit. They are usually given for large quantities when\n--   it's not possible to measure them. For example: proton half-life\ndata LowerLimit a = LowerLimit {\n    lowerLimit        :: !a\n    -- ^ Lower limit\n  , llConfidenceLevel :: !(CL Double)\n    -- ^ Confidence level for which limit was calculated\n  } deriving (Eq, Read, Show, Typeable, Data, Generic)\n\ninstance Binary   a => Binary   (LowerLimit a) where\n  get = liftM2 LowerLimit get get\n  put (LowerLimit l cl) = put l >> put cl\ninstance FromJSON a => FromJSON (LowerLimit a)\ninstance ToJSON   a => ToJSON   (LowerLimit a)\ninstance NFData   a => NFData   (LowerLimit a) where\n    rnf (LowerLimit x cl) = rnf x `seq` rnf cl\n\n\n----------------------------------------------------------------\n-- Deriving unbox instances\n----------------------------------------------------------------\n\nderivingUnbox \"CL\"\n  [t| forall a. Unbox a => CL a -> a |]\n  [| \\(CL a) -> a |]\n  [| CL           |]\n\nderivingUnbox \"PValue\"\n  [t| forall a. Unbox a => PValue a -> a |]\n  [| \\(PValue a) -> a |]\n  [| PValue           |]\n\nderivingUnbox \"Estimate\"\n  [t| forall a e. (Unbox a, Unbox (e a)) => Estimate e a -> (a, e a) |]\n  [| \\(Estimate x dx) -> (x,dx) |]\n  [| \\(x,dx) -> (Estimate x dx) |]\n\nderivingUnbox \"NormalErr\"\n  [t| forall a. Unbox a => NormalErr a -> a |]\n  [| \\(NormalErr a) -> a |]\n  [| NormalErr           |]\n\nderivingUnbox \"ConfInt\"\n  [t| forall a. Unbox a => ConfInt a -> (a, a, CL Double) |]\n  [| \\(ConfInt a b c) -> (a,b,c) |]\n  [| \\(a,b,c) -> ConfInt a b c   |]\n\nderivingUnbox \"UpperLimit\"\n  [t| forall a. Unbox a => UpperLimit a -> (a, CL Double) |]\n  [| \\(UpperLimit a b) -> (a,b) |]\n  [| \\(a,b) -> UpperLimit a b   |]\n\nderivingUnbox \"LowerLimit\"\n  [t| forall a. Unbox a => LowerLimit a -> (a, CL Double) |]\n  [| \\(LowerLimit a b) -> (a,b) |]\n  [| \\(a,b) -> LowerLimit a b   |]\n", "meta": {"hexsha": "9b5d319f3854e0b80761dd2baabe78eb9f834cbc", "size": 17003, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Types.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-11T23:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T22:33:10.000Z", "max_issues_repo_path": "Statistics/Types.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-02-26T06:10:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:27:01.000Z", "max_forks_repo_path": "Statistics/Types.hs", "max_forks_repo_name": "infinity0/statistics", "max_forks_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-12-14T09:59:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T23:04:37.000Z", "avg_line_length": 32.0811320755, "max_line_length": 84, "alphanum_fraction": 0.6033641122, "num_tokens": 4757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4531351110573846}}
{"text": "module GenerateSet where \n\nimport Data.Word\nimport Data.List.Split\nimport Data.Scientific as Scientific\nimport Data.Complex\nimport Control.Monad\nimport Codec.Picture\nimport Data.List\nimport Data.Time.Clock\nimport Data.Time.Calendar\nimport Graphics.X11.Xlib\nimport System.Exit (exitWith, ExitCode(..))\nimport Control.Concurrent \nimport Data.Bits\nimport GHC.Conc (numCapabilities)\n\nimport Mand\n\n\ngenerateSet mv = do\n  step <- promptForImput mv \"enter step\" \n  sr <- promptForImput mv \"enter starting real\"\n  nr <- promptForImput mv \"enter no of real points\" \n  si <- promptForImput mv \"starting im\"\n  ni <- promptForImput mv \"no of im\"\n  name <- promptForImput mv \"Enter name:\"\n\n  let stepf = read step :: Double\n  let srf = read sr :: Double -- starting real\n  let nrf = read nr :: Double --number of real points\n  let sif = read si :: Double -- starting imaginary\n  let nif = read ni :: Double -- number of imaginary points\n  \n  d <- getCurrentTime\n  desc <- promptForImput mv \"description:\" \n  appendFile \"mand/log.txt\" $ \"\\n\"++(take 19 $ show d)++\", \"++name++\", \"++desc\n    \n  --writePng name $ generateImage (\\x y -> PixelRGB8 (fromIntegral 0) (fromIntegral 0) (fromIntegral $ mand $ ((read sr :: S) + (read (show x) :: S) * (read step :: S)) :+ ((read si :: S) + (read (show y) :: S) * (read step :: S)))) (read nr :: Int) (read ni :: Int)\n  writePng (\"mand/\"++name) $ generateImage (\\x y -> generatingFunction stepf srf sif (sif+ nif * stepf) x y ) (read nr :: Int) (read ni :: Int)\n--writePng \"mandv1\" $ generateImage (\\x y -> PixelRGB8 (fromIntegral 100) (fromIntegral 100) (fromIntegral 0)) 300 200\n  print \"completed\"\n  comment <- promptForImput mv \"add comments:\"\n  appendFile \"mand/log.txt\" $ \", \"++comment\n  \n\n\n\ngeneratingFunction stepf srf sif realend x y = normal stepf srf sif realend x y\n  where \n    m = general mand_iteration Nothing ((srf + (fromIntegral x) * stepf) :+ (realend - ((fromIntegral y) * stepf))) 255 \n    normal stepf srf sif realend x y = PixelRGB8 (fromIntegral 0)  (fromIntegral 0) (fromIntegral m)\n    fullcolour stepf srf sif realend x y = PixelRGB8 p1 p2 p3\n    max = 10\n    scale x = round $ 255 * ((fromIntegral x) / (fromIntegral (max * max * max -1)))\n    --p1 = scale $ fromIntegral $ max * max * (div m max* max)\n    --p2 = scale $ fromIntegral $ max * max * (mod (div m max) max * max)\n    --p3 = scale $ max * max * (fromIntegral $ mod m max)\n    p1 = fromIntegral $ div (scaleUp 5000 m) 65536\n    p2 = fromIntegral $ mod (div (scaleUp 5000 m) 255) 256 \n    p3 = fromIntegral $ mod (scaleUp 5000 m) 255 \n\n\nscaleUp :: Integral a => a -> a -> a \nscaleUp max i = round $ 16777215 * fromIntegral i / fromIntegral max\n    --m :: Int\n    --m = mand $ Right $ fromFloatDigits (srf + (fromIntegral x) * stepf) :+ fromFloatDigits (sif + (fromIntegral y) * stepf)\n    --m = mand $ ( (read :: String -> Scientific) (show (srf + (fromIntegral x) * stepf)) :=  (read :: String -> Scientific) (show (sif+ (fromIntegral y) * stepf))\n    --m = if (mand $ (srf + (fromIntegral x) * stepf) :+ (sif + (fromIntegral y) * stepf) )== 255  then 0 else 255\n   \n\n--test = foldl (\\acc x -> 'b':acc) []  [1..100]\n\n\ncolCorect1 :: Int -> Int\ncolCorect1 x = floor $ 256*(1 - exp(fromIntegral x/40))\n\ncolCorect2 :: Int -> Int\ncolCorect2 x = floor . (/255) . fromIntegral  $  x * x\n\npromptForImput :: MVar Bool -> String ->  IO String\npromptForImput mv message = do\n  takeMVar mv\n  print message\n  input <- getLine  \n  putMVar mv True\n  if input == \"*\" then promptForImput mv message else return input\n", "meta": {"hexsha": "66851f972866ecbbd67df8354a517ede2afec909", "size": 3517, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "source/GenerateSet.hs", "max_stars_repo_name": "AlwinHughes/fractal", "max_stars_repo_head_hexsha": "dc99dbf9444e2a5583d5c51f29417592426c5ff4", "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": "source/GenerateSet.hs", "max_issues_repo_name": "AlwinHughes/fractal", "max_issues_repo_head_hexsha": "dc99dbf9444e2a5583d5c51f29417592426c5ff4", "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": "source/GenerateSet.hs", "max_forks_repo_name": "AlwinHughes/fractal", "max_forks_repo_head_hexsha": "dc99dbf9444e2a5583d5c51f29417592426c5ff4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9659090909, "max_line_length": 266, "alphanum_fraction": 0.6539664487, "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45309118073017185}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule AI.Learning.NeuralNetwork\n    (\n      -- * Representation\n      NeuralNetwork\n      -- * Prediction and Training\n    , nnPredict\n    , nnTrain\n    , nnTrainIO\n    ) where\n\nimport Control.Monad.Random hiding (fromList)\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Util\nimport System.IO.Unsafe\n\nimport AI.Learning.Core\nimport AI.Util.Matrix\n\n-----------------------\n-- NN Representation --\n----------------------\n\n-- |Representation for a single-hidden-layer neural network. If the network\n--  has K input nodes, H hidden nodes and L output layers then the dimensions\n--  of the matrices theta0 and theta1 are\n--\n--  * size Layer1 = (K+1) x H\n--  * size Layer2 = (H+1) x L\n--\n--  the (+1)s account for the addition of bias nodes in the input layer and\n--  the hidden layer. Therefore the total number of parameters is\n--  H * (K + L) + H + L\ndata NeuralNetwork = NN (Matrix Double) (Matrix Double)\n\n-- |Three-tuple describing the shape of a network: (input, hidden, output).\ntype NNShape = (Int,Int,Int)\n\ninstance Show NeuralNetwork where\n    show (NN theta0 theta1) = \"Neural Net:\\n\\n\" ++ dispf 3 theta0 ++\n                                           \"\\n\" ++ dispf 3 theta1\n\nfromVector :: NNShape -> Vector Double -> NeuralNetwork\nfromVector (k,h,l) vec = NN theta0 theta1\n    where theta0 = reshape h $ takeVector ((k + 1) * h) vec\n          theta1 = reshape l $ dropVector ((k + 1) * h) vec\n\ntoVector :: Matrix Double -> Matrix Double -> Vector Double\ntoVector theta0 theta1 = join [flatten theta0, flatten theta1]\n\n----------------------\n-- NN Train/Predict --\n----------------------\n\n-- |Make predictions using a neural network.\nnnPredict :: NeuralNetwork -> Matrix Double -> Matrix Double\nnnPredict nn x = h where (_,_,h) = nnForwardProp nn x\n\n-- |Train a neural network from a training set. Note that you must supply\n--  an initial vector of weights. Supplying initial weights all equal to\n--  zero will generally give poor performance.\nnnTrain :: Int              -- number of hidden neurons\n        -> Matrix Double    -- y\n        -> Matrix Double    -- x\n        -> Double           -- lambda\n        -> Vector Double    -- initial weights\n        -> NeuralNetwork\nnnTrain h y x lambda initialVec = fromVector shape vec\n    where shape = (cols x, h, cols y)\n          vec   = minimizeS cost grad initialVec\n          cost  = fst . nnCostGradient shape y x lambda\n          grad  = snd . nnCostGradient shape y x lambda\n\n-- |Train a neural network from a training set.\n--\n--  Note that this is implemented as an IO action, because it randomly sets the\n--  weights in the network before performing numerical optimization (this is to\n--  break the symmetry that exists in the network when all weights are zero).\n--  As a result, it is possible to get different results when training the\n--  network multiple times with the same data.\nnnTrainIO :: Int              -- number of hidden neurons\n          -> Matrix Double    -- y\n          -> Matrix Double    -- x\n          -> Double           -- lambda\n          -> IO NeuralNetwork\nnnTrainIO h y x lambda = nnTrain h y x lambda `fmap` initialVec (cols x, h, cols y)\n\n-- |Choose initial random weights for a neural network.\ninitialVec :: NNShape -> IO (Vector Double)\ninitialVec (k,h,l) = do\n    let len = h * (k + l) + h + l\n    xs <- getRandomRs (0.0, 0.01)\n    return . fromList $ take len xs\n\n------------------------------\n-- Forward/Back Propagation --\n------------------------------\n\n-- |Perform forward propagation through a neural network, returning the matrices\n--  created in the process.\nnnForwardProp :: NeuralNetwork                                 -- neural net\n              -> Matrix Double                                 -- design matrix (x)\n              -> (Matrix Double, Matrix Double, Matrix Double) -- results of fwd prop\nnnForwardProp (NN theta0 theta1) x = (a0,a1,a2)\n    where a0 = addOnes $ x\n          a1 = addOnes $ sigmoid (a0 <> theta0)\n          a2 = sigmoid (a1 <> theta1)\n\n-- |Perform backward propagiation through a neural network. You must supply the\n--  target values and the results of forward propagation for each layer, and\n--  the function returns the gradient matrices for the neural network.\nnnBackProp :: NeuralNetwork                                 -- neural net\n           -> Matrix Double                                 -- target (y)\n           -> (Matrix Double, Matrix Double, Matrix Double) -- results of fwd prop\n           -> (Matrix Double, Matrix Double)                -- gradient (delta0, delta1)\nnnBackProp (NN _ theta1) y (a0,a1,a2) = (dropColumns 1 delta0, delta1)\n    where\n        d2     = a2 - y\n        d1     = (d2 <> trans theta1) * a1 * (1 - a1)\n        delta0 = trans a0 <> d1\n        delta1 = trans a1 <> d2\n\n-- |Perform back and forward propagation through a neural network, returning the\n--  final predictions (variable /a2/) and the gradient matrices (variables\n--  /delta0/ and /delta1/) produced.\nnnFwdBackProp :: NeuralNetwork -> Matrix Double -> Matrix Double -> (Matrix Double, Matrix Double, Matrix Double)\nnnFwdBackProp nn@(NN theta0 theta1) y x = (a2, delta0, delta1)\n    where\n        (a0,a1,a2)      = nnForwardProp nn x\n        (delta0,delta1) = nnBackProp nn y (a0,a1,a2)\n\n-- |Compute the penalty function and gradient vector for a neural network\n--  given a training set.\nnnCostGradient :: NNShape                   -- (K,H,L)\n               -> Matrix Double             -- targets (y)\n               -> Matrix Double             -- design matrix (x)\n               -> Double                    -- regularization parameter (lambda)\n               -> Vector Double             -- neural network\n               -> (Double, Vector Double)   -- (cost, gradient)\nnnCostGradient shape y x lambda vec = (cost, grad)\n    where\n        m = fromIntegral (rows x)\n        nn@(NN theta0 theta1) = fromVector shape vec\n        (h, delta0, delta1)   = nnFwdBackProp nn y x\n\n        cost  = (cost1 + cost2) / m\n        cost1 = negate $ sumMatrix $ y * log h + (1-y) * log (1-h)\n        cost2 = lambda/2 * (normMatrix theta0 + normMatrix theta1)\n\n        grad  = (1/m) `scale` (grad1 + grad2)\n        grad1 = toVector delta0 delta1\n        grad2 = lambda `scale` toVector (insertNils theta0) (insertNils theta1)\n\n        normMatrix m = sumMatrix $ (dropRows 1 m) ^ 2\n        insertNils m = vertcat [0, dropRows 1 m]\n\nnnCost shape y x lambda = fst . nnCostGradient shape y x lambda\nnnGrad shape y x lambda = snd . nnCostGradient shape y x lambda\n\n-- |Use central differencing to compute an approximation to the gradient\n--  vector for a neural network. This is mainly used for checking the\n--  implementation of backprop.\nnnGradApprox :: NNShape -> Matrix Double -> Matrix Double -> Double -> Vector Double -> Vector Double\nnnGradApprox shape y x lambda vec = fromList $ g `map` [0..n-1]\n    where\n        h = 1e-6\n        n = dim vec\n        f v = nnCost shape y x lambda v\n        g i = (f (vec + e i) - f (vec - e i)) / (2*h)\n        e i = fromList $ replicate i 0 ++ [h] ++ replicate (n-i-1) 0\n\n-------------\n-- Testing --\n-------------\n\ntestNN :: NeuralNetwork\ntestNN = NN t0 t1\n    where t0 = fromLists [[11.9934, -5.1396], [-7.7162, 10.1512], [-7.668, 10.1835]]\n          t1 = fromLists [[-16.8806], [10.0445], [8.7476]]\n\ntestFwdProp :: IO ()\ntestFwdProp = do\n    putStrLn \"***\\nCompare forward propagation to the MATLAB implementation.\\n\"\n    let theta0 = fromLists [[0], [-10]]\n        theta1 = fromLists [[5],[-10]]\n        nn = NN theta0 theta1\n        x = fromLists [[-1],[0],[1]]\n    -- sigmoid [10, 0, -10] = [1, 0.5, 0]\n    -- sigmoid [-5, 0, 5]  = [0.0, 0.5, 1]\n    let y = nnPredict nn x\n    putStrLn \"Predictions (should be roughly 0.0, 0.5, 1.0)\"\n    disp 2 y\n    \ntestBackProp :: IO ()\ntestBackProp = do\n    putStrLn \"***\\nCompare back propagation to the MATLAB implementation.\\n\"\n    let nn = testNN\n        x  = fromLists [[0, 0], [0, 1], [1, 0], [1, 1]]\n        y  = fromLists [[0], [1], [1], [0]]\n        (h, delta0, delta1) = nnFwdBackProp nn y x\n    putStrLn \"Predictions (should be 0.0011, 0.8487, 0.8476, 0.0004)\"\n    disp 4 h\n    putStrLn \"Delta 0 (should be -0.0401, -0.0171, -0.0205, -0.0088, -0.0195, -0.0084)\"\n    disp 4 delta0\n    putStrLn \"Delta 1 (should be -0.3022, -0.2985, -0.3013)\"\n    disp 4 delta1\n\ntestCostGradient :: IO ()\ntestCostGradient = do\n    putStrLn \"***\\nTest cost/gradient against the MATLAB implementation.\\n\"\n    let nn@(NN theta0 theta1) = testNN\n        x = fromLists [[0, 0], [0, 1], [1, 0], [1, 1]]\n        y = fromLists [[0], [1], [1], [0]]\n        lambda = 1e-4\n        (cost, grad) = nnCostGradient (2,2,1) y x lambda (toVector theta0 theta1)\n    putStrLn \"Cost (should be around 0.0890)\"\n    print cost\n    putStrLn \"Gradient (should be -0.0100, -0.0043, -0.0053, -0.0019, -0.0051, -0.0019, -0.0755, -0.0744, -0.0751)\"\n    disp 4 (asColumn grad)\n\ntest :: Int -> Double -> IO ()\ntest n lambda = do\n    putStrLn \"***\\nLearning XOR function.\\n\"\n    x <- rand n 2\n    e <- fmap (0.01*) (rand n 1)\n    let y = mapMatrix (\\x -> if x > 0.5 then 1.0 else 0.0) (xor x)\n    nn <- nnTrainIO 4 y x lambda\n    let ypred = nnPredict nn x\n    -- Show predictions\n    putStrLn \"Predictions:\"\n    disp 2 $ takeRows 10 $ horzcat [x, y, ypred]\n    -- Show neural net\n    print nn\n    -- Final test; should approximately compute xor function\n    let xx = fromLists [[0,0],[0,1],[1,0],[1,1]]\n        yy = nnPredict nn xx\n    putStrLn \"Exclusive or:\"\n    disp 2 $ horzcat [xx,yy]\n    \nxor :: Matrix Double -> Matrix Double\nxor x = let [u,v] = toColumns x in asColumn (u + v - 2 * u * v)\n    \n", "meta": {"hexsha": "7596e09b3883d11a525217a524f255fdb79955f9", "size": 9617, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Learning/NeuralNetwork.hs", "max_stars_repo_name": "cagix/aima-haskell", "max_stars_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 245, "max_stars_repo_stars_event_min_datetime": "2015-01-08T18:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T06:58:10.000Z", "max_issues_repo_path": "src/AI/Learning/NeuralNetwork.hs", "max_issues_repo_name": "bemcho/aima-haskell-1", "max_issues_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-09T12:56:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-10T23:14:19.000Z", "max_forks_repo_path": "src/AI/Learning/NeuralNetwork.hs", "max_forks_repo_name": "bemcho/aima-haskell-1", "max_forks_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2015-01-12T00:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T03:09:12.000Z", "avg_line_length": 39.4139344262, "max_line_length": 115, "alphanum_fraction": 0.596755745, "num_tokens": 2730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4529074850024481}}
{"text": "{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule Valuation\n    ( module Valuation\n    , throwError\n    ) where\n\nimport Control.Applicative\nimport Control.Monad.Except\nimport Control.Monad.Identity\nimport Control.Monad.Reader\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal\n\ntype Year = Int\n\nnewtype Scenario a = Scenario\n    { scenario :: a\n    }\n\nnewtype Value s a = Value\n    { runValue :: ReaderT (Scenario s) (ExceptT String Identity) a\n    } deriving (Monad, Applicative, Alternative, Functor, MonadReader (Scenario s), MonadError String)\n\ninstance Num a => Num (Value s a) where\n    negate = fmap negate\n    (+) = liftM2 (+)\n    (*) = liftM2 (*)\n    fromInteger = pure . fromInteger\n    abs = fmap abs\n    signum = fmap signum\n\ninstance Fractional a => Fractional (Value s a) where\n    (/) = liftM2 (/)\n    fromRational = pure . fromRational\n    recip x = 1 / x\n\ntype TimeValue s a = Year -> Value s a\n\nrunValuation :: s -> Value s a -> Either String a\nrunValuation s v = runIdentity (runExceptT (runReaderT (runValue v) (Scenario s)))\n\nrunV :: (Show a, RealFrac a) => TimeValue () a -> [Year] -> IO ()\nrunV v (y:ys) = do\n    putStr $ show y\n    putStr \"  \"\n    case runValuation () $ v y of\n        Left s -> print s\n        Right result -> print result\n    runV v ys\nrunV _ [] = return ()\n\ndiscount :: TimeValue s Double -> Year -> TimeValue s Double -> TimeValue s Double\ndiscount r t0 v t\n    | t == t0 = v t\n    | otherwise = discount r (t0 + 1) v t / (1 + r (t0 + 1))\n\nnpv :: TimeValue s Double -> TimeValue s Double -> TimeValue s Double\nnpv r v t = v t + (npv r v (t + 1) / (1 + r (t + 1)) <|> return 0)\n\nlinear :: Fractional a => TimeValue s a -> Year -> Year -> a -> TimeValue s a\nlinear v t0 t1 target t\n    | t0 < t && t <= t1 = do\n        base <- v t0\n        return $ base + (target - base) * fromIntegral (t - t0) / fromIntegral (t1 - t0)\n    | t1 < t = return target\n\npvAnnuity :: Double -> Double -> Int -> Double\npvAnnuity r pmt n = pmt * (1 - (1 + r) ^^ (-n)) / r\n\nblackScholes :: Double -> Double -> Double -> Double -> Double -> Double\nblackScholes sigma r t s k =\n    let d1 = 1 / (sigma * sqrt t) * (log (s / k) + (r + sigma ** t / 2) * t)\n        d2 = d1 - sigma * sqrt t\n    in s * cumulative standard d1 - cumulative standard d2 * k * exp (-r * t)\n", "meta": {"hexsha": "d8cd7bab7fd47e3e82b35f51672b305d0eb6b81b", "size": 2304, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Valuation.hs", "max_stars_repo_name": "sboehler/haskell-valuation", "max_stars_repo_head_hexsha": "7d2b23ce99773cbd53df39ee8ee4314d53d9d328", "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/Valuation.hs", "max_issues_repo_name": "sboehler/haskell-valuation", "max_issues_repo_head_hexsha": "7d2b23ce99773cbd53df39ee8ee4314d53d9d328", "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/Valuation.hs", "max_forks_repo_name": "sboehler/haskell-valuation", "max_forks_repo_head_hexsha": "7d2b23ce99773cbd53df39ee8ee4314d53d9d328", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3157894737, "max_line_length": 102, "alphanum_fraction": 0.6137152778, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4529029922992993}}
{"text": "{-# LANGUAGE ApplicativeDo         #-}\n{-# LANGUAGE EmptyCase             #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE InstanceSigs          #-}\n{-# LANGUAGE KindSignatures        #-}\n{-# LANGUAGE LambdaCase            #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE StandaloneDeriving    #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeInType            #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE UndecidableInstances  #-}\n\nmodule TensorOps.Backend.BTensor\n  ( BTensor\n  , BTensorL, BTensorV\n  , HMat\n  , HMatD\n  ) where\n\nimport           Control.Applicative\nimport           Control.DeepSeq\nimport           Data.Distributive\nimport           Data.Kind\nimport           Data.List.Util\nimport           Data.Monoid\nimport           Data.Nested hiding             (unScalar, unVector, gmul')\nimport           Data.Singletons\nimport           Data.Singletons.Prelude hiding (Reverse, Head, sReverse, (:-))\nimport           Data.Type.Combinator\nimport           Data.Type.Combinator.Util\nimport           Data.Type.Length               as TCL\nimport           Data.Type.Length.Util          as TCL\nimport           Data.Type.Nat\nimport           Data.Type.Product              as TCP\nimport           Data.Type.Product.Util         as TCP\nimport           Data.Type.Sing\nimport           Data.Type.Uniform\nimport           Statistics.Distribution\nimport           TensorOps.BLAS\nimport           TensorOps.BLAS.HMat\nimport           TensorOps.NatKind\nimport           TensorOps.Types\nimport           Type.Class.Higher\nimport           Type.Class.Higher.Util\nimport           Type.Class.Witness\nimport           Type.Family.List\nimport           Type.Family.List.Util\nimport           Type.Family.Nat\nimport qualified Data.Type.Vector               as TCV\nimport qualified Data.Type.Vector.Util          as TCV\nimport qualified Data.Vector.Sized              as VS\n\n\ndata BTensor :: (k -> Type -> Type) -> (BShape k -> Type) -> [k] -> Type where\n    BTS :: { unScalar :: !(ElemB b)     } -> BTensor v b '[]\n    BTV :: { unVector :: !(b ('BV n))   } -> BTensor v b '[n]\n    BTM :: { unMatrix :: !(b ('BM n m)) } -> BTensor v b '[n,m]\n    BTN :: { unNested :: !(v n (BTensor v b (o ': m ': ns))) }\n        -> BTensor v b (n ': o ': m ': ns)\n\ntype BTensorL = BTensor (Flip2 TCV.VecT   I)\ntype BTensorV = BTensor (Flip2 VS.VectorT I)\n\ninstance (Nesting Proxy Show v, Show1 b, Show (ElemB b)) => Show (BTensor v b s) where\n    showsPrec p = \\case\n      BTS x  -> showParen (p > 10) $ showString \"BTS \"\n                                   . showsPrec 11 x\n      BTV xs -> showParen (p > 10) $ showString \"BTV \"\n                                   . showsPrec1 11 xs\n      BTM xs -> showParen (p > 10) $ showString \"BTM \"\n                                   . showsPrec1 11 xs\n      BTN xs -> showParen (p > 10) $ showString \"BTN \"\n                                   . showsPrec' 11 xs\n      where\n        showsPrec' :: forall n s'. Int -> v n (BTensor v b s') -> ShowS\n        showsPrec' p' xs = showsPrec p' xs\n            \\\\ (nesting Proxy :: Show (BTensor v b s')\n                              :- Show (v n (BTensor v b s'))\n               )\n\ninstance (Nesting Proxy Show v, Show1 b, Show (ElemB b)) => Show1 (BTensor v b)\n\ninstance (NFData (ElemB b), NFData1 b, Nesting Proxy NFData v) => Nesting1 Proxy NFData (BTensor v b) where\n    nesting1 _ = Wit\n\ninstance (NFData (ElemB b), NFData1 b, Nesting Proxy NFData v) => NFData (BTensor v b js) where\n    rnf = \\case\n      BTS x  -> rnf  x\n      BTV xs -> rnf1 xs\n      BTM xs -> rnf1 xs\n      BTN (xs :: v n (BTensor v b (o ': m ': ns))) ->\n        rnf xs \\\\ (nesting Proxy :: NFData (BTensor v b (o ': m ': ns))\n                                 :- NFData (v n (BTensor v b (o ': m ': ns)))\n                  )\n\ninstance (NFData (ElemB b), NFData1 b, Nesting Proxy NFData v) => NFData1 (BTensor v b)\n\ninstance ( BLAS b\n         , Vec v\n         , Nesting1 Proxy Functor v\n         , Nesting1 Sing Applicative v\n         , SingI ns\n         , Num (ElemB b)\n         )\n        => Num (BTensor v b ns) where\n    (+) = zipBase sing\n                  (+)\n                  (\\_          xs ys -> axpy 1 xs (Just ys))\n                  (\\(SBM _ sM) xs ys -> gemm 1 xs (eye sM) (Just (1, ys)))\n    {-# INLINE (+) #-}\n    (-) = zipBase sing\n                  (-)\n                  (\\_          xs ys -> axpy (-1) ys (Just xs))\n                  (\\(SBM _ sM) xs ys -> gemm 1 xs (eye sM) (Just (-1, ys)))\n    {-# INLINE (-) #-}\n    (*) = zipBTensorElems sing (*)\n    {-# INLINE (*) #-}\n    negate = mapBase sing\n                     negate\n                     (\\_          xs -> axpy (-1) xs Nothing)\n                     (\\(SBM _ sM) xs -> gemm 1 xs (eye sM) Nothing)\n    {-# INLINE negate #-}\n    abs    = mapBTensorElems abs\n    {-# INLINE abs #-}\n    signum = mapBTensorElems signum\n    {-# INLINE signum #-}\n    fromInteger i = genBTensor sing $ \\_ -> fromInteger i\n    {-# INLINE fromInteger #-}\n\n-- | TODO: add RULES pragmas so that this can be done without checking\n-- lengths at runtime in the common case that the lengths are known at\n-- compile-time.\n--\n-- Also, totally forgot about matrix-scalar multiplication here, but there\n-- isn't really any way of making it work without a lot of empty cases.\n-- should probably handle one level up.\ndispatchBLAS\n    :: forall b ms os ns v. (RealFloat (ElemB b), BLAS b)\n    => MaxLength N1 ms\n    -> MaxLength N1 os\n    -> MaxLength N1 ns\n    -> BTensor v b (ms         ++ os)\n    -> BTensor v b (Reverse os ++ ns)\n    -> BTensor v b (ms         ++ ns)\ndispatchBLAS lM lO lN v r = case (lM, lO, lN) of\n    (MLZ    , MLZ    , MLZ    ) -> case (v, r) of\n      -- scalar-scalar\n      (BTS x, BTS y) -> BTS $ x * y\n    (MLZ    , MLZ    , MLS MLZ) -> case (v, r) of\n      -- scalar-vector\n      (BTS x, BTV y) -> BTV $ axpy x y Nothing\n    (MLZ    , MLS MLZ, MLZ    ) -> case (v, r) of\n      -- dot\n      (BTV x, BTV y) -> BTS $ x `dot` y\n    (MLZ    , MLS MLZ, MLS MLZ) -> case (v, r) of\n      -- vector-matrix\n      -- TODO: transpose?\n      (BTV x, BTM y) -> BTV $ gemv 1 (transpB y) x Nothing\n    (MLS MLZ, MLZ    , MLZ    ) -> case (v, r) of\n      -- vector-scalar\n      (BTV x, BTS y) -> BTV $ axpy y x Nothing\n    (MLS MLZ, MLZ    , MLS MLZ) -> case (v, r) of\n      -- vector-scalar\n      (BTV x, BTV y) -> BTM $ ger x y\n    (MLS MLZ, MLS MLZ, MLZ    ) -> case (v, r) of\n      -- matrx-vector\n      (BTM x, BTV y) -> BTV $ gemv 1 x y Nothing\n    (MLS MLZ, MLS MLZ, MLS MLZ) -> case (v, r) of\n      -- matrix-matrix\n      (BTM x, BTM y) -> BTM $ gemm 1 x y Nothing\n{-# INLINE dispatchBLAS #-}\n\nmapRowsBTensor\n    :: forall k (v :: k -> Type -> Type) ns ms os b. (Vec v, BLAS b)\n    => Sing ns\n    -> Length os\n    -> (BTensor v b ms -> BTensor v b os)\n    -> BTensor v b (ns ++ ms)\n    -> BTensor v b (ns ++ os)\nmapRowsBTensor sN lO f = getI . bRows sN lO (I . f)\n{-# INLINE mapRowsBTensor #-}\n\n\nbRows\n    :: forall k (v :: k -> Type -> Type) ns ms os b f. (Applicative f, Vec v, BLAS b)\n    => Sing ns\n    -> Length os\n    -> (BTensor v b ms -> f (BTensor v b os))\n    -> BTensor v b (ns ++ ms)\n    -> f (BTensor v b (ns ++ os))\nbRows sN lO f = bIxRows sN lO (\\_ -> f)\n{-# INLINE bRows #-}\n\nmapIxRows\n    :: forall k (v :: k -> Type -> Type) ns ms os b. (Vec v, BLAS b)\n    => Sing ns\n    -> Length os\n    -> (Prod (IndexN k) ns -> BTensor v b ms -> BTensor v b os)\n    -> BTensor v b (ns ++ ms)\n    -> BTensor v b (ns ++ os)\nmapIxRows sN lO f = getI . bIxRows sN lO (\\i -> I . f i)\n{-# INLINE mapIxRows #-}\n\nfoldMapIxRows\n    :: forall k (v :: k -> Type -> Type) ns ms m b. (Vec v, Monoid m, BLAS b)\n    => Sing ns\n    -> (Prod (IndexN k) ns -> BTensor v b ms -> m)\n    -> BTensor v b (ns ++ ms)\n    -> m\nfoldMapIxRows s f = getConst . bIxRows s LZ (\\i -> Const . f i)\n{-# INLINE foldMapIxRows #-}\n\nbIxRows\n    :: forall k (v :: k -> Type -> Type) ns ms os b f. (Applicative f, Vec v, BLAS b)\n    => Sing ns\n    -> Length os\n    -> (Prod (IndexN k) ns -> BTensor v b ms -> f (BTensor v b os))\n    -> BTensor v b (ns ++ ms)\n    -> f (BTensor v b (ns ++ os))\nbIxRows = \\case\n    SNil   -> \\_  f -> f \u00d8\n    s `SCons` ss -> \\lO f -> \\case\n      BTV xs -> case ss of\n        -- ns ~ '[n]\n        -- ms ~ '[]\n        SNil -> case lO of\n          -- ns ++ os ~ '[n]\n          LZ        -> BTV <$> iElemsB (\\i -> fmap unScalar . f (pbvProd i) . BTS) xs\n          -- ns ++ os ~ '[n,m]\n          LS LZ     -> BTM <$> bgenRowsA (\\i -> unVector <$> f (i :< \u00d8) (BTS $ indexB (PBV i) xs))\n                         \\\\ s\n          LS (LS _) -> BTN <$> vGenA s (\\i -> f (i :< \u00d8) (BTS $ indexB (PBV i) xs))\n      BTM xs -> case ss of\n        -- ns ~ '[n]\n        -- ms ~ '[m]\n        SNil -> case lO of\n          -- ns ++ os ~ '[n]\n          LZ        -> BTV <$> bgenA (SBV s) (\\(PBV i) -> unScalar <$> f (i :< \u00d8) (BTV (indexRowB i xs)))\n          -- ns ++ os ~ '[n,o]\n          LS LZ     -> BTM <$> iRowsB (\\i -> fmap unVector . f (i :< \u00d8) . BTV) xs\n          LS (LS _) -> BTN <$> vGenA s (\\i -> f (i :< \u00d8) (BTV (indexRowB i xs)))\n        -- ns ~ '[n,m]\n        -- ms ~ '[]\n        s' `SCons` ss' -> (\\\\ s') $ case ss' of\n          SNil -> case lO of\n            LZ   -> BTM <$> iElemsB (\\i -> fmap unScalar . f (pbmProd i) . BTS) xs\n            LS _ -> BTN <$>\n                      vGenA s (\\i ->\n                          btn lO <$>\n                            vGenA s' (\\j ->\n                                f (i :< j :< \u00d8) (BTS (indexB (PBM i j) xs))\n                              )\n                        )\n      BTN xs -> (\\\\ s) $\n          fmap (btn (singLength ss `TCL.append'` lO))\n        . vITraverse (\\i -> bIxRows ss lO (\\is -> f (i :< is)))\n        $ xs\n\nindexRowBTensor\n    :: forall k (b :: BShape k -> Type) v ns ms.\n     ( BLAS b\n     , Vec v\n     )\n    => Prod (IndexN k) ns\n    -> BTensor v b (ns ++ ms)\n    -> BTensor v b ms\nindexRowBTensor = \\case\n    \u00d8       -> id\n    i :< is -> \\case\n      BTV xs -> case is of\n        \u00d8      -> BTS $ indexB    (PBV i)   xs\n      BTM xs -> case is of\n        \u00d8      -> BTV $ indexRowB i         xs\n        j :< \u00d8 -> BTS $ indexB    (PBM i j) xs\n      BTN xs -> indexRowBTensor is (vIndex i xs)\n{-# INLINE indexRowBTensor #-}\n\nmapBTensorElems\n    :: (Vec v, BLAS b)\n    => (ElemB b -> ElemB b)\n    -> BTensor v b ns\n    -> BTensor v b ns\nmapBTensorElems f = getI . bTensorElems (I . f)\n{-# INLINE mapBTensorElems #-}\n\nbTensorElems\n    :: forall k (v :: k -> Type -> Type) ns b f. (Applicative f, Vec v, BLAS b)\n    => (ElemB b -> f (ElemB b))\n    -> BTensor v b ns\n    -> f (BTensor v b ns)\nbTensorElems f = \\case\n    BTS x  -> BTS <$> f x\n    BTV xs -> BTV <$> elemsB f xs\n    BTM xs -> BTM <$> elemsB f xs\n    BTN xs -> BTN <$> vITraverse (\\_ x -> bTensorElems f x) xs\n{-# INLINE bTensorElems #-}\n\nifoldMapBTensor\n    :: forall k (v :: k -> Type -> Type) ns m b. (Monoid m, Vec v, BLAS b)\n    => (Prod (IndexN k) ns -> ElemB b -> m)\n    -> BTensor v b ns\n    -> m\nifoldMapBTensor f = getConst . bTensorIxElems (\\i -> Const . f i)\n{-# INLINE ifoldMapBTensor #-}\n\nbTensorIxElems\n    :: forall k (v :: k -> Type -> Type) ns b f. (Applicative f, Vec v, BLAS b)\n    => (Prod (IndexN k) ns -> ElemB b -> f (ElemB b))\n    -> BTensor v b ns\n    -> f (BTensor v b ns)\nbTensorIxElems f = \\case\n    BTS x  -> BTS <$> f \u00d8 x\n    BTV xs -> BTV <$> iElemsB (f . pbvProd) xs\n    BTM xs -> BTM <$> iElemsB (f . pbmProd) xs\n    BTN xs -> BTN <$> vITraverse (\\i -> bTensorIxElems (\\is -> f (i :< is))) xs\n{-# INLINE bTensorIxElems #-}\n\nzipBTensorElems\n    :: forall v b ns. (BLAS b, Nesting1 Sing Applicative v)\n    => Sing ns\n    -> (ElemB b -> ElemB b -> ElemB b)\n    -> BTensor v b ns\n    -> BTensor v b ns\n    -> BTensor v b ns\nzipBTensorElems = \\case\n    SNil -> \\f -> \\case\n      BTS x -> \\case\n        BTS y -> BTS (f x y)\n    sN `SCons` SNil -> \\f -> \\case\n      BTV xs -> \\case\n        BTV ys -> BTV (zipB (SBV sN) f xs ys)\n    sN `SCons` (sM `SCons` SNil) -> \\f -> \\case\n      BTM xs -> \\case\n        BTM ys -> BTM (zipB (SBM sN sM) f xs ys)\n    (s :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \\f -> \\case\n      BTN xs -> \\case\n        BTN ys -> BTN (zipBTensorElems ss f <$> xs <*> ys)\n                    \\\\ (nesting1 s :: Wit (Applicative (v k)))\n{-# INLINE zipBTensorElems #-}\n\nliftBTensor\n    :: forall v b ns n.\n     ( BLAS b\n     , Nesting1 Proxy Functor      v\n     , Nesting1 Sing  Distributive v\n     )\n    => Sing ns\n    -> (TCV.Vec n (ElemB b) -> ElemB b)\n    -> TCV.Vec n (BTensor v b ns)\n    -> BTensor v b ns\nliftBTensor = \\case\n    SNil                         -> \\f xs ->\n        let xs' = unScalar <$> xs\n        in  BTS $ f xs'\n    sN `SCons` SNil              -> \\f xs ->\n        let xs' = unVector <$> xs\n        in  BTV $ liftB (SBV sN) f xs'\n    sN `SCons` (sM `SCons` SNil) -> \\f xs ->\n        let xs' = unMatrix <$> xs\n        in  BTM $ liftB (SBM sN sM) f xs'\n    (s :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \\f xs ->\n        let xs' = unNested <$> xs\n        in  BTN $ TCV.liftVecD (liftBTensor ss f) xs'\n              \\\\ (nesting1 s     :: Wit (Distributive (v k)))\n{-# INLINE liftBTensor #-}\n\nmapBTM\n    :: forall k (v :: k -> Type -> Type) ns n m ms b. (Vec v, BLAS b)\n    => Sing ns\n    -> Length ms\n    -> (b ('BM n m) -> BTensor v b ms)\n    -> BTensor v b (ns ++ [n,m])\n    -> BTensor v b (ns ++ ms)\nmapBTM sN lM f = getI . traverseBTM sN lM (I . f)\n{-# INLINE mapBTM #-}\n\nfoldMapBTM\n    :: (Monoid a, Vec v, BLAS b)\n    => Length ns\n    -> (b ('BM n m) -> a)\n    -> BTensor v b (ns ++ [n,m])\n    -> a\nfoldMapBTM l f = ifoldMapBTM l (\\_ -> f)\n{-# INLINE foldMapBTM #-}\n\ntraverseBTM\n    :: forall k (v :: k -> Type -> Type) ns n m ms b f. (Applicative f, Vec v, BLAS b)\n    => Sing ns\n    -> Length ms\n    -> (b ('BM n m) -> f (BTensor v b ms))\n    -> BTensor v b (ns ++ [n,m])\n    -> f (BTensor v b (ns ++ ms))\ntraverseBTM = \\case\n    SNil         -> \\_ f -> \\case\n      BTM x  -> f x\n    s `SCons` ss -> \\lM f -> \\case\n      BTV _  -> case ss of\n      BTM _  -> case ss of\n      BTN xs -> (\\\\ s) $\n          fmap (btn (singLength ss `TCL.append'` lM))\n        . vITraverse (\\_ -> traverseBTM ss lM f)\n        $ xs\n{-# INLINE traverseBTM #-}\n\nimapBTM\n    :: forall k (v :: k -> Type -> Type) ns n m ms b. (Vec v, BLAS b)\n    => Sing ns\n    -> Length ms\n    -> (Prod (IndexN k) ns -> b ('BM n m) -> BTensor v b ms)\n    -> BTensor v b (ns ++ [n,m])\n    -> BTensor v b (ns ++ ms)\nimapBTM sN lM f = getI . itraverseBTM sN lM (\\i -> I . f i)\n{-# INLINE imapBTM #-}\n\nifoldMapBTM\n    :: (Vec v, Monoid a, BLAS b)\n    => Length ns\n    -> (Prod (IndexN k) ns -> b ('BM n m) -> a)\n    -> BTensor v b (ns ++ [n,m])\n    -> a\nifoldMapBTM = \\case\n    LZ -> \\f -> \\case\n      BTM xs -> f \u00d8 xs\n    LS l -> \\f -> \\case\n      BTV _  -> case l of\n      BTM _  -> case l of\n      BTN xs -> vIFoldMap (\\i -> ifoldMapBTM l (\\is -> f (i :< is))) xs\n{-# INLINE ifoldMapBTM #-}\n\nitraverseBTM\n    :: forall k (v :: k -> Type -> Type) ns n m ms b f. (Applicative f, Vec v, BLAS b)\n    => Sing ns\n    -> Length ms\n    -> (Prod (IndexN k) ns -> b ('BM n m) -> f (BTensor v b ms))\n    -> BTensor v b (ns ++ [n,m])\n    -> f (BTensor v b (ns ++ ms))\nitraverseBTM = \\case\n    SNil         -> \\_ f -> \\case\n      BTM x  -> f \u00d8 x\n    s `SCons` ss -> \\lM f -> \\case\n      BTV _  -> case ss of\n      BTM _  -> case ss of\n      BTN xs -> (\\\\ s) $\n          fmap (btn (singLength ss `TCL.append'` lM))\n        . vITraverse (\\i -> itraverseBTM ss lM (\\is ys -> f (i :< is) ys))\n        $ xs\n{-# INLINE itraverseBTM #-}\n\nmapBase\n    :: forall v b ns. (Nesting1 Proxy Functor v)\n    => Sing ns\n    -> (ElemB b -> ElemB b)\n    -> (forall n. Sing n -> b ('BV n) -> b ('BV n))\n    -> (forall n m. Sing ('BM n m) -> b ('BM n m) -> b ('BM n m))\n    -> BTensor v b ns\n    -> BTensor v b ns\nmapBase = \\case\n    SNil -> \\f _ _ -> \\case\n      BTS x  -> BTS (f x)\n    sN `SCons` SNil -> \\_ g _ -> \\case\n      BTV xs -> BTV (g sN          xs)\n    sN `SCons` (sM `SCons` SNil) -> \\_ _ h -> \\case\n      BTM xs -> BTM (h (SBM sN sM) xs)\n    (_ :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \\f g h -> \\case\n      BTN xs -> BTN (mapBase ss f g h <$> xs)\n                  \\\\ (nesting1 Proxy :: Wit (Functor (v k)))\n{-# INLINE mapBase #-}\n\nzipBase\n    :: forall v b ns. (Nesting1 Sing Applicative v)\n    => Sing ns\n    -> (ElemB b -> ElemB b -> ElemB b)\n    -> (forall n. Sing n -> b ('BV n) -> b ('BV n) -> b ('BV n))\n    -> (forall n m. Sing ('BM n m) -> b ('BM n m) -> b ('BM n m) -> b ('BM n m))\n    -> BTensor v b ns\n    -> BTensor v b ns\n    -> BTensor v b ns\nzipBase = \\case\n    SNil -> \\f _ _ -> \\case\n      BTS x -> \\case\n        BTS y -> BTS (f x y)\n    sN `SCons` SNil -> \\_ g _ -> \\case\n      BTV xs -> \\case\n        BTV ys -> BTV (g sN          xs ys)\n    sN `SCons` (sM `SCons` SNil) -> \\_ _ h -> \\case\n      BTM xs -> \\case\n        BTM ys -> BTM (h (SBM sN sM) xs ys)\n    (s :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \\f g h -> \\case\n      BTN xs -> \\case\n        BTN ys -> BTN $ zipBase ss f g h <$> xs <*> ys\n                    \\\\ (nesting1 s :: Wit (Applicative (v k)))\n{-# INLINE zipBase #-}\n\ngenBTensorA\n    :: forall k (b :: BShape k -> Type) v (ns :: [k]) f. (Applicative f, BLAS b, Vec v)\n    => Sing ns\n    -> (Prod (IndexN k) ns -> f (ElemB b))\n    -> f (BTensor v b ns)\ngenBTensorA = \\case\n    SNil                                   -> \\f ->\n        BTS <$> f \u00d8\n    sN `SCons` SNil                        -> \\f ->\n        BTV <$> bgenA (SBV sN)    (f . pbvProd)\n    sN `SCons` (sM `SCons` SNil)           -> \\f ->\n        BTM <$> bgenA (SBM sN sM) (f . pbmProd)\n    s `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \\f ->\n        BTN <$> vGenA s (\\i -> genBTensorA ss (\\is -> f (i :< is)))\n{-# INLINE genBTensorA #-}\n\ngenBTensor\n    :: forall k (b :: BShape k -> Type) v (ns :: [k]). (BLAS b, Vec v)\n    => Sing ns\n    -> (Prod (IndexN k) ns -> ElemB b)\n    -> BTensor v b ns\ngenBTensor s f = getI $ genBTensorA s (I . f)\n{-# INLINE genBTensor #-}\n\nindexBTensor\n    :: forall k (b :: BShape k -> Type) v ns. (BLAS b, Vec v)\n    => Prod (IndexN k) ns\n    -> BTensor v b ns\n    -> ElemB b\nindexBTensor = \\case\n    \u00d8      -> \\case\n      BTS x  -> x\n    i :< \u00d8 -> \\case\n      BTV xs -> indexB (PBV i) xs\n    i :< j :< \u00d8 -> \\case\n      BTM xs -> indexB (PBM i j) xs\n    i :< js@(_ :< _ :< _) -> \\case\n      BTN xs -> indexBTensor js (vIndex i xs)\n{-# INLINE indexBTensor #-}\n\nbtn :: (BLAS b, Vec v, SingI n)\n    => Length ns\n    -> v n (BTensor v b ns)\n    -> BTensor v b (n ': ns)\nbtn = \\case\n    LZ        -> \\xs ->\n      BTV $ bgen sing (unScalar . (`vIndex` xs) . unPBV)\n    LS LZ     -> \\xs ->\n      BTM $ bgenRows  (unVector . (`vIndex` xs))\n    LS (LS _) -> BTN\n{-# INLINE btn #-}\n\ngmul'\n    :: forall v b ms os ns.\n     ( SingI (ms ++ ns)\n     , RealFloat (ElemB b)\n     , Vec v\n     , Nesting1 Proxy Functor     v\n     , Nesting1 Sing  Applicative v\n     , BLAS b\n     )\n    => Length ms\n    -> Length os\n    -> Length ns\n    -> BTensor v b (ms         ++ os)\n    -> BTensor v b (Reverse os ++ ns)\n    -> BTensor v b (ms         ++ ns)\ngmul' lM lO lN = gmulB sM lO lN \\\\ sN\n  where\n    sM :: Sing ms\n    sN :: Sing ns\n    (sM, sN) = splitSing lM sing\n{-# INLINE[0] gmul' #-}\n\n{-# RULES\n\"gmul'/SS\"  gmul' = dispatchSS\n\"gmul'/SV\"  gmul' = dispatchSV\n\"gmul'/dot\" gmul' = dispatchDot\n\"gmul'/VM\"  gmul' = dispatchVM\n\"gmul'/VS\"  gmul' = dispatchVS\n\"gmul'/out\" gmul' = dispatchOut\n\"gmul'/MV\"  gmul' = dispatchMV\n\"gmul'/MM\"  gmul' = dispatchMM\n  #-}\n\n\n\n-- | General strategy:\n--\n-- *   We can only outsource to BLAS (using 'dispatchBLAS') in the case\n--     that @os@ and @ns@ have length 0 or 1.  Anything else, fall back to\n--     the basic reverse-indexing method in \"Data.Nested\".\n-- *   If @ms@ is length 2 or higher, \"traverse down\" to the length 0 or\n--     1 tail...and then sum them up.\ngmulB\n    :: forall k (b :: BShape k -> Type) v ms os ns.\n     ( RealFloat (ElemB b)\n     , SingI ns\n     , BLAS b\n     , Vec v\n     , Nesting1 Proxy Functor     v\n     , Nesting1 Sing  Applicative v\n     )\n    => Sing ms\n    -> Length os\n    -> Length ns\n    -> BTensor v b (ms         ++ os)\n    -> BTensor v b (Reverse os ++ ns)\n    -> BTensor v b (ms         ++ ns)\ngmulB sM lO lN v r = case splitting (S_ Z_) (lengthProd lN) of\n    Fewer mlN _ -> case splittingEnd (S_ (S_ Z_)) (lengthProd lO) of\n      FewerEnd MLZ             _ -> gmulBLAS sM MLZ       mlN v r\n      FewerEnd (MLS MLZ)       _ -> gmulBLAS sM (MLS MLZ) mlN v r\n      FewerEnd (MLS (MLS MLZ)) _ -> case mlN of\n        MLZ -> case r of\n          BTM ys -> mapBTM sM LZ (\\xs -> BTS $ traceB (gemm 1 xs ys Nothing)) v\n        MLS MLZ -> naiveGMul sM lO lN v r\n      SplitEnd _ _ _ -> naiveGMul sM lO lN v r\n    Split _ _ _ -> naiveGMul sM lO lN v r\n{-# INLINE[0] gmulB #-}\n\n-- | Naive implementation of 'gmul' (based on the implementation for\n-- 'NTensor') that does not utilize any BLAS capabilities.\nnaiveGMul\n    :: forall k (b :: BShape k -> Type) v ms os ns.\n     ( BLAS b\n     , Vec v\n     , Num (ElemB b)\n     , Nesting1 Proxy Functor     v\n     , Nesting1 Sing  Applicative v\n     , SingI ns\n     )\n    => Sing ms\n    -> Length os\n    -> Length ns\n    -> BTensor v b (ms         ++ os)\n    -> BTensor v b (Reverse os ++ ns)\n    -> BTensor v b (ms         ++ ns)\nnaiveGMul sM _ lN v r =\n    mapRowsBTensor sM lN (getSum . ifoldMapBTensor (\\i -> Sum . f i)) v\n  where\n    f  :: Prod (IndexN k) os\n       -> ElemB b\n       -> BTensor v b ns\n    f is x = mapBase sing\n                     (x *)\n                     (\\_ ys -> scaleB x ys)\n                     (\\_ ys -> scaleB x ys)\n                     (indexRowBTensor (TCP.reverse' is) r)\n\n-- | A 'gmul' that runs my dispatching BLAS commands when it can.\n-- Contains the type-level constraint that @os@ and @ns@ have to have\n-- either length 0 or 1.\n--\n-- TODO: no longer needs Sing ms\ngmulBLAS\n    :: forall b ms os ns v.\n     ( RealFloat (ElemB b)\n     , BLAS b\n     , Vec v\n     , SingI ns\n     , Nesting1 Proxy Functor     v\n     , Nesting1 Sing  Applicative v\n     )\n    => Sing ms\n    -> MaxLength N1 os\n    -> MaxLength N1 ns\n    -> BTensor v b (ms         ++ os)\n    -> BTensor v b (Reverse os ++ ns)\n    -> BTensor v b (ms         ++ ns)\ngmulBLAS sM mlO mlN v r = case mlO of\n    MLZ -> case splittingEnd (S_ (S_ Z_)) spM of\n      FewerEnd MLZ             _ -> dispatchBLAS MLZ       mlO  mlN v r\n      FewerEnd (MLS MLZ)       _ -> dispatchBLAS (MLS MLZ) mlO mlN v r\n      FewerEnd (MLS (MLS MLZ)) _ -> case v of\n        BTM xs -> case mlN of\n          MLZ     -> case r of\n            BTS y  -> BTM $ scaleB y xs\n          -- TODO: can this be made non-naive?\n          -- ms ~ '[m1,m2]\n          -- os ~ '[]\n          -- ns ~ '[n]\n          MLS MLZ -> naiveGMul sM LZ (fromMaxLength mlN) v r\n      SplitEnd (ELS (ELS ELZ)) spM0 spM1 -> case mlN of\n        MLZ -> case r of\n          BTS y -> mapBTM (prodSing   spM0)\n                          (prodLength spM1)\n                          (\\xs -> BTM $ scaleB y xs)\n                          v\n                     \\\\ appendNil lM\n        -- TODO: can this be made non-naive?\n        -- ms ~ (ms0 ++ '[m1,m2])\n        -- os ~ '[]\n        -- ns ~ '[n]\n        MLS MLZ -> naiveGMul sM LZ (fromMaxLength mlN) v r\n    MLS MLZ -> case splittingEnd (S_ Z_) spM of\n      FewerEnd mlM       _         -> dispatchBLAS mlM mlO mlN v r\n      SplitEnd (ELS ELZ) spM0 spM1 ->\n        let sM0 = prodSing spM0\n            lM0 = prodLength spM0\n            lM1 = prodLength spM1\n        in  (\\\\ appendAssoc (TCL.tail' lM0)\n                            lM1\n                            (LS LZ :: Length os)\n            ) $ case mlN of\n          MLZ -> case r of\n            BTV ys -> mapBTM sM0 lM1 (\\xs -> BTV $ gemv 1 xs ys Nothing) v\n                        \\\\ appendNil lM\n          MLS MLZ -> case r of\n            BTM ys -> mapBTM sM0\n                            (lM1 `TCL.append'` (LS LZ :: Length ns))\n                            (\\xs -> BTM $ gemm 1 xs ys Nothing)\n                            v\n                        \\\\ appendAssoc (TCL.tail' lM0)\n                                       lM1\n                                       (LS LZ :: Length ns)\n  where\n    spM = singProd sM\n    lM  = singLength sM\n\ndiagBTensor\n    :: forall k (b :: BShape k -> Type) v n ns.\n     ( SingI (n ': ns)\n     , BLAS b\n     , Vec v\n     , Num (ElemB b)\n     , Eq (IndexN k n)\n     )\n    => Uniform n ns\n    -> BTensor v b '[n]\n    -> BTensor v b (n ': ns)\ndiagBTensor = \\case\n    U\u00d8    -> id\n    US U\u00d8 -> \\case\n      BTV xs -> BTM $ diagB xs\n    u@(US (US _)) -> \\(BTV xs) ->\n      genBTensor sing (\\i -> case TCV.uniformVec (prodToVec I (US u) i) of\n                               Nothing -> 0\n                               Just (I i') -> indexB (PBV i') xs\n                      )\n{-# INLINE diagBTensor #-}\n\ntranspBTensor\n    :: (BLAS b, Vec v)\n    => Sing ns\n    -> BTensor v b ns\n    -> BTensor v b (Reverse ns)\ntranspBTensor s = \\case\n    BTS x      -> BTS x\n    BTV xs     -> BTV xs\n    BTM xs     -> BTM $ transpB xs\n    xs@(BTN _) -> (\\\\ reverseReverse (singLength s)) $\n                    genBTensor (sReverse s) $ \\i ->\n                      indexBTensor (TCP.reverse' i) xs\n{-# INLINE transpBTensor #-}\n\nsumBTensor\n    :: forall v b n ns.\n     ( BLAS b\n     , Vec v\n     , Num (ElemB b)\n     , Foldable (v n)\n     , SingI ns\n     , SingI n\n     , Nesting1 Proxy Functor     v\n     , Nesting1 Sing  Applicative v\n     )\n    => BTensor v b (n ': ns)\n    -> BTensor v b ns\nsumBTensor = \\case\n    BTV xs  -> BTS $ sumB xs\n    BTM (xs :: b ('BM n m))\n            -> BTV $ gemv 1 (transpB xs)\n                          (bgen (SBV (sing :: Sing n)) (\\_ -> 1))\n                          Nothing\n    BTN xs  -> sum xs\n\ninstance\n      ( Vec (v :: k -> Type -> Type)\n      , BLAS b\n      , RealFloat (ElemB b)\n      , Nesting1 Proxy Functor      v\n      , Nesting1 Proxy Foldable     v\n      , Nesting1 Sing  Applicative  v\n      , Nesting1 Sing  Distributive v\n      , Eq1 (IndexN k)\n      )\n  => Tensor (BTensor v b) where\n    type ElemT (BTensor v b) = ElemB b\n\n    liftT\n        :: SingI ns\n        => (TCV.Vec n (ElemB b) -> ElemB b)\n        -> TCV.Vec n (BTensor v b ns)\n        -> BTensor v b ns\n    liftT = liftBTensor sing\n    {-# INLINE liftT #-}\n\n    sumT = sum'\n    {-# INLINE sumT #-}\n\n    scaleT \u03b1 = mapBase sing (\u03b1*) (\\_ -> scaleB \u03b1) (\\_ -> scaleB \u03b1)\n    {-# INLINE scaleT #-}\n\n    gmul\n        :: forall ms os ns. SingI (ms ++ ns)\n        => Length ms\n        -> Length os\n        -> Length ns\n        -> BTensor v b (ms         ++ os)\n        -> BTensor v b (Reverse os ++ ns)\n        -> BTensor v b (ms         ++ ns)\n    gmul = gmul'\n    {-# INLINE gmul #-}\n\n    diag\n        :: forall n ns. SingI (n ': ns)\n        => Uniform n ns\n        -> BTensor v b '[n]\n        -> BTensor v b (n ': ns)\n    diag = diagBTensor\n             \\\\ (produceEq1 :: Eq1 (IndexN k) :- Eq (IndexN k n))\n    {-# INLINE diag #-}\n\n    getDiag\n        :: SingI n\n        => Uniform n ns\n        -> BTensor v b (n ': n ': ns)\n        -> BTensor v b '[n]\n    getDiag = \\case\n      U\u00d8   -> \\case\n        BTM xs -> BTV $ getDiagB xs\n      u@(US _) -> \\xs ->\n        genBTensor sing $ \\(i :< \u00d8) ->\n          indexBTensor (TCP.replicate i (US (US u))) xs\n    {-# INLINE getDiag #-}\n\n    transp = transpBTensor sing\n    {-# INLINE transp #-}\n\n    generateA = genBTensorA sing\n    {-# INLINE generateA #-}\n\n    genRand d g = generateA (\\_ -> realToFrac <$> genContVar d g)\n    {-# INLINE genRand #-}\n\n    ixRows\n        :: forall f ms os ns. (Applicative f, SingI (ms ++ os))\n        => Length ms\n        -> Length os\n        -> (Prod (IndexN k) ms -> BTensor v b ns -> f (BTensor v b os))\n        -> BTensor v b (ms ++ ns)\n        -> f (BTensor v b (ms ++ os))\n    ixRows lM lO = bIxRows sM lO\n      where\n        sM :: Sing ms\n        sM = takeSing lM lO (sing :: Sing (ms ++ os))\n    {-# INLINE ixRows #-}\n\n    (!) = flip indexBTensor\n    {-# INLINE (!) #-}\n\n    sumRows\n        :: forall n ns. (SingI (n ': ns), SingI ns)\n        => BTensor v b (n ': ns)\n        -> BTensor v b ns\n    sumRows = sumBTensor\n                \\\\ (nesting1 Proxy :: Wit (Foldable (v n)))\n                \\\\ sHead (sing :: Sing (n ': ns))\n    {-# INLINE sumRows #-}\n\n    mapRows :: forall ns ms. SingI (ns ++ ms)\n            => Length ns\n            -> (BTensor v b ms -> BTensor v b ms)\n            -> BTensor v b (ns ++ ms)\n            -> BTensor v b (ns ++ ms)\n    mapRows l f = mapRowsBTensor sN (singLength sM) f\n      where\n        sN :: Sing ns\n        sM :: Sing ms\n        (sN, sM) = splitSing l (sing :: Sing (ns ++ ms))\n    {-# INLINE mapRows #-}\n\n\n-- * Boring dispatches\n\ndispatchSS\n    :: Num (ElemB b)\n    => Length '[]\n    -> Length '[]\n    -> Length '[]\n    -> BTensor v b '[]\n    -> BTensor v b '[]\n    -> BTensor v b '[]\ndispatchSS _ _ _ (BTS x) (BTS y) = BTS (x * y)\n{-# INLINE dispatchSS #-}\n\ndispatchSV\n    :: BLAS b\n    => Length '[]\n    -> Length '[]\n    -> Length '[n]\n    -> BTensor v b '[]\n    -> BTensor v b '[n]\n    -> BTensor v b '[n]\ndispatchSV _ _ _ (BTS x) (BTV y) = BTV $ axpy x y Nothing\n{-# INLINE dispatchSV #-}\n\ndispatchDot\n    :: BLAS b\n    => Length '[]\n    -> Length '[n]\n    -> Length '[]\n    -> BTensor v b '[n]\n    -> BTensor v b '[n]\n    -> BTensor v b '[]\ndispatchDot _ _ _ (BTV x) (BTV y) = BTS $ x `dot` y\n{-# INLINE dispatchDot #-}\n\ndispatchVM\n    :: (Num (ElemB b), BLAS b)\n    => Length '[]\n    -> Length '[n]\n    -> Length '[m]\n    -> BTensor v b '[n]\n    -> BTensor v b '[n,m]\n    -> BTensor v b '[m]\ndispatchVM _ _ _ (BTV x) (BTM y) = BTV $ gemv 1 (transpB y) x Nothing\n{-# INLINE dispatchVM #-}\n\ndispatchVS\n    :: BLAS b\n    => Length '[n]\n    -> Length '[]\n    -> Length '[]\n    -> BTensor v b '[n]\n    -> BTensor v b '[]\n    -> BTensor v b '[n]\ndispatchVS _ _ _ (BTV x) (BTS y) = BTV $ axpy y x Nothing\n{-# INLINE dispatchVS #-}\n\ndispatchOut\n    :: BLAS b\n    => Length '[n]\n    -> Length '[]\n    -> Length '[m]\n    -> BTensor v b '[n]\n    -> BTensor v b '[m]\n    -> BTensor v b '[n,m]\ndispatchOut _ _ _ (BTV x) (BTV y) = BTM $ ger x y\n{-# INLINE dispatchOut #-}\n\ndispatchMV\n    :: (Num (ElemB b), BLAS b)\n    => Length '[n]\n    -> Length '[m]\n    -> Length '[]\n    -> BTensor v b '[n,m]\n    -> BTensor v b '[m]\n    -> BTensor v b '[n]\ndispatchMV _ _ _ (BTM x) (BTV y) = BTV $ gemv 1 x y Nothing\n{-# INLINE dispatchMV #-}\n\ndispatchMM\n    :: (Num (ElemB b), BLAS b)\n    => Length '[m]\n    -> Length '[o]\n    -> Length '[n]\n    -> BTensor v b '[m,o]\n    -> BTensor v b '[o,n]\n    -> BTensor v b '[m,n]\ndispatchMM _ _ _ (BTM x) (BTM y) = BTM $ gemm 1 x y Nothing\n{-# INLINE dispatchMM #-}\n\n", "meta": {"hexsha": "d2c93f43cab1ae7769acfa0bb0c46e154ab933b9", "size": 30674, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/TensorOps/Backend/BTensor.hs", "max_stars_repo_name": "mstksg/tensor-ops", "max_stars_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2016-08-24T06:50:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T00:31:35.000Z", "max_issues_repo_path": "src/TensorOps/Backend/BTensor.hs", "max_issues_repo_name": "mstksg/tensor-ops", "max_issues_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-09-29T06:01:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T10:52:51.000Z", "max_forks_repo_path": "src/TensorOps/Backend/BTensor.hs", "max_forks_repo_name": "mstksg/tensor-ops", "max_forks_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-09-28T05:44:48.000Z", "max_forks_repo_forks_event_max_datetime": "2017-01-30T11:01:34.000Z", "avg_line_length": 31.5576131687, "max_line_length": 107, "alphanum_fraction": 0.4831779357, "num_tokens": 10231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189134878876, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.45270339352735633}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Clustering.Hierarchical where\n\nimport Numeric.LinearAlgebra\nimport Data.List.Lens\nimport Control.Lens\nimport Control.Applicative\nimport Debug.Trace ( trace )\n\nimport Clustering.Util\nimport Clustering.Data\n\n\nfindClosest2 :: (Ord t) => (a -> a -> t) -> [a] -> Maybe ((Int, Int), t)\nfindClosest2 _ []  = Nothing\nfindClosest2 f cls = getidx r1 r2\n    where\n        r1 = findClosest1s f cls\n        r2 = argminval (snd <$>) r1\n        getidx :: [Maybe (Int, t)] -> Maybe (Int, Maybe t) -> Maybe ((Int, Int), t)\n        getidx l (Just (i, Just v1)) = case l !! i of\n          Nothing -> Nothing\n          Just (j, v2) -> Just ((i, j), v1)\n        getidx l (Just (i, Nothing)) = Nothing\n        getidx _ Nothing = Nothing\n\n\nfindClosest1s :: (Ord t) => (a -> a -> t) -> [a] -> [Maybe (Int, t)]\nfindClosest1s _ [] = []\nfindClosest1s f ls = reverse $ findClosest1s' [] ls []\n    where\n        findClosest1s' left [] cl = cl\n        findClosest1s' left (x:right) cl =\n            findClosest1s' (left ++ [x]) right $\n                        selectMMin\n                            (findClosest f x left)\n                            ((_1 +~ 1 + length left) <$> findClosest f x right)\n                            -- shift right index\n                        : cl\n\nfindClosest :: (Ord t) =>  (a -> a -> t) -> a -> [a] -> Maybe (Int, t)\nfindClosest _ _ [] = Nothing\nfindClosest d x ls = argminval (d x) ls\n\nselectMMin :: Ord b => Maybe (a, b) -> Maybe (a, b) -> Maybe (a, b)\nselectMMin (Just (n, v1)) (Just (m, v2)) | v2 < v1 = Just (m, v2)\nselectMMin (Just (n, v1)) (Just (m, v2)) | v2 > v1 = Just (n, v1)\nselectMMin m1 m2 = m1 <|> m2\n\nmerge ::(Ord t) => t -> ([a] -> [a] -> t) -> [[a]] -> [[a]]\nmerge _ _ [] = []\nmerge m f ls = case findClosest2 f ls of\n  Nothing          -> ls\n  Just ((i, j), v) -> if v < m\n                        then merge m f $ merge2 i j ls\n                        else ls\n\nmerge2 :: Int -> Int -> [[a]] -> [[a]]\nmerge2 i j ls = deleteList j $ ix i %~ (\\l -> l ++ ls !! j) $ ls\n\n-- | Generalized aggregative scheme using Dendrogram\ngasd :: forall a.\n    (Dendrogram a -> Dendrogram a -> Float) -- ^ dendrogram distance\n    -> (Dendrogram a -> Dendrogram a -> a)  -- ^ representative update\n    -> [a] -> Dendrogram a\ngasd dd ru xs = agglomerated' 0 $ map dLeaf xs\n    where\n        agglomerated' :: Int -> [Dendrogram a] -> Dendrogram a\n        agglomerated' _ [] = DNil\n        agglomerated' _ ds@(d:_) | length ds == 1 = d\n        agglomerated' level ds = case findClosest2 dd ds of\n            Nothing -> error \"Nothing to merge!\"\n            Just ((i, j), v) -> let (newl, newr) = (ds !! i, ds !!j) in\n                agglomerated' (level + 1) $ (DNode (ru newl newr) (level + 1) v newl newr) : dels [i, j] ds\n\n-- | Generalized aggregative scheme\ngas ::  Ord t => forall a. ([a] -> [a] -> t) -> [a] -> [[[a]]]\ngas cd xs = agglomerate' [map (:[]) xs]\n    where\n        -- agglomerate' :: [[[a]]] -> [[[a]]]\n        agglomerate' [] = []\n        agglomerate' [[]] = []\n        agglomerate' acs@(c:_) | length c == 1 = acs\n        agglomerate' acs@(c:_) = case findClosest2 cd c of\n            Nothing -> acs\n            Just ((i, j), _) -> agglomerate' $ merge2 i j c:acs\n\n\nbuildSimilarityMtrx :: (a -> a -> Float) -> [a] -> Matrix Float\nbuildSimilarityMtrx d xs = l >< l $ concatMap (\\x -> map (d x) xs) xs\n    where\n        l = length xs\n\n-- | Matrix update aggregative scheme\nmuas :: Matrix Float -> (Matrix Float -> Int -> Int -> Int) -> [[Int]]\nmuas p d = undefined -- TODO optimized agglomerative scheme using matrix update\n\n-- | Modified general divisive scheme\nmgds :: (Ord t, Num t, Fractional t) =>\n    (a -> a -> t) -- ^ dissimiliarity measure\n    -> [a]\n    -> [[[a]]]\nmgds d [] = []\nmgds d xs = divideAll [[xs]]\n    where\n        divideAll [] = []\n        divideAll acs@(c:cs) = if length cs == length xs then acs\n                                                         else divideAll $ (c >>= splitCluster) : acs\n        splitCluster [] = []\n        splitCluster xs = reassign $ outsider xs\n                      -- map (((1/fromIntegral (length xs) * ) . sum) . (\\x -> map (d x) xs)) xs\n        outsider xs = case argmax id $ map (avg . flip map xs . d) xs of\n                        Nothing -> error \"What happend?!\"\n                        Just n -> case pop n xs of\n                             (as, Nothing) -> ([], as)\n                             (as, Just a) -> ([a], as)\n\n        reassign ([], os) = [os]\n        reassign (ns, []) = [ns]\n        reassign (ns, as) = [ns, as]\n                            ", "meta": {"hexsha": "f4060f204e9de0eeedb90ce3bb9881f337ab5ac3", "size": 4584, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Clustering/Hierarchical.hs", "max_stars_repo_name": "zitkat/clustering", "max_stars_repo_head_hexsha": "69dc90ae776e118f4212355850e7c34287dad832", "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/Clustering/Hierarchical.hs", "max_issues_repo_name": "zitkat/clustering", "max_issues_repo_head_hexsha": "69dc90ae776e118f4212355850e7c34287dad832", "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/Clustering/Hierarchical.hs", "max_forks_repo_name": "zitkat/clustering", "max_forks_repo_head_hexsha": "69dc90ae776e118f4212355850e7c34287dad832", "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.5737704918, "max_line_length": 107, "alphanum_fraction": 0.5043630017, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4524913262658595}}
{"text": "-- |\n-- Module      :  HashedExpression.Interp\n-- Copyright   :  (c) OCA 2020\n-- License     :  MIT (see the LICENSE file)\n-- Maintainer  :  anandc@mcmaster.ca\n-- Stability   :  provisional\n-- Portability :  unportable\n--\n-- Evaluate expressions. Mainly useful for testings.\nmodule HashedExpression.Interp where\n\nimport Data.Array\nimport Data.Complex hiding (conjugate)\nimport qualified Data.List as List\nimport qualified Data.Map as Map\nimport HashedExpression.Internal.Base hiding ((**))\nimport HashedExpression.Internal.Node\nimport HashedExpression.Utils\nimport HashedExpression.Value\n\ndata InterpValue\n  = VR Double\n  | VC (Complex Double)\n  | V1DR (Array Int Double)\n  | V1DC (Array Int (Complex Double))\n  | V2DR (Array (Int, Int) Double)\n  | V2DC (Array (Int, Int) (Complex Double))\n  | V3DR (Array (Int, Int, Int) Double)\n  | V3DC (Array (Int, Int, Int) (Complex Double))\n  deriving (Show, Eq)\n\neval :: IsExpression e => ValMap -> e -> InterpValue\neval valMap e =\n  let (mp, nID) = asRawExpr e\n      (shape, et, op) = retrieveNode nID mp\n      eval' :: NodeID -> InterpValue\n      eval' x = eval valMap (mp, x)\n      -------------------------------------------------------------------------------\n      -- Partial helper functions\n      constructR :: [Double] -> InterpValue\n      constructR vs = case (shape, vs) of\n        ([], [v]) -> VR v\n        ([size], _) -> V1DR $ listArray (0, size - 1) vs\n        ([size1, size2], _) -> V2DR $ listArray ((0, 0), (size1 - 1, size2 - 1)) vs\n        ([size1, size2, size3], _) -> V3DR $ listArray ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1)) vs\n      extractR :: InterpValue -> [Double]\n      extractR val = case val of\n        VR v -> [v]\n        V1DR arr -> elems arr\n        V2DR arr -> elems arr\n        V3DR arr -> elems arr\n      constructC :: [Complex Double] -> InterpValue\n      constructC vs = case (shape, vs) of\n        ([], [v]) -> VC v\n        ([size], _) -> V1DC $ listArray (0, size - 1) vs\n        ([size1, size2], _) -> V2DC $ listArray ((0, 0), (size1 - 1, size2 - 1)) vs\n        ([size1, size2, size3], _) -> V3DC $ listArray ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1)) vs\n      extractC :: InterpValue -> [Complex Double]\n      extractC val = case val of\n        VC v -> [v]\n        V1DC arr -> elems arr\n        V2DC arr -> elems arr\n        V3DC arr -> elems arr\n      unaryR op arg = arg |> eval' |> extractR |> map op |> constructR\n      unaryC op arg = arg |> eval' |> extractC |> map op |> constructC\n      binaryR op arg1 arg2 = zipWith op (extractR $ eval' arg1) (extractR $ eval' arg2) |> constructR\n      binaryC op arg1 arg2 = zipWith op (extractC $ eval' arg1) (extractC $ eval' arg2) |> constructC\n   in case op of\n        Var name -> case (shape, Map.lookup name valMap) of\n          ([], Just (VScalar val)) -> VR val\n          ([_], Just (V1D arr)) -> V1DR arr\n          ([_, _], Just (V2D arr)) -> V2DR arr\n          ([_, _, _], Just (V3D arr)) -> V3DR arr\n        Param name -> case (shape, Map.lookup name valMap) of\n          ([], Just (VScalar val)) -> VR val\n          ([_], Just (V1D arr)) -> V1DR arr\n          ([_, _], Just (V2D arr)) -> V2DR arr\n          ([_, _, _], Just (V3D arr)) -> V3DR arr\n        Const v -> constructR $ replicate (product shape) v\n        Sum args\n          | et == R -> args |> map eval' |> map extractR |> foldl1 (zipWith (+)) |> constructR\n          | et == C -> args |> map eval' |> map extractC |> foldl1 (zipWith (+)) |> constructC\n        Mul args\n          | et == R -> args |> map eval' |> map extractR |> foldl1 (zipWith (*)) |> constructR\n          | et == C -> args |> map eval' |> map extractC |> foldl1 (zipWith (*)) |> constructC\n        Power x arg\n          | et == R -> unaryR (** fromIntegral x) arg\n          | et == C -> unaryC (** fromIntegral x) arg\n        Neg arg\n          | et == R -> unaryR negate arg\n          | et == C -> unaryC negate arg\n        Scale arg1 arg2 -> case (retrieveElementType arg1 mp, retrieveElementType arg2 mp) of\n          (R, R) ->\n            let VR v = eval' arg1\n             in unaryR (v *) arg2\n          (R, C) ->\n            let VR v = eval' arg1\n             in unaryC ((v :+ 0) *) arg2\n          (C, C) ->\n            let VC v = eval' arg1\n             in unaryC (v *) arg2\n        Div arg1 arg2\n          | et == R -> binaryR (/) arg1 arg2\n          | et == C -> binaryC (/) arg1 arg2\n        -------------------------------------------------------------------------------\n        Sqrt arg -> unaryR sqrt arg\n        Sin arg -> unaryR sin arg\n        Cos arg -> unaryR cos arg\n        Tan arg -> unaryR tan arg\n        Exp arg -> unaryR exp arg\n        Log arg -> unaryR log arg\n        Sinh arg -> unaryR sinh arg\n        Cosh arg -> unaryR cosh arg\n        Tanh arg -> unaryR tanh arg\n        Asin arg -> unaryR asin arg\n        Acos arg -> unaryR acos arg\n        Atan arg -> unaryR atan arg\n        Asinh arg -> unaryR asinh arg\n        Acosh arg -> unaryR acosh arg\n        Atanh arg -> unaryR atanh arg\n        -------------------------------------------------------------------------------\n        RealImag arg1 arg2 ->\n          let re = extractR (eval' arg1)\n              im = extractR (eval' arg2)\n           in constructC $ zipWith (:+) re im\n        RealPart arg -> extractC (eval' arg) |> map realPart |> constructR\n        ImagPart arg -> extractC (eval' arg) |> map imagPart |> constructR\n        Conjugate arg -> unaryC conjugate arg\n        -------------------------------------------------------------------------------\n        InnerProd arg1 arg2\n          | et == R ->\n            let x = extractR (eval' arg1)\n                y = extractR (eval' arg2)\n             in VR $ sum $ zipWith (*) x y\n          | et == C ->\n            let x = extractC (eval' arg1)\n                y = extractC (eval' arg2)\n             in VC $ sum $ zipWith (*) x (map conjugate y)\n        Piecewise marks conditionArg branchArgs\n          | et == R ->\n            let condition = extractR (eval' conditionArg)\n                branches = map (extractR . eval') branchArgs\n             in constructR $ zipWith (chooseBranch marks) condition (List.transpose branches)\n          | et == C ->\n            let condition = extractR (eval' conditionArg)\n                branches = map (extractC . eval') branchArgs\n             in constructC $ zipWith (chooseBranch marks) condition (List.transpose branches)\n        Rotate rotateAmount arg\n          | et == R -> case (rotateAmount, shape) of\n            ([amount], [size]) ->\n              let V1DR arr = eval' arg\n               in V1DR $ rotate1D size amount arr\n            ([amount1, amount2], [size1, size2]) ->\n              let V2DR arr = eval' arg\n               in V2DR $ rotate2D (size1, size2) (amount1, amount2) arr\n            ([amount1, amount2, amount3], [size1, size2, size3]) ->\n              let V3DR arr = eval' arg\n               in V3DR $ rotate3D (size1, size2, size3) (amount1, amount2, amount3) arr\n          | et == C -> case (rotateAmount, shape) of\n            ([amount], [size]) ->\n              let V1DC arr = eval' arg\n               in V1DC $ rotate1D size amount arr\n            ([amount1, amount2], [size1, size2]) ->\n              let V2DC arr = eval' arg\n               in V2DC $ rotate2D (size1, size2) (amount1, amount2) arr\n            ([amount1, amount2, amount3], [size1, size2, size3]) ->\n              let V3DC arr = eval' arg\n               in V3DC $ rotate3D (size1, size2, size3) (amount1, amount2, amount3) arr\n        FT arg -> case shape of\n          [] -> eval' arg\n          [size] ->\n            let V1DC arr = eval' arg\n             in V1DC $ fourierTransform1D FT_FORWARD size arr\n          [size1, size2] ->\n            let V2DC arr = eval' arg\n             in V2DC $ fourierTransform2D FT_FORWARD (size1, size2) arr\n          [size1, size2, size3] ->\n            let V3DC arr = eval' arg\n             in V3DC $ fourierTransform3D FT_FORWARD (size1, size2, size3) arr\n        IFT arg -> case shape of\n          [] -> eval' arg\n          [size] ->\n            let V1DC arr = eval' arg\n             in V1DC $ fourierTransform1D FT_BACKWARD size arr\n          [size1, size2] ->\n            let V2DC arr = eval' arg\n             in V2DC $ fourierTransform2D FT_BACKWARD (size1, size2) arr\n          [size1, size2, size3] ->\n            let V3DC arr = eval' arg\n             in V3DC $ fourierTransform3D FT_BACKWARD (size1, size2, size3) arr\n        Project dss arg -> case shape of\n          [] -> case (retrieveShape arg mp, dss) of\n            ([size], [At i]) -> case eval' arg of\n              V1DR base -> VR $ base ! i\n              V1DC base -> VC $ base ! i\n            ([size1, size2], [At i, At j]) -> case eval' arg of\n              V2DR base -> VR $ base ! (i, j)\n              V2DC base -> VC $ base ! (i, j)\n            ([size1, size2, size3], [At i, At j, At k]) -> case eval' arg of\n              V3DR base -> VR $ base ! (i, j, k)\n              V3DC base -> VC $ base ! (i, j, k)\n          [size] -> case (retrieveShape arg mp, dss) of\n            ([bSize], [ds]) -> case eval' arg of\n              V1DR base -> V1DR $ listArray (0, size - 1) [base ! i | i <- mkIndices ds bSize]\n              V1DC base -> V1DC $ listArray (0, size - 1) [base ! i | i <- mkIndices ds bSize]\n            ([bSize1, bSize2], [ds1, ds2]) -> case eval' arg of\n              V2DR base ->\n                V1DR $\n                  listArray (0, size - 1) $\n                    [base ! (i, j) | i <- mkIndices ds1 bSize1, j <- mkIndices ds2 bSize2]\n              V2DC base ->\n                V1DC $\n                  listArray (0, size - 1) $\n                    [base ! (i, j) | i <- mkIndices ds1 bSize1, j <- mkIndices ds2 bSize2]\n            ([bSize1, bSize2, bSize3], [ds1, ds2, ds3]) -> case eval' arg of\n              V3DR base ->\n                V1DR $\n                  listArray (0, size - 1) $\n                    [base ! (i, j, k) | i <- mkIndices ds1 bSize1, j <- mkIndices ds2 bSize2, k <- mkIndices ds3 bSize3]\n              V3DC base ->\n                V1DC $\n                  listArray (0, size - 1) $\n                    [base ! (i, j, k) | i <- mkIndices ds1 bSize1, j <- mkIndices ds2 bSize2, k <- mkIndices ds3 bSize3]\n          [size1, size2] -> case (retrieveShape arg mp, dss) of\n            ([bSize1, bSize2], [ds1, ds2]) -> case eval' arg of\n              V2DR base ->\n                V2DR $\n                  listArray\n                    ((0, 0), (size1 - 1, size2 - 1))\n                    [base ! (i, j) | i <- mkIndices ds1 bSize1, j <- mkIndices ds2 bSize2]\n              V2DC base ->\n                V2DC $\n                  listArray\n                    ((0, 0), (size1 - 1, size2 - 1))\n                    [base ! (i, j) | i <- mkIndices ds1 bSize1, j <- mkIndices ds2 bSize2]\n            ([bSize1, bSize2, bSize3], [ds1, ds2, ds3]) -> case eval' arg of\n              V3DR base ->\n                V2DR $\n                  listArray\n                    ((0, 0), (size1 - 1, size2 - 1))\n                    [base ! (i, j, k) | i <- mkIndices ds1 bSize1, j <- mkIndices ds2 bSize2, k <- mkIndices ds3 bSize3]\n              V3DC base ->\n                V2DC $\n                  listArray\n                    ((0, 0), (size1 - 1, size2 - 1))\n                    [base ! (i, j, k) | i <- mkIndices ds1 bSize1, j <- mkIndices ds2 bSize2, k <- mkIndices ds3 bSize3]\n          [size1, size2, size3] -> case (retrieveShape arg mp, dss) of\n            ([bSize1, bSize2, bSize3], [ds1, ds2, ds3]) -> case eval' arg of\n              V3DR base ->\n                V3DR $\n                  listArray\n                    ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n                    [base ! (i, j, k) | i <- mkIndices ds1 bSize1, j <- mkIndices ds2 bSize2, k <- mkIndices ds3 bSize3]\n              V3DC base ->\n                V3DC $\n                  listArray\n                    ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n                    [base ! (i, j, k) | i <- mkIndices ds1 bSize1, j <- mkIndices ds2 bSize2, k <- mkIndices ds3 bSize3]\n        Inject dss subArg baseArg\n          | et == R ->\n            let injectingElements = extractR $ eval' subArg\n             in case (eval' baseArg, dss, shape) of\n                  (V1DR base, [ds], [size]) ->\n                    let indices = mkIndices ds size\n                     in V1DR $ base // zip indices injectingElements\n                  (V2DR base, [ds1, ds2], [size1, size2]) ->\n                    let indices = [(i, j) | i <- mkIndices ds1 size1, j <- mkIndices ds2 size2]\n                     in V2DR $ base // zip indices injectingElements\n                  (V3DR base, [ds1, ds2, ds3], [size1, size2, size3]) ->\n                    let indices = [(i, j, k) | i <- mkIndices ds1 size1, j <- mkIndices ds2 size2, k <- mkIndices ds3 size3]\n                     in V3DR $ base // zip indices injectingElements\n          | et == C ->\n            let injectingElements = extractC $ eval' subArg\n             in case (eval' baseArg, dss, shape) of\n                  (V1DC base, [ds], [size]) ->\n                    let indices = mkIndices ds size\n                     in V1DC $ base // zip indices injectingElements\n                  (V2DC base, [ds1, ds2], [size1, size2]) ->\n                    let indices = [(i, j) | i <- mkIndices ds1 size1, j <- mkIndices ds2 size2]\n                     in V2DC $ base // zip indices injectingElements\n                  (V3DC base, [ds1, ds2, ds3], [size1, size2, size3]) ->\n                    let indices = [(i, j, k) | i <- mkIndices ds1 size1, j <- mkIndices ds2 size2, k <- mkIndices ds3 size3]\n                     in V3DC $ base // zip indices injectingElements\n        MatMul arg1 arg2\n          | et == R ->\n            case (shape, retrieveShape arg1 mp, retrieveShape arg2 mp) of\n              ([_m], [m, _n], [n]) ->\n                let V2DR x = eval' arg1\n                    V1DR y = eval' arg2\n                 in V1DR $\n                      listArray\n                        (0, m - 1)\n                        [ sum [(x ! (i, j)) * (y ! j) | j <- [0 .. n - 1]]\n                          | i <- [0 .. m - 1]\n                        ]\n              ([_m, _p], [m, _n], [n, p]) ->\n                let V2DR x = eval' arg1\n                    V2DR y = eval' arg2\n                 in V2DR $\n                      listArray\n                        ((0, 0), (m - 1, p - 1))\n                        [ sum [(x ! (i, k)) * (y ! (k, j)) | k <- [0 .. n - 1]]\n                          | i <- [0 .. m - 1],\n                            j <- [0 .. p - 1]\n                        ]\n          | et == C ->\n            case (shape, retrieveShape arg1 mp, retrieveShape arg2 mp) of\n              ([_m], [m, _n], [n]) ->\n                let V2DC x = eval' arg1\n                    V1DC y = eval' arg2\n                 in V1DC $\n                      listArray\n                        (0, m - 1)\n                        [ sum [(x ! (i, j)) * (y ! j) | j <- [0 .. n - 1]]\n                          | i <- [0 .. m - 1]\n                        ]\n              ([_m, _p], [m, _n], [n, p]) ->\n                let V2DC x = eval' arg1\n                    V2DC y = eval' arg2\n                 in V2DC $\n                      listArray\n                        ((0, 0), (m - 1, p - 1))\n                        [ sum [(x ! (i, k)) * (y ! (k, j)) | k <- [0 .. n - 1]]\n                          | i <- [0 .. m - 1],\n                            j <- [0 .. p - 1]\n                        ]\n        Transpose arg\n          | et == R ->\n            case (retrieveShape arg mp, shape) of\n              -- ([m], [1, _m]) ->\n              --   let V1DR x = eval' arg\n              --    in V2DR $ listArray ((0, 0), (1, m - 1)) $ elems x\n              ([m, n], [_n, _m]) ->\n                let V2DR x = eval' arg\n                 in V2DR $ listArray ((0, 0), (n - 1, m - 1)) [x ! (j, i) | i <- [0 .. n - 1], j <- [0 .. m - 1]]\n          | et == C ->\n            case (retrieveShape arg mp, shape) of\n              -- ([m], [1, _m]) ->\n              --   let V1DC x = eval' arg\n              --    in V2DC $ listArray ((0, 0), (1, m - 1)) $ elems x\n              ([m, n], [_n, _m]) ->\n                let V2DC x = eval' arg\n                 in V2DC $ listArray ((0, 0), (n - 1, m - 1)) [x ! (j, i) | i <- [0 .. n - 1], j <- [0 .. m - 1]]\n        Coerce _ arg\n          | et == R -> constructR . extractR $ eval' arg\n          | et == C -> constructC . extractC $ eval' arg\n        node -> error $ show node\n\nzipWithA :: Ix x => (a -> b -> c) -> Array x a -> Array x b -> Array x c\nzipWithA f xs ys = listArray (bounds xs) $ zipWith f (elems xs) (elems ys)\n\n-- | Choose branch base on condition value.\n-- In Decision tree, there are 2 possible outcomes, Head and Tail.\n-- The decision of being Head or Tail is made based on the the condition value.\nchooseBranch :: [Double] -> Double -> [a] -> a\nchooseBranch marks val branches\n  | val < head marks = head branches\n  | otherwise =\n    snd . last . filter ((val >=) . fst) $ zip marks (tail branches)\n\n-- NOTE: `mod` in Haskell with negative number, e.g, (-5) `mod` 3 = 1\n\n-- | One dimension rotation.\n--   The elemnts falling off of the length of the 1D array will appear at the beginning of the array\nrotate1D ::\n  -- | Size of the input array\n  Int ->\n  -- | amount of rotation\n  Int ->\n  -- | Input array\n  Array Int a ->\n  -- | Rotated array\n  Array Int a\nrotate1D size amount arr =\n  listArray\n    (0, size - 1)\n    [arr ! ((i - amount) `mod` size) | i <- [0 .. size - 1]]\n\n-- | Two dimension rotation.\n--   The elements falling off of the length of the 2D array will appear at the beginning of the each row or column of the array\nrotate2D ::\n  -- | Size of the 2d input array\n  (Int, Int) ->\n  -- | amount of rotation for 2d array\n  (Int, Int) ->\n  -- | Input 2d array\n  Array (Int, Int) a ->\n  -- | Rotated 2d array\n  Array (Int, Int) a\nrotate2D (size1, size2) (amount1, amount2) arr =\n  listArray\n    ((0, 0), (size1 - 1, size2 - 1))\n    [ arr ! ((i - amount1) `mod` size1, (j - amount2) `mod` size2)\n      | i <- [0 .. size1 - 1],\n        j <- [0 .. size2 - 1]\n    ]\n\n-- | Three dimension rotation\nrotate3D ::\n  -- | Size of 3d input array\n  (Int, Int, Int) ->\n  -- | Amount of Rotation for 3d array\n  (Int, Int, Int) ->\n  -- | Input 3d array\n  Array (Int, Int, Int) a ->\n  -- | Rotated 3d array\n  Array (Int, Int, Int) a\nrotate3D (size1, size2, size3) (amount1, amount2, amount3) arr =\n  listArray\n    ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n    [ arr\n        ! ( (i - amount1) `mod` size1,\n            (j - amount2) `mod` size2,\n            (k - amount3) `mod` size3\n          )\n      | i <- [0 .. size1 - 1],\n        j <- [0 .. size2 - 1],\n        k <- [0 .. size3 - 1]\n    ]\n\ndata FTMode = FT_FORWARD | FT_BACKWARD deriving (Eq, Ord)\n\n-- | Fourier Transform in 1D.\n--  Frequency is just in one dimension.\n--  Consider a real-valued function, S(x),\n--  that is integrable on an interval of P, which will be the period of the Fourier series.\n--  number of cycles is n.\n--  length of cycle is P/n, and frequency is n/P.\n--  so for input i the frequency is (2*pi*i*n)/P\nfourierTransform1D ::\n  FTMode -> Int -> Array Int (Complex Double) -> Array Int (Complex Double)\nfourierTransform1D mode size arr =\n  listArray (0, size - 1) [computeX i | i <- [0 .. size - 1]]\n  where\n    s = if mode == FT_BACKWARD then fromIntegral size else 1\n    computeX i = (sum $ zipWithA (*) arr (fourierBasis i)) / s\n    fourierBasis i =\n      let frequency n = (2 * pi * fromIntegral (i * n) / fromIntegral size) * (if mode == FT_BACKWARD then -1 else 1)\n       in listArray\n            (0, size - 1)\n            [ cos (frequency n) :+ (- sin (frequency n))\n              | n <- [0 .. size - 1]\n            ]\n\n-- | Fourier Transform in 2D\n--  the frequency should be calculated in 2D\n--  Consider a real-valued function, S(x),\n--  that is integrable on an interval of P, which will be the period of the Fourier series.\n--  numbber of cycles is n.\n--  length of cycle is P/n, and frequency is n/P.\n--  so for input i the frequency is (2*pi*i*n)/P\n--  the frequency should be calculated in both dimensions for i and j\nfourierTransform2D ::\n  FTMode ->\n  (Int, Int) ->\n  Array (Int, Int) (Complex Double) ->\n  Array (Int, Int) (Complex Double)\nfourierTransform2D mode (size1, size2) arr =\n  listArray\n    ((0, 0), (size1 - 1, size2 - 1))\n    [computeX i j | i <- [0 .. size1 - 1], j <- [0 .. size2 - 1]]\n  where\n    s = if mode == FT_BACKWARD then fromIntegral (size1 * size2) else 1\n    computeX i j = (sum $ zipWithA (*) arr (fourierBasis i j)) / s\n    fourierBasis i j =\n      let frequency m n =\n            ( 2 * pi * fromIntegral (i * m) / fromIntegral size1\n                + 2 * pi * fromIntegral (j * n) / fromIntegral size2\n            )\n              * (if mode == FT_BACKWARD then -1 else 1)\n       in listArray\n            ((0, 0), (size1 - 1, size2 - 1))\n            [ cos (frequency m n) :+ (- sin (frequency m n))\n              | m <- [0 .. size1 - 1],\n                n <- [0 .. size2 - 1]\n            ]\n\n-- | Fourier Transform in 3D\n--   the frequency should be calculated in 3D\n--   Consider a real-valued function, S(x),\n--   that is integrable on an interval of P, which will be the period of the Fourier series.\n--   numbber of cycles is n.\n--   length of cycle is P/n, and frequency is n/P.\n--   so for input i the frequency is (2*pi*i*n)/P\n--   the frequency should be calculated for all dimensions, i , j , k\nfourierTransform3D ::\n  FTMode ->\n  (Int, Int, Int) ->\n  Array (Int, Int, Int) (Complex Double) ->\n  Array (Int, Int, Int) (Complex Double)\nfourierTransform3D mode (size1, size2, size3) arr =\n  listArray\n    ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n    [ computeX i j k\n      | i <- [0 .. size1 - 1],\n        j <- [0 .. size2 - 1],\n        k <- [0 .. size3 - 1]\n    ]\n  where\n    s = if mode == FT_BACKWARD then fromIntegral (size1 * size2) else 1\n    computeX i j k = (sum $ zipWithA (*) arr (fourierBasis i j k)) / s\n    fourierBasis i j k =\n      let frequency m n p =\n            ( 2 * pi * fromIntegral (i * m) / fromIntegral size1\n                + 2 * pi * fromIntegral (j * n) / fromIntegral size2\n                + 2 * pi * fromIntegral (k * p) / fromIntegral size3\n            )\n              * (if mode == FT_BACKWARD then -1 else 1)\n       in listArray\n            ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n            [ cos (frequency m n p) :+ (- sin (frequency m n p))\n              | m <- [0 .. size1 - 1],\n                n <- [0 .. size2 - 1],\n                p <- [0 .. size3 - 1]\n            ]\n", "meta": {"hexsha": "dfca585e26d6c50eaf028a73fe31db888f770b3b", "size": 22585, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HashedExpression/Interp.hs", "max_stars_repo_name": "McMasterU/HashedExpression", "max_stars_repo_head_hexsha": "5372372e445913c5d26a41d350da46f836751bf7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43, "max_stars_repo_stars_event_min_datetime": "2020-06-02T00:45:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T07:11:11.000Z", "max_issues_repo_path": "src/HashedExpression/Interp.hs", "max_issues_repo_name": "McMasterU/HashedExpression", "max_issues_repo_head_hexsha": "5372372e445913c5d26a41d350da46f836751bf7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-06-02T00:47:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-15T02:00:36.000Z", "max_forks_repo_path": "src/HashedExpression/Interp.hs", "max_forks_repo_name": "McMasterU/HashedExpression", "max_forks_repo_head_hexsha": "5372372e445913c5d26a41d350da46f836751bf7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-01T14:40:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T13:47:47.000Z", "avg_line_length": 43.769379845, "max_line_length": 127, "alphanum_fraction": 0.4832410892, "num_tokens": 6829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.45201911349856766}}
{"text": "{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DeriveGeneric         #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE OverloadedStrings     #-}\n{-# LANGUAGE OverloadedLabels      #-}\n\nmodule Grenade.Dynamic.Layers.FullyConnected \n  ( SpecFullyConnected (..)\n  , specFullyConnected\n  , fullyConnected\n  ) where\n\nimport           Data.Proxy\nimport           Data.Reflection                     (reifyNat)\nimport           Data.Singletons\nimport           Data.Singletons.Prelude.Num         ((%*))\nimport           Data.Singletons.TypeLits            hiding (natVal)\nimport           GHC.TypeLits\n\nimport           Numeric.LinearAlgebra.Static        hiding (build, toRows, (&),\n                                                      (|||), size)\n\nimport           Grenade.Core\nimport           Grenade.Utils.ListStore\nimport           Grenade.Dynamic.Internal.Build\nimport           Grenade.Dynamic.Specification\nimport           Grenade.Layers.FullyConnected\n\n-------------------- DynamicNetwork instance --------------------\n\ninstance (KnownNat i, KnownNat o) => FromDynamicLayer (FullyConnected i o) where\n  fromDynamicLayer _ _ _ = SpecNetLayer $ SpecFullyConnected (natVal (Proxy :: Proxy i)) (natVal (Proxy :: Proxy o))\n\ninstance ToDynamicLayer SpecFullyConnected where\n  toDynamicLayer wInit gen (SpecFullyConnected nrI nrO) =\n    reifyNat nrI $ \\(pxInp :: (KnownNat i) => Proxy i) ->\n      reifyNat nrO $ \\(pxOut :: (KnownNat o') => Proxy o') ->\n        case singByProxy pxInp %* singByProxy pxOut of\n          SNat -> do\n            (layer :: FullyConnected i o') <- randomFullyConnected wInit gen\n            return $ SpecLayer layer (sing :: Sing ('D1 i)) (sing :: Sing ('D1 o'))\n\n-- | Make a specification of a fully connected layer (see Grenade.Dynamic.Build for a user-interface to specifications).\nspecFullyConnected :: Integer -> Integer -> SpecNet\nspecFullyConnected nrI nrO = SpecNetLayer $ SpecFullyConnected nrI nrO\n\n\n-- | A Fully-connected layer with input dimensions as given in last output layer and output dimensions specified. 1D only!\nfullyConnected :: Integer -> BuildM ()\nfullyConnected rows = do\n  (inRows, _, _) <- buildRequireLastLayerOut Is1D\n  buildAddSpec (SpecNetLayer $ SpecFullyConnected inRows rows)\n  buildSetLastLayer (rows, 1, 1)\n\n\n-------------------- GNum instances --------------------\n\ninstance (KnownNat i, KnownNat o) => GNum (FullyConnected i o) where\n  s |* FullyConnected w store = FullyConnected (s |* w) (s |* store)\n  FullyConnected w1 store1 |+ FullyConnected w2 store2 = FullyConnected (w1 |+ w2) (store1 |+ store2)\n  gFromRational r = FullyConnected (gFromRational r) mkListStore\n\ninstance (KnownNat i, KnownNat o) => GNum (FullyConnected' i o) where\n  s |* FullyConnected' b w = FullyConnected' (dvmap (fromRational s *) b) (dmmap (fromRational s *) w)\n  FullyConnected' b1 w1 |+ FullyConnected' b2 w2 = FullyConnected' (b1 + b2) (w1 + w2)\n  gFromRational r = FullyConnected' (fromRational r) (fromRational r)\n", "meta": {"hexsha": "93be6b4c7e9edf08c532367a35921dde8b63b9f5", "size": 3289, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Dynamic/Layers/FullyConnected.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Dynamic/Layers/FullyConnected.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Dynamic/Layers/FullyConnected.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8533333333, "max_line_length": 122, "alphanum_fraction": 0.6391000304, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.45199487384552794}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TemplateHaskell #-}\n-- | a variation on <http://hackage.haskell.org/package/hmatrix-syntax>,\n-- which constructs a matrix which has dimensions stored.\nmodule Numeric.LinearAlgebra.Dimensional.DK.QuasiQuotes\n(\n  vec,\n  vecShape,\n  mat,\n) where\n\nimport Language.Haskell.TH\n\nimport Language.Haskell.TH as TH\nimport Language.Haskell.TH.Quote as TH\nimport Language.Haskell.TH.Syntax as TH\nimport Language.Haskell.TH.Quote\nimport Language.Haskell.Meta.Parse as Meta\n\nimport Numeric.Units.Dimensional.DK (Quantity, Dimension, DLength, DMass)\nimport Numeric.LinearAlgebra.Dimensional.DK.Internal (DimMat(..), vecSingleton, vecCons, fromRowVector, vconcat, vconcat', vconcat'')\nimport Numeric.LinearAlgebra.Dimensional.DK.Shapes\n\nimport Data.List.Split\n\n\nvec = QuasiQuoter {\n  quoteExp = parseVectorExp,\n  quotePat = error \"vec\",\n  quoteDec = error \"vec\",\n  quoteType = parseVectorType\n}\n\nvecShape = QuasiQuoter {\n  quoteExp = error \"vecShape\",\n  quotePat = error \"vecShape\",\n  quoteDec = error \"vecShape\",\n  quoteType = parseVectorShapeType\n}\n\nmat = QuasiQuoter {\n  quoteExp = parseMatrixExp,\n  quotePat = error \"mat\",\n  quoteDec = error \"mat\",\n  quoteType = error \"mat\"\n}\n\nparseMatrixExp :: String -> Q Exp\nparseMatrixExp s = let rs = fmap parseVectorExp $ splitSemicolonList s\n                    in makeMatrixExp rs\n\nparseVectorExp :: String -> Q Exp\nparseVectorExp s = let qs = fmap parseQuantityExp $ splitCommaList s\n                    in makeVectorExp qs\n\nparseQuantityExp :: String -> Q Exp\nparseQuantityExp s = do\n                       case (Meta.parseExp s) of\n                         Left err -> fail $ show err\n                         Right e -> return e\n\nparseVectorType :: String -> Q Type\nparseVectorType s = [t| DimMat $(parseVectorShapeType s) |]\n\nparseVectorShapeType :: String -> Q Type\nparseVectorShapeType s = let dimTypes = fmap parseDimensionType $ splitCommaList s\n                          in makeVectorShapeType dimTypes\n\nparseDimensionType :: String -> Q Type\nparseDimensionType s = do\n                          case (Meta.parseType s) of\n                            Left err -> fail $ show err\n                            Right t -> return t\n\nmakeMatrixExp :: [Q Exp] -> Q Exp\nmakeMatrixExp [] = fail \"Empty matrices not permitted.\"\nmakeMatrixExp [e] = [| fromRowVector $(e) |]\n--makeMatrixExp (e:[e2]) = [| vconcat'' $(e) $(e2) |]\nmakeMatrixExp (e:es) = [| vconcat' $(e) $(makeMatrixExp es) |]\n\nmakeVectorExp :: [Q Exp] -> Q Exp\nmakeVectorExp [] = fail \"Empty vectors not permitted.\"\nmakeVectorExp [e] = [| vecSingleton $(e) |]\nmakeVectorExp (e:es) = [| vecCons $(e) $(makeVectorExp es) |]\n\nmakeVectorShapeType :: [Q Type] -> Q Type\nmakeVectorShapeType (d : ds) = [t| 'VectorShape $(d) $(makeTypeLevelList ds) |]\nmakeVectorShapeType _ = fail \"Empty vectors not permitted.\"\n\nmakeTypeLevelList :: [Q Type] -> Q Type\nmakeTypeLevelList (t : ts) = [t| $(t) ': $(makeTypeLevelList ts) |]\nmakeTypeLevelList [] = [t| '[] |]\n\nsplitCommaList :: String -> [String]\nsplitCommaList = splitOn \",\"\n\nsplitSemicolonList :: String -> [String]\nsplitSemicolonList = splitOn \";\"\n", "meta": {"hexsha": "52a43820b8f72083b59085f922e88c14fde9b3fb", "size": 3154, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/Dimensional/DK/QuasiQuotes.hs", "max_stars_repo_name": "dmcclean/dimensional-dk-linalg", "max_stars_repo_head_hexsha": "acc39b98d5422b5f5f405efc504edd472c368924", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-02-01T09:15:12.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-01T09:15:12.000Z", "max_issues_repo_path": "src/Numeric/LinearAlgebra/Dimensional/DK/QuasiQuotes.hs", "max_issues_repo_name": "dmcclean/dimensional-dk-linalg", "max_issues_repo_head_hexsha": "acc39b98d5422b5f5f405efc504edd472c368924", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LinearAlgebra/Dimensional/DK/QuasiQuotes.hs", "max_forks_repo_name": "dmcclean/dimensional-dk-linalg", "max_forks_repo_head_hexsha": "acc39b98d5422b5f5f405efc504edd472c368924", "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.54, "max_line_length": 133, "alphanum_fraction": 0.6715282181, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45197368108095753}}
{"text": "{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE CPP #-}\n\n\nmodule NQS.SR\n  ( -- * Stochastic Reconfiguration\n    --\n    -- Globally, the SR algorithm looks more or less like this\n    --\n    -- @\n    --     for n in {0,...,maxIter - 1} do\n    --         (F, \u2202\u03c8) <- sample \u03c8\n    --         S <- covariance\u207d\u207f\u207e \u2202\u03c8\n    --         \u03b4 <- (S + \u03bb\u207d\u207f\u207e)\u207b\u00b9 F\n    --         \u03c8 <- \u03c8 - learningRate * \u03b4\n    --     done\n    -- @\n\n    -- * AXPY\n    -- * Sampling\n    -- * Constructing S\n    -- * Solving S\n    sr\n  , IterInfo(..)\n  , HasIter(..)\n  , HasSampler(..)\n  , HasSolver(..)\n  , HasMoments(..)\n  , HasForceNorm(..)\n  ) where\n\nimport           Prelude                 hiding ( zipWith\n                                                , zipWithM\n                                                , map\n                                                , mapM\n                                                )\n\nimport           GHC.Generics                   ( Generic )\n\nimport           Debug.Trace\nimport           Control.Exception              ( assert )\nimport           Control.Monad.Identity         ( Identity(..) )\nimport           Control.Monad.ST\nimport           System.IO.Unsafe               ( unsafePerformIO )\nimport           Foreign.Storable\nimport           Foreign.ForeignPtr\nimport           Data.Vector.Storable           ( Vector )\nimport qualified Data.Vector.Storable          as V\nimport           Data.Vector.Storable.Mutable   ( MVector )\nimport qualified Data.Vector.Storable.Mutable  as MV\nimport qualified Data.Vector.Unboxed\n\nimport           Data.Singletons\nimport           Data.Complex\nimport           Data.Semigroup                 ( (<>) )\nimport           Control.Monad                  ( (>=>) )\nimport           Control.Monad.Primitive\n\nimport           Control.DeepSeq\nimport           System.CPUTime\nimport Data.Aeson\n\nimport qualified NQS.CG                        as CG\nimport           NQS.CG                         ( Operator )\nimport           NQS.Rbm (Rbm(..))\nimport           NQS.Rbm.Mutable\nimport           NQS.Internal.BLAS\nimport           NQS.Internal.LAPACK\nimport           NQS.Internal.Types\nimport           NQS.Internal.Hamiltonian\nimport           NQS.Internal.Sampling\nimport           NQS.Internal.Rbm (unsafeFreezeRbm)\n\nimport           Lens.Micro\nimport           Lens.Micro.TH\nimport           Lens.Micro.Extras\n\nimport           GHC.Float                      ( int2Float )\n\n\nimport           Data.Aeson\nimport qualified Data.ByteString.Lazy.Char8     as BS\n\n-- | In Stochastic Reconfiguration we only ever deal with 'Direct' vectors.\ntype V = MDenseVector 'Direct\n\n-- | A shorter name for dense matrices.\ntype M orient s a = MDenseMatrix orient s a\n\n\ndata SolverStats = SolverStats\n  { _solverStatsIters :: {-# UNPACK #-}!Int\n  , _solverStatsErr   :: {-# UNPACK #-}!\u211d\n  , _solverStatsTime  :: {-# UNPACK #-}!Double\n  }\n\nmakeFields ''SolverStats\n\ninstance ToJSON SolverStats where\n  toJSON stats =\n    object [ \"iters\" .= (stats ^. iters)\n           , \"error\" .= (stats ^. err)\n           , \"time\"  .= (stats ^. time)\n           ]\n  toEncoding stats =\n    pairs $ \"iters\" .= (stats ^. iters)\n         <> \"error\" .= (stats ^. err)\n         <> \"time\"  .= (stats ^. time)\n\ninstance FromJSON SolverStats where\n  parseJSON = withObject \"SolverStats\" $ \\v ->\n    SolverStats <$> v .: \"iters\"\n                <*> v .: \"error\"\n                <*> v .: \"time\"\n\n\ndata SamplerStats = SamplerStats\n  { _samplerStatsMoments  :: {-# UNPACK #-}!(Vector \u2102)\n  , _samplerStatsStdDev   :: !(Maybe \u211d)\n  , _samplerStatsDim      :: {-# UNPACK #-}!Int\n  , _samplerStatsTime     :: {-# UNPACK #-}!Double\n  }\n\nmakeFields ''SamplerStats\n\ninstance ToJSON SamplerStats where\n  toJSON stats =\n    object [ \"moments\" .= (stats ^. moments)\n           , \"stddev\"  .= (stats ^. stdDev)\n           , \"dim\"     .= (stats ^. dim)\n           , \"time\"    .= (stats ^. time)\n           ]\n  toEncoding stats =\n    pairs $ \"moments\" .= (stats ^. moments)\n         <> \"stddev\"  .= (stats ^. stdDev)\n         <> \"dim\"     .= (stats ^. dim)\n         <> \"time\"    .= (stats ^. time)\n\ninstance FromJSON SamplerStats where\n  parseJSON = withObject \"SamplerStats\" $ \\v ->\n    SamplerStats <$> v .: \"moments\"\n                 <*> v .: \"stddev\"\n                 <*> v .: \"dim\"\n                 <*> v .: \"time\"\n\ndata IterInfo = IterInfo\n  { _iterInfoIter      :: {-# UNPACK #-}!Int\n  , _iterInfoState     :: Rbm\n  , _iterInfoSampler   :: !SamplerStats\n  , _iterInfoSolver    :: !SolverStats\n  , _iterInfoForceNorm :: {-# UNPACK #-}!\u211d\n  , _iterInfoDeltaNorm :: {-# UNPACK #-}!\u211d\n  }\n\nmakeFields ''IterInfo\n\ninstance ToJSON IterInfo where\n  toJSON stats =\n    object [ \"iter\"      .= (stats ^. iter)\n           , \"state\"     .= (stats ^. state)\n           , \"sampler\"   .= (stats ^. sampler)\n           , \"solver\"    .= (stats ^. solver)\n           , \"forceNorm\" .= (stats ^. forceNorm)\n           , \"deltaNorm\" .= (stats ^. deltaNorm)\n           ]\n  toEncoding stats =\n    pairs $ \"iter\"      .= (stats ^. iter)\n         <> \"state\"     .= (stats ^. state)\n         <> \"sampler\"   .= (stats ^. sampler)\n         <> \"solver\"    .= (stats ^. solver)\n         <> \"forceNorm\" .= (stats ^. forceNorm)\n         <> \"deltaNorm\" .= (stats ^. deltaNorm)\n\ninstance FromJSON IterInfo where\n  parseJSON = withObject \"IterInfo\" $ \\v ->\n    IterInfo <$> v .: \"iter\"\n             <*> v .: \"state\"\n             <*> v .: \"sampler\"\n             <*> v .: \"solver\"\n             <*> v .: \"forceNorm\"\n             <*> v .: \"deltaNorm\"\n\n-- AXPY\n-- -----------------------------------------------------------------------------\n\ntype AxpyFun v m = \u2102 -> V (PrimState m) \u2102 -> v (PrimState m) -> m ()\n\n-- | \\(Y \\leftarrow \\alpha X + Y\\) for 'Column' matrices.\naxpyMatrix\n  :: (PrimMonad m, Storable a, AXPY (MDenseVector 'Direct) a)\n  => a\n  -> MDenseVector 'Direct (PrimState m) a\n  -> MDenseMatrix 'Column (PrimState m) a\n  -> m ()\naxpyMatrix !\u03b1 !x !y@(MDenseMatrix !rows !cols !stride !buff) =\n  assert (rows * cols == x ^. dim) $ loop 0\n where\n  getX !i = slice (i * rows) rows x\n  getY !i = unsafeColumn i y\n  loop !i | i < cols  = axpy \u03b1 (getX i) (getY i) >> loop (i + 1)\n          | otherwise = return ()\n\n-- | Performs @y <- \u03b1x + y@ where @x@ is a vector and @y@ -- an RBM.\naxpyRbm :: AxpyFun MRbm IO\naxpyRbm \u03b1 x y =\n  let n = sizeVisible y\n      m = sizeHidden y\n  in  assert (x ^. dim == size y) $ do\n        withVisible y $ \\a -> do\n          axpy \u03b1 (slice 0 n x) a\n          -- unsafeFreeze a >>= \\a' -> print (a' ^. buffer)\n        withHidden y $ \\b -> do\n          axpy \u03b1 (slice n m x) b\n          -- unsafeFreeze b >>= \\b' -> print (b' ^. buffer)\n        withWeights y $ \\w -> do\n          axpyMatrix \u03b1 (slice (n + m) (n * m) x) w\n          -- unsafeFreeze w >>= \\w' -> print (w' ^. buffer)\n\n-- Monte-Carlo sampling\n-- -----------------------------------------------------------------------------\n\n-- | Sampling\ntype SampleFun v m\n  = v (PrimState m)\n -> V (PrimState m) \u2102\n -> M 'Row (PrimState m) \u2102\n -> m SamplerStats\n\n-- | Monte-Carlo sampling an RBM\nsampleRbm :: MCConfig -> Hamiltonian -> SampleFun MRbm IO\nsampleRbm config hamiltonian = doSample\n where\n  doSample rbm force derivatives = do\n    t1                    <- getCPUTime\n    moments               <- MV.new 2\n    (dimension, variance) <- sampleGradients config\n                                             hamiltonian\n                                             rbm\n                                             moments\n                                             force\n                                             derivatives\n    t2 <- getCPUTime\n    V.unsafeFreeze moments >>= \\moments' -> return\n      (SamplerStats moments'\n                    (sqrt <$> variance)\n                    dimension\n                    (fromIntegral (t2 - t1) * 1.0E-12)\n      )\n\ntype SolveFun wrapper m\n  = wrapper -- ^ S\n -> V (PrimState m) \u2102 -- ^ b\n -> V (PrimState m) \u2102 -- ^ x\n -> m SolverStats\n\ntype MakeSFun wrapper m = Int -> M 'Row (PrimState m) \u2102 -> m wrapper\n\n-- | Sparse representation of the @S@ matrix.\ndata SMatrix s =\n  SMatrix !(M 'Row s \u2102) -- ^ Derivatives (O - \u2329O\u232a)\n          !(V s \u2102) -- ^ Workspace of size #steps.\n          !(Maybe \u2102) -- ^ Regulariser \u03bb\n\nmakeS :: PrimMonad m => Maybe (Int -> \u2102) -> MakeSFun (SMatrix (PrimState m)) m\nmakeS regulariser i gradients = do\n  workspace <- newDenseVector (gradients ^. dim ^. _1)\n  return $! SMatrix gradients workspace ((\\f -> f i) <$> regulariser)\n\nmakeS' :: PrimMonad m => Maybe (Int -> \u2102) -> MakeSFun (M 'Row (PrimState m) \u2102) m\nmakeS' regulariser i gradients = do\n  let (steps, params) = gradients ^. dim\n  s <- newDenseMatrix params params\n  herk MatUpper ConjTranspose (1 / int2Float steps) gradients 0 s\n  herk MatLower ConjTranspose (1 / int2Float steps) gradients 0 s\n  case regulariser of\n    Just f  -> do\n      one <- MDenseVector @'Direct params 0 <$> V.unsafeThaw (V.singleton 1)\n      axpy (f i) one (MDenseVector @'Direct params (s ^. stride + 1) (s ^. buffer))\n    Nothing -> return ()\n  return $! s\n\nopS :: PrimMonad m => SMatrix (PrimState m) -> Operator m \u2102\nopS (SMatrix o temp \u03bb) x out = do\n  let scale = (1 / int2Float (o ^. dim ^. _1)) :+ 0\n  gemv NoTranspose 1 o x 0 temp\n  case \u03bb of\n    (Just \u03bb') -> copy x out >> gemv ConjTranspose scale o temp \u03bb' out\n    Nothing   -> gemv ConjTranspose scale o temp 0 out\n\n{-\nsolveS :: PrimMonad m => CGConfig \u211d -> SolveFun (MDenseMatrix 'Row (PrimState m) \u2102) m\nsolveS (CGConfig maxIter tol) = doSolve\n  where doSolve s b x = do\n          let operator = \\input output -> gemv NoTranspose 1 s input 0 output\n          zero <- MDenseVector @'Direct (b ^. dim) 0 <$> V.unsafeThaw (V.singleton 0)\n          copy zero x\n          !answer <- CG.cg maxIter tol operator b x\n          trace (show answer) (return ())\n-}\n\nsolveS :: CGConfig \u211d -> SolveFun (SMatrix RealWorld) IO\nsolveS (CGConfig maxIter tol) = doSolve\n where\n  doSolve s b x = do\n    t1  <- getCPUTime\n    one <- MDenseVector @ 'Direct (b ^. dim) 0 <$> V.unsafeThaw (V.singleton 0)\n    copy one x\n    (iters, err) <- CG.cg maxIter tol (opS s) b x\n    t2           <- getCPUTime\n    return $! SolverStats iters err (fromIntegral (t2 - t1) * 1.0E-12)\n\nsolveS' :: SolveFun (MDenseMatrix 'Row RealWorld \u2102) IO\nsolveS' s b x = assert (x ^. stride == 1) $ do\n  t1 <- getCPUTime\n  copy b x\n  cgelsd s (MDenseMatrix (b ^. dim) 1 1 (x ^. buffer)) (-1.0)\n  t2 <- getCPUTime\n  return $! SolverStats (-1) (-1.0) (fromIntegral (t2 - t1) * 1.0E-12)\n\n\ntype Stepper v m a = v (PrimState m) a -> m ()\n\n\nnumberSteps :: (Int, Int, Int) -> Int\nnumberSteps (low, high, step) = (high - low - 1) `div` step + 1\n\nnewWorkspace :: PrimMonad m => Int -> Int -> m (DenseWorkspace (PrimState m) \u2102)\nnewWorkspace nParams nSteps =\n  DenseWorkspace\n    <$> newDenseVector nParams\n    <*> newDenseMatrix nSteps nParams\n    <*> newDenseVector nParams\n\nsr\n  :: SRConfig \u2102\n  -> Hamiltonian\n  -> MRbm (PrimState IO)\n  -> (IterInfo -> IO ())\n  -> IO ()\nsr config hamiltonian \u03c8 process = newWorkspace nParams nSteps\n  >>= \\w -> loop w 0\n where\n  nParams  = size \u03c8\n  nSteps   = config ^. mc ^. runs * numberSteps (config ^. mc ^. steps)\n  doAxpy   = axpyRbm\n  doMakeS  = makeS (config ^. regulariser)\n  doSolveS = solveS (config ^. cg)\n  doSample = sampleRbm (config ^. mc) hamiltonian\n  loop !w@(DenseWorkspace f grad \u03b4) !i\n    | i >= config ^. maxIter = return ()\n    | otherwise = do\n      mcStats <- doSample \u03c8 f grad\n      fNorm   <- nrm2 f\n      cgStats <- doMakeS i grad >>= \\s -> doSolveS s f \u03b4\n      \u03b4Norm   <- nrm2 \u03b4\n      unsafeFreezeRbm \u03c8\n        >>= \\\u03c8' ->\n              let stats = IterInfo i \u03c8' mcStats cgStats fNorm \u03b4Norm\n              in  process stats\n      doAxpy (-(config ^. rate) i) \u03b4 \u03c8\n      loop w (i + 1)\n\n\n", "meta": {"hexsha": "18f8a912127965fbc3ca596c0a3bced6a20768cc", "size": 12225, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NQS/SR.hs", "max_stars_repo_name": "twesterhout/tcm-swarm", "max_stars_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NQS/SR.hs", "max_issues_repo_name": "twesterhout/tcm-swarm", "max_issues_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NQS/SR.hs", "max_forks_repo_name": "twesterhout/tcm-swarm", "max_forks_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1710526316, "max_line_length": 85, "alphanum_fraction": 0.5362781186, "num_tokens": 3462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4519535347080347}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Numeric.HHT.Internal.FFT (\n    fft\n  , ifft\n  ) where\n\nimport           Data.Complex\nimport qualified Data.Array.CArray         as CA\nimport qualified Data.Array.IArray         as IA\nimport qualified Data.Ix                   as Ix\nimport qualified Data.Vector.Generic       as VG\nimport qualified Data.Vector.Generic.Sized as SVG\nimport qualified Foreign.Storable          as FS\nimport qualified Math.FFT                  as FFT\nimport qualified Math.FFT.Base             as FFT\n\nfft :: (FFT.FFTWReal a, VG.Vector v (Complex a))\n    => SVG.Vector v n (Complex a)\n    -> SVG.Vector v n (Complex a)\nfft = SVG.withVectorUnsafe $\n        fromCA\n      . FFT.dft\n      . toCA\n\nifft\n    :: (FFT.FFTWReal a, VG.Vector v (Complex a))\n    => SVG.Vector v n (Complex a)\n    -> SVG.Vector v n (Complex a)\nifft = SVG.withVectorUnsafe $\n        fromCA\n      . FFT.idft\n      . toCA\n\nfromCA\n    :: (FS.Storable a, VG.Vector v (Complex a))\n    => CA.CArray Int (Complex a)\n    -> v (Complex a)\nfromCA v = VG.generate (Ix.rangeSize (IA.bounds v)) (v IA.!)\n\ntoCA\n    :: (FS.Storable a, VG.Vector v (Complex a))\n    => v (Complex a)\n    -> CA.CArray Int (Complex a)\ntoCA v = IA.listArray (0, VG.length v - 1) (VG.toList v)\n", "meta": {"hexsha": "f15848e9747707d412be8e32919930587a45d1f0", "size": 1247, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/HHT/Internal/FFT.hs", "max_stars_repo_name": "mstksg/emd", "max_stars_repo_head_hexsha": "bc02724d861a8932b72a97745542a62dd19071d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-07-11T08:16:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T07:49:50.000Z", "max_issues_repo_path": "src/Numeric/HHT/Internal/FFT.hs", "max_issues_repo_name": "mstksg/emd", "max_issues_repo_head_hexsha": "bc02724d861a8932b72a97745542a62dd19071d0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-07-26T09:36:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-22T09:24:58.000Z", "max_forks_repo_path": "src/Numeric/HHT/Internal/FFT.hs", "max_forks_repo_name": "mstksg/emd", "max_forks_repo_head_hexsha": "bc02724d861a8932b72a97745542a62dd19071d0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1086956522, "max_line_length": 60, "alphanum_fraction": 0.6094627105, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4519535235611916}}
{"text": "{-|\nModule: MachineLearning.Utils\nDescription: Utils\nCopyright: (c) Alexander Ignatyev, 2016\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n\nVarious helpful utilities.\n-}\n\nmodule MachineLearning.Utils\n(\n  reduceByRowsV\n  , reduceByColumnsV\n  , reduceByRows\n  , reduceByColumns\n  , sumByRows\n  , sumByColumns\n  , listOfTuplesToList\n)\n\nwhere\n\n  \nimport MachineLearning.Types (R, Vector, Matrix)\nimport qualified Data.Vector.Storable as V\nimport qualified Numeric.LinearAlgebra as LA\n\n\nreduceByRowsV :: (Vector -> R) -> Matrix -> Vector\nreduceByRowsV f = LA.vector . map f . LA.toRows\n\n\nreduceByColumnsV :: (Vector -> R) -> Matrix -> Vector\nreduceByColumnsV f = LA.vector . map f . LA.toColumns\n\n\nreduceByRows :: (Vector -> R) -> Matrix -> Matrix\nreduceByRows f = LA.asColumn . reduceByRowsV f\n\n\nreduceByColumns :: (Vector -> R) -> Matrix -> Matrix\nreduceByColumns f = LA.asRow . reduceByColumnsV f\n\n\nsumByColumns :: Matrix -> Matrix\nsumByColumns = reduceByColumns V.sum\n\n\nsumByRows :: Matrix -> Matrix\nsumByRows = reduceByRows V.sum\n\n\n-- | Converts list of tuples into list.\nlistOfTuplesToList :: [(a, a)] -> [a]\nlistOfTuplesToList [] = []\nlistOfTuplesToList ((a, b):xs) = a : b : listOfTuplesToList xs\n", "meta": {"hexsha": "ada7a8bfeb3b8b1eb612b1f228c53da844faaf2f", "size": 1212, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/Utils.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "src/MachineLearning/Utils.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "src/MachineLearning/Utils.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 20.5423728814, "max_line_length": 62, "alphanum_fraction": 0.7252475248, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.4518111738140916}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule Statistics.Test.Internal (\n    rank\n  , rankUnsorted  \n  , splitByTags  \n  ) where\n\nimport Data.Ord\nimport           Data.Vector.Generic           ((!))\nimport qualified Data.Vector.Generic         as G\nimport qualified Data.Vector.Generic.Mutable as M\nimport Statistics.Function\n\n\n-- Private data type for unfolding\ndata Rank v a = Rank {\n      rankCnt :: {-# UNPACK #-} !Int        -- Number of ranks to return\n    , rankVal :: {-# UNPACK #-} !Double     -- Rank to return\n    , rankNum :: {-# UNPACK #-} !Double     -- Current rank\n    , rankVec :: v a                        -- Remaining vector\n    }\n\n-- | Calculate rank of every element of sample. In case of ties ranks\n--   are averaged. Sample should be already sorted in ascending order.\n--\n--   Rank is index of element in the sample, numeration starts from 1.\n--   In case of ties average of ranks of equal elements is assigned\n--   to each\n--\n-- >>> rank (==) (fromList [10,20,30::Int])\n-- > fromList [1.0,2.0,3.0]\n--\n-- >>> rank (==) (fromList [10,10,10,30::Int])\n-- > fromList [2.0,2.0,2.0,4.0]\nrank :: (G.Vector v a, G.Vector v Double)\n     => (a -> a -> Bool)        -- ^ Equivalence relation\n     -> v a                     -- ^ Vector to rank\n     -> v Double\nrank eq vec = G.unfoldr go (Rank 0 (-1) 1 vec)\n  where\n    go (Rank 0 _ r v)\n      | G.null v  = Nothing\n      | otherwise =\n          case G.length h of\n            1 -> Just (r, Rank 0 0 (r+1) rest)\n            n -> go Rank { rankCnt = n\n                         , rankVal = 0.5 * (r*2 + fromIntegral (n-1))\n                         , rankNum = r + fromIntegral n\n                         , rankVec = rest\n                         }\n          where\n            (h,rest) = G.span (eq $ G.head v) v\n    go (Rank n val r v) = Just (val, Rank (n-1) val r v)\n{-# INLINE rank #-}\n\n-- | Compute rank of every element of vector. Unlike rank it doesn't\n--   require sample to be sorted.\nrankUnsorted :: ( Ord a\n                , G.Vector v a\n                , G.Vector v Int\n                , G.Vector v Double\n                , G.Vector v (Int, a)\n                )\n             => v a\n             -> v Double\nrankUnsorted xs = G.create $ do\n    -- Put ranks into their original positions\n    -- NOTE: backpermute will do wrong thing\n    vec <- M.new n\n    for 0 n $ \\i ->\n      M.unsafeWrite vec (index ! i) (ranks ! i)\n    return vec\n  where\n    n = G.length xs\n    -- Calculate ranks for sorted array\n    ranks = rank (==) sorted\n    -- Sort vector and retain original indices of elements\n    (index, sorted)\n      = G.unzip\n      $ sortBy (comparing snd)\n      $ indexed xs\n{-# INLINE rankUnsorted #-}\n\n\n-- | Split tagged vector\nsplitByTags :: (G.Vector v a, G.Vector v (Bool,a)) => v (Bool,a) -> (v a, v a)\nsplitByTags vs = (G.map snd a, G.map snd b)\n  where\n    (a,b) = G.unstablePartition fst vs\n{-# INLINE splitByTags #-}\n", "meta": {"hexsha": "225cfdaf282642aa6d81e4a7fda19a10d3d6338b", "size": 2894, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Test/Internal.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:39:40.000Z", "max_issues_repo_path": "Statistics/Test/Internal.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T14:21:32.000Z", "max_forks_repo_path": "Statistics/Test/Internal.hs", "max_forks_repo_name": "infinity0/statistics", "max_forks_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2015-02-13T00:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:19:16.000Z", "avg_line_length": 31.8021978022, "max_line_length": 78, "alphanum_fraction": 0.5400829302, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.45164112567814274}}
{"text": "module HaskovSpec where\n\nimport Haskov (fromList,imap,hmatrix,walk,walkFrom,steady,steadyState,statesI)\n\nimport System.Random\nimport Test.Hspec\nimport qualified Data.Set as Set\nimport qualified Numeric.LinearAlgebra.Data as Dat\nimport Data.List (intercalate)\n\nimport           Control.Monad (unless,when)\n\ntestTransitions =\n  [ ((\"A\", \"B\"), 0.3)\n  , ((\"A\", \"A\"), 0.7)\n  , ((\"B\", \"C\"), 1.0)\n  , ((\"C\", \"A\"), 1.0)\n  ]\n\n\nspec :: Spec\nspec =\n\n  describe \"haskov\" $ do\n\n--    describe \"steadyState\" $ do\n--\n--      it \"should always contain positive numbers\" $ do\n--        let\n--          transitions = [ ((\"A\", \"B\"), 1.0), ((\"B\", \"C\"), 1.0), ((\"C\", \"A\"), 1.0)]\n--          haskov = fromList transitions\n--          s = steadyState haskov\n--        --mapM (\\(s, p) -> s `shouldSatisfy` (> 0))\n--        print s\n--        True `shouldBe` True\n\n    describe \"A haskov walk\" $ do\n\n    -- could use quickcheck for better tests\n\n      it \"should never do invalid transitions when transitions are ordered\" $ do\n        let\n          transitions = [((\"A\", \"B\"), 1.0), ((\"B\", \"C\"), 1.0), ((\"C\", \"A\"), 1.0)]\n          valid = map fst transitions\n          markov = fromList transitions\n        gen <- getStdGen\n        res <- walk 10 markov gen\n        expectOnlyValidTransitions transitions res\n\n      it \"should never do invalid transitions when transtions are not ordered\" $ do\n        let\n          transitions = [ ((\"C\", \"A\"), 1.0), ((\"A\", \"B\"), 1.0), ((\"B\", \"C\"), 1.0)]\n          valid = map fst transitions\n          haskov = fromList transitions\n        gen <- getStdGen\n        res <- walk 3 haskov gen\n        expectOnlyValidTransitions transitions res\n\n\n    describe \"A haskov walkFrom\" $ do\n\n      it \"starts with the head initial state\" $ do\n        let\n          markov = fromList testTransitions\n        gen <- getStdGen\n        res <- walkFrom \"B\" 10 markov gen\n        head res `shouldBe` \"B\"\n\n      it \"just some test\" $ do\n        let\n          markov = fromList testTransitions\n          index = imap markov\n          matrix = hmatrix markov\n          start = \"A\"\n        gen <- getStdGen\n        res <- walkFrom \"B\" 10 markov gen\n        --putStrLn $ \"index: \" ++ ( show index)\n        --putStrLn $ \"matrix: \" ++ ( show matrix)\n        --putStrLn $ \"result from \" ++ start ++ \": \" ++ ( show res)\n        return ()\n\n\n\n\nexpectTrue :: HasCallStack => String -> Bool -> Expectation\nexpectTrue msg b = unless b (expectationFailure msg)\n\nexpectOnlyValidTransitions transitions actual = do\n  let\n    valid = map fst transitions\n    actualTransitions = zip actual (drop 1 actual)\n    actualUnique = Set.fromList actualTransitions\n    invalid = Set.filter (\\e -> not $ elem e valid) actualUnique\n    len = length invalid\n    invalidMsg inv = \"invalid transitions encountered: \" ++ ( intercalate \", \" (Set.toList (Set.map (\\(a,b) -> a ++ \"->\" ++ b) inv)))\n  expectTrue (invalidMsg invalid) $ len == 0\n", "meta": {"hexsha": "9dcdfceaeeae2f943d69c6d96bcfb24a3cce564f", "size": 2899, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/HaskovSpec.hs", "max_stars_repo_name": "francisdb/haskov", "max_stars_repo_head_hexsha": "5fe128335238d5a838676fc2396cb85cda56e258", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-04-25T20:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-19T13:14:24.000Z", "max_issues_repo_path": "test/HaskovSpec.hs", "max_issues_repo_name": "francisdb/haskov", "max_issues_repo_head_hexsha": "5fe128335238d5a838676fc2396cb85cda56e258", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-08-22T07:26:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-12T19:03:37.000Z", "max_forks_repo_path": "test/HaskovSpec.hs", "max_forks_repo_name": "francisdb/haskov", "max_forks_repo_head_hexsha": "5fe128335238d5a838676fc2396cb85cda56e258", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-09-26T22:04:01.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-26T22:04:01.000Z", "avg_line_length": 29.8865979381, "max_line_length": 133, "alphanum_fraction": 0.5784753363, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.45164110802856094}}
{"text": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n-- |\n-- Module    : Statistics.Transform\n-- Copyright : (c) 2011 Bryan O'Sullivan\n-- License   : BSD3\n--\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : portable\n--\n-- Fourier-related transformations of mathematical functions.\n--\n-- These functions are written for simplicity and correctness, not\n-- speed.  If you need a fast FFT implementation for your application,\n-- you should strongly consider using a library of FFTW bindings\n-- instead.\n\nmodule Transform ( kPointFFT ) where\n\nimport Control.Monad         (when)\nimport Control.Monad.ST      (ST)\nimport Data.Bits             (shiftL, shiftR, (.&.), (.|.))\nimport Data.Complex          (Complex(..), conjugate, realPart, magnitude)\nimport qualified Data.Vector.Generic         as G\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Unboxed         as U\n\n\ntype CD = Complex Float\n\n-- | /O(log n)/ Compute the logarithm in base 2 of the given value.\nlog2 :: Int -> Int\nlog2 v0\n    | v0 <= 0   = error \"Statistics.Math.log2: invalid input\"\n    | otherwise = go 5 0 v0\n  where\n    go !i !r !v | i == -1        = r\n                | v .&. b i /= 0 = let si = U.unsafeIndex sv i\n                                   in go (i-1) (r .|. si) (v `shiftR` si)\n                | otherwise      = go (i-1) r v\n    b = U.unsafeIndex bv\n    !bv = U.fromList [0x2, 0xc, 0xf0, 0xff00, 0xffff0000, 0xffffffff00000000]\n    !sv = U.fromList [1,2,4,8,16,32]\n\nhanning :: Float -> Float -> Float\nhanning m n = 0.5 - 0.5 * cos(2 * pi * n / m)\n\nkPointFFT :: U.Vector Float -> U.Vector Float\nkPointFFT !vec = mag where\n    winlen = realToFrac $ G.length vec - 1\n    window = G.imap (\\i x -> ((hanning winlen (realToFrac i)) * x) :+ 0.0) vec\n    fftres = halfFFT window\n    mag    = G.map (\\x -> let val = 20 * (logBase 10 $ magnitude x) in if(val < 0) then 0 else val) fftres\n\n\nhalfFFT :: U.Vector CD -> U.Vector CD\nhalfFFT !vec = U.take (U.length vec `div` 2) (fft vec)\n\n-- | Radix-2 decimation-in-time fast Fourier transform.\nfft :: U.Vector CD -> U.Vector CD\nfft !v = G.create $ do\n          mv <- G.thaw v\n          mfft mv\n          return mv\n\nmfft :: (M.MVector v CD) => v s CD -> ST s ()\nmfft vec\n    | 1 `shiftL` m /= len = error \"Statistics.Transform.fft: bad vector size\"\n    | otherwise           = bitReverse 0 0\n where\n  bitReverse i j | i == len-1 = stage 0 1\n                 | otherwise  = do\n    when (i < j) $ M.swap vec i j\n    let inner k l | k <= l    = inner (k `shiftR` 1) (l-k)\n                  | otherwise = bitReverse (i+1) (l+k)\n    inner (len `shiftR` 1) j\n  stage l !l1 | l == m    = return ()\n              | otherwise = do\n    let !l2 = l1 `shiftL` 1\n        !e  = -6.283185307179586/fromIntegral l2\n        flight j !a | j == l1   = stage (l+1) l2\n                    | otherwise = do\n          let butterfly i | i >= len  = flight (j+1) (a+e)\n                          | otherwise = do\n                let i1 = i + l1\n                xi1 :+ yi1 <- M.read vec i1\n                let !c = cos a\n                    !s = sin a\n                    d  = (c*xi1 - s*yi1) :+ (s*xi1 + c*yi1)\n                ci <- M.read vec i\n                M.write vec i1 (ci - d)\n                M.write vec i (ci + d)\n                butterfly (i+l2)\n          butterfly j\n    flight 0 0\n  len = M.length vec\n  m   = log2 len\n\nfi :: Int -> CD\nfi = fromIntegral\n\nhalve :: Int -> Int\nhalve = (`shiftR` 1)", "meta": {"hexsha": "58b2f8dba67f77c91c86ad3f6c6322c1b243b49e", "size": 3457, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/Transform.hs", "max_stars_repo_name": "matthewleon/haskell-portaudio", "max_stars_repo_head_hexsha": "9bd13b7001370c47b303d6f90c0d710ae08415c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-01-26T01:34:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-30T11:10:30.000Z", "max_issues_repo_path": "examples/Transform.hs", "max_issues_repo_name": "matthewleon/haskell-portaudio", "max_issues_repo_head_hexsha": "9bd13b7001370c47b303d6f90c0d710ae08415c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-10-08T18:04:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-09T02:26:03.000Z", "max_forks_repo_path": "examples/Transform.hs", "max_forks_repo_name": "matthewleon/haskell-portaudio", "max_forks_repo_head_hexsha": "9bd13b7001370c47b303d6f90c0d710ae08415c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-01-13T21:24:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T01:35:15.000Z", "avg_line_length": 33.5631067961, "max_line_length": 106, "alphanum_fraction": 0.5475846109, "num_tokens": 1066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.45143930001467464}}
{"text": "{-# language OverloadedStrings #-}\nmodule Report (generateReports) where\n\nimport Graphics.Vega.VegaLite hiding (Sum)\nimport Prelude hiding (filter, lookup, repeat)\nimport Data.Monoid (Sum(..))\nimport Numeric.LinearAlgebra ((#>), Vector, toList)\nimport Data.Maybe\n\nimport GA\nimport Fitness \n\n-- | Plot the evolution of average fitness along the generations\nplotEvo :: [Double] -> IO ()\nplotEvo avgs = \n  let gens = [1.0 .. fromIntegral (length avgs)] \n      plotData = dataFromColumns []\n               . dataColumn \"generation\" (Numbers gens)\n               . dataColumn \"avg\" (Numbers avgs)\n               $ []\n      enc      = encoding\n               . position X [ PName \"generation\", PmType Quantitative]\n               . position Y [ PName \"avg\", PmType Quantitative]\n               $ []\n  in  toHtmlFile \"evolution.html\" $ toVegaLite [ plotData, mark Line [], enc, height 800, width 600 ]\n\nplotPoly :: [[Double]] -> Vector Double -> Solution (Poly n) -> IO ()\nplotPoly xss ys sol = \n  let x0 = map head xss\n      zss = decode xss (map _getPoly $ _chromo sol)\n      ysHat = toList $ zss #> (fromJust . _coeffs) sol\n      ys'   = toList ys\n      clusters = replicate (length x0) \"poly\" ++ replicate (length x0) \"real\"\n      plotData = dataFromColumns []\n               . dataColumn \"x0\" (Numbers $ x0 ++ x0)\n               . dataColumn \"y\" (Numbers $ ysHat ++ ys')\n               . dataColumn \"Cluster\" (Strings clusters)\n               $ []\n      enc      = encoding\n               . position X [ PName \"x0\", PmType Quantitative]\n               . position Y [ PName \"y\", PmType Quantitative]\n               . color [ MName \"Cluster\", MmType Nominal ]\n               $ []\n  in  toHtmlFile \"poly.html\" $ toVegaLite [ plotData, mark Line [], enc, height 800, width 600 ]\n\ngenerateReports :: [[Double]] -> Vector Double -> [Double] -> Solution (Poly n) -> IO ()\ngenerateReports xss ys avgs best = do plotEvo avgs\n                                      plotPoly xss ys best\n", "meta": {"hexsha": "f04dc0534be36c37fcd6cd03a5996a0b38505e5e", "size": 1973, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Report.hs", "max_stars_repo_name": "folivetti/gapoly", "max_stars_repo_head_hexsha": "a0e2b727f046b1284353f56699b0459ed536155d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-06T11:25:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T11:25:13.000Z", "max_issues_repo_path": "src/Report.hs", "max_issues_repo_name": "folivetti/gapoly", "max_issues_repo_head_hexsha": "a0e2b727f046b1284353f56699b0459ed536155d", "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/Report.hs", "max_forks_repo_name": "folivetti/gapoly", "max_forks_repo_head_hexsha": "a0e2b727f046b1284353f56699b0459ed536155d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2653061224, "max_line_length": 101, "alphanum_fraction": 0.5843892549, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.4514226193118302}}
{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE TemplateHaskell     #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE KindSignatures      #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\nmodule Test.Grenade.Layers.PadCrop where\n\nimport           Grenade\n\nimport           Hedgehog\n\nimport           Numeric.LinearAlgebra.Static ( norm_Inf )\n\nimport           Test.Hedgehog.Hmatrix\n\nprop_pad_crop :: Property\nprop_pad_crop =\n  let net :: Network '[Pad 2 3 4 6, Crop 2 3 4 6] '[ 'D3 7 9 5, 'D3 16 15 5, 'D3 7 9 5 ]\n      net = Pad :~> Crop :~> NNil\n  in  property $\n    forAll genOfShape >>= \\(d :: S ('D3 7 9 5)) ->\n      let (tapes, res)  = runForwards  net d\n          (_    , grad) = runBackwards net tapes d\n      in  do assert $ d ~~~ res\n             assert $ grad ~~~ d\n\nprop_pad_crop_2d :: Property\nprop_pad_crop_2d =\n  let net :: Network '[Pad 2 3 4 6, Crop 2 3 4 6] '[ 'D2 7 9, 'D2 16 15, 'D2 7 9 ]\n      net = Pad :~> Crop :~> NNil\n  in  property $\n    forAll genOfShape >>= \\(d :: S ('D2 7 9)) ->\n      let (tapes, res)  = runForwards  net d\n          (_    , grad) = runBackwards net tapes d\n      in  do assert $ d ~~~ res\n             assert $ grad ~~~ d\n\n(~~~) :: S x -> S x -> Bool\n(S1D x) ~~~ (S1D y) = norm_Inf (x - y) < 0.00001\n(S2D x) ~~~ (S2D y) = norm_Inf (x - y) < 0.00001\n(S3D x) ~~~ (S3D y) = norm_Inf (x - y) < 0.00001\n\n\ntests :: IO Bool\ntests = checkParallel $$(discover)\n", "meta": {"hexsha": "f39768235a5a0d36c031a9f655c56e2dea193132", "size": 1521, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Layers/PadCrop.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1527, "max_stars_repo_stars_event_min_datetime": "2016-06-23T13:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T05:22:00.000Z", "max_issues_repo_path": "test/Test/Grenade/Layers/PadCrop.hs", "max_issues_repo_name": "Alien-Inc/grenade", "max_issues_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 69, "max_issues_repo_issues_event_min_datetime": "2016-06-27T22:16:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-20T17:50:09.000Z", "max_forks_repo_path": "test/Test/Grenade/Layers/PadCrop.hs", "max_forks_repo_name": "Alien-Inc/grenade", "max_forks_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2016-06-28T02:24:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:17:29.000Z", "avg_line_length": 30.42, "max_line_length": 88, "alphanum_fraction": 0.5391190007, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.45142261513192133}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults -fno-warn-orphans -Wall #-}\n\nmodule Main where\n\nimport Algebra.Bridge.Singular\nimport Algebra.Field.Prime\nimport Algebra.Prelude.Core\nimport Cases\nimport Control.Monad (void)\nimport qualified Data.Text as T\nimport qualified Data.Vector.Unboxed as V\nimport Statistics.Resampling\nimport Statistics.Resampling.Bootstrap\nimport Statistics.Types\nimport qualified System.Random.MWC as Rand\nimport Prelude (read)\n\nbenchIdeal :: IsSingularPolynomial poly => Text -> Ideal poly -> IO Double\nbenchIdeal fun i =\n  fmap ((/ 1000) . read . T.unpack) $\n    singular $\n      toProg fun i\n\ntoProg :: (SingularOrder (Arity poly) (MOrder poly), SingularCoeff (Coefficient poly), IsOrderedPolynomial poly) => Text -> Ideal poly -> Text\ntoProg fun i =\n  let expr = funE fun [idealE' i]\n   in prettySingular $ do\n        directC \"system(\\\"--ticks-per-sec\\\", 1000000)\"\n        void $ ringC \"R\" expr\n        declOnlyC IdealT \"G\"\n        directC \"timer=1\"\n        directC \"int t=rtimer\"\n        letC \"G\" expr\n        directC \"print(rtimer-t)\"\n        directC \"exit\"\n\nanalyse :: (IsSingularPolynomial poly) => String -> Text -> Ideal poly -> IO ()\nanalyse lab fun ideal = do\n  gen <- Rand.create\n  i2Gr <- V.replicateM 50 $ benchIdeal fun ideal\n  res <- resample gen [Mean, StdDev] 1000 i2Gr\n  let [Estimate mn (ConfInt lbmn ubmn _), Estimate dv _] =\n        bootstrapBCA cl95 i2Gr res\n  putStrLn lab\n  mapM_\n    (putStrLn . ('\\t' :))\n    [ \"Mean:\\t\" ++ show mn ++ \"(ms)\"\n    , \"MeanLB:\\t\" ++ show lbmn\n    , \"MeanUB:\\t\" ++ show ubmn\n    , \"StdDev:\\t\" ++ show dv\n    ]\n\nrunTestCases ::\n  (IsMonomialOrder n o, KnownNat n) =>\n  String ->\n  Ideal (OrderedPolynomial Rational o n) ->\n  IO ()\nrunTestCases lab i = do\n  analyse (lab ++ \" (Q, Lex, Sing(gr))\") \"groebner\" $ fmap (changeOrder Lex) i\n  analyse (lab ++ \" (Q, Lex, Sing(sba))\") \"sba\" $ fmap (changeOrder Lex) i\n  analyse (lab ++ \" (Q, Grevlex, Sing(gr))\") \"groebner\" $ fmap (changeOrder Grevlex) i\n  analyse (lab ++ \" (Q, Grevlex, Sing(sba))\") \"sba\" $ fmap (changeOrder Grevlex) i\n  analyse (lab ++ \" (F_65521, Lex, Sing(gr))\") \"groebner\" $ fmap (mapCoeff ratToF . changeOrder Lex) i\n  analyse (lab ++ \" (F_65521, Lex, Sing(sba))\") \"sba\" $ fmap (mapCoeff ratToF . changeOrder Lex) i\n  analyse (lab ++ \" (F_65521, Grevlex, Sing(gr))\") \"groebner\" $ fmap (mapCoeff ratToF . changeOrder Grevlex) i\n  analyse (lab ++ \" (F_65521, Grevlex, Sing(sba))\") \"sba\" $ fmap (mapCoeff ratToF . changeOrder Grevlex) i\n\nmain :: IO ()\nmain = do\n  runTestCases \"Cyclic-4\" $ cyclic (sNat :: SNat 4)\n  runTestCases \"Cyclic-5\" $ cyclic (sNat :: SNat 5)\n  runTestCases \"Cyclic-6\" $ cyclic (sNat :: SNat 6)\n  runTestCases \"Katsura-5\" $ katsura (sNat :: SNat 5)\n  runTestCases \"Katsura-6\" $ katsura (sNat :: SNat 6)\n  runTestCases \"Katsura-7\" $ katsura (sNat :: SNat 7)\n\nratToF :: Rational -> F 65521\nratToF = modRat'\n", "meta": {"hexsha": "5a42021299ff563068881d64308fcacf766ef72a", "size": 3272, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "halg-algorithms/bench/singular-heavy-bench.hs", "max_stars_repo_name": "hangingman/computational-algebra", "max_stars_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2015-02-09T01:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T04:37:09.000Z", "max_issues_repo_path": "halg-algorithms/bench/singular-heavy-bench.hs", "max_issues_repo_name": "hangingman/computational-algebra", "max_issues_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-09-18T16:31:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T08:28:37.000Z", "max_forks_repo_path": "halg-algorithms/bench/singular-heavy-bench.hs", "max_forks_repo_name": "hangingman/computational-algebra", "max_forks_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-12-22T16:04:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T19:35:53.000Z", "avg_line_length": 35.956043956, "max_line_length": 142, "alphanum_fraction": 0.6601466993, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4512620036758786}}
{"text": "module Main where\n-- package \u306e import\n-- CSV\u306e\u8aad\u307f\u8fbc\u307f\nimport qualified    Text.CSV                                as CSV\nimport qualified    Data.Text                               as T\nimport              Data.Attoparsec.Text                    as DAT\n-- \u7d71\u8a08\u306e\u305f\u3081\u306e\u30d1\u30c3\u30b1\u30fc\u30b8\nimport qualified    Statistics.Correlation                  as SC\n-- \u305d\u306e\u4ed6\nimport qualified    Control.Monad                           as CM\nimport qualified    Data.List                               as L\nimport qualified    Data.Vector.Unboxed                     as VU\nimport              Data.IORef\n\nmain = do\n    -- csv\u30d5\u30a1\u30a4\u30eb\u306e\u8aad\u307f\u8fbc\u307f\n    xs <- read_csv \"Data/multiTimeline.csv\"\n    -- \u30c7\u30fc\u30bf\u306e\u8868\u793a\n    print_data (L.head xs) (L.tail xs)\n    -- Header\u306e\u62bd\u51fa\n    let headers = L.map T.unpack $ L.head xs\n    -- \u5024\u306eDouble\u3078\u306e\u5909\u63db\n    let body    = L.transpose\n                $ L.map  (L.map parseDouble)\n                $ L.tail xs\n    -- \u5206\u6790\u3059\u308b\u30c7\u30fc\u30bf\u306e\u9078\u629e\n    -- x\u3068y\u306eHeader\u540d\u3092\u66f8\u304d\u63db\u3048\u3088\u3046\n    let x = column body \"AI\" headers\n    let y = column body \"Python\" headers\n    -- \u76f8\u95a2\u4fc2\u6570\u3092\u6c42\u3081\u308b\n    let res = SC.pearson\n            $ VU.zip (VU.fromList x) (VU.fromList y)\n    -- \u76f8\u95a2\u4fc2\u6570\u306e\u8868\u793a\n    putStrLn $ \"\u76f8\u95a2\u4fc2\u6570:\" ++ show res\n\n\n\n\n-- ** \u4f5c\u696d\u7528\u95a2\u6570\n-- \u5225\u306e\u30e2\u30b8\u30e5\u30fc\u30eb\u306b\u307e\u3068\u3081\u3066\u304a\u304f\u306e\u304c\u826f\u3044\u304c\u8907\u96d1\u306b\u306a\u308b\u306e\u3067\u3053\u3053\u306b\u307e\u3068\u3081\u3066\u304a\u304f\n-- | Double\u306e\u30d1\u30fc\u30b5\n{-# INLINE parseDouble #-}\nparseDouble :: T.Text -> Double\nparseDouble tx = case DAT.parseOnly DAT.double tx of\n        Right r   -> r\n        Left  l   -> error $ \"Error on parseDouble : \" ++ show l\n\n-- | \u30c7\u30fc\u30bf\u306e\u8aad\u307f\u8fbc\u307f\nread_csv :: String -> IO [[T.Text]]\nread_csv file\n    = CSV.parseCSVFromFile file >>= \\res\n    -> case res of\n        Right xs -> return $ L.map (L.map T.pack) xs\n        Left  xs -> error $ \"error on parseCSVFromFile: \" ++ show xs\n\n-- | data set \u3063\u307d\u304f\u8868\u793a\u3059\u308b\nprint_data :: (Show a)  => [T.Text] {- header -}\n                        -> [[a]]    {- body -}\n                        -> IO ()\nprint_data hs bs = do\n    let max_length  =  let hs_max = L.maximum (L.map T.length hs)\n                    in let bs_max = L.maximum\n                                  $ (flip L.map) bs\n                                  $ \\x  -> L.maximum\n                                  $ L.map (L.length . show) x\n                    in case compare hs_max bs_max  of\n                        LT -> bs_max\n                        _  -> hs_max\n\n    let bs_digit_num =  L.length (show (L.length bs))\n    putStr $ \" \" ++ L.replicate bs_digit_num ' '\n    CM.forM_ hs $ \\x -> let tx = T.unpack x\n                     in case compare (L.length tx) max_length of\n                        LT -> putStr $ tx ++ (L.replicate  (max_length -  (L.length tx)) ' ')  ++ \" \"\n                        _  -> putStr $ tx ++ \" \"\n    putStrLn \"\"\n\n    currentNum <- newIORef 0 :: IO (IORef Int)\n\n    let  total_col = L.length bs\n    case total_col  > 10 of\n        False -> CM.forM_ bs $  \\xs -> readIORef currentNum >>= \\num\n                                    -> putStr ((show num)   ++ \" \"\n                                                            ++ L.replicate\n                                                                (bs_digit_num - (L.length (show num))) ' ')\n                                    >> modifyIORef currentNum (\\x -> x + 1)\n                                    >> CM.forM_ xs  ( \\x -> let tx = show x\n                                                         in putStr  $ tx\n                                                                    ++ (L.replicate  (max_length -  (L.length tx)) ' ')\n                                                                    ++ \" \")\n                                    >> putStrLn \"\"\n        True ->  CM.forM_ bs $  \\xs -> readIORef currentNum >>= \\num\n                                    -> case (num <= 4 || (total_col - num) <= 4) of\n                                        True  -> putStr ((show num)   ++ \" \" ++ L.replicate (bs_digit_num - (L.length (show num))) ' ')\n                                              >> modifyIORef currentNum (\\x -> x + 1)\n                                              >> CM.forM_ xs  ( \\x -> let tx = show x\n                                                         in putStr  $ tx\n                                                                    ++ (L.replicate  (max_length -  (L.length tx)) ' ')\n                                                                    ++ \" \")\n                                              >> putStrLn \"\"\n                                        False -> modifyIORef currentNum (\\x -> x + 1)\n\n\n-- | header\u306b\u3088\u308b\u60c5\u5831\u306e\u629c\u304d\u51fa\u3057\ncolumn :: [[Double]] -> String -> [String] -> [Double]\ncolumn xs name hs = case (L.elemIndex name hs) of\n                    Just i  -> xs !! i\n                    Nothing -> error $ \"error at column: \" ++ name ++ \"doesn't exest.\"\n", "meta": {"hexsha": "bff2c5bf0abead6892130170ceafd7b44a3828e8", "size": 4656, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Coef.hs", "max_stars_repo_name": "yakagika/stat_hs", "max_stars_repo_head_hexsha": "8cfc9c5a04a00fc2fe0a71a9abf74aea14e05dec", "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/Coef.hs", "max_issues_repo_name": "yakagika/stat_hs", "max_issues_repo_head_hexsha": "8cfc9c5a04a00fc2fe0a71a9abf74aea14e05dec", "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/Coef.hs", "max_forks_repo_name": "yakagika/stat_hs", "max_forks_repo_head_hexsha": "8cfc9c5a04a00fc2fe0a71a9abf74aea14e05dec", "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": 42.7155963303, "max_line_length": 135, "alphanum_fraction": 0.4093642612, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4506170902755016}}
