File size: 404,942 Bytes
5697766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{"text": "{-# LANGUAGE MagicHash, CPP, UnboxedTuples, BangPatterns, FlexibleContexts #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Data.Packed.Internal.Vector\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-- Vector implementation\n--\n-----------------------------------------------------------------------------\n\nmodule Data.Packed.Internal.Vector (\n    Vector, dim,\n    fromList, toList, (|>),\n    join, (@>), safe, at, at', subVector, takesV,\n    mapVector, mapVectorWithIndex, zipVectorWith, unzipVectorWith,\n    mapVectorM, mapVectorM_, mapVectorWithIndexM, mapVectorWithIndexM_,\n    foldVector, foldVectorG, foldLoop, foldVectorWithIndex,\n    createVector, vec,\n    asComplex, asReal, float2DoubleV, double2FloatV,\n    stepF, stepD, condF, condD,\n    conjugateQ, conjugateC,\n    fwriteVector, freadVector, fprintfVector, fscanfVector,\n    cloneVector,\n    unsafeToForeignPtr,\n    unsafeFromForeignPtr,\n    unsafeWith\n) where\n\nimport Data.Packed.Internal.Common\nimport Data.Packed.Internal.Signatures\nimport Foreign.Marshal.Alloc(free)\nimport Foreign.Marshal.Array(peekArray, pokeArray, copyArray, advancePtr)\nimport Foreign.ForeignPtr(ForeignPtr, castForeignPtr)\nimport Foreign.Ptr(Ptr)\nimport Foreign.Storable(Storable, peekElemOff, pokeElemOff, sizeOf)\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Data.Complex\nimport Control.Monad(when)\nimport System.IO.Unsafe(unsafePerformIO)\n\n#if __GLASGOW_HASKELL__ >= 605\nimport GHC.ForeignPtr           (mallocPlainForeignPtrBytes)\n#else\nimport Foreign.ForeignPtr       (mallocForeignPtrBytes)\n#endif\n\nimport GHC.Base\n#if __GLASGOW_HASKELL__ < 612\nimport GHC.IOBase hiding (liftIO)\n#endif\n\nimport qualified Data.Vector.Storable as Vector\nimport Data.Vector.Storable(Vector,\n                            unsafeToForeignPtr,\n                            unsafeFromForeignPtr,\n                            unsafeWith)\n\n\n-- | Number of elements\ndim :: (Storable t) => Vector t -> Int\ndim = Vector.length\n\n\n-- C-Haskell vector adapter\n-- vec :: Adapt (CInt -> Ptr t -> r) (Vector t) r\nvec :: (Storable t) => Vector t -> (((CInt -> Ptr t -> t1) -> t1) -> IO b) -> IO b\nvec x f = unsafeWith x $ \\p -> do\n    let v g = do\n        g (fi $ dim x) p\n    f v\n{-# INLINE vec #-}\n\n\n-- allocates memory for a new vector\ncreateVector :: Storable a => Int -> IO (Vector a)\ncreateVector n = do\n    when (n <= 0) $ error (\"trying to createVector of dim \"++show n)\n    fp <- doMalloc undefined\n    return $ unsafeFromForeignPtr fp 0 n\n  where\n    --\n    -- Use the much cheaper Haskell heap allocated storage\n    -- for foreign pointer space we control\n    --\n    doMalloc :: Storable b => b -> IO (ForeignPtr b)\n    doMalloc dummy = do\n#if __GLASGOW_HASKELL__ >= 605\n        mallocPlainForeignPtrBytes (n * sizeOf dummy)\n#else\n        mallocForeignPtrBytes      (n * sizeOf dummy)\n#endif\n\n{- | creates a Vector from a list:\n\n@> fromList [2,3,5,7]\n4 |> [2.0,3.0,5.0,7.0]@\n\n-}\nfromList :: Storable a => [a] -> Vector a\nfromList l = unsafePerformIO $ do\n    v <- createVector (length l)\n    unsafeWith v $ \\ p -> pokeArray p l\n    return v\n\nsafeRead v = inlinePerformIO . unsafeWith v\n{-# INLINE safeRead #-}\n\ninlinePerformIO :: IO a -> a\ninlinePerformIO (IO m) = case m realWorld# of (# _, r #) -> r\n{-# INLINE inlinePerformIO #-}\n\n{- | extracts the Vector elements to a list\n\n@> toList (linspace 5 (1,10))\n[1.0,3.25,5.5,7.75,10.0]@\n\n-}\ntoList :: Storable a => Vector a -> [a]\ntoList v = safeRead v $ peekArray (dim v)\n\n{- | An alternative to 'fromList' with explicit dimension. The input\n     list is explicitly truncated if it is too long, so it may safely\n     be used, for instance, with infinite lists.\n\n     This is the format used in the instances for Show (Vector a).\n-}\n(|>) :: (Storable a) => Int -> [a] -> Vector a\ninfixl 9 |>\nn |> l = if length l' == n\n            then fromList l'\n            else error \"list too short for |>\"\n  where l' = take n l\n\n\n-- | access to Vector elements without range checking\nat' :: Storable a => Vector a -> Int -> a\nat' v n = safeRead v $ flip peekElemOff n\n{-# INLINE at' #-}\n\n--\n-- turn off bounds checking with -funsafe at configure time.\n-- ghc will optimise away the salways true case at compile time.\n--\n#if defined(UNSAFE)\nsafe :: Bool\nsafe = False\n#else\nsafe = True\n#endif\n\n-- | access to Vector elements with range checking.\nat :: Storable a => Vector a -> Int -> a\nat v n\n    | safe      = if n >= 0 && n < dim v\n                    then at' v n\n                    else error \"vector index out of range\"\n    | otherwise = at' v n\n{-# INLINE at #-}\n\n{- | takes a number of consecutive elements from a Vector\n\n@> subVector 2 3 (fromList [1..10])\n3 |> [3.0,4.0,5.0]@\n\n-}\nsubVector :: Storable t => Int       -- ^ index of the starting element\n                        -> Int       -- ^ number of elements to extract\n                        -> Vector t  -- ^ source\n                        -> Vector t  -- ^ result\nsubVector = Vector.slice\n\n\n{- | Reads a vector position:\n\n@> fromList [0..9] \\@\\> 7\n7.0@\n\n-}\n(@>) :: Storable t => Vector t -> Int -> t\ninfixl 9 @>\n(@>) = at\n\n\n{- | creates a new Vector by joining a list of Vectors\n\n@> join [fromList [1..5], constant 1 3]\n8 |> [1.0,2.0,3.0,4.0,5.0,1.0,1.0,1.0]@\n\n-}\njoin :: Storable t => [Vector t] -> Vector t\njoin [] = error \"joining zero vectors\"\njoin [v] = v\njoin as = unsafePerformIO $ do\n    let tot = sum (map dim as)\n    r <- createVector tot\n    unsafeWith r $ \\ptr ->\n        joiner as tot ptr\n    return r\n  where joiner [] _ _ = return ()\n        joiner (v:cs) _ p = do\n            let n = dim v\n            unsafeWith v $ \\pb -> copyArray p pb n\n            joiner cs 0 (advancePtr p n)\n\n\n{- | Extract consecutive subvectors of the given sizes.\n\n@> takesV [3,4] (linspace 10 (1,10))\n[3 |> [1.0,2.0,3.0],4 |> [4.0,5.0,6.0,7.0]]@\n\n-}\ntakesV :: Storable t => [Int] -> Vector t -> [Vector t]\ntakesV ms w | sum ms > dim w = error $ \"takesV \" ++ show ms ++ \" on dim = \" ++ (show $ dim w)\n            | otherwise = go ms w\n    where go [] _ = []\n          go (n:ns) v = subVector 0 n v\n                      : go ns (subVector n (dim v - n) v)\n\n---------------------------------------------------------------\n\n-- | transforms a complex vector into a real vector with alternating real and imaginary parts \nasReal :: (RealFloat a, Storable a) => Vector (Complex a) -> Vector a\nasReal v = unsafeFromForeignPtr (castForeignPtr fp) (2*i) (2*n)\n    where (fp,i,n) = unsafeToForeignPtr v\n\n-- | transforms a real vector into a complex vector with alternating real and imaginary parts\nasComplex :: (RealFloat a, Storable a) => Vector a -> Vector (Complex a)\nasComplex v = unsafeFromForeignPtr (castForeignPtr fp) (i `div` 2) (n `div` 2)\n    where (fp,i,n) = unsafeToForeignPtr v\n\n---------------------------------------------------------------\n\nfloat2DoubleV :: Vector Float -> Vector Double\nfloat2DoubleV v = unsafePerformIO $ do\n    r <- createVector (dim v)\n    app2 c_float2double vec v vec r \"float2double\"\n    return r\n\ndouble2FloatV :: Vector Double -> Vector Float\ndouble2FloatV v = unsafePerformIO $ do\n    r <- createVector (dim v)\n    app2 c_double2float vec v vec r \"double2float2\"\n    return r\n\n\nforeign import ccall unsafe \"float2double\" c_float2double:: TFV\nforeign import ccall unsafe \"double2float\" c_double2float:: TVF\n\n---------------------------------------------------------------\n\nstepF :: Vector Float -> Vector Float\nstepF v = unsafePerformIO $ do\n    r <- createVector (dim v)\n    app2 c_stepF vec v vec r \"stepF\"\n    return r\n\nstepD :: Vector Double -> Vector Double\nstepD v = unsafePerformIO $ do\n    r <- createVector (dim v)\n    app2 c_stepD vec v vec r \"stepD\"\n    return r\n\nforeign import ccall unsafe \"stepF\" c_stepF :: TFF\nforeign import ccall unsafe \"stepD\" c_stepD :: TVV\n\n---------------------------------------------------------------\n\ncondF :: Vector Float -> Vector Float -> Vector Float -> Vector Float -> Vector Float -> Vector Float\ncondF x y l e g = unsafePerformIO $ do\n    r <- createVector (dim x)\n    app6 c_condF vec x vec y vec l vec e vec g vec r \"condF\"\n    return r\n\ncondD :: Vector Double -> Vector Double -> Vector Double -> Vector Double -> Vector Double -> Vector Double\ncondD x y l e g = unsafePerformIO $ do\n    r <- createVector (dim x)\n    app6 c_condD vec x vec y vec l vec e vec g vec r \"condD\"\n    return r\n\nforeign import ccall unsafe \"condF\" c_condF :: CInt -> PF -> CInt -> PF -> CInt -> PF -> TFFF\nforeign import ccall unsafe \"condD\" c_condD :: CInt -> PD -> CInt -> PD -> CInt -> PD -> TVVV\n\n--------------------------------------------------------------------------------\n\nconjugateAux fun x = unsafePerformIO $ do\n    v <- createVector (dim x)\n    app2 fun vec x vec v \"conjugateAux\"\n    return v\n\nconjugateQ :: Vector (Complex Float) -> Vector (Complex Float)\nconjugateQ = conjugateAux c_conjugateQ\nforeign import ccall unsafe \"conjugateQ\" c_conjugateQ :: TQVQV\n\nconjugateC :: Vector (Complex Double) -> Vector (Complex Double)\nconjugateC = conjugateAux c_conjugateC\nforeign import ccall unsafe \"conjugateC\" c_conjugateC :: TCVCV\n\n--------------------------------------------------------------------------------\n\ncloneVector :: Storable t => Vector t -> IO (Vector t)\ncloneVector v = do\n        let n = dim v\n        r <- createVector n\n        let f _ s _ d =  copyArray d s n >> return 0\n        app2 f vec v vec r \"cloneVector\"\n        return r\n\n------------------------------------------------------------------\n\n-- | map on Vectors\nmapVector :: (Storable a, Storable b) => (a-> b) -> Vector a -> Vector b\nmapVector f v = unsafePerformIO $ do\n    w <- createVector (dim v)\n    unsafeWith v $ \\p ->\n        unsafeWith w $ \\q -> do\n            let go (-1) = return ()\n                go !k = do x <- peekElemOff p k\n                           pokeElemOff      q k (f x)\n                           go (k-1)\n            go (dim v -1)\n    return w\n{-# INLINE mapVector #-}\n\n-- | zipWith for Vectors\nzipVectorWith :: (Storable a, Storable b, Storable c) => (a-> b -> c) -> Vector a -> Vector b -> Vector c\nzipVectorWith f u v = unsafePerformIO $ do\n    let n = min (dim u) (dim v)\n    w <- createVector n\n    unsafeWith u $ \\pu ->\n        unsafeWith v $ \\pv ->\n            unsafeWith w $ \\pw -> do\n                let go (-1) = return ()\n                    go !k = do x <- peekElemOff pu k\n                               y <- peekElemOff pv k\n                               pokeElemOff      pw k (f x y)\n                               go (k-1)\n                go (n -1)\n    return w\n{-# INLINE zipVectorWith #-}\n\n-- | unzipWith for Vectors\nunzipVectorWith :: (Storable (a,b), Storable c, Storable d) \n                   => ((a,b) -> (c,d)) -> Vector (a,b) -> (Vector c,Vector d)\nunzipVectorWith f u = unsafePerformIO $ do\n      let n = dim u\n      v <- createVector n\n      w <- createVector n\n      unsafeWith u $ \\pu ->\n          unsafeWith v $ \\pv ->\n              unsafeWith w $ \\pw -> do\n                  let go (-1) = return ()\n                      go !k   = do z <- peekElemOff pu k\n                                   let (x,y) = f z \n                                   pokeElemOff      pv k x\n                                   pokeElemOff      pw k y\n                                   go (k-1)\n                  go (n-1)\n      return (v,w)\n{-# INLINE unzipVectorWith #-}\n\nfoldVector :: Storable a => (a -> b -> b) -> b -> Vector a -> b\nfoldVector f x v = unsafePerformIO $\n    unsafeWith v $ \\p -> do\n        let go (-1) s = return s\n            go !k !s = do y <- peekElemOff p k\n                          go (k-1::Int) (f y s)\n        go (dim v -1) x\n{-# INLINE foldVector #-}\n\n-- the zero-indexed index is passed to the folding function\nfoldVectorWithIndex :: Storable a => (Int -> a -> b -> b) -> b -> Vector a -> b\nfoldVectorWithIndex f x v = unsafePerformIO $\n    unsafeWith v $ \\p -> do\n        let go (-1) s = return s\n            go !k !s = do y <- peekElemOff p k\n                          go (k-1::Int) (f k y s)\n        go (dim v -1) x\n{-# INLINE foldVectorWithIndex #-}\n\nfoldLoop f s0 d = go (d - 1) s0\n     where\n       go 0 s = f (0::Int) s\n       go !j !s = go (j - 1) (f j s)\n\nfoldVectorG f s0 v = foldLoop g s0 (dim v)\n    where g !k !s = f k (at' v) s\n          {-# INLINE g #-} -- Thanks to Ryan Ingram (http://permalink.gmane.org/gmane.comp.lang.haskell.cafe/46479)\n{-# INLINE foldVectorG #-}\n\n-------------------------------------------------------------------\n\n-- | monadic map over Vectors\n--    the monad @m@ must be strict\nmapVectorM :: (Storable a, Storable b, Monad m) => (a -> m b) -> Vector a -> m (Vector b)\nmapVectorM f v = do\n    w <- return $! unsafePerformIO $! createVector (dim v)\n    mapVectorM' w 0 (dim v -1)\n    return w\n    where mapVectorM' w' !k !t\n              | k == t               = do\n                                       x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k \n                                       y <- f x\n                                       return $! inlinePerformIO $! unsafeWith w' $! \\q -> pokeElemOff q k y\n              | otherwise            = do\n                                       x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k \n                                       y <- f x\n                                       _ <- return $! inlinePerformIO $! unsafeWith w' $! \\q -> pokeElemOff q k y\n                                       mapVectorM' w' (k+1) t\n{-# INLINE mapVectorM #-}\n\n-- | monadic map over Vectors\nmapVectorM_ :: (Storable a, Monad m) => (a -> m ()) -> Vector a -> m ()\nmapVectorM_ f v = do\n    mapVectorM' 0 (dim v -1)\n    where mapVectorM' !k !t\n              | k == t            = do\n                                    x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k\n                                    f x\n              | otherwise         = do\n                                    x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k \n                                    _ <- f x\n                                    mapVectorM' (k+1) t\n{-# INLINE mapVectorM_ #-}\n\n-- | monadic map over Vectors with the zero-indexed index passed to the mapping function\n--    the monad @m@ must be strict\nmapVectorWithIndexM :: (Storable a, Storable b, Monad m) => (Int -> a -> m b) -> Vector a -> m (Vector b)\nmapVectorWithIndexM f v = do\n    w <- return $! unsafePerformIO $! createVector (dim v)\n    mapVectorM' w 0 (dim v -1)\n    return w\n    where mapVectorM' w' !k !t\n              | k == t               = do\n                                       x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k \n                                       y <- f k x\n                                       return $! inlinePerformIO $! unsafeWith w' $! \\q -> pokeElemOff q k y\n              | otherwise            = do\n                                       x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k \n                                       y <- f k x\n                                       _ <- return $! inlinePerformIO $! unsafeWith w' $! \\q -> pokeElemOff q k y\n                                       mapVectorM' w' (k+1) t\n{-# INLINE mapVectorWithIndexM #-}\n\n-- | monadic map over Vectors with the zero-indexed index passed to the mapping function\nmapVectorWithIndexM_ :: (Storable a, Monad m) => (Int -> a -> m ()) -> Vector a -> m ()\nmapVectorWithIndexM_ f v = do\n    mapVectorM' 0 (dim v -1)\n    where mapVectorM' !k !t\n              | k == t            = do\n                                    x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k\n                                    f k x\n              | otherwise         = do\n                                    x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k \n                                    _ <- f k x\n                                    mapVectorM' (k+1) t\n{-# INLINE mapVectorWithIndexM_ #-}\n\n\nmapVectorWithIndex :: (Storable a, Storable b) => (Int -> a -> b) -> Vector a -> Vector b\n--mapVectorWithIndex g = head . mapVectorWithIndexM (\\a b -> [g a b])\nmapVectorWithIndex f v = unsafePerformIO $ do\n    w <- createVector (dim v)\n    unsafeWith v $ \\p ->\n        unsafeWith w $ \\q -> do\n            let go (-1) = return ()\n                go !k = do x <- peekElemOff p k\n                           pokeElemOff      q k (f k x)\n                           go (k-1)\n            go (dim v -1)\n    return w\n{-# INLINE mapVectorWithIndex #-}\n\n-------------------------------------------------------------------\n\n\n-- | Loads a vector from an ASCII file (the number of elements must be known in advance).\nfscanfVector :: FilePath -> Int -> IO (Vector Double)\nfscanfVector filename n = do\n    charname <- newCString filename\n    res <- createVector n\n    app1 (gsl_vector_fscanf charname) vec res \"gsl_vector_fscanf\"\n    free charname\n    return res\n\nforeign import ccall unsafe \"vector_fscanf\" gsl_vector_fscanf:: Ptr CChar -> TV\n\n-- | Saves the elements of a vector, with a given format (%f, %e, %g), to an ASCII file.\nfprintfVector :: FilePath -> String -> Vector Double -> IO ()\nfprintfVector filename fmt v = do\n    charname <- newCString filename\n    charfmt <- newCString fmt\n    app1 (gsl_vector_fprintf charname charfmt) vec v \"gsl_vector_fprintf\"\n    free charname\n    free charfmt\n\nforeign import ccall unsafe \"vector_fprintf\" gsl_vector_fprintf :: Ptr CChar -> Ptr CChar -> TV\n\n-- | Loads a vector from a binary file (the number of elements must be known in advance).\nfreadVector :: FilePath -> Int -> IO (Vector Double)\nfreadVector filename n = do\n    charname <- newCString filename\n    res <- createVector n\n    app1 (gsl_vector_fread charname) vec res \"gsl_vector_fread\"\n    free charname\n    return res\n\nforeign import ccall unsafe \"vector_fread\" gsl_vector_fread:: Ptr CChar -> TV\n\n-- | Saves the elements of a vector to a binary file.\nfwriteVector :: FilePath -> Vector Double -> IO ()\nfwriteVector filename v = do\n    charname <- newCString filename\n    app1 (gsl_vector_fwrite charname) vec v \"gsl_vector_fwrite\"\n    free charname\n\nforeign import ccall unsafe \"vector_fwrite\" gsl_vector_fwrite :: Ptr CChar -> TV\n\n", "meta": {"hexsha": "5892e67a66a35b547da3b2af58a25a63aa1e7b0a", "size": 18349, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Data/Packed/Internal/Vector.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/Vector.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/Vector.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.0171755725, "max_line_length": 115, "alphanum_fraction": 0.5481497629, "num_tokens": 4959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.5544704649604272, "lm_q1q2_score": 0.2988502851925982}}
{"text": "{-# LANGUAGE NoImplicitPrelude, TypeSynonymInstances, RankNTypes, StandaloneDeriving,\nScopedTypeVariables, TypeApplications, GADTs, TypeOperators, DeriveTraversable,\nFlexibleInstances, AllowAmbiguousTypes, UndecidableInstances, TypeFamilies, LambdaCase #-}\nmodule Lib\n    where\nimport Numeric.LinearAlgebra\nimport Control.Category\nimport Prelude hiding ((.), id)\nimport Control.Arrow ((***))\nsomeFunc :: IO ()\nsomeFunc = putStrLn \"someFunc\"\n\n\n\n{-\ntype V a = a -> Double\ntype D a = a -> Double\nD (V a)\ntype V a  = ContT () Q a -- ContT b Q a = (a ->Q b) -> Q b. Has some way of dealing with a index. Some kind of\nSelT -- takes a diag, unsummed?\n-- (a -> Q b) -> Q a\n\nnewtype Dag a = Dag (a -> Q ())\n\nclass Dagger a where\n    type Dual :: * -> * -- *?\n    dag :: a -> Dual a\ninstance Dagger (D (Vec a)) where\n    type Dual = Vec\n    dag (D v) = join $ ContT ()\n-- dagger needs to embed a search procedure?\n\ninstance Dagger (D (Vec Bool)) where\n    type Dual = Vec Bool\n    dag (D v) = join $ ContT ()\ninstance Dagger a b where\n    dag :: a -> b\n    dag' :: b -> a\ninstance Dagger k where\n    type family Dual :: * -> *\n    dag :: k a (Dual a) -- dag'?\n\n-- also a kind of dot product\ndag1 :: ((a -> Q ()) -> Q ()) -> (((a -> Q ()) -> Q ()) -> Q ()\ndag1 f = \n\n-- it's a kind of dot product.\nlift :: f Double -> (a -> Double) -> Double\nlift w f = fold (+) $ (mapWithIndex \\k v -> (f k) * v) w\n\n-- tensor is a_i b_i, mutiply out without summing\ntensor :: f a ->  f a  -> f a\ntensor = intersectWith (*)\n\ntype V' a = (a -> Q ()) -> Q ()\ntensor :: V' a -> V' a -> V' a\n\ndag :: (V' Bool -> Q ()) -> V' Bool\ndag f = \\g -> True False\n\ndag :: (Bool -> Q ()) -> V' Bool\ndag :: (Bool -> Q ()) -> (Bool -> Q ()) -> Q ()\ndag f g = (f True) (g True) + (f False) (g False)\n\n\n\ndag :: (Bool -> Q ()) -> Q Bool\ndag f = (f True) >>= true + (f False) >>= false\n\ndag :: Q Bool -> (Bool -> Q ())\ndag xs b = lookup b xs \ndag :: Eq a => Q a -> (a -> Q ()) -- maybe Ord\ndag xs b = lookup b xs \n\n-- If we mixed Hedges select sat solver with the Q monad?\n-- (Bool -> Q Bool) -> Q Bool ? the unsummed trace? diag? Hedgest hing would come out weirder.\n\n\ntrue :: () -> Q Bool\ntrue _ = pure True\nfalse :: () -> Q Bool\nfalse _ = pure False\n\n-- the seelect function.\n-- (b -> m ()) -> m b\n\n-}\n\n\ntype M = Matrix Double\n\n{-\n\ndata BMatrix a b = BMatrix M M M M | Id -- A B C D\n\ninstance Category BMatrix where\n    id = Id\n    Id . x = x\n    x . Id = x\n    (BMatrix a b c d) . (BMatrix e f g h) = BMatrix <\\> where\n            q = d + e\n            qlu = lupacked q\n            qinv = lusolve qlu\n            a' = a - (b <> (qinv c))\n            b' =  b <> (qinv f)\n            c' = g <> (qinv c)\n            d' = h - g <> (qinv f)\n\npar :: BMatrix a b -> BMatrix c d -> BMatrix (a,c) (b,d)\npar (Matrix a b c d) (BMatrix e f g h) = BMatrix (diagBlock [a,e]) (diagBlock [b,f]) (diagBlock [c,g])  (diagBlock [d,h]) \ndup = BMatrix a (a,a)\ndup = BMatrix (diagBlock [ident,ident]) (ident ||| ident) (ident === ident) (diagBlock [ident,ident])\nid = BMatrix ident ident ident ident\navg = \n-}\ndata QuadFun a b = QuadFun {mat :: M, vec :: Vector Double, c :: Double } deriving Show\n\n\n--data QuadFun a b where\n--   QuadFun :: (Bounded a, Bounded b, Enum a, Enum b) => M -> Vector Double -> Double -> QuadFun a b } \n\n-- This is kron product.\ninstance (Enum a, Enum b, Bounded a) => Enum (a,b) where\n  toEnum x =  let (a, b) = quotRem x (fromEnum (maxBound :: a)) in\n                (toEnum a   , toEnum b)\n  fromEnum (a,b) =  (fromEnum (maxBound :: a)) * (fromEnum a) + (fromEnum b)\n  {-\ninstance (Enum a, Enum b, Bounded a) => Enum (Either a b) where\n    toEnum x | x > (fromEnum (maxBound :: a)) = Left (toEnum x)\n             | otherwise = Right $ toEnum (x - 1 - (fromEnum (maxBound :: a)))\n    fromEnum (Left a) =  fromEnum a\n    fromEnum (Right b) =  (fromEnum (maxBound :: a)) + 1 + (fromEnum b) \n-}\n-- deriving instance (Enum a, Enum b) => Enum (a,b)\n\n\ncount :: forall a. (Enum a, Bounded a) => Int\ncount = (fromEnum (maxBound @a)) - (fromEnum (minBound @a)) + 1\n\nid ::forall a. (Enum a, Bounded a) => QuadFun a a\nid = let s = 2 * (count @ a) in QuadFun (ident s) (konst 0 s) 0\n\n--dup :: QuadFun a (a,a)\n--dup  = QuadFun (ident\n\nclass (Bounded a, Enum a) => BEnum a where\ninstance (Bounded a, Enum a) => BEnum a where\n\nt7 :: QuadFun () ()\nt7 = QuadFun (konst 4 (2,2)) (konst 7 2) 3\n\nt8 = (mat t7) <\\> (vec t7)\nt4 = par t7 t7\nt9 = (mat t4) <\\> (vec t4)\n\ncompose :: forall a b c. BEnum b => QuadFun b c -> QuadFun a b -> QuadFun a c\ncompose (QuadFun m' w' c') (QuadFun m w c) = QuadFun m'' w'' c'' where\n   n = count @b\n   k = rows m -- assuming square\n   l = rows m'\n   i = ident n\n   q = konst 0 (k-n,n)  === i  -- I underneath zeros\n   q' = -i === konst 0 (l-n,n)   -- -i above zeros\n   m'' = fromBlocks [[m,    q, 0], \n                     [tr q ,0, tr q'], \n                     [0,    q', m']]\n   w'' = vjoin [w, konst 0 n, w']\n   c'' = c + c'\n\nidentOut :: forall a b. BEnum b => QuadFun a b -> M\nidentOut (QuadFun m w c) = konst 0 (k-n,n)  === i  where\n    n = count @b\n    k = rows m\n    i = ident n\nidentIn :: forall a b. BEnum a => QuadFun a b -> M\nidentIn (QuadFun m w c) = -i === konst 0 (k-n,n)   where\n    n = count @a\n    k = rows m\n    i = ident n\ntype a :+: b = Either a b\n-- I kind of feel like our sign convention is flipped\npar :: forall a b c d. (BEnum a, BEnum b, BEnum c, BEnum d) => QuadFun a c -> QuadFun b d -> QuadFun (a :+: b) (c :+: d)\npar x@(QuadFun m w c) y@(QuadFun m' w' c') = QuadFun m'' w'' c'' where\n    ia = ident (count @a)\n    ib = ident (count @b)\n    ia' = identIn x\n    ib' = identIn y\n    ia't = tr ia'\n    ib't = tr ib'\n    ic = - ident (count @c)\n    id = - ident (count @d)\n    ic' = identOut x\n    id' = identOut y\n    ic't = tr ic'\n    id't = tr id'\n    n = (count @a) + (count @b)\n    n' = (count @c) + (count @d)\n    --iab = fromBlocks [[0,0,ia,0], [0,0,0,ib], [ia, 0,0,0], [0,ib,0,0]]\n    --iab' = fromBlocks [[tr (identIn x),0],  [0 , tr (identIn y)]]\n    --zab = konst 0 (n,n)\n    -- should be 2 ins + 2 langrange + 2 matr + 2lagarne + 2 outs = 10x10 block matrix\n    m'' = fromBlocks [[0 ,0 , ia, 0, 0, 0, 0 ,0,0,0], \n                    [0, 0,  0, ib, 0, 0, 0, 0,0,0 ] , \n                    [ia, 0, 0, 0,  ia't, 0,0,0,0, 0],\n                    [0, ib, 0, 0,  0,ib't,0, 0,0 ,0],  \n                    [0, 0, ia',0,  m, 0 , ic',0,0,0],\n                    [0, 0,  0, ib',0, m', 0,id',0,0], \n                    [0, 0,  0, 0, ic't,0 ,0,0,ic,0], \n                    [0, 0,  0, 0,  0,id't,0,0,0,id],\n                    [0, 0,  0, 0,  0, 0,  ic,0,0,0],\n                    [0, 0,  0, 0,  0, 0,  0,id,0,0]]\n    w'' = vjoin [konst 0 (2*n), w,w', konst 0 (2*n')]\n    c'' = c + c'\n\ndup :: forall a. BEnum a => QuadFun a (a,a)\ndup = QuadFun m 0 0 where -- 1 input, 2 lagrange mutipliers, and 2 outputs.\n    ia = ident (count @a)\n    m = fromBlocks [ [0, ia,ia, 0,0],\n                     [ia, 0, 0, -ia,0],\n                     [0, ia, 0, 0, -ia],\n                     [0,-ia, 0, 0, 0 ],\n                     [0, 0, -ia, 0,0]]\n\n-- fst...?\n-- for snd, we could just leave it alone\n-- fuse?\n-- swap.\ndata Void\nfuse :: forall a. BEnum a => QuadFun (a,a) Void\nfuse = QuadFun m 0 0 where -- 2 inputs, 1 lagrange multiplier.\n    ia = ident (count @a)\n    m = fromBlocks [[0,0,    ia],\n                    [0 ,0 , -ia],\n                    [ia, -ia, 0]]\n\n-- The analog for this slicing for convex sets may be to slice the \n-- dimensions into in and out dimensions. Then \n\n\n\ndata Cell a = Cell {phi :: Double, j :: Double, next :: a} deriving (Show, Traversable, Foldable, Functor) -- composition of cell is a statically sized vector. Derive applicative?\n\n\n\ninstance Applicative Cell where\n    pure x = Cell 0 0 x\n    (Cell phi1 j1 f) <*> (Cell phi2 j2 x) = Cell (phi1 + phi2) (j1 + j2) (f x) -- ? I doubt this makes any sense.\n{-\ndata Cell a = Cell { phi :: a, j :: a}\ntype f :+: g = Product f g\ngaussK :: Lens ((Cell :+: Cell) a) (Cell a)\n\ngaussK :: -> Lens (Cell :*: f a) -- no Cell is very not this.\n\ntype Row = (Cell Cell Cell Cell Cell)\n\n\nLens (a, b, other) (b, other)\n\n\ngaussK :: Lens \n\ndata Cell2 f a b = Cell2 {phi :: a , j :: a, next :: f b} \ndata Cell2 f a = Cell2 {phi :: f Double a , j ::f Double, next :: f a} \n\n-- zipA :: f a -> f b -> f (a,b) \n-- zipA x y = (,) <$> x <*> y \n-- monProd\n\nfmap2 = fmap . fmap\nfmap4 = fmap2 . fmap2\nfmap8 = fmap4 . fmap4\n\nzipA x y = (,) <$> x <*> y \nzip2 = zipA . (fmap zipA) -- hmm. Maybe we should be using Compose. we're going to need famp2. Compose will get us these instances for free.\nzip4 = zip2 . (fmap2 zip2)\nzip8 = zip4 . (fmap4 zip4)\n\n\nparK :: Lens (f b) b -> Lens (g a) a -> Lens (f g a) a\nparK :: forall b. Lens (f b) (f' b) -> Lens (g a) (g' a) -> Lens (f g a) (f' (g' a))\nparK :: forall b. Lens (f g a) (f' g a) -> Lens (g a) (g' a) -> Lens (f g a) (f' (g' a))\nparK = compose (fmap l2) l1\n\n\n\n\nDo the y direction inductively\n\nydir :: Lens (Cell a, Cell a) (a,a)\nydir = \\(Cell phi j x, Cell phi2 j2 y) -> ((x,y), \\(x',y') -> (Cell phi j x, Cell phi2 j2 y)      )\n\n\nydir :: Lens (Cell a, Cell a) (a,a)\nydir = \\(a,b) -> ((Cell phi j x) , f) = (gaussK a) in ((Cell phi j y) , g) = (gaussK b) in \n\nLens ( (X (), (X (), a) (X (), a)\nydir = \\(r1, (r2, z) ->  zip8    )    -- = gaussK r1 in  = gaussK r2 in \n\nLens (f a) a -> Lens (f a) a -> Lens (f a, f a) a\nLens (Cell a) a -> Lens \n\nLens x y x' y'\n\n-}\n\n{-\ncan i just use regular lenses? I need to set in kind of a weird way though.\n-}\n\ndata Lens a b = Lens (a -> (b, b -> a)) \n-- newtype Lens a b = Lens forall r. (a -> (b -> (b -> a) -> r) -> r) -- cpsify for speed? van Laarhoven?\n\n-- SLens s a b = SLens (a -> ST s (b, b -> ST s a)) mutable update\n-- MLens a b = MLens (a -> m (b , b -> m a)) -- monadic lens\n-- KLens a b = KLens (a -> (b, k b a)) ---- this is sort of what Conal wrote.\ncomp :: Lens b c -> Lens a b -> Lens a c\ncomp (Lens f) (Lens g) = Lens $ \\x -> let (y, g') = g x in\n                                      let (z, f') = f y in\n                                      (z, g' . f')\n\n-- Gauss Seidel of the standard 1 -2 1 matrix\n-- j1 is the effective source incliuding the influence from phi values up in the stack\n-- Double Cell construction is rather wonky\n-- gaussK :: Vec (S (S n)) Double -> Vec (S n)\n-- we could also go for the lagrange mutiplier interface.\n-- can also push the rho value needed for stability up and down.\n\n-- -2 phi1 + 1 phi2 = ~j1\n-- -1 phi1 + -2 phi2 + ...? = j2\n\n{-\nWe are moving the lower diagonal to the right hand side as the splitting.\nThat ends up to claculating an effective j based on previous values.\nWe then triangular solve the upper diagonal, which we are able to find the new diagonal element in terms of the lower values.\n\n-}\n-- it's kind of weird that we mutate j on the way down but restore it on the way up.\n-- But we do need a way to access j. (Phi (Phi a), J a) (Phi )\n\ngaussK :: Lens (Cell (Cell a)) (Cell a) -- we need the context Cell\ngaussK = Lens $ \\case (Cell phi1 j1 (Cell phi2 j2 y)) -> (Cell phi2 (j2 - phi1) y , \\case (Cell phi2' j2' z) -> let j1' = j1 - phi2' in  -- moving the triangular upsolve to the right hand side\n                                                                                                             Cell (- j1' / 2) j1 (Cell phi2' j2 z))\n\n-- interface in , internals, interface out. was the previous way of talking about it. But then the internals grow, which is fine\n-- compose :: Lens in internal out -> Lens in' internal' out' -> Lens in (internal, out, in', internal') out\n-- some ind of 2 category? Enriched? The morphisms have this internal structure.\n-- this is more a containing relationship. The larger context can be converted into the smaller context.                                                                                                             \n-- \n\ng2 :: Lens (Cell (Cell (Cell a))) (Cell a)\ng2 = gaussK `comp` gaussK\ng4 = g2 `comp` g2\ng8 = g4 `comp` g4\ng16 = g8 `comp` g8\ng32 = g16 `comp` g16\n\ncapZero :: Lens (Cell ()) () -- not even sure i really need this? does runGauss (f `comp` capZero) ~ runGauss f\ncapZero = Lens $ \\case (Cell phi j _) -> ((), \\_ -> Cell (- j / 2) j ())\n\n-- runGauss ::  Lens a b -> a -> a -- removes the open ended nature of the thing.\nrunGauss ::  Lens a () -> a -> a -- this might make more sense as what you really want. This is some kind of cap operation.\nrunGauss (Lens f) x = let (y , trisolve)  = f x in trisolve y\nstartingVal :: Cell (Cell (Cell ()))\nstartingVal = (Cell 0 0 (Cell 0 1 (Cell 0 0 ())))\n\niters = iterate (runGauss (capZero `comp` g2)) startingVal\n--iters' = iterate (runGauss g2) startingVal -- They are different. \n\nsol = ((3><3) [-2,1,0,\n               1,-2,1,\n               0,1,-2])  <\\> (vector [0,1,0])\n\n-- can do inner block solves also (via an iterative method perhaps)\n-- this is reminsecent of a multiscale attack.\nparC :: Lens a a' -> Lens b b' -> Lens (a,b) (a',b')\nparC (Lens f) (Lens g) = Lens $ \\(x,y) -> let (x', f') = f x in\n                                          let (y', g') = g y in\n                                          ((x',y') , f' *** g')\n\n-- profucntor optics paper\ndata FunList a b t = Done t | More a (FunList a b (b -> t))\n-- contents and fill\n-- contents (s -> a^n)\n-- fill s -> b^n -> t\n-- s -> exists n. (a^n, a^n -> s) is a traversal. Could use a Vec. But we already have a Vec. Cell is a Vec\n-- s -> exists n, (Vec n a, Vec n a -> s)\n-- maybe we do need an applicative. We sort of need to zip together two rows to start going 2d.\n\n-- huh. A block wise schur is kind of the monoidal ppoduct here. No. monoidal product is pure dsum.\n-- actually composition? is kind of what plays the game of block wise stuff.\n{-\n\nif we want this to be not the case,\ncomp :: Lens (a,a') a'\n\n\nschur :: Lens a a' -> (a -> b) -> (b -> a) -> Lens b b' -> Lens (a,b) (a',b')\nschur (Lens a) b c (Lens d) = Lens $ \\(x,y) -> let (x', a') = a x in\n                                               let (y', d') = d x in\n                                               (       )\n-}\n-- Lens (f (g a)) (g a)\n\n                                               -- we can change this all into a continuation form\n-- \n\n{-\npar :: forall a b c d. (BEnum a, BEnum b, BEnum c, BEnum d) => BMatrix a b -> \n                         BMatrix c d -> BMatrix (a,c) (b,d)\npar q@(QuadFun m w r) q'@(QuadFun m' w' r') = QuadFun q'' w'' r'' where\n     a' = diagBlock [sliceA q, sliceA q']\n     b' = diagBlock [sliceB q, sliceB q']\n     c' = diagBlock [sliceC q, sliceC q']\n     d' = diagBlock [sliceD q, sliceD q']\n     q'' = fromBlocks [[a',b'], [c',d']]\n     u' = vjoin [sliceU v, sliceU v']\n     v' = vjoin [sliceV v, sliceV v']\n     w'' = vjoin [u', v']\n     r'' = r + r'\n\n\n\n\n\nsliceA :: forall a b. (BEnum a, BEnum b) => QuadFun a b -> M\nsliceA (QuadFun m v c) = subMatrix (0,0) (count @a, count @a)  m\nsliceB :: forall a b. (BEnum a, BEnum b) => QuadFun a b -> M\nsliceB (QuadFun m v c) = subMatrix (0,count @a) (count @a, count @b) m\nsliceC :: forall a b. (BEnum a, BEnum b) => QuadFun a b -> M\nsliceC (QuadFun m v c) = subMatrix (count @a,0) (count @b, count @a) m\nsliceD :: forall a b. (BEnum a, BEnum b) => QuadFun a b -> M\nsliceD (QuadFun m v c) = subMatrix (count @a,count @a) (count @b, count @b) m\n\nsliceU :: forall a b. (BEnum a, BEnum b) => QuadFun a b -> Vector Double\nsliceU (QuadFun m v c) = subVector 0 (count @a) v\nsliceV :: forall a b. (BEnum a, BEnum b) => QuadFun a b -> Vector Double\nsliceV (QuadFun m v c) = subVector (count @a) (count @b) v\n\nn = count @a\nm = count @b\nq = rows m\np = q - m\na = subMatrix (0,0) (count @a, count @a)  m\n\n\na = subMatrix\n--Other options\n-- Keep a matrix with the end and the beginning are the \n\n-- Keep Constraints too?\n\n-- what in the world\n-- stack build --ghc-options /usr/lib/libiconv.dylib\n\n-- size\n-- rows\n-- cols\n\ncompose :: QuadFun b c -> QuadFun a b -> QuadFun a c\ncompose (QuadFun m w c) (QuadFun m' w' c') = QuadFun m'' w'' c'' where\n    n = (count @b)\n    corner =  fromBlocks [[ident n, 0],[0, -(ident n)]]\n    corner' = fromBlocks [[0,0],[corner,0]]\n    m'' = fromBlocks [[m ,corner'], [tr corner', m']]  \n    w'' = vjoin [w, const 0 n, w']\n    c'' = c + c\n\npar (QuadFun m w c) (QuadFun m' w' c') = \n\n\ntype a :+: b = Either a b\ndata QuadFun x = QuadFun\n\n\n((a,b,c),\n (d,e,f),\n (g,h,i)) = \n\n\n data BMatrix' = BMatrix' M M M M M M M M M \n compose (BMatrix' a' b' c' d' e' f' g' h' i') (BMatrix' a b c d e f g h i) =\n    BMatrix' a'' b'' c'' d'' e'' f'' g'' h'' i'' where\n    a'' = a\n    b'' = b ||| c ||| 0\n    c'' = 0\n    d'' = d === g === 0\n    e'' = fromBlocks [[e,f,0], [h, i + a', b'], [0, d', e']]\n    f'' = 0 === c' === f'\n    g'' =  0\n    h'' = 0 ||| g' ||| h'\n    i'' = i'\ncompose' (BVec u' v' w') (BVec u v w) = BVec u (vjoin [v ,w + u', v']) w'\n\n\npar :: QuadFun a b -> QuadFun c d -> QuadFun (Either a c) (Either b d)\npar (BMatrix' a' b' c' d' e' f' g' h' i') (BMatrix' a b c d e f g h i) =\n   BMatrix' a'' b'' c'' d'' e'' f'' g'' h'' i'' where\n   a'' = diagBlock [a',a]\n   b'' = diagBlock [b',b]\n   c'' = diagBlock [c',c]\n   d'' = diagBlock [d',d]\n   e'' = diagBlock [e',e]\n   f'' = diagBlock [f',f]\n   g'' = diagBlock [g',g]\n   h'' = diagBlock [h',h]\n   i'' = diagBlock [i',i]\n\n-- If we're just recording the entire program, we might as well just record it in a DSL\n-- rather than directly building the matrix\n-- data QuadFunDSL = Par QuadFun\n-- FreeCat + (Lit HMatrix)\n\n-- iterative matrix solution proximal method?\n-- \n-- gauss seidel\ntype VBlock = [Vector Double]\n-- (V, V)\n-- Maybe schur solve works. But with possible splitting\n-- Maybe unsolvable schur\n-- could damp a little if the diagonal isn't dominant enough \n-- (lusolve a (w - V <#| v', ) -- WHat I'm suggesting here is block Jacobi? No\n-- No it isn't. Because we're passing back v' it is guass seidel.\n-- in order to do block gauss seidel\n-- type L = VBlock -> (VBlock, VBlock -> VBlock)\n\n-- Writing in the monoidal categroy style makes parallelism more apparent.\n\n\n-- [vjoin blocks] -> ([lesser blocks] , update [lesserblocks] -> [blocks]\n-- \\x:xs -> (a*x + xs, \\b -> b )  \n\n-- storage in the lens?\n-- In my AD lens, I had all the weights in the input. This was ungainly\n-- Maybe a choice monad? Everyone could have access to a global state\n-- forall s. (ActualLens s a, a -> (b, db -> da))\n-- compsoe (ActualLens s a, a -> (b, db -> da))\n-- par \n-- ActualLens are functional references. Do they allow us to refiy sharing?\n-- (ActualLens acc a,   )\n\n-- alternative a -> State s (b, db -> State ds da)\n\n-- Mutiple directions of composition. Horizontsl and vertical?\n-- a 2-category?\n-- ActualLens s a -> ActualLens s' s\n\n-- Jules Hedges:\n-- Lens sigma a b -> Lens sigm' b c -> Lens (sig,sig') a c\n-- Lens :: Sigma -> (sigma,  ) -> Lens a b -- hides sigma, we'll never be able to get at it \n\n-}", "meta": {"hexsha": "9fb5fee586dab7fee638b2617e5ae742341b7d80", "size": 18697, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "philzook58/ConvexCat", "max_stars_repo_head_hexsha": "ba2162c9bf19a026758441ffd2023e5af1cd8e2d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-11-15T22:38:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T14:42:47.000Z", "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "philzook58/ConvexCat", "max_issues_repo_head_hexsha": "ba2162c9bf19a026758441ffd2023e5af1cd8e2d", "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": "philzook58/ConvexCat", "max_forks_repo_head_hexsha": "ba2162c9bf19a026758441ffd2023e5af1cd8e2d", "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.8713768116, "max_line_length": 213, "alphanum_fraction": 0.5426004172, "num_tokens": 6529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.29820941428449704}}
{"text": "{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-|\nModule      : Grenade.Core.Pad\nDescription : Padding layer for 2D and 3D images\nCopyright   : (c) Huw Campbell, 2016-2017\nLicense     : BSD2\nStability   : experimental\n-}\nmodule Grenade.Layers.Pad (\n    Pad (..)\n  ) where\n\nimport           Data.Maybe\nimport           Data.Proxy\nimport           Data.Serialize\nimport           Data.Singletons.TypeLits\nimport           GHC.TypeLits\n\nimport           Grenade.Core\nimport           Grenade.Layers.Internal.Pad\n\nimport           Numeric.LinearAlgebra (konst, subMatrix, diagBlock)\nimport           Numeric.LinearAlgebra.Static (extract, create)\n\n-- | A padding layer for a neural network.\n--\n--   Pads on the X and Y dimension of an image.\ndata Pad  :: Nat\n          -> Nat\n          -> Nat\n          -> Nat -> * where\n  Pad  :: Pad padLeft padTop padRight padBottom\n\ninstance Show (Pad padLeft padTop padRight padBottom) where\n  show Pad = \"Pad\"\n\ninstance UpdateLayer (Pad l t r b) where\n  type Gradient (Pad l t r b) = ()\n  runUpdate _ x _ = x\n  createRandom = return Pad\n\ninstance Serialize (Pad l t r b) where\n  put _ = return ()\n  get = return Pad\n\n-- | A two dimentional image can be padded.\ninstance ( KnownNat padLeft\n         , KnownNat padTop\n         , KnownNat padRight\n         , KnownNat padBottom\n         , KnownNat inputRows\n         , KnownNat inputColumns\n         , KnownNat outputRows\n         , KnownNat outputColumns\n         , (inputRows + padTop + padBottom) ~ outputRows\n         , (inputColumns + padLeft + padRight) ~ outputColumns\n         ) => Layer (Pad padLeft padTop padRight padBottom) ('D2 inputRows inputColumns) ('D2 outputRows outputColumns) where\n  type Tape (Pad padLeft padTop padRight padBottom) ('D2 inputRows inputColumns) ('D2 outputRows outputColumns)  = ()\n  runForwards Pad (S2D input) =\n    let padl  = fromIntegral $ natVal (Proxy :: Proxy padLeft)\n        padt  = fromIntegral $ natVal (Proxy :: Proxy padTop)\n        padr  = fromIntegral $ natVal (Proxy :: Proxy padRight)\n        padb  = fromIntegral $ natVal (Proxy :: Proxy padBottom)\n        m     = extract input\n        r     = diagBlock [konst 0 (padt,padl), m, konst 0 (padb,padr)]\n    in  ((), S2D . fromJust . create $ r)\n  runBackwards Pad _ (S2D dEdy) =\n    let padl  = fromIntegral $ natVal (Proxy :: Proxy padLeft)\n        padt  = fromIntegral $ natVal (Proxy :: Proxy padTop)\n        nrows = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        ncols = fromIntegral $ natVal (Proxy :: Proxy inputColumns)\n        m     = extract dEdy\n        vs    = subMatrix (padt, padl) (nrows, ncols) m\n    in  ((), S2D . fromJust . create $ vs)\n\n-- | A two dimentional image can be padded.\ninstance ( KnownNat padLeft\n         , KnownNat padTop\n         , KnownNat padRight\n         , KnownNat padBottom\n         , KnownNat inputRows\n         , KnownNat inputColumns\n         , KnownNat outputRows\n         , KnownNat outputColumns\n         , KnownNat channels\n         , KnownNat (inputRows * channels)\n         , KnownNat (outputRows * channels)\n         , (inputRows + padTop + padBottom) ~ outputRows\n         , (inputColumns + padLeft + padRight) ~ outputColumns\n         ) => Layer (Pad padLeft padTop padRight padBottom) ('D3 inputRows inputColumns channels) ('D3 outputRows outputColumns channels) where\n  type Tape (Pad padLeft padTop padRight padBottom) ('D3 inputRows inputColumns channels) ('D3 outputRows outputColumns channels)  = ()\n  runForwards Pad (S3D input) =\n    let padl  = fromIntegral $ natVal (Proxy :: Proxy padLeft)\n        padt  = fromIntegral $ natVal (Proxy :: Proxy padTop)\n        padr  = fromIntegral $ natVal (Proxy :: Proxy padRight)\n        padb  = fromIntegral $ natVal (Proxy :: Proxy padBottom)\n        outr  = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        outc  = fromIntegral $ natVal (Proxy :: Proxy outputColumns)\n        inr   = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        inc   = fromIntegral $ natVal (Proxy :: Proxy inputColumns)\n        ch    = fromIntegral $ natVal (Proxy :: Proxy channels)\n        m     = extract input\n        padded = pad ch padl padt padr padb inr inc outr outc m\n    in  ((), S3D . fromJust . create $ padded)\n\n  runBackwards Pad () (S3D gradient) =\n    let padl  = fromIntegral $ natVal (Proxy :: Proxy padLeft)\n        padt  = fromIntegral $ natVal (Proxy :: Proxy padTop)\n        padr  = fromIntegral $ natVal (Proxy :: Proxy padRight)\n        padb  = fromIntegral $ natVal (Proxy :: Proxy padBottom)\n        outr  = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        outc  = fromIntegral $ natVal (Proxy :: Proxy outputColumns)\n        inr   = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        inc   = fromIntegral $ natVal (Proxy :: Proxy inputColumns)\n        ch    = fromIntegral $ natVal (Proxy :: Proxy channels)\n        m     = extract gradient\n        cropped = crop ch padl padt padr padb inr inc outr outc m\n    in  ((), S3D . fromJust . create $ cropped)\n", "meta": {"hexsha": "e9600e1b0f359e735d0bdf16deb45a1b25319152", "size": 5214, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Pad.hs", "max_stars_repo_name": "Nickske666/grenade", "max_stars_repo_head_hexsha": "9309b3ba7ae0ee33e6220e6eeb3b184dac715c45", "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/Pad.hs", "max_issues_repo_name": "Nickske666/grenade", "max_issues_repo_head_hexsha": "9309b3ba7ae0ee33e6220e6eeb3b184dac715c45", "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/Pad.hs", "max_forks_repo_name": "Nickske666/grenade", "max_forks_repo_head_hexsha": "9309b3ba7ae0ee33e6220e6eeb3b184dac715c45", "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.712, "max_line_length": 143, "alphanum_fraction": 0.6279248178, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.29819745067296105}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE Strict           #-}\nmodule FourierMethod.FourierSeries2D\n  ( module FourierMethod.FourierSeries2D\n  , module FourierMethod.BlockCudaMatrix\n  , module FourierMethod.BlockMatrixAcc\n  ) where\n\nimport           Control.DeepSeq\nimport           Control.Monad                               as M\nimport           Control.Monad.IO.Class\nimport           Control.Monad.Trans.Resource\nimport qualified Data.Array.Accelerate                       as A\nimport           Data.Array.Accelerate.LLVM.PTX              as A\nimport           Data.Array.Accelerate.Numeric.LinearAlgebra as A\nimport           Data.Array.Repa                             as R\nimport           Data.Complex\nimport           Data.Conduit                                as C\nimport           Data.Conduit.List                           as CL\nimport           Data.List                                   as L\nimport           Data.Vector.Storable                        as VS\nimport           Data.Vector.Unboxed                         as VU\nimport           Foreign.CUDA.Driver                         as CUDA\nimport           FourierMethod.BlockCudaMatrix\nimport           FourierMethod.BlockMatrixAcc\nimport           FourierMethod.FourierSeries2DAcc\nimport           Utils.BLAS\nimport           Utils.Distribution\nimport           Utils.List\nimport           Utils.Parallel                              hiding ((.|))\nimport           Utils.Time\n\n{-# INLINE harmonicMatPTX #-}\nharmonicMatPTX ::\n     ( Storable e\n     , A.Elt (Complex e)\n     , A.Elt e\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     )\n  => Int\n  -> e\n  -> e\n  -> e\n  -> PTX\n  -> [(Int, Int)]\n  -> CuMat (Complex e)\nharmonicMatPTX numPoints period delta deltaFreq ptx r2Freqs =\n  let rows = L.length r2Freqs\n  in CuMat rows (numPoints ^ 2) .\n     CuVecHost .\n     VS.fromList .\n     A.toList .\n     run1With ptx (harmonicAcc numPoints period delta deltaFreq) .\n     A.fromList (A.Z A.:. (L.length r2Freqs)) $\n     r2Freqs\n\n-- create column-major inverse harmonics\n{-# INLINE inverseHarmonicMatPTX #-}\ninverseHarmonicMatPTX ::\n     ( Storable e\n     , A.Elt (Complex e)\n     , A.Elt e\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     )\n  => Int\n  -> e\n  -> e\n  -> PTX\n  -> [(Int, Int)]\n  -> CuMat (Complex e)\ninverseHarmonicMatPTX numFreqs period delta ptx r2Positions =\n  let cols = L.length r2Positions\n  in CuMat (numFreqs ^ 2) cols .\n     CuVecHost .\n     VS.fromList .\n     A.toList .\n     run1With ptx (inverseHarmonicAcc numFreqs period delta) .\n     A.fromList (A.Z A.:. (L.length r2Positions)) $\n     r2Positions\n\n{-# INLINE inverseHarmonicMatPTX1 #-}\ninverseHarmonicMatPTX1 ::\n     ( Storable e\n     , A.Elt (Complex e)\n     , A.Elt e\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     )\n  => Int\n  -> e\n  -> e\n  -> PTX\n  -> [(Int, Int)]\n  -> CuMat (Complex e)\ninverseHarmonicMatPTX1 numFreqs period delta ptx r2Positions =\n  let rows = L.length r2Positions\n  in CuMat rows (numFreqs ^ 2) .\n     CuVecHost .\n     VS.fromList .\n     A.toList .\n     run1With ptx (inverseHarmonicAcc1 numFreqs period delta) .\n     A.fromList (A.Z A.:. (L.length r2Positions)) $\n     r2Positions\n\ncreateHarmonicMatriesGPU ::\n     ( Storable e\n     , A.Elt (Complex e)\n     , A.Elt e\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     )\n  => [PTX]\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> IO [[CuMat (Complex e)]]\ncreateHarmonicMatriesGPU ptxs numBatch numPoints numFreqs period delta deltaFreq = do\n  let idxs =\n        L.map (divideListN numBatch) . divideListN (L.length ptxs) $\n        [ (xFreq, yFreq)\n        | xFreq <- getListFromNumber numFreqs\n        , yFreq <- getListFromNumber numFreqs\n        ]\n  let output =\n        parZipWith\n          rdeepseq\n          (\\ptx -> L.map (harmonicMatPTX numPoints period delta deltaFreq ptx))\n          ptxs $\n        idxs\n  return output\n\n\ncreateInverseHarmonicMatriesGPU ::\n     ( Storable e\n     , A.Elt (Complex e)\n     , A.Elt e\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     )\n  => [PTX]\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> IO [[CuMat (Complex e)]]\ncreateInverseHarmonicMatriesGPU ptxs numBatch numPoints numFreqs period delta = do\n  let idxs =\n        L.map (divideListN numBatch) . divideListN (L.length ptxs) $\n        [ (x, y)\n        | x <- getListFromNumber numPoints\n        , y <- getListFromNumber numPoints\n        ]\n  return .\n    parZipWith\n      rdeepseq\n      (\\ptx -> L.map (inverseHarmonicMatPTX numFreqs period delta ptx))\n      ptxs $\n    idxs\n\ncomputeFourierCoefficientsR2 ::\n     ( Storable e\n     , CUBLAS (Complex e)\n     , Unbox e\n     , RealFloat e\n     , A.Elt e\n     , A.Elt (Complex e)\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     )\n  => [Int]\n  -> [PTX]\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> Int\n  -> [CuMat (Complex e)]\n  -> IO (R.Array U DIM3 (Complex e))\ncomputeFourierCoefficientsR2 deviceIDs ptxs numFreqs numPoints period delta deltaFreq numBatchR2Freqs xs = do\n  let simpsonNorm = (delta / 3) ^ 2 :+ 0\n      cols = L.foldl' (\\s mat -> s + getColsCuMat mat) 0 xs\n  harmonics <-\n    createHarmonicMatriesGPU\n      ptxs\n      numBatchR2Freqs\n      numPoints\n      numFreqs\n      period\n      delta\n      deltaFreq\n  coefs <- blockMatrixMultiply2 True deviceIDs harmonics xs\n  return .\n    fromUnboxed (Z :. cols :. numFreqs :. numFreqs) .\n    VU.map (* simpsonNorm) . VS.convert . getHostCuMat $\n    coefs\n\ncomputeFourierSeriesR2 ::\n     ( Storable e\n     , CUBLAS (Complex e)\n     , Unbox e\n     , RealFloat e\n     , A.Elt e\n     , A.Elt (Complex e)\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     )\n  => [Int]\n  -> Int\n  -> Int\n  -> e\n  -> [[CuMat (Complex e)]]\n  -> [CuMat (Complex e)]\n  -> IO (R.Array U DIM3 (Complex e))\ncomputeFourierSeriesR2 deviceIDs numFreqs numPoints period inverseHarmonics xs = do\n  let rows = L.foldl' (\\s mat -> s + getRowsCuMat mat) 0 xs\n  series <- blockMatrixMultiply1 False deviceIDs xs inverseHarmonics\n  return .\n    fromUnboxed (Z :. rows :. numPoints :. numPoints) .\n    VS.convert . getHostCuMat $\n    series\n\n\n{-# INLINE applyGaussian #-}\napplyGaussian ::\n     (R.Source s (Complex e), Unbox e, RealFloat e)\n  => e\n  -> e\n  -> R.Array s DIM3 (Complex e)\n  -> R.Array D DIM3 (Complex e)\napplyGaussian deltaFreq std arr =\n  let (Z :. _ :. numFreq :. _) = extent arr\n      freq = div numFreq 2\n      gaussianCoefficients =\n        computeUnboxedS . R.fromFunction (Z :. numFreq :. numFreq) $ \\(Z :. xFreq :. yFreq) ->\n          gaussian2D\n            (deltaFreq * (fromIntegral $ xFreq - freq))\n            (deltaFreq * (fromIntegral $ yFreq - freq))\n            std :+\n          0\n  in R.traverse2 arr gaussianCoefficients const $ \\fC fG idx@(Z :. _ :. i :. j) ->\n       fC idx * fG (Z :. i :. j)\n\n-- Stream\n{-# INLINE indexSource #-}\nindexSource :: Int -> Int -> ConduitT () [(Int, Int)] (ResourceT IO) ()\nindexSource numIndex numBatch =\n  let xs =\n        divideListN numBatch $\n        [ (xFreq, yFreq)\n        | xFreq <- getListFromNumber numIndex\n        , yFreq <- getListFromNumber numIndex\n        ]\n  in CL.sourceList xs\n\n{-# INLINE fourierCoefficientsConduit #-}\nfourierCoefficientsConduit ::\n     ( Storable e\n     , CUBLAS (Complex e)\n     , Unbox e\n     , RealFloat e\n     , A.Elt e\n     , A.Elt (Complex e)\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     , Show e\n     )\n  => [Int]\n  -> [PTX]\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> [CuMat (Complex e)]\n  -> ConduitT [(Int, Int)] (CuMat (Complex e)) (ResourceT IO) ()\nfourierCoefficientsConduit deviceIDs ptxs numPoints period delta deltaFreq xs =\n  awaitForever $ \\idx' -> do\n    let idxs = divideListN (L.length deviceIDs) idx'\n        harmonics =\n          parMap\n            rdeepseq\n            (uncurry (harmonicMatPTX numPoints period delta deltaFreq)) $\n          L.zip ptxs idxs\n    liftIO $ printCurrentTime \"\"\n    coefs <- liftIO $ blockMatrixMultiply3 False deviceIDs harmonics xs\n    yield $!! coefs\n\n{-# INLINE fourierCoefficientsSink #-}\nfourierCoefficientsSink ::\n     (Storable e, Unbox e, RealFloat e, Show e)\n  => Int\n  -> e\n  -> ConduitT (CuMat (Complex e)) Void (ResourceT IO) ((R.Array U DIM3 (Complex e)))\nfourierCoefficientsSink numR2Freqs delta = do\n  xs <- CL.consume\n  let cols = getColsCuMat . L.head $ xs\n      simpsonNorm = (delta / 3) ^ 2 :+ 0\n  return .\n    fromUnboxed (Z :. cols :. numR2Freqs :. numR2Freqs) .\n    VU.map (* simpsonNorm) .\n    VS.convert . getHostCuMat . transposeCuMat . concatCuMat $\n    xs\n\ncomputeFourierCoefficientsR2Stream ::\n     ( Storable e\n     , CUBLAS (Complex e)\n     , Unbox e\n     , RealFloat e\n     , A.Elt e\n     , A.Elt (Complex e)\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     )\n  => [Int]\n  -> [PTX]\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> Int\n  -> [CuMat (Complex e)]\n  -> IO (R.Array U DIM3 (Complex e))\ncomputeFourierCoefficientsR2Stream deviceIDs ptxs numFreqs numPoints period delta deltaFreq numBatch xs =\n  runConduitRes $\n  indexSource numFreqs numBatch .|\n  fourierCoefficientsConduit deviceIDs ptxs numPoints period delta deltaFreq xs .|\n  fourierCoefficientsSink numFreqs delta\n\n{-# INLINE fourierSeriesConduit #-}\nfourierSeriesConduit ::\n     ( Storable e\n     , CUBLAS (Complex e)\n     , Unbox e\n     , RealFloat e\n     , A.Elt e\n     , A.Elt (Complex e)\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     , Show e\n     )\n  => [Int]\n  -> [PTX]\n  -> Int\n  -> e\n  -> e\n  -> [CuMat (Complex e)]\n  -> ConduitT [(Int, Int)] (CuMat (Complex e)) (ResourceT IO) ()\nfourierSeriesConduit deviceIDs ptxs numFreqs period delta xs =\n  awaitForever $ \\idx' -> do\n    let idxs = divideListN (L.length deviceIDs) idx'\n        harmonics =\n          parMap\n            rdeepseq\n            (uncurry (inverseHarmonicMatPTX1 numFreqs period delta)) $\n          L.zip ptxs idxs\n    liftIO $ printCurrentTime \"fourierSeriesConduit\"\n    coefs <- liftIO $ blockMatrixMultiply3 False deviceIDs harmonics xs\n    yield $!! coefs\n\n{-# INLINE fourierSeriesSink #-}\nfourierSeriesSink ::\n     (Storable e, Unbox e, RealFloat e, Show e)\n  => Int\n  -> ConduitT (CuMat (Complex e)) Void (ResourceT IO) ((R.Array U DIM3 (Complex e)))\nfourierSeriesSink numPoints = do\n  xs <- CL.consume\n  let cols = getColsCuMat . L.head $ xs\n  return .\n    fromUnboxed (Z :. cols :. numPoints :. numPoints) .\n    VS.convert . getHostCuMat . transposeCuMat . concatCuMat $\n    xs\n\ncomputeFourierSeriesR2Stream ::\n     ( Storable e\n     , CUBLAS (Complex e)\n     , Unbox e\n     , RealFloat e\n     , A.Elt e\n     , A.Elt (Complex e)\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     )\n  => [Int]\n  -> [PTX]\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> Int\n  -> [CuMat (Complex e)]\n  -> IO (R.Array U DIM3 (Complex e))\ncomputeFourierSeriesR2Stream deviceIDs ptxs numFreqs numPoints period delta numBatch xs = \n  runConduitRes $\n    indexSource numPoints numBatch .|\n    fourierSeriesConduit deviceIDs ptxs numFreqs period delta xs .|\n    fourierSeriesSink numPoints\n    \n\n{-# INLINE fourierSeriesConduitAcc #-}\nfourierSeriesConduitAcc ::\n     ( A.Floating e\n     , A.Elt (Complex e)\n     , A.FromIntegral Int e\n     , Numeric (Complex e)\n     , Unbox e\n     )\n  => [PTX]\n  -> Int\n  -> e\n  -> e\n  -> A.Acc (Matrix (Complex e))\n  -> ConduitT [(Int, Int)] (VU.Vector (Complex e)) (ResourceT IO) ()\nfourierSeriesConduitAcc ptxs numFreqs period delta x =\n  awaitForever $ \\idx' -> do\n    let idxs = divideListN (L.length ptxs) idx'\n        harmonics =\n          L.map\n            (\\r2Positions ->\n               inverseHarmonicAcc2 numFreqs period delta .\n               A.fromList (A.Z A.:. L.length r2Positions) $\n               r2Positions) $\n          idxs\n    liftIO $ printCurrentTime \"fourierSeriesConduit\"\n    yield $!! blockMatrixMultiply ptxs harmonics x\n\n{-# INLINE fourierSeriesSinkAcc #-}\nfourierSeriesSinkAcc ::\n     (Unbox e)\n  => Int\n  -> Int\n  -> ConduitT (VU.Vector (Complex e)) Void (ResourceT IO) (R.Array U DIM3 (Complex e))\nfourierSeriesSinkAcc numPoints cols = do\n  xs <- CL.consume\n  computeP .\n    R.backpermute\n      (Z :. cols :. numPoints :. numPoints)\n      (\\(Z :. a :. b :. c) -> Z :. b :. c :. a) .\n    fromUnboxed (Z :. numPoints :. numPoints :. cols) . VU.concat $\n    xs\n\ncomputeFourierSeriesR2StreamAcc ::\n     ( A.Floating e\n     , A.Elt (Complex e)\n     , A.FromIntegral Int e\n     , Numeric (Complex e)\n     , Unbox e\n     )\n  => [PTX]\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> Int\n  -> Acc (Matrix (Complex e))\n  -> IO (R.Array U DIM3 (Complex e))\ncomputeFourierSeriesR2StreamAcc ptxs numFreqs numPoints cols period delta numBatch x =\n  runConduitRes $\n  indexSource numPoints numBatch .|\n  fourierSeriesConduitAcc ptxs numFreqs period delta (A.compute x) .|\n  fourierSeriesSinkAcc numPoints cols\n\n{-# INLINE fourierSeriesConduitAcc' #-}\nfourierSeriesConduitAcc' ::\n     ( A.Floating e\n     , A.Elt (Complex e)\n     , A.FromIntegral Int e\n     , Numeric (Complex e)\n     , Unbox e\n     , Prelude.Num e\n     )\n  => [PTX]\n  -> Int\n  -> e\n  -> e\n  -> A.Acc (Matrix (Complex e))\n  -> ConduitT [(Int, Int)] (VU.Vector (Complex e)) (ResourceT IO) ()\nfourierSeriesConduitAcc' ptxs numFreqs period delta x =\n  awaitForever $ \\idx' -> do\n    let idxs = divideListN (L.length ptxs) idx'\n        harmonics =\n          L.map\n            (\\r2Positions ->\n               inverseHarmonicAcc2' numFreqs period delta .\n               A.fromList (A.Z A.:. L.length r2Positions) $\n               r2Positions) $\n          idxs\n    liftIO $ printCurrentTime \"fourierSeriesConduit\"\n    yield $ blockMatrixMultiply ptxs harmonics x\n\ncomputeFourierSeriesR2StreamAcc' ::\n     ( A.Floating e\n     , A.Elt (Complex e)\n     , A.FromIntegral Int e\n     , Numeric (Complex e)\n     , Unbox e\n     , Prelude.Num e\n     )\n  => [PTX]\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> Int\n  -> Acc (Matrix (Complex e))\n  -> IO (R.Array U DIM3 (Complex e))\ncomputeFourierSeriesR2StreamAcc' ptxs numFreqs numPoints cols period delta numBatch x =\n  runConduitRes $\n  indexSource numPoints numBatch .|\n  fourierSeriesConduitAcc' ptxs numFreqs period delta (A.compute x) .|\n  fourierSeriesSinkAcc numPoints cols\n", "meta": {"hexsha": "3eb1d1bedf57c072345a86241bbe5725d91551d1", "size": 14125, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FourierMethod/FourierSeries2D.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/FourierMethod/FourierSeries2D.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/FourierMethod/FourierSeries2D.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": 27.1634615385, "max_line_length": 109, "alphanum_fraction": 0.5976637168, "num_tokens": 4275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.2977582243230572}}
{"text": "-- Copyright 2016 TensorFlow authors.\n--\n-- Licensed under the Apache License, Version 2.0 (the \"License\");\n-- you may not use this file except in compliance with the License.\n-- You may obtain a copy of the License at\n--\n--     http://www.apache.org/licenses/LICENSE-2.0\n--\n-- Unless required by applicable law or agreed to in writing, software\n-- distributed under the License is distributed on an \"AS IS\" BASIS,\n-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-- See the License for the specific language governing permissions and\n-- limitations under the License.\n\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n\nmodule TensorFlow.Gradient\n    ( GradientCompatible\n    , gradients\n    ) where\n\nimport Control.Monad (forM, zipWithM)\nimport Control.Monad.State.Strict (State, evalState, gets, modify)\nimport Data.ByteString (ByteString)\nimport Data.Complex (Complex)\nimport Data.Default (def)\nimport Data.Int (Int32, Int64)\nimport Data.Foldable (foldlM)\nimport Data.List (foldl', sortBy)\nimport Data.Map.Strict (Map)\nimport Data.Maybe (fromMaybe, maybeToList, mapMaybe)\nimport Data.Ord (comparing)\nimport Data.ProtoLens.TextFormat (showMessage)\nimport Data.Set (Set)\nimport Data.Text (Text)\nimport Data.Tuple (swap)\nimport Lens.Family2 (Lens', view, (&), (^.), (.~), (%~))\nimport Lens.Family2.State.Strict (uses)\nimport Lens.Family2.Stock (at, intAt)\nimport Lens.Family2.Unchecked (lens, iso)\nimport Prelude hiding (sum)\nimport Text.Printf (printf)\nimport qualified Data.Graph.Inductive.Basic as FGL\nimport qualified Data.Graph.Inductive.Graph as FGL\nimport qualified Data.Graph.Inductive.PatriciaTree as FGL\nimport qualified Data.Graph.Inductive.Query.DFS as FGL\nimport qualified Data.IntMap.Strict as IntMap\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Set as Set\nimport qualified Data.Text as Text\n\nimport qualified TensorFlow.GenOps.Core as CoreOps\nimport TensorFlow.Build\n    ( MonadBuild\n    , Build\n    , build\n    , renderedNodeDefs\n    , opDef\n    , opAttr\n    , opInputs\n    )\nimport TensorFlow.BuildOp\nimport TensorFlow.Ops\n    ( addN\n    , broadcastGradientArgs\n    , expandDims\n    , fill\n    , matMul\n    , matMul'\n    , reducedShape\n    , reluGrad\n    , reshape\n    , scalar\n    , shape\n    , softmaxCrossEntropyWithLogits\n    , sum\n    , scalarize\n    , vector\n    , zerosLike\n    )\nimport TensorFlow.Output\n    ( NodeName(..)\n    , Output(..)\n    , OutputIx(..)\n    , outputIndex\n    )\nimport TensorFlow.Tensor\n    ( Tensor(..)\n    , Value\n    , render\n    , expr\n    , Rendered\n    , tensorNodeName\n    , renderedOutput\n    , renderValue\n    , ToTensor(..)\n    )\nimport TensorFlow.Types (Attribute, OneOf, TensorType, attrLens)\nimport Proto.Tensorflow.Core.Framework.NodeDef\n    (NodeDef, attr, input, op, name)\n\ntype GradientCompatible a =\n    -- TODO(fmayle): MaxPoolGrad doesn't support Double for some reason.\n    (Num a, OneOf '[ Float, Complex Float, Complex Double ] a)\n\n-- TODO(fmayle): Support control flow.\n-- TODO(fmayle): Support gate_gradients-like option to avoid race conditions.\n-- TODO(fmayle): Do we need to consider control inputs? See _PendingCount in\n-- tensorflow/python/ops/gradients.py.\n-- TODO(fmayle): Maybe store the gradient functions and numOutputs on the OpDef.\n\n\n-- | Gradient of @y@ w.r.t. each element of @xs@.\ngradients :: forall a v1 t m . ( MonadBuild m\n                               , Rendered t\n                               , ToTensor t\n                               , GradientCompatible a\n                               )\n          => Tensor v1 a  -- ^ The output of the graph.\n          -> [t a]        -- ^ Tensors for which gradients are computed.\n          -> m [Tensor Value a]\ngradients y xs = build $ do\n    -- The gradients are computed using \"reverse accumulation\", similarly to\n    -- what is described here:\n    -- https://en.wikipedia.org/wiki/Automatic_differentiation#The_chain_rule.2C_forward_and_reverse_accumulation\n    --\n    -- The code is summarised as follows:\n    --\n    -- 1. Create an fgl graph of the relevant nodes (ops) and edges (tensors).\n    -- 2. Initialize the gradient of y to 1 (∂y/∂y = 1) and the rest of tensor's\n    --    gradients to nothing.\n    -- 3. Process the nodes in reverse topological order (i.e. each node comes\n    --    after all of its outputs so that the output gradients for a node have\n    --    been completely calculated before it is processed):\n    --      a. Record the gradient for each of the node's output tensors (∂y/∂w\n    --         for each output tensor w).\n    --      b. Calculate the gradient of y w.r.t. each of the node's input\n    --         tensors using the gradients of the node's output tensors.\n    --\n    --         Written differently, for each output tensor w and input tensor v:\n    --           ∂y/∂w = ...            (calculated in previous steps)\n    --           ∂w/∂v = ...            (op specific)\n    --           ∂y/∂v = ∂y/∂w * ∂w/∂v  (technically, if tensor v is an input\n    --                                   to multiple nodes, then this is only\n    --                                   part of ∂y/∂v)\n    --\n    -- 4. Lookup the recorded gradient for each x in xs.\n\n    y' <- renderValue y\n    let yName = tensorNodeName y'\n    yOne <- render $ fill (shape y') (scalar 1)\n    -- TODO(fmayle): Move this into Build.hs and call it unsafeNodeDefFromName?\n    nodeDefLookup :: (NodeName -> NodeDef) <- uses renderedNodeDefs $\n        (\\f x -> fromMaybe (error $ \"no NodeDef found for \" ++ show x) (f x))\n        . flip Map.lookup\n    let (gr, nodeMap) = createGraph yName nodeDefLookup\n    -- Set gradient of y to one.\n    -- TODO: nicer\n    let initPending :: Map.Map FGL.Node (PendingGradients a)\n            = Map.empty & (at (nodeMap Map.! yName)\n                                . nonEmpty\n                                . outputIxAt (outputIndex $ renderedOutput y')\n                                . nonEmpty\n                                .~ [yOne]\n                                )\n    -- Calculate the gradients of y w.r.t. each node in the graph.\n    gradientMap <- graphGrads gr initPending\n    -- Lookup the gradients for each x.\n    forM xs $ \\x ->\n        let Output i xName = renderedOutput x\n        in maybe (render $ zerosLike $ toTensor x) return $ do\n            n <- nodeMap ^. at xName\n            gradientMap ^. at n . nonEmpty . outputIxAt i\n\noutputIxAt :: OutputIx -> Lens' (IntMap.IntMap v) (Maybe v)\noutputIxAt = intAt . unOutputIx\n\n-- | Incomplete gradients of a node's outputs.\n--\n-- The lists represent partial sums. The key is an OutputIx sans newtype.\ntype PendingGradients a = IntMap.IntMap [Tensor Value a]\n\n-- | Gradients of a node's outputs. The key is an OutputIx sans newtype.\n-- TODO: precache the rendering?\ntype Gradients a = IntMap.IntMap (Tensor Value a)\n\n-- | Graph of TensorFlow operations.\ntype Graph = FGL.Gr NodeDef EdgeLabel\n\n-- | Data associated with an edge.\n--\n-- Pair of\n--   1. Output index of a tensor from the source node.\n--   2. Input index that the tensor connects to on the destination node.\ntype EdgeLabel = (OutputIx, OutputIx)\n\n\n-- | State used for calculating gradients.\ndata GradientsState a = GradientsState\n                      { _gradientsPending :: !(Map FGL.Node (PendingGradients a))\n                      , _gradientsResult  :: !(Map FGL.Node (Gradients a))\n                      }\n\ngradientsPending :: Lens' (GradientsState a) (Map FGL.Node (PendingGradients a))\ngradientsPending = lens _gradientsPending (\\x y -> x { _gradientsPending = y })\n\ngradientsResult :: Lens' (GradientsState a) (Map FGL.Node (Gradients a))\ngradientsResult = lens _gradientsResult (\\x y -> x { _gradientsResult = y })\n\n\n-- TODO(fmayle): Use something like Data.List.Safe.\n-- | Safe version of (!!).\nsafeIndex :: [a] -> Int -> Maybe a\n_      `safeIndex` n | n < 0 = Nothing\n[]     `safeIndex` _         = Nothing\n(x:_)  `safeIndex` 0         = Just x\n(_:xs) `safeIndex` n         = xs `safeIndex` (n-1)\n\n-- Copy of http://hackage.haskell.org/package/lens-3.9.0.2/docs/Control-Lens-Iso.html#v%3anon\nanon :: a -> (a -> Bool) -> Lens' (Maybe a) a\nanon a p = iso (fromMaybe a) go where\n  go b | p b       = Nothing\n       | otherwise = Just b\n\nnon :: Eq a => a -> Lens' (Maybe a) a\nnon a = anon a (a==)\n\n-- | Lens that defaults Nothing to mempty.\nnonEmpty :: (Monoid (t v), Foldable t) => Lens' (Maybe (t v)) (t v)\nnonEmpty = anon mempty null\n\n-- TODO: strictness (e.g., foldlM')\n\n-- | Calculate the gradients for every node in a graph.\ngraphGrads :: forall a. GradientCompatible a\n           => Graph\n           -> Map FGL.Node (PendingGradients a)\n           -- ^ Initial gradients (usually just 1 for the node of interest).\n           -> Build (Map FGL.Node (Gradients a))\ngraphGrads gr initPending = view gradientsResult <$> foldlM go initState nodeOrder\n  where\n    initState = GradientsState initPending Map.empty\n    -- Reverse topological sort.\n    -- TODO(fmayle): Filter out nodes that are not successors of any x in xs to\n    -- avoid calculating gradients that won't be used.\n    nodeOrder = FGL.topsort $ FGL.grev gr\n    go :: GradientsState a -> Int -> Build (GradientsState a)\n    go state node = do\n        -- Aggregate the accumulated gradients for this node.\n        outputGrads <-\n                sumPendingGradient (state ^. gradientsPending . at node . nonEmpty)\n        if null outputGrads\n           then pure state\n           else do\n              let ctx = FGL.context gr node\n              inputGrads <- calculateInputGrads ctx outputGrads gr\n              -- Calculate the gradients for each of the node's inputs.\n              let nextState = state & gradientsResult %~ Map.insert node outputGrads\n              pure $ updatePendingGradients ctx inputGrads nextState\n\n-- | Reduce accumulated gradients for each output to one Tensor.\nsumPendingGradient :: GradientCompatible a\n                   => PendingGradients a -> Build (Gradients a)\nsumPendingGradient = sequence . IntMap.mapMaybe f\n  where\n    f [] = Nothing\n    f [x] = Just (pure x)\n    f xs = Just (render $ addN xs)\n\n\n-- | Calculate the gradients of a node's input tensors.\n--\n-- This is mostly just a wrapper around opGrad.\ncalculateInputGrads :: forall a. GradientCompatible a\n                    => FGL.Context NodeDef EdgeLabel\n                    -> Gradients a  -- ^ Output gradients of the node.\n                    -> Graph\n                    -> Build [Maybe (Tensor Value a)]\ncalculateInputGrads (inputEdges, _, nodeDef, _) outputGrads gr = do\n    fullOutGrads <- fullOutputGrads (numOutputs nodeDef) (nodeDefName nodeDef)\n                        outputGrads\n    traverse (traverse render) $ opGrad (nodeDef ^. op) nodeDef inputTensors fullOutGrads\n  where\n    -- Create a tensor from an edge (technically an Output, but it seems less\n    -- confusing to refer to it as a tensor here).\n    edgeToTensor :: (EdgeLabel, FGL.Node) -> Output\n    edgeToTensor ((i, _), n) =\n        case FGL.lab gr n of\n            Just edgeNodeDef -> Output i (NodeName $ edgeNodeDef ^. name)\n            Nothing -> error $ \"calculateInputGrads: missing input node for \"\n                               ++ Text.unpack (nodeDef ^. name)\n    -- Input tensors, sorted by input index.\n    inputTensors = map edgeToTensor $ sortBy (comparing (snd . fst)) inputEdges\n\n-- | Convert a Map of gradients to a list, with zeros for missing outputs.\nfullOutputGrads :: (TensorType a, Num a)\n                => OutputIx  -- ^ Number of outputs.\n                -> NodeName\n                -> Gradients a\n                -> Build [Tensor Value a]\nfullOutputGrads n o gs =\n    mapM (\\i -> maybe (render $ zero i) return (gs ^. outputIxAt i)) [0..n-1]\n  where\n    -- A tensor of zeros with the same shape as the i'th output.\n    zero i = zerosLike $ toT (Output i o)\n\n\n-- | Update the pending gradients of a node's inputs.\nupdatePendingGradients :: forall a. (TensorType a, Num a)\n                       => FGL.Context NodeDef EdgeLabel\n                       -> [Maybe (Tensor Value a)]\n                       -- ^ Gradient of each input tensor.\n                       -> GradientsState a\n                       -> GradientsState a\nupdatePendingGradients (inputEdges, _, nodeDef, _) inputGrads initState =\n    foldl' go initState inputEdges\n  where\n    go :: GradientsState a -> (EdgeLabel, FGL.Node) -> GradientsState a\n    go state ((outIndex, OutputIx inIndex), node) =\n        case maybeGradient of\n            Nothing -> state\n            Just g ->\n                -- Add to the list of pending gradients for this tensor.\n                state & gradientsPending\n                      . at node\n                      . nonEmpty\n                      . outputIxAt outIndex\n                      . nonEmpty\n                      %~ (g:)\n      where\n        badSizeErr = error $ printf \"updatePendingGradients: bad input index \\\n                                    \\%d for inputGrads of length %d in %s\"\n                                    inIndex (length inputGrads)\n                                    (show (nodeDef ^. name))\n        maybeGradient = fromMaybe badSizeErr (safeIndex inputGrads inIndex)\n\n\n-- | Create a graph that includes a node and its transitive dependencies.\ncreateGraph :: NodeName -> (NodeName -> NodeDef)\n            -> (Graph, Map NodeName FGL.Node)\ncreateGraph nodeName nodeDefLookup = (FGL.nmap nodeDefLookup graph, nodeMap)\n  where\n    -- Parse a tensor name.\n    parseTensorName :: Text -> Maybe (NodeName, OutputIx)\n    parseTensorName n\n        | Text.null n        = error \"parseTensorName: empty name\"\n        | Text.head n == '^' = Nothing  -- Control edge\n        | otherwise          =\n            let (nm, indexStr) = Text.breakOn \":\" n\n                index | Text.null indexStr = 0\n                      | otherwise = read $ Text.unpack $ Text.tail indexStr\n            in Just (NodeName nm, OutputIx index)\n\n    -- Build a map from node name to outward edges.\n    --\n    -- The state is the set of visited nodes.\n    collect :: Maybe (NodeName, OutputIx, OutputIx)\n            -> NodeName\n            -> State (Set NodeName)\n                     (Map NodeName [(NodeName, OutputIx, OutputIx)])\n    collect outgoingEdge nm = do\n        let nextLookup = Map.singleton nm (maybeToList outgoingEdge)\n        seen <- gets (Set.member nm)\n        modify (Set.insert nm)\n        if seen\n            then pure nextLookup\n            else do\n                let inputs = nodeDefLookup nm ^. input\n                    recurse inIndex (parentName, outIndex) =\n                        collect (Just (nm, outIndex, inIndex)) parentName\n                subEdgeLookups <-\n                    zipWithM recurse [0..] $ mapMaybe parseTensorName inputs\n                pure $ Map.unionsWith (++) (nextLookup:subEdgeLookups)\n\n    edgeLookup = evalState (collect Nothing nodeName) Set.empty\n    -- Associate an ID with each node name.\n    nodeMap = Map.fromList $ zip (Map.keys edgeLookup) [0..]\n    -- Create the graph.\n    graph = FGL.mkGraph (swap <$> Map.toList nodeMap)\n                        [ (nodeMap Map.! n, nodeMap Map.! m, (i, j))\n                        | (n, edges) <- Map.toList edgeLookup\n                        , (m, i, j) <- edges\n                        ]\n\n-- | Function to compute the gradient of y w.r.t. each input.\n--\n-- Let y be an arbitrary tensor\n-- and [w_0, ..., w_n] be the output tensors of a node\n-- and [v_0, ..., v_n] be the input tensors of the same node.\n--\n-- Given [∂y/∂w_0, ..., ∂y/∂w_n] and [v_0, ..., v_n], a GradientFunc computes\n-- [∂y/∂v_0, ..., ∂y/∂v_n] for a particular op type.\n--\n-- A Nothing gradient is equivalent to zero (but allows for short circuiting\n-- computation when all the gradients for something are Nothing).\ntype GradientFunc a = NodeDef\n                    -> [Output]\n                    -- ^ Input tensors.\n                    -> [Tensor Value a]\n                    -- ^ Gradient of y w.r.t. each output tensor.\n                    -> [Maybe (Tensor Build a)]\n                    -- ^ Gradient of y w.r.t. each input tensor.\n\n\n-- TODO(fmayle): Assert the type is correct.\n-- | Create a Tensor from an Output.\ntoT :: Output -> Tensor Build a\ntoT = Tensor . pure\n\n\n-- | Wrapper around `TensorFlow.GenOps.Core.slice` that builds vectors from scalars for\n-- simple slicing operations.\nflatSlice :: forall v1 t . TensorType t\n         => Tensor v1 t    -- ^ __input__\n         -> Int32          -- ^ __begin__: specifies the offset into the first dimension of\n                           -- 'input' to slice from.\n         -> Int32          -- ^ __size__: specifies the number of elements of the first dimension\n                           -- of 'input' to slice. If size is -1, all remaining elements in the dimension\n                           -- are included in the slice (i.e. this is equivalent to setting\n                           -- size = input.dim_size(0) - begin).\n         -> Tensor Build t -- ^ __output__\nflatSlice t begin size = CoreOps.slice t (vector [begin]) (vector [size])\n\nnodeDefName :: NodeDef -> NodeName\nnodeDefName = NodeName . view name\n\n-- | Gradient helper for binary component wise operations\n-- See https://github.com/tensorflow/tensorflow/blob/e9de087fa7f59c39bbe12ac2c83c5547c83f746c/tensorflow/core/ops/math_grad.cc#L329\ngradForBinaryCwise :: ( OneOf '[ Int32, Int64, Float, Double, Complex Float, Complex Double ] t\n                      )\n                   => (Tensor v1 t, Tensor v1 t)\n                   -> (Tensor v1 t, Tensor v1 t)\n                   -> [ Maybe (Tensor Build t) ]\ngradForBinaryCwise (x, gx) (y, gy) =\n    [ Just dx\n    , Just dy ]\n  where\n    dx = reshape (sum gx rx) sx\n    dy = reshape (sum gy ry) sy\n    sx = shape x\n    sy = shape y\n    (rx, ry) = broadcastGradientArgs sx sy\n\n-- | The gradient function for an op type.\n--\n-- These implementations should match their python counterparts in:\n-- third_party/tensorflow/python/ops/*_grad.py\nopGrad :: forall a . GradientCompatible a => Text -> GradientFunc a\n\nopGrad \"Abs\" _ [toT -> x] [dz] = [Just $ expr dz * signum x]\nopGrad \"Neg\" _ [_] [dz] = [Just $ negate $ expr dz]\nopGrad \"Relu\" _ [toT -> x] [dz] = [Just $ reluGrad dz x]\nopGrad \"ReluGrad\" _ [_, toT -> x ] [dz] = [Just $ reluGrad dz x, Just $ CoreOps.zerosLike x]\n\nopGrad \"Concat\" _ _ix [dy]\n    -- Concat concatenates input tensors\n    --   x1 of shape s1 = [k1, ..., ki_1, ..., kn]\n    --   x2 of shape s2 = [k1, ..., ki_2, ..., kn]\n    --    .           .     .          .        .\n    --    .           .     .          .        .\n    --    .           .     .          .        .\n    --   xm of shape sm = [k1, ..., ki_m, ..., kn]\n    --  along dimension i to an output tensor\n    --   y  of shape sy = [k1, ..., k, ..., kn]\n    --  where k = sum ki = sum [ki_1,...,ki_m]\n    --\n    --  The incoming gradient dy from backpropagation is\n    --   simply forwarded split across input tensors yielding dx.\n    --   Forwarded gradients have shapes s = [s1, ..., sm].\n    | m == 1    = Nothing : [Just $ expr dy]\n    | otherwise = Nothing : map Just (dx `reshapeZip` s)\n  where\n    reshapeZip = zipWith reshape\n    dx = CoreOps.splitV (fromIntegral m) dy ki _i\n    s  :: [Tensor Build Int32]\n    s  = map shape x\n    x  :: [Tensor Build a]\n    x  = map toT $ tail _ix\n    -- i: concat dimension. Adjusted modulo n to handle negative indices.\n    _i = toT (head _ix) `CoreOps.floorMod` n\n    i  = reshape _i $ vector [1 :: Int32]\n    -- sizes along concatenated dimension\n    ki :: Tensor Build Int32\n    ki = CoreOps.concat 0 $ map (\\t -> CoreOps.slice t i $ vector [1 :: Int32]) s\n    m  = length x\n    n  = CoreOps.rank (head x)\n\nopGrad \"Square\" _ [toT -> x] [dz] =\n    -- TODO(fmayle): Handle complex numbers.\n    -- TODO(fmayle): The python code makes dz a control dependency of the 2*x\n    -- (for performance reasons?). Will need to put these functions in the Build\n    -- monad to replicate that.\n    [Just $ dz `CoreOps.mul` (2 * x)]\n\nopGrad \"Gather\" _ [toT -> x, toT -> indices] [dz] =\n    -- TODO(fmayle): The python version uses a better performance implementation\n    -- when the shape is known without having to run the graph.\n    -- TODO(fmayle): We shouldn't convert the result to a dense tensor. Sparse\n    -- tensor support will require some thinking.\n    [ Just $ CoreOps.unsortedSegmentSum values indices' numRows\n    , Nothing\n    ]\n  where\n    -- TODO(gnezdo): Use colocateWith but it requires Build monad.\n    denseShape = shape (x :: Tensor Build a)\n    numRows = scalarize $ flatSlice denseShape 0 1\n    valuesShape = CoreOps.concat 0 [ allDimensions\n                                   , flatSlice denseShape 1 (-1)\n                                   ]\n    values = reshape dz valuesShape\n    -- TODO(fmayle): This could be either Int32 or Int64.\n    indices' = reshape indices allDimensions :: Tensor Build Int32\n\nopGrad \"Max\" _ [toT -> x, toT -> indices] [dz] =\n    [Just $ indicators `CoreOps.div` numSelected * dz', Nothing]\n  where\n    sx = shape (x :: Tensor Build a)\n    outputShapeKeptDims = reducedShape sx (indices :: Tensor Build Int32)\n    y = CoreOps.max x indices\n    y' = reshape y outputShapeKeptDims\n    dz' = reshape dz outputShapeKeptDims\n    indicators = CoreOps.cast $ CoreOps.equal y' x\n    numSelected = reshape (sum indicators indices) outputShapeKeptDims\n\n-- Min and Max have identical gradient implementations.\nopGrad \"Min\" u v w = opGrad \"Max\" u v w\n\n-- Element wise maximum gradient\n-- See https://github.com/tensorflow/tensorflow/blob/e9de087fa7f59c39bbe12ac2c83c5547c83f746c/tensorflow/core/ops/math_grad.cc#L473\nopGrad \"Maximum\" _ [toT -> x, toT -> y] [dz] =\n    gradForBinaryCwise (x, gx) (y, gy)\n  where\n    xmask = CoreOps.greaterEqual x y\n    gx = CoreOps.select xmask dz (CoreOps.zerosLike dz)\n    gy = CoreOps.select (CoreOps.logicalNot xmask) dz (CoreOps.zerosLike dz)\n\nopGrad \"Sum\" _ [toT -> x, toT -> indices] [dz] =\n    [ Just $ CoreOps.tile grad tileScaling, Nothing ]\n  where\n    -- TODO(gnezdo): Implement the fast-path from math_grad._SumGrad.\n    sx = shape (x :: Tensor Build a)\n    outputShapeKeptDims = reducedShape sx (indices :: Tensor Build Int32)\n    tileScaling = safeShapeDiv sx outputShapeKeptDims\n    grad = reshape dz outputShapeKeptDims\n\nopGrad \"Mean\" u v@[toT -> x, _] w =\n    [Just $ dz `CoreOps.div` CoreOps.cast factor, Nothing]\n  where\n    [Just dz, Nothing] = opGrad \"Sum\" u v w\n    inputShape = shape (x :: Tensor Build a)\n    outputShape = shape (dz :: Tensor Build a)\n    -- TODO(fmayle): Add fast path when shape is known.\n    inputSize = CoreOps.prod inputShape $ rangeOfRank inputShape\n    outputSize = CoreOps.prod outputShape $ rangeOfRank outputShape\n    factor = safeShapeDiv inputSize outputSize\n\nopGrad \"Add\" _ [toT -> x, toT -> y] [dz] =\n    [ Just $ reshape (sum dz rx) sx\n    , Just $ reshape (sum dz ry) sy ]\n  where\n    sx = shape (x :: Tensor Build a)\n    sy = shape (y :: Tensor Build a)\n    (rx, ry) = broadcastGradientArgs sx sy\n\n-- Copies the gradients to all inputs\n-- Not broadcasting\nopGrad \"AddN\" _ inputs [dz] =\n    map ((const . Just . expr) dz) inputs\n\nopGrad \"Sub\" u v w =\n    [Just x, Just (-y)]\n  where\n    [Just x, Just y] = opGrad \"Add\" u v w\n\nopGrad \"SoftmaxCrossEntropyWithLogits\" _ [toT -> x, toT -> y] [dz, _] =\n    [ Just $ expandDims dz (-1) * snd (softmaxCrossEntropyWithLogits x y)\n    , Nothing ]\n\nopGrad \"Mul\" _ [toT -> x, toT -> y] [dz] =\n    -- TODO(fmayle): Handle complex numbers.\n    [ Just $ reshape (sum (dz `CoreOps.mul` y) rx) sx\n    , Just $ reshape (sum (x `CoreOps.mul` dz) ry) sy ]\n  where\n    sx = shape (x :: Tensor Build a)\n    sy = shape (y :: Tensor Build a)\n    (rx, ry) = broadcastGradientArgs sx sy\n\nopGrad \"Div\" _ [toT -> x, toT -> y] [dz] =\n    -- TODO(fmayle): Handle complex numbers.\n    -- TODO(gnezdo): Provide Fractional instance and use '/' instead of div.\n    [ Just $ reshape (sum (dz `CoreOps.div` y) rx) sx\n    , Just $ reshape (sum (dz `CoreOps.mul` (negate x `CoreOps.div` (y * y)))\n                         ry)\n                sy\n    ]\n  where\n    sx = shape (x :: Tensor Build a)\n    sy = shape (y :: Tensor Build a)\n    (rx, ry) = broadcastGradientArgs sx sy\n\nopGrad \"MatMul\" nodeDef [toT -> x, toT -> y] [dz] =\n    let transposeA = lookupAttr nodeDef \"transpose_a\"\n        transposeB = lookupAttr nodeDef \"transpose_b\"\n        transAttrs a b =\n            (opAttr \"transpose_a\" .~ a) . (opAttr \"transpose_b\" .~ b)\n    in case (transposeA, transposeB) of\n       (False, False) ->\n           [ Just $ matMul' (transAttrs False True) dz y\n           , Just $ matMul' (transAttrs True False) x dz]\n       (False, True) ->\n           [ Just $ matMul dz y\n           , Just $ matMul' (transAttrs True False) dz x]\n       (True, False) ->\n           [ Just $ matMul' (transAttrs False True) y dz\n           , Just $ matMul x dz]\n       (True, True) ->\n           [ Just $ matMul' (transAttrs True True) y dz\n           , Just $ matMul' (transAttrs True True) dz x]\n\nopGrad \"Transpose\" _ [_, toT -> p] [dz] =\n    [ Just $ CoreOps.transpose dz\n            (CoreOps.invertPermutation p :: Tensor Build Int32)\n    , Nothing\n    ]\n\nopGrad \"Conv2D\" nodeDef [toT -> x, toT -> y] [dz] =\n    [ Just $ CoreOps.conv2DBackpropInput'\n                ((opAttr \"strides\" .~ strides)\n                    . (opAttr \"padding\" .~ padding)\n                    . (opAttr \"use_cudnn_on_gpu\" .~ useCudnnOnGpu)\n                    . (opAttr \"data_format\" .~ dataFormat))\n                (shape x) y dz\n    , Just $ CoreOps.conv2DBackpropFilter'\n                ((opAttr \"strides\" .~ strides)\n                    . (opAttr \"padding\" .~ padding)\n                    . (opAttr \"use_cudnn_on_gpu\" .~ useCudnnOnGpu)\n                    . (opAttr \"data_format\" .~ dataFormat))\n                x (shape y) dz\n    ]\n  where\n    strides = lookupAttr nodeDef \"strides\" :: [Int64]\n    padding = lookupAttr nodeDef \"padding\" :: ByteString\n    useCudnnOnGpu = lookupAttr nodeDef \"use_cudnn_on_gpu\" :: Bool\n    dataFormat = lookupAttr nodeDef \"data_format\" :: ByteString\n\nopGrad \"Conv2DBackpropInput\" nodeDef [_, toT -> x, toT -> y] [dz] =\n    [ Nothing\n    , Just $ CoreOps.conv2DBackpropFilter'\n                ((opAttr \"strides\" .~ strides)\n                    . (opAttr \"padding\" .~ padding)\n                    . (opAttr \"use_cudnn_on_gpu\" .~ useCudnnOnGpu)\n                    . (opAttr \"data_format\" .~ dataFormat))\n                dz (shape x) y\n    , Just $ CoreOps.conv2D'\n                ((opAttr \"strides\" .~ strides)\n                    . (opAttr \"padding\" .~ padding)\n                    . (opAttr \"use_cudnn_on_gpu\" .~ useCudnnOnGpu)\n                    . (opAttr \"data_format\" .~ dataFormat))\n                dz x\n    ]\n  where\n    strides = lookupAttr nodeDef \"strides\" :: [Int64]\n    padding = lookupAttr nodeDef \"padding\" :: ByteString\n    useCudnnOnGpu = lookupAttr nodeDef \"use_cudnn_on_gpu\" :: Bool\n    dataFormat = lookupAttr nodeDef \"data_format\" :: ByteString\n\nopGrad \"MaxPool\" nodeDef [toT -> x] [dz] =\n    [ Just $ CoreOps.maxPoolGrad'\n                ((opAttr \"ksize\" .~ ksize)\n                    . (opAttr \"strides\" .~ strides)\n                    . (opAttr \"padding\" .~ padding)\n                    . (opAttr \"data_format\" .~ dataFormat))\n                x output dz\n    ]\n  where\n    output :: Tensor Build a\n    output = toT $ Output 0 (nodeDefName nodeDef)\n    ksize = lookupAttr nodeDef \"ksize\" :: [Int64]\n    strides = lookupAttr nodeDef \"strides\" :: [Int64]\n    padding = lookupAttr nodeDef \"padding\" :: ByteString\n    dataFormat = lookupAttr nodeDef \"data_format\" :: ByteString\n\nopGrad \"Reshape\" _ [toT -> x, _] [dz] =\n    [Just $ reshape dz $ shape (x :: Tensor Build a), Nothing]\n\nopGrad \"OneHot\" _ _ _ = [Nothing, Nothing, Nothing, Nothing]\nopGrad \"TruncatedNormal\" _ _ _ = [Nothing]\n\nopGrad \"RefIdentity\" _ _ [dz] = [Just $ expr dz]\nopGrad \"Cast\" nodeDef _ [dz] = [Just reverseCast]\n  where\n    -- TODO(gnezdo): too permissive, python only allows float types as src_type.\n    reverseCast =\n        pureOp [] $ pure (opDef \"Cast\"\n                 & opAttr \"DstT\" .~ (lookupAttr nodeDef \"SrcT\" :: ByteString)\n                 & opAttr \"SrcT\" .~ (lookupAttr nodeDef \"DstT\" :: ByteString)\n                 & opInputs .~ [renderedOutput dz])\n\nopGrad \"DynamicStitch\" nodeDef inputs [dz] =\n    replicate halfLen Nothing ++ valuesGrads\n  where\n    halfLen =\n        let len = length inputs\n            half = len `div` 2\n        in if 2 * half == len\n           then half\n           else error (\"Uneven input size \" ++ show (len, showMessage nodeDef))\n    valuesGrads = [ Just $ CoreOps.gather dz (toT idx :: Tensor Build Int32)\n                  | idx <- take halfLen inputs\n                  ]\n\nopGrad \"DynamicPartition\" nodeDef [toT -> xs, toT -> indices] dz =\n    [ Just reconstructed, Nothing ]\n  where\n    reconstructed = CoreOps.reshape stitched\n                    (CoreOps.shape (xs :: Tensor Build a) :: Tensor Build Int32)\n    stitched = CoreOps.dynamicStitch partitionedIndices dz\n    partitionedIndices = CoreOps.dynamicPartition np originalIndices indices\n    np = lookupAttr nodeDef \"num_partitions\" :: Int64\n    originalIndices =\n        CoreOps.reshape (CoreOps.range 0 (CoreOps.size indices) 1) prefixShape\n    prefixShape = shapeInt32 indices\n    shapeInt32 t = CoreOps.shape t :: Tensor Build Int32\n\nopGrad \"Select\" _ [toT -> c, toT -> x, _] [dz] =\n    [ Nothing\n    , Just $ CoreOps.select c dz zeros\n    , Just $ CoreOps.select c zeros dz\n    ]\n  where zeros = CoreOps.zerosLike x\n\n-- TODO(gnezdo): Unlike Python, no control dependency on dz.\nopGrad \"Log\" _ [toT -> x] [dz] = [ Just $ dz `CoreOps.mul` CoreOps.inv x ]\n-- TODO(gnezdo): Reuse the output instead of doing another exp,\n-- though, it is probably CSE'd away anyway.\nopGrad \"Exp\" _ [toT -> x] [dz] = [ Just $ dz `CoreOps.mul` CoreOps.exp x ]\nopGrad \"SparseSegmentSum\" _ [toT -> x, toT -> y, toT -> t] [dz] =\n    [ Just $ CoreOps.unsortedSegmentSum\n             (CoreOps.gather dz (t :: Tensor Build Int32))\n             (y :: Tensor Build Int32) inputRows\n    , Nothing\n    , Nothing\n    ]\n  where inputRows = flatSlice (shape (x :: Tensor Build a)) 0 1\n\nopGrad \"LabelClasses\" _ _ _ = [Nothing, Nothing]\nopGrad \"LabelWeights\" _ _ _ = [Nothing]\nopGrad \"Size\" _ _ _ = [Nothing]\n\n-- TODO (jcberentsen): Python implementation uses set_shape for\n-- static shape inference, which is unsupported.\n-- TODO: implement support for static shape inference\nopGrad \"Tile\" _ [toT -> x, toT -> multiples] [dz] =\n    [Just inputGrad, Nothing]\n  where\n    inputGrad = sum reshapedDz axes\n    inputShape = shape (x :: Tensor Build a)\n    packed = CoreOps.pack [multiples, inputShape]\n    perm = vector [1, 0 :: Int32]\n    splitShape = CoreOps.reshape (CoreOps.transpose packed perm) allDimensions\n    axes = CoreOps.range 0 (CoreOps.size splitShape) (2 :: Tensor Build Int32)\n    reshapedDz = CoreOps.reshape dz splitShape\n\nopGrad \"ZerosLike\" _ _ _ = [Nothing]\nopGrad \"Fill\" _ _ [dz] = [Nothing, Just $ sum dz rx]\n  where\n    rx = rangeOfRank dz\n\n-- Treat read ops as an identity function on the variable. This allows us to\n-- take gradients w.r.t. to the variable handle instead of the result of a read\n-- op. If a variable is read multiple times, the gradients will propagate back\n-- through each read.\nopGrad \"ReadVariableOp\" _ _ [dz] = [Just $ expr dz]\n\n-- TODO(fmayle): These can go away if we properly prune the graph.\nopGrad \"Const\" _ _ _ = [Nothing, Nothing]\nopGrad \"Placeholder\" _ _ _ = []\nopGrad \"VarHandleOp\" _ _ _ = []\nopGrad \"Variable\" _ _ _ = []\n\nopGrad n nodeDef ins grads =\n    error $ \"no gradient implemented for \" ++\n            show (n, length ins, length grads, showMessage nodeDef, ins)\n\n-- | The number of outputs for an op type.\nnumOutputs :: NodeDef -> OutputIx\nnumOutputs o =\n    case o ^. op of\n        \"Abs\" -> 1\n        \"Add\" -> 1\n        \"AddN\" -> 1\n        \"Cast\" -> 1\n        \"Const\" -> 1\n        \"Concat\" -> 1\n        \"Conv2D\" -> 1\n        \"Conv2DBackpropInput\" -> 1\n        \"Div\" -> 1\n        \"DynamicStitch\" -> 1\n        \"DynamicPartition\" ->\n            fromIntegral (lookupAttr o \"num_partitions\" :: Int64)\n        \"Exp\" -> 1\n        \"Gather\" -> 1\n        \"LabelClasses\" -> 1\n        \"LabelWeights\" -> 1\n        \"Log\" -> 1\n        \"MatMul\" -> 1\n        \"Max\" -> 1\n        \"Maximum\" -> 1\n        \"MaxPool\" -> 1\n        \"Mean\" -> 1\n        \"Min\" -> 1\n        \"Mul\" -> 1\n        \"Neg\" -> 1\n        \"Placeholder\" -> 1\n        \"OneHot\" -> 1\n        \"ReadVariableOp\" -> 1\n        \"RefIdentity\" -> 1\n        \"Relu\" -> 1\n        \"ReluGrad\" -> 1\n        \"Reshape\" -> 1\n        \"Select\" -> 1\n        \"Size\" -> 1\n        \"SoftmaxCrossEntropyWithLogits\" -> 2\n        \"Square\" -> 1\n        \"SparseSegmentSum\" -> 1\n        \"Sub\" -> 1\n        \"Sum\" -> 1\n        \"Tile\" -> 1\n        \"Transpose\" -> 1\n        \"TruncatedNormal\" -> 1\n        \"VarHandleOp\" -> 1\n        \"Variable\" -> 1\n        \"ZerosLike\" -> 1\n        \"Fill\" -> 1\n        _ -> error $ \"numOutputs not implemented for \" ++ show (o ^. op)\n\n-- Divides `x / y` assuming `x, y >= 0`, treating `0 / 0 = 0`\nsafeShapeDiv :: Tensor v1 Int32 -> Tensor v2 Int32 -> Tensor Build Int32\nsafeShapeDiv x y = x `CoreOps.div` (CoreOps.maximum y 1)\n\nallDimensions :: Tensor Build Int32\nallDimensions = vector [-1 :: Int32]\n\nrangeOfRank :: forall v1 t. TensorType t => Tensor v1 t -> Tensor Build Int32\nrangeOfRank x = CoreOps.range 0 (CoreOps.rank x) 1\n\nlookupAttr ::  Attribute a1 => NodeDef -> Text -> a1\nlookupAttr nodeDef attrName = nodeDef ^. attr . at attrName . non def . attrLens\n", "meta": {"hexsha": "9fcbaaf0e417a60ad67ebeff15ab888454729424", "size": 33643, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tensorflow-ops/src/TensorFlow/Gradient.hs", "max_stars_repo_name": "doofin/haskell-1", "max_stars_repo_head_hexsha": "111f8c138d090ac7881a5eddf78053d545976225", "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": "tensorflow-ops/src/TensorFlow/Gradient.hs", "max_issues_repo_name": "doofin/haskell-1", "max_issues_repo_head_hexsha": "111f8c138d090ac7881a5eddf78053d545976225", "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": "tensorflow-ops/src/TensorFlow/Gradient.hs", "max_forks_repo_name": "doofin/haskell-1", "max_forks_repo_head_hexsha": "111f8c138d090ac7881a5eddf78053d545976225", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3025700935, "max_line_length": 131, "alphanum_fraction": 0.6026216449, "num_tokens": 9092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.29614125174964995}}
{"text": "{-# LANGUAGE GADTs #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule HVX.Primitives\n-- TODO(mh): Currently primitives that should generate implicit constraints are\n-- unsupported. The should be supported shortily. (2014-06-04)\n  ( apply\n  , hadd\n  , (+~)\n  , hmul\n  , (*~)\n  , habs\n  , neg\n  , hlog\n  , hexp\n  , logsumexp\n  , hmax\n  , hmin\n  , norm\n  , berhu\n  , huber\n  , quadform\n  , powBaseP0\n  , powBaseP01\n  , powBaseP1\n  , powBaseP1InfEven\n  , powBaseP1InfNotInt\n  ) where\n\nimport Numeric.LinearAlgebra hiding (i)\nimport Numeric.LinearAlgebra.LAPACK\n\nimport HVX.Internal.DCP\nimport HVX.Internal.Matrix\nimport HVX.Internal.Primitives\nimport HVX.Internal.Util\n\napply :: (Vex vf, Mon mf, Vex ve, Mon me, Vex (ApplyVex vf mf ve me), Mon (ApplyMon mf me))\n  => Fun vf mf -> Expr ve me -> Expr (ApplyVex vf mf ve me) (ApplyMon mf me)\napply = EFun\n\nhadd :: (Vex v1, Mon m1, Vex v2, Mon m2, Vex (AddVex v1 v2), Mon (AddMon m1 m2))\n  => Expr v1 m1 -> Expr v2 m2 -> Expr (AddVex v1 v2) (AddMon m1 m2)\nhadd = EAdd\n\ninfixl 6 +~\n(+~) :: (Vex v1, Mon m1, Vex v2, Mon m2, Vex (AddVex v1 v2), Mon (AddMon m1 m2))\n  => Expr v1 m1 -> Expr v2 m2 -> Expr (AddVex v1 v2) (AddMon m1 m2)\n(+~) = hadd\n\n-- Constructors that enforce DCP constraints.\nhmul :: (Vex v1, Mon m1, Vex (ApplyVex Affine Nonmon v1 m1), Mon (ApplyMon Nonmon m1))\n  => Expr Affine Const -> Expr v1 m1 -> Expr (ApplyVex Affine Nonmon v1 m1) (ApplyMon Nonmon m1)\nhmul (EConst a) e = apply (Mul a) e\nhmul _ _ = error \"the left argument of a multiply must be a constant\"\n\ninfixl 7 *~\n(*~) :: (Vex v1, Mon m1, Vex (ApplyVex Affine Nonmon v1 m1), Mon (ApplyMon Nonmon m1))\n  => Expr Affine Const -> Expr v1 m1 -> Expr (ApplyVex Affine Nonmon v1 m1) (ApplyMon Nonmon m1)\n(*~) (EConst a) e = apply (Mul a) e\n(*~) _ _ = error \"the left argument of a multiply must be a constant\"\n\nhabs :: (Vex v1, Mon m1, Vex (ApplyVex Convex Nonmon v1 m1), Mon (ApplyMon Nonmon m1))\n  => Expr v1 m1 -> Expr (ApplyVex Convex Nonmon v1 m1) (ApplyMon Nonmon m1)\nhabs = apply Abs\n\nneg :: (Vex v1, Mon m1, Vex (ApplyVex Affine Noninc v1 m1), Mon (ApplyMon Noninc m1))\n  => Expr v1 m1 -> Expr (ApplyVex Affine Noninc v1 m1) (ApplyMon Noninc m1)\nneg = apply Neg\n\nhlog :: (Vex v1, Mon m1, Vex (ApplyVex Concave Nondec v1 m1), Mon (ApplyMon Nondec m1))\n  => Expr v1 m1 -> Expr (ApplyVex Concave Nondec v1 m1) (ApplyMon Nondec m1)\nhlog = apply Log\n\nhexp :: (Vex v1, Mon m1, Vex (ApplyVex Convex Nondec v1 m1), Mon (ApplyMon Nondec m1))\n  => Expr v1 m1 -> Expr (ApplyVex Convex Nondec v1 m1) (ApplyMon Nondec m1)\nhexp = apply Exp\n\nlogsumexp :: (Vex v1, Mon m1, Vex (ApplyVex Convex Nondec v1 m1), Mon (ApplyMon Nondec m1))\n  => Expr v1 m1 -> Expr (ApplyVex Convex Nondec v1 m1) (ApplyMon Nondec m1)\nlogsumexp = apply LogSumExp\n\nhmax :: (Vex v1, Mon m1, Vex (ApplyVex Convex Nondec v1 m1), Mon (ApplyMon Nondec m1))\n  => Expr v1 m1 -> Expr (ApplyVex Convex Nondec v1 m1) (ApplyMon Nondec m1)\nhmax = apply Max\n\nhmin :: (Vex v1, Mon m1, Vex (ApplyVex Concave Nondec v1 m1), Mon (ApplyMon Nondec m1))\n  => Expr v1 m1 -> Expr (ApplyVex Concave Nondec v1 m1) (ApplyMon Nondec m1)\nhmin = apply Min\n\nnorm :: (Vex v1, Mon m1, Vex (ApplyVex Convex Nonmon v1 m1), Mon (ApplyMon Nonmon m1))\n  => Double -> Expr v1 m1 -> Expr (ApplyVex Convex Nonmon v1 m1) (ApplyMon Nonmon m1)\nnorm p\n  | p == infinity = error \"Internal: Infinity norm should become max . abs.\"\n  | 1 <= p = apply (Norm p)\n  | otherwise = error \"Internal: Norm only supports p >= 1.\"\n\nberhu :: (Vex v1, Mon m1, Vex (ApplyVex Convex Nonmon v1 m1), Mon (ApplyMon Nonmon m1))\n  => Double -> Expr v1 m1 -> Expr (ApplyVex Convex Nonmon v1 m1) (ApplyMon Nonmon m1)\nberhu m\n  | 0 < m = apply (Berhu m)\n  | otherwise = error \"Internal: Berhu only supports m >= 0.\"\n\nhuber :: (Vex v1, Mon m1, Vex (ApplyVex Convex Nonmon v1 m1), Mon (ApplyMon Nonmon m1))\n  => Double -> Expr v1 m1 -> Expr (ApplyVex Convex Nonmon v1 m1) (ApplyMon Nonmon m1)\nhuber m\n  | 0 < m = apply (Huber m)\n  | otherwise = error \"Internal: Huber only supports m >= 0.\"\n\nquadform :: (Mon m1, Vex (ApplyVex Convex Nonmon Affine m1), Mon (ApplyMon Nonmon m1))\n  => Expr Affine Const -> Expr Affine m1 -> Expr (ApplyVex Convex Nonmon Affine m1) (ApplyMon Nonmon m1)\nquadform (EConst a) e\n  | rows a == cols a\n    && fpequalsMat a (trans a)\n    && 0 <= maxElement (eigOnlyS a) = apply (Quadform a) e\n  | otherwise = error \"Matrices in quadratic forms must be positive semidefinite.\"\nquadform _ _ = error \"The matrix sandwitched by the quadratic form must be constant.\"\n\npowBaseP0 :: (Vex v1, Mon m1, Vex (ApplyVex Affine Const v1 m1), Mon (ApplyMon Const m1))\n  => Double -> Expr v1 m1 -> Expr (ApplyVex Affine Const v1 m1) (ApplyMon Const m1)\npowBaseP0 p\n  | p `fpequals` 0 = apply PowBaseP0\n  | otherwise = error \"Internal: PowBaseP0 only supports p == 0.\"\n\npowBaseP01 :: (Vex v1, Mon m1, Vex (ApplyVex Concave Nondec v1 m1), Mon (ApplyMon Nondec m1))\n  => Double -> Expr v1 m1 -> Expr (ApplyVex Concave Nondec v1 m1) (ApplyMon Nondec m1)\npowBaseP01 p\n  | 0 < p && p < 1 = apply (PowBaseP01 p)\n  | otherwise = error \"Internal: PowBaseP01 only supports 0 < p < 1.\"\n\npowBaseP1 :: (Vex v1, Mon m1, Vex (ApplyVex Affine Nondec v1 m1), Mon (ApplyMon Nondec m1))\n  => Double -> Expr v1 m1 -> Expr (ApplyVex Affine Nondec v1 m1) (ApplyMon Nondec m1)\npowBaseP1 p\n  | p `fpequals` 1 = apply PowBaseP1\n  | otherwise = error \"Internal: PowBaseP1 only supports p == 1.\"\n\npowBaseP1InfEven :: (Vex v1, Mon m1, Vex (ApplyVex Convex Nonmon v1 m1), Mon (ApplyMon Nonmon m1))\n  => Double -> Expr v1 m1 -> Expr (ApplyVex Convex Nonmon v1 m1) (ApplyMon Nonmon m1)\npowBaseP1InfEven p\n  | 1 < p && isInteger p && even intP = apply (PowBaseP1InfEven intP)\n  | otherwise = error \"Internal: PowBaseP1InfEven only supports even p > 1.\"\n  where intP = round p :: Integer\n\npowBaseP1InfNotInt :: (Vex v1, Mon m1, Vex (ApplyVex Convex Nondec v1 m1), Mon (ApplyMon Nondec m1))\n  => Double -> Expr v1 m1 -> Expr (ApplyVex Convex Nondec v1 m1) (ApplyMon Nondec m1)\npowBaseP1InfNotInt p\n  | 1 < p && not (isInteger p) = apply (PowBaseP1InfNotInt p)\n  | otherwise = error \"Internal: PowBaseP1InfNotInt only supports non integral p > 1.\"\n", "meta": {"hexsha": "6322edb8173a64a061914061f2f918e78adb7cc7", "size": 6127, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HVX/Primitives.hs", "max_stars_repo_name": "wellposed/hvx", "max_stars_repo_head_hexsha": "4cc39c1ff940960e8ff7d50e368c76031786befe", "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/HVX/Primitives.hs", "max_issues_repo_name": "wellposed/hvx", "max_issues_repo_head_hexsha": "4cc39c1ff940960e8ff7d50e368c76031786befe", "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/HVX/Primitives.hs", "max_forks_repo_name": "wellposed/hvx", "max_forks_repo_head_hexsha": "4cc39c1ff940960e8ff7d50e368c76031786befe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-01-09T12:49:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:38:03.000Z", "avg_line_length": 41.1208053691, "max_line_length": 104, "alphanum_fraction": 0.6773298515, "num_tokens": 2285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.29551001500710844}}
{"text": "-- TODO: better naming conventions\n\n{-# LANGUAGE TypeFamilies, TypeOperators #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE DataKinds, PolyKinds, ConstraintKinds #-}\n{-# LANGUAGE FlexibleInstances, FlexibleContexts, UndecidableInstances #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n\nmodule GrammarNNDAG where\n\nimport Control.Monad (foldM)\nimport Data.Function (fix)\n\nimport Generics.SOP hiding (SingI)\nimport Generics.SOP.NP\nimport Generics.SOP.NS\nimport Generics.SOP.Constraint\nimport Generics.SOP.Dict\nimport Data.Vinyl hiding (Dict)\nimport Data.Singletons.Prelude hiding (All, And)\nimport Data.Singletons.Prelude.List (Length)\n\nimport Utils\nimport List\nimport Grammar\nimport TensorHMatrix\nimport DAGIO\nimport TensorDAG\nimport VinylUtils\nimport Random\n\nimport Data.Default\nimport DefaultM\n\nimport Numeric.LinearAlgebra (Numeric)\nimport qualified Data.Vector.Storable as Vector\n\ntype family Size (s :: k -> *) t :: k\ntype IntegralS (s :: k -> *) = IntegralK ('KProxy :: KProxy k)\n\nclass SingI (Size s t) => KnownSize s t\ninstance SingI (Size s t) => KnownSize s t\n\nclass All2 (KnownSize s) (Code t) => KnownSizes s t\ninstance All2 (KnownSize s) (Code t) => KnownSizes s t\n\nclass SingI (FromInteger (Length (Code t)) :: k) => KnownCode (s :: k -> *) t\ninstance SingI (FromInteger (Length (Code t)) :: k) => KnownCode (s :: k -> *) t\n\nclass HasNodes t where\n  getNodes :: t -> [Some Node]\n\nnewtype Repr a dim = Repr { runRepr :: Node (Tensor '[dim] a) }\n\ninstance HasNodes (Repr a dim) where\n  getNodes (Repr node) = [Some node]\n\nnewtype ReprT a s t = ReprT { runReprT :: Node (Tensor '[Size s t] a) }\n\ninstance HasNodes (ReprT a s t) where\n  getNodes (ReprT node) = [Some node]\n\ninstance (Default a, Usable a, IntegralS s, KnownSize s t) => DefaultM IO (ReprT a s t) where\n  defM = ReprT <$> defM\n\n--newtype Linear a outDim inDim = Linear (Node (Tensor '[outDim, inDim] a))\nnewtype LinearT a s tOut tIn = LinearT (Node (Tensor '[Size s tOut, Size s tIn] a))\n\ninstance HasNodes (LinearT a s tOut tIn) where\n  getNodes (LinearT node) = [Some node]\n\n--instance (Default a, Usable a, IntegralN outDim, SingI outDim, SingI inDim) => DefaultM IO (Linear a outDim inDim) where\n--  defM = Linear <$> defM\n\ninstance (Default a, Usable a, IntegralS s, KnownSize s tIn, KnownSize s tOut) => DefaultM IO (LinearT a s tOut tIn) where\n  defM = LinearT <$> defM\n\n--linear :: Numeric a => Linear a outDim inDim -> Repr a inDim -> IO (Node (Tensor a '[outDim]))\n--linear (Linear m) (Repr v) = makeMV m v\n\nlinearT :: (SingI (Size s tOut), IntegralS s, Usable a) => LinearT a s tOut tIn -> ReprT a s tIn -> IO (ReprT a s tOut)\nlinearT (LinearT m) (ReprT v) = ReprT <$> makeMV m v\n\ndata EncodeParams' a s parent children = EncodeParams' (ReprT a s parent) (NP (LinearT a s parent) children)\n\ninstance HasNodes (EncodeParams' a s parent children) where\n  getNodes (EncodeParams' bias weights) = getNodes bias ++ concat (collapse_NP $ liftA_NP' (K . getNodes) weights)\n\ninstance (Default a, Usable a, IntegralS s, KnownSize s parent, SListI children, All (KnownSize s) children) => DefaultM IO (EncodeParams' a s parent children) where\n  defM = EncodeParams' <$> defM <*> sequence'_NP (cpure_NP (Proxy::Proxy (KnownSize s)) (Comp defM))\n\nencodeParent' :: (Usable a, Floating a, Floating (Vector.Vector a), IntegralS s, KnownSize s parent) =>\n  EncodeParams' a s parent children -> NP (ReprT a s) children -> IO (ReprT a s parent)\nencodeParent' (EncodeParams' (ReprT bias) weights) inputs = do\n  let linearT' m v = Comp $ K <$> linearT m v\n  children <- map runReprT . collapse_NP <$> (sequence'_NP $ liftA2_NP' linearT' weights inputs)\n  parent <- foldM (makeBinary (+)) bias children\n  ReprT <$> makeUnary tanh parent\n\nnewtype EncodeParams a s t = EncodeParams { runEncodeParams :: NP (EncodeParams' a s t) (Code t) }\n\ninstance HasNodes (EncodeParams a s t) where\n  getNodes (EncodeParams params) = concat . collapse_NP $ liftA_NP' (K . getNodes) params\n\nencodeParent :: (Floating a, Floating (Vector.Vector a), Usable a, IntegralS s, KnownSize s t) =>\n  EncodeParams a s t -> SOP (ReprT a s) (Code t) -> IO (ReprT a s t)\nencodeParent (EncodeParams params) (SOP sop) = collapse_NS $ liftA2_NS' encode params sop\n  where encode p cs = K $ encodeParent' p cs\n\ndata Encoding a s t where\n  Primitive :: ReprT a s t -> Encoding a s t\n  Generic :: ReprT a s t -> SOP (Encoding a s) (Code t) -> Encoding a s t\n\ngetRepr :: Encoding a s t -> ReprT a s t\ngetRepr (Primitive repr) = repr\ngetRepr (Generic repr _) = repr\n\ninstance (Default a, Usable a, IntegralS s, KnownSize s t, KnownSizes s t) => DefaultM IO (EncodeParams a s t) where\n  defM = EncodeParams <$> sequence'_NP (cpure_NP (Proxy::Proxy (All (KnownSize s))) (Comp defM))\n\nnewtype Encoder a s t = Encoder { runEncoder :: t -> IO (Encoding a s t) }\n\nencodeRec :: forall ts a s t. (Floating a, Floating (Vector.Vector a), Usable a, KnownSize s t, IntegralS s) =>\n  Rec (Encoder a s) ts -> Dict (Contained ts) t -> EncodeParams a s t -> Encoder a s t\n\nencodeRec encoders Dict params = Encoder f where\n  encoders' = cpure_POP (Proxy::Proxy (Find ts)) (Fn $ Comp . runEncoder (index find encoders) . unI)\n  f t = do\n    children <- sequence_SOP' (ap_SOP encoders' (from t))\n    let childReprs = liftA_SOP' getRepr children\n    parent <- encodeParent params childReprs\n    return $ Generic parent children\n\nmakeEncoders :: forall p g a s. (Floating a, Floating (Vector.Vector a), Usable a, IntegralS s, All (KnownSize s) g) =>\n  Complete p g -> NP (EncodeParams a s) g -> Rec (Encoder a s) p -> Rec (Encoder a s) (p :++ g)\nmakeEncoders complete params prim = fix f where\n  f encoders = rAppend prim $ np2rec (cliftA2_NP (Proxy::Proxy (KnownSize s)) (encodeRec encoders) (unAll_NP complete) params)\n\nnewtype AnyEncoder a s ts = AnyEncoder { runAnyEncoder :: forall t. Find ts t => t -> IO (Encoding a s t) }\n\nmakeEncoder :: (Floating a, Floating (Vector.Vector a), Usable a, IntegralS s, All (KnownSize s) g) =>\n  Complete p g -> NP (EncodeParams a s) g -> Rec (Encoder a s) p -> AnyEncoder a s (p :++ g)\nmakeEncoder complete params prim = AnyEncoder $ runEncoder (index find encoders)\n  where encoders = makeEncoders complete params prim\n\nnewtype LinearIn a s t t' = LinearIn (Node (Tensor '[Size s t', Size s t] a))\n\ninstance HasNodes (LinearIn a s t t') where\n  getNodes (LinearIn node) = [Some node]\n\ninstance (Default a, Usable a, IntegralS s, KnownSize s t, KnownSize s t') => DefaultM IO (LinearIn a s t t') where\n  defM = LinearIn <$> defM\n\nlinearIn :: (IntegralS s, KnownSize s t', Usable a) => LinearIn a s t t' -> ReprT a s t -> IO (ReprT a s t')\nlinearIn (LinearIn m) (ReprT v) = ReprT <$> makeMV m v\n\ndata AffineIn a s t t' = AffineIn (ReprT a s t') (LinearIn a s t t')\n\ninstance HasNodes (AffineIn a s t t') where\n  getNodes (AffineIn bias linear) = getNodes bias ++ getNodes linear\n\ninstance (Default a, Usable a, IntegralS s, KnownSize s t, KnownSize s t') => DefaultM IO (AffineIn a s t t') where\n  defM = AffineIn <$> defM <*> defM\n\naffineIn :: (Floating a, Floating (Vector.Vector a), Usable a, IntegralS s, KnownSize s t') => AffineIn a s t t' -> ReprT a s t -> IO (ReprT a s t')\naffineIn (AffineIn (ReprT bias) weights) input = do\n  ReprT l <- linearIn weights input\n  b <- makeBinary (+) bias l\n  t <- makeUnary tanh b\n  return $ ReprT t\n\ndata Affine' a outDim inDim =\n  Affine' (Node (Tensor '[outDim] a)) (Node (Tensor '[outDim, inDim] a))\n\ninstance HasNodes (Affine' a outDim inDim) where\n  getNodes (Affine' bias linear) = [Some bias, Some linear]\n\ninstance (Default a, Usable a, IntegralN outDim, SingI outDim, SingI inDim) => DefaultM IO (Affine' a outDim inDim) where\n  defM = Affine' <$> defM <*> defM\n\nsigmoid x = 1 / (1 + exp (-x))\n\naffine' :: (Floating a, Floating (Vector.Vector a), Usable a, IntegralN outDim, SingI outDim) => Affine' a outDim inDim -> Repr a inDim -> IO (Repr a outDim)\naffine' (Affine' bias weight) (Repr input) = do\n  l <- makeMV weight input\n  b <- makeBinary (+) bias l\n  Repr <$> makeUnary sigmoid b\n\ndata DecodeParams a s t =\n  DecodeParams (Affine' a (Length (Code t)) (Size s t)) (POP (AffineIn a s t) (Code t))\n\ninstance HasNodes (DecodeParams a s t) where\n  getNodes (DecodeParams aff params) = getNodes aff ++ concat (collapse_POP' $ liftA_POP' (K . getNodes) params)\n\ninstance (Default a, Usable a, KnownCode s t, KnownSize s t, KnownSizes s t) => DefaultM IO (DecodeParams a s t) where\n  defM = DecodeParams <$> defM <*> sequence'_POP (cpure_POP (Proxy::Proxy (KnownSize s)) (Comp defM))\n\ndecodeParent :: forall a s t. (Real a, Floating a, Floating (Vector.Vector a), Usable a, All2 (KnownSize s) (Code t), KnownCode s t) =>\n  DecodeParams a s t -> ReprT a s t -> IO (SOP (ReprT a s) (Code t))\ndecodeParent (DecodeParams aff params) parent = do\n  Repr node <- affine' aff (Repr $ runReprT parent)\n  Vector v <- evalNode node\n  let weights = map toRational $ Vector.toList v\n  \n  let children = np2ns . unPOP $ cliftA_POP (Proxy::Proxy (KnownSize s)) (Comp . flip affineIn parent) params\n  \n  child <- sample $ zip children weights\n  sequence'_SOP $ SOP child\n\nnewtype Decoder a s t = Decoder { runDecoder :: ReprT a s t -> IO t }\n\ndecodeRec :: forall ts a s t. (Real a, Floating a, Floating (Vector.Vector a), Usable a, KnownSizes s t, KnownCode s t) =>\n  Rec (Decoder a s) ts -> Dict (Contained ts) t -> DecodeParams a s t -> Decoder a s t\n\ndecodeRec decoders Dict params = Decoder f where\n  decoders' = cpure_POP (Proxy::Proxy (Find ts)) (Fn $ Comp . (I <$>) . runDecoder (index find decoders))\n  f repr = do\n    childReprs <- decodeParent params repr\n    children <- sequence_SOP' (ap_SOP decoders' childReprs)\n    return $ to children\n\nmakeDecoders :: forall p g a s. (Real a, Floating a, Floating (Vector.Vector a), Usable a, All (And (KnownSizes s) (KnownCode s)) g) =>\n  Complete p g -> NP (DecodeParams a s) g -> Rec (Decoder a s) p -> Rec (Decoder a s) (p :++ g)\nmakeDecoders complete params prim = fix f where\n  f decoders = rAppend prim $ np2rec (cliftA2_NP (Proxy::Proxy (And (KnownSizes s) (KnownCode s))) (decodeRec decoders) (unAll_NP complete) params)\n\nnewtype AnyDecoder a s ts = AnyDecoder { runAnyDecoder :: forall t. Find ts t => ReprT a s t -> IO t }\n\nmakeDecoder :: (Real a, Floating a, Floating (Vector.Vector a), Usable a, All (And (KnownSizes s) (KnownCode s)) g) =>\n  Complete p g -> NP (DecodeParams a s) g -> Rec (Decoder a s) p -> AnyDecoder a s (p :++ g)\nmakeDecoder complete params prim = AnyDecoder $ runDecoder (index find decoders)\n  where decoders = makeDecoders complete params prim\n\nnewtype AutoDecoder a s t = AutoDecoder { runAutoDecoder :: Encoding a s t -> IO (Node a) }\n\nautoDecodeRec :: forall ts a s t. (Floating a, Floating (Vector.Vector a), Usable a, KnownCode s t, All2 (KnownSize s) (Code t)) =>\n  Rec (AutoDecoder a s) ts -> Dict (Contained ts) t -> DecodeParams a s t -> AutoDecoder a s t\n\nautoDecodeRec autoDecoders Dict (DecodeParams aff params) = AutoDecoder f where\n  autoDecoders' = cpure_POP (Proxy::Proxy (Find ts)) (Fn $ Comp . (K <$>) . runAutoDecoder (index find autoDecoders))\n  f :: Encoding a s t -> IO (Node a)\n  f (Generic parent children) = do\n    Repr node <- affine' aff (Repr $ runReprT parent)\n    let i = ns2int (unSOP children)\n    \n    prob <- makeSelect i node\n    log_score <- makeUnary (negate . log) prob\n    \n    let childReprs = liftA_SOP getRepr children\n    let decodings = cliftA_POP (Proxy::Proxy (KnownSize s)) (Comp . flip affineIn parent) params\n    \n    let dist :: forall t'. KnownSize s t' => (IO :.: ReprT a s) t' -> ReprT a s t' -> (IO :.: K (Node a)) t'\n        dist dIO (ReprT c) = Comp $ do\n          ReprT d <- unComp dIO\n          diff <- makeBinary (-) d c\n          norm <- makeDot diff diff\n          return $ K norm\n    \n    norms <- collapse_SOP <$> (sequence_SOP' $ cliftA2_SOP (Proxy::Proxy (KnownSize s)) dist decodings childReprs)\n    \n    childNodes <- collapse_SOP <$> sequence_SOP' (ap_SOP autoDecoders' children)\n    \n    foldM (makeBinary (+)) log_score (norms ++ childNodes)\n\nprimAutoDecoder :: Num a => AutoDecoder a s t\nprimAutoDecoder = AutoDecoder f where\n  f (Primitive _) = makeSource 0\n\nmakeAutoDecoders :: forall proxy p g a s. (Real a, Floating a, Floating (Vector.Vector a), Usable a, All (And (KnownSizes s) (KnownCode s)) g) =>\n  Complete p g -> NP (DecodeParams a s) g -> Rec (AutoDecoder a s) p -> Rec (AutoDecoder a s) (p :++ g)\nmakeAutoDecoders complete params prim = fix f where\n  --prim = np2rec $ pure_NP primitiveAutoDecoder :: Rec _ p\n  f autoDecoders = rAppend prim $ np2rec (cliftA2_NP (Proxy::Proxy (And (KnownSizes s) (KnownCode s))) (autoDecodeRec autoDecoders) (unAll_NP complete) params)\n\nnewtype AnyAutoDecoder a s ts = AnyAutoDecoder { runAnyAutoDecoder :: forall t. Find ts t => Encoding a s t -> IO (Node a) }\n\nmakeAutoDecoder :: (Real a, Floating a, Floating (Vector.Vector a), Usable a, All (And (KnownSizes s) (KnownCode s)) g) =>\n  Complete p g -> NP (DecodeParams a s) g -> Rec (AutoDecoder a s) p -> AnyAutoDecoder a s (p :++ g)\nmakeAutoDecoder complete params prim = AnyAutoDecoder $ runAutoDecoder (index find autoDecoders)\n  where autoDecoders = makeAutoDecoders complete params prim\n\nnewtype AutoEncoder a s t = AutoEncoder { runAutoEncoder :: t -> IO (Node a) }\n\nmakeAutoEncoders :: forall p g a s. (Real a, Floating a, Floating (Vector.Vector a), Usable a, All (KnownSize s) g, All (And (KnownSizes s) (KnownCode s)) g) =>\n  Complete p g -> NP (EncodeParams a s) g -> Rec (Encoder a s) p -> NP (DecodeParams a s) g -> Rec (AutoDecoder a s) p -> Rec (AutoEncoder a s) (p :++ g)\n\nmakeAutoEncoders complete encodeParams primEncoders decodeParams primAutoDecoders = autoEncoders where\n  encoders = makeEncoders complete encodeParams primEncoders\n  autoDecoders = makeAutoDecoders complete decodeParams primAutoDecoders\n  \n  makeAutoEncoder (Encoder e) (AutoDecoder d) = AutoEncoder f where\n    f t = e t >>= d\n  \n  autoEncoders = rZipWith makeAutoEncoder encoders autoDecoders\n\nnewtype AnyAutoEncoder a s ts = AnyAutoEncoder { runAnyAutoEncoder :: forall t. Find ts t => t -> IO (Node a) }\n\nmakeAutoEncoder :: (Real a, Floating a, Floating (Vector.Vector a), Usable a, All (KnownSize s) g, All (And (KnownSizes s) (KnownCode s)) g) =>\n  Complete p g -> NP (EncodeParams a s) g -> Rec (Encoder a s) p -> NP (DecodeParams a s) g -> Rec (AutoDecoder a s) p -> AnyAutoEncoder a s (p :++ g)\nmakeAutoEncoder complete encodeParams primEncoders decodeParams primAutoDecoders = AnyAutoEncoder $ runAutoEncoder (index find autoEncoders)\n  where autoEncoders = makeAutoEncoders complete encodeParams primEncoders decodeParams primAutoDecoders\n\n", "meta": {"hexsha": "513a00761cbffc9de838d94014802a53196c349b", "size": 14670, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "GrammarNNDAG.hs", "max_stars_repo_name": "vladfi1/hs-misc", "max_stars_repo_head_hexsha": "ff658f38bc2027d03d689b3f46dbeb4140312163", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-03-09T05:39:54.000Z", "max_stars_repo_stars_event_max_datetime": "2016-03-09T05:39:54.000Z", "max_issues_repo_path": "GrammarNNDAG.hs", "max_issues_repo_name": "vladfi1/hs-misc", "max_issues_repo_head_hexsha": "ff658f38bc2027d03d689b3f46dbeb4140312163", "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": "GrammarNNDAG.hs", "max_forks_repo_name": "vladfi1/hs-misc", "max_forks_repo_head_hexsha": "ff658f38bc2027d03d689b3f46dbeb4140312163", "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.9411764706, "max_line_length": 165, "alphanum_fraction": 0.693728698, "num_tokens": 4460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.29270749717982675}}
{"text": "{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Numeric.LinearAlgebra.HArpack\n       ( eigs\n       , eigsN\n       , eigsS\n       , linearOperator\n       , SparseMatrix (..)\n       , Problem (..)\n       , SWhich (..)\n       , NWhich (..)\n       , Result (..)\n       , Dimension\n       , HowMany\n       , Tolerance\n       , Iterations ) where\n\nimport           Control.Monad\nimport           Control.Monad.Loops\nimport           Data.Complex\nimport           Data.Vector.Storable         (Vector)\nimport qualified Data.Vector.Storable         as V\nimport           Data.Vector.Storable.Mutable (IOVector)\nimport qualified Data.Vector.Storable.Mutable as MV\nimport           Foreign\nimport           Foreign.C.String\nimport           Foreign.C.Types\nimport           Foreign.ForeignPtr.Unsafe    as FPUnsafe\nimport           System.IO.Unsafe\n\n-- | Functions of type 'LinearOperator' represent a matrix vector product.\n-- The values in the second vector should be overwritten by operator applied to\n-- the first.\n\ndata SparseMatrix =\n  SparseMatrix { dim ::Int\n               , indexes :: [((Int,Int),Double)] }\n  deriving Show\n\ndata LinearOperator =\n  LinearOperator\n    { applyOperator :: IOVector CDouble -> IOVector CDouble -> IO () }\n\nlinearOperator :: [((Int,Int),Double)] -> LinearOperator\nlinearOperator l = LinearOperator $ \\x y ->\n  do MV.set y 0\n     forM_ l $ \\((i,j),v) -> do\n       v' <- (* realToFrac v) <$> MV.read x j\n       MV.modify y (+ v') i\n\n--------------------------------------------------------------------------------\n-- | Which eigenvalues to calculate:\n-- - The first character refers to 'S'ymmetric or 'N'on-Symmetric;\n-- - The second refers to 'L'argest or 'S'mallest;\n-- - The third refers to 'M'agnitude, 'A'lgebraic, 'R'eal, 'I'mmaginary;\n-- - The option 'BE' means 'BE'tween, for central eigenvalues.\n\ndata SWhich = SLM | SSM | SLA | SSA | SBE\n\ninstance Show SWhich where\n  show SLM = \"LM\"\n  show SSM = \"SM\"\n  show SLA = \"LA\"\n  show SSA = \"SA\"\n  show SBE = \"BE\"\n\n----------\n\ndata NWhich = NLM | NSM | NLR | NSR | NLI | NSI\n\ninstance Show NWhich where\n  show NLM = \"LM\"\n  show NSM = \"SM\"\n  show NLR = \"LR\"\n  show NSR = \"SR\"\n  show NLI = \"LI\"\n  show NSI = \"SI\"\n\n----------\n\ndata Problem = Symmetric SWhich | NonSymmetric NWhich\n     deriving (Show)\n\ndata Eigenpairs = Error String\n                | EReal [(Double,Vector Double)]\n                | EComplex [(Complex Double, Vector (Complex Double))]\n\n--------------------------------------------------------------------------------\n\n-- | Encapsulates the arrays and data needed to invoke _naupd routines in ARPACK\n\ndata ArpackSetup =\n  ArpackSetup { aIDO    :: Ptr CInt\n              , aBMAT   :: Ptr CChar\n              , aN      :: Ptr CInt\n              , aWHICH  :: Ptr CChar\n              , aNEV    :: Ptr CInt\n              , aTOL    :: Ptr CDouble\n              , aRESID  :: Ptr CDouble\n              , aNCV    :: Ptr CInt\n              , aV      :: Ptr CDouble\n              , aLDV    :: Ptr CInt\n              , aIPARAM :: Ptr CInt\n              , aIPNTR  :: Ptr CInt\n              , aWORKD  :: Ptr CDouble\n              , aWORKL  :: Ptr CDouble\n              , aLWORKL :: Ptr CInt\n              , aINFO   :: Ptr CInt }\n  deriving (Show)\n\ntype Dimension = Int\ntype HowMany = Int\ntype Tolerance = Double\ntype Iterations = Int\n\n-- | The 'setupArpack' function allocates the arrays and data\n-- needed by ARPACK to solve an eigenvalue problem\n\nsetupArpack :: Problem\n            -> Dimension\n            -> HowMany\n            -> Tolerance\n            -> Iterations\n            -> IO ArpackSetup\n\nsetupArpack (NonSymmetric which') n nev tol maxIter =\n  do let ncv = min n (2 * nev + 1)\n         lWorkl = 3 * ncv * ncv + 6 * ncv\n         ldv = n\n\n     idoPtr <- ptrInt 0\n     nPtr   <- ptrInt n\n     nevPtr <- ptrInt nev\n     ncvPtr <- ptrInt ncv\n     ldvPtr <- ptrInt ldv\n\n     bmatPtr  <- ptrCharArray \"I\"\n     whichPtr <- ptrCharArray (show which')\n\n     tolPtr   <- ptrDouble tol\n\n     residPtr <- mallocDoubleArray n\n     vPtr     <- mallocDoubleArray (n * ncv)\n     workdPtr <- mallocDoubleArray (3 * n)\n     worklPtr <- mallocDoubleArray lWorkl\n\n     iParamPtr <- mallocIntArray 11\n\n     pokeElemOff iParamPtr 0 1\n     pokeElemOff iParamPtr 2 (fromIntegral maxIter)\n     pokeElemOff iParamPtr 3 1\n     pokeElemOff iParamPtr 6 1\n\n     iPntrPtr  <- mallocIntArray 14\n\n     lworklPtr <- ptrInt lWorkl\n     infoPtr   <- ptrInt 0\n\n     setup <- return $\n              ArpackSetup idoPtr bmatPtr nPtr whichPtr nevPtr tolPtr\n                          residPtr ncvPtr vPtr ldvPtr iParamPtr iPntrPtr\n                          workdPtr worklPtr lworklPtr infoPtr\n\n     dnaupd setup\n     return setup\n\nsetupArpack (Symmetric which) n nev tol maxIter =\n  do let ncv = min n (2 * nev + 1)\n         lWorkl = ncv * ncv + 8 * ncv\n         ldv = n\n\n     idoPtr <- ptrInt 0\n     nPtr   <- ptrInt n\n     nevPtr <- ptrInt nev\n     ncvPtr <- ptrInt ncv\n     ldvPtr <- ptrInt ldv\n\n     bmatPtr  <- ptrCharArray \"I\"\n     whichPtr <- ptrCharArray (show which)\n\n     tolPtr   <- ptrDouble tol\n\n     residPtr <- mallocDoubleArray n\n     vPtr     <- mallocDoubleArray (n * ncv)\n     workdPtr <- mallocDoubleArray (3 * n)\n     worklPtr <- mallocDoubleArray lWorkl\n\n     iParamPtr <- mallocIntArray 11\n\n     pokeElemOff iParamPtr 0 1\n     pokeElemOff iParamPtr 2 (fromIntegral maxIter)\n     pokeElemOff iParamPtr 3 1\n     pokeElemOff iParamPtr 6 1\n\n     iPntrPtr  <- mallocIntArray 11\n\n     lworklPtr <- ptrInt lWorkl\n     infoPtr   <- ptrInt 0\n\n     setup <- return $\n              ArpackSetup idoPtr bmatPtr nPtr whichPtr nevPtr tolPtr\n                          residPtr ncvPtr vPtr ldvPtr iParamPtr iPntrPtr\n                          workdPtr worklPtr lworklPtr infoPtr\n\n     dsaupd setup\n\n     return setup\n\n-- |Invoke ARPACK's iteration through the reverse communication interface.\niterateArpack :: Problem -> LinearOperator -> ArpackSetup -> IO ()\niterateArpack (NonSymmetric _) f setup = do\n  workdXElem <- peekElemOff (aIPNTR setup) 0\n  workdYElem <- peekElemOff (aIPNTR setup) 1\n\n  n <- peek (aN setup)\n\n  xPtr <- newForeignPtr_ $ advancePtr (aWORKD setup) (fromIntegral workdXElem - 1)\n  yPtr <- newForeignPtr_ $ advancePtr (aWORKD setup) (fromIntegral workdYElem - 1)\n\n  let x = MV.unsafeFromForeignPtr xPtr 0 (fromIntegral n)\n      y = MV.unsafeFromForeignPtr yPtr 0 (fromIntegral n)\n\n  applyOperator f x y\n\n  dnaupd setup\n\niterateArpack (Symmetric _) f setup = do\n  workdXElem <- peekElemOff (aIPNTR setup) 0\n  workdYElem <- peekElemOff (aIPNTR setup) 1\n\n  n <- peek (aN setup)\n\n  xPtr <- newForeignPtr_ $ advancePtr (aWORKD setup) (fromIntegral workdXElem - 1)\n  yPtr <- newForeignPtr_ $ advancePtr (aWORKD setup) (fromIntegral workdYElem - 1)\n\n  let x = MV.unsafeFromForeignPtr xPtr 0 (fromIntegral n)\n      y = MV.unsafeFromForeignPtr yPtr 0 (fromIntegral n)\n\n  applyOperator f x y\n\n  dsaupd setup\n\n\narpack :: LinearOperator -> Problem -> Dimension -> HowMany -> Tolerance ->\n          Iterations -> IO ArpackSetup\narpack op problem n nev tol mxItr = do\n  ar <- setupArpack problem n nev tol mxItr\n  iterateArpack problem op ar\n  whileM_ ((== 1) <$> peek (aIDO ar)) (iterateArpack problem op ar)\n  return ar\n\n--------------------------------------------------------------------------------\n\ndata D = DReal (IOVector CDouble)\n       | DComplex (IOVector CDouble) (IOVector CDouble)\n\ndata Sigma = SReal (Ptr CDouble)\n           | SComplex (Ptr CDouble) (Ptr CDouble)\n\ndata ArpackResults =\n  ArpackResults { eRVEC    :: Ptr CInt\n                , eHOWMNY  :: Ptr CChar\n                , eSELECT  :: Ptr CInt\n                , eD       :: D\n                , eZ       :: IOVector CDouble\n                , eLDZ     :: Ptr CInt\n                , eSIGMA   :: Sigma\n                , eWORKEV  :: Maybe (Ptr CDouble)\n                , eSetup   :: ArpackSetup }\n\nerrCheck :: ArpackResults -> IO Bool\nerrCheck ar = do\n  info <- (peek . aINFO . eSetup) ar\n  print info\n  return (info < 0)\n\nparseArpackOutput :: Problem -> ArpackSetup -> IO ArpackResults\nparseArpackOutput (NonSymmetric _) setup = do\n  ncv <- peek (aNCV setup)\n  nev <- peek (aNEV setup)\n  n <- peek (aN setup)\n\n  rvecPtr <- ptrInt 1\n  howmnyPtr <- ptrCharArray \"A\"\n  drVec <- newVectorDouble (nev + 1)\n  diVec <- newVectorDouble (nev + 1)\n  selectPtr <- mallocIntArray (fromIntegral ncv)\n  zVec <- newVectorDouble (n*(nev+1))\n  ldzPtr <- ptrInt (fromIntegral n)\n  sigmarPtr <- mallocDouble\n  sigmaiPtr <- mallocDouble\n  workevPtr <- mallocDoubleArray (fromIntegral (3*ncv))\n\n  let (drfPtr,_,_) = MV.unsafeToForeignPtr drVec\n      drPtr = FPUnsafe.unsafeForeignPtrToPtr drfPtr\n      (difPtr,_,_) = MV.unsafeToForeignPtr diVec\n      diPtr = FPUnsafe.unsafeForeignPtrToPtr difPtr\n      (zfPtr,_,_) = MV.unsafeToForeignPtr zVec\n      zPtr = FPUnsafe.unsafeForeignPtrToPtr zfPtr\n\n  c_dneupd rvecPtr howmnyPtr selectPtr drPtr diPtr zPtr ldzPtr sigmarPtr\n    sigmaiPtr workevPtr (aBMAT setup) (aN setup) (aWHICH setup) (aNEV setup)\n    (aTOL setup) (aRESID setup) (aNCV setup) (aV setup) (aLDV setup)\n    (aIPARAM setup) (aIPNTR setup) (aWORKD setup) (aWORKL setup) (aLWORKL setup)\n    (aINFO setup)\n\n  return $ ArpackResults rvecPtr howmnyPtr selectPtr (DComplex drVec diVec) zVec\n               ldzPtr (SComplex sigmarPtr sigmaiPtr) (Just workevPtr) setup\n\nparseArpackOutput (Symmetric _) setup = do\n  ncv <- peek (aNCV setup)\n  nev <- peek (aNEV setup)\n  n <- peek (aN setup)\n\n  rvecPtr <- ptrInt 1\n  howmnyPtr <- ptrCharArray \"A\"\n  dVec <- newVectorDouble nev\n  selectPtr <- mallocIntArray (fromIntegral ncv)\n  zVec <- newVectorDouble (n*(nev+1))\n  ldzPtr <- ptrInt (fromIntegral n)\n  sigmaPtr <- mallocDouble\n\n  let (drfPtr,_,_) = MV.unsafeToForeignPtr dVec\n      dPtr = FPUnsafe.unsafeForeignPtrToPtr drfPtr\n      (zfPtr,_,_) = MV.unsafeToForeignPtr zVec\n      zPtr = FPUnsafe.unsafeForeignPtrToPtr zfPtr\n\n  c_dseupd rvecPtr howmnyPtr selectPtr dPtr zPtr ldzPtr\n    sigmaPtr (aBMAT setup) (aN setup) (aWHICH setup) (aNEV setup)\n    (aTOL setup) (aRESID setup) (aNCV setup) (aV setup) (aLDV setup)\n    (aIPARAM setup) (aIPNTR setup) (aWORKD setup) (aWORKL setup) (aLWORKL setup)\n    (aINFO setup)\n\n  return $ ArpackResults rvecPtr howmnyPtr selectPtr (DReal dVec) zVec\n               ldzPtr (SReal sigmaPtr) Nothing setup\n\ngetComplexEigenvalue :: ArpackResults -> Int -> IO (Complex Double)\ngetComplexEigenvalue results index = do\n  let DComplex reEigs imEigs = eD results\n  re <- MV.read reEigs index\n  im <- MV.read imEigs index\n  return (realToFrac re :+ realToFrac im)\n\n\ngetRealEigenvector :: ArpackResults -> Int -> IO (Vector (Complex Double))\ngetRealEigenvector results index = do\n  n <- (peek . aN . eSetup) results\n  ldz <- peek $ eLDZ results\n  let z = eZ results\n  evec <- V.freeze $ MV.slice (index * fromIntegral ldz) (fromIntegral n) z\n  return $ V.map ((:+0) . realToFrac) evec\n\ngetComplexEigenvector\n  :: ArpackResults -> Int -> Bool -> IO (Vector (Complex Double))\ngetComplexEigenvector results index conjugate = do\n  n <- (peek . aN . eSetup) results\n  ldz <- peek $ eLDZ results\n  let z = eZ results\n  reEvec <- V.freeze $ MV.slice (index * fromIntegral ldz) (fromIntegral n) z\n  imEvec <- V.freeze $ MV.slice ((index+1) * fromIntegral ldz) (fromIntegral n) z\n  if conjugate\n     then return $\n          V.zipWith (:+) (V.map realToFrac reEvec)\n                         (V.map (negate . realToFrac) imEvec)\n     else return $\n          V.zipWith (:+) (V.map realToFrac reEvec)\n                         (V.map realToFrac imEvec)\n\ngetEigenpair\n  :: ArpackResults -> Int -> IO (Complex Double, V.Vector (Complex Double))\ngetEigenpair results index = do\n  eig <- getComplexEigenvalue results index\n  let evec = case compare (imagPart eig) 0 of\n        EQ -> getRealEigenvector results index\n        LT -> getComplexEigenvector results (index - 1) True\n        GT -> getComplexEigenvector results index False\n  evec' <- evec\n  return (eig,evec')\n\n-- | The function 'eigs' computes a few eigenvalues of a real valued\n-- unsymmetric matrix by invoking the ARPACK library. First element is true if\n-- ARPACK converged. If converged the second element is a list of eigenpairs.\n\neigsN :: LinearOperator\n      -> NWhich\n      -> Dimension\n      -> HowMany\n      -> Tolerance\n      -> Iterations\n      -> Maybe [(Complex Double, Vector (Complex Double))]\neigsN f which' n' nev' tol' iters = unsafePerformIO $ do\n  setup <- arpack f (NonSymmetric which') n' nev' tol' iters\n  results <- parseArpackOutput (NonSymmetric which') setup\n  err <- errCheck results\n  if err\n    then return Nothing\n    else do\n      pairs <- mapM (getEigenpair results) [0..(nev'-1)]\n      return (Just pairs)\n\ndata Result = RError\n            | RReal [(Double,Vector Double)]\n            | RComplex [(Complex Double, Vector (Complex Double))]\n              deriving Show\n\neigs :: SparseMatrix\n     -> Problem\n     -> HowMany\n     -> Result\neigs m (NonSymmetric w) h =\n  case eigsN (linearOperator (indexes m)) w (dim m) h (1e-10) 6000 of\n  Nothing -> RError\n  Just x -> RComplex x\neigs m (Symmetric w) h =\n  case eigsS (linearOperator (indexes m)) w (dim m) h (1e-10) 6000 of\n  Nothing -> RError\n  Just x -> RReal x\n\n--------------------------------------------------------------------------------\n\ngetSymmetricEigenvalue :: ArpackResults -> Int -> IO Double\ngetSymmetricEigenvalue results index = do\n  let DReal eigV = eD results\n  eig <- MV.read eigV index\n  return (realToFrac eig)\n\ngetSymmetricEigenvector :: ArpackResults -> Int -> IO (Vector Double)\ngetSymmetricEigenvector results index = do\n  n <- fromIntegral <$> (peek . aN . eSetup) results\n  ldz <- peek $ eLDZ results\n  let z = eZ results\n  evec <- V.freeze $ MV.slice (index * fromIntegral ldz) n z\n  return $ V.map realToFrac evec\n\ngetSymmetricEigenpair :: ArpackResults -> Int -> IO (Double, Vector Double)\ngetSymmetricEigenpair results index = do\n  eig <- getSymmetricEigenvalue results index\n  evec <- getSymmetricEigenvector results index\n  return (eig,evec)\n\neigsS :: LinearOperator\n      -> SWhich\n      -> Dimension\n      -> HowMany\n      -> Tolerance\n      -> Iterations\n      -> Maybe [(Double,Vector Double)]\neigsS f which n nev tol' iters = unsafePerformIO $ do\n  setup <- arpack f (Symmetric which) n nev tol' iters\n  results <- parseArpackOutput (Symmetric which) setup\n  err <- errCheck results\n  if err\n    then return Nothing\n    else do\n      pairs <- mapM (getSymmetricEigenpair results) [0..(nev-1)]\n      return (Just pairs)\n\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nmallocInt :: IO (Ptr CInt)\nmallocInt = malloc\n\nptrInt :: Int -> IO (Ptr CInt)\nptrInt k =\n  do ptr <- malloc\n     poke ptr (fromIntegral k)\n     return ptr\n\nmallocIntArray :: Int -> IO (Ptr CInt)\nmallocIntArray = mallocArray\n\n----------\n\nmallocDouble :: IO (Ptr CDouble)\nmallocDouble = malloc\n\nptrDouble :: Double -> IO (Ptr CDouble)\nptrDouble x =\n  do ptr <- malloc\n     poke ptr (realToFrac x)\n     return ptr\n\nmallocDoubleArray :: Int -> IO (Ptr CDouble)\nmallocDoubleArray = mallocArray\n\nnewVectorDouble :: CInt -> IO (MV.IOVector CDouble)\nnewVectorDouble = MV.new . fromIntegral\n\n----------\n\nmallocChar :: IO (Ptr CChar)\nmallocChar = malloc\n\nmallocCharArray :: Int -> IO (Ptr CChar)\nmallocCharArray = mallocArray\n\nptrCharArray :: String -> IO (Ptr CChar)\nptrCharArray s =\n  do ptr <- mallocCharArray (length s + 1)\n     pokeArray ptr (map castCharToCChar s)\n     return ptr\n\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nforeign import ccall unsafe \"arpack.h dnaupd_\"\n  c_dnaupd :: Ptr CInt    -- ^ reverse communication flag, to be started with 0\n           -> Ptr CChar   -- ^ 'I' for standard problem, 'G' for generalized\n           -> Ptr CInt    -- ^ dimension of the eigenproblem\n           -> Ptr CChar   -- ^ which eigenpairs to compute\n           -> Ptr CInt    -- ^ N : number of eigenpairs to compute\n           -> Ptr CDouble -- ^ tolerance\n           -> Ptr CDouble -- ^ residual vector\n           -> Ptr CInt    -- ^ NCV : number of columns of V matrix\n           -> Ptr CDouble -- ^ N x NCV output array\n           -> Ptr CInt    -- ^ leading dimension of V\n           -> Ptr CInt    -- ^ array for internal parameters, length 11\n           -> Ptr CInt    -- ^ pointer of starting locations, length 14\n           -> Ptr CDouble -- ^ workd : work array\n           -> Ptr CDouble -- ^ workl : work array\n           -> Ptr CInt    -- ^ length of workl\n           -> Ptr CInt    -- ^ info\n           -> IO ()\n\ndnaupd :: ArpackSetup -> IO ()\ndnaupd setup =\n  c_dnaupd (aIDO setup) (aBMAT setup) (aN setup) (aWHICH setup) (aNEV setup)\n           (aTOL setup) (aRESID setup) (aNCV setup) (aV setup) (aLDV setup)\n           (aIPARAM setup) (aIPNTR setup) (aWORKD setup) (aWORKL setup)\n           (aLWORKL setup) (aINFO setup)\n\nforeign import ccall unsafe \"arpack.h dneupd_\"\n  c_dneupd :: Ptr CInt    -- ^ whether to calculate eigenvectors\n           -> Ptr CChar   -- ^ whether to calculate Ritz or Schur vectors\n           -> Ptr CInt    -- ^ selects the vectors to be computed\n           -> Ptr CDouble -- ^ real part of eigenvalues\n           -> Ptr CDouble -- ^ imaginary part of eigenvalues\n           -> Ptr CDouble -- ^ approximate eigenvectors\n           -> Ptr CInt    -- ^ leading dimension of former array\n           -> Ptr CDouble -- ^ real part of the shift\n           -> Ptr CDouble -- ^ imaginary part of the shift\n           -> Ptr CDouble -- ^ work array\n           -> Ptr CChar -> Ptr CInt -> Ptr CChar -> Ptr CInt -> Ptr CDouble\n           -> Ptr CDouble -> Ptr CInt -> Ptr CDouble -> Ptr CInt -> Ptr CInt\n           -> Ptr CInt -> Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr CInt\n           -> IO ()\n\n--------------------------------------------------------------------------------\n\nforeign import ccall unsafe \"arpack.h dsaupd_\"\n  c_dsaupd :: Ptr CInt    -- ^ reverse communication flag, to be started with 0\n           -> Ptr CChar   -- ^ 'I' for standard problem, 'G' for generalized\n           -> Ptr CInt    -- ^ dimension of the eigenproblem\n           -> Ptr CChar   -- ^ which eigenpairs to compute\n           -> Ptr CInt    -- ^ N : number of eigenpairs to compute\n           -> Ptr CDouble -- ^ tolerance\n           -> Ptr CDouble -- ^ residual vector\n           -> Ptr CInt    -- ^ NCV : number of columns of V matrix\n           -> Ptr CDouble -- ^ N x NCV output array\n           -> Ptr CInt    -- ^ leading dimension of V\n           -> Ptr CInt    -- ^ array for internal parameters, length 11\n           -> Ptr CInt    -- ^ pointer of starting locations, length 14\n           -> Ptr CDouble -- ^ workd : work array\n           -> Ptr CDouble -- ^ workl : work array\n           -> Ptr CInt    -- ^ length of workl\n           -> Ptr CInt    -- ^ info\n           -> IO ()\n\ndsaupd :: ArpackSetup -> IO ()\ndsaupd setup =\n  c_dsaupd (aIDO setup) (aBMAT setup) (aN setup) (aWHICH setup) (aNEV setup)\n           (aTOL setup) (aRESID setup) (aNCV setup) (aV setup) (aLDV setup)\n           (aIPARAM setup) (aIPNTR setup) (aWORKD setup) (aWORKL setup)\n           (aLWORKL setup) (aINFO setup)\n\nforeign import ccall unsafe \"arpack.h dseupd_\"\n  c_dseupd :: Ptr CInt    -- ^ whether to calculate eigenvectors\n           -> Ptr CChar   -- ^ whether to calculate Ritz or Schur vectors\n           -> Ptr CInt    -- ^ selects the vectors to be computed\n           -> Ptr CDouble -- ^ eigenvalues\n           -> Ptr CDouble -- ^ approximate eigenvectors\n           -> Ptr CInt    -- ^ leading dimension of former array\n           -> Ptr CDouble -- ^ shift\n           -> Ptr CChar -> Ptr CInt -> Ptr CChar -> Ptr CInt -> Ptr CDouble\n           -> Ptr CDouble -> Ptr CInt -> Ptr CDouble -> Ptr CInt -> Ptr CInt\n           -> Ptr CInt -> Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr CInt\n           -> IO ()\n", "meta": {"hexsha": "14c062c3b78d853af22ee2666ce0e914c1af8909", "size": 19940, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/HArpack.hs", "max_stars_repo_name": "guaraqe/harpack", "max_stars_repo_head_hexsha": "f7c4ab6b7ee429c0dd49b94b164713b4c8992011", "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": "lib/Numeric/LinearAlgebra/HArpack.hs", "max_issues_repo_name": "guaraqe/harpack", "max_issues_repo_head_hexsha": "f7c4ab6b7ee429c0dd49b94b164713b4c8992011", "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/HArpack.hs", "max_forks_repo_name": "guaraqe/harpack", "max_forks_repo_head_hexsha": "f7c4ab6b7ee429c0dd49b94b164713b4c8992011", "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.8539898132, "max_line_length": 82, "alphanum_fraction": 0.5988465396, "num_tokens": 5626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2924350640661757}}
{"text": "{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE StandaloneDeriving    #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-|\nModule      : Grenade.Core.Pooling\nDescription : Max Pooling layer for 2D and 3D images\nCopyright   : (c) Huw Campbell, 2016-2017\nLicense     : BSD2\nStability   : experimental\n-}\nmodule Grenade.Layers.Pooling (\n    Pooling (..)\n  ) where\n\nimport           Data.Maybe\nimport           Data.Proxy\nimport           Data.Serialize\nimport           Data.Singletons.TypeLits hiding (natVal)\nimport           GHC.TypeLits\nimport           Control.DeepSeq (NFData)\nimport           GHC.Generics    (Generic)\n\n\nimport           Grenade.Core\nimport           Grenade.Layers.Internal.Pooling\n\nimport           Numeric.LinearAlgebra.Static as LAS hiding ((|||), build, toRows)\n\n-- | A pooling layer for a neural network.\n--\n--   Does a max pooling, looking over a kernel similarly to the convolution network, but returning\n--   maxarg only. This layer is often used to provide minor amounts of translational invariance.\n--\n--   The kernel size dictates which input and output sizes will \"fit\". Fitting the equation:\n--   `out = (in - kernel) / stride + 1` for both dimensions.\n--\ndata Pooling :: Nat -> Nat -> Nat -> Nat -> * where\n  Pooling :: Pooling kernelRows kernelColumns strideRows strideColumns\n  deriving (NFData, Generic)\n\ninstance Show (Pooling k k' s s') where\n  show Pooling = \"Pooling\"\n\ninstance UpdateLayer (Pooling kernelRows kernelColumns strideRows strideColumns) where\n  type Gradient (Pooling kernelRows kernelColumns strideRows strideColumns) = ()\n  runUpdate _ Pooling _ = Pooling\n\ninstance RandomLayer (Pooling k k' s s') where\n  createRandomWith _ _ = return Pooling\n\ninstance Serialize (Pooling kernelRows kernelColumns strideRows strideColumns) where\n  put _ = return ()\n  get = return Pooling\n\n-- | A two dimentional image can be pooled.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat inputRows\n         , KnownNat inputColumns\n         , KnownNat outputRows\n         , KnownNat outputColumns\n         , ((outputRows - 1) * strideRows) ~ (inputRows - kernelRows)\n         , ((outputColumns - 1) * strideColumns) ~ (inputColumns - kernelColumns)\n         ) => Layer (Pooling kernelRows kernelColumns strideRows strideColumns) ('D2 inputRows inputColumns) ('D2 outputRows outputColumns) where\n  type Tape (Pooling kernelRows kernelColumns strideRows strideColumns) ('D2 inputRows inputColumns) ('D2 outputRows outputColumns) = S ('D2 inputRows inputColumns)\n  runForwards Pooling (S2D input) =\n    let height = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        width  = fromIntegral $ natVal (Proxy :: Proxy inputColumns)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelColumns)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideColumns)\n        ex = extract input\n        r  = poolForward 1 height width kx ky sx sy ex\n        rs = fromJust . create $ r\n    in  (S2D input, S2D rs)\n  runBackwards Pooling (S2D input) (S2D dEdy) =\n    let height = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        width  = fromIntegral $ natVal (Proxy :: Proxy inputColumns)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelColumns)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideColumns)\n        ex = extract input\n        eo = extract dEdy\n        vs = poolBackward 1 height width kx ky sx sy ex eo\n    in  ((), S2D . fromJust . create $ vs)\n\n\n-- | A three dimensional image can be pooled on each layer.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat inputRows\n         , KnownNat inputColumns\n         , KnownNat outputRows\n         , KnownNat outputColumns\n         , KnownNat channels\n         , KnownNat (outputRows * channels)\n         , ((outputRows - 1) * strideRows) ~ (inputRows - kernelRows)\n         , ((outputColumns - 1) * strideColumns) ~ (inputColumns - kernelColumns)\n         ) => Layer (Pooling kernelRows kernelColumns strideRows strideColumns) ('D3 inputRows inputColumns channels) ('D3 outputRows outputColumns channels) where\n  type Tape (Pooling kernelRows kernelColumns strideRows strideColumns) ('D3 inputRows inputColumns channels) ('D3 outputRows outputColumns channels) = S ('D3 inputRows inputColumns channels)\n  runForwards Pooling (S3D input) =\n    let ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputColumns)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelColumns)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideColumns)\n        ch = fromIntegral $ natVal (Proxy :: Proxy channels)\n        ex = extract input\n        r  = poolForward ch ix iy kx ky sx sy ex\n        rs = fromJust . create $ r\n    in  (S3D input, S3D rs)\n  runBackwards Pooling (S3D input) (S3D dEdy) =\n    let ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputColumns)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelColumns)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideColumns)\n        ch = fromIntegral $ natVal (Proxy :: Proxy channels)\n        ex = extract input\n        eo = extract dEdy\n        vs = poolBackward ch ix iy kx ky sx sy ex eo\n    in  ((), S3D . fromJust . create $ vs)\n\n-------------------- GNum instance --------------------\n\ninstance GNum (Pooling k k' s s') where\n  _ |* _ = Pooling\n  _ |+ _ = Pooling\n  gFromRational _ = Pooling \n", "meta": {"hexsha": "50bf2feaf4a578215ec16e3cb4e0d27a137546a9", "size": 6353, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Pooling.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/Pooling.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/Pooling.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": 43.8137931034, "max_line_length": 191, "alphanum_fraction": 0.6587439005, "num_tokens": 1571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.28880848501789774}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule HVX.Primitives\n-- TODO(mh): Currently primitives that should generate implicit constraints are\n-- unsupported. The should be supported shortily. (2014-06-04)\n  ( apply\n  , hadd\n  , (+~)\n  , hmul\n  , (*~)\n  , habs\n  , neg\n  , hlog\n  , hexp\n  , logsumexp\n  , hmax\n  , hmin\n  , norm\n  , berhu\n  , huber\n  , quadform\n  , powBaseP0\n  , powBaseP01\n  , powBaseP1\n  , powBaseP1InfEven\n  , powBaseP1InfNotInt\n  ) where\n\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.HMatrix (eigSH')\n\nimport HVX.Internal.DCP\nimport HVX.Internal.Matrix\nimport HVX.Internal.Primitives\nimport HVX.Internal.Util\n\napply :: (ApplyVex vf mf ve me ~ vr, ValidVex vr)\n  => Fun vf mf -> Expr ve me -> Expr vr (ApplyMon mf me)\napply = EFun\n\nhadd :: (AddVex v1 v2 ~ v3, ValidVex v3)\n  => Expr v1 m1 -> Expr v2 m2 -> Expr v3 (AddMon m1 m2)\nhadd = EAdd\n\ninfixl 6 +~\n(+~) :: (AddVex v1 v2 ~ v3, ValidVex v3)\n  => Expr v1 m1 -> Expr v2 m2 -> Expr v3 (AddMon m1 m2)\n(+~) = hadd\n\n-- Constructors that enforce DCP constraints.\nhmul :: (ApplyVex 'Affine 'Nonmon v1 m1 ~ v2, ValidVex v2)\n  => Expr 'Affine 'Const -> Expr v1 m1 -> Expr v2 (ApplyMon 'Nonmon m1)\nhmul (EConst a) e = apply (Mul a) e\nhmul _ _ = error \"the left argument of a multiply must be a constant\"\n\ninfixl 7 *~\n(*~) :: (ApplyVex 'Affine 'Nonmon v1 m1 ~ v2, ValidVex v2)\n  => Expr 'Affine 'Const -> Expr v1 m1 -> Expr v2 (ApplyMon 'Nonmon m1)\n(*~) (EConst a) e = apply (Mul a) e\n(*~) _ _ = error \"the left argument of a multiply must be a constant\"\n\nhabs :: (ApplyVex 'Convex 'Nonmon v1 m1 ~ v2, ValidVex v2)\n  => Expr v1 m1 -> Expr v2 (ApplyMon 'Nonmon m1)\nhabs = apply Abs\n\nneg :: (ApplyVex 'Affine 'Noninc v1 m1 ~ v2, ValidVex v2)\n  => Expr v1 m1 -> Expr v2 (ApplyMon 'Noninc m1)\nneg = apply Neg\n\nhlog :: (ApplyVex 'Concave 'Nondec v1 m1 ~ v2, ValidVex v2)\n  => Expr v1 m1 -> Expr v2 (ApplyMon 'Nondec m1)\nhlog = apply Log\n\nhexp :: (ApplyVex 'Convex 'Nondec v1 m1 ~ v2, ValidVex v2)\n  => Expr v1 m1 -> Expr v2 (ApplyMon 'Nondec m1)\nhexp e = apply Exp e\n\nlogsumexp :: (ApplyVex 'Convex 'Nondec v1 m1 ~ v2, ValidVex v2)\n  => Expr v1 m1 -> Expr v2 (ApplyMon 'Nondec m1)\nlogsumexp = apply LogSumExp\n\nhmax :: (ApplyVex 'Convex 'Nondec v1 m1 ~ v2, ValidVex v2)\n  => Expr v1 m1 -> Expr v2 (ApplyMon 'Nondec m1)\nhmax = apply Max\n\nhmin :: (ApplyVex 'Concave 'Nondec v1 m1 ~ v2, ValidVex v2)\n  => Expr v1 m1 -> Expr v2 (ApplyMon 'Nondec m1)\nhmin = apply Min\n\nnorm :: (ApplyVex 'Convex 'Nonmon v1 m1 ~ v2, ValidVex v2)\n  => Double -> Expr v1 m1 -> Expr v2 (ApplyMon 'Nonmon m1)\nnorm p\n  | p == infinity = error \"Internal: Infinity norm should become max . abs.\"\n  | 1 <= p = apply (Norm p)\n  | otherwise = error \"Internal: Norm only supports p >= 1.\"\n\nberhu :: (ApplyVex 'Convex 'Nonmon v1 m1 ~ v2, ValidVex v2)\n  => Double -> Expr v1 m1 -> Expr v2 (ApplyMon 'Nonmon m1)\nberhu m\n  | 0 < m = apply (Berhu m)\n  | otherwise = error \"Internal: Berhu only supports m >= 0.\"\n\nhuber :: (ApplyVex 'Convex 'Nonmon v1 m1 ~ v2, ValidVex v2)\n  => Double -> Expr v1 m1 -> Expr v2 (ApplyMon 'Nonmon m1)\nhuber m\n  | 0 < m = apply (Huber m)\n  | otherwise = error \"Internal: Huber only supports m >= 0.\"\n\nquadform :: (ApplyVex 'Convex 'Nonmon 'Affine m1 ~ v2, ValidVex v2)\n  => Expr 'Affine 'Const -> Expr 'Affine m1 -> Expr v2 (ApplyMon 'Nonmon m1)\nquadform (EConst a) e\n  | rows a == cols a\n    && fpequalsMat a (tr a)\n    && 0 <= (maxElement.fst.eigSH' $ a) = apply (Quadform a) e -- we have checked that the matrix being passed in is Hermitian, so it's safe to use eigSH'.\n  | otherwise = error \"Matrices in quadratic forms must be positive semidefinite.\"\nquadform _ _ = error \"The matrix sandwitched by the quadratic form must be constant.\"\n\npowBaseP0 :: (ApplyVex 'Affine 'Const v1 m1 ~ v2, ValidVex v2)\n  => Double -> Expr v1 m1 -> Expr v2 (ApplyMon 'Const m1)\npowBaseP0 p\n  | p `fpequals` 0 = apply PowBaseP0\n  | otherwise = error \"Internal: PowBaseP0 only supports p == 0.\"\n\npowBaseP01 :: (ApplyVex 'Concave 'Nondec v1 m1 ~ v2, ValidVex v2)\n  => Double -> Expr v1 m1 -> Expr v2 (ApplyMon 'Nondec m1)\npowBaseP01 p\n  | 0 < p && p < 1 = apply (PowBaseP01 p)\n  | otherwise = error \"Internal: PowBaseP01 only supports 0 < p < 1.\"\n\npowBaseP1 :: (ApplyVex 'Affine 'Nondec v1 m1 ~ v2, ValidVex v2)\n  => Double -> Expr v1 m1 -> Expr v2 (ApplyMon 'Nondec m1)\npowBaseP1 p\n  | p `fpequals` 1 = apply PowBaseP1\n  | otherwise = error \"Internal: PowBaseP1 only supports p == 1.\"\n\npowBaseP1InfEven :: (ApplyVex 'Convex 'Nonmon v1 m1 ~ v2, ValidVex v2)\n  => Double -> Expr v1 m1 -> Expr v2 (ApplyMon 'Nonmon m1)\npowBaseP1InfEven p\n  | 1 < p && isInteger p && even intP = apply (PowBaseP1InfEven intP)\n  | otherwise = error \"Internal: PowBaseP1InfEven only supports even p > 1.\"\n  where intP = round p :: Integer\n\npowBaseP1InfNotInt :: (ApplyVex 'Convex 'Nondec v1 m1 ~ v2, ValidVex v2)\n  => Double -> Expr v1 m1 -> Expr v2 (ApplyMon 'Nondec m1)\npowBaseP1InfNotInt p\n  | 1 < p && not (isInteger p) = apply (PowBaseP1InfNotInt p)\n  | otherwise = error \"Internal: PowBaseP1InfNotInt only supports non integral p > 1.\"\n", "meta": {"hexsha": "e12ad09682fae23e68038faf63f8a30ca4d5d9cd", "size": 5106, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HVX/Primitives.hs", "max_stars_repo_name": "chrisnc/hvx", "max_stars_repo_head_hexsha": "4256e83d265c7b6bf9336533c15eae9fecce9a6d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2015-02-06T21:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T06:40:50.000Z", "max_issues_repo_path": "src/HVX/Primitives.hs", "max_issues_repo_name": "chrisnc/hvx", "max_issues_repo_head_hexsha": "4256e83d265c7b6bf9336533c15eae9fecce9a6d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-08-01T05:22:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-09T17:07:19.000Z", "max_forks_repo_path": "src/HVX/Primitives.hs", "max_forks_repo_name": "chrisnc/hvx", "max_forks_repo_head_hexsha": "4256e83d265c7b6bf9336533c15eae9fecce9a6d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-07-31T09:08:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-07T15:50:42.000Z", "avg_line_length": 34.04, "max_line_length": 155, "alphanum_fraction": 0.660791226, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.2874332967922436}}
{"text": "{-# LANGUAGE CPP                  #-}\n{-# LANGUAGE DeriveDataTypeable   #-}\n{-# LANGUAGE FlexibleContexts     #-}\n{-# LANGUAGE NoImplicitPrelude    #-}\n{-# LANGUAGE ScopedTypeVariables  #-}\n{-# LANGUAGE StandaloneDeriving   #-}\n{-# LANGUAGE UndecidableInstances #-}\n\n--------------------------------------------------------------------------------\n-- |\n-- Module:     Numeric.LevMar\n-- Copyright:  (c) 2009 - 2014 Roel van Dijk & Bas van Dijk\n-- License:    BSD-style (see the file LICENSE)\n-- Maintainer: Roel van Dijk <vandijk.roel@gmail.com>\n--             Bas van Dijk <v.dijk.bas@gmail.com>\n-- Stability:  Experimental\n--\n-- For additional documentation see the\n-- <http://www.ics.forth.gr/~lourakis/levmar/ documentation of the levmar C>\n-- library which this library is based on:\n--\n--------------------------------------------------------------------------------\n\nmodule Numeric.LevMar\n    ( -- * Model & Jacobian.\n      Params, Samples\n    , Model, Jacobian\n\n      -- * Levenberg-Marquardt algorithm.\n    , LevMarable(levmar)\n\n      -- * Minimization options.\n    , Options(..), defaultOpts\n\n      -- * Constraints\n    , Constraints(..), LinearConstraints\n\n      -- * Output\n    , Info(..), StopReason(..), LevMarError(..)\n    ) where\n\n\n-------------------------------------------------------------------------------\n-- Imports\n-------------------------------------------------------------------------------\n\n-- from base:\nimport Control.Monad         ( return, mplus )\nimport Control.Exception     ( Exception )\nimport Data.Bool             ( (&&), (||), otherwise )\nimport Data.Data             ( Data )\nimport Data.Typeable         ( Typeable )\nimport Data.Either           ( Either(Left, Right) )\nimport Data.Eq               ( Eq, (==), (/=) )\nimport Data.Function         ( (.), ($) )\nimport Data.Functor          ( (<$>) )\nimport Data.Int              ( Int )\nimport Data.List             ( lookup, (++) )\nimport Data.Maybe            ( Maybe(Nothing, Just), isJust, fromJust, fromMaybe )\nimport Data.Monoid           ( Monoid, mempty, mappend )\nimport Data.Ord              ( Ord, (<) )\nimport Foreign.C.Types       ( CInt )\nimport Foreign.Marshal.Array ( allocaArray, withArray, peekArray, copyArray )\nimport Foreign.Ptr           ( Ptr, nullPtr )\nimport Foreign.ForeignPtr    ( ForeignPtr, newForeignPtr_, withForeignPtr )\nimport Foreign.Storable      ( Storable )\nimport Prelude               ( Num, Enum, Fractional, RealFrac, Float, Double\n                             , fromIntegral, toEnum, (-), (*), error, floor\n                             )\nimport System.IO             ( IO )\nimport System.IO.Unsafe      ( unsafePerformIO )\nimport Text.Read             ( Read )\nimport Text.Show             ( Show, show )\n\n#if __GLASGOW_HASKELL__ >= 605\nimport GHC.ForeignPtr        ( mallocPlainForeignPtrBytes )\nimport Prelude               ( undefined )\nimport Foreign.Storable      ( sizeOf )\n#else\nimport Foreign.ForeignPtr    ( mallocForeignPtrArray )\n#endif\n\n#if __GLASGOW_HASKELL__ < 700\nimport Prelude               ( fromInteger, (>>=), (>>), fail )\n#endif\n\n-- from hmatrix:\n#if MIN_VERSION_hmatrix(0,17,0)\nimport Numeric.LinearAlgebra.Data ( Matrix, flatten, rows, reshape )\nimport Numeric.LinearAlgebra      ( Container, Element )\n#else\nimport Data.Packed.Matrix         ( Matrix, Element, flatten, rows, reshape )\nimport Numeric.Container          ( Container )\nimport Numeric.LinearAlgebra      ( {- Instances for Matrix -} )\n#endif\n\n-- from vector:\nimport           Data.Vector.Storable       ( Vector )\nimport qualified Data.Vector.Storable as VS ( unsafeWith, length\n                                            , unsafeFromForeignPtr\n                                            , length\n                                            )\n\n-- from bindings-levmar:\nimport Bindings.LevMar ( c'LM_INFO_SZ\n\n                       , withModel\n                       , withJacobian\n\n                       , c'LM_ERROR\n                       , c'LM_ERROR_LAPACK_ERROR\n                       , c'LM_ERROR_FAILED_BOX_CHECK\n                       , c'LM_ERROR_MEMORY_ALLOCATION_FAILURE\n                       , c'LM_ERROR_CONSTRAINT_MATRIX_ROWS_GT_COLS\n                       , c'LM_ERROR_CONSTRAINT_MATRIX_NOT_FULL_ROW_RANK\n                       , c'LM_ERROR_TOO_FEW_MEASUREMENTS\n                       , c'LM_ERROR_SINGULAR_MATRIX\n                       , c'LM_ERROR_SUM_OF_SQUARES_NOT_FINITE\n\n                       , c'LM_INIT_MU\n                       , c'LM_STOP_THRESH\n                       , c'LM_DIFF_DELTA\n                       )\nimport qualified Bindings.LevMar ( Model, Jacobian )\n\n-- from levmar (this package):\nimport Bindings.LevMar.CurryFriendly ( LevMarDer,     LevMarDif\n                                     , LevMarBCDer,   LevMarBCDif\n                                     , LevMarLecDer,  LevMarLecDif\n                                     , LevMarBLecDer, LevMarBLecDif\n\n                                     , dlevmar_der,      slevmar_der\n                                     , dlevmar_dif,      slevmar_dif\n                                     , dlevmar_bc_der,   slevmar_bc_der\n                                     , dlevmar_bc_dif,   slevmar_bc_dif\n                                     , dlevmar_lec_der,  slevmar_lec_der\n                                     , dlevmar_lec_dif,  slevmar_lec_dif\n                                     , dlevmar_blec_der, slevmar_blec_der\n                                     , dlevmar_blec_dif, slevmar_blec_dif\n                                     )\n\n\n--------------------------------------------------------------------------------\n-- Model & Jacobian.\n--------------------------------------------------------------------------------\n\n-- | Parameter vector of length @m@.\n--\n-- Ensure that @m <= n@ where @n@ is the length of the 'Samples' vector.\ntype Params r = Vector r\n\n-- | Sample vector of length @n@.\n--\n-- Ensure that @n >= m@ where @m@ is the length of the 'Params' vector.\ntype Samples r = Vector r\n\n{-| A functional relation describing measurements represented as a function\nfrom a vector of parameters to a vector of expected samples.\n\n * Ensure that the length @m@ of the parameter vector equals the length of the\n   initial parameter vector in 'levmar'.\n\n * Ensure that the length @n@ of the output sample vector equals the length of\n   the sample vector in 'levmar'.\n\n * Ensure that the length @n@ of the output sample vector vector is bigger than or\n   equal to the length @m@ of the parameter vector.\n-}\ntype Model r = Params r -> Samples r\n\n{-| The <http://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant jacobian>\nof the 'Model' function. Expressed as a function from a vector of\nparameters to a matrix which for each expected sample describes the\npartial derivatives of the parameters.\n\n * Ensure that the length @m@ of the parameter vector equals the length of the\n   initial parameter vector in 'levmar'.\n\n * Ensure that the output matrix has the dimension @n><m@ where @n@ is the\n   number of samples and @m@ is the number of parameters.\n-}\ntype Jacobian r = Params r -> Matrix r\n\n--------------------------------------------------------------------------------\n-- Levenberg-Marquardt algorithm.\n--------------------------------------------------------------------------------\n\n-- | The Levenberg-Marquardt algorithm is overloaded to work on 'Double' and 'Float'.\nclass LevMarable r where\n\n    -- | The Levenberg-Marquardt algorithm.\n    --\n    -- Returns a triple of the found parameters, a structure containing\n    -- information about the minimization and the covariance matrix\n    -- corresponding to LS solution.\n    --\n    -- Ensure that @n >= m@.\n    levmar :: Model r            -- ^ Model\n           -> Maybe (Jacobian r) -- ^ Optional jacobian\n           -> Params r           -- ^ Initial parameters of length @m@\n           -> Samples r          -- ^ Sample vector of length @n@\n           -> Int                -- ^ Maximum iterations\n           -> Options r          -- ^ Minimization options\n           -> Constraints r      -- ^ Constraints\n           -> Either LevMarError (Params r, Info r, Matrix r)\n\ninstance LevMarable Float where\n    levmar = gen_levmar slevmar_der\n                        slevmar_dif\n                        slevmar_bc_der\n                        slevmar_bc_dif\n                        slevmar_lec_der\n                        slevmar_lec_dif\n                        slevmar_blec_der\n                        slevmar_blec_dif\n\ninstance LevMarable Double where\n    levmar = gen_levmar dlevmar_der\n                        dlevmar_dif\n                        dlevmar_bc_der\n                        dlevmar_bc_dif\n                        dlevmar_lec_der\n                        dlevmar_lec_dif\n                        dlevmar_blec_der\n                        dlevmar_blec_dif\n\n{-| @gen_levmar@ takes the low-level C functions as arguments and\nexecutes one of them depending on the optional jacobian and constraints.\n\nPreconditions:\n\n@\n  length ys >= length ps\n\n     isJust mLowBs && length (fromJust mLowBs) == length ps\n  && isJust mUpBs  && length (fromJust mUpBs)  == length ps\n\n  boxConstrained && (all $ zipWith (<=) (fromJust mLowBs) (fromJust mUpBs))\n@\n-}\ngen_levmar :: forall r. (RealFrac r, Element r)\n           => LevMarDer r\n           -> LevMarDif r\n           -> LevMarBCDer r\n           -> LevMarBCDif r\n           -> LevMarLecDer r\n           -> LevMarLecDif r\n           -> LevMarBLecDer r\n           -> LevMarBLecDif r\n\n           -> Model r            -- ^ Model\n           -> Maybe (Jacobian r) -- ^ Optional jacobian\n           -> Params r           -- ^ Initial parameters\n           -> Samples r          -- ^ Samples\n           -> Int                -- ^ Maximum iterations\n           -> Options r          -- ^ Options\n           -> Constraints r      -- ^ Constraints\n           -> Either LevMarError (Params r, Info r, Matrix r)\ngen_levmar f_der\n           f_dif\n           f_bc_der\n           f_bc_dif\n           f_lec_der\n           f_lec_dif\n           f_blec_der\n           f_blec_dif\n           model mJac ps ys itMax opts (Constraints mLowBs mUpBs mWeights mLinC)\n               | m == 0    = Left LevMarError -- LAPACK will crash otherwise!\n               | otherwise =\n  -- All effects are contained, so we can safely perform:\n  unsafePerformIO $ do\n\n    -- We need to pass the initial parameters 'ps' to the C function.\n    -- However, we can't just pass a pointer to them because the C function\n    -- will modify the parameters during execution which will violate\n    -- referential transparanency. Instead we allocate new space\n    -- and copy the parameters to it.\n    --\n    -- Note that, in the end, the array is returned from this function.\n    -- This means that the only way to guarantee its finalisation\n    -- is to allocate it using a ForeignPtr:\n    psFP <- fastMallocForeignPtrArray m\n    withForeignPtr psFP $ \\psPtr -> do\n      VS.unsafeWith ps $ \\psPtrInp ->\n        copyArray psPtr psPtrInp m\n\n      -- Retrieve the (read-only) pointer 'ysPtr' to the samples vector 'ys'\n      -- so we can pass it to the C function:\n      VS.unsafeWith ys $ \\ysPtr ->\n\n        -- Convert the Options 'opts' to a list and then to an array\n        -- so we can pass the (read-only) pointer 'optsPtr' to the C function:\n        withArray (optsToList opts) $ \\optsPtr ->\n\n          -- Allocate space for the info array\n          -- so we can pass it to the C function.\n          -- Note that, in the end, this array is converted to an Info value\n          -- and returned from this function.\n          allocaArray c'LM_INFO_SZ $ \\infoPtr -> do\n\n            -- Allocate space for the covariance matrix\n            -- so we can pass it to the C function.\n            -- Like the parameters array the matrix\n            -- needs to be returned from this function.\n            -- So we also allocate it using a ForeignPtr:\n            covarFP <- fastMallocForeignPtrArray mm\n            withForeignPtr covarFP $ \\covarPtr ->\n\n              -- 'cmodel' is the low-level model function which is converted\n              -- to the FunPtr 'modelFunPtr' and passed to the C function.\n              -- 'cmodel' will first convert the parameters pointer 'parPtr'\n              -- into a Vector after converting it into a ForeignPtr\n              -- (without a finalizer).\n              -- Then it will apply the high-level 'model' function\n              -- to this parameter vector. The resulting vector is then copied\n              -- to the output buffer 'hxPtr':\n              let cmodel :: Bindings.LevMar.Model r\n                  cmodel parPtr hxPtr _ _ _ = do\n                    parFP <- newForeignPtr_ parPtr\n                    let psV = VS.unsafeFromForeignPtr parFP 0 m\n                        vector = model psV\n                    VS.unsafeWith vector $ \\p -> copyArray hxPtr p (VS.length vector)\n              in withModel cmodel $ \\modelFunPtr -> do\n\n                 -- All the low-level C functions share a common set of arguments.\n                 -- 'runDif' applies these arguments to the given C function 'f':\n                 let runDif :: LevMarDif r -> IO CInt\n                     runDif f = f modelFunPtr\n                                  psPtr\n                                  ysPtr\n                                  (fromIntegral m)\n                                  (fromIntegral n)\n                                  (fromIntegral itMax)\n                                  optsPtr\n                                  infoPtr\n                                  nullPtr\n                                  covarPtr\n                                  nullPtr\n\n                 err <- case mJac of\n                   Nothing -> if boxConstrained\n                              then if linConstrained\n                                   then withBoxConstraints\n                                          (withLinConstraints $ withWeights runDif)\n                                          f_blec_dif\n                                   else withBoxConstraints runDif f_bc_dif\n                              else if linConstrained\n                                   then withLinConstraints runDif f_lec_dif\n                                   else runDif f_dif\n\n                   Just jac ->\n                     let cjacobian :: Bindings.LevMar.Jacobian r\n                         cjacobian parPtr jPtr _ _ _ = do\n                           parFP <- newForeignPtr_ parPtr\n                           let psV    = VS.unsafeFromForeignPtr parFP 0 m\n                               matrix = jac psV\n                               vector = flatten matrix\n                           VS.unsafeWith vector $ \\p ->\n                             copyArray jPtr p (VS.length vector)\n                     in withJacobian cjacobian $ \\jacobPtr ->\n\n                       let runDer :: LevMarDer r -> IO CInt\n                           runDer f = runDif $ f jacobPtr\n                       in if boxConstrained\n                          then if linConstrained\n                               then withBoxConstraints\n                                      (withLinConstraints $ withWeights runDer)\n                                      f_blec_der\n                               else withBoxConstraints runDer f_bc_der\n                          else if linConstrained\n                               then withLinConstraints runDer f_lec_der\n                               else runDer f_der\n\n                 -- Handling errors:\n                 if err < 0\n                    -- we don't treat the following two as an error:\n                    && err /= c'LM_ERROR_SINGULAR_MATRIX\n                    && err /= c'LM_ERROR_SUM_OF_SQUARES_NOT_FINITE\n                   then return $ Left $ convertLevMarError err\n\n                   else do -- Converting results:\n                     info <- listToInfo <$> peekArray c'LM_INFO_SZ infoPtr\n                     let psV = VS.unsafeFromForeignPtr psFP 0 m\n                     let covarM = reshape m $ VS.unsafeFromForeignPtr covarFP 0 mm\n\n                     return $ Right (psV, info, covarM)\n  where\n    m  = VS.length ps\n    n  = VS.length ys\n    mm = m*m\n\n    -- Whether the parameters are constrained by a linear equation.\n    linConstrained = isJust   mLinC\n    (cMat, rhcVec) = fromJust mLinC\n\n    -- Whether the parameters are constrained by a bounding box.\n    boxConstrained = isJust mLowBs || isJust mUpBs\n\n    withBoxConstraints f g =\n        maybeWithArray mLowBs $ \\lBsPtr ->\n          maybeWithArray mUpBs $ \\uBsPtr ->\n            f $ g lBsPtr uBsPtr\n\n    withLinConstraints f g =\n        VS.unsafeWith (flatten cMat) $ \\cMatPtr ->\n          VS.unsafeWith rhcVec $ \\rhcVecPtr ->\n            f . g cMatPtr rhcVecPtr $ fromIntegral $ rows cMat\n\n    withWeights f g = maybeWithArray mWeights $ f . g\n\nmaybeWithArray :: (Storable a) => Maybe (Vector a) -> (Ptr a -> IO β) -> IO β\nmaybeWithArray Nothing  f = f nullPtr\nmaybeWithArray (Just v) f = VS.unsafeWith v f\n\n#if __GLASGOW_HASKELL__ >= 605\n{-# INLINE fastMallocForeignPtrArray #-}\nfastMallocForeignPtrArray :: forall a. Storable a => Int -> IO (ForeignPtr a)\nfastMallocForeignPtrArray n = mallocPlainForeignPtrBytes\n                                (n * sizeOf (undefined :: a))\n#else\nfastMallocForeignPtrArray :: forall a. Storable a => Int -> IO (ForeignPtr a)\nfastMallocForeignPtrArray = mallocForeignPtrArray\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Minimization options.\n--------------------------------------------------------------------------------\n\n-- | Minimization options\ndata Options r =\n    Opts { optScaleInitMu      :: !r -- ^ Scale factor for initial /mu/.\n         , optStopNormInfJacTe :: !r -- ^ Stopping thresholds for @||J^T e||_inf@.\n         , optStopNorm2Dp      :: !r -- ^ Stopping thresholds for @||Dp||_2@.\n         , optStopNorm2E       :: !r -- ^ Stopping thresholds for @||e||_2@.\n         , optDelta            :: !r -- ^ Step used in the difference\n                                     -- approximation to the Jacobian. If\n                                     -- @optDelta<0@, the Jacobian is approximated\n                                     -- with central differences which are more\n                                     -- accurate (but slower!)  compared to the\n                                     -- forward differences employed by default.\n         } deriving (Eq, Ord, Read, Show, Data, Typeable)\n\n-- | Default minimization options\ndefaultOpts :: Fractional r => Options r\ndefaultOpts = Opts { optScaleInitMu      = c'LM_INIT_MU\n                   , optStopNormInfJacTe = c'LM_STOP_THRESH\n                   , optStopNorm2Dp      = c'LM_STOP_THRESH\n                   , optStopNorm2E       = c'LM_STOP_THRESH\n                   , optDelta            = c'LM_DIFF_DELTA\n                   }\n\noptsToList :: Options r -> [r]\noptsToList (Opts mu  eps1  eps2  eps3  delta) =\n                [mu, eps1, eps2, eps3, delta]\n\n\n--------------------------------------------------------------------------------\n-- Constraints\n--------------------------------------------------------------------------------\n\n-- | Ensure that these vectors have the same length as the number of parameters.\ndata Constraints r = Constraints\n    { lowerBounds       :: !(Maybe (Params r))            -- ^ Optional lower bounds\n    , upperBounds       :: !(Maybe (Params r))            -- ^ Optional upper bounds\n    , weights           :: !(Maybe (Params r))            -- ^ Optional weights\n    , linearConstraints :: !(Maybe (LinearConstraints r)) -- ^ Optional linear constraints\n    } deriving (Read, Show, Typeable)\n\nderiving instance (Eq r, Container Vector r, Num r) => Eq (Constraints r)\n\n-- | Linear constraints consisting of a constraints matrix, @k><m@ and\n--   a right hand constraints vector, of length @k@ where @m@ is the number of\n--   parameters and @k@ is the number of constraints.\ntype LinearConstraints r = (Matrix r, Vector r)\n\n-- | * 'mempty' is defined as a 'Constraints' where all fields are 'Nothing'.\n--\n--   * 'mappend' merges two 'Constraints' by taking the first non-'Nothing' value\n--     for each field.\ninstance Monoid (Constraints r) where\n    mempty = Constraints Nothing Nothing Nothing Nothing\n    mappend (Constraints lb1 ub1 w1 l1)\n            (Constraints lb2 ub2 w2 l2) = Constraints (lb1 `mplus` lb2)\n                                                      (ub1 `mplus` ub2)\n                                                      (w1  `mplus` w2)\n                                                      (l1  `mplus` l2)\n\n\n--------------------------------------------------------------------------------\n-- Output\n--------------------------------------------------------------------------------\n\n-- | Information regarding the minimization.\ndata Info r = Info\n  { infNorm2initE      :: !r          -- ^ @||e||_2@             at initial parameters.\n  , infNorm2E          :: !r          -- ^ @||e||_2@             at estimated parameters.\n  , infNormInfJacTe    :: !r          -- ^ @||J^T e||_inf@       at estimated parameters.\n  , infNorm2Dp         :: !r          -- ^ @||Dp||_2@            at estimated parameters.\n  , infMuDivMax        :: !r          -- ^ @\\mu/max[J^T J]_ii ]@ at estimated parameters.\n  , infNumIter         :: !Int        -- ^ Number of iterations.\n  , infStopReason      :: !StopReason -- ^ Reason for terminating.\n  , infNumFuncEvals    :: !Int        -- ^ Number of function evaluations.\n  , infNumJacobEvals   :: !Int        -- ^ Number of jacobian evaluations.\n  , infNumLinSysSolved :: !Int        -- ^ Number of linear systems solved,\n                                      --   i.e. attempts for reducing error.\n  } deriving (Eq, Ord, Read, Show, Data, Typeable)\n\nlistToInfo :: (RealFrac r) => [r] -> Info r\nlistToInfo [a,b,c,d,e,f,g,h,i,j] =\n    Info { infNorm2initE      = a\n         , infNorm2E          = b\n         , infNormInfJacTe    = c\n         , infNorm2Dp         = d\n         , infMuDivMax        = e\n         , infNumIter         = floor f\n         , infStopReason      = toEnum $ floor g - 1\n         , infNumFuncEvals    = floor h\n         , infNumJacobEvals   = floor i\n         , infNumLinSysSolved = floor j\n         }\nlistToInfo _ = error \"liftToInfo: wrong list length\"\n\n-- | Reason for terminating.\ndata StopReason\n  = SmallGradient  -- ^ Stopped because of small gradient @J^T e@.\n  | SmallDp        -- ^ Stopped because of small Dp.\n  | MaxIterations  -- ^ Stopped because maximum iterations was reached.\n  | SingularMatrix -- ^ Stopped because of singular matrix. Restart from current\n                   --   estimated parameters with increased 'optScaleInitMu'.\n  | SmallestError  -- ^ Stopped because no further error reduction is\n                   --   possible. Restart with increased 'optScaleInitMu'.\n  | SmallNorm2E    -- ^ Stopped because of small @||e||_2@.\n  | InvalidValues  -- ^ Stopped because model function returned invalid values\n                   --   (i.e. NaN or Inf). This is a user error.\n    deriving (Eq, Ord, Read, Show, Data, Typeable, Enum)\n\n\n--------------------------------------------------------------------------------\n-- Error\n--------------------------------------------------------------------------------\n\ndata LevMarError\n    = LevMarError                    -- ^ Generic error (not one of the others)\n    | LapackError                    -- ^ A call to a lapack subroutine failed\n                                     --   in the underlying C levmar library.\n    | FailedBoxCheck                 -- ^ At least one lower bound exceeds the\n                                     --   upper one.\n    | MemoryAllocationFailure        -- ^ A call to @malloc@ failed in the\n                                     --   underlying C levmar library.\n    | ConstraintMatrixRowsGtCols     -- ^ The matrix of constraints cannot have\n                                     --   more rows than columns.\n    | ConstraintMatrixNotFullRowRank -- ^ Constraints matrix is not of full row\n                                     --   rank.\n    | TooFewMeasurements             -- ^ Cannot solve a problem with fewer\n                                     --   measurements than unknowns.  In case\n                                     --   linear constraints are provided, this\n                                     --   error is also returned when the number\n                                     --   of measurements is smaller than the\n                                     --   number of unknowns minus the number of\n                                     --   equality constraints.\n      deriving (Eq, Ord, Read, Show, Data, Typeable)\n\n-- Handy in case you want to thow a LevMarError as an exception:\ninstance Exception LevMarError\n\nlevmarCErrorToLevMarError :: [(CInt, LevMarError)]\nlevmarCErrorToLevMarError =\n    [ (c'LM_ERROR,                                     LevMarError)\n    , (c'LM_ERROR_LAPACK_ERROR,                        LapackError)\n  --, (c'LM_ERROR_NO_JACOBIAN,                         can never happen)\n  --, (c'LM_ERROR_NO_BOX_CONSTRAINTS,                  can never happen)\n    , (c'LM_ERROR_FAILED_BOX_CHECK,                    FailedBoxCheck)\n    , (c'LM_ERROR_MEMORY_ALLOCATION_FAILURE,           MemoryAllocationFailure)\n    , (c'LM_ERROR_CONSTRAINT_MATRIX_ROWS_GT_COLS,      ConstraintMatrixRowsGtCols)\n    , (c'LM_ERROR_CONSTRAINT_MATRIX_NOT_FULL_ROW_RANK, ConstraintMatrixNotFullRowRank)\n    , (c'LM_ERROR_TOO_FEW_MEASUREMENTS,                TooFewMeasurements)\n  --, (c'LM_ERROR_SINGULAR_MATRIX,                     we don't treat this as an error)\n  --, (c'LM_ERROR_SUM_OF_SQUARES_NOT_FINITE,           we don't treat this as an error)\n    ]\n\nconvertLevMarError :: CInt -> LevMarError\nconvertLevMarError err = fromMaybe (error $ \"Unknown levmar error: \" ++ show err)\n                                   (lookup err levmarCErrorToLevMarError)\n", "meta": {"hexsha": "2c2c0f534f93e0b893404fd019f5a6333b916d80", "size": 25896, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/LevMar.hs", "max_stars_repo_name": "ann-yang-leapyear/levmar", "max_stars_repo_head_hexsha": "5e942dc92b0ca8c209070772890f61540e3a4ab6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:16:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-20T19:02:16.000Z", "max_issues_repo_path": "Numeric/LevMar.hs", "max_issues_repo_name": "ann-yang-leapyear/levmar", "max_issues_repo_head_hexsha": "5e942dc92b0ca8c209070772890f61540e3a4ab6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-01-06T06:14:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-07T06:41:00.000Z", "max_forks_repo_path": "Numeric/LevMar.hs", "max_forks_repo_name": "basvandijk/levmar", "max_forks_repo_head_hexsha": "6fbeccde6d4c52bfe27be638e97eed371ede604c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-01-06T01:33:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-02T16:57:55.000Z", "avg_line_length": 44.2666666667, "max_line_length": 90, "alphanum_fraction": 0.5208912573, "num_tokens": 5700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2866101383685545}}
{"text": "{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances #-}\n\nmodule SMC where\n\nimport PPL ( Sample(sample), Infer(score, observe, logscore), Model, runModel, sampleWeighted, WeightedT )\nimport Randomness ( Random, Weighted, Weight, parallel )\nimport Control.Monad ( ap, replicateM, zipWithM )\nimport Data.Either ( partitionEithers )\nimport Particle ( ParticleT(..), reweight )\nimport Control.Monad.Trans.Class (lift)\nimport Data.Monoid (Product(..))\nimport Control.Monad.Trans.Writer (WriterT, tell, runWriterT)\nimport Numeric.Log (Log(..))\nimport Distribution ( Dist (samplefrom), logpdf, Uniform (Uniform) )\nimport Statistics.Resampling (Bootstrap(resamples))\nimport Control.Monad.ST (ST)\nimport Control.Parallel (pseq)\nimport Data.List ( partition, sortOn, groupBy )\nimport Debug.Trace ( trace )\nimport Control.Monad.RWS (gets)\n\n\ntype Address = Int\n\ninstance (Monoid w, Sample m) => Sample (ParticleT l w m) where\n  sample = Compute . fmap return . sample\n\ninstance Sample m => Infer (ParticleT l (Product Weight) m) where\n  score w = Done (Product $ Exp $ log w) ()\n  logscore w = Done (Product w) ()\n  observe d x = Done (Product $ logpdf d x) ()\n\n-- SMC with seperate score and resample statements\ntype SMCModel = ParticleT () (Product Weight) Random\ntype AddressSMC = ParticleT Address (Product Weight) Random\n\navg :: [Weighted Double] -> Double\navg xs = let total = sum (map snd xs) in\n         exp $ ln $ sum [Exp (log a) * w / total | (a, w) <- xs]\n\nstats :: Functor f => f [Weighted (Double, Double) ] -> f Double\nstats = fmap (avg . map (\\((a,b),c) -> (a,c)))\n\nweight :: ParticleT l (Product Weight) m a -> Weight\nweight (Done w _) = getProduct w\nweight (Resample l w _) = getProduct w\nweight (Compute _) = error \"Compute has no weight\"\n\n-- A stochastic monad is one that can perform some sort of stochastic compute step\nclass Monad m => Stochastic m  where\n  compute :: m a -> Random (m a)\n\ninstance Stochastic (ParticleT l (Product Weight) Random) where\n  -- run a computation until it reaches a resample or is done\n  compute (Compute ma) = ma >>= compute\n  compute p = return p\n\nclass Stochastic m => Resampleable m where\n  resample :: m ()\n\ninstance Resampleable SMCModel where\n  resample = Resample () mempty $ return ()\n\nclass Infer m => SMC m where\n  resampleSMC :: Int -> [m a] -> Random [Weighted a]\n  normalisingConstant :: Int -> [m a] -> Random Weight\n\nclass Infer m => SampleWeighted m where\n  doResample :: [m a] -> Random [m a]\n\n-- SMC where every resample is explicit\nnewtype ExplicitResample a = ExplicitResample { unexplicit :: SMCModel a } deriving (Functor, Applicative, Monad, Sample, Resampleable, Infer, SMC)\n\n-- SMC where every score triggers a resample\nnewtype AlwaysResample a = AlwaysResample { unalways :: SMCModel a } deriving (Functor, Applicative, Monad, Sample, Resampleable, SMC)\n\n-- SMC where weight zero particles are resampled\nnewtype AliveFilter a = AliveFilter { unalive :: SMCModel a } deriving (Functor, Applicative, Monad, Sample, Resampleable, SMC)\n\n-- SMC where subsets of particles are resampled based on addresses\nnewtype AlphaSMC a = AlphaSMC { unalpha :: AddressSMC a } deriving (Functor, Applicative, Monad, Sample, Infer)\n\n-- SMC where subsets of particles are resampled based on addresses\nnewtype Adaptive a = Adaptive { unadapt :: SMCModel a } deriving (Functor, Applicative, Monad, Sample, Resampleable, Show)\n\n-- SMC with Startified Resampling\nnewtype Stratified a = Stratified { unstrat :: SMCModel a } deriving (Functor, Applicative, Monad, Sample, Resampleable)\n\n-- SMC with Subset Resampling\nnewtype Labelled a = Labelled { unlab :: AddressSMC a } deriving (Functor, Applicative, Monad, Sample, Infer)\n\n-- these all have implicit resamples:\ninstance Infer AliveFilter where\n  score w = AliveFilter (score w >> resample)\n  observe d x = AliveFilter (observe d x >> resample)\n\ninstance Infer Adaptive where\n  score w = Adaptive (score w >> resample)\n  observe d x = Adaptive (observe d x >> resample)\n\ninstance Infer AlwaysResample where\n  score w = AlwaysResample (score w >> resample)\n  observe d x = AlwaysResample (observe d x >> resample)\n\ninstance Infer Stratified where\n  score w = Stratified (score w >> resample)\n  observe d x = Stratified (observe d x >> resample)\n\n-- Generalized Newtype Deriving isn't quite enough to do these \ninstance Stochastic ExplicitResample where\n  compute (ExplicitResample a) = ExplicitResample <$> compute a\n\ninstance Stochastic Labelled where\n  compute (Labelled a) = Labelled <$> compute a\n\ninstance Stochastic AlwaysResample where\n  compute (AlwaysResample a) = AlwaysResample <$> compute a\n\ninstance Stochastic Adaptive where\n  compute (Adaptive a) = Adaptive <$> compute a\n\ninstance Stochastic Stratified where\n  compute (Stratified a) = Stratified <$> compute a\n\nresampleLab :: [Labelled a] -> Random [Labelled a]\nresampleLab ms = do\n    -- do all the stochastic compuations so everything\n    -- is either done or at a resample statement \n    ms' <- parallel $ map (compute . unlab) ms\n    -- check if all particles are done...\n    if all isDone ms'\n      -- ... in which case return \n      then return $ map Labelled ms'\n      -- otherwise we do resampling\n      else do\n        -- we need to prune the resample we dealt with and reset weights\n        resampled <- labResample $ map getweight ms'\n        -- recursive call to continue inference\n        resampleLab $ map Labelled resampled\n\nlabResample :: [Weighted (AddressSMC a)] -> Random [AddressSMC a]\nlabResample ms = let grouped = groupBy (\\(x,_) (y,_) -> address x == address y) ms in \n    fmap concat $ parallel $ map stratResample grouped\n\nresampleStrat :: [Stratified a] -> Random [Stratified a]\nresampleStrat ms = do\n    -- do all the stochastic compuations so everything\n    -- is either done or at a resample statement \n    ms' <- parallel $ map (compute . unstrat) ms\n    -- check if all particles are done...\n    if all isDone ms'\n      -- ... in which case return \n      then return $ map Stratified ms'\n      -- otherwise we do resampling\n      else do\n        -- we need to prune the resample we dealt with and reset weights\n        resampled <- stratResample $ map getweight ms'\n        -- recursive call to continue inference\n        resampleStrat $ map Stratified resampled\n\ngetSamples :: [Weight] -> [Weighted a] -> [a]\ngetSamples [] _ = []\ngetSamples (r:rs) values = let (y:ys) = dropWhile (\\(x,w) -> w < r) values\n                           in fst y : getSamples rs (y:ys)\n\nresidual :: [Weighted a] -> ([a], [Weighted a])\nresidual [] = ([], [])\nresidual ((a, w) : rest) = let (xs, wxs) = residual rest\n                           in let w' = floor w\n                           in (replicate w' a ++ xs, (a, w - fromIntegral w') : wxs)\n\n\nstratResample :: Functor m => [Weighted (ParticleT l (Product Weight) m a)] -> Random [ParticleT l (Product Weight) m a]\nstratResample xs = do\n    -- get sum of weights\n    let weight = sum $ map snd xs\n    let n = length xs\n    let avgweight = weight / Exp (log $ fromIntegral n)\n    -- residuals\n    let (guaranteed, rest) = residual [(a, w / avgweight) | (a,w) <- xs]\n    let n' = n - length guaranteed\n    -- rest\n    let weighted = let (as, ws) = unzip rest in zip as (scanl1 (+) ws)\n    let avgrest = snd (last weighted) / Exp (log $ fromIntegral n')\n\n    -- list of n uniform[i-1/n,i/n] random values \n    let between a b = do\n          r <- samplefrom (Uniform (fromIntegral a) (fromIntegral b))\n          return $ avgrest * Exp (log r)\n\n    rs <- zipWithM between [0..n'-1] [1..n']\n    return $ map (reweight $ Product avgweight) (getSamples rs weighted ++ guaranteed)\n{-\nstratResample :: [Weighted (SMCModel a)] -> Random [SMCModel a]\nstratResample xs = do\n    -- [(a1, w1), (a2, w2), ...] becomes [(a1, w1), (a2, w1+w2), ...]\n    let weighted = let (as, ws) = unzip xs in zip as (scanl1 (+) ws)\n    -- get sum of weights\n    let weight = snd $ last weighted\n    let n = length weighted\n    let avgweight = weight / Exp (log $ fromIntegral n)\n\n    -- list of n uniform[i-1/n,i/n] random values \n    let between a b = do\n          r <- samplefrom (Uniform (fromIntegral a) (fromIntegral b))\n          return $ avgweight * Exp (log r)\n    rs <- zipWithM between [0..n-1] [1..n]\n\n    -- list of k weighted samples \n    let result = getSamples rs weighted\n    return $ map (reweight $ Product avgweight) result\n-}\n\nclass Infer m => Addressable m where\n  resample' :: Address -> m ()\n\n  score' :: Address -> Double -> m ()\n  score' a w = score w >> resample' a\n\n  observe' :: Dist d v => Address -> d -> v -> m ()\n  observe' a d v = observe d v >> resample' a\n  \n-- subset SMC specific functions\ninstance Addressable Labelled where\n  resample' a = Labelled $ Resample a mempty $ return ()\n\n-- alpha-SMC specific functions\ninstance Addressable AlphaSMC where\n  resample' a = AlphaSMC $ Resample a mempty $ return ()\n\n-- get address from a Dome or Resample\naddress :: Bounded l => ParticleT l w m a -> l\naddress (Resample a _ _) = a\naddress (Done _ _) = maxBound\naddress (Compute _ ) = error \"compute has no address\"\n\n-- helper function used by alpha-SMC\nresampleMinSubset :: [AddressSMC a] -> Random [AddressSMC a]\nresampleMinSubset ps = do\n  let mini = minimum $ map address ps\n  let (minima, rest) = partition ((== mini) . address) ps\n  let w = sum $ map weight minima\n  let n = length minima\n  minima' <- sampleWeighted n $ map getweight minima\n  let normalized = map (reweight $ Product (w / Exp (log $ fromIntegral n))) minima'\n  return (normalized ++ rest)\n\nresampleAlpha :: Int -> [AlphaSMC a] -> Random [AlphaSMC a]\nresampleAlpha n ms = do\n    -- do all the stochastic compuations so everything\n    -- is either done or at a resample statement \n    ms' <- parallel $ map (compute . unalpha) ms\n    -- check if all particles are done...\n    if all isDone ms'\n      -- ... in which case return \n      then return $ map AlphaSMC ms'\n      -- otherwise we do resampling\n      else do\n        -- we need to prune the resample we dealt with and reset weights\n        resampled <- resampleMinSubset ms'\n        -- recursive call to continue inference\n        resampleAlpha n $ map AlphaSMC resampled\n\nresampleESS :: Int -> ([Adaptive a], Weight) -> Random ([Adaptive a], Weight)\nresampleESS n (ms, w) = do\n    -- do all the stochastic compuations so everything\n    -- is either done or at a resample statement \n    ms' <- parallel $ map (compute . unadapt) ms\n    let w1 = sum (map weight ms')\n    let w2 = sum (map ((^2) . weight) ms')\n    let ess = w1 * w1 / w2\n    let w' = w * (w1 / Exp (log $ fromIntegral n))\n\n    -- check if all particles are done...\n    if all isDone ms'\n      -- ... in which case return \n      then return (map Adaptive ms', w')\n      -- otherwise we do resampling\n      else do\n        if ess < Exp (log (1 * fromIntegral n))\n        then do\n          resampled <- sampleWeighted n (map getweight ms')\n          resampleESS n (map Adaptive resampled, w')\n        else\n          resampleESS n (map (Adaptive . ignoreResample) ms', w)\n\ninstance SMC AlphaSMC where\n  resampleSMC n ms = do\n    ms' <- resampleAlpha n ms\n    return (map (\\(AlphaSMC (Done w a)) -> (a, getProduct w)) ms')\n  normalisingConstant n ms = do\n    ms' <- resampleAlpha n ms\n    let w = sum (map (\\(AlphaSMC (Done w a)) -> getProduct w) ms')\n    return $ w / Exp (log $ fromIntegral n)\n\ninstance SMC Labelled where\n  resampleSMC n ms = do\n    ms' <- resampleLab ms\n    return (map (\\(Labelled (Done w a)) -> (a, getProduct w)) ms')\n  normalisingConstant n ms = do\n    ms' <- resampleLab ms\n    return $ getProduct (sum $ map (\\(Labelled (Done w a)) -> w) ms') / Exp (log $ fromIntegral $ length ms')\n\ninstance SMC Adaptive where\n  resampleSMC n ms = do\n    (ms', w) <- resampleESS n (ms, Exp 0)\n    return (map (\\(Adaptive (Done w a)) -> (a, getProduct w)) ms')\n  normalisingConstant n ms = snd <$> resampleESS n (ms, Exp 0)\n\ninstance SMC Stratified where\n  resampleSMC n ms = do\n    ms' <- resampleStrat ms\n    return (map (\\(Stratified (Done w a)) -> (a, getProduct w)) ms')\n  normalisingConstant n ms = do\n    ms' <- resampleStrat ms\n    return $ getProduct (sum $ map (\\(Stratified (Done w a)) -> w) ms') / Exp (log $ fromIntegral $ length ms')\n\nignoreResample :: ParticleT l (Product Weight) Random a -> ParticleT l (Product Weight) Random a\nignoreResample (Resample _ w a) = reweight w a\nignoreResample p@(Done _ _) = p\nignoreResample (Compute _) = error \"unexpected compute\"\n\n\n\ninstance Stochastic AliveFilter where\n  -- keep trying until we get a nonzero weight\n  compute p@(AliveFilter (Compute ma)) = do\n    a <- compute (Compute ma)\n    if weight a == Exp (log 0) -- note that log 0 = -Infinity\n    then compute p\n    else return $ AliveFilter a\n  compute p = return p\n\ninstance Stochastic AlphaSMC where\n  -- keep trying until we get a nonzero weight\n  compute p@(AlphaSMC (Compute ma)) = do\n    a <- compute (Compute ma)\n    if weight a == Exp (log 0) -- note that log 0 = -Infinity\n    then compute p\n    else return $ AlphaSMC a\n  compute p = return p\n\n-- get weights, clear internal weights, remove resample\ngetweight :: ParticleT l (Product Weight) m a -> Weighted (ParticleT l (Product Weight) m a)\ngetweight (Done w a) = (Done mempty a, getProduct w)\ngetweight (Resample l w a) = (a, getProduct w)\ngetweight (Compute a) = error \"unexpected compuation\"\n\n-- check if particle is done\nisDone :: ParticleT l w m a -> Bool\nisDone (Done _ _) = True\nisDone _ = False\n\nsmcmodel :: Int -> ([SMCModel a], Weight) -> Random ([SMCModel a], Weight)\nsmcmodel n (ms, w) = do\n  -- do all the stochastic compuations so everything\n    -- is either done or at a resample statement \n    ms' <- parallel $ map compute ms\n    let w' = w * sum (map weight ms') / Exp (log $ fromIntegral n)\n    -- check if all particles are done...\n    if all isDone ms'\n      -- ... in which case return \n      then return (ms', w')\n      -- otherwise we do resampling\n      else do\n        -- we need to prune the resample we dealt with and reset weights\n        resampled <- sampleWeighted n (map getweight ms')\n        -- recursive call to continue inference\n        smcmodel n (resampled, w')\n\ninstance SMC SMCModel where\n  resampleSMC n ms = do\n    (ms', w) <- smcmodel n (ms, Exp 0)\n    return (map (\\(Done w a) -> (a, getProduct w)) ms')\n  normalisingConstant n ms = snd <$> smcmodel n (ms, Exp 0)\n\n\ninferSMC :: SMC m => Int -> m a -> Random [Weighted a]\ninferSMC n m = resampleSMC n (replicate n m)\n\ninferConstant :: SMC m => Int -> m a -> Random Weight\ninferConstant n m = normalisingConstant n (replicate n m)\n\n\n", "meta": {"hexsha": "e6d6d746f867fadd0a362b20ef620c1caa135f7b", "size": 14532, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SMC.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/SMC.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/SMC.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": 37.7454545455, "max_line_length": 147, "alphanum_fraction": 0.665015139, "num_tokens": 4041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2837411336464998}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule Image.Transform where\n\nimport           Data.Array.Repa              as R\nimport           Data.Array.Repa.Stencil      as R\nimport           Data.Array.Repa.Stencil.Dim2 as R\nimport           Data.DList                   as DL\nimport           Data.List                    as L\nimport           Data.Vector.Unboxed          as VU\nimport           Numeric.LinearAlgebra        as NL\n\n-- factor = 2^n, n = 0,1,..\n-- the first factor in the list corresponds to the inner-most (right-most) dimension.\n{-# INLINE downsample #-}\ndownsample ::\n     (Source s e, Shape sh) => [Int] -> R.Array s sh e -> R.Array D sh e\ndownsample factorList arr\n  | L.all (== 1) factorList = delay arr\n  | L.any (< 1) newDList = error \"Downsample factors are too large.\"\n  | otherwise =\n    R.backpermute\n      (shapeOfList newDList)\n      (shapeOfList . L.zipWith (*) factorList . listOfShape)\n      arr\n  where\n    dList = listOfShape . extent $ arr\n    newDList = L.zipWith div dList factorList\n\n{-# INLINE downsampleUnsafe #-}\ndownsampleUnsafe ::\n     (Source s e, Shape sh) => [Int] -> R.Array s sh e -> R.Array D sh e\ndownsampleUnsafe factorList arr =\n  R.backpermute newSh (shapeOfList . L.zipWith (*) factorList . listOfShape) arr\n  where\n    dList = listOfShape $ extent arr\n    newSh = shapeOfList $ L.zipWith div dList factorList\n    \n{-# INLINE upsample #-}\nupsample ::\n     (Source s e, Shape sh, Num e) => [Int] -> R.Array s sh e -> R.Array D sh e\nupsample factorList arr\n  | L.all (== 1) factorList = delay arr\n  | L.any (< 1) factorList =\n    error $ \"upsample: factor must be >= 1.\\n\" L.++ show factorList\n  | otherwise =\n    R.backpermuteDft\n      (fromFunction\n         (shapeOfList $ L.zipWith (*) (listOfShape . extent $ arr) factorList)\n         (const 0))\n      (\\shape ->\n         if L.all (== 0) . L.zipWith (flip mod) factorList . listOfShape $ shape\n           then Just .\n                shapeOfList . L.zipWith (flip div) factorList . listOfShape $\n                shape\n           else Nothing)\n      arr\n\n{-# INLINE crop #-}\ncrop ::\n     (Source s e, Shape sh)\n  => [Int]\n  -> [Int]\n  -> R.Array s sh e\n  -> R.Array D sh e\ncrop start len arr\n  | L.any (< 0) start ||\n      L.or (L.zipWith3 (\\x y z -> x > (z - y)) start len dList) =\n    error $\n    \"Crop out of boundary!\\n\" L.++ show start L.++ \"\\n\" L.++ show len L.++ \"\\n\" L.++\n    show dList\n  | L.length start /= L.length len || L.length start /= L.length dList =\n    error $\n    \"crop: dimension error. \\n start: \" L.++ show (L.length start) L.++ \" len:\" L.++\n    show (L.length len) L.++\n    \" arr:\" L.++\n    show (L.length dList)\n  | otherwise =\n    R.backpermute\n      (shapeOfList len)\n      (shapeOfList . L.zipWith (+) start . listOfShape)\n      arr\n  where\n    dList = listOfShape $ extent arr\n\n{-# INLINE cropUnsafe #-}\ncropUnsafe ::\n     (Source s e, Shape sh)\n  => [Int]\n  -> [Int]\n  -> R.Array s sh e\n  -> R.Array D sh e\ncropUnsafe start len =\n  R.backpermute\n    (shapeOfList len)\n    (shapeOfList . L.zipWith (+) start . listOfShape)\n\n{-# INLINE pad #-}\npad :: (Source s e, Shape sh) => [Int] -> e -> R.Array s sh e -> R.Array D sh e\npad newDims padVal arr\n  | L.all (== 0) diff = delay arr\n  | otherwise =\n    backpermuteDft\n      (fromFunction (shapeOfList dimList) (const padVal))\n      (\\sh' ->\n         let idx = L.zipWith (-) (listOfShape sh') diff\n          in if L.or (L.zipWith (\\i j -> i < 0 || (i >= j)) idx oldDimList)\n               then Nothing\n               else Just $ shapeOfList idx)\n      arr\n  where\n    oldDimList = listOfShape . extent $ arr\n    dimList = L.zipWith max newDims oldDimList\n    diff =\n      L.zipWith\n        (\\a b ->\n           if a - b <= 0\n             then 0\n             else if a - b == 1\n                    then 1\n                    else div (a - b) 2)\n        newDims\n        oldDimList\n\n{-# INLINE normalizeValueRange #-}\nnormalizeValueRange ::\n     (Source r e, Shape sh, Num e, Fractional e, Ord e, Unbox e)\n  => (e, e)\n  -> R.Array r sh e\n  -> R.Array D sh e\nnormalizeValueRange (minVal, maxVal) arr\n  | maxV == minV = delay arr\n  | otherwise =\n    R.map (\\x -> (x - minV) / (maxV - minV) * (maxVal - minVal) + minVal) $ arr\n  where\n    vec = computeUnboxedS . delay $ arr\n    minV = VU.minimum . toUnboxed $ vec\n    maxV = VU.maximum . toUnboxed $ vec\n\n{-# INLINE computeDerivativeS #-}\ncomputeDerivativeS ::\n     (R.Source r e, Num e, Fractional e) => R.Array r DIM2 e -> R.Array D DIM3 e\ncomputeDerivativeS arr =\n  L.foldl' R.append (R.extend (Z :. R.All :. R.All :. (1 :: Int)) arr) ds\n  where\n    xStencil =\n      makeStencil2 3 3 $ \\ix ->\n        case ix of\n          Z :. 0 :. (-1) -> Just (-1)\n          Z :. 0 :. 1 -> Just 1\n          _ -> Nothing\n    yStencil =\n      makeStencil2 3 3 $ \\ix ->\n        case ix of\n          Z :. -1 :. 0 -> Just (-1)\n          Z :. 1 :. 0 -> Just 1\n          _ -> Nothing\n    xyStencil =\n      makeStencil2 3 3 $ \\ix ->\n        case ix of\n          Z :. -1 :. -1 -> Just 1\n          Z :. -1 :. 1 -> Just (-1)\n          Z :. 1 :. -1 -> Just (-1)\n          Z :. 1 :. 1 -> Just 1\n          _ -> Nothing\n    ds =\n      L.map\n        (\\s ->\n           extend (Z :. R.All :. R.All :. (1 :: Int)) . R.map (/ 2) $\n           mapStencil2 BoundClamp s arr)\n        [xStencil, yStencil, xyStencil]\n        \n{-# INLINE bicubicInterpolation #-}\nbicubicInterpolation ::\n     (R.Source r Double)\n  => ((Int, Int) -> (Double, Double))\n  -> (Int, Int)\n  -> R.Array r DIM2 Double\n  -> R.Array U DIM2 Double\nbicubicInterpolation idxFunc (newCols, newRows) arr =\n  let (Z :. cols :. rows) = extent arr\n      derivative = computeDerivativeS arr\n      derivative16 =\n        R.traverse\n          derivative\n          (const (Z :. newCols :. newRows :. 4 :. (4 :: Int)))\n          (\\f (Z :. a :. b :. derivativeIdx :. pairIdx) ->\n             let (x, y) = idxFunc (a, b)\n                 (x', y') =\n                   case pairIdx of\n                     0 -> (floor x, floor y)\n                     1 -> (floor x, ceiling y)\n                     2 -> (ceiling x, floor y)\n                     3 -> (ceiling x, ceiling y)\n              in if (x' < 0) ||\n                    (x' > (fromIntegral cols - 1)) ||\n                    (y' < 0) || (y' > (fromIntegral rows - 1))\n                   then 0\n                   else f (Z :. x' :. y' :. derivativeIdx))\n      mat = ((newRows * newCols) >< 16) . R.toList $ derivative16\n      multiplicationResultArray =\n        fromListUnboxed (Z :. newCols :. newRows :. 4 :. 4) .\n        NL.toList . flatten $\n        mat NL.<> maxtrixA\n   in R.sumS . R.sumS $\n      R.traverse\n        multiplicationResultArray\n        id\n        (\\f idx@(Z :. a :. b :. i :. j) ->\n           let (x, y) = idxFunc (a, b)\n               x' = x - fromIntegral (floor x :: Int)\n               y' = y - fromIntegral (floor y :: Int)\n            in f idx * (x' ^ i) * (y' ^ j))\n  where\n    maxtrixA =\n      NL.fromColumns . L.map NL.fromList $\n      [ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n      , [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n      , [-3, 3, 0, 0, -2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n      , [2, -2, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n      , [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]\n      , [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]\n      , [0, 0, 0, 0, 0, 0, 0, 0, -3, 3, 0, 0, -2, -1, 0, 0]\n      , [0, 0, 0, 0, 0, 0, 0, 0, 2, -2, 0, 0, 1, 1, 0, 0]\n      , [-3, 0, 3, 0, 0, 0, 0, 0, -2, 0, -1, 0, 0, 0, 0, 0]\n      , [0, 0, 0, 0, -3, 0, 3, 0, 0, 0, 0, 0, -2, 0, -1, 0]\n      , [9, -9, -9, 9, 6, 3, -6, -3, 6, -6, 3, -3, 4, 2, 2, 1]\n      , [-6, 6, 6, -6, -3, -3, 3, 3, -4, 4, -2, 2, -2, -2, -1, -1]\n      , [2, 0, -2, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0]\n      , [0, 0, 0, 0, 2, 0, -2, 0, 0, 0, 0, 0, 1, 0, 1, 0]\n      , [-6, 6, 6, -6, -4, -2, 4, 2, -3, 3, -3, 3, -2, -1, -2, -1]\n      , [4, -4, -4, 4, 2, 2, -2, -2, 2, -2, 2, -2, 1, 1, 1, 1]\n      ] \n      \n{-# INLINE bilinearInterpolation #-}\nbilinearInterpolation ::\n     (R.Source r Double)\n  => ((Int, Int) -> (Double, Double))\n  -> (Int, Int)\n  -> R.Array r DIM2 Double\n  -> R.Array U DIM2 Double\nbilinearInterpolation idxFunc (newCols, newRows) arr =\n  let (Z :. cols :. rows) = extent arr\n  in computeS . R.traverse arr id $ \\f (Z :. a :. b) ->\n       let (x, y) = idxFunc (a, b)\n           x1 = floor x\n           x2 = ceiling x\n           y1 = floor y\n           y2 = ceiling y\n           q11 = f (Z :. x1 :. y1)\n           q12 = f (Z :. x1 :. y2)\n           q21 = f (Z :. x2 :. y1)\n           q22 = f (Z :. x2 :. y2)\n           r1 =\n             ((fromIntegral x2 - x) / fromIntegral (x2 - x1)) * q11 +\n             ((x - fromIntegral x1) / fromIntegral (x2 - x1)) * q21\n           r2 =\n             ((fromIntegral x2 - x) / fromIntegral (x2 - x1)) * q12 +\n             ((x - fromIntegral x1) / fromIntegral (x2 - x1)) * q22\n           p =\n             ((fromIntegral y2 - y) / fromIntegral (y2 - y1)) * r1 +\n             ((y - fromIntegral y1) / fromIntegral (y2 - y1)) * r2\n       in if (x < 0) ||\n             (x > (fromIntegral cols - 1)) ||\n             (y < 0) || (y > (fromIntegral rows - 1))\n            then 0\n            else if x1 == x2\n                   then if y1 == y2\n                          then q11\n                          else ((fromIntegral y2 - y) / fromIntegral (y2 - y1)) *\n                               q11 +\n                               ((y - fromIntegral y1) / fromIntegral (y2 - y1)) *\n                               q12\n                   else if y1 == y2\n                          then r1\n                          else p\n\n{-# INLINE resize2D #-}\nresize2D ::\n     (Source s Double)\n  => (Int, Int)\n  -> (Double, Double)\n  -> R.Array s DIM2 Double\n  -> R.Array D DIM2 Double\nresize2D newSize@(newNx, newNy) bound arr =\n  normalizeValueRange bound $\n  bicubicInterpolation\n    (\\(i, j) -> (ratioX * fromIntegral i, ratioY * fromIntegral j))\n    newSize\n    arr\n  where\n    (Z :. nx' :. ny') = extent arr\n    ratioX = fromIntegral nx' / fromIntegral newNx\n    ratioY = fromIntegral ny' / fromIntegral newNy\n\n{-# INLINE resize25D #-}\nresize25D ::\n     (Source s Double)\n  => (Int, Int)\n  -> (Double, Double)\n  -> R.Array s DIM3 Double\n  -> R.Array D DIM3 Double\nresize25D newSize@(newNx, newNy) bound arr =\n  normalizeValueRange bound .\n  fromUnboxed (Z :. nf' :. newNx :. newNy) .\n  VU.concat .\n  L.map\n    (\\i ->\n       toUnboxed .\n       bicubicInterpolation\n         (\\(i, j) -> (ratioX * fromIntegral i, ratioY * fromIntegral j))\n         newSize .\n       R.slice arr $\n       (Z :. i :. R.All :. R.All)) $\n  [0 .. nf' - 1]\n  where\n    (Z :. nf' :. nx' :. ny') = extent arr\n    ratioX = fromIntegral nx' / fromIntegral newNx\n    ratioY = fromIntegral ny' / fromIntegral newNy\n    \n{-# INLINE resize2DFixedRatio #-}\nresize2DFixedRatio ::\n     (Source s Double)\n  => Int\n  -> (Double, Double)\n  -> R.Array s DIM2 Double\n  -> R.Array D DIM2 Double\nresize2DFixedRatio n bound arr =\n  normalizeValueRange bound $\n  bicubicInterpolation\n    (\\(i, j) -> (ratio * fromIntegral i, ratio * fromIntegral j))\n    newSize\n    arr\n  where\n    (Z :. nx' :. ny') = extent arr\n    newSize =\n      if nx' > ny'\n        then (n, round $ fromIntegral ny' * ratio)\n        else (round $ fromIntegral nx' * ratio, n)\n    ratio = fromIntegral (max nx' ny') / fromIntegral n\n    \n{-# INLINE resize25DFixedRatio #-}\nresize25DFixedRatio ::\n     (Source s Double)\n  => Int\n  -> (Double, Double)\n  -> R.Array s DIM3 Double\n  -> R.Array D DIM3 Double\nresize25DFixedRatio n bound arr =\n  normalizeValueRange bound .\n  fromUnboxed (Z :. nf' :. newNx :. newNy) .\n  VU.concat .\n  L.map\n    (\\i ->\n       toUnboxed .\n       bicubicInterpolation\n         (\\(i, j) -> (ratio * fromIntegral i, ratio * fromIntegral j))\n         newSize .\n       R.slice arr $\n       (Z :. i :. R.All :. R.All)) $\n  [0 .. nf' - 1]\n  where\n    (Z :. nf' :. nx' :. ny') = extent arr\n    newSize@(newNx, newNy) =\n      if nx' > ny'\n        then (n, round $ fromIntegral ny' * ratio)\n        else (round $ fromIntegral nx' * ratio, n)\n    ratio = fromIntegral (max nx' ny') / fromIntegral n\n\n\n{-# INLINE rescale2D #-}\nrescale2D ::\n     (Source s Double)\n  => Double\n  -> (Double, Double)\n  -> R.Array s DIM2 Double\n  -> R.Array D DIM2 Double\nrescale2D scale bound arr =\n  normalizeValueRange bound $\n  bicubicInterpolation\n    (\\(i, j) -> (fromIntegral i / scale, fromIntegral j / scale))\n    (round $ scale * fromIntegral nx', round $ scale * fromIntegral ny')\n    arr\n  where\n    (Z :. nx' :. ny') = extent arr\n\n{-# INLINE rescale25D #-}\nrescale25D ::\n     (Source s Double)\n  => Double\n  -> (Double, Double)\n  -> R.Array s DIM3 Double\n  -> R.Array D DIM3 Double\nrescale25D scale bound arr =\n  normalizeValueRange bound .\n  fromUnboxed (Z :. nf' :. newNx :. newNy) .\n  VU.concat .\n  L.map\n    (\\i ->\n       toUnboxed .\n       bicubicInterpolation\n         (\\(i, j) -> (fromIntegral i / scale, fromIntegral j / scale))\n         (newNx, newNy) .\n       R.slice arr $\n       (Z :. i :. R.All :. R.All)) $\n  [0 .. nf' - 1]\n  where\n    (Z :. nf' :. nx' :. ny') = extent arr\n    newNx = round $ scale * fromIntegral nx'\n    newNy = round $ scale * fromIntegral ny'\n\n{-# INLINE rotate2D #-}\nrotate2D ::\n     (Source s Double)\n  => Double\n  -> (Double, Double)\n  -> R.Array s DIM2 Double\n  -> R.Array U DIM2 Double\nrotate2D theta (centerX, centerY) arr =\n  bicubicInterpolation\n    (\\(i, j) ->\n       let i' = fromIntegral i - centerX\n           j' = fromIntegral j - centerY\n        in ( i' * cos theta - j' * sin theta + centerX\n           , i' * sin theta + j' * cos theta + centerY))\n    (nx', ny')\n    arr\n  where\n    (Z :. nx' :. ny') = extent arr\n\n\n{-# INLINE rotate25D #-}\nrotate25D ::\n     (Source s Double)\n  => Double\n  -> (Double, Double)\n  -> R.Array s DIM3 Double\n  -> R.Array U DIM3 Double\nrotate25D theta (centerX, centerY) arr =\n  fromUnboxed (Z :. nf' :. nx' :. ny') .\n  VU.concat .\n  L.map\n    (\\i ->\n       toUnboxed .\n       -- bicubicInterpolation\n       bilinearInterpolation\n         (\\(i, j) ->\n            let i' = fromIntegral i - centerX\n                j' = fromIntegral j - centerY\n            in ( i' * cos theta - j' * sin theta + centerX\n               , i' * sin theta + j' * cos theta + centerY))\n         (nx', ny') .\n       R.slice arr $\n       (Z :. i :. R.All :. R.All)) $\n  [0 .. nf' - 1]\n  where\n    (Z :. nf' :. nx' :. ny') = extent arr\n", "meta": {"hexsha": "c9f1cccf7abe75c195dc3c37b7a378cdcffac607", "size": 14378, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Image/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/Image/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/Image/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": 31.4617067834, "max_line_length": 85, "alphanum_fraction": 0.5031993323, "num_tokens": 4918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28047471413508634}}
{"text": "{-|\nModule: Class.Mappable\nDescription: Map functions over data as polymorphically as possible.\nLicense: 0BSD\nMaintainer: wygulmage@users.noreply.github.com\nStability: Experimental\nPortability: GHC\n\n'Mappable' lets you 'map' over various structures. It's intended to unify all the functions named @map@ ('Data.List.map', 'Data.Set.map', 'Data.Text.map', etc.). To do this it uses type families.\n'Data.Functor.Functor' and 'Data.MonoTraversable.MonoFunctor' provide simpler interfaces. But, 'Functor' 'fmap' requires a fully polymorphic container, while 'Data.MonoTraversable.MonoFunctor' 'Data.MonoTraversable.omap' can only map with endofunctions (and neither provides 'mapCoerce' yet).\n-}\n\n{-# LANGUAGE NoImplicitPrelude\n           , ScopedTypeVariables\n           , TypeFamilies\n           , UndecidableInstances\n           , FlexibleContexts\n           , FlexibleInstances\n           , DefaultSignatures\n           , RankNTypes\n           , MultiParamTypeClasses\n           , GeneralizedNewtypeDeriving\n   #-}\n\n\nmodule Class.Mappable (\nMappable (..), omap,\nValidMorph,\nWrapMappable (..),\nWrapFunctor (..),\n) where\n\n\nimport Control.Arrow (Arrow)\nimport Control.Applicative\nimport Control.Monad (Monad)\nimport Control.Monad.ST (ST)\nimport qualified Control.Exception as Exception\nimport Data.Ord\nimport Data.Semigroup\nimport qualified Data.Semigroup as Semigroup\nimport qualified Data.Monoid as Monoid\nimport qualified Data.Functor as Data\nimport Data.Bool (Bool)\nimport Data.Char\nimport Data.Int (Int)\nimport Data.Word (Word8)\nimport qualified Data.ByteString as Bytes\nimport qualified Data.ByteString.Lazy as Lazy.Bytes\nimport qualified Data.Text as Text\nimport qualified Data.Text.Lazy as Lazy.Text\nimport qualified Data.Sequence as Seq\nimport qualified Data.Tree as Rose\nimport qualified Data.Set as Set\nimport qualified Data.IntSet as IntSet\nimport qualified Data.Map as Map\nimport qualified Data.IntMap as IntMap\nimport Data.Complex\nimport Data.Tagged\nimport Data.Maybe (Maybe)\nimport Data.Either\nimport Data.Proxy\nimport Data.Functor.Identity\nimport qualified Data.List.NonEmpty as NonEmpty\nimport Data.Coerce (Coercible, coerce)\nimport Data.Kind\n\nimport GHC.Arr (Array)\nimport GHC.Conc (STM)\n\nimport Prelude (IO)\n\nimport Text.ParserCombinators.ReadP (ReadP)\nimport Text.ParserCombinators.ReadPrec (ReadPrec)\n\n\nnewtype WrapFunctor m a = WrapFunctor (m a)\n   deriving (Data.Functor, Applicative, Alternative, Monad)\n\nnewtype WrapMappable t = WrapMappable t\n\n\ntype family ObjectDefault (ma :: Type) where ObjectDefault (m (a :: Type)) = a\n{- ^ the rightmost parameter of a type -}\n\ntype family MorphDefault (x :: Type) (y :: Type) where\n   MorphDefault (polymorphic a) b = polymorphic b\n   MorphDefault monomorphic b     = monomorphic\n{- ^ Try to replace the rightmost parameter of a type. If the type is polymorphic, the rightmost parameter is replaced; otherwise the original type is returned. -}\n\nclass    (Object (Morph mb a) ~ a)=> ValidMorph (mb :: Type) (a :: Type)\ninstance (Object (Morph mb a) ~ a)=> ValidMorph (mb :: Type) (a :: Type)\n\nclass (Morph mb (Object mb) ~ mb)=> Mappable (mb :: Type) where\n{-^ @Mappable@ extends the power of 'Functor' to monomorphic containers and containers that constrain their contents.\nTo create an instance of @Mappable@ for a 'Functor', write e.g. @instance Mappable [b]@.\nTo create an instance of @Mappable@ for a monomorphic type, write e.g.\n@instance Mappable 'Text.Text' where\n   type Object 'Text.Text' = 'Char'\n   'map' = 'Text.map'\n@\nTo create an instance for a type that constraints its objects, you need to include a definition of 'mapCoerce'.\n@instance (Ord b)=> Mappable ('Set.Set' b) where\n   'map' = 'Set.map'\n   'mapCoerce' = 'map' 'coerce'\n@\nTo define an instance where the 'Object' is phantom, use a kind annotation: @instance Mappable ('Proxy' (o :: 'Type'))@.\n\nLaws:\n   1. for all f g. @map (g '$!') . map f@ === @map ((g '$!') . f)@, as long as equal ('==') objects produced by @f@ are indistinguishable to 'g'.\n   2. @map 'id'@ === 'id'\n   3. 'mapCoerce' === @'map' 'coerce'@\nThe first law forces @g@'s argument to accommodate both strict and lazy containers, and has the condition on equal objects to accommodate both 'Arg' and 'Set.Set'.\n-}\n   type Morph mb (a :: Type) :: Type\n   {-^ Try to change the type of an object in a container. @Morph [a] b = [b]@; @Morph 'Text.Text' b = 'Text.Text'. -}\n   type Morph mb a = MorphDefault mb a\n   type Object mb :: Type\n   {-^ The type of the objects in the container. By default it's the type's rightmost parameter. -}\n   type Object mb = ObjectDefault mb\n\n   map ::\n      forall a. (ValidMorph mb a)=>\n      (a -> Object mb) -> Morph mb a -> mb\n   {-^ Map a function over all the 'Object's in a container. -}\n\n   mapCoerce ::\n      forall a. (ValidMorph mb a, Coercible a (Object mb))=>\n      Morph mb a -> mb\n   {-^ Coerce all the 'Object's in a container to a new type. -}\n   -- mapCoerce = map coerce\n\n   default map ::\n      (ValidMorph mb a, Morph mb a ~ m a, m (Object mb) ~ mb, Data.Functor m)=>\n      (a -> Object mb) -> Morph mb a -> mb\n   map = Data.fmap\n   {-# INLINE map #-}\n\n   default mapCoerce ::\n      (ValidMorph mb a, Coercible (Morph mb a) mb)=> Morph mb a -> mb\n   mapCoerce = coerce\n   {-# INLINE mapCoerce #-}\n\n\nomap :: (Mappable t)=> (Object t -> Object t) -> t -> t\nomap = map\n{-# INLINE omap #-}\n\n------ Instances ------\n\n-- TODO: Add instances for lifted `Functor`s (e.g. `Ap m b`). Should these rely on the `Functor` instance or the `Mappable` instance? In favor of `Mappble` is being able to use constrained containers like `Set`.\n\n--- State Functors ---\ninstance Mappable (IO b)\ninstance Mappable (ST s b)\ninstance Mappable (STM b)\n\n--- Empty Containers ---\ninstance Mappable (Proxy (b :: Type))\n\n--- Identity Containers ---\ninstance Mappable (Identity b)\ninstance Mappable (Down b)\ninstance Mappable (Dual b)\ninstance Mappable (Semigroup.First b)\ninstance Mappable (Semigroup.Last b)\ninstance Mappable (Max b)\ninstance Mappable (Min b)\ninstance Mappable (Product b)\ninstance Mappable (Sum b)\n\ninstance Mappable Semigroup.All where\n   type Object Semigroup.All = Bool\n   map = coerce\n\ninstance Mappable Semigroup.Any where\n   type Object Semigroup.Any = Bool\n   map = coerce\n\n\n--- Affine Containers ---\ninstance Mappable (Maybe b)\ninstance Mappable (Monoid.First b)\ninstance Mappable (Monoid.Last b)\n\n--- Fixed-size Vectors ---\ninstance Mappable (Complex b)\n\n--- Sequences ---\ninstance Mappable [b]\ninstance Mappable (ZipList b)\n\ninstance Mappable (NonEmpty.NonEmpty b)\n\ninstance Mappable (Seq.Seq b)\ninstance Mappable (Seq.ViewL b)\ninstance Mappable (Seq.ViewR b)\n\ninstance Mappable (Rose.Tree b)\n\ninstance Mappable (Array i b)\n\ninstance Mappable Bytes.ByteString where\n   type Object Bytes.ByteString = Word8\n   map = Bytes.map\n\ninstance Mappable Lazy.Bytes.ByteString where\n   type Object Lazy.Bytes.ByteString = Word8\n   map = Lazy.Bytes.map\n\ninstance Mappable Text.Text where\n   type Object Text.Text = Char\n   map = Text.map\n\ninstance Mappable Lazy.Text.Text where\n   type Object Lazy.Text.Text = Char\n   map = Lazy.Text.map\n\n--- Sets ---\ninstance (Ord b)=> Mappable (Set.Set b) where\n   map = Set.map\n   mapCoerce = map coerce\n{-^ WARNING: @map (g $!) . map f@ is not equivalent to @map ((g $!) . f)@ when @g@ can distinguish between different but equal ('==') values produced by @f@. For example, @map (\\ ('Arg' () n) -> n) . map ('Arg' ())@ is likely to give a very different result than @map ((\\ ('Arg' () n) -> n) . 'Arg' ())@. -}\n\ninstance Mappable IntSet.IntSet where\n   type Object IntSet.IntSet = Int\n   map = IntSet.map\n\n--- Bifunctors ---\ninstance Mappable (Const c (b :: Type))\n\ninstance Mappable (Tagged c b)\n\ninstance Mappable (Either c b)\n\ninstance Mappable (c, b)\ninstance Mappable (Arg c b)\n\n--- Functions ---\ninstance Mappable (a -> b)\n\ninstance Mappable (Exception.Handler b)\n\ninstance Mappable (ReadP b)\ninstance Mappable (ReadPrec b)\n\n--- Maps ---\ninstance Mappable (Map.Map i b)\ninstance Mappable (IntMap.IntMap b)\n\n--- Wrapped Instances ---\ninstance (Arrow p)=> Mappable (WrappedArrow p c b) where\n   mapCoerce = map coerce\n\ninstance (Data.Functor m)=> Mappable (WrapFunctor m a) where\n   mapCoerce = map coerce\n\ninstance (Mappable t)=> Mappable (WrapMappable t) where\n   type Object (WrapMappable t) = Object t\n   type Morph (WrapMappable t) a = WrapMappable (Morph t a)\n   map f (WrapMappable xs) = WrapMappable (map f xs)\n   mapCoerce (WrapMappable xs) = WrapMappable (mapCoerce xs)\n", "meta": {"hexsha": "c094248bb59d7e98d1d84accae358f0bd3bce02a", "size": 8462, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Class/Mappable.hs", "max_stars_repo_name": "wygulmage/class-mappable", "max_stars_repo_head_hexsha": "ef42155bb7f286ee42f9bec07d76df013d221710", "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/Class/Mappable.hs", "max_issues_repo_name": "wygulmage/class-mappable", "max_issues_repo_head_hexsha": "ef42155bb7f286ee42f9bec07d76df013d221710", "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/Class/Mappable.hs", "max_forks_repo_name": "wygulmage/class-mappable", "max_forks_repo_head_hexsha": "ef42155bb7f286ee42f9bec07d76df013d221710", "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": 32.174904943, "max_line_length": 307, "alphanum_fraction": 0.7024344127, "num_tokens": 2291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.27669690436688293}}
{"text": "-- |\n-- Module      : Southpaw.Picasso.Render\n-- Description : Vector rendering in 2D with Cairo\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 1 2015\n\n-- TODO | - Rename (eg. Draw, Shapes) (?)\n--        - Text, typography (find good library)\n--        - Debug versions (cf. Occlusion.Render)\n--        - Use BoundingBox (?)\n\n-- SPEC | -\n--        -\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- GHC directives\n--------------------------------------------------------------------------------------------------------------------------------------------\n{-# LANGUAGE TupleSections #-}\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- API\n--------------------------------------------------------------------------------------------------------------------------------------------\nmodule Southpaw.Picasso.Render where\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- We'll need these\n--------------------------------------------------------------------------------------------------------------------------------------------\nimport Data.Complex\nimport Control.Monad (forM, forM_, liftM, liftM2, void)\n\nimport Control.Monad.IO.Class\n\nimport qualified Graphics.Rendering.Cairo                         as Cairo\n-- import qualified Graphics.Rendering.Cairo.Internal.Surfaces.Image as Image\n\nimport qualified Southpaw.Picasso.Palette     as Palette\nimport qualified Southpaw.Picasso.Shapes      as Shapes\nimport           Southpaw.Picasso.RenderUtils\nimport           Southpaw.Math.Constants\nimport           Southpaw.Cartesian.Plane.Utilities\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- General ---------------------------------------------------------------------------------------------------------------------------------\n-- |\n-- TODO: Rename (eg. plot)\n-- TODO: Generalise (not just circles)\ntrail :: Palette.Colour Double -> [Complex Double] -> Cairo.Render ()\ntrail fill trail = forM_ trail $ \\dot -> do\n    choose fill\n    circle dot 3\n\n\n-- |\ngrid :: Int -> Int -> Double -> Cairo.Render ()\ngrid cols rows size = do\n    -- TODO: Figure out how to use fill AND stroke\n    Cairo.setLineWidth 4\n    gridM_ cols rows $ \\ cl rw -> tilePath cl rw >> Cairo.fill   --\n    gridM_ cols rows $ \\ cl rw -> tilePath cl rw >> Cairo.stroke --\n    where\n      chooseColour cl rw = if (cl `mod` 2) == (rw `mod` 2) then 0.3 else 0.75 -- TODO: This should be a utility function\n      tilePath cl rw     = Cairo.rectangle (fromIntegral cl*size) (fromIntegral rw*size) size size >> Cairo.setSourceRGBA 0.22 0.81 (chooseColour cl rw) 0.32\n\n-- Primitives ------------------------------------------------------------------------------------------------------------------------------\n\n-- |\nline :: Complex Double -> Complex Double -> Cairo.Render ()\nline (fr:+om) (t:+o) = Cairo.moveTo fr om >> Cairo.lineTo t o\n\n\n-- | Renders a path of connected lines\n-- TODO: Options for colour, width, closed/open, etcairo.\nlinepath :: [Complex Double] -> Cairo.Render ()\nlinepath []      = return ()\nlinepath (e:dge) = void $ vectorise Cairo.moveTo e >> forM dge (vectorise Cairo.lineTo)\n\n\n-- |\n-- TODO: Support asymmetrical crosshairs (?)\ncrosshairs :: Complex Double -> Complex Double -> Cairo.Render ()\ncrosshairs centre size = do\n  line (centre - (hdx:+0)) (centre + (hdx:+0))\n  line (centre - (0:+hdy)) (centre + (0:+hdy))\n  where\n    (hdx:+hdy) = 0.5*size\n\n-- Shapes ----------------------------------------------------------------------------------------------------------------------------------\n\n-- |\n-- TODO: Extract argument conversion logic (centre/size vectors to unpacked left-top/dx/dy)\nrectangle :: Complex Double -> Complex Double -> Cairo.Render ()\nrectangle (cx:+cy) (dx:+dy) = Cairo.rectangle (cx-dx/2) (cy-dy/2) dx dy\n\n\n-- | A rectangle with an 'anchor' (in normalised coordinates) that is relative to the centre\n-- TODO: Should anchor point be relative to centre or topleft corner, use normalised or absolute coords (?)\n-- TODO: Less confusing terminology...\n-- TODO: Refactor\n-- TODO: Test\nanchoredRectangle :: Complex Double -> Complex Double -> Complex Double -> Cairo.Render ()\nanchoredRectangle p size anchor = rectangle (p-dotwise (*) (anchor+(0.5:+0.5)) size) size\n\n\n-- |\n-- TODO: Add arguments for colour, stroke, etcairo.\n-- TODO: Maybe it'd be better if we stuck to the normal pattern of path-config-action that Cairo follows\n-- TODO: Make polymorphic\npolygon :: Integral int => int -> Double -> Complex Double -> (Double, Double, Double, Double) -> Bool -> Cairo.Render ()\npolygon sides radius origin (r,g,b,a) filled = do\n    -- TODO: Refine 'wrap-around logic'\n    Cairo.moveTo fx fy\n    forM_ rest $ \\(x:+y) -> Cairo.lineTo x y\n\n    Cairo.setSourceRGBA r g b a\n    Cairo.setLineWidth 12\n    if filled\n        then Cairo.fill\n        else Cairo.stroke\n    where\n      ((fx:+fy):rest) = Shapes.polygon sides radius origin ++ [fx:+fy]\n\n\n-- |\n-- TODO: Options for fill/stroke, colour, width, etcairo.\ncircle :: Complex Double -> Double -> Cairo.Render ()\ncircle (cx:+cy) radius = do\n    Cairo.arc cx cy radius 0 τ\n    -- Cairo.fill\n\n-- Composite -------------------------------------------------------------------------------------------------------------------------------\n\n-- |\narrow :: Complex Double -> Complex Double -> Double -> Double -> Double -> Cairo.Render ()\narrow from to sl sw hw = do\n    let (first:rest) = closePath $ Shapes.arrow from to sl sw hw\n    vectorise Cairo.moveTo first\n    forM_ rest $ vectorise Cairo.lineTo\n\n\n-- |\n-- Ugh, I hate underscores so much\n-- TODO: Make polymorphic\ncirclearc :: Int -> Complex Double -> Double -> Double -> Double -> Double -> Cairo.Render ()\ncirclearc\n    count    -- Number of small circles\n    (ox:+oy) -- Centre of the 'arc' (pixels?)\n    spread   -- Radius of the 'arc'\n    radius   -- Radius of the small circles\n    begin    -- Start angle of the arc\n    extent = forM_ [1..count] $ \\ n -> do\n        let n' = fromIntegral n\n        let θ  = begin + n'*extent/fromIntegral count\n        Cairo.arc (ox - spread*cos θ) (oy - spread*sin θ) radius 0 τ\n        Cairo.setSourceRGBA (0.5 * (1 + sin θ)) (0.1*n') (1/n') 0.95\n        Cairo.fill\n\n\n-- |\nbezier :: Complex Double -> Complex Double -> Complex Double -> Cairo.Render ()\nbezier (x1:+y1) (x2:+y2) (x3:+y3) = Cairo.curveTo x1 y1 x2 y2 x3 y3\n\n\n-- |\n-- TODO: Generic rounded polygon\nroundrect :: Complex Double -> Complex Double -> Double -> Cairo.Render ()\nroundrect centre@(cx:+cy) size@(dx:+dy) radius = forM_ (zip [real, imag, real, imag] [(-dx):+(-dy), (dx):+(-dy), (dx):+(dy), (-dx):+(dy)]) $ \\(dir, delta@(dx':+dy')) -> do\n\n  -- TODO: Finish refactoring\n\n\t--\n\t-- let dir = (signum (dx*dy))\n\n\t-- Line segment\n\tvectorise Cairo.moveTo (centre + delta + dir radius)\n\tvectorise Cairo.lineTo (centre - flipx size/2 - real radius)\n\n\t-- Curve\n\n\t-- -- First line segment\n\t-- vectorise Cairo.moveTo (centre - size/2       + real radius)\n\t-- vectorise Cairo.lineTo (centre - flipx size/2 - real radius)\n\n\t-- -- Curve\n\t-- let (cx':+cy') = (centre - flipx size/2 + ((-radius):+radius)) in Cairo.arc cx' cy' radius (3*π/2) (4*π/2)\n\n\t-- -- Second line segment\n\t-- vectorise Cairo.moveTo (centre - flipx size/2  + imag radius)\n\t-- vectorise Cairo.lineTo (centre + size/2        - imag radius)\n\n\t-- -- Curve\n\t-- let (cx':+cy') = (centre + size/2 - (radius:+radius)) in Cairo.arc cx' cy' radius 0 (π/2)\n\n\t-- -- Third line segment\n\t-- vectorise Cairo.moveTo (centre + size/2       - real radius)\n\t-- vectorise Cairo.lineTo (centre - flipy size/2 + real radius)\n\n\t-- -- Curve\n\t-- let (cx':+cy') = (centre - flipy size/2 + flipy (radius:+radius)) in Cairo.arc cx' cy' radius (π/2) π\n\n\t-- -- Fourth line segment\n\t-- vectorise Cairo.moveTo (centre - flipy size/2 - imag radius)\n\t-- vectorise Cairo.lineTo (centre - size/2       + imag radius)\n\n\t-- -- Curve\n\t-- let (cx':+cy') = (centre - size/2 + (radius:+radius)) in Cairo.arc cx' cy' radius π (3*π/2)\n\n-- Images ----------------------------------------------------------------------------------------------------------------------------------\n\n-- |\n-- TODO: Factor out clip logic, document properly (cf. other anchored functions in this module)\n-- TODO: Wrapper for images (?)\n-- TODO: Factor out clip area (?)\nanchoredImageWithClip :: (Complex Double -> Complex Double -> Cairo.Render ()) -> Complex Double -> Complex Double -> Cairo.Surface -> Cairo.Render ()\nanchoredImageWithClip clip p anchor im = do\n  size   <- imageSurfaceSize im\n  centre <- return $ p - dotwise (*) anchor size\n  clip centre size\n  Cairo.clip\n  vectorise Cairo.translate $ (centre - size*0.5)\n  Cairo.setSourceSurface im 0 0\n  -- vectorise Cairo.moveTo (centre - size*0.5)\n  Cairo.paint\n  vectorise Cairo.translate $ negate (centre - size*0.5)\n  Cairo.resetClip\n\n\n-- |\nanchoredImage :: Complex Double -> Complex Double -> Cairo.Surface -> Cairo.Render ()\nanchoredImage p anchor im = anchoredImageWithClip rectangle p anchor im\n\n\n-- |\nimageWithClip :: (Complex Double -> Complex Double -> Cairo.Render ()) -> Complex Double -> Cairo.Surface -> Cairo.Render ()\nimageWithClip clip centre im = anchoredImageWithClip clip centre (0.0:+0.0) im\n\n\n-- |\nimage :: Complex Double -> Cairo.Surface -> Cairo.Render ()\nimage p im = anchoredImageWithClip rectangle p (0.0:+0.0) im\n\n-- Typography ------------------------------------------------------------------------------------------------------------------------------\n\n-- | Renders the given string (with an arbitrary function 'draw'). The position of the centre of the bounding box is\n--   given by the pin point 'p' and an 'anchor' (whose coordinates are normalised with respect to the text bounds).\n-- TODO: Extract anchoring logic\n-- TODO: Define anchor constants (eg. left:+top, centre:+bottom) (?)\nanchoredText :: Complex Double -> Complex Double -> (String -> Cairo.Render a) -> String -> Cairo.Render a\nanchoredText p anchor draw text = do\n  extents <- textsize text\n  vectorise Cairo.moveTo $ p - dotwise (*) (anchor + (0.5:+0.5)) extents\n  draw text\n\n\n-- |\ncentredText :: Complex Double -> (String -> Cairo.Render a) -> String -> Cairo.Render a\ncentredText centre draw text = anchoredText centre (0.0:+0.0) draw text\n", "meta": {"hexsha": "a6f827e3e42f2decb7e275a64acc6c669731bf8b", "size": 10792, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Southpaw/Picasso/Render.hs", "max_stars_repo_name": "SwiftsNamesake/Southpaw", "max_stars_repo_head_hexsha": "190d2d869083ac9d5e1face165c6afb9955f305b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-07-23T09:11:10.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-23T09:11:10.000Z", "max_issues_repo_path": "lib/Southpaw/Picasso/Render.hs", "max_issues_repo_name": "SwiftsNamesake/Southpaw", "max_issues_repo_head_hexsha": "190d2d869083ac9d5e1face165c6afb9955f305b", "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/Southpaw/Picasso/Render.hs", "max_forks_repo_name": "SwiftsNamesake/Southpaw", "max_forks_repo_head_hexsha": "190d2d869083ac9d5e1face165c6afb9955f305b", "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.5311355311, "max_line_length": 171, "alphanum_fraction": 0.5401223128, "num_tokens": 2489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2752225396311443}}
{"text": "-- (C) Copyright Chris Banks 2011-2012\n\n-- This file is part of The Continuous Pi-calculus Workbench (CPiWB).\n\n--     CPiWB is free software: you can redistribute it and/or modify\n--     it under the terms of the GNU General Public License as published by\n--     the Free Software Foundation, either version 3 of the License, or\n--     (at your option) any later version.\n\n--     CPiWB is distributed in the hope that it will be useful,\n--     but WITHOUT ANY WARRANTY; without even the implied warranty of\n--     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n--     GNU General Public License for more details.\n\n--     You should have received a copy of the GNU General Public License\n--     along with CPiWB.  If not, see <http://www.gnu.org/licenses/>.\n\n{-# OPTIONS_GHC -w #-}\n\nmodule CPi.ODE\n    (-- * Important functions:\n     dPdt,\n     solveODE,\n     evolveProcess,\n     derivs,\n     -- * Types:\n     Solver,\n     P',\n     Expr(..),\n     -- * Functions:\n     timeSeries,\n     timePoints,\n     prettyODE,\n     initials,\n     speciesIn,\n     speciesVars,\n     diff,\n     simp,\n     simpP',\n     (><)\n    )where\n\n--import qualified Data.List as L\nimport qualified Control.Exception as X\nimport qualified Data.Map as Map\nimport Data.Map (Map)\n--import Data.Maybe\n\nimport qualified Numeric.GSL as GSL\nimport qualified Numeric.LinearAlgebra as LA\n\nimport BioCalcLib.Lib\nimport CPi.Lib\nimport CPi.Semantics\n\n--------------------------------------------\n-- Output the ODEs describing a CPi system\n--------------------------------------------\n\n-- Get the ODEs in a functional form.\nxdot :: Env\n     -> P' -- ^\n     -> (Double -> [Double] -> [Double]) -- ^ ODEs in functional form\nxdot env p = xdot'\n    where\n      -- the xdot function we need to return\n      xdot' t xs = toODE p' vmap xs\n      -- simplify the P'\n      p' = Map.toList (simpP' env p)\n      -- map species to indexed vars:\n      defs2vars :: [(Species,Expr)] -> [Int] -> [(Species,Int)]\n      defs2vars ((k,v):ks) (x:xs) = (k,x) : (defs2vars ks xs)\n      defs2vars [] _ = []\n      defs2vars _ [] = X.throw $ CpiException \"CPi.ODE.xdot: run out of vars!\"\n      xvars :: [Int]\n      xvars = [0..]\n      vmap :: [(Species,Int)]\n      vmap = defs2vars p' xvars\n      -- get ODE expressions from P' expressions:\n      toODE :: [(Species,Expr)] -> [(Species,Int)] -> [Double] -> [Double]\n      toODE ps vmap xs = map (convert . snd) ps\n          where\n            convert (Var s') = xs!!(maybe (err s') id (lookup s' vmap))\n            convert (Plus e e') = (convert e) + (convert e')\n            convert (Times e e') = (convert e) * (convert e')\n            convert (Num d) = d\n            err s' = X.throw $ CpiException\n                     (\"Bug: bad lookup (\"++(pretty s')++\") in CPi.ODE.xdot.toODE\")\n\n{- FIXME: xdot and jac share a lot of inlined code. Refactor!\n          vmap etc. can be replaced with 'speciesVars' (see below).\n-}\n\n-- Map species to labels:\nspeciesVars :: Env -> [a] -> P' -> Map Species a\nspeciesVars env vs p' = Map.fromList $ zip (Map.keys p') vs\n\n-- Get the Jacobian in hmatrix form\njac :: Env -> P' -> (Double -> LA.Vector Double -> LA.Matrix Double)\njac env p = jac'\n    where\n      jac' t xs = toJac p' vmap (LA.toList xs)\n      -- simplify the P'\n      p' = Map.toList (simpP' env p)\n      -- map species to indexed vars:\n      defs2vars :: [(Species,Expr)] -> [Int] -> [(Species,Int)]\n      defs2vars ((k,v):ks) (x:xs) = (k,x) : (defs2vars ks xs)\n      defs2vars [] _ = []\n      defs2vars _ [] = X.throw $ CpiException \"CPi.ODE.xdot: run out of vars!\"\n      xvars :: [Int]\n      xvars = [0..]\n      vmap :: [(Species,Int)]\n      vmap = defs2vars p' xvars\n      -- get the jacobian matrix:\n      toJac p vmap xs = (len><len) (map convert (map (simp env) (map diff' (cp (unzip p')))))\n          where\n            len = length p'\n            cp (x,y) = [(a,b)|b<-y,a<-x]\n            diff' (x,e) = diff x e\n            convert (Var s') = xs!!(maybe (err s') id (lookup s' vmap))\n            convert (Plus e e') = (convert e) + (convert e')\n            convert (Times e e') = (convert e) * (convert e')\n            convert (Num d) = d\n            err s' = X.throw $ CpiException\n                     (\"Bug: bad lookup (\"++(pretty s')++\") in CPi.ODE.xdot.toODE\")\n\n-- Bringing in some infix funs from Numeric.LinearAlgebra:\n-- Matrix constructor:\nx><y = x LA.>< y\n-- Vector accessor:\nx@>y = x LA.! y\n\n-- get the initial concentrations of the primes in process space:\ninitials :: Env -> Process -> P' -> [Double]\ninitials env proc p' = initials' (Map.toList (simpP' env p'))\n    where\n      initials' [] = []\n      initials' ((s,_):ss) = (initconc proc s):(initials' ss)\n\n-- Get the time points\ntimePoints :: (Int,(Double,Double)) -> LA.Vector Double\ntimePoints (r,(o,l)) = LA.linspace r (o,l)\n\n-- | An ODE solver.\ntype Solver = Env -- ^ the environment\n            -> Process -- ^ the syntactic process\n            -> MTS -- ^ the MTS (from 'processMTS')\n            -> P' -- ^ the symbolic process space (from 'dPdt')\n            -> (Int,(Double,Double)) -- ^ time points to solve for (points(start,end))\n            -> LA.Matrix Double -- ^ Matrix of numerical solution\n\n-- FIXME: All solvers should be of this type ^\n--        Need to refactor the following to conform.\n--        (So we can pass different solvers around).\n\n-- | Solve the ODEs using the internal solver.\n--   Uses RKf45 explicit solver (general purpose, non-stiff).\nsolveODE :: Solver\nsolveODE env p mts dpdt (ts,(t0,tn))\n    = GSL.odeSolve (xdot env dpdt) (initials env (wholeProc env p mts) dpdt) (timePoints (ts,(t0,tn)))\n\n-- solve ODEs using Jacobian with hmatrix\nsolveODE' :: (Double -> [Double] -> [Double])\n          -> (Double -> LA.Vector Double -> LA.Matrix Double)\n          -> [Double]\n          -> LA.Vector Double\n          -> LA.Matrix Double\nsolveODE' odes jacob inits ts\n   = GSL.odeSolveV (GSL.MSBDF jacob) hi epsAbs epsRel (l2v odes) (LA.fromList inits) ts\n      where\n        hi = (ts@>1 - ts@>0)/100\n        epsAbs = 1e-06\n        epsRel = 1e-06\n        l2v f = \\t -> LA.fromList . f t . LA.toList\nsolveODE'' odes inits ts\n    = GSL.odeSolveV GSL.MSAdams hi epsAbs epsRel (l2v odes) (LA.fromList inits) ts\n      where\n        hi = (ts@>1 - ts@>0)/100\n        epsAbs = 1e-06\n        epsRel = 1e-06\n        l2v f = \\t -> LA.fromList . f t . LA.toList\n\n-- plot the time series with GNUPlot\n-- NOTE: deprecated by the CPi.Plot module.\n--plotODE :: LA.Matrix Double -> LA.Vector Double -> IO ()\n--plotODE x ts = Plot.mplot (ts : LA.toColumns x)\n\n-- pretty print a Map of ODEs:\nprettyODE env map = pp (Map.toList (simpP' env map))\n    where\n      pp [] = []\n      pp ((x,y):z) = \"d[\" ++ pretty(nice x) ++ \"]/dt ===> \" ++ pretty y ++ \"\\n\" ++ pp z\n      nice x = maybe x id (revLookupDef env x)\n\n\n---------------------------------------\n-- Time series output of ODE solutions:\n---------------------------------------\n\n-- e.g. for sending to the model checker\n\n-- A time series here is a list of time points with corresponding\n-- map from Species to concentration.\ntype TimeSeries = [(Double, Map Species Double, Map Species Double)]\n\n-- List of species in a process space (reduced to Defs if possible):\nspeciesIn :: Env -> P' -> [Species]\nspeciesIn env p = map\n                  (\\s->maybe s id (revLookupDef env s))\n                  (map fst (Map.toList (simpP' env p)))\n\n-- Get the raw time series:\ntimeSeries :: LA.Vector Double -- times\n           -> LA.Matrix Double -- concs\n           -> LA.Matrix Double -- derivs\n           -> [Species]\n           -> TimeSeries\ntimeSeries v cm dm ss\n    = timeSeries' (LA.toList v)\n      (map LA.toList (LA.toColumns (LA.tr cm)))\n      (map LA.toList (LA.toColumns (LA.tr dm)))\n      ss\n          where\n            timeSeries' [] _ _ _ = []\n            timeSeries' _ [] _ _ = []\n            timeSeries' _ _ [] _ = []\n            timeSeries' _ _ _ [] = []\n            timeSeries' (t:ts) (cs:css) (ds:dss) ss\n                = (t, Map.fromList (zip ss cs), Map.fromList (zip ss ds))\n                  : timeSeries' ts css dss ss\n\n\n-----------------------------------\n-- Process evolution\n-----------------------------------\n\n-- | Gives the syntactic process with initial conditions corresponding to the\n-- | end conditions of the given process.\n\nevolveProcess :: Env -- ^ the environment\n              -> Process -- ^ the syntactic process\n              -> MTS -- ^ the MTS (from 'processMTS')\n              -> P' -- ^ the symbolic process space (from 'dPdt')\n              -> (Int,(Double,Double)) -- ^ time points to solve for (points(start,end))\n              -> Solver -- ^ the ODE solving function to use\n              -> Process\nevolveProcess env p mts p' ts solver\n    = let matrix = solver env p mts p' ts\n          vals = LA.toList $ last $ LA.toRows $ matrix\n          ss = speciesIn env p'\n          (Process _ net) = p\n      in Process (zip ss vals) net\n\n\n-----------------------------\n-- Concentration derivatives\n-----------------------------\n\nderivs :: Env -- ^ the Environment\n       -> P' -- ^ the symbolic process space (from 'dPdt')\n       -> (Int,(Double,Double)) -- ^ time points to solve for (points(start,end))\n       -> LA.Matrix Double -- ^ Matrix of numerical solution\n       -> LA.Matrix Double -- ^ Matrix of concentration derivatives\nderivs env p' ts solns\n    = LA.fromLists $\n      map\n      (\\(t,sol)->(xdot env p') t sol)\n      (zip (LA.toList(timePoints ts)) (LA.toLists solns))\n\n--------------------------------------------\n-- Symbolic semantics\n--------------------------------------------\n\n-- Here we build the symbolic counterpart to the CPi immediate behaviour\n-- substituting a variable for the real values.\n\n-- We map to an expression, rather than a real value:\ndata Expr = Var Species\n          | Plus Expr Expr\n          | Times Expr Expr\n          | Num Double\n            deriving (Show,Eq,Ord)\n\ninstance Pretty Expr where\n    pretty (Var x) = \"[\" ++ (pretty x) ++ \"]\"\n    pretty (Plus x y) = pretty x ++ \" + \" ++ pretty y\n    pretty (Times (Plus x y) (Plus x' y'))\n        = \"(\" ++ pretty (Plus x y) ++ \") * (\" ++ pretty (Plus x' y') ++ \")\"\n    pretty (Times (Plus x y) z)\n        = \"(\" ++ pretty (Plus x y) ++ \") * \" ++ pretty z\n    pretty (Times x (Plus y z))\n        = pretty x ++ \" * (\" ++ pretty (Plus y z) ++ \")\"\n    pretty (Times x y) = pretty x ++ \" * \" ++ pretty y\n    pretty (Num k) = show k\n\n-- | Symbolic representation of the process space.\ntype P' = Map Species Expr\ntype D' = Map (Species,Name,Concretion) Expr\n\n-- pretty print our symbolic immediate behaviour:\nprettyP' x = concat $ map (\\(k,v)->((pretty k)++\" |-> \"++(pretty v)++\"\\n\")) (Map.toList x)\n\n-- Zero vectors:\np0' :: P'\np0' = Map.empty\nd0' :: D'\nd0' = Map.empty\n\n-- vector constructors:\npVec' :: Env -> Species -> Expr -> P'\npVec' env s x\n    = foldr (\\s' -> \\m -> Map.insertWith Plus s' x m) p0' (primes env s)\ndVec' :: (Species,Name,Concretion) -> Expr -> D'\ndVec' t x = Map.singleton t x\n\n-- Vector addition in P' and D':\npplus' :: P' -> P' -> P'\npplus' x y = Map.unionWith (Plus) x y\ndplus' :: D' -> D' -> D'\ndplus' x y = Map.unionWith (Plus) x y\n\n-- Scalar multiplication in P and D:\nptimes' :: P' -> Double -> P'\nptimes' p v = Map.map (Times (Num v)) p\ndtimes' :: D' -> Double -> D'\ndtimes' d v = Map.map (Times (Num v)) d\n\n-- Vector subtraction in P and D:\npminus' :: P' -> P' -> P'\npminus' x y = x `pplus'` (y `ptimes'` (-1))\ndminus' :: D' -> D' -> D'\ndminus' x y = x `dplus'` (y `dtimes'` (-1))\n\n-- The interaction potential\npartial' :: Env -> MTS -> Process -> D'\npartial' _ _ (Process [] _) = d0'\npartial' env mts proc@(Process ps _) = foldr dplus' d0' (map partial'' ps)\n    where\n      partial'' (s,_) = foldr dplus' d0'\n                        (map (\\tr->dVec' (triple tr) (Var s)) (pots s))\n      pots x = potentials (MTS (lookupTrans mts x))\n      triple (TransSC s n c) = (s,n,c)\n      triple _ = X.throw $ CpiException (\"Bug: CPi.ODE.partial'.triple passed something other than a TransSC\")\n\n-- The interaction tensor\ntensor' :: Env -> AffNet -> D' -> D' -> P'\ntensor' env net ds1 ds2 = foldr pplus' p0' (map expr ds)\n    where\n      expr (x,y,p) = pVec' env p (expr' x y) `pminus'`\n                     pVec' env (tri1(fst(x))) (expr' x y) `pminus'`\n                     pVec' env (tri1(fst(y))) (expr' x y)\n      ds = [(x,y,p)\n            | x<-Map.toList ds1,\n              y<-Map.toList ds2,\n              p<-[maybe Nil id (pseudoapp (tri3(fst(x))) (tri3(fst(y))))],\n              p/=Nil,\n              aff net (tri2(fst(x)),tri2(fst(y))) /= Nothing]\n      -- above: x,y are (Spec,Name,Conc),Concentration);\n      -- a is Rate; p is Species result of pseudoapplication\n      expr' ((s,n,c),e) ((s',n',c'),e')\n          = maybe (Num 0.0)\n            (\\x-> (Times (Num x) (Times e e')))\n            (aff net (n,n'))\n\n-- | The symbolic immediate behaviour of a process (equivalent to the set of ODEs).\ndPdt :: Env -- ^ the environment\n     -> MTS -- ^ the MTS (generated by 'processMTS')\n     -> Process -- ^ the syntactic process\n     -> P' -- ^ the symbolic process space (=ODEs)\ndPdt env mts proc = dPdt' env mts (wholeProc env proc mts)\n    where\n      dPdt' _ _ (Process [] _) = p0'\n      dPdt' env mts p@(Process [(s,c)] net)\n          = foldr pplus' p0' (map f taus)\n            `pplus'`\n            Map.map (\\x->(Times (Num 0.5) x))\n                   (tensor' env net (partial' env mts p) (partial' env mts p))\n          where\n            taus = [x|x<-lookupTrans mts s, tau x]\n            tau (TransT _ _ _) = True\n            tau _ = False\n            f (TransT src r dst)\n                = pVec' env dst (Times (Num k) (Var s)) `pplus'`\n                  pVec' env s (Times (Num(-1*k)) (Var s))\n                      where k = rate r\n                            rate (TTau r) = r\n            f _ = X.throw $ CpiException (\"Bug: CPi.ODE.dPdt'.f passed something other than a TransT\")\n      dPdt' env mts (Process (p:ps) net)\n          = (tensor' env net partH partT)\n            `pplus'` (dPdt' env mts procH)\n            `pplus'` (dPdt' env mts procT)\n                where\n                  partH = partial' env mts procH\n                  partT = partial' env mts procT\n                  procH = Process [p] net\n                  procT = Process ps net\n\n-- Symbolic differentiation of an Expr\ndiff :: Species -> Expr -> Expr\ndiff _ (Num _) = Num 0.0\ndiff x (Var s)\n    | s==x\n        = Num 1.0\n    | otherwise\n        = Num 0.0\ndiff x (Plus a b)\n    = Plus (diff x a) (diff x b)\ndiff x (Times a b)\n    = Plus (Times (diff x a) b) (Times a (diff x b))\n\n-- Simple simplification of an expression\nsimp :: Env -> Expr -> Expr\nsimp env x\n    | x==x' = x'\n    | otherwise = simp env x'\n    where\n      x' = simp' x\n      simp' (Num n) = Num n\n      simp' (Var s) = Var (simpS env s)\n      simp' (Plus (Num 0.0) b) = simp env b\n      simp' (Plus a (Num 0.0)) = simp env a\n      simp' (Plus (Num a) (Num b)) = Num (a+b)\n      simp' (Plus a b) = Plus (simp env a) (simp env b)\n      simp' (Times (Num 0.0) b) = Num 0.0\n      simp' (Times a (Num 0.0)) = Num 0.0\n      simp' (Times (Num 1.0) b) = simp env b\n      simp' (Times a (Num 1.0)) = simp env a\n      simp' (Times (Num (-1.0)) (Num b)) = Num (-b)\n      simp' (Times (Num a) (Num (-1.0))) = Num (-a)\n      simp' (Times (Num a) (Num b)) = Num (a*b)\n      simp' (Times a b) = Times (simp env a) (simp env b)\n\n-- Simplify dP/dt\nsimpP' :: Env -> P' -> P'\nsimpP' env p = Map.mapKeys (simpS env) (Map.map (simp env) p)\n\n-- Simplify species\nsimpS :: Env -> Species -> Species\nsimpS env s = maybe s id (revLookupDef env s)\n", "meta": {"hexsha": "cae02e24e96f0edaadec0e8d2a8de9e445edee6e", "size": 15542, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "cpilib/CPi/ODE.hs", "max_stars_repo_name": "twright/bondwb", "max_stars_repo_head_hexsha": "5557788f8cdf780fa2899ca29eb926ed5c3ab205", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-04T20:00:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-16T11:54:15.000Z", "max_issues_repo_path": "cpilib/CPi/ODE.hs", "max_issues_repo_name": "twright/bondwb", "max_issues_repo_head_hexsha": "5557788f8cdf780fa2899ca29eb926ed5c3ab205", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpilib/CPi/ODE.hs", "max_forks_repo_name": "twright/bondwb", "max_forks_repo_head_hexsha": "5557788f8cdf780fa2899ca29eb926ed5c3ab205", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3227272727, "max_line_length": 110, "alphanum_fraction": 0.5445245142, "num_tokens": 4573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.4225046348141883, "lm_q1q2_score": 0.27520045494908085}}
{"text": "{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n{-# OPTIONS_GHC -Wno-partial-type-signatures #-}\n{-# LANGUAGE StandaloneKindSignatures #-}\nmodule Inference.Conjugate where\n\nimport           Control.Monad.Primitive        ( PrimMonad\n                                                , PrimState\n                                                )\nimport           Control.Monad.Reader           ( ReaderT\n                                                , runReaderT\n                                                )\nimport           Control.Monad.Reader.Class     ( MonadReader(ask) )\nimport           Control.Monad.State            ( State\n                                                , StateT\n                                                , evalState\n                                                , evalStateT\n                                                , execStateT\n                                                , runStateT\n                                                )\nimport           Control.Monad.State.Class      ( get\n                                                , modify\n                                                , put\n                                                )\nimport           Control.Monad.Trans.Maybe      ( MaybeT(MaybeT)\n                                                , runMaybeT\n                                                )\nimport           Control.Monad.Writer\nimport           Data.Dynamic                   ( Dynamic\n                                                , Typeable\n                                                , fromDynamic\n                                                , toDyn\n                                                )\nimport           Data.Kind\nimport           Data.Maybe                     ( fromMaybe )\nimport           Data.MultiSet                 as MS\nimport qualified Data.Sequence                 as S\nimport           Data.Typeable                  ( Proxy(Proxy)\n                                                , typeRep\n                                                )\nimport qualified Data.Vector                   as V\nimport qualified Debug.Trace                   as DT\nimport           GHC.Float                      ( int2Double )\nimport           GHC.Generics\nimport           GHC.TypeNats\nimport           Lens.Micro\nimport           Lens.Micro.Extras\nimport           Lens.Micro.TH                  ( makeLenses )\nimport           Numeric.SpecFunctions          ( logBeta\n                                                , logChoose\n                                                , logFactorial\n                                                , logGamma\n                                                )\nimport           System.Random.MWC.Probability\n                                         hiding ( Uniform )\n\n----------------------------------------------------------------\n-- type classes and families for distributions and conjugates --\n----------------------------------------------------------------\n\n-- | Describes a family of distributions with a fixed form.\n-- For example, a 'Bernoulli' distribution is parameterized by a probability @p@\n-- and produces binary samples\n-- (@True@ with probability @p@, @False@ with probability @1-p@).\n--\n-- Its 'Distribution' instance is:\n-- > instance Distribution Bernoulli where\n-- >   type Params Bernoulli = Double\n-- >   type Support Bernoulli = Bool\n-- >   distSample _ = uncurry bernoulli\n-- >   distLogP _ p True = log p\n-- >   distLogP _ p False = log (1 - p)\nclass Distribution a where\n  type Params a :: Type\n  type Support a :: Type\n  distSample :: (PrimMonad m) => a -> Params a -> Prob m (Support a)\n  distLogP :: a -> Params a -> Support a -> Double\n\n-- -- | Used as a type-lifted kind for conjugate distribution pairs.\n-- data Conj a b = Conj a bb\n\n-- | A type-level marker for treating a distribution as a prior.\nnewtype AsPrior p = AsPrior p\n\n-- -- | A type-level marker for treating a distribution as a likelihood.\n-- newtype AsLk l = AsLk l\n\n-- | Marks two distributions as a conjugate pair of prior and likelihood.\n-- The property of such a pair is that the posterior has the same form as the prior\n-- (including the same 'Params' and 'Support'),\n-- and that its parameters can be obtained analytically from the parameters of the prior\n-- and a set of observations.\n--\n-- The class method 'updatePrior' returns the parameters of the posterior\n-- given the prior parameters after a single observation.\nclass (Distribution p, Distribution l, Support p ~ Params l) => Conjugate p l where\n  priorSingleton :: p -- ^ provides a singleton instance of the prior distribution\n                      -- in order to make sampling from priors easier.\n  updatePrior :: l -> Params p -> Support l -> Params p\n  predLogP :: l -> Params p -> Support l -> Double\n\ntype family Hyper (a :: k) :: Type\ntype instance Hyper (AsPrior p) = Params p\n\ntype family Probs (a :: k) :: Type\ntype instance Probs (AsPrior p) = Support p\n\n-- type family Value (a :: k) :: Type\n-- type instance Value (Conj p l) = Support l\n\n-- helper types for instantiating hyperparameters, parameters, and values\n-- ----------------------------------------------------------------------\n\nnewtype HyperRep p = HyperRep { runHyper :: Hyper (AsPrior p) }\nderiving instance Show (Hyper (AsPrior p)) => Show (HyperRep p)\n\ntype instance Hyper (a :: (Type -> Type) -> Type) = a HyperRep\n\nnewtype ProbsRep p = ProbsRep { runProbs :: Probs (AsPrior p)}\nderiving instance Show (Probs (AsPrior p)) => Show (ProbsRep p)\n\ntype instance Probs (a :: (Type -> Type) -> Type) = a ProbsRep\n\n-- newtype ValueRep p l = ValueRep { runValue :: Value (Conj p l) }\n-- deriving instance Show (Value (Conj p l)) => Show (ValueRep p l)\n\n-- type instance Value (a :: (Type -> Type -> Type) -> Type) = a ValueRep\n\n-----------------------------------------------------\n-- generic magic for conjugates and parameter sets --\n-----------------------------------------------------\n\n-- Jeffreys prior\n-- ---------------\n\nclass Jeffreys a where\n  jeffreysPrior :: Hyper a\n\nclass GJeffreys t where\n  gjeffreysPrior :: forall p. t p\n\ninstance GJeffreys V1 where\n  gjeffreysPrior = undefined -- ok\n\ninstance GJeffreys U1 where\n  gjeffreysPrior = U1\n\n-- base case: k is a conjugate distribution\ninstance (Jeffreys (AsPrior p)) => GJeffreys (K1 i (HyperRep p)) where\n  gjeffreysPrior = K1 $ HyperRep $ jeffreysPrior @(AsPrior p)\n\n-- recursive case: k is another record\ninstance (Jeffreys k, k HyperRep ~ Hyper k) => GJeffreys (K1 i (k HyperRep)) where\n  gjeffreysPrior = K1 $ jeffreysPrior @k\n\ninstance (GJeffreys t) => GJeffreys (M1 i c (t :: Type -> Type)) where\n  gjeffreysPrior = M1 gjeffreysPrior\n\ninstance (GJeffreys ta, GJeffreys tb) => GJeffreys (ta :*: tb) where\n  gjeffreysPrior = gjeffreysPrior @ta :*: gjeffreysPrior @tb\n\ninstance (Generic (t HyperRep), GJeffreys (Rep (t HyperRep))) => Jeffreys (t :: (Type -> Type) -> Type) where\n  jeffreysPrior = GHC.Generics.to (gjeffreysPrior @(Rep (t HyperRep)))\n\n-- uniform prior\n-- -------------\n\nclass Uniform a where\n  uniformPrior :: Hyper a\n\nclass GUniform t where\n  guniformPrior :: forall p. t p\n\ninstance GUniform V1 where\n  guniformPrior = undefined -- ok\n\ninstance GUniform U1 where\n  guniformPrior = U1\n\n-- base case: k is a conjugate distribution\ninstance (Uniform (AsPrior p)) => GUniform (K1 i (HyperRep p)) where\n  guniformPrior = K1 $ HyperRep $ uniformPrior @(AsPrior p)\n\n-- recursive case: k is another record\ninstance (Uniform k, k HyperRep ~ Hyper k) => GUniform (K1 i (k HyperRep)) where\n  guniformPrior = K1 $ uniformPrior @k\n\ninstance (GUniform t) => GUniform (M1 i c (t :: Type -> Type)) where\n  guniformPrior = M1 guniformPrior\n\ninstance (GUniform ta, GUniform tb) => GUniform (ta :*: tb) where\n  guniformPrior = guniformPrior @ta :*: guniformPrior @tb\n\ninstance (Generic (t HyperRep), GUniform (Rep (t HyperRep))) => Uniform (t :: (Type -> Type) -> Type) where\n  uniformPrior = GHC.Generics.to (guniformPrior @(Rep (t HyperRep)))\n\n-- sampling from prior\n-- ------------------\n\nclass Prior a where\n  sampleProbs :: (PrimMonad m) => Hyper a -> Prob m (Probs a)\n\nclass GPrior i o where\n  gsampleProbs :: forall m p. PrimMonad m => i p -> Prob m (o p)\n\ninstance GPrior V1 V1 where\n  gsampleProbs = undefined -- ok\n\ninstance GPrior U1 U1 where\n  gsampleProbs _ = pure U1\n\n-- base case: k is a conjugate distribution\ninstance (Prior (AsPrior p)) => GPrior (K1 i (HyperRep p)) (K1 i (ProbsRep p)) where\n  gsampleProbs (K1 (HyperRep hyper)) =\n    K1 . ProbsRep <$> sampleProbs @(AsPrior p) hyper\n\n-- recursive case: k is another record\ninstance (Prior k, k HyperRep ~ Hyper k, k ProbsRep ~ Probs k) =>\n         GPrior (K1 i (k HyperRep)) (K1 i (k ProbsRep)) where\n  gsampleProbs (K1 hyper) = K1 <$> sampleProbs @k hyper\n\ninstance (GPrior ti to) => GPrior (M1 i c ti) (M1 i' c' to) where\n  gsampleProbs (M1 x) = M1 <$> gsampleProbs x\n\ninstance (GPrior ia oa, GPrior ib ob) => GPrior (ia :*: ib) (oa :*: ob) where\n  gsampleProbs (a :*: b) = (:*:) <$> gsampleProbs a <*> gsampleProbs b\n\ninstance (GPrior ia oa, GPrior ib ob) => GPrior (ia :+: ib) (oa :+: ob) where\n  gsampleProbs (L1 a) = L1 <$> gsampleProbs a\n  gsampleProbs (R1 b) = R1 <$> gsampleProbs b\n\ninstance ( Generic (a HyperRep)\n         , Generic (a ProbsRep)\n         , GPrior (Rep (a HyperRep)) (Rep (a ProbsRep))\n         ) => Prior (a :: (Type -> Type) -> Type) where\n  sampleProbs hyper = GHC.Generics.to <$> gsampleProbs (from hyper)\n\n-----------------------\n-- likelihood monads --\n-----------------------\n\ntype Accessor r p = forall f . Lens' (r f) (f p)\n\nclass Monad m => RandomInterpreter m r | m -> r where\n  type SampleCtx m a :: Constraint\n  sampleValue :: (Conjugate p l, SampleCtx m l) => String -> l -> Accessor r p -> m (Support l)\n  sampleConst :: (Distribution d, SampleCtx m d) => String -> d -> Params d -> m (Support d)\n  permutationPlate :: (Ord a) => Int -> m a -> m [a]\n\nnewtype Trace (r :: (Type -> Type) -> Type)  = Trace { runTrace :: S.Seq Dynamic }\n  deriving (Show)\n\nobserveValue\n  :: (Conjugate p l, Typeable (Support l), Monad m)\n  => String\n  -> l\n  -> Accessor r p\n  -> Support l\n  -> StateT (Trace r) m ()\nobserveValue _ _ _ val = modify $ \\(Trace st) -> Trace $ st S.|> toDyn val\n\nobserveConst\n  :: (Distribution d, Typeable (Support d), Monad m)\n  => String\n  -> d\n  -> Params d\n  -> Support d\n  -> StateT (Trace r) m ()\nobserveConst _ _ _ val = modify $ \\(Trace st) -> Trace $ st S.|> toDyn val\n\ntakeTrace :: Typeable a => Trace r -> Maybe (a, Trace r)\ntakeTrace (Trace t) = do\n  (valDyn, rest) <- case S.viewl t of\n    S.EmptyL         -> Nothing\n    valDyn S.:< rest -> Just (valDyn, rest)\n  val <- fromDynamic valDyn\n  pure (val, Trace rest)\n\n-- just sample\n-- -----------\n\nnewtype SampleI m r a = SampleI (ReaderT (r ProbsRep) (Prob m) a)\n  deriving (Functor, Applicative, Monad)\n\ninstance (PrimMonad m) => RandomInterpreter (SampleI m r) r where\n  type SampleCtx (SampleI m r) a = ()\n  sampleValue\n    :: forall p l\n     . (Conjugate p l)\n    => String\n    -> l\n    -> Accessor r p\n    -> SampleI m r (Support l)\n  sampleValue _ lk getProbs = SampleI $ do\n    probs <- ask\n    lift $ distSample lk $ runProbs $ view getProbs probs\n  sampleConst\n    :: forall d\n     . (Distribution d)\n    => String\n    -> d\n    -> Params d\n    -> SampleI m r (Support d)\n  sampleConst _ dist params = SampleI $ lift $ distSample dist params\n  permutationPlate = replicateM\n\nsampleResult :: p ProbsRep -> SampleI m p a -> Gen (PrimState m) -> m a\nsampleResult probs (SampleI a) = sample (runReaderT a probs)\n\n-- sample and trace the execution process\n-- --------------------------------------\n\nnewtype TraceI m r a = TraceI (ReaderT (r ProbsRep) (StateT (Trace r) (Prob m)) a)\n  deriving (Functor, Applicative, Monad)\n\ninstance (PrimMonad m) => RandomInterpreter (TraceI m r) r where\n  type SampleCtx (TraceI m r) l = Typeable (Support l)\n  sampleValue\n    :: forall p l\n     . (Conjugate p l, Typeable (Support l))\n    => String\n    -> l\n    -> Accessor r p\n    -> TraceI m r (Support l)\n  sampleValue _ lk getProbs = TraceI $ do\n    probs <- ask\n    val   <- lift $ lift $ distSample lk $ runProbs $ view getProbs probs\n    modify $ \\(Trace obs) -> Trace $ obs S.|> toDyn val\n    pure val\n  sampleConst\n    :: forall d\n     . (Distribution d, Typeable (Support d))\n    => String\n    -> d\n    -> Params d\n    -> TraceI m r (Support d)\n  sampleConst _ dist params = TraceI $ do\n    val <- lift $ lift $ distSample dist params\n    modify $ \\(Trace obs) -> Trace $ obs S.|> toDyn val\n    pure val\n  permutationPlate = replicateM\n\nsampleTrace\n  :: r ProbsRep -> TraceI m r a -> Gen (PrimState m) -> m (a, Trace r)\nsampleTrace probs (TraceI a) = do\n  let st = runReaderT a probs\n      pr = runStateT st (Trace mempty)\n  sample pr\n\n-- evaluate the probability of a trace\n-- -----------------------------------\n\nnewtype EvalTraceI r a = EvalTraceI (ReaderT (r ProbsRep) (StateT (Trace r, Double) Maybe) a)\n  deriving (Functor, Applicative, Monad)\n\ninstance RandomInterpreter (EvalTraceI r) r where\n  type SampleCtx (EvalTraceI r) l = Typeable (Support l)\n  sampleValue\n    :: forall p l\n     . (Conjugate p l, Typeable (Support l))\n    => String\n    -> l\n    -> Accessor r p\n    -> EvalTraceI r (Support l)\n  sampleValue _ lk getProbs = EvalTraceI $ do\n    probs              <- ask\n    (trace, totalLogP) <- get\n    (val  , trace'   ) <- lift $ lift $ takeTrace trace\n    let logP = distLogP lk (runProbs $ view getProbs probs) val\n    put (trace', totalLogP + logP)\n    pure val\n  sampleConst\n    :: forall d\n     . (Distribution d, Typeable (Support d))\n    => String\n    -> d\n    -> Params d\n    -> EvalTraceI r (Support d)\n  sampleConst _ dist params = EvalTraceI $ do\n    (trace, totalLogP) <- get\n    (val  , trace'   ) <- lift $ lift $ takeTrace trace\n    let logP = distLogP dist params val\n    put (trace', totalLogP + logP)\n    pure val\n  permutationPlate n submodel = EvalTraceI $ do\n    probs                     <- ask\n    (trace  , totalLogP     ) <- get\n    (results, (trace', logP)) <- lift $ lift $ runTraceLogP\n      probs\n      trace\n      (replicateM n submodel)\n    let unique = MS.fromList results\n        permutations =\n          logFactorial n - sum (logFactorial . snd <$> MS.toOccurList unique)\n    put (trace', totalLogP + logP + permutations)\n    pure results\n\nrunTraceLogP\n  :: r ProbsRep -> Trace r -> EvalTraceI r a -> Maybe (a, (Trace r, Double))\nrunTraceLogP probs trace (EvalTraceI model) = do\n  runStateT (runReaderT model probs) (trace, 0)\n\nevalTraceLogP :: r ProbsRep -> Trace r -> EvalTraceI r a -> Maybe (a, Double)\nevalTraceLogP probs trace model = do\n  (val, (_trace, logp)) <- runTraceLogP probs trace model\n  pure (val, logp)\n\n\n-- evaluate the predictive probability of a trace\n-- -----------------------------------\n\nnewtype EvalPredTraceI r a = EvalPredTraceI (ReaderT (r HyperRep) (StateT (Trace r, Double) Maybe) a)\n  deriving (Functor, Applicative, Monad)\n\ninstance RandomInterpreter (EvalPredTraceI r) r where\n  type SampleCtx (EvalPredTraceI r) l = Typeable (Support l)\n  sampleValue\n    :: forall p l\n     . (Conjugate p l, Typeable (Support l))\n    => String\n    -> l\n    -> Accessor r p\n    -> EvalPredTraceI r (Support l)\n  sampleValue _ lk getHyper = EvalPredTraceI $ do\n    hyper              <- ask\n    (trace, totalLogP) <- get\n    (val  , trace'   ) <- lift $ lift $ takeTrace trace\n    let logP = predLogP @p lk (runHyper $ view getHyper hyper) val\n    put (trace', totalLogP + logP)\n    pure val\n  sampleConst\n    :: forall d\n     . (Distribution d, Typeable (Support d))\n    => String\n    -> d\n    -> Params d\n    -> EvalPredTraceI r (Support d)\n  sampleConst _ dist params = EvalPredTraceI $ do\n    (trace, totalLogP) <- get\n    (val  , trace'   ) <- lift $ lift $ takeTrace trace\n    let logP = distLogP dist params val\n    put (trace', totalLogP + logP)\n    pure val\n  permutationPlate n submodel = EvalPredTraceI $ do\n    probs                     <- ask\n    (trace  , totalLogP     ) <- get\n    (results, (trace', logP)) <- lift $ lift $ runTracePredLogP\n      probs\n      trace\n      (replicateM n submodel)\n    let unique = MS.fromList results\n        permutations =\n          logFactorial n - sum (logFactorial . snd <$> MS.toOccurList unique)\n    put (trace', totalLogP + logP + permutations)\n    pure results\n\nrunTracePredLogP\n  :: r HyperRep -> Trace r -> EvalPredTraceI r a -> Maybe (a, (Trace r, Double))\nrunTracePredLogP hyper trace (EvalPredTraceI model) = do\n  runStateT (runReaderT model hyper) (trace, 0)\n\nevalTracePredLogP\n  :: r HyperRep -> Trace r -> EvalPredTraceI r a -> Maybe (a, Double)\nevalTracePredLogP hyper trace model = do\n  (val, (_trace, logp)) <- runTracePredLogP hyper trace model\n  pure (val, logp)\n\n\n-- update priors\n-- -------------\n\nnewtype UpdatePriorsI r a = UpdatePriorsI (StateT (Trace r, r HyperRep) Maybe a)\n  deriving (Functor, Applicative, Monad)\n\ninstance RandomInterpreter (UpdatePriorsI r) r where\n  type SampleCtx (UpdatePriorsI r) l = Typeable (Support l)\n  sampleValue\n    :: forall p l\n     . (Conjugate p l, Typeable (Support l))\n    => String\n    -> l\n    -> Accessor r p\n    -> UpdatePriorsI r (Support l)\n  sampleValue _ lk accessor = UpdatePriorsI $ do\n    (trace, priors) <- get\n    (val  , trace') <- lift $ takeTrace trace\n    let priors' :: r HyperRep\n        priors' = over\n          accessor\n          (\\(HyperRep pr) -> HyperRep $ updatePrior @p @l lk pr val)\n          priors\n    put (trace', priors')\n    pure val\n  sampleConst _ _ _ = UpdatePriorsI $ do\n    (trace, priors) <- get\n    (val  , trace') <- lift $ takeTrace trace\n    put (trace', priors)\n    pure val\n  permutationPlate = replicateM\n\ngetPosterior\n  :: r HyperRep -> Trace r -> UpdatePriorsI r a -> Maybe (r HyperRep)\ngetPosterior priors trace (UpdatePriorsI model) = do\n  (_trace, posteriors) <- execStateT model (trace, priors)\n  pure posteriors\n\n-- show how a trace is generated by a model\n-- ----------------------------------------\n\nnewtype ShowTraceI r a = ShowTraceI (MaybeT (WriterT String (State (Trace r))) a)\n  deriving (Functor, Applicative, Monad)\n\nshowTraceItem\n  :: forall l r\n   . (Show (Support l), Typeable l, Typeable (Support l))\n  => String\n  -> ShowTraceI r (Support l)\nshowTraceItem name = ShowTraceI $ do\n  trace         <- get\n  (val, trace') <- MaybeT $ pure $ takeTrace trace\n  put trace'\n  let distName = show (typeRep (Proxy :: Proxy l))\n  tell\n    $  \"Sampled value \"\n    <> show val\n    <> \" from a \"\n    <> distName\n    <> \" at \"\n    <> name\n    <> \".\\n\"\n  pure val\n\ninstance RandomInterpreter (ShowTraceI r) r where\n  type SampleCtx (ShowTraceI r) l\n    = (Typeable (Support l), Typeable l, Show (Support l))\n  sampleValue\n    :: forall p l\n     . (Conjugate p l, Typeable (Support l), Typeable l, Show (Support l))\n    => String\n    -> l\n    -> Accessor r p\n    -> ShowTraceI r (Support l)\n  sampleValue name _ acc = showTraceItem @l name\n  sampleConst\n    :: forall d\n     . (Distribution d, SampleCtx (ShowTraceI r) d)\n    => String\n    -> d\n    -> Params d\n    -> ShowTraceI r (Support d)\n  sampleConst name _ _ = showTraceItem @d name\n  permutationPlate = replicateM\n\nshowTrace :: Trace r -> ShowTraceI r a -> (Maybe a, String)\nshowTrace trace (ShowTraceI model) =\n  evalState (runWriterT (runMaybeT model)) trace\n\nprintTrace :: Trace r -> ShowTraceI r a -> IO ()\nprintTrace trace model = do\n  let (res, txt) = showTrace trace model\n  putStrLn txt\n  case res of\n    Nothing -> do\n      putStrLn \"Trace does not match the model (stops here)\"\n    Just _ -> pure ()\n\n-- tracing interpreter (for debugging)\n-- -----------------------------------\n\nnewtype TraceTraceI r a = TraceTraceI (State (Trace r) a)\n  deriving (Functor, Applicative, Monad)\n\ntraceTraceItem\n  :: forall l r\n   . (Show (Support l), Typeable l, Typeable (Support l))\n  => String\n  -> TraceTraceI r (Support l)\ntraceTraceItem name = TraceTraceI $ do\n  trace <- get\n  let loc = show (typeRep (Proxy :: Proxy l)) <> \" at \" <> name\n  case takeTrace trace of\n    Just (val, trace') -> do\n      put trace'\n      DT.traceM $ \"Sampled value \" <> show val <> \" from a \" <> loc <> \".\"\n      pure val\n    Nothing -> error $ \"Incompatible trace at \" <> loc <> \".\"\n\ninstance RandomInterpreter (TraceTraceI r) r where\n  type SampleCtx (TraceTraceI r) l\n    = (Typeable (Support l), Typeable l, Show (Support l))\n  sampleValue\n    :: forall p l\n     . (Conjugate p l, Typeable (Support l), Typeable l, Show (Support l))\n    => String\n    -> l\n    -> Accessor r p\n    -> TraceTraceI r (Support l)\n  sampleValue name _ acc = traceTraceItem @l name\n  sampleConst\n    :: forall d\n     . (Distribution d, SampleCtx (TraceTraceI r) d)\n    => String\n    -> d\n    -> Params d\n    -> TraceTraceI r (Support d)\n  sampleConst name _ _ = traceTraceItem @d name\n  permutationPlate = replicateM\n\ntraceTrace :: Trace r -> TraceTraceI r a -> a\ntraceTrace trace (TraceTraceI model) = evalState model trace\n\n-------------------\n-- distributions --\n-------------------\n\n-- Beta\n-- ----\n\ndata Beta = Beta\n  deriving (Eq, Ord, Show, Generic)\n\ninstance Distribution Beta where\n  type Params Beta = (Double, Double)\n  type Support Beta = Double\n  distSample _ = uncurry beta\n  distLogP _ (a, b) p =\n    log (p ** (a - 1)) + log ((1 - p) ** (b - 1)) - logBeta a b\n\ninstance Jeffreys (AsPrior Beta) where\n  jeffreysPrior = (0.5, 0.5)\n\ninstance Uniform (AsPrior Beta) where\n  uniformPrior = (1, 1)\n\ninstance Prior (AsPrior Beta) where\n  sampleProbs = distSample Beta\n\n-- Bernoulli\n-- ---------\n\ndata Bernoulli = Bernoulli\n  deriving (Eq, Ord, Show, Generic)\n\ninstance Distribution Bernoulli where\n  type Params Bernoulli = Double\n  type Support Bernoulli = Bool\n  distSample _ = bernoulli\n  distLogP _ p True  = log p\n  distLogP _ p False = log (1 - p)\n\n-- Binomial\n-- --------\n\nnewtype Binomial = Binomial Int\n  deriving (Eq, Ord, Show, Generic)\n\ninstance Distribution Binomial where\n  type Params Binomial = Double\n  type Support Binomial = Int\n  distSample (Binomial n) = binomial n\n  distLogP (Binomial n) p k =\n    logChoose n k + (log p * k') + (log (1 - p) * (n' - k'))\n   where\n    k' = int2Double k\n    n' = int2Double n\n\n-- Categorical\n-- -----------\n\ntype Categorical :: Nat -> Type\ndata Categorical n = Categorical\n  deriving (Eq, Ord, Show, Generic)\n\ninstance Distribution (Categorical n) where\n  type Params (Categorical n) = V.Vector Double\n  type Support (Categorical n) = Int\n  distSample _ = categorical\n  distLogP _ ps cat = log $ fromMaybe 0 $ ps V.!? cat\n\n-- Dirichlet\n-- ---------\n\ntype Dirichlet :: Nat -> Type\ndata Dirichlet n = Dirichlet\n  deriving (Eq, Ord, Show, Generic)\n\ninstance Distribution (Dirichlet n) where\n  type Params (Dirichlet n) = V.Vector Double\n  type Support (Dirichlet n) = V.Vector Double\n  distSample _ = dirichlet\n  distLogP _ counts probs = logp + logz\n   where\n    logp = sum (V.zipWith (\\a x -> log x * (a - 1)) counts probs)\n    logz = logGamma (sum counts) - sum (logGamma <$> counts)\n\ninstance KnownNat n => Jeffreys (AsPrior (Dirichlet n)) where\n  jeffreysPrior = V.replicate (fromIntegral $ natVal (Proxy :: Proxy n)) 0.5\n\ninstance KnownNat n => Uniform (AsPrior (Dirichlet n)) where\n  uniformPrior = V.replicate (fromIntegral $ natVal (Proxy :: Proxy n)) 1\n\ninstance Prior (AsPrior (Dirichlet n)) where\n  sampleProbs = distSample Dirichlet\n\n-- Geometric (from 0)\n-- ------------------\n\ndata Geometric0 = Geometric0\n  deriving (Eq, Ord, Show, Generic)\n\ninstance Distribution Geometric0 where\n  type Params Geometric0 = Double\n  type Support Geometric0 = Int\n  distSample _ = geometric0\n   where\n    geometric0 p = do\n      coin <- bernoulli p\n      if coin then pure 0 else (1 +) <$> geometric0 p\n  distLogP _ p val | val >= 0  = (log (1 - p) * int2Double val) + log p\n                   | otherwise = log 0\n\n-- Geometric (from 1)\n-- ------------------\n\ndata Geometric1 = Geometric1\n  deriving (Eq, Ord, Show, Generic)\n\ninstance Distribution Geometric1 where\n  type Params Geometric1 = Double\n  type Support Geometric1 = Int\n  distSample _ = geometric1\n   where\n    geometric1 p = do\n      coin <- bernoulli p\n      if coin then pure 1 else (1 +) <$> geometric1 p\n  distLogP _ p val | val >= 1  = (log (1 - p) * int2Double (val - 1)) + log p\n                   | otherwise = log 0\n\n-----------------------------\n-- conjugate distributions --\n-----------------------------\n\n-- beta bernoulli\n-- --------------\n\ninstance Conjugate Beta Bernoulli where\n  priorSingleton = Beta\n  updatePrior _ (a, b) False = (a, b + 1)\n  updatePrior _ (a, b) True  = (a + 1, b)\n  predLogP _ (a, b) False = log a - log (a + b)\n  predLogP _ (a, b) True  = log b - log (a + b)\n\n-- B(1+a, b)   G(1+a) G(b) G(a+b)   G(1+a) G(a+b)   a G(a) G(a+b)        a\n-- --------- = ------------------ = ------------- = ----------------- = ---\n-- B(a, b)     G(a) G(b) G(a+b+1)   G(a) G(a+b+1)   G(a) (a+b) G(a+b)   a+b\n\n-- beta binomial\n-- -------------\n\ninstance Conjugate Beta Binomial where\n  priorSingleton = Beta\n  updatePrior (Binomial n) (a, b) x = (a + x', b + (n' - x'))\n   where\n    x' = int2Double x\n    n' = int2Double n\n  predLogP (Binomial n) (a, b) k =\n    logChoose n k + logBeta (k' + a) (n' - k' + a) - logBeta a b\n   where\n    n' = int2Double n\n    k' = int2Double k\n\n-- beta geometric0\n-- ---------------\n\ninstance Conjugate Beta Geometric0 where\n  priorSingleton = Beta\n  updatePrior _ (a, b) k = (a + 1, b + int2Double k)\n  predLogP _ (a, b) k =\n    (log a + logGamma (a + b) + logGamma (k' + b))\n      - (logGamma b + logGamma (a + b + k' + 1))\n    where k' = int2Double k\n\n\n-- beta geometric1\n-- ---------------\n\ninstance Conjugate Beta Geometric1 where\n  priorSingleton = Beta\n  updatePrior _ (a, b) k = (a + 1, b + int2Double (k - 1))\n  predLogP _ (a, b) k =\n    (log a + logGamma (a + b) + logGamma (k' + b))\n      - (logGamma b + logGamma (a + b + k' + 1))\n    where k' = int2Double k - 1\n\n-- dirichlet categorical\n-- ---------------------\n\ninstance Conjugate (Dirichlet n) (Categorical n) where\n  priorSingleton = Dirichlet\n  updatePrior _ counts obs\n    | obs >= 0, obs < V.length counts\n    = counts V.// [(obs, (counts V.! obs) + 1)]\n    | otherwise\n    = counts\n  predLogP _ counts obs =\n    log (fromMaybe 0 $ counts V.!? obs) - log (V.sum counts)\n", "meta": {"hexsha": "c1f05f6f987b9140621a135eb73adee33edc652e", "size": 26792, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Inference/Conjugate.hs", "max_stars_repo_name": "DCMLab/conjugate-haskell-programs", "max_stars_repo_head_hexsha": "f2f48f7942605722494b2cd58be573b85dadc106", "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/Inference/Conjugate.hs", "max_issues_repo_name": "DCMLab/conjugate-haskell-programs", "max_issues_repo_head_hexsha": "f2f48f7942605722494b2cd58be573b85dadc106", "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/Inference/Conjugate.hs", "max_forks_repo_name": "DCMLab/conjugate-haskell-programs", "max_forks_repo_head_hexsha": "f2f48f7942605722494b2cd58be573b85dadc106", "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.5145631068, "max_line_length": 109, "alphanum_fraction": 0.5909226635, "num_tokens": 7490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521102, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2736977495091383}}
{"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE RankNTypes #-}\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702\n{-# LANGUAGE Trustworthy #-}\n{-# LANGUAGE DeriveGeneric #-}\n#endif\n{-# LANGUAGE DeriveDataTypeable #-}\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 708\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n#endif\n-----------------------------------------------------------------------------\n-- |\n-- License     :  BSD-style (see the file LICENSE)\n-- Maintainer  :  Edward Kmett <ekmett@gmail.com>\n-- Stability   :  provisional\n-- Portability :  portable\n--\n-- Operations on affine spaces.\n-----------------------------------------------------------------------------\nmodule Linear.Affine where\n\nimport Control.Applicative\nimport Control.DeepSeq\nimport Control.Monad (liftM)\nimport Control.Lens\nimport Data.Binary as Binary\nimport Data.Bytes.Serial\nimport Data.Complex (Complex)\nimport Data.Data\nimport Data.Distributive\nimport Data.Foldable as Foldable\nimport Data.Functor.Bind\nimport Data.Functor.Classes\nimport Data.Functor.Rep as Rep\nimport Data.HashMap.Lazy (HashMap)\nimport Data.Hashable\nimport Data.IntMap (IntMap)\nimport Data.Ix\nimport Data.Map (Map)\nimport Data.Serialize as Cereal\nimport Data.Vector (Vector)\nimport Foreign.Storable\n#if __GLASGOW_HASKELL__ >= 702\nimport GHC.Generics (Generic)\n#endif\n#if __GLASGOW_HASKELL__ >= 706\nimport GHC.Generics (Generic1)\n#endif\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed.Base as U\nimport Linear.Epsilon\nimport Linear.Metric\nimport Linear.Plucker\nimport Linear.Quaternion\nimport Linear.V\nimport Linear.V0\nimport Linear.V1\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport Linear.Vector\n\n#ifdef HLINT\n{-# ANN module \"HLint: ignore Unused LANGUAGE pragma\" #-}\n#endif\n\n-- | An affine space is roughly a vector space in which we have\n-- forgotten or at least pretend to have forgotten the origin.\n--\n-- > a .+^ (b .-. a)  =  b@\n-- > (a .+^ u) .+^ v  =  a .+^ (u ^+^ v)@\n-- > (a .-. b) ^+^ v  =  (a .+^ v) .-. q@\nclass Additive (Diff p) => Affine p where\n  type Diff p :: * -> *\n\n  infixl 6 .-.\n  -- | Get the difference between two points as a vector offset.\n  (.-.) :: Num a => p a -> p a -> Diff p a\n\n  infixl 6 .+^\n  -- | Add a vector offset to a point.\n  (.+^) :: Num a => p a -> Diff p a -> p a\n\n  infixl 6 .-^\n  -- | Subtract a vector offset from a point.\n  (.-^) :: Num a => p a -> Diff p a -> p a\n  p .-^ v = p .+^ negated v\n  {-# INLINE (.-^) #-}\n\n-- | Compute the quadrance of the difference (the square of the distance)\nqdA :: (Affine p, Foldable (Diff p), Num a) => p a -> p a -> a\nqdA a b = Foldable.sum (fmap (join (*)) (a .-. b))\n{-# INLINE qdA #-}\n\n-- | Distance between two points in an affine space\ndistanceA :: (Floating a, Foldable (Diff p), Affine p) => p a -> p a -> a\ndistanceA a b = sqrt (qdA a b)\n{-# INLINE distanceA #-}\n\n#define ADDITIVEC(CTX,T) instance CTX => Affine T where type Diff T = T ; \\\n  (.-.) = (^-^) ; {-# INLINE (.-.) #-} ; (.+^) = (^+^) ; {-# INLINE (.+^) #-} ; \\\n  (.-^) = (^-^) ; {-# INLINE (.-^) #-}\n#define ADDITIVE(T) ADDITIVEC((), T)\n\nADDITIVE([])\nADDITIVE(Complex)\nADDITIVE(ZipList)\nADDITIVE(Maybe)\nADDITIVE(IntMap)\nADDITIVE(Identity)\nADDITIVE(Vector)\nADDITIVE(V0)\nADDITIVE(V1)\nADDITIVE(V2)\nADDITIVE(V3)\nADDITIVE(V4)\nADDITIVE(Plucker)\nADDITIVE(Quaternion)\nADDITIVE(((->) b))\nADDITIVEC(Ord k, (Map k))\nADDITIVEC((Eq k, Hashable k), (HashMap k))\nADDITIVEC(Dim n, (V n))\n\n-- | A handy wrapper to help distinguish points from vectors at the\n-- type level\nnewtype Point f a = P (f a)\n  deriving ( Eq, Ord, Show, Read, Monad, Functor, Applicative, Foldable\n           , Eq1, Ord1, Show1, Read1\n           , Traversable, Apply, Additive, Metric\n           , Fractional , Num, Ix, Storable, Epsilon\n           , Hashable\n#if __GLASGOW_HASKELL__ >= 702\n           , Generic\n#endif\n#if __GLASGOW_HASKELL__ >= 706\n           , Generic1\n#endif\n#if __GLASGOW_HASKELL__ >= 708\n           , Typeable, Data\n#endif\n           )\n\ninstance NFData (f a) => NFData (Point f a) where\n  rnf (P x) = rnf x\n\ninstance Serial1 f => Serial1 (Point f) where\n  serializeWith f (P p) = serializeWith f p\n  deserializeWith m = P `liftM` deserializeWith m\n\ninstance Serial (f a) => Serial (Point f a) where\n  serialize (P p) = serialize p\n  deserialize = P `liftM` deserialize\n\ninstance Binary (f a) => Binary (Point f a) where\n  put (P p) = Binary.put p\n  get = P `liftM` Binary.get\n\ninstance Serialize (f a) => Serialize (Point f a) where\n  put (P p) = Cereal.put p\n  get = P `liftM` Cereal.get\n\n#if __GLASGOW_HASKELL__ < 708\ninstance forall f. Typeable1 f => Typeable1 (Point f) where\n  typeOf1 _ = mkTyConApp (mkTyCon3 \"linear\" \"Linear.Affine\" \"Point\") [] `mkAppTy`\n              typeOf1 (undefined :: f a)\n\nderiving instance (Data (f a), Typeable1 f, Typeable a) => Data (Point f a)\n#endif\n\nlensP :: Lens' (Point g a) (g a)\nlensP afb (P a) = P <$> afb a\n{-# INLINE lensP #-}\n\n_Point :: Iso' (Point f a) (f a)\n_Point = iso (\\(P a) -> a) P\n{-# INLINE _Point #-}\n\ninstance (t ~ Point g b) => Rewrapped (Point f a) t\ninstance Wrapped (Point f a) where\n  type Unwrapped (Point f a) = f a\n  _Wrapped' = _Point\n  {-# INLINE _Wrapped' #-}\n\ninstance Bind f => Bind (Point f) where\n  join (P m) = P $ join $ fmap (\\(P m')->m') m\n\ninstance Distributive f => Distributive (Point f) where\n  distribute = P . collect (\\(P p) -> p)\n\ninstance Representable f => Representable (Point f) where\n  type Rep (Point f) = Rep f\n  tabulate f = P (tabulate f)\n  {-# INLINE tabulate #-}\n  index (P xs) = Rep.index xs\n  {-# INLINE index #-}\n\ntype instance Index (Point f a) = Index (f a)\ntype instance IxValue (Point f a) = IxValue (f a)\n\ninstance Ixed (f a) => Ixed (Point f a) where\n  ix l = lensP . ix l\n  {-# INLINE ix #-}\n\ninstance Traversable f => Each (Point f a) (Point f b) a b where\n  each = traverse\n  {-# INLINE each #-}\n\ninstance R1 f => R1 (Point f) where\n  _x = lensP . _x\n  {-# INLINE _x #-}\n\ninstance R2 f => R2 (Point f) where\n  _y = lensP . _y\n  {-# INLINE _y #-}\n  _xy = lensP . _xy\n  {-# INLINE _xy #-}\n\ninstance R3 f => R3 (Point f) where\n  _z = lensP . _z\n  {-# INLINE _z #-}\n  _xyz = lensP . _xyz\n  {-# INLINE _xyz #-}\n\ninstance R4 f => R4 (Point f) where\n  _w = lensP . _w\n  {-# INLINE _w #-}\n  _xyzw = lensP . _xyzw\n  {-# INLINE _xyzw #-}\n\ninstance Additive f => Affine (Point f) where\n  type Diff (Point f) = f\n  P x .-. P y = x ^-^ y\n  {-# INLINE (.-.) #-}\n  P x .+^ v = P (x ^+^ v)\n  {-# INLINE (.+^) #-}\n  P x .-^ v = P (x ^-^ v)\n  {-# INLINE (.-^) #-}\n\n-- | Vector spaces have origins.\norigin :: (Additive f, Num a) => Point f a\norigin = P zero\n\n-- | An isomorphism between points and vectors, given a reference\n--   point.\nrelative :: (Additive f, Num a) => Point f a -> Iso' (Point f a) (f a)\nrelative p0 = iso (.-. p0) (p0 .+^)\n{-# INLINE relative #-}\n\ndata instance U.Vector    (Point f a) =  V_P !(U.Vector    (f a))\ndata instance U.MVector s (Point f a) = MV_P !(U.MVector s (f a))\ninstance U.Unbox (f a) => U.Unbox (Point f a)\n\ninstance U.Unbox (f a) => M.MVector U.MVector (Point f a) where\n  {-# INLINE basicLength #-}\n  {-# INLINE basicUnsafeSlice #-}\n  {-# INLINE basicOverlaps #-}\n  {-# INLINE basicUnsafeNew #-}\n  {-# INLINE basicUnsafeRead #-}\n  {-# INLINE basicUnsafeWrite #-}\n  basicLength (MV_P v) = M.basicLength v\n  basicUnsafeSlice m n (MV_P v) = MV_P (M.basicUnsafeSlice m n v)\n  basicOverlaps (MV_P v) (MV_P u) = M.basicOverlaps v u\n  basicUnsafeNew n = MV_P `liftM` M.basicUnsafeNew n\n  basicUnsafeRead (MV_P v) i = P `liftM` M.basicUnsafeRead v i\n  basicUnsafeWrite (MV_P v) i (P x) = M.basicUnsafeWrite v i x\n#if MIN_VERSION_vector(0,11,0)\n  basicInitialize (MV_P v) = M.basicInitialize v\n  {-# INLINE basicInitialize #-}\n#endif\n\ninstance U.Unbox (f a) => G.Vector U.Vector (Point f a) where\n  {-# INLINE basicUnsafeFreeze #-}\n  {-# INLINE basicUnsafeThaw   #-}\n  {-# INLINE basicLength       #-}\n  {-# INLINE basicUnsafeSlice  #-}\n  {-# INLINE basicUnsafeIndexM #-}\n  basicUnsafeFreeze (MV_P v) = V_P `liftM` G.basicUnsafeFreeze v\n  basicUnsafeThaw   ( V_P v) = MV_P `liftM` G.basicUnsafeThaw   v\n  basicLength       ( V_P v) = G.basicLength v\n  basicUnsafeSlice m n (V_P v) = V_P (G.basicUnsafeSlice m n v)\n  basicUnsafeIndexM (V_P v) i = P `liftM` G.basicUnsafeIndexM v i\n", "meta": {"hexsha": "b1b67da2152fd26a5346c0445e29654da12e19ea", "size": 8564, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Linear/Affine.hs", "max_stars_repo_name": "bgamari/linear", "max_stars_repo_head_hexsha": "e474ad140a92fae25b5099c5359a10178086111f", "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/Linear/Affine.hs", "max_issues_repo_name": "bgamari/linear", "max_issues_repo_head_hexsha": "e474ad140a92fae25b5099c5359a10178086111f", "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/Linear/Affine.hs", "max_forks_repo_name": "bgamari/linear", "max_forks_repo_head_hexsha": "e474ad140a92fae25b5099c5359a10178086111f", "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.4295532646, "max_line_length": 81, "alphanum_fraction": 0.6317141523, "num_tokens": 2691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26906947542758086}}
{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE KindSignatures      #-}\n{-# LANGUAGE RecordWildCards     #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications    #-}\n{-# LANGUAGE TypeInType          #-}\n{-# LANGUAGE TypeOperators       #-}\n\nmodule Eigen.SparseMatrix\n  ( -- * Types\n    SparseMatrix(..)\n  , SparseMatrixXf\n  , SparseMatrixXd\n  , SparseMatrixXcf\n  , SparseMatrixXcd\n\n    -- * Matrix internal data\n  , elems\n  , values\n  , innerIndices\n  , outerStarts\n  , innerNNZs\n\n    -- * Accessors\n  , cols\n  , rows\n  , coeff\n  , (!)\n  , getRow\n  , getCol\n  , getRows\n  , getCols\n  , unsafeGetCol\n  , unsafeGetRow\n  , unsafeFromRows\n  , unsafeFromCols\n\n    -- * Matrix conversions\n  , fromList\n  , toList\n  , fromVector\n  , toVector\n  , fromVectorSized\n  , fromListSized\n  , fromDenseList\n  , toDenseList\n  , fromMatrix\n  , toMatrix\n\n    -- * Matrix properties\n  , norm\n  , squaredNorm\n  , blueNorm\n  , block\n  , unsafeBlock\n  , nonZeros\n  , innerSize\n  , outerSize\n\n    -- * Basic matrix algebra\n  , add\n  , sub\n  , mul\n\n    -- * Matrix tranformations\n  , pruned\n  , scale\n  , transpose\n  , adjoint\n  , map\n  , imap\n\n    -- * Matrix representation\n  , compress\n  , uncompress\n  , compressed\n\n    -- * Matrix serialisation\n  , encode\n  , decode\n\n    -- * Mutable matrices\n  , thaw\n  , freeze\n  , unsafeThaw\n  , unsafeFreeze\n  ) where\n\nimport Control.Monad (when, guard)\nimport Control.Monad.Primitive (PrimMonad(..), unsafePrimToPrim)\nimport qualified Prelude\nimport Prelude hiding (read, map)\nimport Data.Binary (Binary(..))\nimport qualified Data.Binary as Binary\nimport qualified Data.ByteString.Lazy as BSL\nimport Data.Complex (Complex)\nimport Data.Kind (Type)\nimport qualified Data.Vector.Storable as VS\nimport qualified Data.Vector.Storable.Mutable as VSM\nimport Foreign.C.String (CString)\nimport Foreign.C.Types (CInt)\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, touchForeignPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Ptr (Ptr)\nimport Foreign.Storable (Storable(..))\nimport qualified Foreign.Concurrent as FC\nimport GHC.TypeLits (Nat, KnownNat, type (<=))\nimport Eigen.Internal\n  ( Elem\n  , Cast(..)\n  , CSparseMatrix\n  , CSparseMatrixPtr\n  , natToInt\n  , Row(..)\n  , Col(..)\n  , CTriplet(..)\n  )\nimport qualified Data.List as List\nimport qualified Eigen.Internal as Internal\nimport qualified Eigen.Matrix as M\nimport qualified Eigen.Matrix.Mutable as MM\nimport qualified Eigen.SparseMatrix.Mutable as SMM\n\n{-| A versatible sparse matrix representation.\nSparseMatrix is the main sparse matrix representation of Eigen's sparse module.\nIt offers high performance and low memory usage.\nIt implements a more versatile variant of the widely-used Compressed Column (or Row) Storage scheme.\nIt consists of four compact arrays:\n* `values`: stores the coefficient values of the non-zeros.\n* `innerIndices`: stores the row (resp. column) indices of the non-zeros.\n* `outerStarts`: stores for each column (resp. row) the index of the first non-zero in the previous two arrays.\n* `innerNNZs`: stores the number of non-zeros of each column (resp. row). The word inner refers to an inner vector that is a column for a column-major matrix, or a row for a row-major matrix. The word outer refers to the other direction.\nThis storage scheme is better explained on an example. The following matrix\n@\n0   3   0   0   0\n22  0   0   0   17\n7   5   0   1   0\n0   0   0   0   0\n0   0   14  0   8\n@\nand one of its possible sparse, __column major__ representation:\n@\nvalues:         22  7   _   3   5   14  _   _   1   _   17  8\ninnerIndices:   1   2   _   0   2   4   _   _   2   _   1   4\nouterStarts:    0   3   5   8   10  12\ninnerNNZs:      2   2   1   1   2\n@\nCurrently the elements of a given inner vector are guaranteed to be always sorted by increasing inner indices.\nThe \"\\_\" indicates available free space to quickly insert new elements. Assuming no reallocation is needed,\nthe insertion of a random element is therefore in @O(nnz_j)@ where @nnz_j@ is the number of nonzeros of the\nrespective inner vector. On the other hand, inserting elements with increasing inner indices in a given inner\nvector is much more efficient since this only requires to increase the respective `innerNNZs` entry that is a @O(1)@ operation.\nThe case where no empty space is available is a special case, and is refered as the compressed mode.\nIt corresponds to the widely used Compressed Column (or Row) Storage schemes (CCS or CRS).\nAny `SparseMatrix` can be turned to this form by calling the `compress` function.\nIn this case, one can remark that the `innerNNZs` array is redundant with `outerStarts` because we the equality:\n@InnerNNZs[j] = OuterStarts[j+1]-OuterStarts[j]@. Therefore, in practice a call to `compress` frees this buffer.\nThe results of Eigen's operations always produces compressed sparse matrices.\nOn the other hand, the insertion of a new element into a `SparseMatrix` converts this later to the uncompressed mode.\nFor more infomration please see Eigen <http://eigen.tuxfamily.org/dox/classEigen_1_1SparseMatrix.html documentation page>.\n-}\nnewtype SparseMatrix :: Nat -> Nat -> Type -> Type where\n  SparseMatrix :: ForeignPtr (CSparseMatrix a) -> SparseMatrix n m a\n\ninstance forall n m a. (Elem a, Show a, KnownNat n, KnownNat m) => Show (SparseMatrix n m a) where\n  show m = concat\n    [ \"SparseMatrix\"\n    , show (rows_ m)\n    , \"x\"\n    , show (cols_ m)\n    , \"\\n\"\n    , List.intercalate \"\\n\" $ Prelude.map (List.intercalate \"\\t\" . Prelude.map show) $ toDenseList m\n    , \"\\n\"\n    ]\n\ninstance forall n m a. (Elem a, KnownNat n, KnownNat m) => Binary (SparseMatrix n m a) where\n  put mat = do\n    put $ Internal.magicCode (undefined :: C a)\n    put $ natToInt @n\n    put $ natToInt @m\n    put $ toVector mat\n  \n  get = do\n    get >>= (`when` fail \"wrong matrix type\") . (/= Internal.magicCode (undefined :: C a))\n    fromVector <$> get\n\n-- | Encode the sparse matrix as a lazy bytestring\nencode :: (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> BSL.ByteString\nencode = Binary.encode\n\n-- | Decode the sparse matrix from a lazy bytestring\ndecode :: (Elem a, KnownNat n, KnownNat m) => BSL.ByteString -> SparseMatrix n m a\ndecode = Binary.decode\n\n-- | Alias for single precision sparse matrix\ntype SparseMatrixXf  n m = SparseMatrix n m Float\n-- | Alias for double precision sparse matrix\ntype SparseMatrixXd  n m = SparseMatrix n m Double\n-- | Alias for single previsiom sparse matrix of complex numbers\ntype SparseMatrixXcf n m = SparseMatrix n m (Complex Float)\n-- | Alias for double prevision sparse matrix of complex numbers\ntype SparseMatrixXcd n m = SparseMatrix n m (Complex Double)\n\n-- | Get the coefficient values of the non-zeros.\nvalues :: Elem a => SparseMatrix n m a -> VS.Vector a\nvalues = VS.map fromC . _getvec Internal.sparse_values\n\n-- | Get the row indices of the non-zeros.\ninnerIndices :: Elem a => SparseMatrix n m a -> VS.Vector Int\ninnerIndices = VS.map fromC . _getvec Internal.sparse_innerIndices\n\n-- | Gets for each column the index of the first non-zero in the previous two arrays.\nouterStarts :: Elem a => SparseMatrix n m a -> VS.Vector Int\nouterStarts = VS.map fromC . _getvec Internal.sparse_outerStarts\n\n-- | Gets the number of non-zeros of each column.\n-- The word inner refers to an inner vector that is a column for a column-major matrix, or a row for a row-major matrix.\n-- The word outer refers to the other direction\ninnerNNZs :: Elem a => SparseMatrix n m a -> Maybe (VS.Vector Int)\ninnerNNZs m\n  | compressed m = Nothing\n  | otherwise    = Just $ VS.map fromC $ _getvec Internal.sparse_innerNNZs m\n\n-- | Number of rows in the sparse matrix\nrows :: forall n m a. (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> Row n\nrows _ = Row @n\n\n-- | Number of colums in the sparse matrix\ncols :: forall n m a. (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> Col m\ncols _ = Col @m\n\n-- | Number of rows in the sparse matrix\nrows_ :: forall n m a. (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> Int\nrows_ _ = natToInt @n\n\n-- | Number of colums in the sparse matrix\ncols_ :: forall n m a. (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> Int\ncols_ _ = natToInt @m\n\n-- | Sparse matrix coefficient at the given row and column\ncoeff :: forall n m r c a. (Elem a, KnownNat n, KnownNat m, KnownNat r, KnownNat c, r <= n, c <= m)\n  => Row r -> Col c -> SparseMatrix n m a -> a\ncoeff _ _ (SparseMatrix fp) =\n  let !c_row = toC $! natToInt @r\n      !c_col = toC $! natToInt @c\n  in Internal.performIO $ withForeignPtr fp $ \\p -> alloca $ \\pq -> do\n       Internal.call $ Internal.sparse_coeff p c_row c_col pq\n       fromC <$> peek pq\n\n-- | Matrix coefficient at the given row and column\n(!) :: forall n m r c a. (Elem a, KnownNat n, KnownNat m, KnownNat r, KnownNat c, r <= n, c <= m)\n  => SparseMatrix n m a -> (Row r, Col c) -> a\n(!) m (row,col) = coeff row col m\n\n{-| For vectors, the l2 norm, and for matrices the Frobenius norm.\n    In both cases, it consists in the square root of the sum of the square of all the matrix entries.\n    For vectors, this is also equals to the square root of the dot product of this with itself.\n-}\nnorm :: Elem a => SparseMatrix n m a -> a\nnorm = _unop Internal.sparse_norm (pure . fromC)\n\n-- | For vectors, the squared l2 norm, and for matrices the Frobenius norm. In both cases, it consists in the sum of the square of all the matrix entries. For vectors, this is also equals to the dot product of this with itself.\nsquaredNorm :: Elem a => SparseMatrix n m a -> a\nsquaredNorm = _unop Internal.sparse_squaredNorm (pure . fromC)\n\n-- | The l2 norm of the matrix using the Blue's algorithm. A Portable Fortran Program to Find the Euclidean Norm of a Vector, ACM TOMS, Vol 4, Issue 1, 1978.\nblueNorm :: Elem a => SparseMatrix n m a -> a\nblueNorm = _unop Internal.sparse_blueNorm (pure . fromC)\n\nunsafeBlock ::\n     (Elem a)\n  => Int\n  -> Int\n  -> Int\n  -> Int\n  -> SparseMatrix n m a\n  -> SparseMatrix n1 m1 a\nunsafeBlock !sr !sc !br !bc =\n  let !c_startRow = toC $! sr\n      !c_startCol = toC $! sc\n      !c_rows     = toC $! br\n      !c_cols     = toC $! bc\n  in _unop (\\p pq -> Internal.sparse_block p c_startRow c_startCol c_rows c_cols pq) _mk\n\n-- | Extract a rectangular block from the sparse matrix, given a startRow, startCol, blockRows, blockCols\nblock :: forall sr sc br bc n m a.\n     (Elem a, KnownNat sr, KnownNat sc, KnownNat br, KnownNat bc, KnownNat n, KnownNat m)\n  => (sr <= n, sc <= m, br <= n, bc <= m)\n  => Row sr\n  -> Col sc\n  -> Row br\n  -> Col bc\n  -> SparseMatrix n m a\n  -> SparseMatrix br bc a\nblock _ _ _ _ =\n  let !c_startRow = toC $! natToInt @sr\n      !c_startCol = toC $! natToInt @sc\n      !c_rows     = toC $! natToInt @br\n      !c_cols     = toC $! natToInt @bc\n  in _unop (\\p pq -> Internal.sparse_block p c_startRow c_startCol c_rows c_cols pq) _mk\n\n-- | Number of non-zeros elements in the sparse matrix\nnonZeros :: Elem a => SparseMatrix n m a -> Int\nnonZeros = _unop Internal.sparse_nonZeros (pure . fromC)\n\n-- | Number of elements in the sparse matrix, including zeros\nelems :: forall n m a. (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> Int\nelems _ = (natToInt @n) * (natToInt @m)\n\n-- | The matrix in the compressed format\ncompress :: Elem a => SparseMatrix n m a -> SparseMatrix n m a\ncompress = _unop Internal.sparse_makeCompressed _mk\n\n-- | The matrix in the uncompressed format\nuncompress :: Elem a => SparseMatrix n m a -> SparseMatrix n m a\nuncompress = _unop Internal.sparse_uncompress _mk\n\n-- | Is the matrix compressed?\ncompressed :: Elem a => SparseMatrix n m a -> Bool\ncompressed = _unop Internal.sparse_isCompressed (pure . (/=0))\n\n-- | Minor dimension with respect to the storage order\ninnerSize :: Elem a => SparseMatrix n m a -> Int\ninnerSize = _unop Internal.sparse_innerSize (pure . fromC)\n\n-- | Major dimension with respect to the storage order\nouterSize :: Elem a => SparseMatrix n m a -> Int\nouterSize = _unop Internal.sparse_outerSize (pure . fromC)\n\n-- | Suppresses all nonzeros which are much smaller than the reference under the tolerance @epsilon@\npruned :: Elem a => a -> SparseMatrix n m a -> SparseMatrix n m a\npruned r = _unop (\\p pq -> alloca $ \\pr -> poke pr (toC r) >> Internal.sparse_prunedRef p pr pq) _mk\n\n-- | Multiply matrix on a given scalar\nscale :: Elem a => a -> SparseMatrix n m a -> SparseMatrix n m a\nscale x = _unop (\\p pq -> alloca $ \\px -> poke px (toC x) >> Internal.sparse_scale p px pq) _mk\n\n-- | Transpose of the sparse matrix\ntranspose :: Elem a => SparseMatrix n m a -> SparseMatrix m n a\ntranspose = _unop Internal.sparse_transpose _mk\n\n-- | Adjoint of the sparse matrix\nadjoint :: Elem a => SparseMatrix n m a -> SparseMatrix m n a\nadjoint = _unop Internal.sparse_adjoint _mk\n\n-- | Add two sparse matrices by adding the corresponding entries together.\nadd :: Elem a => SparseMatrix n m a -> SparseMatrix n m a -> SparseMatrix n m a\nadd = _binop Internal.sparse_add _mk\n\n-- | Subtract two sparse matrices by subtracting the corresponding entries together.\nsub :: Elem a => SparseMatrix n m a -> SparseMatrix n m a -> SparseMatrix n m a\nsub = _binop Internal.sparse_sub _mk\n\n-- | Matrix multiplication.\nmul :: Elem a => SparseMatrix p q a -> SparseMatrix q r a -> SparseMatrix p r a\nmul = _binop Internal.sparse_mul _mk\n\n-- | Map a function over the 'SparseMatrix'.\nmap :: (Elem a, Elem b, KnownNat n, KnownNat m) => (a -> b) -> SparseMatrix n m a -> SparseMatrix n m b\nmap f m = fromVector . VS.map g . toVector $ m where\n  g (CTriplet r c v) = CTriplet r c $ (toC . f . fromC) v\n\n-- | Map an indexed function over the 'SparseMatrix'.\nimap :: (Elem a, Elem b, KnownNat n, KnownNat m) => (Int -> Int -> a -> b) -> SparseMatrix n m a -> SparseMatrix n m b\nimap f m = fromVector . VS.map g . toVector $ m where\n  g (CTriplet r c v) =\n    let !_r = fromC r\n        !_c = fromC c\n        !_v = fromC v\n    in CTriplet r c $ toC $ f _r _c _v\n\n-- | Construct asparse matrix of the given size from the storable vector of triplets (row, col, val)\nfromVector :: forall n m a. (Elem a, KnownNat n, KnownNat m)\n  => VS.Vector (CTriplet a)\n  -> SparseMatrix n m a\nfromVector = fromVectorSized (natToInt @n) (natToInt @m)\n\n-- | Convert a sparse matrix to the list of triplets (row, col, val). Compressed elements will not be included.\ntoVector :: Elem a => SparseMatrix n m a -> VS.Vector (CTriplet a)\ntoVector m@(SparseMatrix fp) = Internal.performIO $ do\n  let !size = nonZeros m\n  tris <- VSM.new size\n  withForeignPtr fp $ \\p ->\n    VSM.unsafeWith tris $ \\q ->\n      Internal.call $ Internal.sparse_toList p q (toC size)\n  VS.unsafeFreeze tris\n\n-- | Convert a sparse matrix to the list of triplets (row, col, val). Compressed elements will not be included.\ntoList :: Elem a => SparseMatrix n m a -> [(Int, Int, a)]\ntoList = Prelude.map fromC . VS.toList . toVector\n\n-- | Construct a sparse matrix from a list of triples (row, val, col)\n--\nfromList :: (Elem a, KnownNat n, KnownNat m) => [(Int, Int, a)] -> SparseMatrix n m a\nfromList = fromVector . VS.fromList . fmap toC\n\nfromListSized :: (Elem a, KnownNat n, KnownNat m) => Int -> Int -> [(Int, Int, a)] -> SparseMatrix n m a\nfromListSized _rows _cols = fromVectorSized _rows _cols . VS.fromList . Prelude.map Internal.toC\n\nfromVectorSized :: forall n m a. (Elem a, KnownNat n, KnownNat m)\n  => Int\n  -> Int\n  -> VS.Vector (CTriplet a)\n  -> SparseMatrix n m a\nfromVectorSized _rows _cols tris =\n  let !c_rs = toC $! _rows\n      !c_cs = toC $! _cols\n      !len  = toC $! VS.length tris\n  in Internal.performIO $ VS.unsafeWith tris $ \\p ->\n       alloca $ \\pq -> do\n         Internal.call $ Internal.sparse_fromList c_rs c_cs p len pq\n         peek pq >>= _mk\n\n\n-- | Construct asparse matrix of the given size from the storable vector of triplets (row, col, val)\n--fromVector :: forall n m a. (Elem a, KnownNat n, KnownNat m)\n--  => VS.Vector (CTriplet a)\n--  -> SparseMatrix n m a\n--fromVector tris =\n--  let !c_rs = toC $! natToInt @n\n--      !c_cs = toC $! natToInt @m\n--      !len  = toC $! VS.length tris\n--  in Internal.performIO $ VS.unsafeWith tris $ \\p ->\n--       alloca $ \\pq -> do\n--         Internal.call $ Internal.sparse_fromList c_rs c_cs p len pq\n--         peek pq >>= _mk\n\n\n\n-- | Convert a sparse matrix to a (n X m) dense list of values.\ntoDenseList :: forall n m a. (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> [[a]]\ntoDenseList mat = [[_unsafeCoeff row col mat | col <- [0 .. _unsafeCols mat - 1]] | row <- [0 .. _unsafeRows mat - 1]]\n\n-- | Construct a sparsematrix from a two-dimensional list of values.\n--   If the dimensions of the list do not match that of the list, 'Nothing' is returned.\n--   Zero values will be compressed.\nfromDenseList :: forall n m a. (Elem a, Eq a, KnownNat n, KnownNat m) => [[a]] -> Maybe (SparseMatrix n m a)\nfromDenseList list =\n  let _rows = List.length list\n      _cols = List.foldl' max 0 $ List.map length list\n  in if ((_rows /= (natToInt @n)) || (_cols /= (natToInt @m)))\n    then Nothing\n    else Just $ fromList $ do\n      (row, vals) <- zip [0..] list\n      (col, val) <- zip [0..] vals\n      guard $ val /= 0\n      return (row, col, val)\n      \n  \n--  fromList $ do\n-- (row, vals) <- zip [0..] list\n-- (col, val) <- zip [0..] vals\n-- guard $ val /= 0\n-- return (row, col, val)\n-- where\n--   rows = List.length list\n--   cols = List.foldl' max 0 $ List.map length list\n\n-- | Construct a dense matrix from a sparse matrix\ntoMatrix :: (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> M.Matrix n m a\ntoMatrix (SparseMatrix fp) = Internal.performIO $ do\n  m0 :: MM.IOMatrix n m a <- MM.new\n  MM.unsafeWith m0 $ \\_vals _rows _cols ->\n    withForeignPtr fp $ \\pm1 ->\n      Internal.call $ Internal.sparse_toMatrix pm1 _vals _rows _cols\n  M.unsafeFreeze m0\n\n-- | Construct a sparse matrix from a dense matrix. zero-elements will be compressed.\nfromMatrix :: (Elem a, KnownNat n, KnownNat m) => M.Matrix n m a -> SparseMatrix n m a\nfromMatrix m1 = Internal.performIO $ alloca $ \\pm0 ->\n  M.unsafeWith m1 $ \\_vals _rows _cols -> do\n    Internal.call $ Internal.sparse_fromMatrix _vals _rows _cols pm0\n    peek pm0 >>= _mk\n\n-- | Yield an immutable copy of the mutable matrix\nfreeze :: (Elem a, PrimMonad p) => SMM.MSparseMatrix n m (PrimState p) a -> p (SparseMatrix n m a)\nfreeze (SMM.MSparseMatrix fp) = SparseMatrix <$> _clone fp\n\n-- | Yield a mutable copy of the immutable matrix.\nthaw :: (Elem a, PrimMonad p) => SparseMatrix n m a -> p (SMM.MSparseMatrix n m (PrimState p) a)\nthaw (SparseMatrix fp) = SMM.MSparseMatrix <$> _clone fp\n\n-- | Unsafely convert a mutable matrix to an immutable one without copying. The mutable matrix may not be used after this operation.\nunsafeFreeze :: (Elem a, PrimMonad p) => SMM.MSparseMatrix n m (PrimState p) a -> p (SparseMatrix n m a) \nunsafeFreeze (SMM.MSparseMatrix fp) = return $! SparseMatrix fp\n\n-- | Unsafely convert an immutable matrix to a mutable one without copying. The immutable matrix may not be used after this operation.\nunsafeThaw :: (Elem a, PrimMonad p) => SparseMatrix n m a -> p (SMM.MSparseMatrix n m (PrimState p) a) \nunsafeThaw (SparseMatrix fp) = return $! SMM.MSparseMatrix fp\n\n-- | Return a single row of the sparse matrix.\ngetRow :: forall n m r a. (Elem a, KnownNat n, KnownNat m, KnownNat r, r <= n, 1 <= n) => Row r -> SparseMatrix n m a -> SparseMatrix 1 m a\ngetRow row mat = block row (Col @0) (Row @1) (Col @m) mat\n\n-- | Return a single column of the sparse matrix.\ngetCol :: forall n m c a. (Elem a, KnownNat n, KnownNat m, KnownNat c, c <= m, 1 <= m) => Col c -> SparseMatrix n m a -> SparseMatrix n 1 a\ngetCol col mat = block (Row @0) col (Row @n) (Col @1) mat\n\n-- | Return all rows of the sparse matrix.\ngetRows :: forall n m a. (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> [SparseMatrix 1 m a]\ngetRows mat = fmap (flip unsafeGetRow mat) [0 .. (natToInt @n) - 1]\n\n-- | Return all columns of a sparse matrix.\ngetCols :: forall n m a. (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> [SparseMatrix n 1 a]\ngetCols mat = fmap (flip unsafeGetCol mat) [0 .. (natToInt @m) - 1]\n\n-- | Returns a single row of the sparse matrix. This is unsafe because it allows out-of-bounds access.\nunsafeGetRow :: forall n m a. (Elem a, KnownNat n, KnownNat m) => Int -> SparseMatrix n m a -> SparseMatrix 1 m a\nunsafeGetRow row mat = unsafeBlock row 0 1 (natToInt @m) mat\n\n-- | Returns a single column of the sparse matrix. This is unsafe because it allows out-of-bounds access.\nunsafeGetCol :: forall n m a. (Elem a, KnownNat n, KnownNat m) => Int -> SparseMatrix n m a -> SparseMatrix n 1 a\nunsafeGetCol col mat = unsafeBlock 0 col (natToInt @n) 1 mat\n\n-- | Get a sparse matrix from a list of columns.\n--   This operation is unsafe because we cannot unify the length of the list with the type variable 'm'.\nunsafeFromCols :: forall n m a. (Elem a, KnownNat n, KnownNat m) => [SparseMatrix n 1 a] -> SparseMatrix n m a\nunsafeFromCols [] = fromListSized 0 0 []\nunsafeFromCols _cols = fromListSized n m . concatMap toList . zipWith updateColIdx [0..] $ _cols\n  where\n    n = maximum . fmap _unsafeRows $ _cols\n    m = length _cols\n\n-- | Get a sparse matrix from a list of rows.\n--   This operation is unsafe because we cannot unify the length of the list with the type variable 'n'.\nunsafeFromRows :: forall n m a. (Elem a, KnownNat n, KnownNat m) => [SparseMatrix 1 m a] -> SparseMatrix n m a\nunsafeFromRows [] = fromListSized 0 0 []\nunsafeFromRows _rows = fromListSized n m . concatMap toList . zipWith updateRowIdx [0..] $ _rows\n  where\n    n = length _rows\n    m = maximum . fmap _unsafeCols $ _rows\n\n-- | Update the row indices of a sparse matrix.\nupdateRowIdx :: forall n m a. (KnownNat n, KnownNat m, Elem a) => Int -> SparseMatrix n m a -> SparseMatrix n m a\nupdateRowIdx row mat = fromListSized n m . fmap (\\(_, j, v) -> (row, j, v)) . toList $ mat\n  where\n    n = row + 1\n    m = _unsafeCols mat\n\n-- | Update the column indices of a sparse matrix.\nupdateColIdx :: forall n m a. (KnownNat n, KnownNat m, Elem a) => Int -> SparseMatrix n m a -> SparseMatrix n m a\nupdateColIdx col mat = fromListSized n m . fmap (\\(i, _, v) -> (i, col, v)) . toList $ mat\n  where\n    n = _unsafeRows mat\n    m = col + 1\n\n--fromRows :: forall n m a. (Elem a, KnownNat n, KnownNat m)\n--  => [SparseMatrix 1 m a]\n--  -> SparseMatrix n m a\n\n\n_unop :: Storable b => (CSparseMatrixPtr a -> Ptr b -> IO CString) -> (b -> IO c) -> SparseMatrix n m a -> c\n_unop f g (SparseMatrix fp) = Internal.performIO $\n  withForeignPtr fp $ \\p ->\n    alloca $ \\pq -> do\n      Internal.call (f p pq)\n      peek pq >>= g\n\n_binop :: Storable b => (CSparseMatrixPtr a -> CSparseMatrixPtr a -> Ptr b -> IO CString) -> (b -> IO c) -> SparseMatrix n m a -> SparseMatrix n1 m1 a -> c\n_binop f g (SparseMatrix fp1) (SparseMatrix fp2) = Internal.performIO $\n  withForeignPtr fp1 $ \\p1 ->\n    withForeignPtr fp2 $ \\p2 ->\n      alloca $ \\pq -> do\n        Internal.call (f p1 p2 pq)\n        peek pq >>= g\n\n_getvec :: (Elem a, Storable b) => (Ptr (CSparseMatrix a) -> Ptr CInt -> Ptr (Ptr b) -> IO CString) -> SparseMatrix n m a -> VS.Vector b\n_getvec f (SparseMatrix fm) = Internal.performIO $\n  withForeignPtr fm $ \\m ->\n    alloca $ \\ps ->\n      alloca $ \\pq -> do\n        Internal.call $ f m ps pq\n        s <- fromIntegral <$> peek ps\n        q <- peek pq\n        fr <- FC.newForeignPtr q $ touchForeignPtr fm\n        pure $! VS.unsafeFromForeignPtr0 fr s\n\n_clone :: (PrimMonad p, Elem a) => ForeignPtr (CSparseMatrix a) -> p (ForeignPtr (CSparseMatrix a))\n_clone fp = unsafePrimToPrim $ withForeignPtr fp $ \\p -> alloca $ \\pq -> do\n  Internal.call $ Internal.sparse_clone p pq\n  q <- peek pq\n  FC.newForeignPtr q $ Internal.call $ Internal.sparse_free q\n\n_mk :: Elem a => Ptr (CSparseMatrix a) -> IO (SparseMatrix n m a)\n_mk p = SparseMatrix <$> FC.newForeignPtr p (Internal.call $ Internal.sparse_free p)\n\n-- | Number of rows in the sparse matrix\n_unsafeRows :: forall n m a. (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> Int\n{-# INLINE _unsafeRows #-}\n_unsafeRows _ = natToInt @n\n\n-- | Number of colums in the sparse matrix\n_unsafeCols :: forall n m a. (Elem a, KnownNat n, KnownNat m) => SparseMatrix n m a -> Int\n{-# INLINE _unsafeCols #-}\n_unsafeCols _ = natToInt @m\n\n_unsafeCoeff :: (Elem a, KnownNat n) => Int -> Int -> SparseMatrix n m a -> a\n{-# INLINE _unsafeCoeff #-}\n_unsafeCoeff !row !col (SparseMatrix fp) =\n  let !c_row = toC row\n      !c_col = toC col\n  in Internal.performIO $ withForeignPtr fp $ \\p -> alloca $ \\pq -> do\n       Internal.call $ Internal.sparse_coeff p c_row c_col pq\n       fromC <$> peek pq", "meta": {"hexsha": "062202105f9e3174d74ac29b26c8c9ef287c1f7e", "size": 24620, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Eigen/SparseMatrix.hs", "max_stars_repo_name": "nilsalex/eigen", "max_stars_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-07-17T08:14:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T10:27:07.000Z", "max_issues_repo_path": "src/Eigen/SparseMatrix.hs", "max_issues_repo_name": "nilsalex/eigen", "max_issues_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2018-07-17T14:12:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T11:37:18.000Z", "max_forks_repo_path": "src/Eigen/SparseMatrix.hs", "max_forks_repo_name": "nilsalex/eigen", "max_forks_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-11-22T08:11:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T07:40:02.000Z", "avg_line_length": 40.6270627063, "max_line_length": 237, "alphanum_fraction": 0.6783915516, "num_tokens": 7228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2664112360207944}}
{"text": "{-# LANGUAGE BangPatterns     #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeSynonymInstances #-}\nmodule Taiji.Utils.DataFrame\n    ( DataFrame(..)\n    , DataFrameIndex(..)\n    , mkDataFrame\n    , fromMatrix\n    , dim\n    , isEmpty\n    , Taiji.Utils.DataFrame.transpose\n    , rbind\n    , cbind\n    , cjoin\n    , rowNames\n    , colNames\n    , ReodrderFn\n    , reorderColumns\n    , reorderRows\n    , Taiji.Utils.DataFrame.map\n    , mapRows\n    , imapRows\n    , mapCols\n    , imapCols\n    , filterRows\n    , filterCols\n    , Taiji.Utils.DataFrame.zip\n    , Taiji.Utils.DataFrame.unzip\n    , readData\n    , writeTable\n    , readTable\n    , readTableWith\n    , orderByHClust\n    , orderByKMeans\n    , orderDataFrame\n    \n    , pearson\n    , spearman\n    ) where\n\nimport           Bio.Utils.Functions    (ihs')\nimport           Bio.Utils.Misc         (readDouble)\nimport Conduit\nimport Control.Monad (forM_)\nimport GHC.Generics (Generic)\nimport qualified Data.ByteString.Char8  as B\nimport qualified Data.Text as T\nimport qualified Data.CaseInsensitive   as CI\nimport           Data.Function          (on)\nimport           Data.List as L\nimport AI.Clustering.Hierarchical hiding (normalize)\nimport AI.Clustering.KMeans\nimport Data.Vector.Binary ()\nimport Data.Maybe\nimport qualified Data.Matrix            as M\nimport qualified Data.Matrix.Unboxed    as MU\nimport qualified Data.Vector            as V\nimport qualified Data.Map.Strict    as HM\nimport qualified Data.HashSet as HS\nimport Statistics.Correlation (pearsonMatByRow, spearmanMatByRow)\nimport Statistics.Matrix (toRowLists, fromRowLists)\nimport Data.Binary (Binary)\nimport Control.DeepSeq (NFData)\n\ndata DataFrame a = DataFrame\n    { _dataframe_row_names :: V.Vector T.Text\n    , _dataframe_row_names_idx :: HM.Map T.Text Int\n    , _dataframe_col_names :: V.Vector T.Text\n    , _dataframe_col_names_idx :: HM.Map T.Text Int\n    , _dataframe_data :: M.Matrix a\n    } deriving (Show, Generic)\n\ninstance Binary a => Binary (M.Matrix a)\ninstance Binary a => Binary (DataFrame a)\ninstance NFData a => NFData (DataFrame a)\n\nmkDataFrame :: [T.Text]     -- ^ row names\n            -> [T.Text]     -- ^ col names\n            -> [[a]]        -- ^ data\n            -> DataFrame a\nmkDataFrame r c d = DataFrame\n    { _dataframe_row_names = V.fromList r\n    , _dataframe_row_names_idx = HM.fromList $ L.zip r [0..]\n    , _dataframe_col_names = V.fromList c\n    , _dataframe_col_names_idx = HM.fromList $ L.zip c [0..]\n    , _dataframe_data = M.fromLists d }\n\nfromMatrix :: [T.Text]     -- ^ row names\n           -> [T.Text]     -- ^ col names\n           -> M.Matrix a  -- ^ data\n           -> DataFrame a\nfromMatrix r c mat = DataFrame\n    { _dataframe_row_names = V.fromList r\n    , _dataframe_row_names_idx = HM.fromList $ L.zip r [0..]\n    , _dataframe_col_names = V.fromList c\n    , _dataframe_col_names_idx = HM.fromList $ L.zip c [0..]\n    , _dataframe_data = mat }\n\nclass DataFrameIndex i where\n    csub :: DataFrame a -> [i] -> DataFrame a\n    cindex :: DataFrame a -> i -> V.Vector a\n    rsub :: DataFrame a -> [i] -> DataFrame a\n    rindex :: DataFrame a -> i -> V.Vector a\n    (!)  :: DataFrame a -> (i,i) -> a\n    indexMaybe  :: DataFrame a -> (i,i) -> Maybe a\n\ninstance DataFrameIndex Int where\n    csub df idx = df\n        { _dataframe_col_names = V.fromList col_names\n        , _dataframe_col_names_idx = HM.fromList $ L.zip col_names [0..]\n        , _dataframe_data = M.fromColumns $ L.map (_dataframe_data df `M.takeColumn`) idx }\n      where\n        col_names = L.map (_dataframe_col_names df V.!) idx\n\n    cindex df idx = _dataframe_data df `M.takeColumn` idx\n\n    rsub df idx = df\n        { _dataframe_row_names = V.fromList row_names\n        , _dataframe_row_names_idx = HM.fromList $ L.zip row_names [0..]\n        , _dataframe_data = M.fromRows $ L.map (_dataframe_data df `M.takeRow`) idx }\n      where\n        row_names = L.map (_dataframe_row_names df V.!) idx\n\n    rindex df idx = _dataframe_data df `M.takeRow` idx\n\n    (!) df (i,j) = _dataframe_data df M.! (i,j)\n    indexMaybe df (i,j) \n        | i < r && j < c = Just $ _dataframe_data df M.! (i,j)\n        | otherwise = Nothing\n      where\n        (r, c) = dim df\n\ninstance DataFrameIndex T.Text where\n    csub df idx = csub df idx'\n      where\n        idx' = L.map (\\i -> HM.findWithDefault\n            (error $ \"index doesn't exist: \" ++ T.unpack i) i $\n            _dataframe_col_names_idx df) idx\n\n    cindex df i = cindex df i'\n      where\n        i' = HM.findWithDefault (error $ \"index doesn't exist: \" ++ T.unpack i) i $\n            _dataframe_col_names_idx df\n\n    rsub df idx = rsub df idx'\n      where\n        idx' = L.map (\\i -> HM.findWithDefault\n            (error $ \"index doesn't exist: \" ++ T.unpack i) i $\n            _dataframe_row_names_idx df) idx\n\n    rindex df i = rindex df i'\n      where\n        i' = HM.findWithDefault (error $ \"index doesn't exist: \" ++ T.unpack i) i $\n            _dataframe_row_names_idx df\n\n    (!) df (a,b) = (!) df (i,j)\n      where\n        i = HM.findWithDefault (error $ \"index doesn't exist: \" ++ T.unpack a) a $\n            _dataframe_row_names_idx df\n        j = HM.findWithDefault (error $ \"index doesn't exist: \" ++ T.unpack b) b $\n            _dataframe_col_names_idx df\n\n    indexMaybe df (a,b) = case HM.lookup a (_dataframe_row_names_idx df) of\n        Nothing -> Nothing\n        Just i -> case HM.lookup b (_dataframe_col_names_idx df) of\n            Nothing -> Nothing\n            Just j -> Just $ (!) df (i,j)\n\ndim :: DataFrame a -> (Int, Int)\ndim df = M.dim $ _dataframe_data df\n\nisEmpty :: DataFrame a -> Bool\nisEmpty df = r == 0 || c == 0\n  where\n    (r,c) = M.dim $ _dataframe_data df\n\nrbind :: [DataFrame a] -> DataFrame a\nrbind dfs | allTheSame (L.map _dataframe_col_names dfs) = (head dfs)\n    { _dataframe_row_names = row_names\n    , _dataframe_row_names_idx = HM.fromList $ L.zip (V.toList row_names) [0..]\n    , _dataframe_data = M.fromBlocks undefined $ L.map (return . _dataframe_data) dfs }\n          | otherwise = error \"Columns names differ\"\n  where\n    allTheSame xs = all (== head xs) (tail xs)\n    row_names = V.concat $ L.map (_dataframe_row_names) dfs\n\ncjoin :: DataFrame a -> DataFrame a -> DataFrame a\ncjoin df1 df2 = mkDataFrame rownames (colNames df1 ++ colNames df2) $\n    flip L.map rownames $ \\nm ->\n        V.toList (df1 `rindex` nm) ++ V.toList (df2 `rindex` nm) \n  where\n    rownames = HS.toList $ HS.fromList (rowNames df1) `HS.intersection`\n        HS.fromList (rowNames df2)\n\ncbind :: [DataFrame a] -> DataFrame a\ncbind dfs | allTheSame (L.map (HS.fromList . rowNames) dfs) = (head dfs)\n    { _dataframe_col_names = col_names\n    , _dataframe_col_names_idx = HM.fromList $ L.zip (V.toList col_names) [0..]\n    , _dataframe_data = M.fromBlocks undefined [L.map reorderRow dfs] }\n          | otherwise = error \"Row names differ\"\n  where\n    reorderRow df | rowNames df == row_names = _dataframe_data df\n                  | otherwise = M.fromRows $ L.map (df `rindex`) row_names\n    row_names = rowNames $ head dfs\n    col_names = V.concat $ L.map (_dataframe_col_names) dfs\n    allTheSame xs = all (== head xs) (tail xs)\n\nmap :: (a -> b) -> DataFrame a -> DataFrame b\nmap f df = df{_dataframe_data = M.map f $ _dataframe_data df}\n\nzip :: DataFrame a -> DataFrame b -> DataFrame (a,b)\nzip df1 df2\n    | _dataframe_col_names df1 == _dataframe_col_names df2 &&\n      _dataframe_row_names df1 == _dataframe_row_names df2 = df1\n        {_dataframe_data = M.zip (_dataframe_data df1) $ _dataframe_data df2}\n    | otherwise = error \"names mismatch\"\n\nunzip :: DataFrame (a,b) -> (DataFrame a, DataFrame b)\nunzip df = (df{_dataframe_data = a}, df{_dataframe_data = b})\n  where\n    (a,b) = M.unzip $ _dataframe_data df\n\ntranspose :: DataFrame a -> DataFrame a\ntranspose DataFrame{..} = DataFrame _dataframe_col_names _dataframe_col_names_idx\n    _dataframe_row_names _dataframe_row_names_idx $ M.tr _dataframe_data\n\nrowNames :: DataFrame a -> [T.Text]\nrowNames DataFrame{..} = V.toList _dataframe_row_names\n\ncolNames :: DataFrame a -> [T.Text]\ncolNames DataFrame{..} = V.toList _dataframe_col_names\n\nmapRows :: (V.Vector a -> V.Vector b) -> DataFrame a -> DataFrame b\nmapRows fn df = df\n    { _dataframe_data = M.fromRows $ L.map fn $ M.toRows $ _dataframe_data df }\n\nimapRows :: (T.Text -> V.Vector a -> V.Vector b) -> DataFrame a -> DataFrame b\nimapRows fn df = df{ _dataframe_data = M.fromRows $ L.zipWith fn (rowNames df) $ M.toRows $ _dataframe_data df}\n\nmapCols :: (V.Vector a -> V.Vector b) -> DataFrame a -> DataFrame b\nmapCols fn df = df\n    { _dataframe_data = M.fromColumns $ L.map fn $ M.toColumns $ _dataframe_data df }\n\nimapCols :: (T.Text -> V.Vector a -> V.Vector b) -> DataFrame a -> DataFrame b\nimapCols fn df = df\n    { _dataframe_data = M.fromColumns $ L.zipWith fn (colNames df) $ M.toColumns $ _dataframe_data df }\n\nfilterRows :: (T.Text -> V.Vector a -> Bool) -> DataFrame a -> DataFrame a\nfilterRows fn df = df\n    { _dataframe_row_names = V.fromList names\n    , _dataframe_row_names_idx = HM.fromList $ L.zip names [0..]\n    , _dataframe_data = M.fromRows rows }\n  where\n    (names, rows) = L.unzip $ filter (uncurry fn) $\n        L.zip (V.toList $ _dataframe_row_names df) $ M.toRows $ _dataframe_data df\n\nfilterCols :: (T.Text -> V.Vector a -> Bool) -> DataFrame a -> DataFrame a\nfilterCols fn df = df\n    { _dataframe_col_names = V.fromList names\n    , _dataframe_col_names_idx = HM.fromList $ L.zip names [0..]\n    , _dataframe_data = M.fromColumns cols }\n  where\n    (names, cols) = L.unzip $ filter (uncurry fn) $\n        L.zip (V.toList $ _dataframe_col_names df) $ M.toColumns $ _dataframe_data df\n\ntype ReodrderFn a = [(T.Text, V.Vector a)] -> [(T.Text, V.Vector a)]\n\nreorderRows :: ReodrderFn a -> DataFrame a -> DataFrame a\nreorderRows fn df\n    | isEmpty df = df\n    | otherwise = df\n        { _dataframe_row_names = V.fromList names\n        , _dataframe_row_names_idx = HM.fromList $ L.zip names [0..]\n        , _dataframe_data = M.fromRows rows }\n  where\n    (names, rows) = L.unzip $ fn $ L.zip (V.toList $ _dataframe_row_names df) $\n        M.toRows $ _dataframe_data df\n\nreorderColumns :: ReodrderFn a -> DataFrame a -> DataFrame a\nreorderColumns fn df\n    | isEmpty df = df\n    | otherwise = df\n        { _dataframe_col_names = V.fromList names\n        , _dataframe_col_names_idx = HM.fromList $ L.zip names [0..]\n        , _dataframe_data = M.fromColumns cols}\n  where\n    (names, cols) = L.unzip $ fn $ L.zip (V.toList $ _dataframe_col_names df) $\n        M.toColumns $ _dataframe_data df\n\nwriteTable :: FilePath -> (a -> T.Text) -> DataFrame a -> IO ()\nwriteTable output f DataFrame{..} = runResourceT $ runConduit $\n    source .| unlinesAsciiC .| sinkFile output\n  where\n    source = do\n        yield $ B.pack $ T.unpack $ T.intercalate \"\\t\" $\n            \"\" : V.toList _dataframe_col_names\n        forM_ (L.zip (V.toList _dataframe_row_names) $ M.toRows _dataframe_data) $\n            \\(nm, xs) -> yield $ B.pack $ T.unpack $\n                T.intercalate \"\\t\" $ nm : L.map f (V.toList xs)\n{-# NOINLINE writeTable #-}\n    \n-- | Read data, normalize and calculate p-values.\nreadData :: FilePath   -- ^ PageRank\n         -> FilePath   -- ^ Gene expression\n         -> IO (DataFrame (Double, Double))  -- ^ ranks, expression\nreadData input1 input2 = do\n    rank <- readTSV <$> B.readFile input1\n\n    -- Read expression profile and apply \"ihs\" transformation\n    expr <- (fmap ihs' . readTSV) <$> B.readFile input2\n\n    let (labels, xs) = L.unzip $ L.map L.unzip $ groupBy ((==) `on` (fst.fst)) $ sort $\n            HM.toList $ HM.intersectionWith (,) rank expr\n        rowlab = L.map (T.pack . B.unpack . CI.original) $ fst $ L.unzip $ L.map head labels\n        collab = L.map (T.pack . B.unpack . CI.original) $ snd $ L.unzip $ head labels\n    return $ mkDataFrame rowlab collab xs\n\nreadTSV :: B.ByteString -> HM.Map (CI.CI B.ByteString, CI.CI B.ByteString) Double\nreadTSV input = HM.fromList $ concatMap (f . B.split '\\t') content\n  where\n    f (x:xs) = L.zipWith (\\s v -> ((CI.mk x, CI.mk s), readDouble v)) samples xs\n    (header:content) = B.lines input\n    samples = tail $ B.split '\\t' header\n\nreadTable :: FilePath -> IO (DataFrame Double)\nreadTable = readTableWith readDouble\n\nreadTableWith :: (B.ByteString -> a) -> FilePath -> IO (DataFrame a)\nreadTableWith f input = do\n    (header:content) <- B.lines <$> B.readFile input\n    let samples = tail $ B.split '\\t' header\n        (rows, dat) = L.unzip $ L.map ((\\(x:xs) ->\n            (T.pack $ B.unpack x, L.map f xs)) . B.split '\\t') content\n    return $ mkDataFrame rows (L.map (T.pack . B.unpack) samples) dat\n\n    {-\norderByName :: [T.Text] -> ReodrderFn a\norderByName prefix = sortBy $ \\(a,_) (b,_) ->\n    let idx1 = findIdx a\n        idx2 = findIdx b\n    in case () of\n        _ | isJust idx1 && isJust idx2 -> case compare idx1 idx2 of\n                LT -> LT\n                GT -> GT\n                EQ -> compare a b\n          | otherwise -> compare a b\n  where\n    findIdx x = go prefix 0\n      where\n        go (y:ys) !i | isPrefixOf y x = Just i\n                     | otherwise = go ys (i+1)\n        go _ _ = Nothing\n        -}\n\norderByHClust :: (a -> Double) -> ReodrderFn a \norderByHClust f xs = flatten $ hclust Ward (V.fromList xs) dist\n  where\n    dist = euclidean `on` V.map f . snd\n\norderByKMeans :: Int -> (a -> Double) -> ReodrderFn a \norderByKMeans k f xs = concatMap fst $ flatten $ hclust Ward r dist\n  where\n    r = V.fromList $ L.zip (fromJust $ clusters kmRes) (MU.toRows $ centers kmRes)\n    kmRes = kmeansBy k (V.fromList xs) (V.convert . V.map f . snd) defaultKMeansOpts\n    dist = euclidean `on` snd\n\npearson :: DataFrame Double -> DataFrame Double\npearson DataFrame{..} = DataFrame _dataframe_row_names _dataframe_row_names_idx \n    _dataframe_row_names _dataframe_row_names_idx $ M.fromLists $\n    toRowLists $ pearsonMatByRow $ fromRowLists $ M.toLists _dataframe_data \n\nspearman :: DataFrame Double -> DataFrame Double\nspearman DataFrame{..} = DataFrame _dataframe_row_names _dataframe_row_names_idx \n    _dataframe_row_names _dataframe_row_names_idx $ M.fromLists $\n    toRowLists $ spearmanMatByRow $ fromRowLists $ M.toLists _dataframe_data \n\norderDataFrame :: (a -> Double) -> DataFrame a -> DataFrame a\norderDataFrame f = reorderColumns (orderByHClust f) . reorderRows (orderByHClust f)", "meta": {"hexsha": "e310726b7e01dab8b5ec61675a2e601bf448e91a", "size": 14445, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Taiji/Utils/DataFrame.hs", "max_stars_repo_name": "Taiji-pipeline/Taiji-utils", "max_stars_repo_head_hexsha": "f5e009cf7a9a683f7e43bf97fb33c758ba13d97b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Taiji/Utils/DataFrame.hs", "max_issues_repo_name": "Taiji-pipeline/Taiji-utils", "max_issues_repo_head_hexsha": "f5e009cf7a9a683f7e43bf97fb33c758ba13d97b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Taiji/Utils/DataFrame.hs", "max_forks_repo_name": "Taiji-pipeline/Taiji-utils", "max_forks_repo_head_hexsha": "f5e009cf7a9a683f7e43bf97fb33c758ba13d97b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9133858268, "max_line_length": 111, "alphanum_fraction": 0.6409830391, "num_tokens": 4114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2628011815734384}}
{"text": "{-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, DeriveGeneric, TupleSections, RecordWildCards #-}\n\nmodule BayesStack.Models.Topic.CitationInfluence\n  ( -- * Primitives\n    NetData(..)\n  , netData\n  , HyperParams(..)\n  , MState(..)\n  , CitedUpdateUnit\n  , CitingUpdateUnit\n  , ItemSource(..)\n  , CitedNode(..), CitedNodeItem(..)\n  , CitingNode(..), CitingNodeItem(..)\n  , Citing(..), Cited(..)\n  , Item(..), Topic(..), NodeItem(..), Node(..), Arc(..)\n  , setupNodeItems\n    -- * Initialization\n  , verifyNetData, cleanNetData\n  , ModelInit\n  , randomInitialize\n  , model\n  , updateUnits\n    -- * Diagnostics\n  , modelLikelihood\n  , influence\n  , arcTopicMixture\n  ) where\n\nimport qualified Data.Vector as V\nimport Statistics.Sample (mean)\n\nimport           Prelude hiding (mapM_, sum)\n\nimport           Data.Set (Set)\nimport qualified Data.Set as S\n\nimport           Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as M\n\nimport           Data.Foldable hiding (product)\nimport           Control.Applicative ((<$>), (<*>))\nimport           Control.Monad (when)\nimport           Control.Monad.Trans.State.Strict\nimport           Control.Monad.Trans.Writer.Strict\n\nimport           Data.Random\nimport           Data.Random.Lift (lift)\nimport           Data.Random.Distribution.Categorical (categorical)\nimport           Numeric.Log hiding (sum)\n\nimport           BayesStack.Types\nimport           BayesStack.Gibbs\nimport           BayesStack.DirMulti\nimport           BayesStack.TupleEnum ()\nimport           BayesStack.Models.Topic.Types\n\nimport           GHC.Generics\nimport           Data.Binary (Binary)\nimport           Control.DeepSeq\n\ndata ItemSource = Shared | Own deriving (Show, Eq, Enum, Ord, Generic)\ninstance Binary ItemSource\ninstance NFData ItemSource\n\nnewtype Citing a = Citing a deriving (Show, Eq, Enum, Ord, Generic, NFData)\nnewtype Cited a = Cited a deriving (Show, Eq, Enum, Ord, Generic, NFData)\ninstance Binary a => Binary (Citing a)\ninstance Binary a => Binary (Cited a)\n\ntype CitingNode = Citing Node\ntype CitedNode = Cited Node\ntype CitingNodeItem = Citing NodeItem\ntype CitedNodeItem = Cited NodeItem\n\n-- ^ A directed edge\ndata Arc = Arc {citingNode :: !CitingNode, citedNode :: !CitedNode}\n            deriving (Show, Eq, Ord, Generic)\ninstance Binary Arc\n\ndata HyperParams = HyperParams\n                   { alphaPsi         :: Double\n                   , alphaLambda      :: Double\n                   , alphaPhi         :: Double\n                   , alphaOmega       :: Double\n                   , alphaGammaShared :: Double\n                   , alphaGammaOwn    :: Double\n                   }\n                 deriving (Show, Eq, Generic)\ninstance Binary HyperParams\n\ndata NetData = NetData { dHypers             :: !(HyperParams)\n                       , dArcs               :: !(Set Arc)\n                       , dItems              :: !(Set Item)\n                       , dTopics             :: !(Set Topic)\n                       , dNodeItems          :: !(Map NodeItem (Node, Item))\n                       , dCitingNodes        :: !(Map CitingNode (Set CitedNode))\n                         -- ^ Maps each citing node to the set of nodes cited by it\n                       , dCitedNodes         :: !(Map CitedNode (Set CitingNode))\n                         -- ^ Maps each cited node to the set of nodes citing it\n                       }\n              deriving (Show, Eq, Generic)\ninstance Binary NetData\n\nnetData :: HyperParams -> Set Arc -> Map NodeItem (Node,Item) -> Set Topic -> NetData\nnetData hypers arcs nodeItems topics =\n    NetData { dHypers       = hypers\n            , dArcs         = arcs\n            , dItems        = foldMap (S.singleton . snd) $ M.elems nodeItems\n            , dTopics       = topics\n            , dNodeItems    = nodeItems\n            , dCitingNodes  = M.unionsWith S.union\n                              $ map (\\(Arc a b)->M.singleton a $ S.singleton b)\n                              $ S.toList arcs\n            , dCitedNodes   = M.unionsWith S.union\n                              $ map (\\(Arc a b)->M.singleton b $ S.singleton a)\n                              $ S.toList arcs\n            }\n\ndCitingNodeItems :: NetData -> Map CitingNodeItem (CitingNode, Item)\ndCitingNodeItems nd =\n    M.mapKeys Citing\n    $ M.map (\\(n,i)->(Citing n, i))\n    $ M.filter (\\(n,i)->Citing n `M.member` dCitingNodes nd)\n    $ dNodeItems nd\n\nitemsOfCitingNode :: NetData -> CitingNode -> [Item]\nitemsOfCitingNode d (Citing u) =\n    map snd $ M.elems $ M.filter (\\(n,_)->n==u) $ dNodeItems d\n\nconnectedNodes :: Set Arc -> Set Node\nconnectedNodes arcs =\n    S.map ((\\(Cited n)->n) . citedNode) arcs `S.union` S.map ((\\(Citing n)->n) . citingNode) arcs\n\ncleanNetData :: NetData -> NetData\ncleanNetData d =\n    let nodesWithItems = S.fromList $ map fst $ M.elems $ dNodeItems d\n        nodesWithArcs = connectedNodes $ dArcs d\n        keptNodes = nodesWithItems `S.intersection` nodesWithArcs\n        keepArc (Arc (Citing citing) (Cited cited)) =\n            citing `S.member` keptNodes && cited `S.member` keptNodes\n    in d { dArcs = S.filter keepArc $ dArcs d\n         , dNodeItems = M.filter (\\(n,i)->n `S.member` keptNodes) $ dNodeItems d\n         }\n\nverifyNetData :: (Node -> String) -> NetData -> [String]\nverifyNetData showNode d = execWriter $ do\n    let nodesWithItems = S.fromList $ map fst $ M.elems $ dNodeItems d\n    forM_ (dArcs d) $ \\(Arc (Citing citing) (Cited cited))->do\n        when (cited `S.notMember` nodesWithItems)\n            $ tell [showNode cited++\" has arc yet has no items\"]\n        when (citing `S.notMember` nodesWithItems)\n            $ tell [showNode citing++\" has arc yet has no items\"]\n\ntype CitedModelInit = Map CitedNodeItem (Setting CitedUpdateUnit)\ntype CitingModelInit = Map CitingNodeItem (Setting CitingUpdateUnit)\ndata ModelInit = ModelInit CitedModelInit CitingModelInit\n               deriving (Show)\n\nrandomInitializeCited :: NetData -> CitedModelInit -> RVar CitedModelInit\nrandomInitializeCited d init = execStateT doInit init\n    where doInit = let unset = citedNodeItems `S.difference` M.keysSet init\n                       citedNodeItems = S.map Cited (M.keysSet (dNodeItems d))\n                   in mapM_ (randomInitCitedUU d) (S.toList unset)\n\nmodify' :: Monad m => (a -> a) -> StateT a m ()\nmodify' f = do x <- get\n               put $! f x\n\nrandomInitCitedUU :: NetData -> CitedNodeItem -> StateT CitedModelInit RVar ()\nrandomInitCitedUU d ni = do\n    t' <- lift $ randomElement $ toList $ dTopics d\n    modify' $ M.insert ni t'\n\nrandomInitializeCiting :: NetData -> CitingModelInit -> RVar CitingModelInit\nrandomInitializeCiting d init = execStateT doInit init\n    where doInit :: StateT CitingModelInit RVar ()\n          doInit = let unset = M.keysSet (dCitingNodeItems d) `S.difference` M.keysSet init\n                   in mapM_ (randomInitCitingUU d) (S.toList unset)\n\nrandomInitCitingUU :: NetData -> CitingNodeItem -> StateT CitingModelInit RVar ()\nrandomInitCitingUU d cni@(Citing ni) =\n    let (n,_) = dNodeItems d M.! ni\n    in case dCitingNodes d M.! Citing n of\n           a | S.null a -> do\n               t <- lift $ randomElement $ toList $ dTopics d\n               modify' $ M.insert cni $ OwnSetting t\n\n           citedNodes -> do\n               s <- lift $ randomElement [Shared, Own]\n               c <- lift $ randomElement $ toList citedNodes\n               t <- lift $ randomElement $ toList $ dTopics d\n               modify' $ M.insert cni $\n                   case s of Shared -> SharedSetting t c\n                             Own    -> OwnSetting t\n\nrandomInitialize :: NetData -> RVar ModelInit\nrandomInitialize d =\n    ModelInit <$> randomInitializeCited d M.empty <*> randomInitializeCiting d M.empty\n\nmodel :: NetData -> ModelInit -> MState\nmodel d (ModelInit citedInit citingInit) =\n    let citingNodes = M.keys $ dCitingNodes d\n        HyperParams {..} = dHypers d\n        s = MState { -- Citing model\n                     stPsis = let dist n = case toList $ dCitingNodes d M.! n of\n                                               []    -> M.empty\n                                               nodes -> M.singleton n\n                                                        $ symDirMulti alphaPsi nodes\n                              in foldMap dist citingNodes\n                   , stPhis = let dist = symDirMulti alphaPhi (toList $ dItems d)\n                              in foldMap (\\t->M.singleton t dist) $ dTopics d\n                   , stGammas = let dist = multinom [ (Shared, alphaGammaShared)\n                                                    , (Own, alphaGammaOwn) ]\n                                in foldMap (\\t->M.singleton t dist) citingNodes\n                   , stOmegas = let dist = symDirMulti alphaOmega (toList $ dTopics d)\n                                in foldMap (\\t->M.singleton t dist) citingNodes\n                   , stCiting = M.empty\n\n                   -- Cited model\n                   , stLambdas = let dist = symDirMulti alphaLambda (toList $ dTopics d)\n                                 in foldMap (\\t->M.singleton t dist) $ M.keys $ dCitedNodes d\n                   , stT' = M.empty\n                   }\n\n        initCitingUU :: CitingUpdateUnit -> State MState ()\n        initCitingUU uu = do\n            let err = error $ \"CitationInference: Initial value for \"++show uu++\" not given\\n\"\n                s = maybe err id $ M.lookup (uuNI uu) citingInit\n            modify' $ setCitingUU uu (Just s)\n\n        initCitedUU :: CitedUpdateUnit -> State MState ()\n        initCitedUU uu = do\n            let err = error $ \"CitationInference: Initial value for \"++show uu++\" not given\"\n                s = maybe err id $ M.lookup (uuNI' uu) citedInit\n            modify' $ setCitedUU uu (Just s)\n\n    in execState (do mapM_ initCitingUU $ citingUpdateUnits d\n                     mapM_ initCitedUU $ citedUpdateUnits d\n                 ) s\n\nupdateUnits :: NetData -> [WrappedUpdateUnit MState]\nupdateUnits d = map WrappedUU (citedUpdateUnits d)\n             ++ map WrappedUU (citingUpdateUnits d)\n\ndata CitingSetting = OwnSetting !Topic\n                   | SharedSetting !Topic !CitedNode\n                   deriving (Show, Eq, Generic)\ninstance Binary CitingSetting\ninstance NFData CitingSetting where\n    rnf (OwnSetting t)      = rnf t `seq` ()\n    rnf (SharedSetting t c) = rnf t `seq` rnf c `seq` ()\n\ndata MState = MState { -- Citing model state\n                       stGammas   :: !(Map CitingNode (Multinom Int ItemSource))\n                     , stOmegas   :: !(Map CitingNode (Multinom Int Topic))\n                     , stPsis     :: !(Map CitingNode (Multinom Int CitedNode))\n                     , stPhis     :: !(Map Topic (Multinom Int Item))\n\n                     , stCiting   :: !(Map CitingNodeItem CitingSetting)\n\n                     -- Cited model state\n                     , stLambdas  :: !(Map CitedNode (Multinom Int Topic))\n\n                     , stT'       :: !(Map CitedNodeItem Topic)\n                     }\n            deriving (Show, Generic)\ninstance Binary MState\n\nmodelLikelihood :: MState -> Probability\nmodelLikelihood model =\n    product $ map likelihood (M.elems $ stGammas model)\n           ++ map likelihood (M.elems $ stPhis model)\n           ++ map likelihood (M.elems $ stLambdas model)\n           ++ map likelihood (M.elems $ stOmegas model)\n           ++ map likelihood (M.elems $ stPsis model)\n\n-- | Mixture of the topics of an edge\narcTopicMixture :: NetData -> MState -> Arc -> Topic -> Probability\narcTopicMixture nd m (Arc d c) t =\n    let itemObs = zip (itemsOfCitingNode nd d) (repeat 1)\n        phi = stPhis m M.! t\n        lambda = stLambdas m M.! c\n    in realToFrac (sampleProb lambda t) * obsProb phi itemObs\n\n-- | Geometric mean\ngeomMean :: V.Vector (Log Double) -> Log Double\ngeomMean = Exp . mean . V.map ln\n\n-- | The geometric mean of the probabilities of a collection of items under a\n-- given topic mixture.\ntopicCompatibility :: MState -> [Item] -> Multinom Int Topic -> Probability\ntopicCompatibility m items lambda =\n    geomMean $ V.fromList\n            $ do t <- toList $ dmDomain lambda\n                 let phi = stPhis m M.! t\n                     itemObs = zip items (repeat 1)\n                 return $ realToFrac (sampleProb lambda t) * obsProb phi itemObs\n\n-- | Normalized compatibilities with a set of items\ntopicCompatibilities :: (Functor f, Foldable f)\n                     => MState -> [Item] -> f (Multinom Int Topic) -> f Probability\ntopicCompatibilities m items topics =\n    let scores = fmap (topicCompatibility m items) topics\n    in fmap (/sum scores) scores\n\n-- | The influence of cited nodes on a citing node.\ninfluence :: NetData -> MState -> CitingNode -> Map CitedNode Probability\ninfluence d m u =\n    let lambdas = foldMap (\\f->M.singleton f $ stLambdas m M.! f)\n                 $ S.toList $ dCitingNodes d M.! u\n    in topicCompatibilities m (itemsOfCitingNode d u) lambdas\n\n-- Cited update unit (LDA-like)\ndata CitedUpdateUnit = CitedUpdateUnit { uuNI' :: !CitedNodeItem\n                                       , uuN'  :: !CitedNode\n                                       , uuX' :: !Item\n                                       }\n                     deriving (Show, Generic)\ninstance Binary CitedUpdateUnit\n\ninstance UpdateUnit CitedUpdateUnit where\n    type ModelState CitedUpdateUnit = MState\n    type Setting CitedUpdateUnit = Topic\n    fetchSetting uu ms = maybe (error $ \"Update unit \"++show uu++\" has no setting\") id\n                         $ M.lookup (uuNI' uu) (stT' ms)\n    evolveSetting ms uu = categorical $ citedFullCond (setCitedUU uu Nothing ms) uu\n    updateSetting uu _ s' = setCitedUU uu (Just s') . setCitedUU uu Nothing\n\ncitedProb :: MState -> CitedUpdateUnit -> Setting CitedUpdateUnit -> Double\ncitedProb st (CitedUpdateUnit {uuN'=n', uuX'=x'}) t =\n    let lambda = stLambdas st M.! n'\n        phi = stPhis st M.! t\n    in realToFrac $ sampleProb lambda t * sampleProb phi x'\n\ncitedUpdateUnits :: NetData -> [CitedUpdateUnit]\ncitedUpdateUnits d =\n    map (\\(ni',(n',x'))->CitedUpdateUnit { uuNI'      = Cited ni'\n                                         , uuN'       = Cited n'\n                                         , uuX'       = x'\n                                         }\n        ) $ M.assocs\n          $ M.filter (\\(n,i)->Cited n `M.member` dCitedNodes d)\n          $ dNodeItems d\n\nsetCitedUU :: CitedUpdateUnit -> Maybe Topic -> MState -> MState\nsetCitedUU uu@(CitedUpdateUnit {uuN'=n', uuNI'=ni', uuX'=x'}) setting ms =\n    let t' = maybe (fetchSetting uu ms) id setting\n        set = maybe Unset (const Set) setting\n    in ms { stLambdas = M.adjust (setMultinom set t') n' (stLambdas ms)\n          , stPhis = M.adjust (setMultinom set x') t' (stPhis ms)\n          , stT' = case setting of Just _  -> M.insert ni' t' $ stT' ms\n                                   Nothing -> stT' ms\n          }\n\ncitedFullCond ::MState -> CitedUpdateUnit -> [(Double, Topic)]\ncitedFullCond ms uu = do\n    t <- M.keys $ stPhis ms\n    return (citedProb ms uu t, t)\n\n\n-- Citing Update unit (Shared Taste-like)\ndata CitingUpdateUnit = CitingUpdateUnit { uuNI    :: !CitingNodeItem\n                                         , uuN     :: !CitingNode\n                                         , uuX     :: !Item\n                                         , uuCites :: !(Set CitedNode)\n                                         }\n                      deriving (Show, Generic)\ninstance Binary CitingUpdateUnit\n\ninstance UpdateUnit CitingUpdateUnit where\n    type ModelState CitingUpdateUnit = MState\n    type Setting CitingUpdateUnit = CitingSetting\n    fetchSetting uu ms = stCiting ms M.! uuNI uu\n    evolveSetting ms uu = categorical $ citingFullCond (setCitingUU uu Nothing ms) uu\n    updateSetting uu _ s' = setCitingUU uu (Just s') . setCitingUU uu Nothing\n\ncitingUpdateUnits :: NetData -> [CitingUpdateUnit]\ncitingUpdateUnits d =\n    map (\\(ni,(n,x))->CitingUpdateUnit { uuNI      = ni\n                                       , uuN       = n\n                                       , uuX       = x\n                                       , uuCites   = dCitingNodes d M.! n\n                                       }\n        ) $ M.assocs $ dCitingNodeItems d\n\ncitingProb :: MState -> CitingUpdateUnit -> Setting CitingUpdateUnit -> Double\ncitingProb st (CitingUpdateUnit {uuN=n, uuX=x}) setting =\n    let gamma = stGammas st M.! n\n        omega = stOmegas st M.! n\n        psi = stPsis st M.! n\n    in case setting of\n        SharedSetting t c -> let phi = stPhis st M.! t\n                                 lambda = stLambdas st M.! c\n                             in sampleProb gamma Shared\n                              * sampleProb psi c\n                              * sampleProb lambda t\n                              * sampleProb phi x\n        OwnSetting t      -> let phi = stPhis st M.! t\n                             in sampleProb gamma Own\n                              * sampleProb omega t\n                              * sampleProb phi x\n\ncitingFullCond :: MState -> CitingUpdateUnit -> [(Double, Setting CitingUpdateUnit)]\ncitingFullCond ms uu = map (\\s->(citingProb ms uu s, s)) $ citingDomain ms uu\n\ncitingDomain :: MState -> CitingUpdateUnit -> [Setting CitingUpdateUnit]\ncitingDomain ms uu = do\n    s <- [Own, Shared]\n    t <- M.keys $ stPhis ms\n    case s of\n        Shared -> do c <- S.toList $ uuCites uu\n                     return $ SharedSetting t c\n        Own    -> do return $ OwnSetting t\n\nsetCitingUU :: CitingUpdateUnit -> Maybe (Setting CitingUpdateUnit) -> MState -> MState\nsetCitingUU uu@(CitingUpdateUnit {uuNI=ni, uuN=n, uuX=x}) setting ms =\n    let set = maybe Unset (const Set) setting\n        ms' = case maybe (fetchSetting uu ms) id  setting of\n            SharedSetting t c -> ms { stPsis = M.adjust (setMultinom set c) n $ stPsis ms\n                                    , stLambdas = M.adjust (setMultinom set t) c $ stLambdas ms\n                                    , stPhis = M.adjust (setMultinom set x) t $ stPhis ms\n                                    , stGammas = M.adjust (setMultinom set Shared) n $ stGammas ms\n                                    }\n            OwnSetting t      -> ms { stOmegas = M.adjust (setMultinom set t) n $ stOmegas ms\n                                    , stPhis = M.adjust (setMultinom set x) t $ stPhis ms\n                                    , stGammas = M.adjust (setMultinom set Own) n $ stGammas ms\n                                    }\n    in ms' { stCiting = M.alter (const setting) ni $ stCiting ms' }\n", "meta": {"hexsha": "480b11af61ddec27a4df764250c26aa7064639cd", "size": 18554, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "network-topic-models/BayesStack/Models/Topic/CitationInfluence.hs", "max_stars_repo_name": "bgamari/bayes-stack", "max_stars_repo_head_hexsha": "020df7bb7263104fdea254e57d6c7daf7806da3e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-04-06T22:59:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T12:03:19.000Z", "max_issues_repo_path": "network-topic-models/BayesStack/Models/Topic/CitationInfluence.hs", "max_issues_repo_name": "bgamari/bayes-stack", "max_issues_repo_head_hexsha": "020df7bb7263104fdea254e57d6c7daf7806da3e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "network-topic-models/BayesStack/Models/Topic/CitationInfluence.hs", "max_forks_repo_name": "bgamari/bayes-stack", "max_forks_repo_head_hexsha": "020df7bb7263104fdea254e57d6c7daf7806da3e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-02-13T06:04:39.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-20T14:40:13.000Z", "avg_line_length": 43.2494172494, "max_line_length": 104, "alphanum_fraction": 0.5637598362, "num_tokens": 4688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.26082765004080244}}
{"text": "{-# LANGUAGE DefaultSignatures      #-}\n{-# LANGUAGE DeriveFoldable         #-}\n{-# LANGUAGE DeriveFunctor          #-}\n{-# LANGUAGE DeriveTraversable      #-}\n{-# LANGUAGE FlexibleContexts       #-}\n{-# LANGUAGE FlexibleInstances      #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses  #-}\n{-# LANGUAGE RankNTypes             #-}\n{-# LANGUAGE RecordWildCards        #-}\n{-# LANGUAGE ScopedTypeVariables    #-}\n{-# LANGUAGE TemplateHaskell        #-}\n{-# LANGUAGE TypeFamilies           #-}\n{-# LANGUAGE TypeOperators          #-}\nmodule Circuits.Analysis.DC where\n\nimport           Control.Lens\nimport           Control.Monad.Primitive\nimport           Control.Monad.ST\nimport           Data.Primitive.MutVar\nimport qualified Data.Vector                  as V\nimport qualified Data.Vector.Storable         as VS\nimport qualified Data.Vector.Storable.Mutable as VSM\nimport           Generics.Deriving.Lens\nimport           GHC.Generics\nimport qualified Numeric.LinearAlgebra        as HMatrix\n\nimport           Debug.Trace\n\nimport           Circuits.Circuit\n\n-- | Describes the time scale of a DC simulation. We can either perform a DC steady-state or a transient analysis.\ndata TimeScale\n  = SteadyState\n  -- ^ solving for steady state\n  | Step\n    { _currentTime :: Double -- ^ the current simulation time in seconds since t0\n    , _timeStep    :: Double -- ^ the size of current time step to be taken\n    }\n    -- ^ solving for next time step\n\nmakeLenses ''TimeScale\n\n-- | Type class providing an interface for the component stamps used in DC analysis.\nclass SimulateDC c where\n  -- | Beginning to solve the next time step.\n  beginSolve :: Simulation m Double sim => c -> TimeScale -> sim -> m ()\n  default beginSolve :: (Generic c, GSimulateDC (Rep c), Simulation m Double sim) => c -> TimeScale -> sim -> m ()\n  beginSolve c t s = forOf_ generic c $ \\gc -> gbeginSolve gc t s\n  -- | Beginning the next iteration of solving the non-linear parts.\n  -- This should set up the right hand side based on the current element state.\n  beginIteration :: Simulation m Double sim => c -> TimeScale -> sim -> m ()\n  default beginIteration :: (Generic c, GSimulateDC (Rep c), Simulation m Double sim) => c -> TimeScale -> sim -> m ()\n  beginIteration c t s = forOf_ generic c $ \\gc -> gbeginIteration gc t s\n  -- | End of the current iteration, after the referenced variables have been updated.\n  -- It should update the state of non-linear parts, but not the state of linear parts.\n  endIteration :: c -> TimeScale -> c\n  default endIteration :: (Generic c, GSimulateDC (Rep c)) => c -> TimeScale -> c\n  endIteration c t = over generic (`gendIteration` t) c\n  -- | Finished solving the current time step. Here, the state of linear parts should be updated.\n  endSolve :: c -> TimeScale -> c\n  default endSolve :: (Generic c, GSimulateDC (Rep c)) => c -> TimeScale -> c\n  endSolve c t = over generic (`gendSolve` t) c\n\ninstance SimulateDC Int where\n  beginSolve _ _ _ = pure ()\n  beginIteration _ _ _ = pure ()\n  endIteration x _ = x\n  endSolve x _ = x\n\ninstance SimulateDC Double where\n  beginSolve _ _ _ = pure ()\n  beginIteration _ _ _ = pure ()\n  endIteration x _ = x\n  endSolve x _ = x\n\ninstance SimulateDC Variable\ninstance SimulateDC Node\ninstance SimulateDC Branch\n\ninstance SimulateDC c => SimulateDC (Circuit c)\n\n-- * Generic deriving of SimulateDC instances\n\nclass GSimulateDC f where\n  gbeginSolve :: Simulation m Double sim => f p -> TimeScale -> sim -> m ()\n  gbeginIteration :: Simulation m Double sim => f p -> TimeScale -> sim -> m ()\n  gendIteration :: f p -> TimeScale -> f p\n  gendSolve :: f p -> TimeScale -> f p\n\ninstance GSimulateDC V1 where\n  gbeginSolve _ _ _ = return ()\n  gbeginIteration _ _ _ = return ()\n  gendIteration x _ = x\n  gendSolve x _ = x\n\ninstance GSimulateDC U1 where\n  gbeginSolve _ _ _ = return ()\n  gbeginIteration _ _ _ = return ()\n  gendIteration x _ = x\n  gendSolve x _ = x\n\ninstance SimulateDC a => GSimulateDC (K1 i a) where\n  gbeginSolve (K1 x) = beginSolve x\n  gbeginIteration (K1 x) = beginIteration x\n  gendIteration (K1 x) = K1 . endIteration x\n  gendSolve (K1 x) = K1 . endSolve x\n\ninstance GSimulateDC f => GSimulateDC (M1 i t f) where\n  gbeginSolve (M1 x) = gbeginSolve x\n  gbeginIteration (M1 x) = gbeginIteration x\n  gendIteration (M1 x) = M1 . gendIteration x\n  gendSolve (M1 x) = M1 . gendSolve x\n\ninstance (GSimulateDC f, GSimulateDC g) => GSimulateDC (f :+: g) where\n  gbeginSolve (L1 x) = gbeginSolve x\n  gbeginSolve (R1 x) = gbeginSolve x\n  gbeginIteration (L1 x) = gbeginIteration x\n  gbeginIteration (R1 x) = gbeginIteration x\n  gendIteration (L1 x) = L1 . gendIteration x\n  gendIteration (R1 x) = R1 . gendIteration x\n  gendSolve (L1 x) = L1 . gendSolve x\n  gendSolve (R1 x) = R1 . gendSolve x\n\ninstance (GSimulateDC f, GSimulateDC g) => GSimulateDC (f :*: g) where\n  gbeginSolve (x :*: y) t s = gbeginSolve x t s >> gbeginSolve y t s\n  gbeginIteration (x :*: y) t s = gbeginIteration x t s >> gbeginIteration y t s\n  gendIteration (x :*: y) t = gendIteration x t :*: gendIteration y t\n  gendSolve (x :*: y) t = gendSolve x t :*: gendSolve y t\n\n-- * DC Simulation\n\n-- | A mutable system of linear equations suitable for representing linear circuits.\ndata SimulationState s v = SimulationState\n  { size                 :: Int -- ^ the number of variables in this system\n  , coefficients         :: VSM.MVector s v -- ^ the underlying storage of the equations coefficients in row-major order\n  , coefficientsModified :: MutVar s Bool -- ^ flag indicating whether the coefficient matrix has been modified\n  , rhs                  :: VSM.MVector s v -- ^ the right hand side of the equations\n  , rhsModified          :: MutVar s Bool -- ^ flag indicating whether the RHS has been modified\n  }\n\n-- | Creates a new mutable linear circuit equation system with the given number of variables.\nnewSimulation :: (PrimMonad m, VSM.Storable v, Num v) => Int -> m (SimulationState (PrimState m) v)\nnewSimulation n =\n  SimulationState n <$> VSM.replicate (n * n) 0 <*> newMutVar False <*> VSM.replicate n 0 <*> newMutVar False\n\ncleanCoefficients :: (PrimMonad m) => SimulationState (PrimState m) v -> m ()\ncleanCoefficients s = writeMutVar (coefficientsModified s) False\n\ncleanRhs :: (PrimMonad m) => SimulationState (PrimState m) v -> m ()\ncleanRhs s = writeMutVar (rhsModified s) False\n\n-- | Computes the index into the flat buffer of matrix variables from a row and column.\nflatIndex :: SimulationState s v -- ^ the equation system\n          -> Int -- ^ matrix row\n          -> Int -- ^ matrix column\n          -> Int -- ^ flat buffer index\nflatIndex sim row col = row * size sim + col\n\nclass Monad m => Simulation m v sys | sys -> v  where\n  stampMatrix :: sys -> Variable -> Variable -> v -> m ()\n  stampRhs :: sys -> Variable -> v -> m ()\n\ninstance (PrimMonad m, PrimState m ~ s, Num v, VS.Storable v) => Simulation m v (SimulationState s v) where\n  stampMatrix sys (Index row _) (Index col _) value = do\n    VSM.modify (coefficients sys) (+ value) (flatIndex sys row col)\n    writeMutVar (coefficientsModified sys) True\n  stampMatrix _ _ _ _ = return () -- no stamping when ground is involved\n\n  stampRhs sys (Index row _) value = do\n    VSM.modify (rhs sys) (+ value) row\n    writeMutVar (rhsModified sys) True\n  stampRhs _ Ground _ = return () -- no stamping for ground\n\ninitialSolution :: HasVariables c => Circuit c -> VS.Vector Double\ninitialSolution c = runST $ do\n  vec <- VSM.new (c ^. variableCount)\n  forOf_ (model . variables . _Index) c $ uncurry (VSM.write vec)\n  VS.unsafeFreeze vec\n\nstep :: forall c. (HasVariables c, SimulateDC c) => TimeScale -> Circuit c -> Circuit c\nstep time c = runST simulate where\n  simulate :: ST s (Circuit c)\n  simulate = do\n    sim <- newSimulation (c ^. variableCount)\n    -- initialize matrix\n    beginSolve c time sim\n    mat <- HMatrix.reshape (c ^. variableCount) <$> VS.unsafeFreeze (coefficients sim)\n    cleanCoefficients sim\n    -- iterate\n    writeMutVar (rhsModified sim) True\n    c' <- solveNonLinear sim (HMatrix.luPacked mat) (initialSolution c) c\n    -- finalize\n    return $ endSolve c' time\n\n  solveNonLinear :: SimulationState s Double -> HMatrix.LU Double -> VS.Vector Double -> Circuit c -> ST s (Circuit c)\n  solveNonLinear sim lu prevSolution prevCircuit = do\n    -- prepare RHS\n    beginIteration c time sim\n    rhsUpdated <- readMutVar (rhsModified sim)\n    cleanRhs sim\n    if rhsUpdated\n      then do\n        -- solve and update components\n        rhs' <- VS.unsafeFreeze $ rhs sim\n        let solution = HMatrix.flatten $ HMatrix.luSolve lu (HMatrix.asColumn rhs')\n            c' = endIteration (updateValues solution c) time\n            maxChange = VS.maximum $ VS.zipWith (\\x y -> abs (x - y)) solution prevSolution\n        if maxChange < 1e-6\n          then return c'\n          else solveNonLinear sim lu solution c'\n      else return prevCircuit\n\n\n-- | Update all variable references inside a circuit description with its new values.\nupdateValues :: HasVariables a => VS.Vector Double -> a -> a\nupdateValues values = over variables replace where\n  replace Ground      = Ground\n  replace (Index i _) = vars V.! i\n  vars = V.imap Index $ VS.convert values\n", "meta": {"hexsha": "64c4a1fdedebf67ef01c4472a7d10ad347f9b346", "size": 9208, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Circuits/Analysis/DC.hs", "max_stars_repo_name": "fatho/circuits", "max_stars_repo_head_hexsha": "78849c38fea77989d5d3b88ee04f224845f287eb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-07T22:34:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-07T22:34:40.000Z", "max_issues_repo_path": "src/Circuits/Analysis/DC.hs", "max_issues_repo_name": "fatho/circuits", "max_issues_repo_head_hexsha": "78849c38fea77989d5d3b88ee04f224845f287eb", "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/Circuits/Analysis/DC.hs", "max_forks_repo_name": "fatho/circuits", "max_forks_repo_head_hexsha": "78849c38fea77989d5d3b88ee04f224845f287eb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-07T22:34:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-07T22:34:49.000Z", "avg_line_length": 41.665158371, "max_line_length": 120, "alphanum_fraction": 0.6758253692, "num_tokens": 2511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2606453365095897}}
{"text": "#!/usr/bin/env stack\n-- stack --resolver lts-12.4 script\n{-# LANGUAGE DeriveDataTypeable, ParallelListComp #-}\nmodule Main ( main ) where\n\nimport Hledger\n\nimport Control.Exception ( bracket )\nimport Control.Monad\nimport System.Exit\nimport System.IO\nimport Data.Time.Calendar\nimport Text.Printf\nimport Data.Function (on)\nimport Data.List\nimport Data.Ord\nimport Statistics.Math.RootFinding\nimport Data.Decimal\nimport qualified Data.Text as T\nimport System.Console.CmdArgs\nimport Text.Tabular as Tbl\nimport qualified Text.Tabular.AsciiArt as Ascii\n\ndata Options = Options\n  { cashFlow    :: Bool\n  , debug       :: Bool\n  , file        :: FilePath\n  , investments :: String\n  , pnl         :: String\n  , begin       :: Maybe String\n  , end         :: Maybe String\n  , daily       :: Bool\n  , weekly      :: Bool\n  , monthly     :: Bool\n  , yearly      :: Bool\n  , period      :: Maybe String\n  } deriving (Show, Data, Typeable)\n\nqueryFromOptions kind day accessor opts = \n  -- We ignore QueryOpts with fst as they are irrelevant for this program\n  case parseQuery day (T.pack $ accessor opts) of\n    (Any, _) -> error $ \"you need to specify \" ++ kind ++ \" query\"\n    (query, []) -> query\n    (_,     opts) -> error $ \"this program cannot process query options \" ++ show opts\n    \n\nintervalAndSpanFromOptions :: Day -> Options -> (Maybe Interval, DateSpan)\nintervalAndSpanFromOptions date opts =\n  let begin' = fmap parsedate $ begin opts\n      end' = fmap parsedate $ end opts \n  in\n   case (begin', end', daily opts, weekly opts, monthly opts, yearly opts, period opts) of\n     (Nothing, Nothing, False, False, False, False, Nothing) -> (Nothing, nulldatespan)\n     (b, e, True,  False, False, False, Nothing) -> (Just (Days 1),   DateSpan b e)\n     (b, e, False, True,  False, False, Nothing) -> (Just (Weeks 1),  DateSpan b e)\n     (b, e, False, False, True,  False, Nothing) -> (Just (Months 1), DateSpan b e)\n     (b, e, False, False, False, True,  Nothing) -> (Just (Years 1),  DateSpan b e)\n     (Nothing, Nothing, False, False, False, False, Just pexp) -> \n       let (i, s) = parsePeriodExpr' date (T.pack pexp) in (Just i, s)\n     _ -> error \"Cannot work with this combination of date/period flags\"\n\noptions = \n  Options { \n     cashFlow = \n      False &= name \"c\"\n      &= help \"also show all relevant transactions\"\n    , debug = \n      def \n      &= help \"print debugging info\"\n    , file = \n      def &= name \"f\"\n      &= typFile\n      &= help \"input ledger file (pass '-' for stdin)\"\n    , investments = \n      def &= name \"i\"\n      &= typ \"QUERY\"\n      &= help \"investments query\"\n    , pnl = \n      def &= name \"P\"\n      &= typ \"QUERY\"\n      &= help \"profit-and-loss query\"\n    , begin = \n      Nothing &= name \"b\"\n      &= typ \"DATE\"\n      &= help \"calculate interest from this date\"\n    , end = \n      Nothing &= name \"e\"\n      &= typ \"DATE\"\n      &= help \"calculate interest until this date\"\n    , daily =\n      def &= name \"D\"\n      &= help \"calculate interest for each day\"\n    , weekly =\n      def &= name \"W\"\n      &= help \"calculate interest for each week\"\n    , monthly = \n      def &= name \"M\"\n      &= help \"calculate interest for each month\"\n    , yearly = \n      def &= name \"Y\"\n      &= help \"calculate interest for each year\"\n    , period = \n      Nothing &= name \"p\"\n      &= typ \"PERIODEXP\"\n      &= help \"set start date, end date, and/or report interval all at once (overrides the flags above)\"\n    } \n  &= program \"hledger-roi\"\n  &= summary \"compute return-on-investment for your portfolio using IRR and TWR\"                             \n  &= details [\"\"]\n\nmain ::  IO ()\nmain = bracket (return ()) (\\() -> hFlush stdout >> hFlush stderr) $ \\() -> do\n  opts <-cmdArgs options\n  thisDay <- getCurrentDay\n  \n  let investmentsQuery = queryFromOptions \"investments\" thisDay investments opts\n  let pnlQuery         = queryFromOptions \"pnl\" thisDay pnl opts\n\n  jnl <- readJournalFile definputopts (file opts) >>= either fail return\n\n  let trans = jtxns $ filterJournalTransactions investmentsQuery jnl\n      \n  when (null trans) $ do\n    putStrLn \"No relevant transactions found. Check your investments query\"\n    exitFailure\n  \n  when (debug opts) $ do\n    putStrLn \"DEBUG everything:\"\n    print $ trans\n    putStrLn \"DEBUG just non-PnL transactions:\"\n    print $ filter (matchesTransaction (And [investmentsQuery, Not pnlQuery])) trans\n    putStrLn \"DEBUG just PnL transactions:\"\n    print $ filter (matchesTransaction pnlQuery) trans\n  \n  let (requestedInterval, requestedSpan) = intervalAndSpanFromOptions thisDay opts\n  let existingSpan = \n        let dates = map transactionDate2 trans in \n        DateSpan (Just $ minimum dates) (Just $ addDays 1 $ maximum dates)\n  let wholeSpan = spanDefaultsFrom requestedSpan existingSpan \n\n  let spans = case requestedInterval of\n        Nothing -> [wholeSpan]\n        Just interval ->\n            splitSpan interval $\n            spanIntersect existingSpan wholeSpan\n\n  tableBody <- (flip mapM) spans $ \\(DateSpan (Just ibegin) (Just iend)) -> do\n    -- Spans are [begin,end), and iend here is 1 days after actual end date we are interested in\n    let valueBeforeThisPeriod =\n          total trans (And [ investmentsQuery\n                           , Date (DateSpan Nothing (Just ibegin))])\n      \n    let valueAtTheEndOfPeriod  = \n          total trans (And [investmentsQuery, Date (DateSpan Nothing (Just iend))])\n        \n    let cashFlowInThisPeriod = \n          calculateCashFlow trans (And [ Not investmentsQuery\n                                       , Not pnlQuery\n                                       , Date (DateSpan (Just ibegin) (Just iend)) ] )\n    \n    irr <- internalRateOfReturn opts ibegin iend valueBeforeThisPeriod valueAtTheEndOfPeriod cashFlowInThisPeriod\n    twr <- timeWeightedReturn opts investmentsQuery trans ibegin iend valueBeforeThisPeriod valueAtTheEndOfPeriod cashFlowInThisPeriod\n    let cashFlowAmt = negate $ sum $ map snd cashFlowInThisPeriod\n    return [ showDate ibegin\n           , showDate (addDays (-1) iend)\n           , show valueBeforeThisPeriod\n           , show cashFlowAmt\n           , show valueAtTheEndOfPeriod\n           , show (valueAtTheEndOfPeriod - (valueBeforeThisPeriod + cashFlowAmt))\n           , printf \"%0.2f%%\" irr\n           , printf \"%0.2f%%\" twr ]\n\n  let table = Tbl.Table \n              (Group NoLine (map (Header . show) (take (length tableBody) [1..]))) \n              (Group DoubleLine \n               [ Group SingleLine [Header \"Begin\", Header \"End\"]\n               , Group SingleLine [Header \"Value (begin)\", Header \"Cashflow\", Header \"Value (end)\", Header \"PnL\"]\n               , Group SingleLine [Header \"IRR\", Header \"TWR\"]])\n              tableBody\n  \n  putStrLn $ Ascii.render id id id table\n\ntimeWeightedReturn opts investmentsQuery trans ibegin iend valueBefore valueAfter cashFlowInThisPeriod = do\n  -- Span is [ibegin,iend), and iend is 1 days after actual end date we are interested in\n  let initialUnitPrice = 100\n  let initialUnits = valueBefore / initialUnitPrice\n  let cashflow = \n        -- Aggregate all entries for a single day, assuming that intraday interest is negligible\n        map (\\date_cash -> let (dates, cash) = unzip date_cash in (head dates, sum cash))\n        $ groupBy ((==) `on` fst)\n        $ sortBy (comparing fst) \n        $ map (\\(d,a) -> (d, negate a)) \n        $ filter ((/=0).snd) cashFlowInThisPeriod\n    \n  let units = \n        tail $\n        (flip scanl) \n        (0,0,0,initialUnits)\n        (\\(_,_,_,unitBalance) (date, amt) -> \n          let valueOnDate = \n                total trans (And [investmentsQuery, Date (DateSpan Nothing (Just date))])\n              unitPrice = if unitBalance == 0.0 then initialUnitPrice else valueOnDate / unitBalance\n              unitsBoughtOrSold = amt / unitPrice\n          in\n           (valueOnDate, unitsBoughtOrSold, unitPrice, unitBalance + unitsBoughtOrSold)\n        )  \n        cashflow\n  \n  let finalUnitBalance = if null units then initialUnits else let (_,_,_,u) = last units in u\n      finalUnitPrice = valueAfter / finalUnitBalance\n      totalTWR = roundTo 2 $ (finalUnitPrice - initialUnitPrice)\n      years = (fromIntegral $ diffDays iend ibegin)/365 :: Double\n      annualizedTWR = 100*((1+(realToFrac totalTWR/100))**(1/years)-1) :: Double\n        \n  let s d = show $ roundTo 2 d \n  when (cashFlow opts) $ do\n    printf \"\\nTWR cash flow for %s - %s\\n\" (showDate ibegin) (showDate (addDays (-1) iend)) \n    let (dates', amounts') = unzip cashflow\n        (valuesOnDate',unitsBoughtOrSold', unitPrices', unitBalances') = unzip4 units\n        add x lst = if valueBefore/=0 then x:lst else lst\n        dates = add ibegin dates'\n        amounts = add valueBefore amounts'\n        unitsBoughtOrSold = add initialUnits unitsBoughtOrSold'\n        unitPrices = add initialUnitPrice unitPrices'\n        unitBalances = add initialUnits unitBalances'\n        valuesOnDate = add 0 valuesOnDate'\n        \n    putStr $ Ascii.render id id id \n      (Tbl.Table \n       (Group NoLine (map (Header . showDate) dates))\n       (Group DoubleLine [ Group SingleLine [Header \"Portfolio value\", Header \"Unit balance\"] \n                         , Group SingleLine [Header \"Cash\", Header \"Unit price\", Header \"Units\"]\n                         , Group SingleLine [Header \"New Unit Balance\"]])\n       [ [value, oldBalance, amt, prc, udelta, balance] \n       | value <- map s valuesOnDate\n       | oldBalance <- map s (0:unitBalances)\n       | balance <- map s unitBalances\n       | amt <- map s amounts\n       | prc <- map s unitPrices\n       | udelta <- map s unitsBoughtOrSold ])\n  \n    printf \"Final unit price: %s/%s=%s U.\\nTotal TWR: %s%%.\\nPeriod: %.2f years.\\nAnnualized TWR: %.2f%%\\n\\n\" (s valueAfter) (s finalUnitBalance) (s finalUnitPrice) (s totalTWR) years annualizedTWR\n  \n  return annualizedTWR\n  \n\ninternalRateOfReturn opts ibegin iend valueBefore valueAfter cashFlowInPeriod = do \n  -- Span is [ibegin,iend), and iend is 1 days after actual end date we are interested in\n  let prefix = (ibegin, negate valueBefore)\n\n      postfix = (iend, valueAfter)\n\n      totalCF = filter ((/=0) . snd) $ prefix : (sortBy (comparing fst) cashFlowInPeriod) ++ [postfix]\n\n  when (cashFlow opts) $ do\n    printf \"\\nIRR cash flow for %s - %s\\n\" (showDate ibegin) (showDate (addDays (-1) iend)) \n    let (dates, amounts) = unzip totalCF\n    putStrLn $ Ascii.render id id id \n      (Tbl.Table \n       (Group NoLine (map (Header . showDate) dates))\n       (Group SingleLine [Header \"Amount\"])\n       (map ((:[]) . show) amounts))\n                             \n  -- 0% is always a solution, so require at least something here\n  case ridders 0.00001 (0.000000000001,10000) (interestSum iend totalCF) of\n    Root rate -> return ((rate-1)*100)\n    NotBracketed -> error \"Error: No solution -- not bracketed.\"\n    SearchFailed -> error \"Error: Failed to find solution.\"\n\n\ntype CashFlow = [(Day, Quantity)]\n\ninterestSum :: Day -> CashFlow -> Double -> Double\ninterestSum referenceDay cf rate = sum $ map go cf\n    where go (t,m) = (fromRational $ toRational m) * (rate ** (fromIntegral (referenceDay `diffDays` t) / 365))\n\n\ncalculateCashFlow :: [Transaction] -> Query -> CashFlow\ncalculateCashFlow trans query = map go trans\n    where\n    go t = (transactionDate2 t, total [t] query)\n\ntotal :: [Transaction] -> Query -> Quantity\ntotal trans query = unMix $ sumPostings $ filter (matchesPosting query) $ concatMap realPostings trans\n    \nunMix :: MixedAmount -> Quantity   \nunMix a = \n  case (normaliseMixedAmount $ costOfMixedAmount a) of\n    (Mixed [a]) -> aquantity a\n    _ -> error \"MixedAmount failed to normalize\"\n\n", "meta": {"hexsha": "4142eaff0ec588a94d3aee77315d22736238ff34", "size": 11618, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "hledger-roi.hs", "max_stars_repo_name": "adept/hledger-roi", "max_stars_repo_head_hexsha": "fad20e29eca1e9ac975fa8308e25d1649ca301cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-09-17T00:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T04:17:58.000Z", "max_issues_repo_path": "hledger-roi.hs", "max_issues_repo_name": "adept/hledger-roi", "max_issues_repo_head_hexsha": "fad20e29eca1e9ac975fa8308e25d1649ca301cc", "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": "hledger-roi.hs", "max_forks_repo_name": "adept/hledger-roi", "max_forks_repo_head_hexsha": "fad20e29eca1e9ac975fa8308e25d1649ca301cc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-17T12:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-26T19:23:57.000Z", "avg_line_length": 39.7876712329, "max_line_length": 197, "alphanum_fraction": 0.6325529351, "num_tokens": 3053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2581694375402049}}
{"text": "{-# LANGUAGE ConstraintKinds, DataKinds, FlexibleInstances,\n             GeneralizedNewtypeDeriving, MultiParamTypeClasses,\n             TypeFamilies #-}\n-- | Several implementations of the monad in which our dual numbers live\n-- and implementations of calculating gradient, derivative and value\n-- of an objective function defined on dual numbers.\nmodule HordeAd.Core.Engine\n  ( DualMonadValue, primalValueGeneral, primalValue\n  , DualMonadGradient, dReverseGeneral, dReverse, dForwardGeneral, dForward, prettyPrintDf\n  , DualMonadForward, dFastForwardGeneral, dFastForward\n  , generateDeltaVars, initializerFixed\n  ) where\n\nimport Prelude\n\nimport           Control.Monad.Trans.State.Strict\nimport qualified Data.Array.DynamicS as OT\nimport           Data.Functor.Identity\nimport qualified Data.Strict.Vector as Data.Vector\nimport qualified Data.Vector.Generic as V\nimport           Numeric.LinearAlgebra (Matrix, Numeric, Vector)\nimport qualified Numeric.LinearAlgebra as HM\n\nimport HordeAd.Core.DualClass\n  (Dual, IsPrimal (..), IsPrimalWithScalar, bindInState, dVar)\nimport HordeAd.Core.DualNumber\nimport HordeAd.Core.PairOfVectors (DualNumberVariables, makeDualNumberVariables)\nimport HordeAd.Internal.Delta\n  ( CodeOut (..)\n  , DeltaState (..)\n  , derivativeFromDelta\n  , gradientFromDelta\n  , ppBindings\n  , toDeltaId\n  )\n\n-- * The dummy monad implementation that does not collect deltas.\n-- It's intended for efficiently calculating the value of the function only.\n\n-- An overcomplicated\n-- @type DualMonadValue r = Identity@\n-- to avoid @-Wno-orphans@ and @UndecidableInstances@.\nnewtype DualMonadValue r a = DualMonadValue\n  { runDualMonadValue :: Identity a }\n  deriving (Monad, Functor, Applicative)\n\ninstance IsScalar 'DModeGradient r\n         => DualMonad 'DModeGradient r (DualMonadValue r) where\n  returnLet (D u _u') = DualMonadValue $ Identity $ D u dZero\n\n-- The general case, needed for old, hacky tests using only scalars.\nprimalValueGeneral\n  :: forall r a. IsScalar 'DModeGradient r\n  => (DualNumberVariables 'DModeGradient r\n      -> DualMonadValue r a)\n  -> Domains r\n  -> a\n-- Small enough that inline won't hurt.\n{-# INLINE primalValueGeneral #-}\nprimalValueGeneral f (params0, params1, params2, paramsX) =\n  let replicateZeros p = V.replicate (V.length p) dZero\n      variables = makeDualNumberVariables\n                    (params0, params1, params2, paramsX)\n                    ( replicateZeros params0  -- dummy\n                    , replicateZeros params1\n                    , replicateZeros params2\n                    , replicateZeros paramsX )\n  in runIdentity $ runDualMonadValue $ f variables\n\nprimalValue\n  :: forall r a. IsScalar 'DModeGradient r\n  => (DualNumberVariables 'DModeGradient r\n      -> DualMonadValue r (DualNumber 'DModeGradient a))\n  -> Domains r\n  -> a\n-- Small enough that inline won't hurt.\n{-# INLINE primalValue #-}\nprimalValue f parameters =\n  let D value _ = primalValueGeneral f parameters\n  in value\n\n\n-- * The fully-fledged monad implementation for gradients\n-- and the code that uses it to compute gradients and also derivatives.\n\nnewtype DualMonadGradient r a = DualMonadGradient\n  { runDualMonadGradient :: State (DeltaState r) a }\n  deriving (Monad, Functor, Applicative)\n\ninstance IsScalar 'DModeGradient r\n         => DualMonad 'DModeGradient\n                      r (DualMonadGradient r) where\n  returnLet (D u u') = DualMonadGradient $ do\n    st <- get\n    let (!stNew, !dId) = bindInState u' st\n    put stNew\n    return $! D u (dVar dId)\n\ninitializeState :: forall r. IsScalar 'DModeGradient r\n                => Domains r -> DeltaState r\ninitializeState (params0, params1, params2, paramsX) =\n  DeltaState { deltaCounter0 = toDeltaId (V.length params0)\n             , deltaCounter1 = toDeltaId (V.length params1)\n             , deltaCounter2 = toDeltaId (V.length params2)\n             , deltaCounterX = toDeltaId (V.length paramsX)\n             , deltaBindings = []\n             }\n\ndReverseGeneral\n  :: forall r. HasDelta r\n  => r\n  -> DualNumberVariables 'DModeGradient r\n  -> (DualNumberVariables 'DModeGradient r\n      -> DualMonadGradient r (DualNumber 'DModeGradient r))\n  -> (Domains r, r)\n-- The functions in which @dReverseGeneral@ inlines are not inlined themselves\n-- in client code, so the bloat is limited.\n{-# INLINE dReverseGeneral #-}\ndReverseGeneral dt\n                variables@(params0, _, params1, _, params2, _, paramsX, _)\n                f =\n  let dim0 = V.length params0\n      dim1 = V.length params1\n      dim2 = V.length params2\n      dimX = V.length paramsX\n      initialState = initializeState (params0, params1, params2, paramsX)\n      (D value d, st) = runState (runDualMonadGradient (f variables))\n                                 initialState\n      inlineDerivative primCode primalArgs dualArgs =\n        let D _ u' = outDualNumber primCode primalArgs dualArgs\n        in u'\n      gradient =\n        gradientFromDelta inlineDerivative inlineDerivative inlineDerivative\n                          inlineDerivative inlineDerivative\n                          dim0 dim1 dim2 dimX st d dt\n  in (gradient, value)\n\ndReverse :: HasDelta r\n   => r\n   -> (DualNumberVariables 'DModeGradient r\n       -> DualMonadGradient r (DualNumber 'DModeGradient r))\n   -> Domains r\n   -> (Domains r, r)\ndReverse dt f parameters =\n  let varDeltas = generateDeltaVars parameters\n      variables = makeDualNumberVariables parameters varDeltas\n  in dReverseGeneral dt variables f\n\n-- This function uses @DualMonadGradient@ for an inefficient computation\n-- of forward derivaties. See @dFastForwardGeneral@ for an efficient variant.\ndForwardGeneral\n  :: forall r. HasDelta r\n  => DualNumberVariables 'DModeGradient r\n  -> (DualNumberVariables 'DModeGradient r\n      -> DualMonadGradient r (DualNumber 'DModeGradient r))\n  -> Domains r\n  -> (r, r)\n{-# INLINE dForwardGeneral #-}\ndForwardGeneral variables@(params0, _, params1, _, params2, _, paramsX, _)\n                f ds =\n  let initialState = initializeState (params0, params1, params2, paramsX)\n      (D value d, st) = runState (runDualMonadGradient (f variables))\n                                 initialState\n      inlineDerivative primCode primalArgs dualArgs =\n        let D _ u' = outDualNumber primCode primalArgs dualArgs\n        in u'\n  in ( derivativeFromDelta inlineDerivative inlineDerivative inlineDerivative\n                           inlineDerivative inlineDerivative\n                           st d ds\n     , value )\n\n-- The direction vector ds is taken as an extra argument.\ndForward\n  :: HasDelta r\n  => (DualNumberVariables 'DModeGradient r\n      -> DualMonadGradient r (DualNumber 'DModeGradient r))\n  -> Domains r\n  -> Domains r\n  -> (r, r)\ndForward f parameters ds =\n  let varDeltas = generateDeltaVars parameters\n      variables = makeDualNumberVariables parameters varDeltas\n  in dForwardGeneral variables f ds\n\n\n-- * A monad for efficiently computing forward derivatives.\n\nnewtype DualMonadForward r a = DualMonadForward\n  { runDualMonadForward :: Identity a }\n  deriving (Monad, Functor, Applicative)\n\ninstance IsScalar 'DModeDerivative r\n         => DualMonad 'DModeDerivative\n                      r (DualMonadForward r) where\n  returnLet (D u u') = DualMonadForward $ Identity $ D u u'\n\n-- This the efficient variant of forward derivative computation.\ndFastForwardGeneral\n  :: Dual 'DModeDerivative r ~ r\n  => DualNumberVariables 'DModeDerivative r\n  -> (DualNumberVariables 'DModeDerivative r\n      -> DualMonadForward r (DualNumber 'DModeDerivative r))\n  -> (r, r)\n{-# INLINE dFastForwardGeneral #-}\ndFastForwardGeneral variables f =\n  let D value d = runIdentity $ runDualMonadForward $ f variables\n  in (d, value)\n\n-- The direction vector ds is taken as an extra argument.\ndFastForward\n  :: forall r. (Numeric r, Dual 'DModeDerivative r ~ r)\n  => (DualNumberVariables 'DModeDerivative r\n      -> DualMonadForward r (DualNumber 'DModeDerivative r))\n  -> Domains r\n  -> Domains r\n  -> (r, r)\ndFastForward f parameters (params0, params1, params2, paramsX) =\n  let variables =\n        makeDualNumberVariables\n          parameters\n          (V.convert params0, params1, params2, paramsX)  -- ds\n      (derivative, value) = dFastForwardGeneral variables f\n  in (derivative, value)\n\n\n-- * Additional mechanisms\n\nprettyPrintDf\n  :: forall r. HasDelta r\n  => Bool\n  -> (DualNumberVariables 'DModeGradient r\n      -> DualMonadGradient r (DualNumber 'DModeGradient r))\n  -> Domains r\n  -> String\nprettyPrintDf reversed f parameters =\n  let varDeltas = generateDeltaVars parameters\n      variables = makeDualNumberVariables parameters varDeltas\n      initialState = initializeState parameters\n      (D _ deltaTopLevel, st) = runState (runDualMonadGradient (f variables))\n                                         initialState\n  in ppBindings reversed st deltaTopLevel\n\ngenerateDeltaVars\n  :: forall r. IsScalar 'DModeGradient r\n  => Domains r\n  -> ( Data.Vector.Vector (Dual 'DModeGradient r)\n     , Data.Vector.Vector (Dual 'DModeGradient (Vector r))\n     , Data.Vector.Vector (Dual 'DModeGradient (Matrix r))\n     , Data.Vector.Vector (Dual 'DModeGradient (OT.Array r)) )\ngenerateDeltaVars (params0, params1, params2, paramsX) =\n  let vVar :: forall a v. (IsPrimalWithScalar 'DModeGradient a r, V.Vector v a)\n           => v a -> Data.Vector.Vector (Dual 'DModeGradient a)\n      vVar p = V.generate (V.length p) (dVar . toDeltaId)\n      !v0 = vVar params0\n      !v1 = vVar params1\n      !v2 = vVar params2\n      !vX = vVar paramsX\n  in (v0, v1, v2, vX)\n\n-- | Initialize parameters using a uniform distribution with a fixed range\n-- taken from an argument.\n--\n-- Must be Double, because @randomVector@ only works on that.\n--\n-- This only works fine for nets with levels that have similar size and use\n-- the same activation function. Otherwise, the range should vary per level.\n-- A rule of thumb range for weights is @sqrt(6 / (F_in + F_out)@,\n-- where @F_in + F_out@ is the sum of inputs and outputs of the largest level.\n-- See https://github.com/pytorch/pytorch/issues/15314 and their newer code.\ninitializerFixed :: Int -> Double -> (Int, [Int], [(Int, Int)], [OT.ShapeL])\n                 -> ((Int, Int, Int, Int), Int, Double, Domains Double)\ninitializerFixed seed range (nParams0, lParams1, lParams2, lParamsX) =\n  let vParams1 = V.fromList lParams1\n      vParams2 = V.fromList lParams2\n      vParamsX = V.fromList lParamsX\n      createRandomVector n seedV =\n        HM.scale (2 * range)\n        $ HM.randomVector seedV HM.Uniform n - HM.scalar 0.5\n      params0Init = createRandomVector nParams0 seed\n      params1Init =\n        V.imap (\\i nPV -> createRandomVector nPV (seed + nPV + i)) vParams1\n      params2Init =\n        V.imap (\\i (rows, cols) ->\n                 HM.reshape cols\n                 $ createRandomVector (rows * cols) (seed + rows + i)) vParams2\n      paramsXInit =\n        V.imap (\\i sh ->\n                 let sz = product sh\n                 in OT.fromVector sh\n                    $ createRandomVector sz (seed + sz + i)) vParamsX\n      totalParams = nParams0\n                    + V.sum vParams1\n                    + V.sum (V.map (uncurry (*)) vParams2)\n                    + V.sum (V.map product vParamsX)\n  in ( (nParams0, V.length vParams1, V.length vParams2, V.length vParamsX)\n     , totalParams\n     , range\n     , (params0Init, params1Init, params2Init, paramsXInit) )\n\noutDualNumber :: (IsPrimal d a, RealFloat a, Show a, Show (Dual d a))\n              => CodeOut -> [a] -> [Dual d a]\n              -> DualNumber d a\noutDualNumber PlusOut [u, v] [u', v'] = D u u' + D v v'\noutDualNumber MinusOut [u, v] [u', v'] = D u u' - D v v'\noutDualNumber TimesOut [u, v] [u', v'] = D u u' * D v v'\noutDualNumber NegateOut [u] [u'] = negate $ D u u'\noutDualNumber AbsOut [u] [u'] = abs $ D u u'\noutDualNumber SignumOut [u] [u'] = signum $ D u u'\noutDualNumber DivideOut [u, v] [u', v'] = D u u' / D v v'\noutDualNumber RecipOut [u] [u'] = recip $ D u u'\noutDualNumber ExpOut [u] [u'] = exp $ D u u'\noutDualNumber LogOut [u] [u'] = log $ D u u'\noutDualNumber SqrtOut [u] [u'] = sqrt $ D u u'\noutDualNumber PowerOut [u, v] [u', v'] = D u u' ** D v v'\noutDualNumber LogBaseOut [u, v] [u', v'] = logBase (D u u') (D v v')\noutDualNumber SinOut [u] [u'] = sin $ D u u'\noutDualNumber CosOut [u] [u'] = cos $ D u u'\noutDualNumber TanOut [u] [u'] = tan $ D u u'\noutDualNumber AsinOut [u] [u'] = asin $ D u u'\noutDualNumber AcosOut [u] [u'] = acos $ D u u'\noutDualNumber AtanOut [u] [u'] = atan $ D u u'\noutDualNumber SinhOut [u] [u'] = sinh $ D u u'\noutDualNumber CoshOut [u] [u'] = cosh $ D u u'\noutDualNumber TanhOut [u] [u'] = tanh $ D u u'\noutDualNumber AsinhOut [u] [u'] = asinh $ D u u'\noutDualNumber AcoshOut [u] [u'] = acosh $ D u u'\noutDualNumber AtanhOut [u] [u'] = atanh $ D u u'\noutDualNumber Atan2Out [u, v] [u', v'] = atan2 (D u u') (D v v')\noutDualNumber primCode primalArgs dualArgs =\n  error $ \"outDualNumber: wrong number of arguments\"\n          ++ show (primCode, primalArgs, dualArgs)\n", "meta": {"hexsha": "e09102ce12d91a1b2bbeb98f8e85c4497fff921e", "size": 12980, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Core/Engine.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/Engine.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/Engine.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.0963855422, "max_line_length": 90, "alphanum_fraction": 0.6696456086, "num_tokens": 3536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635841117624, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2561336667539559}}