{"text": "{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}\nmodule Test.Gen where\nimport Test.Utils\nimport Test.QuickCheck\nimport Control.Monad\nimport qualified Numeric.LinearAlgebra as L\nimport Numeric.LinearAlgebra.Devel\nimport qualified Data.Vector.Storable as V\n\nsquared_real_matrices :: Int -> Gen (L.Matrix Float)\nsquared_real_matrices k = do\n vs <- sequence (replicate (k*k) arbitrary) :: Gen [Float]\n return $ L.reshape k $ V.fromList vs\n\nsmall_matrices :: Gen (L.Matrix Float)\nsmall_matrices = do\n n <- choose (2,10)\n squared_real_matrices n\n\npair :: Gen a -> Gen b -> Gen (a,b)\npair = liftM2 (,)\n", "meta": {"hexsha": "07dba0f20169ca7dafa64a741a1991b494bae53c", "size": 603, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Backend-blashs/Test/Gen.hs", "max_stars_repo_name": "pierric/neural-network", "max_stars_repo_head_hexsha": "406ecaf334cde9b10c9324e1f6c4b8663eae58d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-05-24T17:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T22:25:52.000Z", "max_issues_repo_path": "Backend-blashs/Test/Gen.hs", "max_issues_repo_name": "pierric/neural-network", "max_issues_repo_head_hexsha": "406ecaf334cde9b10c9324e1f6c4b8663eae58d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Backend-blashs/Test/Gen.hs", "max_forks_repo_name": "pierric/neural-network", "max_forks_repo_head_hexsha": "406ecaf334cde9b10c9324e1f6c4b8663eae58d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-26T19:28:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T19:28:38.000Z", "avg_line_length": 27.4090909091, "max_line_length": 59, "alphanum_fraction": 0.7429519071, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5998718471902703}} {"text": "module LibSpec where\n\nimport Debug.Trace\nimport Lib (sigmoid)\nimport Numeric.LinearAlgebra (( #> ))\nimport Numeric.LinearAlgebra.Data (Matrix, Vector, cond, tr, vector,\n (><))\nimport Test.Hspec hiding (Spec)\nimport Test.Hspec as Hspec\nimport Test.HUnit (Assertion, assertBool)\n\nspec :: Hspec.Spec\nspec = do\n describe \"sigmoid\" $\n it \"Should be correct.\" $ do\n (sigmoid ((3 >< 2) [1.0 ..]) :: Matrix Double) `shouldBe`\n (((3 >< 2)\n [ 0.7310585786300049\n , 0.8807970779778823\n , 0.9525741268224334\n , 0.9820137900379085\n , 0.9933071490757153\n , 0.9975273768433653\n ]) :: Matrix Double)\n describe \"cond behaviour\" $\n it \"Should be correct.\" $ do\n (traceShowId (cond ((3 >< 2) [1.0 ..] :: Matrix Double) 3 0 1 0)) `shouldBe`\n ((3 >< 2) [0, 0, 1, 0, 0, 0] :: Matrix Double)\n describe \"m.v behaviour\" $\n it \"Should be correct.\" $ do\n let x = (3 >< 2) [1.0 ..] :: Matrix Double\n theta = vector [10.0, 5.0] :: Vector Double\n (x #> theta) `shouldBe` (vector [20.0, 50.0, 80.0] :: Vector Double)\n", "meta": {"hexsha": "419fc5f66c99a0271ccd32e6098dcb2d493febf7", "size": 1308, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/LibSpec.hs", "max_stars_repo_name": "krisajenkins/sketch", "max_stars_repo_head_hexsha": "54289f580f74ac040da7323c0b2d830b18e7fbcf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-17T17:34:19.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-17T17:34:19.000Z", "max_issues_repo_path": "test/LibSpec.hs", "max_issues_repo_name": "krisajenkins/sketch", "max_issues_repo_head_hexsha": "54289f580f74ac040da7323c0b2d830b18e7fbcf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/LibSpec.hs", "max_forks_repo_name": "krisajenkins/sketch", "max_forks_repo_head_hexsha": "54289f580f74ac040da7323c0b2d830b18e7fbcf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4705882353, "max_line_length": 82, "alphanum_fraction": 0.4900611621, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5997981241117869}} {"text": "{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving, Rank2Types #-}\n{-# OPTIONS_HADDOCK hide #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.LinearAlgebra.Matrix.Base\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n\nmodule Numeric.LinearAlgebra.Matrix.Base (\n Matrix(..),\n dim,\n \n fromList,\n fromRow,\n fromCol,\n zero,\n constant,\n \n at,\n unsafeAt,\n\n indices,\n elems,\n assocs,\n\n col,\n unsafeCol,\n cols,\n\n update,\n unsafeUpdate,\n accum,\n unsafeAccum,\n\n map,\n zipWith,\n unsafeZipWith,\n\n \n slice,\n unsafeSlice,\n \n splitRowsAt,\n dropRows,\n takeRows,\n\n splitColsAt,\n dropCols,\n takeCols,\n\n fromVector,\n toVector,\n\n isContig,\n unsafeFromForeignPtr,\n unsafeToForeignPtr,\n unsafeWith,\n\n ) where\n\nimport Prelude hiding ( read, map, zipWith )\nimport qualified Prelude as P\n\nimport Data.AEq( AEq(..) )\nimport Data.Typeable( Typeable )\nimport Foreign( ForeignPtr, Ptr, Storable )\nimport Text.Printf( printf )\n\nimport Numeric.LinearAlgebra.Vector( Vector )\nimport qualified Numeric.LinearAlgebra.Vector as V\n\n-- | Immutable dense matrices.\ndata Matrix e =\n Matrix {-# UNPACK #-} !(Vector e) -- matrix data\n {-# UNPACK #-} !Int -- row dimension\n {-# UNPACK #-} !Int -- column dimension\n {-# UNPACK #-} !Int -- leading dimension\n deriving (Typeable)\n\n-- | Get the matrix dimensions (number of rows and number of columns).\ndim :: (Storable e) => Matrix e -> (Int,Int)\ndim (Matrix _ m n _) = (m,n)\n{-# INLINE dim #-}\n\n-- | Indicates if the elements of the matrix are stored contigously\nisContig :: (Storable e) => Matrix e -> Bool\nisContig (Matrix _ m _ lda) = lda == m || m == 0\n{-# INLINE isContig #-}\n\n-- | Create a matrix of the given dimension with elements initialized\n-- to the values from the list, in column major order.\nfromList :: (Storable e) => (Int,Int) -> [e] -> Matrix e\nfromList (m,n) es\n | m < 0 || n < 0 = error $\n printf \"fromList (%d,%d): negative dimension\" m n\n | otherwise = let\n v = V.fromList (m*n) es\n lda = max 1 m\n in Matrix v m n lda\n{-# INLINE fromList #-}\n\n-- | Create a matrix of the given dimension with all elements initialized\n-- to the given value\nconstant :: (Storable e) => (Int,Int) -> e -> Matrix e\nconstant (m,n) e\n | m < 0 || n < 0 = error $\n printf \"constant (%d,%d): negative dimension\" m n\n | otherwise = let\n v = V.constant (m*n) e\n lda = max 1 m\n in Matrix v m n lda\n{-# INLINE constant #-}\n\n-- | Create a zero of the given dimension with all elements initialized\n-- to zero.\nzero :: (Storable e, Num e) => (Int,Int) -> Matrix e\nzero (m,n)\n | m < 0 || n < 0 = error $\n printf \"zero (%d,%d): negative dimension\" m n\n | otherwise = let\n v = V.zero (m*n)\n lda = max 1 m\n in Matrix v m n lda\n{-# INLINE zero #-}\n\n-- | Returns the element of a matrix at the specified index.\nat :: (Storable e) => Matrix e -> (Int,Int) -> e\nat a ij@(i,j)\n | i < 0 || i >= m || j < 0 || j >= n = error $\n printf (\"at (%d,%d):\"\n ++ \" invalid index\") m n i j\n | otherwise =\n unsafeAt a ij\n where\n (m,n) = dim a\n{-# INLINE at #-}\n\nunsafeAt :: (Storable e) => Matrix e -> (Int,Int) -> e\nunsafeAt (Matrix v _ _ lda) (i,j) = \n V.unsafeAt v (i + j * lda)\n{-# INLINE unsafeAt #-}\n\n-- | Get the indices of the elements in the matrix, in column-major order.\nindices :: (Storable e) => Matrix e -> [(Int,Int)]\nindices a = [ (i,j) | j <- [ 0..n-1 ], i <- [ 0..m-1 ] ]\n where (m,n) = dim a\n\n-- | Returns a list of the elements of a matrix, in the same order as their\n-- indices.\nelems :: (Storable e) => Matrix e -> [e]\nelems (Matrix v m _ lda)\n | lda == m = V.elems v\n | otherwise = let\n breakCols [] = []\n breakCols es = let (c,es') = splitAt lda es in c:(breakCols es')\n\n dropJunk c = take m c\n\n in concatMap dropJunk $ breakCols (V.elems v)\n{-# INLINE elems #-}\n\n-- | Returns the contents of a matrix as a list of associations.\nassocs :: (Storable e) => Matrix e -> [((Int,Int),e)]\nassocs x = zip (indices x) (elems x)\n{-# INLINE assocs #-}\n\n-- | Version of 'update' that doesn't range-check indices.\nunsafeUpdate :: (Storable e) => Matrix e -> [((Int,Int),e)] -> Matrix e\nunsafeUpdate (Matrix v m n lda) ijes = let\n ies = [ (i + j * lda, e) | ((i,j),e) <- ijes ]\n v' = V.unsafeUpdate v ies\n in Matrix v' m n lda\n\n-- | Create a new matrix by replacing the values at the specified indices.\nupdate :: (Storable e) => Matrix e -> [((Int,Int),e)] -> Matrix e\nupdate (Matrix v m n lda) ijes = let\n ies = [ if i < 0 || i >= m || j < 0 || j >= n\n then error $ printf\n (\"update\"\n ++ \" \"\n ++ \" [ ..((%d,%d),_).. ]\"\n ++ \": invalid index\")\n m n i j\n else (i + j * lda, e)\n | ((i,j),e) <- ijes\n ]\n v' = V.unsafeUpdate v ies\n in Matrix v' m n lda\n\n-- | Same as 'accum' but does not range-check indices.\nunsafeAccum :: (Storable e)\n => (e -> e' -> e)\n -> Matrix e\n -> [((Int,Int), e')]\n -> Matrix e\nunsafeAccum f (Matrix v m n lda) ijes = let\n ies = [ (i + j * lda, e) | ((i,j),e) <- ijes ]\n v' = V.unsafeAccum f v ies\n in Matrix v' m n lda\n\n-- | @accum f@ takes a matrix and an association list and accumulates\n-- pairs from the list into the matrix with the accumulating function @f@.\naccum :: (Storable e)\n => (e -> e' -> e) \n -> Matrix e\n -> [((Int,Int), e')]\n -> Matrix e\naccum f (Matrix v m n lda) ijes = let\n ies = [ if i < 0 || i >= m || j < 0 || j >= n\n then error $ printf\n (\"accum\"\n ++ \" \"\n ++ \" [ ..((%d,%d),_).. ]\"\n ++ \": invalid index\")\n m n i j\n else (i + j * lda, e)\n | ((i,j),e) <- ijes\n ]\n v' = V.unsafeAccum f v ies\n in Matrix v' m n lda\n\n-- | Construct a new matrix by applying a function to every element of\n-- a matrix.\nmap :: (Storable e, Storable e')\n => (e -> e')\n -> Matrix e\n -> Matrix e'\nmap f a = fromList (dim a) $ P.map f (elems a)\n{-# INLINE map #-}\n\n-- | Construct a new matrix by applying a function to every pair of elements\n-- of two matrices. The two matrices must have identical dimensions.\nzipWith :: (Storable e, Storable e', Storable f)\n => (e -> e' -> f)\n -> Matrix e\n -> Matrix e'\n -> Matrix f\nzipWith f a a'\n | mn /= mn' = error $\n printf (\"zipWith\"\n ++ \" \"\n ++ \" \"\n ++ \": dimension mismatch\"\n ) (show mn) (show mn')\n | otherwise =\n unsafeZipWith f a a'\n where\n mn = dim a\n mn' = dim a' \n{-# INLINE zipWith #-}\n\n-- | Version of 'zipWith' that does not check if the input matrices\n-- have the same dimensions.\nunsafeZipWith :: (Storable e, Storable e', Storable f)\n => (e -> e' -> f)\n -> Matrix e\n -> Matrix e'\n -> Matrix f\nunsafeZipWith f a a' =\n fromList (dim a') $ P.zipWith f (elems a) (elems a')\n{-# INLINE unsafeZipWith #-}\n\n-- | Get the given column of the matrix.\ncol :: (Storable e) => Matrix e -> Int -> Vector e\ncol a j\n | j < 0 || j >= n = error $\n printf (\"col %d:\"\n ++ \" index out of range\") m n j\n | otherwise =\n unsafeCol a j\n where\n (m,n) = dim a\n{-# INLINE col #-}\n\n-- | Version of 'col' that doesn't range-check indices.\nunsafeCol :: (Storable e) => Matrix e -> Int -> Vector e\nunsafeCol (Matrix v m _ lda) j = \n V.unsafeSlice (j*lda) m v\n{-# INLINE unsafeCol #-}\n\n-- | Get a list of the columns of the matrix.\ncols :: (Storable e) => Matrix e -> [Vector e]\ncols a = P.map (unsafeCol a) [ 0..n-1 ]\n where\n (_,n) = dim a\n{-# INLINE cols #-}\n\n-- | @slice (i,j) (m,n) a@ creates a submatrix view of @a@ starting at\n-- element @(i,j)@ and having dimensions @(m,n)@.\nslice :: (Storable e)\n => (Int,Int)\n -> (Int,Int)\n -> Matrix e\n -> Matrix e\nslice (i,j) (m',n') a\n | (i < 0 || m' < 0 || i + m' > m \n || j < 0 || n' < 0 || j + n' > n) = error $\n printf ( \"slice\"\n ++ \" (%d,%d)\"\n ++ \" (%d,%d)\"\n ++ \" \"\n ++ \": index out of range\"\n ) i j m' n' m n\n | otherwise =\n unsafeSlice (i,j) (m',n') a\n where\n (m,n) = dim a\n{-# INLINE slice #-}\n\n-- | Version of 'slice' that doesn't range-check indices.\nunsafeSlice :: (Storable e)\n => (Int,Int) -> (Int,Int) -> Matrix e -> Matrix e\nunsafeSlice (i,j) (m',n') (Matrix v _ _ lda) = let\n o = i + j*lda\n l = if m' == 0\n then 0\n else lda * n'\n v' = V.unsafeSlice o l v\n in Matrix v' m' n' lda\n{-# INLINE unsafeSlice #-}\n\n-- | Create a view of a matrix by taking the initial rows.\ntakeRows :: (Storable e) => Int -> Matrix e -> Matrix e\ntakeRows i a = slice (0,0) (i,n) a\n where\n (_,n) = dim a\n\n-- | Create a view of a matrix by dropping the initial rows.\ndropRows :: (Storable e) => Int -> Matrix e -> Matrix e\ndropRows i a = slice (i,0) (m-i,n) a\n where\n (m,n) = dim a\n\n-- | Split a matrix into two blocks and returns views into the blocks. If\n-- @(a1, a2) = splitRowsAt i a@, then\n-- @a1 = slice (0,0) (i,n) a@ and\n-- @a2 = slice (i,0) (m-i,n) a@, where @(m,n)@ is the dimension of @a@.\nsplitRowsAt :: (Storable e) => Int -> Matrix e -> (Matrix e, Matrix e)\nsplitRowsAt i a\n | i < 0 || i > m = error $\n printf (\"splitRowsAt %d :\"\n ++ \" invalid index\") i m n\n | otherwise = let\n a1 = unsafeSlice (0,0) (i,n) a\n a2 = unsafeSlice (i,0) (m-i,n) a\n in (a1,a2)\n where\n (m,n) = dim a\n{-# INLINE splitRowsAt #-}\n\n-- | Create a view of a matrix by taking the initial columns.\ntakeCols :: (Storable e) => Int -> Matrix e -> Matrix e\ntakeCols j a = slice (0,0) (m,j) a\n where\n (m,_) = dim a\n\n-- | Create a view of a matrix by dropping the initial columns.\ndropCols :: (Storable e) => Int -> Matrix e -> Matrix e\ndropCols j a = slice (0,j) (m,n-j) a\n where\n (m,n) = dim a\n\n-- | Split a matrix into two blocks and returns views into the blocks. If\n-- @(a1, a2) = splitColsAt j a@, then\n-- @a1 = slice (0,0) (m,j) a@ and\n-- @a2 = slice (0,j) (m,n-j) a@, where @(m,n)@ is the dimension of @a@.\nsplitColsAt :: (Storable e) => Int -> Matrix e -> (Matrix e, Matrix e)\nsplitColsAt j a\n | j < 0 || j > n = error $\n printf (\"splitColsAt %d :\"\n ++ \" invalid index\") j m n\n | otherwise = let\n a1 = unsafeSlice (0,0) (m,j) a\n a2 = unsafeSlice (0,j) (m,n-j) a\n in (a1,a2)\n where\n (m,n) = dim a\n{-# INLINE splitColsAt #-}\n\n\n-- | Convert a matrix to a vector by stacking its columns.\ntoVector :: (Storable e)\n => Matrix e\n -> Vector e\ntoVector a@(Matrix v m n _lda)\n | isContig a = v\n | otherwise = V.fromList (m*n) $ elems a\n\n-- | Cast a vector to a matrix of the given shape.\nfromVector :: (Storable e)\n => (Int,Int)\n -> Vector e\n -> Matrix e\nfromVector (m,n) v\n | nv /= m * n = error $\n printf (\"fromVector\"\n ++ \" (%d,%d)\"\n ++ \" \"\n ++ \": dimension mismatch\"\n ) m n nv\n | otherwise =\n Matrix v m n (max 1 m)\n where\n nv = V.dim v\n{-# INLINE fromVector #-}\n\n-- | Cast a vector to a matrix with one column.\nfromCol :: (Storable e)\n => Vector e\n -> Matrix e\nfromCol v = Matrix v m 1 (max 1 m)\n where\n m = V.dim v\n\n-- | Cast a vector to a matrix with one row.\nfromRow :: (Storable e)\n => Vector e\n -> Matrix e\nfromRow v = Matrix v 1 n 1\n where\n n = V.dim v\n\ninstance (Storable e, Show e) => Show (Matrix e) where\n show x = \"fromList \" ++ show (dim x) ++ \" \" ++ show (elems x)\n {-# INLINE show #-}\n\ninstance (Storable e, Eq e) => Eq (Matrix e) where\n (==) = compareWith (==)\n {-# INLINE (==) #-}\n\ninstance (Storable e, AEq e) => AEq (Matrix e) where\n (===) = compareWith (===)\n {-# INLINE (===) #-}\n (~==) = compareWith (~==)\n {-# INLINE (~==) #-}\n\ncompareWith :: (Storable e, Storable e')\n => (e -> e' -> Bool)\n -> Matrix e\n -> Matrix e'\n -> Bool\ncompareWith cmp a a' =\n dim a == dim a'\n && and (P.zipWith cmp (elems a) (elems a'))\n{-# INLINE compareWith #-}\n\n-- | Create a matrix from a 'ForeignPtr' with offset, dimensions, and lda. The\n-- data may not be modified through the ForeignPtr afterwards.\nunsafeFromForeignPtr :: (Storable e)\n => ForeignPtr e -- ^ pointer\n -> Int\t -- ^ offset\n -> (Int,Int) -- ^ dimensions\n -> Int -- ^ leading dimension (lda)\n -> Matrix e\nunsafeFromForeignPtr p o (m,n) lda = let\n nv = if m == 0 then 0 else n * lda\n v = V.unsafeFromForeignPtr p o nv\n in Matrix v m n lda\n{-# INLINE unsafeFromForeignPtr #-}\n\n-- | Yield the underlying 'ForeignPtr' together with the offset to the data\n-- the matrix dimensions, and the lda. The data may not be modified through\n-- the 'ForeignPtr'.\nunsafeToForeignPtr :: (Storable e)\n => Matrix e\n -> (ForeignPtr e, Int, (Int,Int), Int)\nunsafeToForeignPtr (Matrix v m n lda) = let\n (f,o,_) = V.unsafeToForeignPtr v\n in (f, o, (m,n), lda)\n{-# INLINE unsafeToForeignPtr #-}\n\n-- | Execute an 'IO' action with a pointer to the first element in the\n-- matrix and the leading dimension (lda).\nunsafeWith :: (Storable e) => Matrix e -> (Ptr e -> Int -> IO a) -> IO a\nunsafeWith (Matrix v _ _ lda) f =\n V.unsafeWith v $ \\p -> f p lda\n{-# INLINE unsafeWith #-}\n", "meta": {"hexsha": "0fe67a59ee460b5e206c331ab65e2f9313b64a9c", "size": 14332, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Base.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Base.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Base.hs", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 29.7962577963, "max_line_length": 78, "alphanum_fraction": 0.5274909294, "num_tokens": 4275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5995728019848882}} {"text": "module Main where\n\nimport Criterion.Main\n\nimport Control.Monad\nimport Data.IORef\nimport Data.Random\nimport Data.Random.Distribution.Uniform\nimport Data.Vector (Vector, fromList)\nimport System.Random.MWC (GenIO, uniformVector, createSystemRandom, create)\nimport qualified System.Random.MWC as MWC\nimport Statistics.Sample (mean)\n\nimport Data.Random.Source.PureMT (newPureMT)\nimport Data.Random.Source.DevRandom\n\n\n\nk = 10000\n\nrandomListFu :: RVar (Vector Double)\nrandomListFu = fromList <$> replicateM k stdUniform\n\nrandomListMWC :: GenIO -> IO (Vector Double)\nrandomListMWC gen = fromList <$> replicateM k (MWC.uniform gen)\n\nmain :: IO ()\nmain = do\n mwc <- createSystemRandom\n puremt <- newPureMT >>= newIORef\n\n defaultMain\n [ bgroup \"MWC vs randomu-fu abstraction\"\n [ bench \"random-fu\"\n $ nfIO (mean <$> sampleFrom mwc randomListFu)\n , bench \"mw'\"\n $ nfIO (mean <$> randomListMWC mwc)\n ]\n , bgroup \"Different sources\"\n [ bench \"pureMT\"\n $ nfIO (mean <$> sampleFrom puremt randomListFu)\n , bench \"std\"\n $ nfIO (mean <$> sample randomListFu)\n , bench \"urandom\"\n $ nfIO (mean <$> sampleFrom DevURandom randomListFu)\n ]\n ]\n", "meta": {"hexsha": "620d031cf5bd18734614dea2adb85ffa0deacdfd", "size": 1201, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/benchmark.hs", "max_stars_repo_name": "ttylec/ft14", "max_stars_repo_head_hexsha": "ced663be432d6bb10e96484cdde01212204c4429", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-11-08T21:13:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-10T15:56:47.000Z", "max_issues_repo_path": "examples/benchmark.hs", "max_issues_repo_name": "ttylec/ft14", "max_issues_repo_head_hexsha": "ced663be432d6bb10e96484cdde01212204c4429", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/benchmark.hs", "max_forks_repo_name": "ttylec/ft14", "max_forks_repo_head_hexsha": "ced663be432d6bb10e96484cdde01212204c4429", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0208333333, "max_line_length": 75, "alphanum_fraction": 0.6869275604, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5995728019578574}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n-----------------------------------------------------------------------------\n-- |\n-- License : BSD-style (see the file LICENSE)\n-- Maintainer : Edward Kmett \n-- Stability : provisional\n-- Portability : portable\n--\n-----------------------------------------------------------------------------\nmodule Linear.Algebra\n ( Algebra(..)\n , Coalgebra(..)\n , multRep, unitalRep\n , comultRep, counitalRep\n ) where\n\nimport Control.Lens hiding (index)\nimport Data.Functor.Rep\nimport Data.Complex\nimport Data.Void\nimport Linear.Vector\nimport Linear.Quaternion\nimport Linear.Conjugate\nimport Linear.V0\nimport Linear.V1\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\n\n-- | An associative unital algebra over a ring\nclass Num r => Algebra r m where\n mult :: (m -> m -> r) -> m -> r\n unital :: r -> m -> r\n\nmultRep :: (Representable f, Algebra r (Rep f)) => f (f r) -> f r\nmultRep ffr = tabulate $ mult (index . index ffr)\n\nunitalRep :: (Representable f, Algebra r (Rep f)) => r -> f r\nunitalRep = tabulate . unital\n\ninstance Num r => Algebra r Void where\n mult _ _ = 0\n unital _ _ = 0\n\ninstance Num r => Algebra r (E V0) where\n mult _ _ = 0\n unital _ _ = 0\n\ninstance Num r => Algebra r (E V1) where\n mult f _ = f ex ex\n unital r _ = r\n\ninstance Num r => Algebra r () where\n mult f () = f () ()\n unital r () = r\n\ninstance (Algebra r a, Algebra r b) => Algebra r (a, b) where\n mult f (a,b) = mult (\\a1 a2 -> mult (\\b1 b2 -> f (a1,b1) (a2,b2)) b) a\n unital r (a,b) = unital r a * unital r b\n\ninstance Num r => Algebra r (E Complex) where\n mult f = \\ i -> c^.el i where\n c = (f ee ee - f ei ei) :+ (f ee ei + f ei ee)\n unital r i = (r :+ 0)^.el i\n\ninstance (Num r, TrivialConjugate r) => Algebra r (E Quaternion) where\n mult f = index $ Quaternion\n (f ee ee - (f ei ei + f ej ej + f ek ek))\n (V3 (f ee ei + f ei ee + f ej ek - f ek ej)\n (f ee ej + f ej ee + f ek ei - f ei ek)\n (f ee ek + f ek ee + f ei ej - f ej ei))\n unital r = index (Quaternion r 0)\n\n-- | A coassociative counital coalgebra over a ring\nclass Num r => Coalgebra r m where\n comult :: (m -> r) -> m -> m -> r\n counital :: (m -> r) -> r\n\ncomultRep :: (Representable f, Coalgebra r (Rep f)) => f r -> f (f r)\ncomultRep fr = tabulate $ \\i -> tabulate $ \\j -> comult (index fr) i j\n\ncounitalRep :: (Representable f, Coalgebra r (Rep f)) => f r -> r\ncounitalRep = counital . index\n\ninstance Num r => Coalgebra r Void where\n comult _ _ _ = 0\n counital _ = 0\n\ninstance Num r => Coalgebra r () where\n comult f () () = f ()\n counital f = f ()\n\ninstance Num r => Coalgebra r (E V0) where\n comult _ _ _ = 0\n counital _ = 0\n\ninstance Num r => Coalgebra r (E V1) where\n comult f _ _ = f ex\n counital f = f ex\n\ninstance Num r => Coalgebra r (E V2) where\n comult f = index . index v where\n v = V2 (V2 (f ex) 0) (V2 0 (f ey))\n counital f = f ex + f ey\n\ninstance Num r => Coalgebra r (E V3) where\n comult f = index . index q where\n q = V3 (V3 (f ex) 0 0)\n (V3 0 (f ey) 0)\n (V3 0 0 (f ez))\n counital f = f ex + f ey + f ez\n\ninstance Num r => Coalgebra r (E V4) where\n comult f = index . index v where\n v = V4 (V4 (f ex) 0 0 0) (V4 0 (f ey) 0 0) (V4 0 0 (f ez) 0) (V4 0 0 0 (f ew))\n counital f = f ex + f ey + f ez + f ew\n\ninstance Num r => Coalgebra r (E Complex) where\n comult f = \\i j -> c^.el i.el j where\n c = (f ee :+ 0) :+ (0 :+ f ei)\n counital f = f ee + f ei\n\ninstance (Num r, TrivialConjugate r) => Coalgebra r (E Quaternion) where\n comult f = index . index\n (Quaternion (Quaternion (f ee) (V3 0 0 0))\n (V3 (Quaternion 0 (V3 (f ei) 0 0))\n (Quaternion 0 (V3 0 (f ej) 0))\n (Quaternion 0 (V3 0 0 (f ek)))))\n counital f = f ee + f ei + f ej + f ek\n\ninstance (Coalgebra r m, Coalgebra r n) => Coalgebra r (m, n) where\n comult f (a1, b1) (a2, b2) = comult (\\a -> comult (\\b -> f (a, b)) b1 b2) a1 a2\n counital k = counital $ \\a -> counital $ \\b -> k (a,b)\n", "meta": {"hexsha": "cd15d05818e3e3343b44e1fc95ea9fefeb985ac4", "size": 4092, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Linear/Algebra.hs", "max_stars_repo_name": "ekmett/linear", "max_stars_repo_head_hexsha": "d05577d0a60f6090a343e2adfa0e70a59b9c995c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 162, "max_stars_repo_stars_event_min_datetime": "2015-01-31T10:50:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T19:48:43.000Z", "max_issues_repo_path": "src/Linear/Algebra.hs", "max_issues_repo_name": "ekmett/linear", "max_issues_repo_head_hexsha": "d05577d0a60f6090a343e2adfa0e70a59b9c995c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 94, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T12:52:34.000Z", "max_forks_repo_path": "src/Linear/Algebra.hs", "max_forks_repo_name": "ekmett/linear", "max_forks_repo_head_hexsha": "d05577d0a60f6090a343e2adfa0e70a59b9c995c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2015-01-02T10:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T23:59:32.000Z", "avg_line_length": 29.8686131387, "max_line_length": 82, "alphanum_fraction": 0.568914956, "num_tokens": 1433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5995727851228685}} {"text": "{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n\nmodule Interpreter where\n\nimport Data.Array as A\nimport Data.Complex as DC\nimport qualified Data.IntMap.Strict as IM\nimport Data.Map (Map, fromList)\nimport qualified Data.Map as Map\nimport Expression\nimport Utils\n\ntype family Output d rc where\n Output Scalar R = Double\n Output Scalar C = DC.Complex Double\n Output One R = Array Int Double\n Output One C = Array Int (DC.Complex Double)\n\n-- |\n--\ndata ValMaps =\n ValMaps\n { vm0 :: Map String Double\n , vm1 :: Map String (Array Int Double)\n }\n deriving (Eq, Show, Ord)\n\nsubs :: [(String, Double)] -> [(String, Array Int Double)] -> ValMaps\nsubs vm0 vm1 = ValMaps (fromList vm0) (fromList vm1)\n\n-- |\n--\nclass Evaluable d rc where\n eval :: ValMaps -> Expression d rc -> Output d rc\n\n-- |\n--\ninstance Evaluable Scalar R where\n eval :: ValMaps -> Expression Scalar R -> Double\n eval valMap e@(Expression n mp) =\n case IM.lookup n mp of\n Just ([], Var name) ->\n case Map.lookup name $ vm0 valMap of\n Just val -> val\n _ -> error \"no value associated with the variable\"\n Just ([], Sum Real [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression Scalar R\n subExp2 = Expression node2 mp :: Expression Scalar R\n in eval valMap subExp1 + eval valMap subExp2\n Just ([], Mul Real [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression Scalar R\n subExp2 = Expression node2 mp :: Expression Scalar R\n in eval valMap subExp1 * eval valMap subExp2\n Just ([], Scale Real [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression Scalar R\n subExp2 = Expression node2 mp :: Expression Scalar R\n in eval valMap subExp1 * eval valMap subExp2\n Just ([], InnerProd Real [node1, node2]) ->\n case IM.lookup node1 mp of\n Just ([], _) ->\n let subExp1 = Expression node1 mp :: Expression Scalar R -- shape is [], so must be Scalar R\n subExp2 = Expression node2 mp :: Expression Scalar R -- shape is [], so must be Scalar R\n in eval valMap subExp1 * eval valMap subExp2\n Just ([size], _) ->\n let subExp1 = Expression node1 mp :: Expression One R -- shape is [size], so must be One R\n subExp2 = Expression node2 mp :: Expression One R -- shape is [size], so must be One R\n lst1 = A.elems $ eval valMap subExp1\n lst2 = A.elems $ eval valMap subExp2\n in sum $ zipWith (*) lst1 lst2\n _ -> error \"expression structure Scalar R is wrong\"\n\n-- |\n--\ninstance Evaluable Scalar C where\n eval :: ValMaps -> Expression Scalar C -> DC.Complex Double\n eval valMap e@(Expression n mp) =\n case IM.lookup n mp of\n Just ([], Sum Complex [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression Scalar C\n subExp2 = Expression node2 mp :: Expression Scalar C\n in eval valMap subExp1 + eval valMap subExp2\n Just ([], Mul Complex [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression Scalar C\n subExp2 = Expression node2 mp :: Expression Scalar C\n in eval valMap subExp1 * eval valMap subExp2\n Just ([], Scale Complex [node1, node2]) ->\n let subExp2 = Expression node2 mp :: Expression Scalar C\n scale =\n case nodeNumType . retrieveNode mp $ node1 of\n Real ->\n fromReal . eval valMap $\n (Expression node1 mp :: Expression Scalar R)\n Complex ->\n eval\n valMap\n (Expression node1 mp :: Expression Scalar C)\n in scale * eval valMap subExp2\n Just ([], RealImg [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression Scalar R\n subExp2 = Expression node2 mp :: Expression Scalar R\n in eval valMap subExp1 :+ eval valMap subExp2\n Just ([], InnerProd Complex [node1, node2]) ->\n case IM.lookup node1 mp of\n Just ([], _) ->\n let subExp1 = Expression node1 mp :: Expression Scalar C -- shape is [], so must be Scalar C\n subExp2 = Expression node2 mp :: Expression Scalar C -- shape is [], so must be Scalar C\n in eval valMap subExp1 * eval valMap subExp2\n\n Just ([size], _) ->\n let subExp1 = Expression node1 mp :: Expression One C -- shape is [size], so must be One C\n subExp2 = Expression node2 mp :: Expression One C -- shape is [size], so must be One C\n lst1 = A.elems $ eval valMap subExp1\n lst2 = A.elems $ eval valMap subExp2\n in sum $ zipWith (*) lst1 lst2\n _ -> error \"expression structure Scalar C is wrong\"\n\n-- |\n--\ninstance Evaluable One R where\n eval :: ValMaps -> Expression One R -> Array Int Double\n eval valMap e@(Expression n mp) =\n case IM.lookup n mp of\n Just ([size], Var name) ->\n case Map.lookup name $ vm1 valMap of\n Just val -> val\n _ -> error \"no value associated with the variable\"\n Just ([size], Sum Real [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression One R\n subExp2 = Expression node2 mp :: Expression One R\n lst1 = A.elems $ eval valMap subExp1\n lst2 = A.elems $ eval valMap subExp2\n lstRes = zipWith (+) lst1 lst2\n in A.listArray (0, size - 1) lstRes\n Just ([size], Mul Real [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression One R\n subExp2 = Expression node2 mp :: Expression One R\n lst1 = A.elems $ eval valMap subExp1\n lst2 = A.elems $ eval valMap subExp2\n lstRes = zipWith (*) lst1 lst2\n in A.listArray (0, size - 1) lstRes\n Just ([size], Scale Real [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression Scalar R\n subExp2 = Expression node2 mp :: Expression One R\n scale = eval valMap subExp1\n in fmap (* scale) $ eval valMap subExp2\n _ -> error \"expression structure One R is wrong\"\n\n-- |\n--\ninstance Evaluable One C where\n eval :: ValMaps -> Expression One C -> Array Int (DC.Complex Double)\n eval valMap e@(Expression n mp) =\n case IM.lookup n mp of\n Just ([size], Sum Complex [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression One C\n subExp2 = Expression node2 mp :: Expression One C\n lst1 = A.elems $ eval valMap subExp1\n lst2 = A.elems $ eval valMap subExp2\n lstRes = zipWith (+) lst1 lst2\n in A.listArray (0, size - 1) lstRes\n Just ([size], Mul Complex [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression One C\n subExp2 = Expression node2 mp :: Expression One C\n lst1 = A.elems $ eval valMap subExp1\n lst2 = A.elems $ eval valMap subExp2\n lstRes = zipWith (*) lst1 lst2\n in A.listArray (0, size - 1) lstRes\n Just ([size], Scale Complex [node1, node2]) ->\n let subExp2 = Expression node2 mp :: Expression One C\n lst = A.elems $ eval valMap subExp2\n scale =\n case nodeNumType . retrieveNode mp $ node1 of\n Real ->\n fromReal . eval valMap $\n (Expression node1 mp :: Expression Scalar R)\n Complex ->\n eval\n valMap\n (Expression node1 mp :: Expression Scalar C)\n in A.listArray (0, size - 1) $ map (* scale) lst\n Just ([size], RealImg [node1, node2]) ->\n let subExp1 = Expression node1 mp :: Expression One R\n subExp2 = Expression node2 mp :: Expression One R\n lst1 = A.elems $ eval valMap subExp1\n lst2 = A.elems $ eval valMap subExp2\n lstRes = zipWith (:+) lst1 lst2\n in A.listArray (0, size - 1) lstRes\n _ -> error \"expression structure One C is wrong\"\n", "meta": {"hexsha": "c0b54bbcb2ed7d1a60dd8c8aedc307724025e2fa", "size": 9325, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Interpreter.hs", "max_stars_repo_name": "dandoh/NeatExpression", "max_stars_repo_head_hexsha": "6e3ac12fea6db128f3bca6050e232fd1dc321164", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-07T02:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-07T02:38:17.000Z", "max_issues_repo_path": "src/Interpreter.hs", "max_issues_repo_name": "dandoh/NeatExpression", "max_issues_repo_head_hexsha": "6e3ac12fea6db128f3bca6050e232fd1dc321164", "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/Interpreter.hs", "max_forks_repo_name": "dandoh/NeatExpression", "max_forks_repo_head_hexsha": "6e3ac12fea6db128f3bca6050e232fd1dc321164", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.5677083333, "max_line_length": 116, "alphanum_fraction": 0.5137801609, "num_tokens": 2073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5995414779437968}} {"text": "module Phi.Window\n ( Window, mkWindow\n , length\n , push\n , phi\n ) where\n\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector.Unboxed as V\nimport Prelude hiding (length)\nimport Statistics.Distribution (complCumulative)\nimport Statistics.Distribution.Normal (normalFromSample)\n\ndata Window =\n Window\n { sample :: !(Vector Double)\n , size :: !Int\n }\n\nmkWindow :: Int -> Window\nmkWindow = Window V.empty\n\npush :: Double -> Window -> Window\npush d window = window {sample = sample'}\n where sample' =\n V.take (size window)\n (V.cons d (sample window))\n\nphi :: Window -> Double -> Double\nphi w = negate . logBase 10 . pLater w\n where pLater :: Window -> Double -> Double\n pLater = complCumulative . normalFromSample . sample\n\nlength :: Window -> Int\nlength = V.length . sample\n", "meta": {"hexsha": "17c26dd2004406e3686c76065afeba3f4a842d2c", "size": 919, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Phi/Window.hs", "max_stars_repo_name": "reinh/hs-phi", "max_stars_repo_head_hexsha": "9b7b1833895bc2a6ac0fdb23f5f247d6c7bf7ad4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-05-23T03:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-05T01:09:30.000Z", "max_issues_repo_path": "src/Phi/Window.hs", "max_issues_repo_name": "reinh/hs-phi", "max_issues_repo_head_hexsha": "9b7b1833895bc2a6ac0fdb23f5f247d6c7bf7ad4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Phi/Window.hs", "max_forks_repo_name": "reinh/hs-phi", "max_forks_repo_head_hexsha": "9b7b1833895bc2a6ac0fdb23f5f247d6c7bf7ad4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5277777778, "max_line_length": 66, "alphanum_fraction": 0.6039173014, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5989426076916093}} {"text": "{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TypeOperators #-}\nmodule GenerateInParallel where\n\n\nimport Data.Complex\nimport Control.Monad\nimport Codec.Picture\nimport Data.Array.Repa \nimport Data.Word\n\nimport Mand\n\n\ngenerateInParallel = do\n mapM_ (\\ x-> (computeUnboxedP $ repaMandArray x (-2) (-2) (0.0025) 1600 1600) >>= (savePngImage (\"./repatestcol\" Prelude.++ show x Prelude.++ \".png\") . ImageRGB8 . toImage) ) [2..3]\n\n\n --img <- computeUnboxedP $ repaMandArray (-2) (-2) (0.0005) 8000 8000\n --(savePngImage \"./repatest1.png\" . ImageRGB8 . toImage) img\n\n\nrepaMandArray :: Int -> Double -> Double -> Double -> Int -> Int -> Array D DIM2 Word16\nrepaMandArray pow start_re start_im step width height = fromFunction (Z :. width :. height) (arrayToMand pow start_re start_im step)\n\narrayToMand :: Int -> Double -> Double -> Double -> Z :. Int :. Int -> Word16\narrayToMand pow start_re start_im step (Z :. x :. y) = fromIntegral $ general (mand_pow_iteration pow) Nothing ((start_re + (fromIntegral x) * step ) :+(start_im + step * (fromIntegral y) ) ) 32767\n\n\ntoImage :: Array U DIM2 Word16 -> Image PixelRGB8\ntoImage a = generateImage gen width height\n where\n Z :. width :. height = extent a\n gen x y =\n let d = a ! (Z :. x :. y)\n in PixelRGB8 (fromIntegral $ 2 * mod d 128) (fromIntegral $ 2* mod (div d 128) 128) ( fromIntegral $ 2 * div d 16384) \n", "meta": {"hexsha": "c2d92ee2471fd354a5ec513ea9da59228326d276", "size": 1377, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "source/GenerateInParallel.hs", "max_stars_repo_name": "AlwinHughes/fractal", "max_stars_repo_head_hexsha": "dc99dbf9444e2a5583d5c51f29417592426c5ff4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/GenerateInParallel.hs", "max_issues_repo_name": "AlwinHughes/fractal", "max_issues_repo_head_hexsha": "dc99dbf9444e2a5583d5c51f29417592426c5ff4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/GenerateInParallel.hs", "max_forks_repo_name": "AlwinHughes/fractal", "max_forks_repo_head_hexsha": "dc99dbf9444e2a5583d5c51f29417592426c5ff4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2162162162, "max_line_length": 198, "alphanum_fraction": 0.6710239651, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.7025300449389327, "lm_q1q2_score": 0.5985224428934178}} {"text": "module Mandelbrot where\n\nimport Data.Complex\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport Data.Function (on)\nimport Data.List (partition)\n--import Data.Ratio\n\nc = 0 :+ 0\nman :: RealFloat a => Complex a -> Complex a -> Complex a\nman c z = z*z + c\n\npixelSize\n\t:: (Int, Int)\n\t-> Double\n\t-> Double\n\t-> (Int, Int)\npixelSize maxSize w h =\n\tif (w/h) < (divInt mw mh)\n\t\tthen (ceiling $ (fromIntegral mh)*w/h , mh)\n\t\telse (mw , ceiling $ (fromIntegral mw)*h/w)\n\twhere\n\t\t(mw, mh) = maxSize\n\n-- size = (px,py)\npoints\n\t:: (Int, Int)\n\t-> (Double, Double, Double, Double)\n\t-> ([((Int, Int), (Complex Double, Complex Double))], Int)\npoints size bounds =\n\t([\n\t\t(\n\t\t\t(x,(y+offset)) ,\n\t\t\t(\\z -> (z,z))\n\t\t\t(\n\t\t\t\t( w * (divInt x (px-1)) + lB)\n\t\t\t\t:+\n\t\t\t\t(-h * (divInt y (py-1)) + uB)\n\t\t\t)\n\t\t)\n\t\t| y <- ys , x <- [0..(px-1)]\n\t], py) where\n\t\tys = [0..(py-1)]\n\t\trys = reverse ys\n\t\t(l, r, u, d) = bounds\n\t\t(lB, rB, uB, dB, offset) =\n\t\t\tif (u > 0.0) && (d < 0.0)\n\t\t\t\tthen\n\t\t\t\t\tif u > -d\n\t\t\t\t\t\tthen (l, r, u, 0, 0)\n\t\t\t\t\t\telse (l, r, 0, d, ((snd size) - py))\n\t\t\t\telse (l,r,u,d,0)\n\t\t(w, h) = (rB - lB, uB - dB)\n\t\t(px,py) = pixelSize size w h\n\ndivInt = (/) `on` fromIntegral\n\n\n\nreduce = partition (\\(x,(c,z)) -> magnitude z <= 2)\napply = map (\\(x,(c,z)) -> (x,(c, man c z)))\n\n", "meta": {"hexsha": "7d923dc4eb291c899843446edd0910d7adf9a016", "size": 1264, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Mandelbrot.hs", "max_stars_repo_name": "dorobouNeko/haskell-mandelbrot", "max_stars_repo_head_hexsha": "a656c0669ccf603e44bf9231a546320b41c8baef", "max_stars_repo_licenses": ["WTFPL"], "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/Mandelbrot.hs", "max_issues_repo_name": "dorobouNeko/haskell-mandelbrot", "max_issues_repo_head_hexsha": "a656c0669ccf603e44bf9231a546320b41c8baef", "max_issues_repo_licenses": ["WTFPL"], "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/Mandelbrot.hs", "max_forks_repo_name": "dorobouNeko/haskell-mandelbrot", "max_forks_repo_head_hexsha": "a656c0669ccf603e44bf9231a546320b41c8baef", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.75, "max_line_length": 59, "alphanum_fraction": 0.5237341772, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5985224296895624}} {"text": "module Strategy.RandomWalkMetropolis where\n\nimport Math.Probably.Sampler\nimport Math.Probably.MCMC\nimport Numeric.LinearAlgebra\nimport Control.Monad\nimport Data.Maybe\n\n\nrwm = VStrategy rwmTrans rwmIni\n\nrwmTrans posterior xi (sigma,(i, iaccept)) mpi = do\n let pi = fromMaybe (posterior xi) mpi\n xstar <- fmap fromList $ mapM (\\x -> normal x sigma) $ toList xi\n let pstar = posterior xstar\n let ratio = exp $ pstar - pi\n u <- unit\n let accept = u < ratio\n\n --diminishing adaptation:\n let sigmaNext = if accept then sigma*(min 1.4 $ 1+5.0/i)^3 \n else sigma*(max 0.7143 $ 1-5.0/i)\n\n return $ if accept \n then ((xstar, (sigmaNext, (i+1, iaccept+1))), Just pstar)\n else ((xi, (sigmaNext, (i+1, iaccept))), Just pi) \n \n\nrwmIni _ = (0.1,(1.0, 0.0))\n\n", "meta": {"hexsha": "808b5bb4f5b674cce0a8f2aea3844c3f72b95ace", "size": 819, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Strategy/RandomWalkMetropolis.hs", "max_stars_repo_name": "glutamate/probably-baysig", "max_stars_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-02-12T05:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:37.000Z", "max_issues_repo_path": "src/Strategy/RandomWalkMetropolis.hs", "max_issues_repo_name": "silky/probably-baysig", "max_issues_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Strategy/RandomWalkMetropolis.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 26.4193548387, "max_line_length": 72, "alphanum_fraction": 0.6263736264, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5985069973749758}} {"text": "{-|\nModule : PRNG\nDescription : Class definitions of PRNG api\n\nCopyright : Thodoris Papakonstantinou, 2017\nLicense : GPL-3\nMaintainer : mail@tpapak.com\nStability : experimental\nPortability : POSIX\n\nDeterministic (Pure) Pseudo Random Number Generator Class definitions.\n -}\n\nmodule Data.PRNG\n ( Seed\n , RNG (..)\n , randomBools\n , randomInts\n , randomPermutation\n , sample\n , normalSample\n , truncatedNormalSample\n ) where\n\nimport Data.Maybe\nimport Data.List\nimport qualified Data.Vector as V\nimport qualified Data.Set as S\nimport qualified Data.IntMap as IM\nimport Data.Number.Erf\nimport qualified Numeric.SpecFunctions as NS\n\n\ntype Seed = Int\nclass RNG r where \n getRNG :: Seed -> r\n randomDouble :: r -> (Double, r)\n randomInt :: r -> (Int, r)\n uniformSample :: r -> Int -> [Double]\n\n\n-- | booleans given the length of the list the probability p and the seed\nrandomBools :: RNG r => r -> Int -> Double -> [Bool]\nrandomBools r l p =\n let rndbls 0 _ = []\n rndbls n g = b:(rndbls (n-1) g')\n where (d,g') = randomDouble g\n b = d > p\n in rndbls l r\n\n-- | booleans given the length of the list the probability p and the seed\nrandomInts :: RNG r => r -> Int -> [Int]\nrandomInts r l =\n let rnds 0 _ = []\n rnds n g = i:(rnds (n-1) g')\n where (i,g') = randomInt g\n in rnds l r\n\n-- | Permutates list using a RNG, given that the list has fewer elements than\n-- the minimum between 2^64 which is the precision of Double and the period of the prng,the position probability of every element is uniform.\nrandomPermutation :: RNG r => r -> [a] -> [a]\nrandomPermutation r ls = \n let randoms = zip (uniformSample r (length ls)) ls\n in map snd $ sortOn fst randoms\n\n-- | Sample from list \nsample :: RNG r => r -> Int -> [a] -> [a]\nsample r k c\n | k < 0 || k > length c = []\n | otherwise = take k $ randomPermutation r c\n \n-- | List of doubles from nornal distribution given \n-- RNG -> \u03bc -> \u03c3 -> length of list\nnormalSample :: RNG r => r -> Double -> Double -> Int -> [Double]\nnormalSample r \u03bc \u03c3 n \n | \u03c3 == 0 = replicate n \u03bc\n | otherwise =\n let uds = uniformSample r n\n invx x = \u03c3 * x + \u03bc\n in map (invx . invnormcdf) uds\n\n-- | Sample truncated nomral \u03bc -> \u03c3 -> left bound -> right bound -> length of list\ntruncatedNormalSample :: RNG r => r -> Double -> Double -> Double -> Double -> Int -> [Double]\ntruncatedNormalSample r \u03bc \u03c3 f t n\n | (\u03bc < f) || (\u03bc > t) = []\n | \u03c3 == 0 = replicate n \u03bc\n | otherwise =\n let uds = uniformSample r n\n sqt = sqrt 2\n invtruncnormcdf y = \u03bc - sqt * \u03c3 * inverf (\n - ((-1) + y) * erf((-f + \u03bc)/(sqt * \u03c3)) +\n y * erf((\u03bc - t)/(sqt * \u03c3))\n )\n in map invtruncnormcdf uds\n\n\n-- | List of doubles from the binomial distribution given \n-- RNG -> n -> p -> length of list\nbinomialSample :: RNG r => r -> Int -> Double -> Int -> [Int]\nbinomialSample r n p l =\n let uds = uniformSample r l\n invbinomcdf a n p = let sumpr i = foldl (\\ac i -> ac + (binomialProb i n p)) 0 [1..i] \n binomialProb i n p = n `NS.choose` i * p^^i * (1-p)^^(n-i)\n firstBigger x a \n | sumpr (x-1) > a = x\n | x > n = n\n | otherwise = firstBigger (x+1) a\n in firstBigger 1 a\n in map (\\a -> invbinomcdf a n p) uds\n", "meta": {"hexsha": "1fe4c1019f3fa86067c08241986916849e357490", "size": 3489, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/PRNG.hs", "max_stars_repo_name": "tosku/prng", "max_stars_repo_head_hexsha": "09e29fd445c7d51c11eb73b806b98fb74acb2be7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/PRNG.hs", "max_issues_repo_name": "tosku/prng", "max_issues_repo_head_hexsha": "09e29fd445c7d51c11eb73b806b98fb74acb2be7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/PRNG.hs", "max_forks_repo_name": "tosku/prng", "max_forks_repo_head_hexsha": "09e29fd445c7d51c11eb73b806b98fb74acb2be7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7181818182, "max_line_length": 142, "alphanum_fraction": 0.5700773861, "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5984577087909051}} {"text": "{-# LANGUAGE\n MultiWayIf,\n FlexibleInstances,\n NumDecimals #-}\n\nmodule Jac where\n\nimport Data.Matrix (Matrix(..), fromLists, fromList, toList)\nimport Data.Complex\n\nimport Point\nimport Data (F)\n\ntype FPD = Point -> Double\n\n\n-----------------------------------------------------------------\n-- \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u0430\u044f.\ndiff :: (Floating a, Eq a) => F a -> a -> a\ndiff f x = (f (x - d/2) - f (x + d/2))/d\n where\n d = if\n | x == 0 -> 1e-9\n | otherwise -> x*1e-5\n\n\n-- \u044f\u043a\u043e\u0431\u0438\u0430\u043d.\njac :: F Point -> Point -> Matrix Double\njac f p@(Point x' y') = fromLists [\n [diff (\\a -> f1 p{x = a}) x', diff (\\a -> f1 p{y = a}) y'],\n [diff (\\a -> f2 p{x = a}) x', diff (\\a -> f2 p{y = a}) y']]\n where\n f1 = x.f ; f2 = y.f\n\njac' :: F Point -> Point -> Double\njac' f p@(Point x' y') = log $ abs $\n diff (\\a -> f1 p{x = a}) x'*diff (\\a -> f2 p{y = a}) y'\n - diff (\\a -> f1 p{y = a}) y'*diff (\\a -> f2 p{x = a}) x'\n where\n f1 = x.f ; f2 = y.f\n\n\n\n-- \u0435\u0434\u0438\u043d\u0438\u0447\u043d\u044b\u0439 \u0432\u0435\u043a\u0442\u043e\u0440.\ne :: Double -> Matrix Double\ne f = fromList 2 1 [realPart x, imagPart x]\n where x = cis f\n\n-- \u0441\u043c. \u0441\u0442\u0440. 102. \u0432 \u043a\u043d\u0438\u0433\u0435 1.\nformA :: F Point -> Point -> Double -> Double\nformA f p k = log.abs.toList $ jac f p * e k\n where abs [x, y] = magnitude $ x :+ y\n\n-----------------------------------------------------------------\n-- \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u0432\u0435\u043a\u0442\u043e\u0440\u0430 \u0432 \u0442\u043e\u0447\u043a\u0443.\ninstance Points (Matrix Double) where\n toPoint = toPoint.toList\n fromPoint = fromList 2 1.fromPoint\n\n-----------------------------------------------------------------\n-- \u0421\u043f\u0440\u0430\u0432\u043e\u0447\u043d\u0430\u044f \u043b\u0438\u0442\u0435\u0440\u0430\u0442\u0443\u0440\u0430 --\n-----------------------------------------------------------------\n-- 1. \u0413.\u0421. \u041e\u0441\u0438\u043f\u0435\u043d\u043a\u043e, \u041d.\u0411.\u0410\u043c\u043f\u0438\u043b\u043e\u0432\u0430:\n-- \u0412\u0412\u0415\u0414\u0415\u041d\u0418\u0415 \u0412 \u0421\u0418\u041c\u0412\u041e\u041b\u0418\u0427\u0415\u0421\u041a\u0418\u0419 \u0410\u041d\u0410\u041b\u0418\u0417 \u0414\u0418\u041d\u0410\u041c\u0418\u0427\u0415\u0421\u041a\u0418\u0425 \u0421\u0418\u0421\u0422\u0415\u041c\n", "meta": {"hexsha": "7f4314e1d2d2fc159f67bbdeab78b2be0c148d59", "size": 1733, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Jac.hs", "max_stars_repo_name": "vojiranto/dsa", "max_stars_repo_head_hexsha": "0071c1a00db6c1cfffeca6020e3a7cb22a1aeade", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Jac.hs", "max_issues_repo_name": "vojiranto/dsa", "max_issues_repo_head_hexsha": "0071c1a00db6c1cfffeca6020e3a7cb22a1aeade", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Jac.hs", "max_forks_repo_name": "vojiranto/dsa", "max_forks_repo_head_hexsha": "0071c1a00db6c1cfffeca6020e3a7cb22a1aeade", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6615384615, "max_line_length": 65, "alphanum_fraction": 0.4604731679, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765304654121, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5983619438512973}} {"text": "module Fourier where\n\nimport Data.Complex\nimport Data.Complex.Integrate\n\ncoefficient :: (RealFloat a, Integral b) => (a -> Complex a) -> b -> Complex a\ncoefficient = coefficientWithPrecision 1000\n\ncoefficientWithPrecision\n :: (RealFloat a, Integral b) => Integer -> (a -> Complex a) -> b -> Complex a\ncoefficientWithPrecision prec f n = integrate g prec 0 1\n where\n term t = f t * cis ((-2) * pi * fromIntegral n * t)\n -- \"integrate\" requires a function with a complex input, but \"term\" takes a real input\n g = term . realPart\n", "meta": {"hexsha": "a5c0578839bec46668426a279e220f1cd79b4394", "size": 551, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Fourier.hs", "max_stars_repo_name": "juliagracedefoor/fourier-visualizer", "max_stars_repo_head_hexsha": "c690aa6ebd9a32ae885e61478cd29a6aa20e889c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Fourier.hs", "max_issues_repo_name": "juliagracedefoor/fourier-visualizer", "max_issues_repo_head_hexsha": "c690aa6ebd9a32ae885e61478cd29a6aa20e889c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Fourier.hs", "max_forks_repo_name": "juliagracedefoor/fourier-visualizer", "max_forks_repo_head_hexsha": "c690aa6ebd9a32ae885e61478cd29a6aa20e889c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4375, "max_line_length": 88, "alphanum_fraction": 0.6751361162, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.598337758673967}} {"text": "{-|\nModule: MachineLearning.SoftmaxClassifier\nDescription: Softmax Classifier.\nCopyright: (c) Alexander Ignatyev, 2017-2018.\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n\nSoftmax Classifier (Multiclass Logistic Regression).\n-}\n\nmodule MachineLearning.SoftmaxClassifier\n(\n module MachineLearning.Model\n , module MachineLearning.Classification.MultiClass\n , SoftmaxClassifier(..)\n)\n\nwhere\n\nimport Prelude hiding ((<>))\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra((<>), (<.>), (|||))\nimport qualified Data.Vector.Storable as V\n\nimport qualified MachineLearning as ML\nimport MachineLearning.Types (R, Vector, Matrix)\nimport MachineLearning.Utils (reduceByRows, sumByRows)\nimport MachineLearning.Model\nimport MachineLearning.Classification.MultiClass\n\n\n-- | Softmax Classifier, takes number of classes.\ndata SoftmaxClassifier = Softmax Int\n\ninstance Classifier SoftmaxClassifier where\n cscore (Softmax _) x theta = scores - reduceByRows V.maximum scores\n where scores = x <> (LA.tr theta)\n\n chypothesis m x theta = V.fromList predictions\n where scores = cscore m x theta\n scores' = LA.toRows scores\n predictions = map (fromIntegral . LA.maxIndex) scores'\n\n ccost m lambda x y theta =\n let nSamples = fromIntegral $ LA.rows x\n scores = cscore m x theta\n sum_probs = sumByRows $ exp scores\n loss = LA.sumElements $ (log sum_probs) - remap scores y\n reg = ccostReg lambda theta\n in (loss + reg) / nSamples \n\n cgradient m lambda x y theta =\n let nSamples = fromIntegral $ LA.rows x\n ys = processOutput m y\n scores = cscore m x theta\n sum_probs = sumByRows $ exp scores\n probs = (exp scores) / sum_probs\n probs' = probs - ys\n dw = (LA.tr probs') <> x\n reg = cgradientReg lambda theta\n in (dw + reg)/ nSamples\n\n cnumClasses (Softmax nLabels) = nLabels\n\n\nremap :: Matrix -> Vector -> Matrix\nremap m v = LA.remap cols rows m\n where cols = LA.asColumn $ V.fromList [0..(fromIntegral $ LA.rows m)-1]\n rows = LA.toInt $ LA.asColumn v\n\n", "meta": {"hexsha": "be222a5a7aefb408bcf423e2027fc83c4609a0a8", "size": 2092, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/SoftmaxClassifier.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "src/MachineLearning/SoftmaxClassifier.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "src/MachineLearning/SoftmaxClassifier.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 29.0555555556, "max_line_length": 73, "alphanum_fraction": 0.7021988528, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5982848460987523}} {"text": "-- monadic computations\n-- (contributed by Vivian McPhail)\n\nimport Numeric.LinearAlgebra\nimport Control.Monad.State.Strict\nimport Control.Monad.Maybe\nimport Foreign.Storable(Storable)\nimport System.Random(randomIO)\n\n-------------------------------------------\n\n-- an instance of MonadIO, a monad transformer\ntype VectorMonadT = StateT Int IO\n\ntest1 :: Vector Int -> IO (Vector Int)\ntest1 = mapVectorM $ \\x -> do\n putStr $ (show x) ++ \" \"\n return (x + 1)\n\n-- we can have an arbitrary monad AND do IO\naddInitialM :: Vector Int -> VectorMonadT ()\naddInitialM = mapVectorM_ $ \\x -> do\n i <- get\n liftIO $ putStr $ (show $ x + i) ++ \" \"\n put $ x + i\n\n-- sum the values of the even indiced elements\nsumEvens :: Vector Int -> Int\nsumEvens = foldVectorWithIndex (\\x a b -> if x `mod` 2 == 0 then a + b else b) 0\n\n-- sum and print running total of evens\nsumEvensAndPrint :: Vector Int -> VectorMonadT ()\nsumEvensAndPrint = mapVectorWithIndexM_ $ \\ i x -> do\n when (i `mod` 2 == 0) $ do\n v <- get\n put $ v + x\n v' <- get\n liftIO $ putStr $ (show v') ++ \" \"\n\n\nindexPlusSum :: Vector Int -> VectorMonadT ()\nindexPlusSum v' = do\n let f i x = do\n s <- get\n let inc = x+s\n liftIO $ putStr $ show (i,inc) ++ \" \"\n put inc\n return inc\n v <- mapVectorWithIndexM f v'\n liftIO $ do\n putStrLn \"\"\n putStrLn $ show v\n\n-------------------------------------------\n\n-- short circuit\nmonoStep :: Double -> MaybeT (State Double) ()\nmonoStep d = do\n dp <- get\n when (d < dp) (fail \"negative difference\")\n put d\n{-# INLINE monoStep #-}\n\nisMonotoneIncreasing :: Vector Double -> Bool\nisMonotoneIncreasing v =\n let res = evalState (runMaybeT $ (mapVectorM_ monoStep v)) (v @> 0)\n in case res of\n Nothing -> False\n Just _ -> True\n\n\n-------------------------------------------\n\n-- | apply a test to successive elements of a vector, evaluates to true iff test passes for all pairs\nsuccessive_ :: Storable a => (a -> a -> Bool) -> Vector a -> Bool\nsuccessive_ t v = maybe False (\\_ -> True) $ evalState (runMaybeT (mapVectorM_ step (subVector 1 (dim v - 1) v))) (v @> 0)\n where step e = do\n ep <- lift $ get\n if t e ep\n then lift $ put e\n else (fail \"successive_ test failed\")\n\n-- | operate on successive elements of a vector and return the resulting vector, whose length 1 less than that of the input\nsuccessive :: (Storable a, Storable b) => (a -> a -> b) -> Vector a -> Vector b\nsuccessive f v = evalState (mapVectorM step (subVector 1 (dim v - 1) v)) (v @> 0)\n where step e = do\n ep <- get\n put e\n return $ f ep e\n\n-------------------------------------------\n\nv :: Vector Int\nv = 10 |> [0..]\n\nw = fromList ([1..10]++[10,9..1]) :: Vector Double\n\n\nmain = do\n v' <- test1 v\n putStrLn \"\"\n putStrLn $ show v'\n evalStateT (addInitialM v) 0\n putStrLn \"\"\n putStrLn $ show (sumEvens v)\n evalStateT (sumEvensAndPrint v) 0\n putStrLn \"\"\n evalStateT (indexPlusSum v) 0\n putStrLn \"-----------------------\"\n mapVectorM_ print v\n print =<< (mapVectorM (const randomIO) v :: IO (Vector Double))\n print =<< (mapVectorM (\\a -> fmap (+a) randomIO) (5|>[0,100..1000]) :: IO (Vector Double))\n putStrLn \"-----------------------\"\n print $ isMonotoneIncreasing w\n print $ isMonotoneIncreasing (subVector 0 7 w)\n print $ successive_ (>) v\n print $ successive_ (>) w\n print $ successive (+) v\n", "meta": {"hexsha": "7c6e0f4279f910a99d02f572b79054026591ec77", "size": 3574, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/monadic.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/examples/monadic.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/examples/monadic.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": 30.0336134454, "max_line_length": 123, "alphanum_fraction": 0.5556799105, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5982809605812391}} {"text": "module CNC.DeclarativeTests where\n\nimport CNC.Declarative\nimport CNC.Geometry(eps)\n\nimport Data.Complex\nimport Control.Monad\n\nfig1 = do [p1, p2] <- declarePoints 2\n xSize p1 p2 1\n\npoints1 = [0 :+ 0, 1 :+ 0]\n\nfig2 = do [p1, p2, p3] <- declarePoints 3\n len p1 p2 1\n xAngle p1 p2 (pi/2)\n xAngle p2 p3 (-pi/2)\n len p2 p3 1\n\npoints2 = [0 :+ 0, 0 :+ 1.0, 0 :+ 0]\n\nfig3 = do\n [p1,p2,p3,p4] <- declarePoints 4\n xSize p1 p2 1\n xAngle p2 p3 ( pi / 3)\n len p2 p3 2\n len p4 p3 2\n xAngle p3 p4 (-pi / 3)\n-- xSize p3 p4 2\n\npoints3 = [0, 1, 1 + mkPolar 2 (pi/3), 3] --1 + mkPolar 2 (- 2*pi/3) + 2]\n\ntests = [ (fig1,points1),\n (fig2, points2),\n (fig3, points3)\n ]\n\ndeclarative_tests = do mapM_ run' tests\n where run' (fig, points) = do\n let solved = figure fig\n print solved\n when (any ((> 0.1) . magnitude) $ zipWith (-) (unPath solved) points) $ fail $ \"test failed, should be \" ++ show points\n", "meta": {"hexsha": "b3823de78ac874035dad6495cbdc53902b24d000", "size": 985, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/CNC/DeclarativeTests.hs", "max_stars_repo_name": "akamaus/gcodec", "max_stars_repo_head_hexsha": "cd515673f408f24d4d92fc85246611c21a4ef433", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/CNC/DeclarativeTests.hs", "max_issues_repo_name": "akamaus/gcodec", "max_issues_repo_head_hexsha": "cd515673f408f24d4d92fc85246611c21a4ef433", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/CNC/DeclarativeTests.hs", "max_forks_repo_name": "akamaus/gcodec", "max_forks_repo_head_hexsha": "cd515673f408f24d4d92fc85246611c21a4ef433", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9069767442, "max_line_length": 129, "alphanum_fraction": 0.5593908629, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5976948440714382}} {"text": "{-# LANGUAGE FlexibleInstances #-}\nimport Data.Complex\nimport Data.Numeric.Function\nimport Graphics.Gnuplot.Simple\n\n-- the physical constant are too small and creates rounding errors\nl=1.0e-11\nh=6.62606957e-34\nm=9.10938188e-31\nts = [0.00,0.01e-19..0.60e-19]\n\ne :: Complex Double -> Complex Double\ne n = n^2 * h^2 * pi^2 / (2 * m * l^2)\n\nk :: Complex Double -> Complex Double\nk n = n*pi/l\n\nw :: Complex Double -> Complex Double\nw n = (e n)/h\n\na :: Complex Double\na = sqrt(2/l)\n\nimg :: Complex Double\nimg = 0 :+ 1\n\neexp :: Complex Double -> Complex Double\neexp c = (mkComp (2.7182818**(realPart c))) * ((cos (imagPart c)) :+ (sin (imagPart c)))\n\npsi :: Complex Double -> Double -> Complex Double -> Complex Double\npsi n t x = a * sin((k n) * x) * (eexp (-img*(w n)*(t:+0)))\n\nnums = map (\\x -> x :+ 0) [1..3]\n\npsis = (1/(sqrt . fromIntegral $ (length nums))) * sum $ map psi nums\n\nsans = (^2) . psis\n\nmkComp x = x :+ 0\n\ny :: [[[Double]]]\ny = map (\\gress -> [map magnitude gress, map realPart gress, map imagPart gress]) funcs\n where xs = map mkComp (linearScale 300 (0, realPart l))\n funcs :: [[Complex Double]]\n funcs = map (\\t -> map (sans t) xs) ts\n\n-- | dirty string format\ngress :: Int -> String\ngress i\n | i < 10 = \"00\" ++ show i\n | i < 100 = \"0\" ++ show i\n | otherwise = show i\n\nonePlot :: [[Double]] -> Int -> IO ()\n--onePlot ys i = plotLists ([PNG (\"/tmp/kvantePNG\" ++ gress i ++ \".png\")]) ys\nonePlot ys i = plotLists ([YRange (-5.0e11,5.0e11), PNG (\"/tmp/kvantePNG\" ++ gress i ++ \".png\")]) ys\n--onePlot ys i = plotLists ([YRange (-3,3), PNG (\"/tmp/kvantePNG\" ++ gress i ++ \".png\")]) ys\n\nfun :: (Int, [[Double]]) -> IO ()\nfun (i,ys) = onePlot ys i\n\njazz :: [(Int, [[Double]])]\njazz = zip [1..] y\n\nmain = mapM fun jazz\n", "meta": {"hexsha": "dc5e3ee9dbcccbf74079cfa3f7512f43e6c812f3", "size": 1742, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Kvante.hs", "max_stars_repo_name": "molysgaard/kvante", "max_stars_repo_head_hexsha": "958f671bf45bd2af6c30013cd0bfd5f975a2c39d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-22T07:52:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-22T07:52:53.000Z", "max_issues_repo_path": "Kvante.hs", "max_issues_repo_name": "molysgaard/kvante", "max_issues_repo_head_hexsha": "958f671bf45bd2af6c30013cd0bfd5f975a2c39d", "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": "Kvante.hs", "max_forks_repo_name": "molysgaard/kvante", "max_forks_repo_head_hexsha": "958f671bf45bd2af6c30013cd0bfd5f975a2c39d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3939393939, "max_line_length": 100, "alphanum_fraction": 0.5947187141, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5976526247193862}} {"text": "import Numeric.LinearAlgebra\nimport HVX\n\nn = 4\na = EConst $ (n><1) [1..]\n\nx = EVar \"x\"\ny = EVar \"y\"\nconstNeg3 = EConst $ scale (-3.0) $ konst 1.0 (n, 1)\nconstTwos = EConst $ scale 2.0 $ konst 1.0 (n, 1)\n\nans = subgradMinimize\n (norm 2 (a *~ x) +~ norm 2 (b *~ y) +~ norm 2 (c +~ x +~ neg y))\n [y <=~ constTwos, x <=~ constNeg3]\n (decNonSumStep 10.0) 5000\n [(\"x\", konst 0.0 (n, 1)), (\"y\", konst 0.0 (n, 1))]\n\nmain :: IO ()\nmain = print ans\n", "meta": {"hexsha": "d63213657477bcbaf14318a165984b6a05828d75", "size": 748, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/demo.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": "examples/demo.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": "examples/demo.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": 26.7142857143, "max_line_length": 66, "alphanum_fraction": 0.4064171123, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5976138990647617}} {"text": "import Data.List(transpose)\nimport Numeric.LinearAlgebra.Algorithms\n\ndata Matrix a = Matrix { width :: Int, height :: Int, array :: [a] } deriving (Show, Eq)\n\nmkMatrix :: (Num a) => Int -> Int -> [a] -> Matrix a\nmkMatrix w h a = Matrix w h (take (w*h) (a ++ repeat 0))\n\n--add :: (Num a, Num b, Num c) => Matrix a -> Matrix b -> Maybe (Matrix c)\nadd (Matrix w h a) (Matrix w' h' a') \n | w == w' && h == h' = Just $ Matrix w h (zipWith (+) a a')\n | otherwise = Nothing\n\n\nmultiply (Matrix w h a) (Matrix w' h' a')\n | w == h' = undefined --normal\n | otherwise = Nothing\n\ngroupN n xs@(_:_) = (take n xs) : groupN n (drop n xs)\ngroupN n [] = []\n\ntranspose' :: [[a]] -> [[a]]\ntranspose' xs@(x:_)\n | null x = []\n | otherwise = heads : transpose' tails\n where heads = fmap head xs\n tails = fmap tail xs", "meta": {"hexsha": "b0d19fa8aefe0de40fd8a59ac6360c25eb59d49b", "size": 811, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Matrix.hs", "max_stars_repo_name": "5outh/Haskell-Graphics-Projects", "max_stars_repo_head_hexsha": "5a27e819da4897d56630d9850bfaef99f5bd063e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-14T02:01:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-14T02:01:26.000Z", "max_issues_repo_path": "Matrix.hs", "max_issues_repo_name": "5outh/Haskell-Graphics-Projects", "max_issues_repo_head_hexsha": "5a27e819da4897d56630d9850bfaef99f5bd063e", "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": "Matrix.hs", "max_forks_repo_name": "5outh/Haskell-Graphics-Projects", "max_forks_repo_head_hexsha": "5a27e819da4897d56630d9850bfaef99f5bd063e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.037037037, "max_line_length": 88, "alphanum_fraction": 0.5733662145, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5974024409689119}} {"text": "module Loss where\n\nimport Numeric.LinearAlgebra\n\n\ngetLoss :: String -> Matrix R -> Matrix R -> Matrix R\ngetLoss lossType yMat tMat =\n case lossType of\n \"mse\" -> mse yMat tMat\n otherwise -> yMat -- Warning: Never Used Necessery!\n\nmse :: Matrix R -> Matrix R -> Matrix R\nmse yMat tMat =\n let dyMat = yMat - tMat\n r = rows yMat\n c = cols yMat\n halfMat = (r >< c) [0.5 ..]::(Matrix R) in\n halfMat * dyMat * dyMat\n\n\n", "meta": {"hexsha": "a5e7a1157eabc30695873f85abd448dbcc360532", "size": 435, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "vortex/Loss.hs", "max_stars_repo_name": "neutronest/vortex", "max_stars_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-03-16T06:51:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-06T05:07:06.000Z", "max_issues_repo_path": "vortex/Loss.hs", "max_issues_repo_name": "neutronest/vortex", "max_issues_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "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": "vortex/Loss.hs", "max_forks_repo_name": "neutronest/vortex", "max_forks_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "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": 20.7142857143, "max_line_length": 55, "alphanum_fraction": 0.6206896552, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5970019349771316}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n\n-- |\n-- Module : Numeric.HHT\n-- Copyright : (c) Justin Le 2019\n-- License : BSD3\n--\n-- Maintainer : justin@jle.im\n-- Stability : experimental\n-- Portability : non-portable\n--\n-- Hilbert-Huang transform in pure Haskell.\n--\n-- The main data type is 'HHT', which can be generated using 'hht' or\n-- 'hhtEmd'. See \"Numeric.EMD\" for information on why this module uses\n-- \"sized vectors\", and how to convert unsized vectors to sized vectors.\n--\n-- @since 0.1.2.0\n\nmodule Numeric.HHT (\n -- * Hilbert-Huang Transform\n HHT(..), HHTLine(..)\n , hhtEmd\n , hht\n , ihhtEmd\n , ihht\n -- ** Hilbert-Huang Spectrum\n , hhtSpectrum, hhtSparseSpectrum, hhtDenseSpectrum\n -- ** Properties of spectrum\n , meanMarginal, marginal, instantaneousEnergy, degreeOfStationarity\n , expectedFreq, dominantFreq\n , foldFreq\n -- ** Options\n , EMDOpts(..), defaultEO, BoundaryHandler(..), defaultSifter, SplineEnd(..)\n -- * Hilbert transforms (internal usage)\n , hilbert\n , hilbertIm\n , hilbertPolar\n , hilbertMagFreq\n ) where\n\nimport Control.DeepSeq\nimport Data.Complex\nimport Data.Finite\nimport Data.Fixed\nimport Data.Foldable\nimport Data.Proxy\nimport Data.Semigroup\nimport GHC.Generics (Generic)\nimport GHC.TypeNats\nimport Numeric.EMD\nimport Numeric.HHT.Internal.FFT\nimport qualified Data.Binary as Bi\nimport qualified Data.Map as M\nimport qualified Data.Vector.Generic as VG\nimport qualified Data.Vector.Generic.Sized as SVG\nimport qualified Data.Vector.Sized as SV\nimport qualified Math.FFT.Base as FFT\n\n-- | A Hilbert Trasnform of a given IMF, given as a \"skeleton line\".\ndata HHTLine v n a = HHTLine\n { -- | IMF HHT Magnitude as a time series.\n --\n -- It may be useful to \"zip\" this vector with 'hlFreqs'. To do this,\n -- use a function like 'SVG.init' or 'SVG.tail' to make these two\n -- vectors contain the same length, or 'weaken'/'shift' to make\n -- indices in 'hlFreqs' usable as indices in 'hlMags'.\n --\n -- Prior to v0.1.9.0, this was a length-n vector, just like\n -- 'hlFreqs'. To get the same behavior, use 'SVG.init' on this new\n -- field's value.\n hlMags :: !(SVG.Vector v (n + 1) a)\n -- | IMF HHT instantaneous frequency as a time series (between 0 and 1).\n --\n -- In reality, these frequencies are the frequencies \"in between\"\n -- each step in 'hlMags'.\n , hlFreqs :: !(SVG.Vector v n a)\n -- | Initial phase of skeleton line (between -pi and pi)\n --\n -- @since 0.1.9.0\n , hlInitPhase :: !a\n }\n deriving (Show, Eq, Ord, Generic)\n\n-- | @since 0.1.3.0\ninstance (VG.Vector v a, KnownNat n, Bi.Binary (v a), Bi.Binary a) => Bi.Binary (HHTLine v n a)\n\n-- | @since 0.1.5.0\ninstance (NFData (v a), NFData a) => NFData (HHTLine v n a)\n\n-- | A Hilbert-Huang Transform. An @'HHT' v n a@ is a Hilbert-Huang\n-- transform of an @n@-item time series of items of type @a@ represented\n-- using vector @v@.\n--\n-- Create using 'hht' or 'hhtEmd'.\ndata HHT v n a = HHT\n { -- | Skeleton lines corresponding to each IMF\n hhtLines :: [HHTLine v n a]\n -- | Residual from EMD\n --\n -- @since 0.1.9.0\n , hhtResidual :: SVG.Vector v (n + 1) a\n }\n deriving (Show, Eq, Ord, Generic)\n\n-- | @since 0.1.3.0\ninstance (VG.Vector v a, KnownNat n, Bi.Binary (v a), Bi.Binary a) => Bi.Binary (HHT v n a)\n\n-- | @since 0.1.5.0\ninstance (NFData (v a), NFData a) => NFData (HHT v n a)\n\n-- | Directly compute the Hilbert-Huang transform of a given time series.\n-- Essentially is a composition of 'hhtEmd' and 'emd'. See 'hhtEmd' for\n-- a more flexible version.\nhht :: forall v n a. (VG.Vector v a, VG.Vector v (Complex a), KnownNat n, FFT.FFTWReal a)\n => EMDOpts v (n + 1) a\n -> SVG.Vector v (n + 1) a\n -> HHT v n a\nhht eo = hhtEmd . emd eo\n\n-- | Compute the Hilbert-Huang transform from a given Empirical Mode\n-- Decomposition.\nhhtEmd\n :: forall v n a. (VG.Vector v a, VG.Vector v (Complex a), KnownNat n, FFT.FFTWReal a)\n => EMD v (n + 1) a\n -> HHT v n a\nhhtEmd EMD{..} = HHT (map go emdIMFs) emdResidual\n where\n go i = HHTLine m f \u03c60\n where\n (m, (f, \u03c60)) = hilbertMagFreq i\n\n-- | Invert a Hilbert-Huang transform back to an Empirical Mode\n-- Decomposition\n--\n-- @since 0.1.9.0\nihhtEmd\n :: (VG.Vector v a, Floating a)\n => HHT v n a\n -> EMD v (n + 1) a\nihhtEmd HHT{..} = EMD (map go hhtLines) hhtResidual\n where\n go HHTLine{..} = SVG.zipWith (\\m \u03b8 -> m * cos \u03b8) hlMags \u03b8s\n where\n \u03b8s = SVG.scanl' (+) hlInitPhase ((* (2 * pi)) `SVG.map` hlFreqs)\n\n-- | Construct a time series correpsonding to its hilbert-huang transform.\n--\n-- @since 0.1.9.0\nihht\n :: (VG.Vector v a, Floating a)\n => HHT v n a\n -> SVG.Vector v (n + 1) a\nihht = iemd . ihhtEmd\n\n-- | Fold and collapse a Hilbert-Huang transform along the frequency axis\n-- at each step in time along some monoid.\n--\n-- @since 0.1.8.0\nfoldFreq\n :: forall v u n a b c. (VG.Vector v a, VG.Vector u c, KnownNat n, Monoid b)\n => (a -> a -> b) -- ^ Combining function, taking frequency, then magnitude\n -> (b -> c) -- ^ Projecting function\n -> HHT v n a\n -> SVG.Vector u n c\nfoldFreq f g = pullBack\n . foldl' (SV.zipWith (<>)) (SV.replicate mempty)\n . map split\n . hhtLines\n where\n split :: HHTLine v n a -> SV.Vector n b\n split HHTLine{..} = SVG.generate $ \\i ->\n f (hlFreqs `SVG.index` i) (hlMags `SVG.index` weaken i)\n {-# INLINE split #-}\n pullBack :: SV.Vector n b -> SVG.Vector u n c\n pullBack v = SVG.generate $ \\i -> g (v `SV.index` i)\n {-# INLINE pullBack #-}\n{-# INLINE foldFreq #-}\n\nnewtype SumMap k a = SumMap { getSumMap :: M.Map k a }\n\ninstance (Ord k, Num a) => Semigroup (SumMap k a) where\n SumMap x <> SumMap y = SumMap $ M.unionWith (+) x y\n\ninstance (Ord k, Num a) => Monoid (SumMap k a) where\n mempty = SumMap M.empty\n\n-- | Compute the full Hilbert-Huang Transform spectrum. At each timestep\n-- is a sparse map of frequency components and their respective magnitudes.\n-- Frequencies not in the map are considered to be zero.\n--\n-- Takes a \"binning\" function to allow you to specify how specific you want\n-- your frequencies to be.\n--\n-- See 'hhtSparseSpectrum' for a sparser version, and 'hhtDenseSpectrum'\n-- for a denser version.\nhhtSpectrum\n :: forall v n a k. (VG.Vector v a, KnownNat n, Ord k, Num a)\n => (a -> k) -- ^ binning function. takes rev/tick freq between 0 and 1.\n -> HHT v n a\n -> SV.Vector n (M.Map k a)\nhhtSpectrum f = foldFreq (\\k -> SumMap . M.singleton (f k)) getSumMap\n\n-- | A sparser vesion of 'hhtSpectrum'. Compute the full Hilbert-Huang\n-- Transform spectrum. Returns a /sparse/ matrix representing the power at\n-- each time step (the @'Finite' n@) and frequency (the @k@).\n--\n-- Takes a \"binning\" function to allow you to specify how specific you want\n-- your frequencies to be.\n--\n-- @since 0.1.4.0\nhhtSparseSpectrum\n :: forall v n a k. (VG.Vector v a, KnownNat n, Ord k, Num a)\n => (a -> k) -- ^ binning function. takes rev/tick freq between 0 and 1.\n -> HHT v n a\n -> M.Map (Finite n, k) a\nhhtSparseSpectrum f = M.unionsWith (+) . concatMap go . hhtLines\n where\n go :: HHTLine v n a -> [M.Map (Finite n, k) a]\n go HHTLine{..} = flip fmap (finites @n) $ \\i ->\n M.singleton (i, f $ hlFreqs `SVG.index` i) $\n hlMags `SVG.index` weaken i\n\n-- | A denser version of 'hhtSpectrum'. Compute the full Hilbert-Huang\n-- Transform spectrum, returning a dense matrix (as a vector of vectors)\n-- representing the power at each time step and each frequency.\n--\n-- Takes a \"binning\" function that maps a frequency to one of @m@ discrete\n-- slots, for accumulation in the dense matrix.\n--\n-- @since 0.1.4.0\nhhtDenseSpectrum\n :: forall v n m a. (VG.Vector v a, KnownNat n, KnownNat m, Num a)\n => (a -> Finite m) -- ^ binning function. takes rev/tick freq between 0 and 1.\n -> HHT v n a\n -> SV.Vector n (SV.Vector m a)\nhhtDenseSpectrum f h = SV.generate $ \\i -> SV.generate $ \\j ->\n M.findWithDefault 0 (i, j) ss\n where\n ss = hhtSparseSpectrum f h\n\n-- | Compute the marginal spectrum given a Hilbert-Huang Transform. It\n-- provides the \"total power\" over the entire time series for each\n-- frequency component. See 'meanMarginal' for a version that averages\n-- over the length of the time series, making it more close in nature to\n-- the purpose of a Fourier Transform.\n--\n-- A binning function is accepted to allow you to specify how specific you\n-- want your frequencies to be.\nmarginal\n :: forall v n a k. (VG.Vector v a, KnownNat n, Ord k, Num a)\n => (a -> k) -- ^ binning function. takes rev/tick freq between 0 and 1.\n -> HHT v n a\n -> M.Map k a\nmarginal f = M.unionsWith (+) . concatMap go . hhtLines\n where\n go :: HHTLine v n a -> [M.Map k a]\n go HHTLine{..} = flip fmap (finites @n) $ \\i ->\n M.singleton (f $ hlFreqs `SVG.index` i) (hlMags `SVG.index` weaken i)\n\n-- | Compute the mean marginal spectrum given a Hilbert-Huang Transform. It\n-- is similar to a Fourier Transform; it provides the \"total power\" over\n-- the entire time series for each frequency component, averaged over the\n-- length of the time series.\n--\n-- A binning function is accepted to allow you to specify how specific you\n-- want your frequencies to be.\n--\n-- @since 0.1.8.0\nmeanMarginal\n :: forall v n a k. (VG.Vector v a, KnownNat n, Ord k, Fractional a)\n => (a -> k) -- ^ binning function. takes rev/tick freq between 0 and 1.\n -> HHT v n a\n -> M.Map k a\nmeanMarginal f = fmap (/ n) . marginal f\n where\n n = fromIntegral $ natVal (Proxy @n)\n\n-- | Returns the \"expected value\" of frequency at each time step,\n-- calculated as a weighted average of all contributions at every frequency\n-- at that time step.\n--\n-- @since 0.1.4.0\nexpectedFreq\n :: forall v n a. (VG.Vector v a, KnownNat n, Fractional a)\n => HHT v n a\n -> SVG.Vector v n a\nexpectedFreq = foldFreq (\\x y -> (Sum (x * y), Sum y)) (\\(Sum x, Sum y) -> x / y)\n\n-- | Returns the dominant frequency (frequency with largest magnitude\n-- contribution) at each time step.\n--\n-- @since 0.1.4.0\ndominantFreq\n :: forall v n a. (VG.Vector v a, KnownNat n, Ord a)\n => HHT v n a\n -> SVG.Vector v n a\ndominantFreq = foldFreq comb proj\n where\n comb :: a -> a -> Maybe (Max (Arg a a))\n comb x y = Just $ Max $ Arg y x\n proj :: Maybe (Max (Arg a a)) -> a\n proj Nothing = errorWithoutStackTrace\n \"Numeric.HHT.dominantFreq: HHT was formed with no Intrinsic Mode Functions\"\n proj (Just (Max (Arg _ x))) = x\n\n-- | Compute the instantaneous energy of the time series at every step via\n-- the Hilbert-Huang Transform.\ninstantaneousEnergy\n :: forall v n a. (VG.Vector v a, KnownNat n, Num a)\n => HHT v n a\n -> SVG.Vector v n a\ninstantaneousEnergy = foldFreq (\\_ x -> Sum (x * x)) getSum\n\n-- | Degree of stationarity, as a function of frequency.\ndegreeOfStationarity\n :: forall v n a k. (VG.Vector v a, KnownNat n, Ord k, Fractional a, Eq a)\n => (a -> k) -- ^ binning function. takes rev/tick freq between 0 and 1.\n -> HHT v n a\n -> M.Map k a\ndegreeOfStationarity f h = fmap (/ n)\n . M.unionsWith (+)\n . concatMap go\n . hhtLines\n $ h\n where\n n = fromIntegral $ natVal (Proxy @n)\n meanMarg = meanMarginal f h\n go :: HHTLine v n a -> [M.Map k a]\n go HHTLine{..} = flip fmap (finites @n) $ \\i ->\n let fr = f $ hlFreqs `SVG.index` i\n mm = meanMarg M.! fr\n in M.singleton fr $\n if mm == 0\n then 0\n else (1 - (hlMags `SVG.index` weaken i / mm)) ^ (2 :: Int)\n\n-- | Given a time series, return a time series of the /magnitude/ of the\n-- hilbert transform and the /frequency/ of the hilbert transform, in units\n-- of revolutions per tick. Is only expected to taken in proper/legal\n-- IMFs.\n--\n-- The frequency will always be between 0 and 1, since we can't determine\n-- anything faster given the discretization, and we exclude negative values\n-- as physically unmeaningful for an IMF.\nhilbertMagFreq\n :: forall v n a. (VG.Vector v a, VG.Vector v (Complex a), KnownNat n, FFT.FFTWReal a)\n => SVG.Vector v (n + 1) a\n -> (SVG.Vector v (n + 1) a, (SVG.Vector v n a, a))\nhilbertMagFreq v = (hilbertMag, (hilbertFreq, \u03c60))\n where\n v' = hilbert v\n hilbertMag = SVG.map magnitude v'\n hilbertPhase = SVG.map phase v'\n \u03c60 = SVG.head hilbertPhase\n hilbertFreq = SVG.map ((`mod'` 1) . (/ (2 * pi))) $ SVG.tail hilbertPhase - SVG.init hilbertPhase\n\n-- | The polar form of 'hilbert': returns the magnitude and phase of the\n-- discrete hilbert transform of a series.\n--\n-- The computation of magnitude is unique, but computing phase gives us\n-- some ambiguity. The interpretation of the hilbert transform for\n-- instantaneous frequency is that the original series \"spirals\" around the\n-- complex plane as time progresses, like a helix. So, we impose\n-- a constraint on the phase to uniquely determine it: \\(\\phi_{t+1}\\) is\n-- the /minimal valid phase/ such that \\(\\phi_{t+1} \\geq \\phi_{t}\\). This\n-- enforces the phase to be monotonically increasing at the slowest\n-- possible detectable rate.\n--\n-- @since 0.1.6.0\nhilbertPolar\n :: forall v n a. (VG.Vector v a, VG.Vector v (Complex a), KnownNat n, FFT.FFTWReal a)\n => SVG.Vector v (n + 1) a\n -> (SVG.Vector v (n + 1) a, SVG.Vector v (n + 1) a)\nhilbertPolar v = (hilbertMag, hilbertPhase)\n where\n hilbertMag :: SVG.Vector v (n + 1) a\n hilbertFreq :: SVG.Vector v n a\n (hilbertMag, (hilbertFreq, \u03c60)) = hilbertMagFreq v\n hilbertPhase :: SVG.Vector v (n + 1) a\n hilbertPhase = SVG.scanl' (+) \u03c60 ((* (2 * pi)) `SVG.map` hilbertFreq)\n\n-- | Real part is original series and imaginary part is hilbert transformed\n-- series. Creates a \"helical\" form of the original series that rotates\n-- along the complex plane.\n--\n-- Note that since /0.1.7.0/, this uses the same algorithm as the matlab\n-- implementation \nhilbert\n :: forall v n a.\n ( VG.Vector v a\n , VG.Vector v (Complex a)\n , KnownNat n\n , FFT.FFTWReal a\n )\n => SVG.Vector v n a\n -> SVG.Vector v n (Complex a)\nhilbert v = ifft u'\n where\n v' = SVG.map (:+ 0) v\n u = fft v'\n u' = flip SVG.imap u $ \\(fromIntegral->i) x ->\n if | i == 0 || i == (n `div` 2) -> x\n | i < (n `div` 2) -> 2 * x\n | otherwise -> 0\n n = natVal (Proxy @n)\n\n-- | Hilbert transformed series. Essentially the same series, but\n-- phase-shifted 90 degrees. Is so-named because it is the \"imaginary\n-- part\" of the proper hilbert transform, 'hilbert'.\n--\n-- Note that since /0.1.7.0/, this uses the same algorithm as the matlab\n-- implementation \nhilbertIm\n :: forall v n a.\n ( VG.Vector v a\n , VG.Vector v (Complex a)\n , KnownNat n\n , FFT.FFTWReal a\n )\n => SVG.Vector v n a\n -> SVG.Vector v n a\nhilbertIm = SVG.map imagPart . hilbert\n\n", "meta": {"hexsha": "f4c105ebadc04841ff8b2d92508f2eaf5cfeeefe", "size": 16079, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/HHT.hs", "max_stars_repo_name": "mstksg/emd", "max_stars_repo_head_hexsha": "bc02724d861a8932b72a97745542a62dd19071d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-07-11T08:16:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T07:49:50.000Z", "max_issues_repo_path": "src/Numeric/HHT.hs", "max_issues_repo_name": "mstksg/emd", "max_issues_repo_head_hexsha": "bc02724d861a8932b72a97745542a62dd19071d0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-07-26T09:36:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-22T09:24:58.000Z", "max_forks_repo_path": "src/Numeric/HHT.hs", "max_forks_repo_name": "mstksg/emd", "max_forks_repo_head_hexsha": "bc02724d861a8932b72a97745542a62dd19071d0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7940503432, "max_line_length": 102, "alphanum_fraction": 0.6148392313, "num_tokens": 4856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5969708640862013}} {"text": "{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\nmodule Ch3 where\n\nimport Text.Printf\nimport Numeric.LinearAlgebra\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Yaml as Yaml\n\nimport qualified MNIST as MNIST\nimport NeuralNetwork\n\ntype ActivationFunction = [Double] -> [Double]\ntype Layer = (Matrix R, Vector R, ActivationFunction)\ntype Network = [Layer]\n\n-- ch3_4\nnetwork :: Network\nnetwork = [ ( (2><3) [0.1, 0.3, 0.5, 0.2, 0.4, 0.6]\n , vector [0.1, 0.2, 0.3]\n , map sigmoidFunction\n )\n , ( (3><2) [0.1, 0.4, 0.2, 0.5, 0.3, 0.6]\n , vector [0.1, 0.2]\n , map sigmoidFunction\n )\n , ( (2><2) [0.1, 0.3, 0.2, 0.4]\n , vector [0.1, 0.2]\n , id\n )\n ]\n\nforward :: Network -> Vector R -> Vector R\nforward nw x = foldl propagate x nw\n where propagate x (w, b, f) = fromList . f . toList $ x <# w + b\n\nx = vector [1.0, 0.5]\ny = forward network x\n\n\n-- ch3_6\nreadMatrix :: FilePath -> IO (Matrix R)\nreadMatrix file = do\n s <- BS.readFile file\n let Just m = Yaml.decode s :: Maybe [[Double]]\n return $ fromLists m\n\nreadVector :: FilePath -> IO (Vector R)\nreadVector file = do\n s <- BS.readFile file\n let Just v = Yaml.decode s :: Maybe [Double]\n return $ fromList v\n\nreadNetwork :: IO Network\nreadNetwork = do\n w1 <- readMatrix' \"W1\"\n b1 <- readVector' \"b1\"\n w2 <- readMatrix' \"W2\"\n b2 <- readVector' \"b2\"\n w3 <- readMatrix' \"W3\"\n b3 <- readVector' \"b3\"\n return [ (w1, b1, map sigmoidFunction)\n , (w2, b2, map sigmoidFunction)\n , (w3, b3, (toList . softmax . vector))\n ]\n where readMatrix' f = readMatrix $ \"data/mnist/\" ++ f ++ \".yml\"\n readVector' f = readVector $ \"data/mnist/\" ++ f ++ \".yml\"\n\npredict :: Network -> [Double] -> [Double]\npredict network = toList . (forward network) . vector\n\ndisplayPrediction :: [Double] -> IO ()\ndisplayPrediction xs = do\n mapM_ print' $ zip xs [0..]\n where print' (x, i) = do\n printf \"%d %5.2f%% \" (i :: Int) (x * 100)\n putStrLn $ replicate (floor (x * 20)) '*'\n\nreadImages :: IO [MNIST.Image]\nreadImages = do\n (MNIST.Images _ _ _ imgs) <- MNIST.getImages MNIST.Test\n return imgs\n\nrun :: [MNIST.Image] -> IO ()\nrun imgs = do\n predictor <- predict <$> readNetwork\n mapM_ (predict' predictor) imgs\n where predict' predictor img = do\n MNIST.displayImage img\n displayPrediction $ predictor $ concat img\n\nmain :: IO ()\nmain = run =<< readImages\n", "meta": {"hexsha": "98c7385bb89c66b4819670e77d526b68c1d731f2", "size": 2547, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Ch3.hs", "max_stars_repo_name": "kayhide/deep-learning-from-scratch", "max_stars_repo_head_hexsha": "c6bd6f7abcd4b51cc3a12f75d6fb43a4b34592f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-02-20T13:11:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T20:11:38.000Z", "max_issues_repo_path": "app/Ch3.hs", "max_issues_repo_name": "kayhide/zero-to-deep-learning", "max_issues_repo_head_hexsha": "c6bd6f7abcd4b51cc3a12f75d6fb43a4b34592f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Ch3.hs", "max_forks_repo_name": "kayhide/zero-to-deep-learning", "max_forks_repo_head_hexsha": "c6bd6f7abcd4b51cc3a12f75d6fb43a4b34592f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8105263158, "max_line_length": 66, "alphanum_fraction": 0.5908912446, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984213, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5965195702301102}} {"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\nmodule AI.Singularity.Data.Matrix where\nimport GHC.TypeLits\nimport qualified Numeric.LinearAlgebra.Data as LD\nimport qualified Numeric.LinearAlgebra.Devel as LDev\nimport qualified Numeric.LinearAlgebra as LA\nimport Control.Lens\nimport Data.Proxy\nimport Control.Monad.ST\nimport AI.Singularity.Utils\nimport System.Random\nimport Control.Monad\n\ndata GeneralMatrix :: (* -> *) -> Nat -> Nat -> * where\n Mat :: mat Float -> GeneralMatrix mat m n\n\nderiving instance Show (mat Float) => Show (GeneralMatrix mat m n)\n\ntype Matrix = GeneralMatrix LD.Matrix\n\ntype MutMatrix s = GeneralMatrix (LDev.STMatrix s)\n\nmatr :: Lens' (GeneralMatrix mat m n) (mat Float)\n{-# INLINE matr #-}\nmatr f (Mat m) = Mat <$> f m\n\ndata GeneralInTrainingMat mat m n =\n GeneralInTrainingMat (GeneralMatrix mat m n) (GeneralMatrix mat m n) (GeneralMatrix mat m n)\n\ntype InTrainMat m n = GeneralInTrainingMat LD.Matrix m n\n\ntype STInTrainMat s = GeneralInTrainingMat (LDev.STMatrix s)\n\nderiving instance Show (mat Float) => Show (GeneralInTrainingMat mat m n)\n\ntrMatr :: Lens' (GeneralInTrainingMat mat m n) (GeneralMatrix mat m n)\n{-# INLINE trMatr #-}\ntrMatr f (GeneralInTrainingMat m g h) = (\\x -> GeneralInTrainingMat x g h) <$> f m\n\ntrGrad :: Lens' (GeneralInTrainingMat mat m n) (GeneralMatrix mat m n)\n{-# INLINE trGrad #-}\ntrGrad f (GeneralInTrainingMat m g h) = (\\x -> GeneralInTrainingMat m x h) <$> f g\n\nhGrad :: Lens' (GeneralInTrainingMat mat m n) (GeneralMatrix mat m n)\n{-# INLINE hGrad #-}\nhGrad f (GeneralInTrainingMat m g h) = GeneralInTrainingMat m g <$> f h\n\n\nmatSlice,gradSlice :: forall s m n. (KnownNat m, KnownNat n) => STInTrainMat s m n -> LDev.Slice s Float\nmatSlice m = LDev.Slice (m^.trMatr.matr) 0 0 (fromIntegral . natVal $ Proxy @ n) (fromIntegral . natVal $ Proxy @ m)\ngradSlice m = LDev.Slice (m^.trGrad.matr) 0 0 (fromIntegral . natVal $ Proxy @ n) (fromIntegral . natVal $ Proxy @ m)\n\nthawM :: Matrix m n -> ST s (MutMatrix s m n)\nthawM = Mat <$< LDev.thawMatrix . view matr\n\n\ntoSTInTrainM :: (KnownNat m, KnownNat n) => Matrix m n -> ST s (STInTrainMat s m n)\ntoSTInTrainM m = GeneralInTrainingMat <$> thawM m <*> thawM 0 <*> thawM 0\n\nmatHeight :: forall m n mat. KnownNat n => GeneralMatrix mat m n -> Int\nmatHeight _ = natToInt @ n\n\nmatWidth :: forall m n mat. KnownNat m => GeneralMatrix mat m n -> Int\nmatWidth _ = natToInt @ m\n\n\nmat :: forall m n. (KnownNat m, KnownNat n) => [Float] -> Matrix m n\nmat = Mat . (valm LD.>< valn) . take (valm * valn) . cycle\n where valm = matHeight ( undefined :: Matrix m n)\n valn = matWidth ( undefined :: Matrix m n)\n\nrandomMat :: forall m n. (KnownNat m, KnownNat n) => IO (Matrix m n)\nrandomMat = Mat . (valm LD.>< valn) <$> replicateM (valm * valn) (randomRIO (0.001, 0.1))\n where valm = matHeight ( undefined :: Matrix m n)\n valn = matWidth ( undefined :: Matrix m n)\n\nzeroMat :: forall m n. (KnownNat m, KnownNat n) => Matrix m n\nzeroMat = 0\n\nident :: forall n. (KnownNat n) => Matrix n n\nident = Mat $ LD.ident valn\n where valn = matHeight ( undefined :: Matrix n n)\n\ntransposeM :: forall m n. (KnownNat m, KnownNat n) => Matrix m n -> Matrix n m\ntransposeM = Mat . LA.tr . view matr\n\ninstance (KnownNat n, KnownNat m) => Num (Matrix m n) where\n (+) (Mat m1) (Mat m2) = Mat (m1 + m2)\n (*) (Mat m1) (Mat m2) = Mat (m1 * m2)\n negate (Mat m1) = Mat $ LD.cmap negate m1\n fromInteger i = mat [fromInteger i]\n abs (Mat m1) = Mat $ LD.cmap abs m1\n signum (Mat m1) = Mat $ LD.cmap signum m1\n\ninstance (KnownNat n, KnownNat m) => Fractional (Matrix m n) where\n (/) (Mat m1) (Mat m2) = Mat $ m1 / m2\n fromRational = mat . (:[]) . fromRational\n\ninstance (KnownNat n, KnownNat m, n ~ m) => Monoid (Matrix n m) where\n mempty = Mat $ LA.ident $ fromInteger $ natVal (Proxy :: Proxy n)\n mappend (Mat m1) (Mat m2) = Mat $ (LA.<>) m1 m2\n\nmmap :: (KnownNat n, KnownNat m) => (Float -> Float) -> Matrix m n -> Matrix m n\nmmap f (Mat m) = Mat $ LD.cmap f m\n\ncheckNan :: forall m n. Matrix m n -> Matrix m n\ncheckNan (Mat x) = Mat (LD.cmap nancheck x)\n", "meta": {"hexsha": "7c6c88ee0bf5b1bc318c41437de87e1b9ab2b2f9", "size": 4425, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Singularity/Data/Matrix.hs", "max_stars_repo_name": "Antystenes/Memetic-Predictor", "max_stars_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AI/Singularity/Data/Matrix.hs", "max_issues_repo_name": "Antystenes/Memetic-Predictor", "max_issues_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AI/Singularity/Data/Matrix.hs", "max_forks_repo_name": "Antystenes/Memetic-Predictor", "max_forks_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "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.8205128205, "max_line_length": 117, "alphanum_fraction": 0.6675706215, "num_tokens": 1360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5965147945411097}} {"text": "{-# LANGUAGE FlexibleContexts, Rank2Types, ScopedTypeVariables #-}\n-- | Student's T-test is for assessing whether two samples have\n-- different mean. This module contain several variations of\n-- T-test. It's a parametric tests and assumes that samples are\n-- normally distributed.\nmodule Statistics.Test.StudentT\n (\n studentTTest\n , welchTTest\n , pairedTTest\n , module Statistics.Test.Types\n ) where\n\nimport Statistics.Distribution hiding (mean)\nimport Statistics.Distribution.StudentT\nimport Statistics.Sample (mean, varianceUnbiased)\nimport Statistics.Test.Types\nimport Statistics.Types (mkPValue,PValue)\nimport Statistics.Function (square)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Storable as S\nimport qualified Data.Vector as V\n\n\n\n-- | Two-sample Student's t-test. It assumes that both samples are\n-- normally distributed and have same variance. Returns @Nothing@ if\n-- sample sizes are not sufficient.\nstudentTTest :: (G.Vector v Double)\n => PositionTest -- ^ one- or two-tailed test\n -> v Double -- ^ Sample A\n -> v Double -- ^ Sample B\n -> Maybe (Test StudentT)\nstudentTTest test sample1 sample2\n | G.length sample1 < 2 || G.length sample2 < 2 = Nothing\n | otherwise = Just Test\n { testSignificance = significance test t ndf\n , testStatistics = t\n , testDistribution = studentT ndf\n }\n where\n (t, ndf) = tStatistics True sample1 sample2\n{-# INLINABLE studentTTest #-}\n{-# SPECIALIZE studentTTest :: PositionTest -> U.Vector Double -> U.Vector Double -> Maybe (Test StudentT) #-}\n{-# SPECIALIZE studentTTest :: PositionTest -> S.Vector Double -> S.Vector Double -> Maybe (Test StudentT) #-}\n{-# SPECIALIZE studentTTest :: PositionTest -> V.Vector Double -> V.Vector Double -> Maybe (Test StudentT) #-}\n\n-- | Two-sample Welch's t-test. It assumes that both samples are\n-- normally distributed but doesn't assume that they have same\n-- variance. Returns @Nothing@ if sample sizes are not sufficient.\nwelchTTest :: (G.Vector v Double)\n => PositionTest -- ^ one- or two-tailed test\n -> v Double -- ^ Sample A\n -> v Double -- ^ Sample B\n -> Maybe (Test StudentT)\nwelchTTest test sample1 sample2\n | G.length sample1 < 2 || G.length sample2 < 2 = Nothing\n | otherwise = Just Test\n { testSignificance = significance test t ndf\n , testStatistics = t\n , testDistribution = studentT ndf\n }\n where\n (t, ndf) = tStatistics False sample1 sample2\n{-# INLINABLE welchTTest #-}\n{-# SPECIALIZE welchTTest :: PositionTest -> U.Vector Double -> U.Vector Double -> Maybe (Test StudentT) #-}\n{-# SPECIALIZE welchTTest :: PositionTest -> S.Vector Double -> S.Vector Double -> Maybe (Test StudentT) #-}\n{-# SPECIALIZE welchTTest :: PositionTest -> V.Vector Double -> V.Vector Double -> Maybe (Test StudentT) #-}\n\n-- | Paired two-sample t-test. Two samples are paired in a\n-- within-subject design. Returns @Nothing@ if sample size is not\n-- sufficient.\npairedTTest :: forall v. (G.Vector v (Double, Double), G.Vector v Double)\n => PositionTest -- ^ one- or two-tailed test\n -> v (Double, Double) -- ^ paired samples\n -> Maybe (Test StudentT)\npairedTTest test sample\n | G.length sample < 2 = Nothing\n | otherwise = Just Test\n { testSignificance = significance test t ndf\n , testStatistics = t\n , testDistribution = studentT ndf\n }\n where\n (t, ndf) = tStatisticsPaired sample\n{-# INLINABLE pairedTTest #-}\n{-# SPECIALIZE pairedTTest :: PositionTest -> U.Vector (Double,Double) -> Maybe (Test StudentT) #-}\n{-# SPECIALIZE pairedTTest :: PositionTest -> V.Vector (Double,Double) -> Maybe (Test StudentT) #-}\n\n\n-------------------------------------------------------------------------------\n\nsignificance :: PositionTest -- ^ one- or two-tailed\n -> Double -- ^ t statistics\n -> Double -- ^ degree of freedom\n -> PValue Double -- ^ p-value\nsignificance test t df =\n case test of\n -- Here we exploit symmetry of T-distribution and calculate small tail\n SamplesDiffer -> mkPValue $ 2 * tailArea (negate (abs t))\n AGreater -> mkPValue $ tailArea (negate t)\n BGreater -> mkPValue $ tailArea t\n where\n tailArea = cumulative (studentT df)\n\n\n-- Calculate T statistics for two samples\ntStatistics :: (G.Vector v Double)\n => Bool -- variance equality\n -> v Double\n -> v Double\n -> (Double, Double)\n{-# INLINE tStatistics #-}\ntStatistics varequal sample1 sample2 = (t, ndf)\n where\n -- t-statistics\n t = (m1 - m2) / sqrt (\n if varequal\n then ((n1 - 1) * s1 + (n2 - 1) * s2) / (n1 + n2 - 2) * (1 / n1 + 1 / n2)\n else s1 / n1 + s2 / n2)\n\n -- degree of freedom\n ndf | varequal = n1 + n2 - 2\n | otherwise = square (s1 / n1 + s2 / n2)\n / (square s1 / (square n1 * (n1 - 1)) + square s2 / (square n2 * (n2 - 1)))\n -- statistics of two samples\n n1 = fromIntegral $ G.length sample1\n n2 = fromIntegral $ G.length sample2\n m1 = mean sample1\n m2 = mean sample2\n s1 = varianceUnbiased sample1\n s2 = varianceUnbiased sample2\n\n\n-- Calculate T-statistics for paired sample\ntStatisticsPaired :: (G.Vector v (Double, Double), G.Vector v Double)\n => v (Double, Double)\n -> (Double, Double)\n{-# INLINE tStatisticsPaired #-}\ntStatisticsPaired sample = (t, ndf)\n where\n -- t-statistics\n t = let d = G.map (uncurry (-)) sample\n sumd = G.sum d\n in sumd / sqrt ((n * G.sum (G.map square d) - square sumd) / ndf)\n -- degree of freedom\n ndf = n - 1\n n = fromIntegral $ G.length sample\n", "meta": {"hexsha": "580d00a95678d0a0f0752132e2ed62e7e6bb9783", "size": 5965, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Test/StudentT.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:39:40.000Z", "max_issues_repo_path": "Statistics/Test/StudentT.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T14:21:32.000Z", "max_forks_repo_path": "Statistics/Test/StudentT.hs", "max_forks_repo_name": "infinity0/statistics", "max_forks_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2015-02-13T00:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:19:16.000Z", "avg_line_length": 39.7666666667, "max_line_length": 110, "alphanum_fraction": 0.6124056999, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5964957836633825}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE ViewPatterns #-}\n\nimport Data.Maybe\nimport Numeric.Hamilton\nimport Numeric.LinearAlgebra.Static\nimport qualified Data.Vector.Sized as V\n\ntwoBody :: System 4 2\ntwoBody = mkSystem masses coordinates potential\n where\n masses :: R 4\n masses = vec4 10 10 1 1\n coordinates\n :: Floating a\n => V.Vector 2 a\n -> V.Vector 4 a\n coordinates (V2 r \u03b8) = V4 (r1 * cos \u03b8) (r1 * sin \u03b8)\n (r2 * cos \u03b8) (r2 * sin \u03b8)\n where\n r1 = r * 1 / 11\n r2 = - r * 10 / 11\n potential\n :: Fractional a\n => V.Vector 2 a\n -> a\n potential (V2 r _) = - 10 / r -- G = 1\n\npattern V2 :: a -> a -> V.Vector 2 a\npattern V2 x y <- (V.toList->[x,y])\n where\n V2 x y = fromJust (V.fromList [x,y])\n\npattern V4 :: a -> a -> a -> a -> V.Vector 4 a\npattern V4 x y z a <- (V.toList->[x,y,z,a])\n where\n V4 x y z a = fromJust (V.fromList [x,y,z,a])\n\nconfig0 :: Config 2\nconfig0 = Cfg (vec2 2 0) -- initial positions\n (vec2 0 0.5) -- initial velocities\n\nphase0 :: Phase 2\nphase0 = toPhase twoBody config0\n\nevolution :: [Phase 2]\nevolution = evolveHam' twoBody phase0 [0,0.1 .. 1]\n\nevolution' :: [Phase 2]\nevolution' = iterate (stepHam 0.1 twoBody) phase0\n\npositions :: [R 2]\npositions = phsPositions <$> evolution'\n\npositions' :: [R 4]\npositions' = underlyingPos twoBody <$> positions\n\nmain :: IO ()\nmain = withRows (take 25 positions) (disp 4)\n\n\n", "meta": {"hexsha": "53c11bcb6e7f954943571dc764c008bcd010f2b3", "size": 1558, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "code-samples/hamilton/TwoBody.hs", "max_stars_repo_name": "mstksg/inCode", "max_stars_repo_head_hexsha": "e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2015-01-23T14:58:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:18:48.000Z", "max_issues_repo_path": "code-samples/hamilton/TwoBody.hs", "max_issues_repo_name": "mstksg/inCode", "max_issues_repo_head_hexsha": "e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2016-05-25T21:35:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-28T22:26:17.000Z", "max_forks_repo_path": "code-samples/hamilton/TwoBody.hs", "max_forks_repo_name": "mstksg/inCode", "max_forks_repo_head_hexsha": "e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2015-05-12T05:29:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:24.000Z", "avg_line_length": 24.7301587302, "max_line_length": 55, "alphanum_fraction": 0.5629011553, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5964957621782258}} {"text": "module Main where\n\nimport qualified Numeric.LinearAlgebra.Data\n\nimport Optimization.Types\nimport Optimization.NelderMead\n\ntrivialOpt :: Vector Double -> Double\ntrivialOpt v\n | length v != 3 = error \"Vector is not length-3!\"\n | otherwise = ((v ! 0)**2) * (((v ! 1) - 1)**2) * (((v ! 2) - 2) ** 2)\n\nmain :: IO ()\nmain = do\n let\n tc = terminateAtOrAfter 0.001 1000\n optimum = nelderMead tc trivialOpt (fromList [10.0, 12.1, -4.4])\n\n putStrLn $ show optimum\n \n \n \n", "meta": {"hexsha": "d7f7aa71ac309f5796eba9290a9234681aba1591", "size": 486, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "agbrooks/buzzwords", "max_stars_repo_head_hexsha": "89fa4ef0dc5a2317b6f19bd05f1d44a5b7aa9763", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-10-10T07:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-10T07:11:28.000Z", "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "agbrooks/buzzwords", "max_issues_repo_head_hexsha": "89fa4ef0dc5a2317b6f19bd05f1d44a5b7aa9763", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main.hs", "max_forks_repo_name": "agbrooks/buzzwords", "max_forks_repo_head_hexsha": "89fa4ef0dc5a2317b6f19bd05f1d44a5b7aa9763", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1304347826, "max_line_length": 76, "alphanum_fraction": 0.621399177, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.6893056040203136, "lm_q1q2_score": 0.5964038016670804}} {"text": "{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RecordWildCards #-}\n\n-- |\n-- Module : Statistics.Distribution.Normal\n-- Copyright : (c) 2021 Alexander E. Zarebski\n-- License : MIT\n--\n-- Maintainer : aezarebski@gmail.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- The lognormal distribution.\n\nmodule Statistics.Distribution.Lognormal\n (\n LognormalDistribution\n -- * constructors\n , lognormalDistr\n , lognormalDistrE\n ) where\n\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.MathFunctions.Constants (m_sqrt_2, m_sqrt_2_pi)\nimport Numeric.SpecFunctions (erf, invErf)\n\nimport qualified Statistics.Distribution as D\n\n\n-- | The lognormal distribution.\ndata LognormalDistribution = LND {\n meanlog :: {-# UNPACK #-} !Double\n , sdlog :: {-# UNPACK #-} !Double\n } deriving (Eq, Typeable, Data, Generic)\n\ninstance D.Distribution LognormalDistribution where\n cumulative = cumulative\n\ninstance D.ContDistr LognormalDistribution where\n logDensity = logDensity\n quantile = quantile\n\ninstance D.MaybeMean LognormalDistribution where\n maybeMean = Just . D.mean\n\ninstance D.Mean LognormalDistribution where\n mean LND {..} = exp (meanlog + 0.5 * sdlog ** 2.0)\n\ninstance D.MaybeVariance LognormalDistribution where\n maybeStdDev = Just . D.stdDev\n maybeVariance = Just . D.variance\n\ninstance D.Variance LognormalDistribution where\n variance LND {..} = exp (2.0 * meanlog + sdlog ** 2.0) * (exp (sdlog ** 2.0) - 1)\n\n-- | Create lognormal distribution from parameters.\nlognormalDistr :: Double -- ^ Mean of the logarithm\n -> Double -- ^ Standard deviation of the logarithm\n -> LognormalDistribution\nlognormalDistr m sd = maybe (error $ errMsg m sd) id $ lognormalDistrE m sd\n\n-- | Create normal distribution from parameters.\nlognormalDistrE :: Double -- ^ Mean of logarithm\n -> Double -- ^ Standard deviation of logarithm\n -> Maybe LognormalDistribution\nlognormalDistrE mln sdln\n | sdln > 0 = Just LND { meanlog = mln\n , sdlog = sdln\n }\n | otherwise = Nothing\n\nerrMsg :: Double -> Double -> String\nerrMsg _ sd = \"Statistics.Distribution.Lognormal.lognormalDistr: standard deviation must be positive. Got \" ++ show sd\n\nlogDensity :: LognormalDistribution -> Double -> Double\nlogDensity LND {..} x = - (log x - meanlog) ** 2.0 / (2 * sdlog ** 2.0) - log (x * sdlog * m_sqrt_2_pi)\n\ncumulative :: LognormalDistribution -> Double -> Double\ncumulative LND {..} x = 0.5 * (1 + erf ((log x - meanlog) / (sdlog * m_sqrt_2)))\n\nquantile :: LognormalDistribution -> Double -> Double\nquantile LND {..} p\n | p == 0 = 0\n | p == 1 = inf\n | p == 0.5 = exp meanlog\n | p > 0 && p < 1 = exp (meanlog + sdlog * m_sqrt_2 * invErf (2 * p - 1))\n | otherwise = error $ \"Statistics.Distribution.Lognormal.quantile: p must be in [0,1] range. Got: \"++show p\n where inf = 1/0\n", "meta": {"hexsha": "96dec7e2385f72a3a9aa6c425428980919ddd5eb", "size": 3192, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Distribution/Lognormal.hs", "max_stars_repo_name": "aezarebski/timtam", "max_stars_repo_head_hexsha": "dc0f00a0196045bbc60d81a33a217e5d8e79e489", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-21T01:07:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T01:07:59.000Z", "max_issues_repo_path": "src/Statistics/Distribution/Lognormal.hs", "max_issues_repo_name": "aezarebski/timtam", "max_issues_repo_head_hexsha": "dc0f00a0196045bbc60d81a33a217e5d8e79e489", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-21T01:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T01:19:37.000Z", "max_forks_repo_path": "src/Statistics/Distribution/Lognormal.hs", "max_forks_repo_name": "aezarebski/timtam", "max_forks_repo_head_hexsha": "dc0f00a0196045bbc60d81a33a217e5d8e79e489", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6956521739, "max_line_length": 118, "alphanum_fraction": 0.6318922306, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5963135009828042}} {"text": "module Statistics.Information.Continuous.Entropy where\n\nimport Data.Matrix\nimport Numeric.SpecFunctions\nimport Statistics.Information.Utils.KNN\nimport Statistics.Information.Utils.Random\nimport System.Random\n\nentropy :: RandomGen g => g -> Int -> Int -> Matrix Double -> Double\nentropy g k base xs | k < nrows xs =\n let noised = toLists $ noisy g xs\n distances = knnDistances chebyshevDistance noised k in\n (const + (fromIntegral d) * mean (map log distances)) /\n (log $ fromIntegral base)\n where\n d = ncols xs\n n = nrows xs\n const = digamma (fromIntegral n) - digamma (fromIntegral k) +\n (fromIntegral d) * log 2\n mean xs = sum xs / (fromIntegral $ length xs)\n\ncentropy :: RandomGen g => g -> Int -> Int -> Matrix Double -> Matrix Double ->\n Double\ncentropy g k base xs ys = joint - hy where\n joint = entropy g1 k base (xs <|> ys)\n hy = entropy g2 k base ys\n (g1, g2) = split g\n", "meta": {"hexsha": "ee7cb1dfcd5956ab4430213cc28f26a5b257f7fb", "size": 929, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Information/Continuous/Entropy.hs", "max_stars_repo_name": "eligottlieb/Shannon", "max_stars_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/Information/Continuous/Entropy.hs", "max_issues_repo_name": "eligottlieb/Shannon", "max_issues_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Information/Continuous/Entropy.hs", "max_forks_repo_name": "eligottlieb/Shannon", "max_forks_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1785714286, "max_line_length": 79, "alphanum_fraction": 0.6716899892, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5960849120749024}} {"text": "-- https://github.com/minoki/my-atcoder-solutions\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE NoStarIsType #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\nimport Control.Exception (assert)\nimport Control.Monad\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char (isSpace)\nimport Data.Coerce\nimport Data.Complex\nimport Data.Int (Int64)\nimport Data.List (unfoldr)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxing as U\nimport qualified Data.Vector.Unboxing.Mutable as UM\nimport GHC.TypeNats (type (+), type (*), KnownNat, Nat, type (^),\n natVal)\n\ntype R1 = IntMod (5 * 2^25 + 1)\ntype R2 = IntMod (7 * 2^26 + 1)\ntype R3 = IntMod (3 * 2^18 + 1)\ntype R4 = IntMod (7 * 2^20 + 1)\ntype R5 = IntMod (483 * 2^21 + 1)\n\norder :: (Num a, Eq a) => a -> Int\norder !x = go 1 x\n where\n go !n 1 = n\n go !n y = go (n + 1) (x * y)\n\norder' :: (Num a, Eq a) => Int -> a -> Int\norder' !m !x = go 1 x\n where\n go !n 1 = n\n go !n y | n > m = m + 1\n go !n y = go (n + 1) (x * y)\n\nfindPrimitiveNthRoot :: (Num a, Eq a) => Int -> a\nfindPrimitiveNthRoot n = head [ x | k <- [1..], let x = fromInteger k, order' n x == n ]\n\nmain = do\n -- print (findPrimitiveNthRoot 2)\n -- print (findPrimitiveNthRoot (2^10))\n print (findPrimitiveNthRoot (2^25) :: R1) -- 17 mod 5 * 2^25 + 1\n print (findPrimitiveNthRoot (2^26) :: R2) -- 30 mod 7 * 2^26 + 1\n print (findPrimitiveNthRoot (2^18) :: R3) -- 5 mod 3 * 2^18 + 1\n print (findPrimitiveNthRoot (2^20) :: R4) -- 5 mod 7 * 2^20 + 1\n print (findPrimitiveNthRoot (2^21) :: R5) -- 198 mod 483 * 2^21 + 1\n\n--\n-- Fast Fourier Transform (FFT)\n--\n\nhalve :: G.Vector vec a => vec a -> vec a\nhalve v = let n = G.length v\n in G.generate (n `quot` 2) $ \\j -> v G.! (j * 2)\n\nfft :: forall vec a. (Num a, G.Vector vec a)\n => [vec a] -- ^ For a primitive n-th root of unity @u@, @iterate halve [1,u,u^2 .. u^(n-1)]@\n -> vec a -- ^ a polynomial of length n (= 2^k for some k)\n -> vec a\nfft (u:u2) f | n == 1 = f\n | otherwise = let !n2 = n `quot` 2\n r0, r1', t0, t1' :: vec a\n r0 = G.generate n2 $ \\j -> (f G.! j) + (f G.! (j + n2))\n r1' = G.generate n2 $ \\j -> ((f G.! j) - (f G.! (j + n2))) * u G.! j\n !t0 = fft u2 r0\n !t1' = fft u2 r1'\n in G.generate n $ \\j -> if even j then t0 G.! (j `quot` 2) else t1' G.! (j `quot` 2)\n where n = G.length f\n\nmulFFT :: U.Vector Int -> U.Vector Int -> U.Vector Int\nmulFFT !f !g = let n' = U.length f + U.length g - 2\n k = finiteBitSize n' - countLeadingZeros n'\n !_ = assert (n' < 2^k) ()\n n = bit k\n u :: U.Vector (Complex Double)\n u = U.generate n $ \\j -> cis (fromIntegral j * (2 * pi / fromIntegral n))\n us = iterate halve u\n f' = U.generate n $ \\j -> if j < U.length f then\n fromIntegral (f U.! j)\n else\n 0\n g' = U.generate n $ \\j -> if j < U.length g then\n fromIntegral (g U.! j)\n else\n 0\n f'' = fft us f'\n g'' = fft us g'\n fg = U.generate n $ \\j -> (f'' U.! j) * (g'' U.! j)\n fg' = fft (map (U.map conjugate) us) fg\n in U.generate n $ \\j -> round (realPart (fg' U.! j) / fromIntegral n)\n\n--\n-- Univariate polynomial\n--\n\nnewtype Poly vec a = Poly { coeffAsc :: vec a } deriving Eq\n\nnormalizePoly :: (Eq a, Num a, G.Vector vec a) => vec a -> vec a\nnormalizePoly v | G.null v || G.last v /= 0 = v\n | otherwise = normalizePoly (G.init v)\n\naddPoly :: (Eq a, Num a, G.Vector vec a) => vec a -> vec a -> vec a\naddPoly v w = case compare n m of\n LT -> G.generate m $ \\i -> if i < n\n then v G.! i + w G.! i\n else w G.! i\n GT -> G.generate n $ \\i -> if i < m\n then v G.! i + w G.! i\n else v G.! i\n EQ -> normalizePoly $ G.zipWith (+) v w\n where n = G.length v\n m = G.length w\n\nsubPoly :: (Eq a, Num a, G.Vector vec a) => vec a -> vec a -> vec a\nsubPoly v w = case compare n m of\n LT -> G.generate m $ \\i -> if i < n\n then v G.! i - w G.! i\n else negate (w G.! i)\n GT -> G.generate n $ \\i -> if i < m\n then v G.! i - w G.! i\n else v G.! i\n EQ -> normalizePoly $ G.zipWith (-) v w\n where n = G.length v\n m = G.length w\n\nnaiveMulPoly :: (Num a, G.Vector vec a) => vec a -> vec a -> vec a\nnaiveMulPoly v w = G.generate (n + m - 1) $\n \\i -> sum [(v G.! (i-j)) * (w G.! j) | j <- [max (i-n+1) 0..min i (m-1)]]\n where n = G.length v\n m = G.length w\n\ndoMulP :: (Eq a, Num a, G.Vector vec a) => Int -> vec a -> vec a -> vec a\ndoMulP n !v !w | n <= 16 = naiveMulPoly v w\ndoMulP n !v !w\n | G.null v = v\n | G.null w = w\n | G.length v < n2 = let (w0, w1) = G.splitAt n2 w\n u0 = doMulP n2 v w0\n u1 = doMulP n2 v w1\n in G.generate (G.length v + G.length w - 1)\n $ \\i -> case () of\n _ | i < n2 -> u0 `at` i\n | i < n -> (u0 `at` i) + (u1 `at` (i - n2))\n | i < n + n2 -> (u1 `at` (i - n2))\n | G.length w < n2 = let (v0, v1) = G.splitAt n2 v\n u0 = doMulP n2 v0 w\n u1 = doMulP n2 v1 w\n in G.generate (G.length v + G.length w - 1)\n $ \\i -> case () of\n _ | i < n2 -> u0 `at` i\n | i < n -> (u0 `at` i) + (u1 `at` (i - n2))\n | i < n + n2 -> (u1 `at` (i - n2))\n | otherwise = let (v0, v1) = G.splitAt n2 v\n (w0, w1) = G.splitAt n2 w\n v0_1 = v0 `addPoly` v1\n w0_1 = w0 `addPoly` w1\n p = doMulP n2 v0_1 w0_1\n q = doMulP n2 v0 w0\n r = doMulP n2 v1 w1\n -- s = (p `subPoly` q) `subPoly` r -- p - q - r\n -- q + s*X^n2 + r*X^n\n in G.generate (G.length v + G.length w - 1)\n $ \\i -> case () of\n _ | i < n2 -> q `at` i\n | i < n -> ((q `at` i) + (p `at` (i - n2))) - ((q `at` (i - n2)) + (r `at` (i - n2)))\n | i < n + n2 -> ((r `at` (i - n)) + (p `at` (i - n2))) - ((q `at` (i - n2)) + (r `at` (i - n2)))\n | otherwise -> r `at` (i - n)\n where n2 = n `quot` 2\n at :: (Num a, G.Vector vec a) => vec a -> Int -> a\n at v i = if i < G.length v then v G.! i else 0\n{-# INLINE doMulP #-}\n\nmulPoly :: (Eq a, Num a, G.Vector vec a) => vec a -> vec a -> vec a\nmulPoly !v !w = let k = ceiling ((log (fromIntegral (max n m)) :: Double) / log 2) :: Int\n in doMulP (2^k) v w\n where n = G.length v\n m = G.length w\n{-# INLINE mulPoly #-}\n\nzeroPoly :: (G.Vector vec a) => Poly vec a\nzeroPoly = Poly G.empty\n\nconstPoly :: (Eq a, Num a, G.Vector vec a) => a -> Poly vec a\nconstPoly 0 = Poly G.empty\nconstPoly x = Poly (G.singleton x)\n\nscalePoly :: (Eq a, Num a, G.Vector vec a) => a -> Poly vec a -> Poly vec a\nscalePoly a (Poly xs)\n | a == 0 = zeroPoly\n | otherwise = Poly $ G.map (* a) xs\n\nvalueAtPoly :: (Num a, G.Vector vec a) => Poly vec a -> a -> a\nvalueAtPoly (Poly xs) t = G.foldr' (\\a b -> a + t * b) 0 xs\n\ninstance (Eq a, Num a, G.Vector vec a) => Num (Poly vec a) where\n (+) = coerce (addPoly :: vec a -> vec a -> vec a)\n (-) = coerce (subPoly :: vec a -> vec a -> vec a)\n negate (Poly v) = Poly (G.map negate v)\n (*) = coerce (mulPoly :: vec a -> vec a -> vec a)\n fromInteger = constPoly . fromInteger\n abs = undefined; signum = undefined\n\ndivModPoly :: (Eq a, Fractional a, G.Vector vec a) => Poly vec a -> Poly vec a -> (Poly vec a, Poly vec a)\ndivModPoly f g@(Poly w)\n | G.null w = error \"divModPoly: divide by zero\"\n | degree f < degree g = (zeroPoly, f)\n | otherwise = loop zeroPoly (scalePoly (recip b) f)\n where\n g' = toMonic g\n b = leadingCoefficient g\n -- invariant: f == q * g + scalePoly b p\n loop q p | degree p < degree g = (q, scalePoly b p)\n | otherwise = let q' = Poly (G.drop (degree' g) (coeffAsc p))\n in loop (q + q') (p - q' * g')\n\n toMonic :: (Fractional a, G.Vector vec a) => Poly vec a -> Poly vec a\n toMonic f@(Poly xs)\n | G.null xs = zeroPoly\n | otherwise = Poly $ G.map (* recip (leadingCoefficient f)) xs\n\n leadingCoefficient :: (Num a, G.Vector vec a) => Poly vec a -> a\n leadingCoefficient (Poly xs)\n | G.null xs = 0\n | otherwise = G.last xs\n\n degree :: G.Vector vec a => Poly vec a -> Maybe Int\n degree (Poly xs) = case G.length xs - 1 of\n -1 -> Nothing\n n -> Just n\n\n degree' :: G.Vector vec a => Poly vec a -> Int\n degree' (Poly xs) = case G.length xs of\n 0 -> error \"degree': zero polynomial\"\n n -> n - 1\n\n-- \u7d44\u7acb\u9664\u6cd5\n-- second constPoly (divModByDeg1 f t) = divMod f (Poly (G.fromList [-t, 1]))\ndivModByDeg1 :: (Eq a, Num a, G.Vector vec a) => Poly vec a -> a -> (Poly vec a, a)\ndivModByDeg1 f t = let w = G.postscanr (\\a b -> a + b * t) 0 $ coeffAsc f\n in (Poly (G.tail w), G.head w)\n\n--\n-- Modular Arithmetic\n--\n\nnewtype IntMod (m :: Nat) = IntMod { unwrapN :: Int64 } deriving (Eq)\n\ninstance Show (IntMod m) where\n show (IntMod x) = show x\n\ninstance KnownNat m => Num (IntMod m) where\n t@(IntMod x) + IntMod y\n | x + y >= modulus = IntMod (x + y - modulus)\n | otherwise = IntMod (x + y)\n where modulus = fromIntegral (natVal t)\n t@(IntMod x) - IntMod y\n | x >= y = IntMod (x - y)\n | otherwise = IntMod (x - y + modulus)\n where modulus = fromIntegral (natVal t)\n t@(IntMod x) * IntMod y = IntMod ((x * y) `rem` modulus)\n where modulus = fromIntegral (natVal t)\n fromInteger n = let result = IntMod (fromInteger (n `mod` fromIntegral modulus))\n modulus = natVal result\n in result\n abs = undefined; signum = undefined\n\n{-# RULES\n\"^9/Int\" forall x. x ^ (9 :: Int) = let u = x; v = u * u * u in v * v * v\n\"^9/Integer\" forall x. x ^ (9 :: Integer) = let u = x; v = u * u * u in v * v * v\n #-}\n\nfromIntegral_Int64_IntMod :: KnownNat m => Int64 -> IntMod m\nfromIntegral_Int64_IntMod n = result\n where\n result | 0 <= n && n < modulus = IntMod n\n | otherwise = IntMod (n `mod` modulus)\n modulus = fromIntegral (natVal result)\n\n{-# RULES\n\"fromIntegral/Int->IntMod\" fromIntegral = fromIntegral_Int64_IntMod . (fromIntegral :: Int -> Int64) :: Int -> IntMod (10^9 + 7)\n\"fromIntegral/Int64->IntMod\" fromIntegral = fromIntegral_Int64_IntMod :: Int64 -> IntMod (10^9 + 7)\n #-}\n\ninstance U.Unboxable (IntMod m) where\n type Rep (IntMod m) = Int64\n\nexEuclid :: (Eq a, Integral a) => a -> a -> (a, a, a)\nexEuclid !f !g = loop 1 0 0 1 f g\n where loop !u0 !u1 !v0 !v1 !f 0 = (f, u0, v0)\n loop !u0 !u1 !v0 !v1 !f g =\n case divMod f g of\n (q,r) -> loop u1 (u0 - q * u1) v1 (v0 - q * v1) g r\n\ninstance KnownNat m => Fractional (IntMod m) where\n recip t@(IntMod x) = IntMod $ case exEuclid x modulus of\n (1,a,_) -> a `mod` modulus\n (-1,a,_) -> (-a) `mod` modulus\n _ -> error \"not invertible\"\n where modulus = fromIntegral (natVal t)\n fromRational = undefined\n\nrecipM :: (Eq a, Integral a, Show a) => a -> a -> a\nrecipM !x modulo = case exEuclid x modulo of\n (1,a,_) -> a `mod` modulo\n (-1,a,_) -> (-a) `mod` modulo\n (g,a,b) -> error $ show x ++ \"^(-1) mod \" ++ show modulo ++ \" failed: gcd=\" ++ show g\n\n-- |\n-- >>> crt 3 6 2 7\n-- 9\n-- >>> crt 2 5 3 9\n-- 12\ncrt :: Int64 -> Int64 -> Int64 -> Int64 -> Int64\ncrt !a1 !m1 !a2 !m2 = let m1' = recipM m1 m2\n m2' = recipM m2 m1\n in (m2 * m2' * a1 + m1 * m1' * a2) `mod` (m1 * m2)\n", "meta": {"hexsha": "21c26845aecba8d005ce8bdbd64e0f6b6e168e0d", "size": 13197, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "atc001-c/PrepareNTT.hs", "max_stars_repo_name": "minoki/my-atcoder-solutions", "max_stars_repo_head_hexsha": "b571a65bae7794b315e39b95ab1b2b62706f3aaa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-25T01:44:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T06:53:26.000Z", "max_issues_repo_path": "atc001-c/PrepareNTT.hs", "max_issues_repo_name": "minoki/my-atcoder-solutions", "max_issues_repo_head_hexsha": "b571a65bae7794b315e39b95ab1b2b62706f3aaa", "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": "atc001-c/PrepareNTT.hs", "max_forks_repo_name": "minoki/my-atcoder-solutions", "max_forks_repo_head_hexsha": "b571a65bae7794b315e39b95ab1b2b62706f3aaa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6061538462, "max_line_length": 128, "alphanum_fraction": 0.4612411912, "num_tokens": 4177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5957427985567748}} {"text": "{-|\nModule : Approx\nDescription : Implement Approx for Double, Floats and structures\nCopyright : (c) 2020 Kishaloy Neogi\nLicense : MIT\nMaintainer : Kishaloy Neogi\nEmail : nkishaloy@yahoo.com\n\nThe library is created to allow for a easy-to-use reasonable way of emulating approx in Haskell. The codes are all in /pure/ Haskell. The idea is to have a natural mathematical feel in writing code, with operators which just works when working with Double and Float and their composite types like lists, vectors etc. \n\nThe __Approx__ module defines 2 operators __@=~@__ and __@/~@__, which are for checking /nearly equal to/ and /not nearly equal to/ respectively. \n\nBoth the operators __=~__ and __/~__ are put under the class __Approx__. \n\nAt least one of the operators have to be defined and the other gets automatically defined. \n\nThe library already defines the functions for some of the basic / common types. \n\nFor types where __Eq__ is defined like __Char, Bool, Int, Day, Text__ the approx is simply replaced with __==__. \n\nFor __Float__ and __Double__, the following formula is used, \n\n@\nif max ( |x|, |y| ) < epsilon_Zero\nthen True\nelse \n if |x - y| / max ( |x|, |y| ) < epsilon_Eq\n then True\n else False\n@\n\nThe motivation for defining Approx for classes for which Eq is also defined is to allow for composite types where both Eq and Approx would be present. For example, the following code evaluates to __@True@__, even though the tuple is of type @(Int,Double,Text,[Int],[[Char]],[Double])@.\n\n@\n((2,5.35,\"happ\",[1,2],[\"ret\",\"we\"],[6.78,3.5]) \n :: (Int,Double,Text,[Int],[[Char]],[Double])) \n \n =~ (2,5.35,\"happ\",[1,2],[\"ret\",\"we\"],[6.78,3.5])\n@\n\nFor UTCTime, the approx operator checks for equality to the nearest minute. The following expression evaluates to __@True@__.\n\n@\n(parseTimeM True defaultTimeLocale \"%Y-%m-%d %H:%M:%S\" \"2020-01-15 15:02:15\" \n :: Maybe UTCTime) \n\n =~ parseTimeM True defaultTimeLocale \"%Y-%m-%d %H:%M:%S\" \"2020-01-15 15:01:50\"\n@\n\nThe library also provides approx for Complex and common structures like __List, Boxed and Unboxed Vector, Hashmap, Tuples__ and __Maybe__. For all lists, tuples, hashmaps and vectors, the approximation is checked right down to the elements and the order for lists and vectors are important. \n\nFor lists, only finite lists are supported. Any use of infinite lists would cause a runtime error.\n\nThere are addtional functions __inRange__, __safeInRange__ and __inTol__, which checks for values within Ranges either /explictily/ defined as in __inRange__ and __safeInRange__ or through tolerances as in __inTol__.\n\nYou may see the github repository at \n\n-}\n\n{-# LANGUAGE Strict #-}\n\nmodule Data.Approx\n( \n-- *How to use this library\n-- |Add @approx@ to build-depends and @import Data.Approx@\n\n-- *Documentation\n Approx (..)\n, inRange, safeInRange, inTol\n\n) where\n\nimport Data.List (foldl')\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Unboxed.Mutable as M\nimport qualified Data.Vector as V\nimport Data.Time (Day, UTCTime)\nimport Data.Time.Clock (diffUTCTime)\nimport qualified Data.HashMap.Strict as Hm\nimport Data.Hashable\n\nimport Data.Text (Text)\nimport qualified Data.Complex as Cx\nimport Data.Complex (Complex ( (:+) ) )\n\neZerD :: Double\neZerD = 1e-8; {-# INLINE eZerD #-}\n\neEqD :: Double\neEqD = 1e-7; {-# INLINE eEqD #-}\n\neZerF :: Float\neZerF = 1e-6; {-# INLINE eZerF #-}\n\neEqF :: Float\neEqF = 1e-5; {-# INLINE eEqF #-}\n\ninfix 4 =~, /~\n\n-- |The class @Approx@ defines 2 operators __@=~@__ and __@/~@__, which are for checking /nearly equal to/ and /not nearly equal to/ respectively.\nclass Approx a where \n (=~), (/~) :: a -> a -> Bool \n \n (=~) x y = not (x /~ y)\n {-# INLINE (=~) #-}\n (/~) x y = not (x =~ y)\n {-# INLINE (/~) #-}\n\n {-# MINIMAL (=~) | (/~) #-}\n\ninstance Approx Day where x =~ y = x == y; {-# INLINE (=~) #-}\n\ninstance Approx Char where x =~ y = x == y; {-# INLINE (=~) #-}\n\ninstance Approx Bool where x =~ y = x == y; {-# INLINE (=~) #-}\n\ninstance Approx Text where x =~ y = x == y; {-# INLINE (=~) #-}\n\ninstance Approx Int where x =~ y = x == y; {-# INLINE (=~) #-}\n\ninstance Approx Integer where x =~ y = x == y; {-# INLINE (=~) #-}\n\n\ninstance Approx UTCTime where \n x =~ y = (round . (/60.0) . realToFrac $ x `diffUTCTime` y) == 0\n {-# INLINE (=~) #-}\n\ninstance Approx a => Approx (Cx.Complex a) where\n (a :+ b) =~ (x :+ y) = (a =~ x) && (b =~ y); {-# INLINE (=~) #-}\n\ninstance Approx Float where\n x =~ y = (mx < eZerF) || abs (x-y) / mx < eEqF where mx = max (abs x) (abs y)\n {-# INLINE (=~) #-}\n\ninstance Approx Double where\n x =~ y = (mx < eZerD) || abs (x-y) / mx < eEqD where mx = max (abs x) (abs y)\n {-# INLINE (=~) #-}\n\ninstance Approx a => Approx (Maybe a) where\n Nothing =~ Nothing = True\n Just x =~ Just y = x =~ y \n _ =~ _ = False\n {-# INLINE (=~) #-}\n\ninstance Approx a => Approx [a] where \n x =~ y = (length x == length y) && and (zipWith (=~) x y)\n\ninstance (Approx a, Approx b) => Approx (a, b) where\n (x,y) =~ (a,b) = \n ( (x =~ a) \n && (y =~ b)\n )\n {-# INLINE (=~) #-}\n\ninstance (Approx a, Approx b, Approx c) => Approx (a, b, c) where\n (x,y,z) =~ (a,b,c) = \n ( (x =~ a) \n && (y =~ b) \n && (z =~ c)\n )\n {-# INLINE (=~) #-}\n\ninstance (Approx a,Approx b,Approx c,Approx d) => Approx (a,b,c,d) where\n (x,y,z,u) =~ (a,b,c,d) = \n ( (x =~ a) \n && (y =~ b) \n && (z =~ c) \n && (u =~ d)\n )\n {-# INLINE (=~) #-}\n\ninstance (Approx a,Approx b,Approx c,Approx d, Approx e) => Approx (a,b,c,d,e) where\n (x,y,z,u,v) =~ (a,b,c,d,e) = \n ( (x =~ a) \n && (y =~ b) \n && (z =~ c) \n && (u =~ d) \n && (v =~ e)\n )\n {-# INLINE (=~) #-}\n\ninstance (Approx a,Approx b,Approx c,Approx d, Approx e, Approx f) => Approx (a,b,c,d,e,f) where\n (x,y,z,u,v,w) =~ (a,b,c,d,e,f) = \n ( (x =~ a) \n && (y =~ b) \n && (z =~ c) \n && (u =~ d) \n && (v =~ e) \n && (w =~ f)\n )\n {-# INLINE (=~) #-}\n\ninstance (Approx a,Approx b,Approx c,Approx d, Approx e, Approx f, Approx g) => Approx (a,b,c,d,e,f,g) where\n (x,y,z,u,v,w,p) =~ (a,b,c,d,e,f,g) = \n ( (x =~ a) \n && (y =~ b) \n && (z =~ c) \n && (u =~ d) \n && (v =~ e) \n && (w =~ f) \n && (p =~ g)\n )\n {-# INLINE (=~) #-}\n\ninstance (Approx a,Approx b,Approx c,Approx d, Approx e, Approx f, Approx g, Approx h) => Approx (a,b,c,d,e,f,g,h) where\n (x,y,z,u,v,w,p,q) =~ (a,b,c,d,e,f,g,h) = \n ( (x =~ a) \n && (y =~ b) \n && (z =~ c) \n && (u =~ d) \n && (v =~ e) \n && (w =~ f) \n && (p =~ g) \n && (q =~ h)\n )\n {-# INLINE (=~) #-}\n\ninstance (Approx a,Approx b,Approx c,Approx d, Approx e, Approx f, Approx g, Approx h, Approx i) => Approx (a,b,c,d,e,f,g,h,i) where\n (x,y,z,u,v,w,p,q,r) =~ (a,b,c,d,e,f,g,h,i) = \n ( (x =~ a) \n && (y =~ b) \n && (z =~ c) \n && (u =~ d) \n && (v =~ e) \n && (w =~ f) \n && (p =~ g) \n && (q =~ h) \n && (r =~ i)\n )\n {-# INLINE (=~) #-}\n\ninstance (Approx a,Approx b,Approx c,Approx d, Approx e, Approx f, Approx g, Approx h, Approx i, Approx j) => Approx (a,b,c,d,e,f,g,h,i,j) where\n (x,y,z,u,v,w,p,q,r,s) =~ (a,b,c,d,e,f,g,h,i,j) = \n ( (x =~ a) \n && (y =~ b) \n && (z =~ c) \n && (u =~ d) \n && (v =~ e) \n && (w =~ f) \n && (p =~ g) \n && (q =~ h) \n && (r =~ i) \n && (s =~ j)\n )\n {-# INLINE (=~) #-}\n\ninstance (Approx a,Approx b,Approx c,Approx d, Approx e, Approx f, Approx g, Approx h, Approx i, Approx j, Approx k) => Approx (a,b,c,d,e,f,g,h,i,j,k) where\n (x,y,z,u,v,w,p,q,r,s,t) =~ (a,b,c,d,e,f,g,h,i,j,k) = \n ( (x =~ a) \n && (y =~ b) \n && (z =~ c) \n && (u =~ d) \n && (v =~ e) \n && (w =~ f) \n && (p =~ g) \n && (q =~ h) \n && (r =~ i) \n && (s =~ j) \n && (t =~ k)\n )\n {-# INLINE (=~) #-}\n\ninstance (M.Unbox a, Approx a) => Approx (U.Vector a) where \n x =~ y = (U.length x == U.length y) && U.and (U.zipWith (=~) x y)\n\ninstance (Approx a) => Approx (V.Vector a) where \n x =~ y = (V.length x == V.length y) && V.and (V.zipWith (=~) x y)\n\ninstance (Eq a, Hashable a, Approx b) => Approx (Hm.HashMap a b) where\n x =~ y = fz x y && fz y x where\n fz p q = and $ (\\(k,v) -> Hm.lookup k p =~ Just v) <$> Hm.toList q\n\ninfix 4 `inRange`, `safeInRange`, `inTol`\n\n{-|@inRange (u,v) x = check if x is inside the range (u,v)@\n\nNote: The function __assumes @u < v@__. This is done to ensure speed of operations. Use safeInRange, otherwise. \n-}\ninRange :: Ord a => (a,a) -> a -> Bool\ninRange (u,v) x = (u <= x) && (x <= v)\n{-# INLINE inRange #-}\n\n{-|@safeInRange (u,v) x = check if x is inside the range (u,v)@\n\nNote: The function works even if u>v. However, it has addtional checks and is more expensive. Use only if you are not sure that u < v for your use-case. \n-}\nsafeInRange :: Ord a => (a,a) -> a -> Bool\nsafeInRange (u,v) = inRange $ if u a -> a -> a -> Bool \ninTol t a = inRange (a - t, a + t)\n{-# INLINE inTol #-}\n", "meta": {"hexsha": "079fcc6e684155079c839aa158f523010229ade2", "size": 9290, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Approx.hs", "max_stars_repo_name": "n-kishaloy/approx", "max_stars_repo_head_hexsha": "d035cf2ead25264c1e630689837ccf08c6edeff7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-16T10:46:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T10:46:52.000Z", "max_issues_repo_path": "src/Data/Approx.hs", "max_issues_repo_name": "n-kishaloy/approx", "max_issues_repo_head_hexsha": "d035cf2ead25264c1e630689837ccf08c6edeff7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-15T20:43:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-22T20:44:34.000Z", "max_forks_repo_path": "src/Data/Approx.hs", "max_forks_repo_name": "n-kishaloy/approx", "max_forks_repo_head_hexsha": "d035cf2ead25264c1e630689837ccf08c6edeff7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1744966443, "max_line_length": 317, "alphanum_fraction": 0.5551130248, "num_tokens": 3221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.5957167606209383}} {"text": "module Render(render) where\n \nimport Core\nimport Codec.Picture\nimport Codec.Picture.Types\nimport Control.Monad\nimport System.Random\nimport Control.Monad.Random\n\nimport Numeric.LinearAlgebra\n\ndeltas :: RenderSettings -> (Vec3, Vec3)\ndeltas settings =\n let\n scale_x = 1 / (fromIntegral (width settings) - 1)\n scale_y = 1 / (fromIntegral (height settings) - 1)\n dx = scale scale_x (topRight settings - topLeft settings)\n dy = scale scale_y (bottomRight settings - topRight settings)\n in (dx,dy)\n\ncalc_ray :: RenderSettings -> Int -> Int -> Ray\ncalc_ray settings x y =\n let\n (dx,dy) = deltas settings\n point = topLeft settings + scale (fromIntegral x) dx + scale (fromIntegral y) dy\n dir = point - origin settings\n in (Ray point dir) \n\n\nrender :: RenderSettings -> Scene -> IO DynamicImage\nrender settings scene = do\n mut_img <- createMutableImage (width settings) (height settings) (background settings)\n let pixels = [(x,y) | x <- [1..width settings], y <- [1..height settings]]\n let (dx,dy) = deltas settings\n forM_ pixels $ \\(x,y) -> do\n let (Ray point dir) = calc_ray settings x y\n colors <- forM [1..antialiasing settings] $ \\_ -> do\n kx <- randomRIO (-1,1)\n ky <- randomRIO (-1,1)\n gen <- getStdGen\n let ray' = Ray (point) (dir + scale kx dx + scale ky dy)\n let (color, gen') = runRand (traceRay (background settings) scene ray') gen\n setStdGen gen'\n return $! (1/fromIntegral (antialiasing settings),color)\n writePixel mut_img (x-1) (y-1) (weigh colors)\n img <- unsafeFreezeImage mut_img\n return $! ImageRGBF img\n\n", "meta": {"hexsha": "2c7c672590644fdfdcd845d87a14964bb8477158", "size": 1702, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Render.hs", "max_stars_repo_name": "danrocag/raytracer", "max_stars_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Render.hs", "max_issues_repo_name": "danrocag/raytracer", "max_issues_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Render.hs", "max_forks_repo_name": "danrocag/raytracer", "max_forks_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7346938776, "max_line_length": 90, "alphanum_fraction": 0.6310223267, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505273888289, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5956377451887245}} {"text": "-- Kolmogorov-Smirnov tests for distribution\n--\n-- Note that it's not most powerful test for normality.\nmodule MWC.KS (\n tests\n ) where\n\nimport qualified Data.Vector.Unboxed as U\n\nimport Statistics.Test.KolmogorovSmirnov\n\nimport Statistics.Types\nimport Statistics.Distribution\nimport Statistics.Distribution.Binomial\nimport Statistics.Distribution.Exponential\nimport Statistics.Distribution.Gamma\nimport Statistics.Distribution.Normal\nimport Statistics.Distribution.Uniform\nimport Statistics.Distribution.Beta\n\nimport qualified System.Random.MWC as MWC\nimport qualified System.Random.MWC.Distributions as MWC\n\nimport Test.HUnit hiding (Test)\nimport Test.Framework\nimport Test.Framework.Providers.HUnit\n\n\ntests :: MWC.GenIO -> Test.Framework.Test\ntests g = testGroup \"Kolmogorov-Smirnov\"\n [ testCase \"standard\" $ testKS standard MWC.standard g\n , testCase \"normal m=1 s=2\" $ testKS (normalDistr 1 2) (MWC.normal 1 2) g\n -- Gamma distribution\n , testCase \"gamma k=1 \u03b8=1\" $ testKS (gammaDistr 1 1 ) (MWC.gamma 1 1 ) g\n , testCase \"gamma k=0.3 \u03b8=0.4\" $ testKS (gammaDistr 0.3 0.4) (MWC.gamma 0.3 0.4) g\n , testCase \"gamma k=0.3 \u03b8=3\" $ testKS (gammaDistr 0.3 3 ) (MWC.gamma 0.3 3 ) g\n , testCase \"gamma k=3 \u03b8=0.4\" $ testKS (gammaDistr 3 0.4) (MWC.gamma 3 0.4) g\n , testCase \"gamma k=3 \u03b8=3\" $ testKS (gammaDistr 3 3 ) (MWC.gamma 3 3 ) g\n -- Uniform\n , testCase \"uniform -2 .. 3\" $ testKS (uniformDistr (-2) 3) (MWC.uniformR (-2,3)) g\n -- Exponential\n , testCase \"exponential l=1\" $ testKS (exponential 1) (MWC.exponential 1) g\n , testCase \"exponential l=3\" $ testKS (exponential 3) (MWC.exponential 3) g\n -- Beta\n , testCase \"beta a=0.3,b=0.5\" $ testKS (betaDistr 0.3 0.5) (MWC.beta 0.3 0.5) g\n , testCase \"beta a=0.1,b=0.8\" $ testKS (betaDistr 0.3 0.5) (MWC.beta 0.3 0.5) g\n , testCase \"beta a=0.8,b=0.1\" $ testKS (betaDistr 0.3 0.5) (MWC.beta 0.3 0.5) g\n ]\n\ntestKS :: (Distribution d) => d -> (MWC.GenIO -> IO Double) -> MWC.GenIO -> IO ()\ntestKS distr generator g = do\n sample <- U.replicateM 1000 (generator g)\n case kolmogorovSmirnovTest distr sample of\n Nothing -> assertFailure \"Not enough data to make test\"\n Just t\n | isSignificant (mkPValue 0.01) t == Significant\n -> assertFailure (\"KS test failed: \" ++ show t)\n | otherwise\n -> return ()\n", "meta": {"hexsha": "427bad05d08d7903a0705956724b6f733012c383", "size": 2438, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "mwc-random-bench/test/MWC/KS.hs", "max_stars_repo_name": "Shimuuar/mwc-random", "max_stars_repo_head_hexsha": "225bf0b24a7c85e603e5c3464657e3fa1fdebf92", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2015-04-02T06:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T22:39:12.000Z", "max_issues_repo_path": "mwc-random-bench/test/MWC/KS.hs", "max_issues_repo_name": "Shimuuar/mwc-random", "max_issues_repo_head_hexsha": "225bf0b24a7c85e603e5c3464657e3fa1fdebf92", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2015-01-03T22:19:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-08T17:21:51.000Z", "max_forks_repo_path": "mwc-random-bench/test/MWC/KS.hs", "max_forks_repo_name": "Shimuuar/mwc-random", "max_forks_repo_head_hexsha": "225bf0b24a7c85e603e5c3464657e3fa1fdebf92", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2015-03-28T17:28:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T14:15:18.000Z", "avg_line_length": 40.6333333333, "max_line_length": 90, "alphanum_fraction": 0.6558654635, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5956085235449244}} {"text": "{-# language TypeFamilies #-}\n{-# language FlexibleInstances #-}\n{-# language FlexibleContexts #-}\n\nmodule Geometry.Circle\n ( Circle, Circular (..)\n , trivialCircle, mkCircle\n ) where\n\nimport Data.Complex\nimport Data.Semigroup\nimport Geometry.Base\n\n\n-- | Class for circle and decorated circle\nclass (Trans c, Manifold c, Curve c, ClosedCurve c, Figure c) =>\n Circular c where\n {-# MINIMAL toCircle, asCircle #-}\n toCircle :: c -> Circle\n asCircle :: Circle -> c\n \n -- | Center of the circle.\n center :: c -> Cmp\n center = center . toCircle\n \n -- | Radius of the circle\n radius :: c -> Double\n radius = radius . toCircle\n \n -- | The angle of the starting point.\n phaseShift :: c -> Direction\n phaseShift = phaseShift . toCircle\n\n -- | The orientation of the circle (positive -- CCW).\n orientation :: c -> Direction\n orientation = orientation . toCircle\n\n-- | Represents a circle with given center, radius vector and tangent direction.\ndata Circle = Circle Cmp Cmp Double\n deriving Show\n\ninstance Circular Circle where\n toCircle = id\n asCircle = id\n center (Circle c _ _) = c\n radius (Circle _ r _) = norm r\n orientation (Circle _ _ o) = asDeg (signum o)\n phaseShift (Circle _ r _) = angle r\n\ninstance Circular c => Circular (Maybe c) where\n toCircle = maybe trivialCircle toCircle\n asCircle = Just . asCircle\n\n-- | The trivial circle with zero radius.\ntrivialCircle :: Circle\ntrivialCircle = mkCircle 0 0\n\n-- | The constructor for a circle with given center and radius.\n-- The radius-vector has zero angle, and circle is CCW-oriented.\nmkCircle :: Double -> Cmp -> Circle\nmkCircle r c = Circle c (r:+0) 1 \n\ninstance Eq Circle where\n c1 == c2 = radius c1 ~= radius c2 &&\n center c1 ~= center c2 &&\n phaseShift c1 ~= phaseShift c2 \n\n\ninstance Trans Circle where\n transform t (Circle c r o) = Circle c' r' o'\n where c' = transformCmp t c\n r' = transformCmp t (c + r) - c'\n o' = transformOrientation t * o\n\n\ninstance Manifold Circle where\n type Domain Circle = Cmp\n param c t = center c + mkPolar (radius c) (rad x)\n where\n ph = turns $ phaseShift c\n x = asTurns $ ph + t * deg (orientation c)\n \n project c p = turns (x - ph)\n where\n ph = phaseShift c\n x = orientation c * azimuth (center c) p \n\n isContaining c p = distance p (center c) ~= radius c\n unit _ = 2 * pi\n\n distanceTo p c = abs (distance p (center c) - radius c)\n\ninstance Curve Circle where\n normal c t = azimuth (center c) (c @-> t)\n tangent c t = normal c t + 90 * orientation c\n\n\ninstance ClosedCurve Circle where\n location c p = res\n where res | r' ~= radius c = OnCurve\n | r' < radius c = Inside\n | r' > radius c = Outside\n r' = distance (cmp p) (center c)\n\n\ninstance Figure Circle where\n isTrivial c = radius c <= 0\n refPoint = center\n box cir = ((Min x1, Min y1), (Max x2, Max y2))\n where c = center cir\n r = radius cir\n x1:+y1 = c-(r:+r)\n x2:+y2 = c+(r:+r)\n", "meta": {"hexsha": "59cf20a9a4e7f2cb12c76b76dd6bd7c306f8f8d1", "size": 3011, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Geometry/Circle.hs", "max_stars_repo_name": "MethaHardworker/geometry", "max_stars_repo_head_hexsha": "77c987e0704722636d7d00afa54e22295df3e428", "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": "Geometry/Circle.hs", "max_issues_repo_name": "MethaHardworker/geometry", "max_issues_repo_head_hexsha": "77c987e0704722636d7d00afa54e22295df3e428", "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": "Geometry/Circle.hs", "max_forks_repo_name": "MethaHardworker/geometry", "max_forks_repo_head_hexsha": "77c987e0704722636d7d00afa54e22295df3e428", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4122807018, "max_line_length": 80, "alphanum_fraction": 0.6350049817, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5955002220578898}} {"text": "{-# LANGUAGE OverloadedLists #-}\n{-# LANGUAGE Strict #-}\n\nmodule Main where\n\nimport qualified Data.ByteString as BS\nimport qualified Data.Vector as V\nimport Data.Vector (Vector)\n\nimport Control.Monad (replicateM)\nimport Control.Arrow ((&&&))\n-- import System.Random\n\nimport Linear.Trace\n\nimport Data.Vector.Split (chunksOf)\nimport Data.List (nub)\n\nimport Linear.Vector\n\n\nimport Net\nimport Dense --(softplus, sigmoid, reLU)\nimport Backprop (Net, computeNetState)\nimport Parser\nimport Utils\n\nimport System.Random.MWC\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal\n\nimport Control.DeepSeq (force)\nimport Control.Exception (evaluate)\n\nimageSize :: Int\nimageSize = 28*28\n\nstepSize :: Double\nstepSize = 0.1\n-- stepSize = 0.15\n\ngenWeight :: GenIO -> Int -> IO Double\ngenWeight gen numWeights = genContVar (normalDistr 0 (1/sqrt (fromIntegral numWeights))) gen\n\ngenBias :: GenIO -> Int -> IO Double\ngenBias gen _numWeights = genContVar (normalDistr 0 1) gen\n\nactFn :: Floating a => a -> a\nactFn = sigmoid\n\nboolToDouble :: Bool -> Double\nboolToDouble False = 0\nboolToDouble True = 1\n\ninstance Trace Vector where\n diagonal m =\n V.fromList $ map (\\i -> (m V.! i) V.! i) [0..size-1]\n where\n size = V.length m\n\nclassify :: Vector Double -> Vector Double\nclassify v =\n let idx = V.maxIndex v\n in fmap boolToDouble (oneHotEncode (fromIntegral idx))\n\nmain :: IO ()\nmain = do\n -- setStdGen (mkStdGen 200)\n -- setStdGen (mkStdGen 203)\n genIO <- createSystemRandom\n\n trainLabels0 <- parseLabels <$> BS.readFile \"images/train/train-labels-idx1-ubyte\"\n trainImages <- parseImages <$> BS.readFile \"images/train/train-images-idx3-ubyte\"\n\n testLabels0 <- parseLabels <$> BS.readFile \"images/test/t10k-labels-idx1-ubyte\"\n testImages <- parseImages <$> BS.readFile \"images/test/t10k-images-idx3-ubyte\"\n\n\n let trainLabels = fmap (fmap boolToDouble) trainLabels0\n testLabels = fmap (fmap boolToDouble) testLabels0\n\n let testSampleSize = 1000\n sampleTestImages = V.take testSampleSize testImages\n sampleTestLabels = V.take testSampleSize testLabels\n\n let trainLabelsAndImages\n = V.zip trainImages trainLabels\n\n initialNet <-\n initNet V.replicateM V.fromList imageSize [16, 16, 10] actFn (genWeight genIO) (genBias genIO)\n :: IO (Net Vector Double)\n\n minibatches <- evaluate $ force $ chunksOf 10 (V.take 700 trainLabelsAndImages)\n\n putStrLn \"Minibatches created.\"\n\n let trainedNet =\n -- train 50 stepSize initialNet (map V.fromList $ chunksOf 10 (take 700 trainLabelsAndImages))\n train 50 stepSize initialNet minibatches\n\n -- train 500 stepSize actFn initialNet [V.fromList $ take 3 trainLabelsAndImages]\n -- train 10 stepSize actFn initialNet (take 2 (map V.fromList $ chunksOf 200 trainLabelsAndImages))\n\n putStrLn \"Measuring training set accuracy...\"\n putStr \"Training accuracy: \"\n putStr (show (netTestAccuracy classify trainedNet (V.take 1000 trainImages) (V.take 1000 trainLabels)*100))\n putStrLn \"%\"\n\n putStrLn \"Measuring testing set accuracy...\"\n putStr \"Test accuracy: \"\n putStr (show (netTestAccuracy classify trainedNet sampleTestImages sampleTestLabels*100))\n putStrLn \"%\"\n\n", "meta": {"hexsha": "f7ffb245a8290aafe1faa9194ec71e9c986bfdc2", "size": 3357, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "roboguy13/digit-recog", "max_stars_repo_head_hexsha": "b60eba861cf51d48c1d6d84fd73f50d685ad0a17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "roboguy13/digit-recog", "max_issues_repo_head_hexsha": "b60eba861cf51d48c1d6d84fd73f50d685ad0a17", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main.hs", "max_forks_repo_name": "roboguy13/digit-recog", "max_forks_repo_head_hexsha": "b60eba861cf51d48c1d6d84fd73f50d685ad0a17", "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.4473684211, "max_line_length": 109, "alphanum_fraction": 0.690199583, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.595140702107594}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Common\n ( splitMatrixOfSamples\n , addOnesColumn\n , getDimensions\n , featureNormalize\n , sigmoid\n , sigmoidMatrix\n , regularizeCost\n , MinimizationOpts(..)\n ) where\n\nimport Numeric.LinearAlgebra.Data\n ( Matrix\n , R\n , Vector\n , (|||)\n , (\u00bf)\n , cmap\n , cols\n , flatten\n , fromList\n , fromLists\n , matrix\n , rows\n , toList\n , toLists\n , tr'\n )\nimport Numeric.LinearAlgebra (Container)\nimport Numeric.LinearAlgebra.Devel (foldVector)\n\ndata MinimizationOpts = MinimizationOpts\n { precision :: R\n , tolerance :: R\n , sizeOfFirstTrialStep :: R\n } deriving (Eq)\n\nsplitMatrixOfSamples :: Matrix R -> (Matrix R, Vector R)\nsplitMatrixOfSamples mx =\n let c = cols mx\n in (mx \u00bf [0 .. (c - 2)], flatten $ mx \u00bf [(c - 1)])\n\naddOnesColumn :: Matrix R -> Matrix R\naddOnesColumn mx = matrix 1 (replicate (rows mx) 1) ||| mx\n\ngetDimensions :: Matrix R -> (Int, Int)\ngetDimensions mx = (rows mx, cols mx)\n\nsigmoid :: R -> R\nsigmoid z = 1 / (1 + exp (-1 * z))\n\nsigmoidMatrix :: Container c R => c R -> c R\nsigmoidMatrix = cmap sigmoid\n\nregularizeCost :: Int -> Vector R -> R -> R -> R\nregularizeCost m theta lambda cost =\n let m' = fromIntegral m\n regVal = (foldVector (\\v accum -> (v ** 2) + accum) 0 theta)\n in cost + ((regVal * lambda) / (3 * m'))\n\nfeatureNormalize :: Matrix R -> Matrix R\nfeatureNormalize mx =\n let trMx = toLists $ tr' mx\n normalizedTrMx =\n zipWith\n (\\vals (mean, std) -> normalize mean std <$> vals)\n trMx\n (computeMeanAndStd <$> trMx)\n in tr' $ fromLists normalizedTrMx\n where\n computeMean vals =\n let (accum, n) = foldl (\\(v', n') v -> (v + v', n' + 1)) (0, 0) vals\n in (accum / n, n)\n computeStd n mn vals =\n let sumOfSquares =\n foldl (\\v' v -> ((v - mn) ** (2 :: Double)) + v') (0 :: Double) vals\n in sqrt $ sumOfSquares / (n - 1)\n computeMeanAndStd vals =\n let (mean, n) = computeMean vals\n std = computeStd n mean vals\n in (mean, std)\n normalize mean std val =\n if std == 0\n then mean\n else (val - mean) / std\n", "meta": {"hexsha": "c47a701ae1636d910eaeb8ccf0076d0c28b1236c", "size": 2126, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Common.hs", "max_stars_repo_name": "sebashack/mlToolBox", "max_stars_repo_head_hexsha": "b5566277833f5ec3341f2165f48cdc5429cbea7f", "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/Common.hs", "max_issues_repo_name": "sebashack/mlToolBox", "max_issues_repo_head_hexsha": "b5566277833f5ec3341f2165f48cdc5429cbea7f", "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/Common.hs", "max_forks_repo_name": "sebashack/mlToolBox", "max_forks_repo_head_hexsha": "b5566277833f5ec3341f2165f48cdc5429cbea7f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-03T23:48:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-07T22:33:11.000Z", "avg_line_length": 24.1590909091, "max_line_length": 80, "alphanum_fraction": 0.5931326435, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5950497892787515}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n\n-- |\n-- Module : Test.Factorization\n-- Copyright : (c) 2016-2020 Drexel University\n-- License : BSD-style\n-- Maintainer : mainland@drexel.edu\n\nmodule Test.Factorization (\n factorizationTests,\n f2Test,\n f4Test,\n f8Test,\n cooleyTukeyDITTest,\n cooleyTukeyDIFTest,\n goodThomasTest,\n raderTest,\n bluesteinTest,\n winogradSmallTest,\n ditTest,\n difTest,\n splitRadixTest,\n splitRadix8Test,\n conjPairSplitRadixTest,\n improvedSplitRadixTest,\n opcountSearchTest\n ) where\n\nimport Data.Complex\nimport Data.Modular\nimport Data.Proxy (Proxy(..))\nimport Test.HUnit ((@?=))\nimport Test.Hspec\n\nimport Spiral.Array (M,\n Matrix)\nimport qualified Spiral.Array as A\nimport Spiral.Convolution\nimport Spiral.Driver\nimport Spiral.Exp\nimport Spiral.FFT.Bluestein\nimport Spiral.FFT.CooleyTukey\nimport Spiral.FFT.GoodThomas\nimport Spiral.FFT.Rader\nimport Spiral.FFT.Winograd\nimport Spiral.NumberTheory (factors)\nimport Spiral.RootOfUnity\nimport Spiral.SPL\nimport Spiral.Search.FFTBreakdowns (getCycs)\nimport Spiral.Search.OpCount\n\nfactorizationTests :: Spec\nfactorizationTests = do\n f2Test\n f4Test\n f8Test\n complexFactorizationTests\n describe \"Modular DFT\" $ do\n describe \"\u2124/17\" $\n sequence_ [ditTest (Proxy :: Proxy (\u2124/17)) i | i <- [1..4::Int]]\n describe \"\u2124/2013265921\" $\n sequence_ [ditTest (Proxy :: Proxy (\u2124/2013265921)) i | i <- [1..7::Int]]\n\ncomplexFactorizationTests :: Spec\ncomplexFactorizationTests = do\n describe \"Cooley-Tukey\" $ do\n cooleyTukeyDITTest p 5 7\n cooleyTukeyDIFTest p 5 7\n describe \"Good-Thomas\" $\n goodThomasTest p 5 7\n describe \"Rader\" $ do\n mapM_ (raderTest p \"Rader\" rader) [7, 23]\n mapM_ (raderTest p \"RaderI\" (\\n w -> raderI n w (ConvolutionTheorem (n-1)))) [7, 17, 23]\n mapM_ (raderTest p \"RaderII\" raderII) [7, 17, 23]\n mapM_ (raderTest p \"RaderIII\" raderIII) [7, 17, 23]\n mapM_ (raderTest p \"RaderIV\" raderIV) [7, 17, 23]\n mapM_ (raderTest p \"raderLuIII\" raderLuIII) [7, 17, 23]\n describe \"Bluestein\" $ do\n mapM_ (bluesteinTest p \"Bluestein\" bluestein) [(3, 6), (4, 8), (4, 9), (9, 18)]\n mapM_ (bluesteinTest p \"Bluestein'\" bluestein') [(3, 6), (4, 8), (4, 9), (9, 18)]\n describe \"Winograd Small\" $ do\n winogradSmallTest 3 (ConvolutionTheorem 2)\n winogradSmallTest 5 (ConvolutionTheorem 4)\n winogradSmallTest 7 (SplitNesting [3, 2] [(Winograd 3 [Standard 1, Standard 2]), (Winograd 2 [Standard 1, Standard 1])])\n winogradSmallTest 7 (AgarwalCooley 3 2 (Winograd 3 [Standard 1, Lift 2 6 (Tensor [3,2] [Standard 3,Standard 2])]) (Winograd 2 [Standard 1,Standard 1]))\n describe \"Winograd Large\" $\n mapM_ winogradLargeTest [(2,3), (5, 2), (2,7), (3,4), (4,3), (5,4), (3,8), (5,8), (8,3), (3,5), (5,3)]\n describe \"Winograd 2^n\" $\n mapM_ winogradTwoTest [2^i | i <- [1..5::Int]]\n describe \"Winograd Power\" $ do\n winogradPowerTest 3 2\n winogradSquareTest 3\n winogradSquareTest 5\n describe \"DIT\" $\n sequence_ [ditTest p n | n <- [1..7]]\n describe \"DIF\" $\n sequence_ [difTest p n | n <- [1..7]]\n describe \"Split Radix\" $\n sequence_ [splitRadixTest p n | n <- [1..3]]\n describe \"Split Radix 8\" $\n sequence_ [splitRadix8Test p n | n <- [1..2]]\n describe \"Conjugate Pair Split Radix\" $\n sequence_ [conjPairSplitRadixTest p n | n <- [1..3]]\n describe \"Improved Split Radix\" $\n sequence_ [improvedSplitRadixTest p n | n <- [1..3]]\n where\n p :: Proxy (Complex Double)\n p = Proxy\n\n-- $F_2$\nf2Test :: Spec\nf2Test = it \"F_2\" $ toMatrix (dit 2) @?= f2\n where\n f2 :: Matrix M (Exp (Complex Double))\n f2 = A.matrix [[1, 1],\n [1, -1]]\n\n-- $F_4$ calculated per \"SPL: A Language and Compiler for DSP Algorithms\"\nf4Test :: Spec\nf4Test = it \"F_4\" $ toMatrix (dit 4) @?= f4\n where\n f4 :: Matrix M (Exp (Complex Double))\n f4 = A.matrix [[1, 1, 1, 1],\n [1, -i, -1, i],\n [1, -1, 1, -1],\n [1, i, -1, -i]]\n where\n i :: Exp (Complex Double)\n i = complexE (0 :+ 1)\n\n-- $F_8$ calculated per \"SPL: A Language and Compiler for DSP Algorithms\"\n-- See also:\n-- https://en.wikipedia.org/wiki/DFT_matrix\nf8Test :: Spec\nf8Test = it \"F_8\" $ toMatrix (dit 8) @?= f8\n where\n f8 :: Matrix M (Exp (Complex Double))\n f8 = A.matrix [[1, 1, 1, 1, 1, 1, 1, 1],\n [1, w, -i, -i*w, -1, -w, i, i*w],\n [1, -i, -1, i, 1, -i, -1, i],\n [1, -i*w, i, w, -1, i*w, -i, -w],\n [1, -1, 1, -1, 1, -1, 1, -1],\n [1, -w, -i, i*w, -1, w, i, -i*w],\n [1, i, -1, -i, 1, i, -1, -i],\n [1, i*w, i, -w, -1, -i*w, -i, w]]\n where\n i = complexE (0 :+ 1)\n\n w = omega 8\n\n-- Test Cooley-Tukey DIT\ncooleyTukeyDITTest :: forall p . RootOfUnity (Exp p)\n => Proxy p\n -> Int\n -> Int\n -> Spec\ncooleyTukeyDITTest _ r s =\n it (\"CooleyTukeyDIT(\" ++ show r ++ \",\" ++ show s ++ \")\") $\n toMatrix (cooleyTukeyDIT r s w) @?= toMatrix (F rs w)\n where\n w :: Exp p\n w = omega rs\n\n rs :: Int\n rs = r*s\n\n-- Test Cooley-Tukey DIF\ncooleyTukeyDIFTest :: forall p . RootOfUnity (Exp p)\n => Proxy p\n -> Int\n -> Int\n -> Spec\ncooleyTukeyDIFTest _ r s =\n it (\"CooleyTukeyDIF(\" ++ show r ++ \",\" ++ show s ++ \")\") $\n toMatrix (cooleyTukeyDIF r s w) @?= toMatrix (F rs w)\n where\n w :: Exp p\n w = omega rs\n\n rs :: Int\n rs = r*s\n\n-- Test Good-Thomas with factors 5 and 7\ngoodThomasTest :: forall p . RootOfUnity (Exp p)\n => Proxy p\n -> Int\n -> Int\n -> Spec\ngoodThomasTest _ r s =\n it (\"GoodThomas(\" ++ show r ++ \",\" ++ show s ++ \")\") $\n toMatrix (goodThomas r s w) @?= toMatrix (F rs w)\n where\n w :: Exp p\n w = omega rs\n\n rs :: Int\n rs = r*s\n\n-- Test Rader for given prime\nraderTest :: forall p . RootOfUnity (Exp p)\n => Proxy p\n -> String\n -> (Int -> Exp p -> SPL (Exp p))\n -> Int\n -> Spec\nraderTest _ desc rader n = it (desc ++ \"(\" ++ show n ++ \")\") $\n toMatrix (rader (fromIntegral n) w) @?= toMatrix (F n w)\n where\n w :: Exp p\n w = omega n\n\n-- Test Bluestein for given n and m\nbluesteinTest :: forall p . RootOfUnity (Exp p)\n => Proxy p\n -> String\n -> (Int -> Int -> Exp p -> SPL (Exp p))\n -> (Int, Int)\n -> Spec\nbluesteinTest _ desc bluestein (n, m) = it (desc ++ \"(\" ++ show n ++ \",\" ++ show m ++ \")\") $\n toMatrix (bluestein n m w) @?= toMatrix (DFT n)\n where\n w :: Exp p\n w = omega (2*n)\n\nwinogradSmallTest :: Int\n -> CyclicConvolution (Exp (Complex Double))\n -> Spec\nwinogradSmallTest n cyc =\n it (\"WinogradSmall(\" ++ show n ++ \"--\" ++ show cyc ++ \")\") $\n toMatrix (winogradSmall n w cyc) @?= toMatrix (F n w)\n where\n w :: Exp (Complex Double)\n w = omega n\n\nwinogradLargeTest :: (Int, Int) -> Spec\nwinogradLargeTest (r, s) = it (\"WinogradLarge(\" ++ show r ++ \", \" ++ show s ++ \")\") $\n sequence_ [toMatrix (winogradLarge r s w cr cc) @?= toMatrix (F n w)\n | cr <- take 2 $ getWinogradTriple' r s w getCycs\n , cc <- take 2 $ getWinogradTriple' s r w getCycs]\n where\n n :: Int\n n = r*s\n\n w :: Exp (Complex Double)\n w = omega n\n\nwinogradTwoTest :: Int -> Spec\nwinogradTwoTest n@2 = describe (\"Winograd N=\" ++ show n) $ do\n sequence_ [it (\"DIF(2,1): w^\" ++ show i) $ toMatrix (winogradDIF 2 1 (w^i)) @?= toMatrix (F n (w^i)) | i <- [1..n-1], rem i 2 /= 0]\n sequence_ [it (\"DIT(2,1): w^\" ++ show i) $ toMatrix (winogradDIT 2 1 (w^i)) @?= toMatrix (F n (w^i)) | i <- [1..n-1], rem i 2 /= 0]\n where\n w :: Exp (Complex Double)\n w = omega n\n\nwinogradTwoTest n = describe (\"Winograd N=\" ++ show n) $ do\n sequence_ [it (\"DIF(\" ++ show r ++ \",\" ++ show s ++ \"): w^\" ++ show i) $ toMatrix (winogradDIF r s (w^i)) @?= toMatrix (F n (w^i)) | i <- [1,n-1], rem i 2 /= 0, (r,s) <- factors n]\n sequence_ [it (\"DIT(\" ++ show r ++ \",\" ++ show s ++ \"): w^\" ++ show i) $ toMatrix (winogradDIT r s (w^i)) @?= toMatrix (F n (w^i)) | i <- [1,n-1], rem i 2 /= 0, (r,s) <- factors n]\n sequence_ [it (\"SplitRadix: w^\" ++ show i) $ toMatrix (winogradSplitRadix n (w^i)) @?= toMatrix (F n (w^i)) | i <- [1,n-1], rem i 2 /= 0]\n sequence_ [it (\"ConjPairSplitRadix: w^\" ++ show i) $ toMatrix (winogradConjPairSplitRadix n (w^i)) @?= toMatrix (F n (w^i)) | i <- [1,n-1], rem i 2 /= 0]\n sequence_ [it (\"SplitRadix8: w^\" ++ show i) $ toMatrix (winogradSplitRadix8 n (w^i)) @?= toMatrix (F n (w^i)) | i <- [1,n-1], n >= 8, rem i 2 /= 0]\n sequence_ [it (\"ImprovedSplitRadix: w^\" ++ show i) $ toMatrix (winogradImprovedSplitRadix n (w^i)) @?= toMatrix (F n (w^i)) | i <- [1,n-1], rem i 2 /= 0]\n where\n w :: Exp (Complex Double)\n w = omega n\n\nwinogradPowerTest :: Int -> Int -> Spec\nwinogradPowerTest p k = describe (\"WinogradPower(\" ++ show p ++ \"^\" ++ show k ++ \")\") $\n sequence_\n [it (\"w^\" ++ show i ++ \" -- p': \" ++ show cP ++ \" -- s: \" ++ show cS) $\n toMatrix (winogradPower p k (w^^i) cP cS) @?= toMatrix (F n (w^^i))\n | i <- [1,8],\n cP <- take 2 $ getCycs p',\n cS <- take 2 $ getCycs s]\n where\n n, p', s :: Int\n n = p^k\n p' = (p-1)\n s = p * p'\n\n w :: Exp (Complex Double)\n w = omega n\n\nwinogradSquareTest :: Int -> Spec\nwinogradSquareTest p = describe (\"WinogradSquare(\" ++ show p ++ \"^2)\") $\n sequence_\n [it (\"w^\" ++ show i) $ toMatrix f @?= toMatrix (F n (w^^i))\n | i <- [1,p],\n f <- take 1 $ winogradSquare p k (w^^i) getCycs]\n where\n n, p', s, k :: Int\n k = 2\n n = p^k\n p' = (p-1)\n s = p * p'\n\n w :: Exp (Complex Double)\n w = omega n\n\n-- DIT test\nditTest :: forall p . RootOfUnity (Exp p)\n => Proxy p\n -> Int\n -> Spec\nditTest _ n = it (\"DIT(2^\" ++ show n ++ \")\") $\n toMatrix fft_spl @?= toMatrix (DFT (2^n))\n where\n fft_spl :: SPL (Exp p)\n fft_spl = dit (2^n)\n\n-- DIF test\ndifTest :: forall p . RootOfUnity (Exp p)\n => Proxy p\n -> Int\n -> Spec\ndifTest _ n = it (\"DIF(2^\" ++ show n ++ \")\") $\n toMatrix fft_spl @?= toMatrix (DFT (2^n))\n where\n fft_spl :: SPL (Exp p)\n fft_spl = dif (2^n)\n\n-- Split radix test\nsplitRadixTest :: forall p . RootOfUnity (Exp p)\n => Proxy p\n -> Int\n -> Spec\nsplitRadixTest _ n = it (\"SplitRadix(4^\" ++ show n ++ \")\") $\n toMatrix (splitRadix (4^n) w) @?= toMatrix (DFT (4^n))\n where\n w :: Exp p\n w = omega (4^n)\n\n-- Split radix 8 test\nsplitRadix8Test :: forall p . RootOfUnity (Exp p)\n => Proxy p\n -> Int\n -> Spec\nsplitRadix8Test _ n = it (\"SplitRadix(8^\" ++ show n ++ \")\") $\n toMatrix (splitRadix8 (8^n) w) @?= toMatrix (DFT (8^n))\n where\n w :: Exp p\n w = omega (8^n)\n\n-- Split radix test\nconjPairSplitRadixTest :: forall p . RootOfUnity (Exp p)\n => Proxy p\n -> Int\n -> Spec\nconjPairSplitRadixTest _ n = it (\"ConjPairSplitRadix(4^\" ++ show n ++ \")\") $\n toMatrix (conjPairSplitRadix (4^n) w) @?= toMatrix (DFT (4^n))\n where\n w :: Exp p\n w = omega (4^n)\n\n-- Split radix test\nimprovedSplitRadixTest :: forall p . (Floating (Exp p), RootOfUnity (Exp p))\n => Proxy p\n -> Int\n -> Spec\nimprovedSplitRadixTest _ n = it (\"ImprovedSplitRadix(4^\" ++ show n ++ \")\") $\n toMatrix (improvedSplitRadix (4^n) w) @?= toMatrix (DFT (4^n))\n where\n w :: Exp p\n w = omega (4^n)\n\n-- Lowest-opcount test\nopcountSearchTest :: Int -> Spec\nopcountSearchTest n = it (\"OpcountSearch(\" ++ show n ++ \")\") $ do\n Re e <- runSpiralWith mempty $\n searchOpCount (Re (DFT n) :: SPL (Exp Double))\n toMatrix e @?= toMatrix (DFT n)\n", "meta": {"hexsha": "22d7f09a681db37c43061f8f02cba1ccd45b43b2", "size": 12386, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/test/Test/Factorization.hs", "max_stars_repo_name": "mainland/hspiral", "max_stars_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-05-21T21:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T04:48:25.000Z", "max_issues_repo_path": "src/test/Test/Factorization.hs", "max_issues_repo_name": "mainland/hspiral", "max_issues_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/Test/Factorization.hs", "max_forks_repo_name": "mainland/hspiral", "max_forks_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9414893617, "max_line_length": 184, "alphanum_fraction": 0.5335863071, "num_tokens": 4274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5949883862744442}} {"text": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n\nmodule Cas.Internal.Def where\n\nimport PreludeCustom\nimport Data.Complex.Generic\n\ntype F = Complex Rational\n\ninstance Ord F where\n (x0:+y0) <= (x1:+y1) = x0 < x1 || x0==x1 && y0 < y1\n\ndata C = Pi | E deriving (Eq, Ord, Show)\nnewtype X = X { xI :: Int } deriving (Eq,Ord)\nnewtype Add = Add { addTs :: [T] } deriving (Eq,Ord)\nnewtype Mul = Mul { mulTs :: [T] } deriving (Eq,Ord)\n\ndata T = TF { tF :: F }\n | TX { tX :: X }\n | TC { tC :: C }\n | TAdd { tAdd :: Add }\n | TMul { tMul :: Mul }\n | TPow { tPowB :: T\n , tPowE :: T }\n | TLn { tLnT :: T }\n deriving (Eq,Ord)\n\ndata Equ = Equ { equT :: T } deriving (Eq,Ord)\ndata LinSys = LinSys { linSysEqus :: [Equ] } deriving (Eq,Ord)\n\ndata Rule = Rule {ruleX::X, ruleT::T}\n(-->) :: X -> T -> Rule\n(-->) = Rule\n\n\ndata LinSysSolution = LinSysSolution { solutionRules :: [Rule]\n , constraints :: [Equ] }\n\n\n\n", "meta": {"hexsha": "0e43b2a6cfd0caf077a946793ea3f13ab34edca9", "size": 1137, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Cas/Internal/Def.hs", "max_stars_repo_name": "vcanadi/cas", "max_stars_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-20T22:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-20T22:42:53.000Z", "max_issues_repo_path": "src/Cas/Internal/Def.hs", "max_issues_repo_name": "vcanadi/cas", "max_issues_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Cas/Internal/Def.hs", "max_forks_repo_name": "vcanadi/cas", "max_forks_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0714285714, "max_line_length": 64, "alphanum_fraction": 0.4749340369, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5948158517621197}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.LinearAlgebra.Matrix.ST\n-- Copyright : Copyright (c) , Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Mutable matrices in the ST monad.\n\nmodule Numeric.LinearAlgebra.Matrix.ST (\n -- * Mutable matrices\n STMatrix,\n IOMatrix,\n create,\n \n -- * Read-only matrices\n RMatrix(..),\n \n -- * Creating new matrices\n new_,\n new,\n \n -- * Copying matrices\n newCopy,\n copyTo,\n\n -- * Matrix views\n withSlice,\n withTakeRows,\n withDropRows,\n withSplitRowsAt,\n withTakeCols,\n withDropCols,\n withSplitColsAt,\n withSliceM,\n withTakeRowsM,\n withDropRowsM,\n withSplitRowsAtM,\n withTakeColsM,\n withDropColsM,\n withSplitColsAtM,\n \n -- * Matrix rows and columns\n rowTo,\n unsafeRowTo,\n setRow,\n unsafeSetRow,\n withCol,\n\n withColM,\n withColsM,\n \n swapRows,\n unsafeSwapRows,\n swapCols,\n unsafeSwapCols,\n\n -- * Matrix diagonals\n diagTo,\n setDiag,\n\n -- * Reading and writing matrix elements\n read,\n write,\n modify,\n getIndices,\n getElems,\n getElems',\n getAssocs,\n getAssocs',\n setElems,\n setAssocs,\n\n -- * List-like operations\n mapTo,\n zipWithTo,\n\n -- * Matrix math operations\n shiftDiagM_,\n shiftDiagWithScaleM_,\n addTo,\n subTo,\n scaleM_,\n addWithScaleM_,\n scaleRowsM_,\n scaleColsM_,\n negateTo,\n conjugateTo,\n\n -- * Linear algebra\n transTo,\n conjTransTo,\n rank1UpdateM_,\n \n -- ** Matrix-Vector multiplication\n mulVectorTo,\n mulVectorWithScaleTo,\n addMulVectorWithScalesM_,\n \n -- ** Matrix-Matrix multiplication\n mulMatrixTo,\n mulMatrixWithScaleTo,\n addMulMatrixWithScalesM_,\n\n -- * Conversions between mutable and immutable matrices\n freeze,\n \n -- * Vector views of matrices\n maybeWithVectorM,\n \n -- * Matrix views of vectors\n withFromVector,\n withFromCol,\n withFromRow,\n\n withFromVectorM,\n withFromColM,\n withFromRowM,\n \n -- * Unsafe operations\n unsafeCopyTo,\n unsafeAddWithScaleM_,\n \n ) where\n\nimport Prelude()\nimport Numeric.LinearAlgebra.Matrix.STBase\n", "meta": {"hexsha": "83ac73606f5634c435a9809bf40a7db2e962675d", "size": 2343, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/Matrix/ST.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra/Matrix/ST.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Numeric/LinearAlgebra/Matrix/ST.hs", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 18.1627906977, "max_line_length": 77, "alphanum_fraction": 0.6073410158, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.5944887409427834}} {"text": "\nmodule PCA\n ( fitPCA, transformPCA\n ) where\n\nimport PCA.QModels\nimport Numeric.LinearAlgebra.Data\n (Matrix, Vector, toRows, fromRows)\nimport qualified Numeric.LinearAlgebra.HMatrix as H\n\n\n-- | Theta parameteres which we will you for predict in model\ndata PCAModel = PCAModel\n { scale :: Matrix Double -- ^ W\n , shift :: Vector Double -- ^ \\mu\n }\n\n\nfitPCA :: Matrix Double -> PCAModel\nfitPCA t =\n let (w,mu) = calculateQ t\n in PCAModel\n { scale = w\n , shift = mu\n }\n\n\ntransformPCA :: PCAModel -> Matrix Double -> Matrix Double\ntransformPCA (PCAModel w mu) t =\n fromRows\n (map\n (\\tn ->\n tn + mu)\n (toRows (t H.<> w)))\n", "meta": {"hexsha": "3ab5112d7eac83de0af4574b2d4d1356d2f53272", "size": 716, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PCA.hs", "max_stars_repo_name": "DbIHbKA/vbpca", "max_stars_repo_head_hexsha": "e9c98743b6303436fbfcab360ac7a500183606bf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PCA.hs", "max_issues_repo_name": "DbIHbKA/vbpca", "max_issues_repo_head_hexsha": "e9c98743b6303436fbfcab360ac7a500183606bf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PCA.hs", "max_forks_repo_name": "DbIHbKA/vbpca", "max_forks_repo_head_hexsha": "e9c98743b6303436fbfcab360ac7a500183606bf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4571428571, "max_line_length": 61, "alphanum_fraction": 0.5865921788, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5943461103355892}} {"text": "module Approx where\nimport Data.Complex\n\napproxDbl :: Int -> Double -> Double\napproxDbl n x = fromInteger (round $ x * (10^n)) / (10.0^^n)\n\napprox :: Int -> Complex Double -> Complex Double\napprox n z = approxDbl n (realPart z) :+ approxDbl n (imagPart z)\n", "meta": {"hexsha": "38184ddd04727037088e0f314c5a535f166c065d", "size": 256, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Approx.hs", "max_stars_repo_name": "stla/elliptic", "max_stars_repo_head_hexsha": "62056e4551e33273d6ce7c207df02aa36c716472", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-06T11:28:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-07T18:10:06.000Z", "max_issues_repo_path": "tests/Approx.hs", "max_issues_repo_name": "stla/elliptic", "max_issues_repo_head_hexsha": "62056e4551e33273d6ce7c207df02aa36c716472", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Approx.hs", "max_forks_repo_name": "stla/elliptic", "max_forks_repo_head_hexsha": "62056e4551e33273d6ce7c207df02aa36c716472", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4444444444, "max_line_length": 65, "alphanum_fraction": 0.6796875, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5942536146018397}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MagicHash #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UnboxedTuples #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule Numeric.Matrix.Bidiagonal\n ( BiDiag (..), biDiag, bidiagonalHouseholder\n ) where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Kind\nimport Numeric.Basics\nimport Numeric.DataFrame.ST\nimport Numeric.DataFrame.SubSpace\nimport Numeric.DataFrame.Type\nimport Numeric.Dimensions\nimport Numeric.Matrix.Internal\nimport Numeric.Scalar.Internal\nimport Numeric.Subroutine.Householder\nimport Numeric.Vector.Internal\n\n\n-- | Put two vectors on the main and first upper diagonal.\nbiDiag :: forall (t :: Type) (n :: Nat) (m :: Nat)\n . (PrimBytes t, Num t)\n => Dims '[n,m]\n -> Vector t (Min n m)\n -> Vector t (Min n m)\n -> Matrix t n m\nbiDiag (dn@D :* dm@D :* U) a b = runST $ do\n dnm@D <- pure $ minDim dn dm\n rPtr <- thawDataFrame 0\n forM_ [0 .. dimVal dnm - 1] $ \\i -> do\n writeDataFrame rPtr (Idx i :* Idx i :* U) $ a ! i\n when (i+1 < dimVal dm) $\n writeDataFrame rPtr (Idx i :* Idx (i+1) :* U) $ b ! i\n unsafeFreezeDataFrame rPtr\n\n-- | Decomposition of a matrix \\( A = U B V^\\intercal \\) such that\n-- \\( U \\) and \\( V \\) are orthogonal and \\( B \\) is bidiagonal.\ndata BiDiag (t :: Type) (n :: Nat) (m :: Nat)\n = BiDiag\n { bdU :: Matrix t n n\n -- ^ \\( U \\) left orthogonal matrix\n , bdUDet :: Scalar t\n -- ^ A shortcut for evaluating a determinant of \\( |U| = \\pm 1 \\)\n , bdAlpha :: Vector t (Min n m)\n -- ^ Main diagonal of \\( B \\)\n , bdBeta :: Vector t (Min n m)\n -- ^ First upper diagonal of \\( B \\);\n -- its last element equals zero if \\( n \\geq m \\)\n , bdV :: Matrix t m m\n -- ^ \\( B \\) left orthogonal matrix\n , bdVDet :: Scalar t\n -- ^ A shortcut for evaluating a determinant of \\( |V| = \\pm 1 \\)\n }\n\nderiving instance ( Show t, PrimBytes t\n , KnownDim n, KnownDim m, KnownDim (Min n m))\n => Show (BiDiag t n m)\nderiving instance ( Eq t, PrimBytes t\n , KnownDim n, KnownDim m, KnownDim (Min n m)\n , KnownBackend t '[Min n m])\n => Eq (BiDiag t n m)\n\n{- |\nDecompose a matrix \\( A = U B V^\\intercal \\) such that\n\\( U \\) and \\( V \\) are orthogonal and \\( B \\) is bidiagonal.\n\nThe first returned number\n -}\nbidiagonalHouseholder ::\n forall (t :: Type) (n :: Nat) (m :: Nat)\n . (PrimBytes t, Ord t, Epsilon t, KnownDim n, KnownDim m)\n => Matrix t n m\n -> BiDiag t n m\nbidiagonalHouseholder a = runST $ do\n D <- pure $ minDim (dim @n) (dim @m)\n tmpNPtr <- newDataFrame\n tmpMPtr <- newDataFrame\n uPtr <- thawDataFrame eye\n bPtr <- thawDataFrame a\n vPtr <- thawDataFrame eye\n (ud, vd) <-\n let f (ud, vd) i = do\n ud' <- householderReflectionInplaceL tmpNPtr uPtr bPtr\n (Idx (i - 1) :* Idx (i - 1) :* U)\n vd' <- householderReflectionInplaceR tmpMPtr vPtr bPtr\n (Idx (i - 1) :* Idx i :* U)\n return (ud /= ud', vd /= vd')\n in foldM f (False, False) [1 .. lim - 1]\n\n udn <- householderReflectionInplaceL tmpNPtr uPtr bPtr\n (Idx (lim - 1) :* Idx (lim - 1) :* U)\n vdn <- if (m > lim)\n then householderReflectionInplaceR tmpMPtr vPtr bPtr\n (Idx (lim - 1) :* Idx lim :* U)\n else pure False\n bdU <- unsafeFreezeDataFrame uPtr\n bdV <- unsafeFreezeDataFrame vPtr\n b <- unsafeFreezeDataFrame bPtr\n let bdAlpha = iwgen @t @'[Min n m]\n (\\(Idx i :* U) -> index (Idx i :* Idx i :* U) b)\n bdBeta = iwgen @t @'[Min n m]\n (\\(Idx i :* U) -> if i+1 < m then index (Idx i :* Idx (i+1) :* U) b else 0)\n bdUDet = if ud /= udn then -1 else 1\n bdVDet = if vd /= vdn then -1 else 1\n return BiDiag {..}\n where\n n = dimVal' @n\n m = dimVal' @m\n lim = max 1 (min n m)\n", "meta": {"hexsha": "a62f8653ebce22272ca1af989d1ca5f269f6cfed", "size": 4381, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "easytensor/src/Numeric/Matrix/Bidiagonal.hs", "max_stars_repo_name": "achirkin/fasttensor", "max_stars_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2017-06-30T04:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:46:17.000Z", "max_issues_repo_path": "easytensor/src/Numeric/Matrix/Bidiagonal.hs", "max_issues_repo_name": "achirkin/fasttensor", "max_issues_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-07-17T18:20:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T06:31:42.000Z", "max_forks_repo_path": "easytensor/src/Numeric/Matrix/Bidiagonal.hs", "max_forks_repo_name": "achirkin/fasttensor", "max_forks_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-08T20:44:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T22:08:04.000Z", "avg_line_length": 35.3306451613, "max_line_length": 87, "alphanum_fraction": 0.5539831089, "num_tokens": 1322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5941939885360251}} {"text": "import Test.HUnit\nimport FFT.DFTControl\nimport FFT.Orig\nimport FFT.Samples\nimport System.Environment\nimport Data.Complex\n\ntestDcDft = TestCase (assertEqual \"DFTDc\" expected actual)\n where\n expected = (sum $ dcdft samples512)\n actual = (sum $ dft samples512)\n samples512 = samples 1 512\n\ntests = TestList [TestLabel \"testDcDFT\" testDcDft\n ]\n \nmain = runTestTT tests\n", "meta": {"hexsha": "42d5c43bad5634510c1e5c25c8ce95aa082e2f95", "size": 427, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/test/DFTControlTest.hs", "max_stars_repo_name": "BNJHope/parallel-fourier-transforms", "max_stars_repo_head_hexsha": "274ec189ed99715c4a912659683c0f93c0628a72", "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/test/DFTControlTest.hs", "max_issues_repo_name": "BNJHope/parallel-fourier-transforms", "max_issues_repo_head_hexsha": "274ec189ed99715c4a912659683c0f93c0628a72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/DFTControlTest.hs", "max_forks_repo_name": "BNJHope/parallel-fourier-transforms", "max_forks_repo_head_hexsha": "274ec189ed99715c4a912659683c0f93c0628a72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7222222222, "max_line_length": 58, "alphanum_fraction": 0.6604215457, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.7057850340255387, "lm_q1q2_score": 0.594147931885853}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.Statistics.Histogram\n-- Copyright : (c) A. V. H. McPhail 2010, 2014\n-- License : BSD3\n--\n-- Maintainer : haskell.vivian.mcphail gmail com\n-- Stability : provisional\n-- Portability : portable\n--\n-- create histograms from density functions\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.Statistics.Histogram (\n cumulativeToHistogram\n , gaussianHistogram\n ) where\n\n\n-----------------------------------------------------------------------------\n\n--import qualified Data.Packed.Vector as V\nimport qualified Data.Vector.Storable as V\n\nimport qualified Numeric.GSL.Histogram as H\n--import qualified Numeric.GSL.Histogram2D as H2\n\nimport qualified Numeric.GSL.Distribution.Continuous as C\n\n--import Numeric.LinearAlgebra.Algorithms\n--import Numeric.LinearAlgebra.Interface()\n\n-----------------------------------------------------------------------------\n\nvectorToTuples = toTuples . V.toList\n where toTuples [] = error \"need a minimum of two elements\"\n toTuples [_] = error \"need a minimum of two elements\"\n toTuples [x1,x2] = [(x1,x2)]\n toTuples (x1:x2:xs) = (x1,x2) : (toTuples (x2:xs))\n\n-----------------------------------------------------------------------------\n\ncumulativeToHistogram :: (Double -> Double) -- ^ the cumulative distribution function D(x <= X)\n -> V.Vector Double -- ^ the bins\n -> H.Histogram -- ^ the resulting histogram\ncumulativeToHistogram f v = H.addListWeighted (H.emptyRanges v) $ map (\\(x1,x2) -> ((x1 + x2) / 2.0,f x2 - f x1)) (vectorToTuples v)\n\ngaussianHistogram :: Double -- ^ mean\n -> Double -- ^ standard deviation\n -> V.Vector Double -- ^ the bins\n -> H.Histogram -- ^ the resulting histogram\ngaussianHistogram u s = cumulativeToHistogram (\\x -> C.density_1p C.Gaussian C.Lower s (x-u))\n\n-----------------------------------------------------------------------------\n", "meta": {"hexsha": "22c4efde1340cae95a55c10d03a1bf4dc207072d", "size": 2277, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/Statistics/Histogram.hs", "max_stars_repo_name": "amcphail/hstatistics", "max_stars_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-05-14T19:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T15:23:53.000Z", "max_issues_repo_path": "lib/Numeric/Statistics/Histogram.hs", "max_issues_repo_name": "amcphail/hstatistics", "max_issues_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-12-14T23:36:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-06T23:18:48.000Z", "max_forks_repo_path": "lib/Numeric/Statistics/Histogram.hs", "max_forks_repo_name": "amcphail/hstatistics", "max_forks_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-05-24T22:51:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-13T19:12:30.000Z", "avg_line_length": 40.6607142857, "max_line_length": 132, "alphanum_fraction": 0.4681598595, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.594147927068114}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ConstraintKinds #-}\nmodule Noise(\n histogram\n , Structure(..)\n , quantizationNoise\n ) where \n\nimport qualified Statistics.Sample.Histogram as H\nimport qualified Data.Vector.Unboxed as U\nimport Plot \nimport Graphics.PDF \nimport Common \nimport Generators\nimport Signal \nimport System.Random \nimport Text.Printf \n\nnbBins = 20 \n\ndrawHist :: Int \n -> U.Vector Double \n -> U.Vector Double \n -> Int \n -> Int\n -> CoordinateMapping Double Double \n -> Draw () \ndrawHist nb v b wi hi (toPoint,_) = do\n let binWidth :: Double\n binWidth = fromIntegral wi / fromIntegral nb\n d = binWidth / 2.0\n drawBin p = do \n fillColor (Rgb 0.8 0.8 1.0)\n let (x :+ y) = toPoint p\n r = Rectangle ((x - d) :+ 0) ((x + d) :+ y)\n fill r \n stroke r\n return () \n mapM_ drawBin $ (U.toList $ U.zip v b)\n\nhistogram :: (U.Unbox a, HasDoubleRepresentation a) \n => [a] \n -> StyledSignal Double Double\nhistogram l = do\n let (s,v1) = H.histogram nbBins (U.fromList . map toDouble $ l)\n v = U.map (/ (U.sum v1)) v1\n nb = U.length s\n mas = U.maximum s \n mis = U.minimum s\n d = (mas - mis) / fromIntegral nb / 2.0\n detailed x = printf \"%.2g\" x\n style = defaultPlotStyle { title = Just \"Histogram\"\n , horizontalLabel = Nothing \n , verticalLabel = Nothing \n , horizontalBounds = Just (mis-d,mas+d) \n , verticalBounds = Just (U.minimum v, U.maximum v)\n , epilog = drawHist nb s v\n , axis = False\n , horizontalTickRepresentation = detailed\n }\n discreteSignalsWithStyle (U.length s) style [] \n\nclass Structure m where \n doubleVersion :: (Sample i, Sample o) => m f i o -> m Double Double Double\n transferFunction :: (Sample i, Sample o) => m f i o -> Signal i -> Signal o \n\nquantizationNoise :: (Structure m , Random i, Sample o, Sample i) \n => Signal i\n -> m p i o \n -> IO (Signal Double)\nquantizationNoise r structure = do\n let ds = transferFunction (doubleVersion structure) (mapS toDouble r) \n fs = mapS toDouble . transferFunction structure $ r\n return $ zipWithS (-) ds fs\n\n\n", "meta": {"hexsha": "151c53e012cad53ee6d6ee25985ac072a7876d03", "size": 2569, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Noise.hs", "max_stars_repo_name": "alpheccar/Signal", "max_stars_repo_head_hexsha": "8352b0c2def2a1faa97371a3eadab53b6fb2d7c1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-04-29T10:49:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T11:14:52.000Z", "max_issues_repo_path": "Noise.hs", "max_issues_repo_name": "cpehle/Signal", "max_issues_repo_head_hexsha": "8352b0c2def2a1faa97371a3eadab53b6fb2d7c1", "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": "Noise.hs", "max_forks_repo_name": "cpehle/Signal", "max_forks_repo_head_hexsha": "8352b0c2def2a1faa97371a3eadab53b6fb2d7c1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-01-31T18:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-17T06:19:01.000Z", "avg_line_length": 32.9358974359, "max_line_length": 87, "alphanum_fraction": 0.5278318412, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5941262067522557}} {"text": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ConstraintKinds #-}\nmodule DSLsofMath.Algebra where\nimport qualified Data.Ratio\nimport qualified Prelude\nimport Prelude (Double, Rational, Int, Integer, Bool(..), otherwise,\n Foldable(foldr), (.), const, (==), (<), error)\nimport Data.Complex\n\n-------------------------------\n-- Classes\ninfixl 6 -\ninfixl 6 +\n\ninfixl 7 *\ninfixl 7 /\n\nclass Additive a where\n zero :: a\n (+) :: a -> a -> a\n\nsum :: (Foldable t, Additive a) => t a -> a\nsum = foldr (+) zero\n\ntimes :: Additive a => Integer -> a -> a\ntimes n0 = if n0 < 0 then error \"Algebra.Classes.times: negative number of times\"\n else go n0\n where go 0 _ = zero\n go 1 x = x\n go n x = if r == 0 then twoy else x + twoy\n where (m,r) = n `Prelude.divMod` 2\n y = go m x\n twoy = y+y\n\n(-) :: AddGroup a => a -> a -> a\nx - y = x + negate y\n\nclass Additive a => AddGroup a where\n negate :: a -> a\n\nmult :: AddGroup a => Integer -> a -> a\nmult n x = if n < 0 then negate (times (negate n) x) else times n x\n\nclass Multiplicative a where\n one :: a\n (*) :: a -> a -> a\n\ntwo :: (Additive a, Multiplicative a) => a\ntwo = one+one\n\n(^+) :: Multiplicative a => a -> Int -> a\n\nx0 ^+ n0 = if n0 < 0 then error \"Algebra.Classes.^: negative exponent\"\n else go n0 x0\n where go 0 _ = one\n go 1 x = x\n go n x = if r == 0 then y2 else x * y2\n where (m,r) = n `Prelude.divMod` 2\n y = go m x\n y2 = y * y\n\ntype Ring a = (AddGroup a, Multiplicative a)\n\nfromInteger :: Ring a => Integer -> a\nfromInteger n = mult n one\n\nclass Multiplicative a => MulGroup a where\n {-# MINIMAL (recip | (/)) #-}\n recip :: a -> a\n recip x = one / x\n\n (/) :: a -> a -> a\n x / y = x * recip y\n\n(^) :: MulGroup a => a -> Int -> a\na ^ b | b < 0 = recip (a ^+ (negate b))\n | otherwise = (a ^+ b)\n\ntype Field a = (Ring a, MulGroup a)\n\nfromRational :: Field a => Data.Ratio.Ratio Integer -> a\nfromRational x = fromInteger (Data.Ratio.numerator x) / fromInteger (Data.Ratio.denominator x)\n\nclass Field a => Algebraic a where\n sqrt :: a -> a\n\n-- normally it should be \"Algebraic\" instead of \"Field\" but we're lazy like that.\n-- (Also Transcendental is a terrible name; taken from the \"numeric prelude\".)\nclass Field a => Transcendental a where\n pi :: a\n exp :: a -> a\n sin :: a -> a\n cos :: a -> a\n\ncosh, sinh :: Transcendental a => a -> a\ncosh x = (exp x + exp (negate x))/two\nsinh x = (exp x - exp (negate x))/two\n\n---------------------------------\n-- Instances\n\ninstance Additive Int where (+) = (Prelude.+); zero = 0\ninstance Additive Integer where (+) = (Prelude.+); zero = 0\ninstance Additive Rational where (+) = (Prelude.+); zero = 0\ninstance Additive Double where (+) = (Prelude.+); zero = 0\n\ninstance AddGroup Int where negate = Prelude.negate\ninstance AddGroup Integer where negate = Prelude.negate\ninstance AddGroup Rational where negate = Prelude.negate\ninstance AddGroup Double where negate = Prelude.negate\n\ninstance Multiplicative Int where (*) = (Prelude.*); one = 1\ninstance Multiplicative Integer where (*) = (Prelude.*); one = 1\ninstance Multiplicative Rational where (*) = (Prelude.*); one = 1\ninstance Multiplicative Double where (*) = (Prelude.*); one = 1\n\ninstance MulGroup Rational where (/) = (Prelude./); recip = Prelude.recip\ninstance MulGroup Double where (/) = (Prelude./); recip = Prelude.recip\n\nlift0 :: a -> (x->a)\nlift1 :: (a->b) -> (x->a) -> (x->b)\nlift2 :: (a->b->c) -> (x->a) -> (x->b) -> (x->c)\nlift0 = const\nlift1 = (.)\nlift2 op2 f g = \\x -> op2 (f x) (g x)\n\ninstance Additive a => Additive (x -> a) where (+) = lift2 (+); zero = lift0 zero\ninstance Multiplicative a => Multiplicative (x -> a) where (*) = lift2 (*); one = lift0 one\n\ninstance AddGroup a => AddGroup (x -> a) where negate = lift1 negate\ninstance MulGroup a => MulGroup (x -> a) where recip = lift1 recip\ninstance Algebraic a => Algebraic (x -> a) where sqrt = lift1 sqrt\n\ninstance Transcendental a => Transcendental (x -> a) where\n pi = lift0 pi; sin = lift1 sin; cos = lift1 cos; exp = lift1 exp\n\ninstance Algebraic Double where sqrt = Prelude.sqrt\ninstance Transcendental Double where\n pi = Prelude.pi; sin = Prelude.sin; cos = Prelude.cos; exp = Prelude.exp\n\ninstance Additive a => Additive (Complex a) where (+) = addC; zero = zeroC\ninstance Ring a => Multiplicative (Complex a) where (*) = mulC; one = oneC\ninstance AddGroup a => AddGroup (Complex a) where negate = negateC\ninstance Field a => MulGroup (Complex a) where recip = recipC\n\naddC :: Additive a => Complex a -> Complex a -> Complex a\naddC (x :+ y) (x' :+ y') = (x + x') :+ (y+y')\n\nnegateC :: AddGroup a => Complex a -> Complex a\nnegateC (a :+ b) = negate a :+ negate b\n\nmulC :: Ring a => Complex a -> Complex a -> Complex a\nmulC (a :+ b) (a' :+ b') = (a * a' - b * b') :+ (a * b' + b * a')\n\ntoC :: Additive a => a -> Complex a\ntoC x = x :+ zero\n\nzeroC :: Additive a => Complex a\nzeroC = toC zero\n\noneC :: (Additive a, Multiplicative a) => Complex a\noneC = toC one\n\nrecipC (a :+ b) = (a / m) :+ (negate b / m)\n where m = a*a + b*b\n\ninstance (Algebraic a, Prelude.RealFloat a) => Algebraic (Complex a) where\n sqrt = Prelude.sqrt\n\ninstance (Transcendental a) => Transcendental (Complex a) where\n pi = piC; exp = expC; sin = sinC; cos = cosC\n\npiC :: Transcendental a => Complex a\npiC = toC pi\n\nexpC, sinC, cosC, sinhC, coshC :: Transcendental a => Complex a -> Complex a\nexpC (x:+y) = expx * cos y :+ expx * sin y where expx = exp x\nsinC (x:+y) = sin x * cosh y :+ cos x * sinh y\ncosC (x:+y) = cos x * cosh y :+ negate (sin x * sinh y)\n\nsinhC (x:+y) = cos y * sinh x :+ sin y * cosh x\ncoshC (x:+y) = cos y * cosh x :+ sin y * sinh x\n\n---------------------------------\n-- For RebindableSyntax\n\nifThenElse :: Bool -> p -> p -> p\nifThenElse c a b = if c then a else b\n\n-------------------------------\n-- Typesetting aliases.\n\nneg :: AddGroup a => a -> a\nneg = negate -- |neg| is used to typeset unary minus as a shorter dash, closer to its argument\n\nfrac :: MulGroup a => a -> a -> a\nfrac = (/) -- |frac| is used to typeset a fraction (more compactly than |x / y|)\n", "meta": {"hexsha": "70f74833d692ead69d48dc5786270de022b024ec", "size": 6568, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "L/DSLsofMath/Algebra.hs", "max_stars_repo_name": "nicolabotta/DSLsofMath", "max_stars_repo_head_hexsha": "ce764c9bbff5a726d5cf1699a433d9921a1d6a60", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 248, "max_stars_repo_stars_event_min_datetime": "2015-04-27T21:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:12:24.000Z", "max_issues_repo_path": "L/DSLsofMath/Algebra.hs", "max_issues_repo_name": "nicolabotta/DSLsofMath", "max_issues_repo_head_hexsha": "ce764c9bbff5a726d5cf1699a433d9921a1d6a60", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 51, "max_issues_repo_issues_event_min_datetime": "2016-01-30T15:59:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T20:06:39.000Z", "max_forks_repo_path": "L/DSLsofMath/Algebra.hs", "max_forks_repo_name": "nicolabotta/DSLsofMath", "max_forks_repo_head_hexsha": "ce764c9bbff5a726d5cf1699a433d9921a1d6a60", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 47, "max_forks_repo_forks_event_min_datetime": "2015-11-16T08:41:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:57:42.000Z", "avg_line_length": 33.0050251256, "max_line_length": 98, "alphanum_fraction": 0.5637941535, "num_tokens": 2141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5941262059415092}} {"text": "{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module : Statistics.Distribution.ChiSquared\n-- Copyright : (c) 2010 Alexey Khudyakov\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- The chi-squared distribution. This is a continuous probability\n-- distribution of sum of squares of k independent standard normal\n-- distributions. It's commonly used in statistical tests\nmodule Statistics.Distribution.ChiSquared (\n ChiSquared\n -- Constructors\n , chiSquared\n , chiSquaredNDF\n ) where\n\nimport Data.Aeson (FromJSON, ToJSON)\nimport Data.Binary (Binary)\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.SpecFunctions (\n incompleteGamma,invIncompleteGamma,logGamma,digamma)\n\nimport qualified Statistics.Distribution as D\nimport qualified System.Random.MWC.Distributions as MWC\nimport Data.Binary (put, get)\n\n\n-- | Chi-squared distribution\nnewtype ChiSquared = ChiSquared Int\n deriving (Eq, Read, Show, Typeable, Data, Generic)\n\ninstance FromJSON ChiSquared\ninstance ToJSON ChiSquared\n\ninstance Binary ChiSquared where\n get = fmap ChiSquared get\n put (ChiSquared x) = put x\n\n-- | Get number of degrees of freedom\nchiSquaredNDF :: ChiSquared -> Int\nchiSquaredNDF (ChiSquared ndf) = ndf\n\n-- | Construct chi-squared distribution. Number of degrees of freedom\n-- must be positive.\nchiSquared :: Int -> ChiSquared\nchiSquared n\n | n <= 0 = error $\n \"Statistics.Distribution.ChiSquared.chiSquared: N.D.F. must be positive. Got \" ++ show n\n | otherwise = ChiSquared n\n\ninstance D.Distribution ChiSquared where\n cumulative = cumulative\n\ninstance D.ContDistr ChiSquared where\n density = density\n quantile = quantile\n\ninstance D.Mean ChiSquared where\n mean (ChiSquared ndf) = fromIntegral ndf\n\ninstance D.Variance ChiSquared where\n variance (ChiSquared ndf) = fromIntegral (2*ndf)\n\ninstance D.MaybeMean ChiSquared where\n maybeMean = Just . D.mean\n\ninstance D.MaybeVariance ChiSquared where\n maybeStdDev = Just . D.stdDev\n maybeVariance = Just . D.variance\n\ninstance D.Entropy ChiSquared where\n entropy (ChiSquared ndf) =\n let kHalf = 0.5 * fromIntegral ndf in\n kHalf\n + log 2\n + logGamma kHalf\n + (1-kHalf) * digamma kHalf\n\ninstance D.MaybeEntropy ChiSquared where\n maybeEntropy = Just . D.entropy\n\ninstance D.ContGen ChiSquared where\n genContVar (ChiSquared n) = MWC.chiSquare n\n\n\ncumulative :: ChiSquared -> Double -> Double\ncumulative chi x\n | x <= 0 = 0\n | otherwise = incompleteGamma (ndf/2) (x/2)\n where\n ndf = fromIntegral $ chiSquaredNDF chi\n\ndensity :: ChiSquared -> Double -> Double\ndensity chi x\n | x <= 0 = 0\n | otherwise = exp $ log x * (ndf2 - 1) - x2 - logGamma ndf2 - log 2 * ndf2\n where\n ndf = fromIntegral $ chiSquaredNDF chi\n ndf2 = ndf/2\n x2 = x/2\n\nquantile :: ChiSquared -> Double -> Double\nquantile (ChiSquared ndf) p\n | p == 0 = 0\n | p == 1 = 1/0\n | p > 0 && p < 1 = 2 * invIncompleteGamma (fromIntegral ndf / 2) p\n | otherwise =\n error $ \"Statistics.Distribution.ChiSquared.quantile: p must be in [0,1] range. Got: \"++show p\n", "meta": {"hexsha": "a6ccedb0517ec17dac3b21ac1c0f6a417c231075", "size": 3226, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/ChiSquared.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "Statistics/Distribution/ChiSquared.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Distribution/ChiSquared.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.298245614, "max_line_length": 98, "alphanum_fraction": 0.6965282083, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.594096260303741}} {"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule PlotGreensFunctionR2S1 where\n\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List as L\nimport FokkerPlanck.MonteCarlo\nimport Image.IO\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Text.Printf\nimport Utils.Array\n\n{-# INLINE reduceContrast #-}\nreduceContrast\n :: (R.Source s Double)\n => Int -> Array s DIM3 Double -> Array D DIM3 Double\nreduceContrast idx arr =\n let x = L.head . L.drop idx . L.reverse . L.sort . R.toList $ arr\n in R.map\n (\\y ->\n if y >= x\n then x\n else y)\n arr\n\nmain = do\n args@(numPointStr:numOrientationStr:sigmaStr:taoStr:lenStr:initStr:numTrailStr:numThreadStr:_) <-\n getArgs\n print args\n let numPoint = read numPointStr :: Int\n numOrientation = read numOrientationStr :: Int\n sigma = read sigmaStr :: Double\n tao = read taoStr :: Double\n len = read lenStr :: Int\n numTrail = read numTrailStr :: Int\n numThread = read numThreadStr :: Int\n arr <-\n solveMonteCarloR2S1\n numThread\n numTrail\n numPoint\n numPoint\n numOrientation\n sigma\n tao\n numPoint\n \"\"\n let arr' =\n computeS .\n -- reduceContrast 10 .\n R.extend (Z :. (1 :: Int) :. All :. All) . R.sumS . rotate3D $\n arr\n folderPath = \"output/app/PlotGreensFunctionR2S1\"\n createDirectoryIfMissing True folderPath\n plotImageRepa (folderPath printf \"GreensR2S1.png\") . ImageRepa 8 $\n arr'\n", "meta": {"hexsha": "c5b94d7c9de9bc298f3a03fe8d233ba91d146f3f", "size": 1639, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/FokkerPlanckMonteCarlo/PlotGreensFunctionR2S1/PlotGreensFunctionR2S1.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": "app/FokkerPlanckMonteCarlo/PlotGreensFunctionR2S1/PlotGreensFunctionR2S1.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": "app/FokkerPlanckMonteCarlo/PlotGreensFunctionR2S1/PlotGreensFunctionR2S1.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.7796610169, "max_line_length": 99, "alphanum_fraction": 0.6003660769, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5940704594913784}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeApplications #-}\n\nmodule Lib.STFTSpec where\n\nimport Data.Coerce\nimport Data.Complex\nimport Data.Proxy\nimport qualified Data.Vector as V\nimport GHC.TypeNats\nimport qualified Lib.STFT as STFT\nimport qualified Lib.Util as U\nimport Test.Hspec\nimport Test.QuickCheck\n\ntakeLast :: Int -> V.Vector a -> V.Vector a\ntakeLast n vec = V.reverse $ V.take n $ V.reverse vec\n\nspec = do\n\n describe \"STFT.hamming\" $ do\n it \"creates a hamming window of size N\" $ do\n let result = V.fromList [8.000000000000002e-2 :+ 0.0,\n 0.54 :+ 0.0,1.0 :+ 0.0,\n 0.5400000000000001 :+ 0.0,\n 8.000000000000002e-2 :+ 0.0\n ]\n STFT.runWindow STFT.hamming (STFT.MkWinsz (Proxy @5)) `shouldBe` result\n\n describe \"STFT.zeroPhaseZeroPad\" $ do\n it \"peforms zero phase and zero padding\" $ do\n tuple <- U.readWav \"static/audio/singing-female.wav\"\n let firstFive = V.fromList [(-0.553192138671875) :+ 0.0,\n (-0.55218505859375) :+ 0.0,\n (-0.556488037109375) :+ 0.0,\n (-0.58892822265625) :+ 0.0,\n (-0.610992431640625) :+ 0.0\n ]\n lastFive = V.fromList [(-0.443511962890625) :+ 0.0,\n (-0.479644775390625) :+ 0.0,\n (-0.49029541015625) :+ 0.0,\n (-0.493133544921875) :+ 0.0,\n (-0.52313232421875) :+ 0.0\n ]\n (_, audio) = U.makeSignal tuple\n result :: V.Vector (Complex Double)\n result = coerce $ STFT.zeroPhaseZeroPad (STFT.MkFFTsz (Proxy @2048)) audio\n V.take 5 result `shouldBe` firstFive\n takeLast 5 result `shouldBe` lastFive\n\n describe \"STFT.dftAnal\" $ do\n it \"performs a dft of the given FFT size\" $ do\n tuple <- U.readWav \"static/audio/singing-female.wav\"\n let firstFive = V.fromList [-12.049319770407699,\n -3.8232231987269523,\n -3.5161910098012816,\n -5.778847744891994,\n -4.450941161692169\n ]\n lastFive = V.fromList [9.085997084736617,\n 12.384474935554943,\n 11.667317158981483,\n 20.354458129771224,\n 11.951847223595225\n ]\n (_, audio) = U.makeSignal tuple\n (STFT.MkSpect (STFT.MkMag mag, _)) = STFT.dftAnal (STFT.MkFFTsz (Proxy @2048)) audio\n V.take 5 mag `shouldBe` firstFive\n takeLast 5 mag `shouldBe` lastFive\n\n describe \"STFT.stft\" $ do\n it \"Performs the short time fourier transform\" $ do\n (_, audio) <- U.readWav \"static/audio/singing-female.wav\"\n let firstFive = V.fromList [-95.55314985231192,\n -75.57780027962905,\n -72.63091749228488,\n -74.5060313038982,\n -80.35599835805851\n ]\n lastFive = V.fromList [-132.57867497788396,\n -128.76434452701437,\n -128.15973988408462,\n -131.54917075905306,\n -140.28246959896572\n ]\n (STFT.MkSpect (STFT.MkMag mag, _)) = head $ STFT.stft STFT.config (U.makeSig audio)\n V.take 5 mag `shouldBe` firstFive\n takeLast 5 mag `shouldBe` lastFive\n\n describe \"STFT.divvy\" $ do\n it \"Splits the vector into \" $ do\n let vec = V.replicate 272243 ()\n divvyVec = STFT.divvy (STFT.MkWinsz (Proxy @2048)) (STFT.MkHopsz (Proxy @256)) vec\n fmap length divvyVec `shouldBe` replicate 1056 2048\n", "meta": {"hexsha": "88cab8a2381e924572afb2bb702e3babdfd528fe", "size": 3513, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Lib/STFTSpec.hs", "max_stars_repo_name": "davlum/haskell-twm", "max_stars_repo_head_hexsha": "2e407d6f8b28aafa889ea3c1b134c8cb41803f1c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-05-19T08:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-11T07:13:22.000Z", "max_issues_repo_path": "test/Lib/STFTSpec.hs", "max_issues_repo_name": "davlum/haskell-twm", "max_issues_repo_head_hexsha": "2e407d6f8b28aafa889ea3c1b134c8cb41803f1c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Lib/STFTSpec.hs", "max_forks_repo_name": "davlum/haskell-twm", "max_forks_repo_head_hexsha": "2e407d6f8b28aafa889ea3c1b134c8cb41803f1c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9789473684, "max_line_length": 94, "alphanum_fraction": 0.5710219186, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5938631311395277}} {"text": "module Main where\n\nimport Graphics.Rendering.Chart.Backend.Diagrams (toFile)\nimport qualified Graphics.Rendering.Chart.Easy as Plt\nimport Numeric.GSL.ODE\nimport Numeric.LinearAlgebra\n\ndynamics :: Double -> [Double] -> [Double]\ndynamics _ [_, x1, w] =\n [ x1,\n - mass * g + k * w + cd * x1 ** 2,\n (torque - c * w) / j\n ]\n where\n -- timestep\n dt = 0.01\n -- Coefficient of drag\n cd = 0.1\n -- mass\n mass = 22\n -- gravity\n g = 9.8\n -- inertia\n j = 0.05\n -- Omega to thrust\n k = 5\n -- Coefficient of friction motor\n c = 0.1\n -- Calculate a physics based torque\n torque =\n clamp (-10, 10) $\n mass * g * j / (k * dt)\n - x1 / dt ** 2\n - w * j / dt\n + c * w\n -- Clamp between lower bound and upper bound\n clamp (lb, ub) x = max lb (min ub x)\n\ndumbCopter :: IO ()\ndumbCopter = toFile Plt.def \"DumpCopter.svg\" $ do\n let totalTime = 5\n dt = 0.01\n ts = linspace (round $ totalTime / dt) (0, totalTime)\n sol = odeSolve dynamics [0, -10, 0] ts\n [pos, vel, omega] = toColumns sol\n ts' = toList ts\n Plt.plot (Plt.line \"pos\" [zip ts' (toList pos)])\n Plt.plot (Plt.line \"vel\" [zip ts' (toList vel)])\n Plt.plot (Plt.line \"omega\" [zip ts' (toList omega)])\n\nmain :: IO ()\nmain = dumbCopter\n", "meta": {"hexsha": "d476823b39064b28872e53414d1d054ef5132f4a", "size": 1297, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Sim/Dumpcopter.hs", "max_stars_repo_name": "matte1/halman", "max_stars_repo_head_hexsha": "1b00010c300de931889c61bbb12141fad7285c65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Sim/Dumpcopter.hs", "max_issues_repo_name": "matte1/halman", "max_issues_repo_head_hexsha": "1b00010c300de931889c61bbb12141fad7285c65", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Sim/Dumpcopter.hs", "max_forks_repo_name": "matte1/halman", "max_forks_repo_head_hexsha": "1b00010c300de931889c61bbb12141fad7285c65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4716981132, "max_line_length": 59, "alphanum_fraction": 0.5612952968, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5938403419833685}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# OPTIONS_GHC -Wall #-}\n\n-- | Metric classes\nmodule Plankton.Metric\n ( Signed(..)\n , Normed(..)\n , Metric(..)\n , Epsilon(..)\n , (\u2248)\n ) where\n\nimport Data.Complex (Complex(..))\nimport Plankton.Additive\nimport Plankton.Field\nimport Plankton.Multiplicative\nimport qualified Protolude as P\nimport Protolude\n (Bool(..), Double, Eq(..), Float, Int, Integer, Ord(..), ($), (&&))\n\n-- | 'signum' from base is not an operator replicated in numhask, being such a very silly name, and preferred is the much more obvious 'sign'. Compare with 'Norm' and 'Banach' where there is a change in codomain\n--\n-- > abs a * sign a == a\n--\n-- Generalising this class tends towards size and direction (abs is the size on the one-dim number line of a vector with its tail at zero, and sign is the direction, right?).\nclass (MultiplicativeUnital a) =>\n Signed a where\n sign :: a -> a\n abs :: a -> a\n\ninstance Signed Double where\n sign a =\n if a >= zero\n then one\n else negate one\n abs = P.abs\n\ninstance Signed Float where\n sign a =\n if a >= zero\n then one\n else negate one\n abs = P.abs\n\ninstance Signed Int where\n sign a =\n if a >= zero\n then one\n else negate one\n abs = P.abs\n\ninstance Signed Integer where\n sign a =\n if a >= zero\n then one\n else negate one\n abs = P.abs\n\n-- | Like Signed, except the codomain can be different to the domain.\nclass Normed a b where\n size :: a -> b\n\ninstance Normed Double Double where\n size = P.abs\n\ninstance Normed Float Float where\n size = P.abs\n\ninstance Normed Int Int where\n size = P.abs\n\ninstance Normed Integer Integer where\n size = P.abs\n\ninstance (Multiplicative a, ExpField a, Normed a a) =>\n Normed (Complex a) a where\n size (rx :+ ix) = sqrt (rx * rx + ix * ix)\n\n-- | distance between numbers\n--\n-- > distance a b >= zero\n-- > distance a a == zero\n-- > \\a b c -> distance a c + distance b c - distance a b >= zero &&\n-- > distance a b + distance b c - distance a c >= zero &&\n-- > distance a b + distance a c - distance b c >= zero &&\nclass Metric a b where\n distance :: a -> a -> b\n\ninstance Metric Double Double where\n distance a b = abs (a - b)\n\ninstance Metric Float Float where\n distance a b = abs (a - b)\n\ninstance Metric Int Int where\n distance a b = abs (a - b)\n\ninstance Metric Integer Integer where\n distance a b = abs (a - b)\n\ninstance (Multiplicative a, ExpField a, Normed a a) =>\n Metric (Complex a) a where\n distance a b = size (a - b)\n\n-- | todo: This should probably be split off into some sort of alternative Equality logic, but to what end?\nclass (AdditiveGroup a) =>\n Epsilon a where\n nearZero :: a -> Bool\n aboutEqual :: a -> a -> Bool\n positive :: (Eq a, Signed a) => a -> Bool\n positive a = a == abs a\n veryPositive :: (Eq a, Signed a) => a -> Bool\n veryPositive a = P.not (nearZero a) && positive a\n veryNegative :: (Eq a, Signed a) => a -> Bool\n veryNegative a = P.not (nearZero a P.|| positive a)\n\ninfixl 4 \u2248\n\n-- | todo: is utf perfectly acceptable these days?\n(\u2248) :: (Epsilon a) => a -> a -> Bool\n(\u2248) = aboutEqual\n\ninstance Epsilon Double where\n nearZero a = abs a <= (1e-12 :: Double)\n aboutEqual a b = nearZero $ a - b\n\ninstance Epsilon Float where\n nearZero a = abs a <= (1e-6 :: Float)\n aboutEqual a b = nearZero $ a - b\n\ninstance Epsilon Int where\n nearZero a = a == zero\n aboutEqual a b = nearZero $ a - b\n\ninstance Epsilon Integer where\n nearZero a = a == zero\n aboutEqual a b = nearZero $ a - b\n\ninstance (Epsilon a) => Epsilon (Complex a) where\n nearZero (rx :+ ix) = nearZero rx && nearZero ix\n aboutEqual a b = nearZero $ a - b\n", "meta": {"hexsha": "83a35904664e0114ae82d8487eb2f8ed7e21aafb", "size": 3711, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Plankton/Metric.hs", "max_stars_repo_name": "chessai/plankton", "max_stars_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T05:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T05:38:15.000Z", "max_issues_repo_path": "src/Plankton/Metric.hs", "max_issues_repo_name": "chessai/plankton", "max_issues_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "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/Plankton/Metric.hs", "max_forks_repo_name": "chessai/plankton", "max_forks_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.951048951, "max_line_length": 212, "alphanum_fraction": 0.6389113447, "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5935205937509156}} {"text": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Types\n ( Planet(..)\n , mass\n , diameter\n , pullOn\n , distance\n , distanceScale\n , alterSpeed\n , newPoint\n )\nwhere\n\nimport Numeric.LinearAlgebra\n\ndata Planet = Earth | Jupiter deriving (Eq, Show)\n\ntype Point = (Float, Float)\n\nmass :: Planet -> Int\nmass Earth = 5972\nmass Jupiter = 1898000\n\ndistanceScale :: Float\ndistanceScale = 1000000\n\ndiameter :: Planet -> Integer\ndiameter Earth = 12756000 -- m\ndiameter Jupiter = 142984000\n\ndistance :: Point -> Point -> Float\ndistance (aX, aY) (bX, bY) =\n let height = abs (bY - aY)\n width = abs (bX - aX)\n height2 = height ^ 2\n width2 = width ^ 2\n in sqrt (height2 + width2) * distanceScale * 100 -- planets actual size so brag about distance\n\npullOn :: Planet -> Point -> Planet -> Point -> Vector Float -- a accelaration pointing out from a\npullOn on a from b =\n let\n gConstant = 15 * 10 ^ 12\n massA = mass on\n massB = mass from\n dist = distance b a ^ 2\n forceScalar =\n (-gConstant * fromIntegral massA * fromIntegral massB) / dist\n accScalar = forceScalar / fromIntegral massA\n in\n scale accScalar (vectorize b a)\n\nvectorize :: Point -> Point -> Vector Float\nvectorize (ax, ay) (bx, by) = fromList [bx - ax, by - ay]\n\nalterSpeed :: Vector Float -> Vector Float -> Vector Float\nalterSpeed current pullForce = add current pullForce -- todo\n\nnewPoint :: Point -> Vector Float -> Point\nnewPoint (ax, ay) v = case toList v of\n [bx, by] -> (ax + bx, ay + by)\n x ->\n error\n $ \"cannot create new point from speed vector with /= 2 elements \"\n ++ show x\n", "meta": {"hexsha": "37cd294e291dac84b5e9e2e01b5a56f98a1f3ade", "size": 1720, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Types.hs", "max_stars_repo_name": "mariatsji/planets", "max_stars_repo_head_hexsha": "6ca1272ef18817359c4e30495e61c30599adaa45", "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/Types.hs", "max_issues_repo_name": "mariatsji/planets", "max_issues_repo_head_hexsha": "6ca1272ef18817359c4e30495e61c30599adaa45", "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/Types.hs", "max_forks_repo_name": "mariatsji/planets", "max_forks_repo_head_hexsha": "6ca1272ef18817359c4e30495e61c30599adaa45", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0606060606, "max_line_length": 99, "alphanum_fraction": 0.6058139535, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5935013212256741}} {"text": "{-# LANGUAGE TypeApplications #-}\n\nmodule Section_4_5 where\n\nimport MNIST\nimport Numeric.LinearAlgebra\nimport Section_4_5.TwoLayer\n\nmain :: IO ()\nmain = do\n putStrLn \"Loading Labels...\"\n (Labels _ labels) <- getLabels @Training @OneHotLabel\n\n putStrLn \"Loading Images...\"\n (Images _ _ _ images) <- getImages @Training @FlattenImage True\n\n putStrLn \"Creating Initial Network...\"\n network <- initNetwork [784, 50, 10] [sigmoid, softmax]\n\n putStrLn \"Picking Learning Data...\"\n let label = vector $ map fromIntegral $ labels !! 10\n image = vector $ images !! 10\n\n putStrLn $ \"Answer: \" ++ show label\n\n putStrLn $ \"Prediction before learning: \" ++ show (predict network image)\n\n putStrLn \"Learning Network...\"\n let nw = updateNetwork loss [image] [label] network\n\n putStrLn $ \"Prediction after learning: \" ++ show (predict nw image)\n", "meta": {"hexsha": "49550a65ef33a992d5b473899f8734e5a11753d3", "size": 850, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Section_4_5.hs", "max_stars_repo_name": "lotz84/deep-learning-from-scratch", "max_stars_repo_head_hexsha": "7f58f3c637da0fcbf1981af5f058af5015740383", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-01-16T13:39:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T19:27:32.000Z", "max_issues_repo_path": "src/Section_4_5.hs", "max_issues_repo_name": "lotz84/deep-learning-from-scratch", "max_issues_repo_head_hexsha": "7f58f3c637da0fcbf1981af5f058af5015740383", "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/Section_4_5.hs", "max_forks_repo_name": "lotz84/deep-learning-from-scratch", "max_forks_repo_head_hexsha": "7f58f3c637da0fcbf1981af5f058af5015740383", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5625, "max_line_length": 75, "alphanum_fraction": 0.6964705882, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5934336278071711}} {"text": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RankNTypes #-}\nmodule Primitives.Math (primitives) where\n\nimport Data.Complex (Complex(..))\nimport Data.Functor ((<&>))\nimport Data.List (foldl', foldl1')\nimport Data.Ratio (approxRational)\n\nimport Val\nimport EvaluationMonad (throwError, panic)\nimport Types.Unwrappers (unwrapNum, unwrapRealNum, unwrapExactInteger)\nimport Primitives.Bool (predicate, predicateM)\nimport Primitives.Misc (valuesB)\n\naddP, mulP, modP, quotP, remP :: Primitive\naddP = numericBinop \"+\" (+) 0\nmulP = numericBinop \"*\" (*) 1\nmodP = realBinop1 \"mod\" mod\nquotP = realBinop1 \"quotient\" quot\nremP = realBinop1 \"remainder\" rem\n\n-- | Converts a (Haskell) builtin function on Integers to a 'Primitive'.\n-- The primitive can only cause type errors;\n-- Too many arguments will be folded over the operation;\n-- none will use the default value.\nnumericBinop :: Symbol\n -> (Number -> Number -> Number)\n -> Number\n -> Primitive\nnumericBinop name op start = Prim name (AtLeast 0) $\n fmap (Number . foldl' op start) . mapM unwrapNum\n\n-- | Same as numericBinop, except at least one arg must be given.\nrealBinop1 :: Symbol\n -> (RealNumber -> RealNumber -> RealNumber)\n -> Primitive\nrealBinop1 name op = Prim name (AtLeast 1) $\n fmap (Number . Real . foldl1' op) . mapM unwrapRealNum\n\nguardDivZero :: Primitive -> Primitive\nguardDivZero (Prim name arity f) = Prim name arity $ \\args ->\n if any isExactZeroVal $ tail args\n then throwError $ Default \"divide by zero\"\n else f args\n where\n isExactZeroVal (Number n) = isExactZero n\n isExactZeroVal _ = False\n\n-- | See the r7rs standard.\n--\n-- (- n) evaluates to -n, but (- x y z) evaluates to ((x - y) - z).\nsubP :: Primitive\nsubP = Prim \"-\" (AtLeast 1) $ \\case\n [x] -> Number . negate <$> unwrapNum x\n as@(_:_) -> Number . foldl1' (-) <$> mapM unwrapNum as\n _ -> panic \"sub arity\"\n\n-- | r7rs: (/ n) is 1/n, (/ x y z) is ((x / y) / z)\ndivP :: Primitive\ndivP = guardDivZero $ Prim \"/\" (AtLeast 1) $ \\case\n [] -> panic \"div arity\"\n [x] -> Number . (1 /) <$> unwrapNum x\n as -> Number . foldl1' (/) <$> mapM unwrapNum as\n\nnegateP :: Primitive\nnegateP = Prim \"negate\" (Exactly 1) $\n \\[x] -> Number . negate <$> unwrapNum x\n\nnumericPredicate :: Symbol -> (RealNumber -> Bool) -> Primitive\nnumericPredicate name p = predicateM name $ fmap p . unwrapRealNum\n\nzeroCheck :: Primitive\nzeroCheck = predicate \"zero?\" unwrapNum (== 0)\n\npositiveCheck :: Primitive\npositiveCheck = numericPredicate \"positive?\" (> 0)\n\nnegativeCheck :: Primitive\nnegativeCheck = numericPredicate \"negative?\" (< 0)\n\noddCheck :: Primitive\noddCheck = numericPredicate \"odd?\" $ (0 /=) . mod 2\n\nevenCheck :: Primitive\nevenCheck = numericPredicate \"even?\" $ (0 ==) . mod 2\n\n-------------------------------------------------------------------------------\n-- typically useful math operations\n-------------------------------------------------------------------------------\n\ninexactP :: Primitive\ninexactP = Prim \"inexact\" (Exactly 1) $\n \\[x] -> unwrapNum x <&> \\case\n Real r -> Number $ Real $ realInexact r\n Complex (r :+ i) -> Number $ Complex $ realInexact r :+ realInexact i\n\nrationalizeP :: Primitive\nrationalizeP = Prim \"rationalize\" (Exactly 2) $\n \\[x, eps] -> do\n rx <- unwrapRealNum x\n reps <- unwrapRealNum eps\n return $ Number $ Real $ Ratnum $ approxRational rx reps\n\nsquareP :: Primitive\nsquareP = Prim \"square\" (Exactly 1) $\n \\[x] -> Number . (\\n -> n*n) <$> unwrapNum x\n\n-- | specialize ^ to Int powers\n(^!) :: Num a => a -> Int -> a\nx ^! n = x ^ n\n\nexactIntegerSqrtP :: Primitive\nexactIntegerSqrtP = Prim \"exact-integer-sqrt\" (Exactly 1) $\n \\[k] -> do\n kN <- unwrapExactInteger k\n let root = squareRoot kN\n residual = kN - root ^! 2\n valuesB [makeBignum root, makeBignum residual]\n where\n -- This impl of the standard integer square root algorithm is from\n -- https://wiki.haskell.org/Generic_number_type#squareRoot\n squareRoot :: Integer -> Integer\n squareRoot 0 = 0\n squareRoot 1 = 1\n squareRoot n =\n let twopows = iterate (^! 2) 2\n (lowerRoot, lowerN) =\n last $ takeWhile ((n >=) . snd) $ zip (1:twopows) twopows\n newtonStep x = div (x + n `div` x) 2\n iters = iterate newtonStep (squareRoot (div n lowerN) * lowerRoot)\n isRoot r = r ^! 2 <= n && n < (r+1) ^! 2\n in head $ dropWhile (not . isRoot) iters\n\nexptP :: Primitive\nexptP = Prim \"expt\" (Exactly 2) $\n \\[z1, z2] -> do\n z1' <- unwrapNum z1\n z2' <- unwrapNum z2\n return $ Number $ z1' ** z2'\n\n-------------------------------------------------------------------------------\n-- Complex functions\n-------------------------------------------------------------------------------\n\nmakeRectangularP :: Primitive\nmakeRectangularP = Prim \"make-rectangular\" (Exactly 2) $\n \\[x, y] -> do\n a <- unwrapRealNum x\n b <- unwrapRealNum y\n return $ Number $ Complex $ a :+ b\n\nmakePolarP :: Primitive\nmakePolarP = Prim \"make-polar\" (Exactly 2) $\n \\[m, theta] -> do\n m' <- unwrapRealNum m\n theta' <- unwrapRealNum theta\n return $ Number $ Real m' * Complex (cos theta' :+ sin theta')\n\nrealPartP :: Primitive\nrealPartP = Prim \"real-part\" (Exactly 1) $\n \\[z] -> unwrapNum z <&> \\case\n Real r -> Number $ Real r\n Complex (r :+ _i) -> Number $ Real r\n\nimagPartP :: Primitive\nimagPartP = Prim \"imag-part\" (Exactly 1) $\n \\[z] -> unwrapNum z <&> \\case\n Real _r -> Number $ Real 0\n Complex (_r :+ i) -> Number $ Real i\n\nmagnitudeP :: Primitive\nmagnitudeP = Prim \"magnitude\" (Exactly 1) $\n \\[z] -> Number . abs <$> unwrapNum z\n\nangleP :: Primitive\nangleP = Prim \"angle\" (Exactly 1) $\n \\[z] -> unwrapNum z <&> \\case\n Real r\n | r < 0 || isNegativeZero r -> Number pi\n | otherwise -> Number 0\n Complex (a :+ b) -> Number $ Real $ atan2 b a\n\nliftFloatingMonop :: (Number -> Number) -> Builtin\nliftFloatingMonop f = asBuiltin\n where asBuiltin [x] = do\n nx <- unwrapNum x\n return $ Number $ f nx\n asBuiltin _ = panic \"liftFloatingMonop arity\"\n\nmakeFloatingMonopPrim :: (Symbol, Number -> Number) -> Primitive\nmakeFloatingMonopPrim (name, f) = Prim name (Exactly 1) $ liftFloatingMonop f\n\nfloatingMonopPs :: [Primitive]\nfloatingMonopPs = map makeFloatingMonopPrim\n [ (\"exp\", exp)\n , (\"sqrt\", sqrt)\n , (\"sin\", sin)\n , (\"cos\", cos)\n , (\"tan\", tan)\n , (\"asin\", asin)\n , (\"acos\", acos)\n ]\n\nlogP :: Primitive\nlogP = Prim \"log\" (Between 1 2) $ \\case\n [z] -> Number . log <$> unwrapNum z\n [z1, z2] -> do\n z1' <- unwrapNum z1\n z2' <- unwrapNum z2\n return $ Number $ logBase z2' z1'\n _ -> panic \"logB arity\"\n\natanP :: Primitive\natanP = Prim \"atan\" (Between 1 2) $ \\case\n [z] -> Number . atan <$> unwrapNum z\n [y, x] -> do\n y' <- unwrapRealNum y\n x' <- unwrapRealNum x\n return $ Number $ Real $ atan2 y' x'\n _ -> panic \"atanB arity\"\n\n-------------------------------------------------------------------------------\n\nprimitives :: [Primitive]\nprimitives = [ addP\n , subP\n , mulP\n , divP\n , modP\n , quotP\n , remP\n , negateP\n , zeroCheck\n , positiveCheck\n , negativeCheck\n , oddCheck\n , evenCheck\n\n , inexactP\n , rationalizeP\n , atanP\n , exactIntegerSqrtP\n , squareP\n , exptP\n\n , makeRectangularP\n , makePolarP\n , realPartP, imagPartP\n , magnitudeP, angleP\n , logP\n ]\n ++ floatingMonopPs\n", "meta": {"hexsha": "b01ac20dfce72523fbce20b845b43cbc7ba97c56", "size": 7643, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Primitives/Math.hs", "max_stars_repo_name": "JKTKops/Thcheme", "max_stars_repo_head_hexsha": "f7f73fae244477ccdcd71b23792d2ed50a844d68", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-07-06T15:58:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-07T10:22:01.000Z", "max_issues_repo_path": "src/Primitives/Math.hs", "max_issues_repo_name": "JKTKops/Thcheme", "max_issues_repo_head_hexsha": "f7f73fae244477ccdcd71b23792d2ed50a844d68", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-05T03:48:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-20T06:02:39.000Z", "max_forks_repo_path": "src/Primitives/Math.hs", "max_forks_repo_name": "JKTKops/Thcheme", "max_forks_repo_head_hexsha": "f7f73fae244477ccdcd71b23792d2ed50a844d68", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0905511811, "max_line_length": 79, "alphanum_fraction": 0.5726808845, "num_tokens": 2232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6926419958239133, "lm_q1q2_score": 0.5927984516568772}} {"text": "module ECC.Estimate (estimate,showEstimate) where\n\nimport ECC.Types\nimport qualified Data.Vector.Unboxed as U\nimport Statistics.Sample (mean)\nimport Statistics.Resampling (resample, fromResample, Estimator(..))\nimport Statistics.Resampling.Bootstrap (bootstrapBCA)\nimport Statistics.Types (Estimate (..), ConfInt, mkCL, ConfInt(..), confidenceLevel)\nimport System.Random.MWC (create)\nimport System.Random.MWC\nimport Numeric\n\n-- Estimate the lower and upper bounds, given a random generator state,\n-- a confidence percentage, and a Bit Errors structure.\n\n-- If there are to many samples (as often happens with good error correcting codes),\n-- then we cheat, and combine samples.\n\nestimate :: GenIO -> Double -> MessageLength -> BEs -> IO (Maybe (Estimate ConfInt Double))\nestimate g confidence m_len bes\n | sumBEs bes == 0 = return Nothing\n | otherwise =\n -- 1000 is the default for criterion\n do resamples <- resample g [Mean] 1000 sampleU\n-- print $ U.length $ fromResample $ head $ resamples\n-- print resamples\n return $ Just $ head $ bootstrapBCA (mkCL confidence) sampleU {- [Mean] -} resamples\n where\n sample = map (\\ be -> be / fromIntegral m_len)\n $ extractBEs bes\n sampleU = U.fromList sample\n\n-- | Show estimate in an understandable format\"\nshowEstimate :: Estimate ConfInt Double -> String\nshowEstimate est = showEFloat (Just 2) (estPoint est)\n $ (\" +\" ++)\n $ (if confIntLDX estErr == 0 then (\"?\" ++)\n else showsPercent ((confIntUDX estErr) / (estPoint est)))\n $ (\" -\" ++)\n $ (if confIntUDX estErr == 0 then (\"?\" ++)\n else showsPercent ((confIntLDX estErr) / (estPoint est)))\n $ (\" \" ++)\n $ showsPercent (confidenceLevel (confIntCL estErr))\n $ \"\"\n where\n estErr = estError est\n\nshowsPercent f = shows (round (100 * f)) . (\"%\" ++)\n\n-- (1 - (estLowerBound est) / (estPoint est))))\n\n\n\n\n\n", "meta": {"hexsha": "396cb1cf7fcdd5e51ad498699422006eeada2563", "size": 2006, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ECC/Estimate.hs", "max_stars_repo_name": "ku-fpg/ecc-manifold", "max_stars_repo_head_hexsha": "90af64b6f857ec4d7d0707c37bad25e73a06ae31", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-06-26T17:33:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-24T01:30:34.000Z", "max_issues_repo_path": "src/ECC/Estimate.hs", "max_issues_repo_name": "ku-fpg/ecc-manifold", "max_issues_repo_head_hexsha": "90af64b6f857ec4d7d0707c37bad25e73a06ae31", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-06-02T07:32:26.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-27T05:31:54.000Z", "max_forks_repo_path": "src/ECC/Estimate.hs", "max_forks_repo_name": "ku-fpg/ecc-manifold", "max_forks_repo_head_hexsha": "90af64b6f857ec4d7d0707c37bad25e73a06ae31", "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.8214285714, "max_line_length": 94, "alphanum_fraction": 0.6316051844, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5926716806350013}} {"text": "{-# LANGUAGE DeriveDataTypeable, PatternGuards #-}\nmodule Physics.Quaternion\n ( Quaternion(..)\n , Complicated(..)\n , Hamiltonian(..)\n , slerp\n , asinq\n , acosq\n , atanq\n , asinhq\n , acoshq\n , atanhq\n , absi\n , pow\n , rotate\n ) where\n\nimport Control.Applicative\nimport Control.Lens\nimport Control.Lens.Rep\nimport Data.Complex (Complex((:+)))\nimport Data.Data\nimport Data.Distributive\nimport Data.Foldable\nimport Data.Monoid\nimport Data.Traversable\nimport Physics.Epsilon\nimport Physics.Involutive\nimport Physics.Metric\nimport Physics.V3\nimport Physics.Vector\nimport Prelude hiding (any)\n\ndata Quaternion a = Quaternion a a a a deriving (Eq,Ord,Read,Show,Data,Typeable)\n\ninstance Functor Quaternion where\n fmap f (Quaternion e i j k) = Quaternion (f e) (f i) (f j) (f k)\n a <$ _ = Quaternion a a a a\n\ninstance Applicative Quaternion where\n pure a = Quaternion a a a a\n Quaternion f g h i <*> Quaternion a b c d = Quaternion (f a) (g b) (h c) (i d)\n\ninstance Monad Quaternion where\n return = pure\n (>>=) = bindRep\n\ninstance Representable Quaternion where\n rep f = Quaternion (f e) (f i) (f j) (f k)\n\ninstance Foldable Quaternion where\n foldMap f (Quaternion e i j k) = f e `mappend` f i `mappend` f j `mappend` f k\n foldr f z (Quaternion e i j k) = f e (f i (f j (f k z)))\n\ninstance Traversable Quaternion where\n traverse f (Quaternion e i j k) = Quaternion <$> f e <*> f i <*> f j <*> f k\n\ninstance RealFloat a => Num (Quaternion a) where\n {-# SPECIALIZE instance Num (Quaternion Float) #-}\n {-# SPECIALIZE instance Num (Quaternion Double) #-}\n (+) = liftA2 (+)\n (-) = liftA2 (-)\n negate = fmap negate\n Quaternion a1 b1 c1 d1 * Quaternion a2 b2 c2 d2 = Quaternion\n (a1*a2 - b1*b2 - c1*c2 - d1*d2)\n (a1*b2 + b1*a2 + c1*d2 - d1*c2)\n (a1*c2 - b1*d2 + c1*a2 + d1*b2)\n (a1*d2 + b1*c2 - c1*b2 + d1*a2)\n fromInteger x = Quaternion (fromInteger x) 0 0 0\n abs z = Quaternion (norm z) 0 0 0\n signum q@(Quaternion e i j k)\n | m == 0.0 = q\n | not (isInfinite m || isNaN m) = q ^/ sqrt m\n | any isNaN q = qNaN\n | not (ii || ij || ik) = Quaternion 1 0 0 0\n | not (ie || ij || ik) = Quaternion 0 1 0 0\n | not (ie || ii || ik) = Quaternion 0 0 1 0\n | not (ie || ii || ij) = Quaternion 0 0 0 1\n | otherwise = qNaN\n where\n m = quadrance q\n ie = isInfinite e\n ii = isInfinite i\n ij = isInfinite j\n ik = isInfinite k\n\n -- abs = error \"Quaternion.abs: use norm\"\n -- signum = error \"Quaternion.signum: use signorm\"\n\nqNaN :: RealFloat a => Quaternion a\nqNaN = Quaternion fNaN fNaN fNaN fNaN where fNaN = 0/0\n\n-- {-# RULES \"abs/norm\" abs x = Quaternion (norm x) 0 0 0 #-}\n-- {-# RULES \"signum/signorm\" signum = signorm #-}\n\n-- this will attempt to rewrite calls to abs to use norm intead when it is available.\n\ninstance RealFloat a => Fractional (Quaternion a) where\n {-# SPECIALIZE instance Fractional (Quaternion Float) #-}\n {-# SPECIALIZE instance Fractional (Quaternion Double) #-}\n Quaternion q0 q1 q2 q3 / Quaternion r0 r1 r2 r3 = Quaternion (r0*q0+r1*q1+r2*q2+r3*q3)\n (r0*q1-r1*q0-r2*q3+r3*q2)\n (r0*q2+r1*q3-r2*q0-r3*q1)\n (r0*q3-r1*q2+r2*q1-r3*q0)\n ^/ (r0*r0 + r1*r1 + r2*r2 + r3*r3)\n recip q = q ^/ quadrance q\n fromRational x = Quaternion (fromRational x) 0 0 0\n\ninstance Metric Quaternion where\n Quaternion e i j k `dot` Quaternion e' i' j' k' = e*e' + i*i' + j*j' + k*k'\n\nclass Complicated t where\n e :: Functor f => (a -> f a) -> t a -> f (t a)\n i :: Functor f => (a -> f a) -> t a -> f (t a)\n\ninstance Complicated Complex where\n e f (a :+ b) = (:+ b) <$> f a\n i f (a :+ b) = (a :+) <$> f b\n\ninstance Complicated Quaternion where\n e f (Quaternion a b c d) = (\\a' -> Quaternion a' b c d) <$> f a\n i f (Quaternion a b c d) = (\\b' -> Quaternion a b' c d) <$> f b\n\nclass Complicated t => Hamiltonian t where\n j :: Functor f => (a -> f a) -> t a -> f (t a)\n k :: Functor f => (a -> f a) -> t a -> f (t a)\n ijk :: Functor f => (V3 a -> f (V3 a)) -> t a -> f (t a)\n\ninstance Hamiltonian Quaternion where\n j f (Quaternion a b c d) = (\\c' -> Quaternion a b c' d) <$> f c\n k f (Quaternion a b c d) = Quaternion a b c <$> f d\n\n ijk f (Quaternion a b c d) = (\\(V3 b' c' d') -> Quaternion a b' c' d') <$> f (V3 b c d)\n\ninstance Distributive Quaternion where\n distribute f = Quaternion (fmap (^.e) f) (fmap (^.i) f) (fmap (^.j) f) (fmap (^.k) f)\n\ninstance (Involutive a, Num a) => Involutive (Quaternion a) where\n conjugate (Quaternion e i j k) = Quaternion (conjugate e) (-i) (-j) (-k)\n\n\nreimagine :: RealFloat a => a -> a -> Quaternion a -> Quaternion a\nreimagine r s (Quaternion _ i j k)\n | isNaN s || isInfinite s = Quaternion r\n (if i /= 0 then i * s else 0)\n (if j /= 0 then j * s else 0)\n (if k /= 0 then k * s else 0)\n | otherwise = Quaternion r (i * s) (j * s) (k * s)\n\n-- | quadrance of the imaginary component\nqi :: Num a => Quaternion a -> a\nqi (Quaternion _ i j k) = i*i + j*j + k*k\n\nabsi :: Floating a => Quaternion a -> a\nabsi = sqrt . qi\n\npow :: RealFloat a => Quaternion a -> a -> Quaternion a\npow q t = exp (t *^ log q)\n\n-- ehh..\ninstance RealFloat a => Floating (Quaternion a) where\n {-# SPECIALIZE instance Floating (Quaternion Float) #-}\n {-# SPECIALIZE instance Floating (Quaternion Double) #-}\n pi = Quaternion pi 0 0 0\n exp q@(Quaternion e i j k)\n | qiq == 0 = Quaternion (exp e) i j k\n | ai <- sqrt qiq, ee <- exp e = reimagine (ee * cos ai) (ee * (sin ai / ai)) q\n where qiq = qi q\n log q@(Quaternion e i j k)\n | qiq == 0 = if e >= 0 then Quaternion (log e) i j k else Quaternion (log (negate e)) pi j k -- mmm, pi\n | ai <- sqrt qiq, m <- sqrt (e*e + qiq) = reimagine (log m) (atan2 m e / ai) q\n where qiq = qi q\n x ** y = exp (y * log x)\n sqrt q@(Quaternion e i j k)\n | m == 0 = q\n | qiq == 0 = if e > 0 then Quaternion (sqrt e) 0 0 0 else Quaternion 0 (sqrt (negate e)) 0 0\n | im <- sqrt (0.5*(m-e)) / sqrt qiq = Quaternion (0.5*(m+e)) (i*im) (j*im) (k*im)\n where qiq = qi q\n m = sqrt (e*e + qiq)\n cos q@(Quaternion e i j k)\n | qiq == 0 = Quaternion (cos e) i j k\n | ai <- sqrt qiq = reimagine (cos e * cosh ai) (- sin e * (sinh ai / ai)) q\n where qiq = qi q\n sin q@(Quaternion e i j k)\n | qiq == 0 = Quaternion (sin e) i j k\n | ai <- sqrt qiq = reimagine (sin e * cosh ai) (cos e * (sinh ai / ai)) q\n where qiq = qi q\n tan q@(Quaternion e i j k)\n | qiq == 0 = Quaternion (tan e) i j k\n | ai <- sqrt qiq, ce <- cos e, sai <- sinh ai, d <- ce*ce + sai*sai =\n reimagine (ce * sin e / d) (cosh ai * (sai / ai) / d) q\n where qiq = qi q\n sinh q@(Quaternion e i j k)\n | qiq == 0 = Quaternion (sinh e) i j k\n | ai <- sqrt qiq = reimagine (sinh e * cos ai) (cosh e * (sin ai / ai)) q\n where qiq = qi q\n cosh q@(Quaternion e i j k)\n | qiq == 0 = Quaternion (cosh e) i j k\n | ai <- sqrt qiq = reimagine (cosh e * cos ai) ((sinh e * sin ai) / ai) q\n where qiq = qi q\n tanh q@(Quaternion e i j k)\n | qiq == 0 = Quaternion (tanh e) i j k\n | ai <- sqrt qiq, se <- sinh e, cai <- cos ai, d <- se*se + cai*cai =\n reimagine ((cosh e * se) / d) ((cai * (sin ai / ai)) / d) q\n where qiq = qi q\n\n asin q = cut asin q\n acos q = cut acos q\n atan q = cut atan q\n\n asinh q = cut asinh q\n acosh q = cut acosh q\n atanh q = cut atanh q\n\ncut :: RealFloat a => (Complex a -> Complex a) -> Quaternion a -> Quaternion a\ncut f q@(Quaternion e _ j k)\n | qiq == 0 = Quaternion a b j k\n | otherwise = reimagine a (b / ai) q\n where qiq = qi q\n ai = sqrt qiq\n a :+ b = f (e :+ ai)\n\ncutWith :: RealFloat a => Complex a -> Quaternion a -> Quaternion a\ncutWith (r :+ im) q@(Quaternion e i j k)\n | e /= 0 || qiq == 0 || isNaN qiq || isInfinite qiq = error \"bad cut\"\n | s <- im / sqrt qiq = Quaternion r (i*s) (j*s) (k*s)\n where qiq = qi q\n\nasinq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\nasinq q@(Quaternion e _ _ _) u\n | qiq /= 0.0 || e >= -1 && e <= 1 = asin q\n | otherwise = cutWith (asin (e :+ sqrt qiq)) u\n where qiq = qi q\n\nacosq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\nacosq q@(Quaternion e _ _ _) u\n | qiq /= 0.0 || e >= -1 && e <= 1 = acos q\n | otherwise = cutWith (acos (e :+ sqrt qiq)) u\n where qiq = qi q\n\natanq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\natanq q@(Quaternion e _ _ _) u\n | e /= 0.0 || qiq >= -1 && qiq <= 1 = atan q\n | otherwise = cutWith (atan (e :+ sqrt qiq)) u\n where qiq = qi q\n\nasinhq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\nasinhq q@(Quaternion e _ _ _) u\n | e /= 0.0 || qiq >= -1 && qiq <= 1 = asinh q\n | otherwise = cutWith (asinh (e :+ sqrt qiq)) u\n where qiq = qi q\n\nacoshq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\nacoshq q@(Quaternion e _ _ _) u\n | qiq /= 0.0 || e >= 1 = asinh q\n | otherwise = cutWith (acosh (e :+ sqrt qiq)) u\n where qiq = qi q\n\natanhq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\natanhq q@(Quaternion e _ _ _) u\n | qiq /= 0.0 || e > -1 && e < 1 = atanh q\n | otherwise = cutWith (atanh (e :+ sqrt qiq)) u\n where qiq = qi q\n\nslerp :: RealFloat a => Quaternion a -> Quaternion a -> a -> Quaternion a\nslerp q p t\n | 1.0 - cosphi < 1e-8 = q\n | phi <- acos cosphi, r <- recip (sin phi)\n = (sin ((1-t)*phi)*r *^ q ^+^ f (sin (t*phi)*r) *^ p) ^/ sin phi\n where\n dqp = dot q p\n (cosphi, f) = if dqp < 0 then (-dqp, negate) else (dqp, id)\n{-# SPECIALIZE slerp :: Quaternion Float -> Quaternion Float -> Float -> Quaternion Float #-}\n{-# SPECIALIZE slerp :: Quaternion Double -> Quaternion Double -> Double -> Quaternion Double #-}\n\n--slerp :: RealFloat a => Quaternion a -> Quaternion a -> a -> Quaternion a\n--slerp q0 q1 = let q10 = q1 / q0 in \\t -> pow q10 t * q0\n\nrotate :: Num a => Quaternion a -> V3 a -> V3 a\nrotate (Quaternion a' b c d) (V3 x y z) = V3\n (2*((t8+t10)*x+(t6- t4)*y+(t3+t7)*z)+x)\n (2*((t4+ t6)*y+(t5+t10)*y+(t9-t2)*z)+y)\n (2*((t7- t3)*z+(t2+ t9)*z+(t5+t8)*z)+z)\n where\n a = -a'\n t2 = a*b\n t3 = a*c\n t4 = a*d\n t5 = -b*b\n t6 = b*c\n t7 = b*d\n t8 = -c*c\n t9 = c*d\n t10 = -d*d\n{-# SPECIALIZE rotate :: Quaternion Float -> V3 Float -> V3 Float #-}\n{-# SPECIALIZE rotate :: Quaternion Double -> V3 Double -> V3 Double #-}\n\ninstance (RealFloat a, Epsilon a) => Epsilon (Quaternion a) where\n nearZero = nearZero . quadrance\n", "meta": {"hexsha": "c0f48ab9eae72507e9238f9aac635ace7d573d5b", "size": 10544, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Physics/Quaternion.hs", "max_stars_repo_name": "ekmett/physics", "max_stars_repo_head_hexsha": "08a61035594b3023e3306457947a2a5474661af7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-06-15T12:22:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T02:48:06.000Z", "max_issues_repo_path": "Physics/Quaternion.hs", "max_issues_repo_name": "ekmett/physics", "max_issues_repo_head_hexsha": "08a61035594b3023e3306457947a2a5474661af7", "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": "Physics/Quaternion.hs", "max_forks_repo_name": "ekmett/physics", "max_forks_repo_head_hexsha": "08a61035594b3023e3306457947a2a5474661af7", "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.1466666667, "max_line_length": 107, "alphanum_fraction": 0.5723634294, "num_tokens": 3736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5926716693118909}} {"text": "{-# LANGUAGE ApplicativeDo #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE QuantifiedConstraints #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\nmodule Main where\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Foldable\nimport Data.List hiding (filter)\nimport Data.RVar\nimport Data.Random\nimport qualified Data.Text as T\nimport Data.Time\nimport Graphics.Vega.VegaLite hiding (repeat, sample)\nimport qualified Numeric.LinearAlgebra as V\nimport Prelude hiding (filter)\nimport Q.ContingentClaim.Options\nimport Q.MonteCarlo\nimport Q.Options.BlackScholes\nimport Q.Stats.TimeSeries\nimport Q.Stochastic.Discretize\nimport Q.Stochastic.Process\nimport Q.Time\nimport Q.Time.DayCounter\nimport Q.Types\nimport qualified Q.Util.File as QF\nimport Statistics.Sample.Histogram\n\nimport qualified Data.Time as Time\n\n\ndt :: Double\ndt = 1/365\ngbm = GeometricBrownian 0.0 0.15\n\n\n\nplotPayouts :: IO ()\nplotPayouts = do\n let strike = 100.0\n lowStrike = 95.0\n highStrike = 105.0\n expiry = fromGregorian 2015 3 31\n spots = [90, 90.01..110]\n calls = map (vanillaPayout Call strike) spots\n puts = map (vanillaPayout Put strike) spots\n callSpreads = map (spreadPayout Call lowStrike highStrike) spots\n putSpreads = map (spreadPayout Put lowStrike highStrike) spots\n straddles = map (straddlePayout strike) spots\n\n payouts = dataFromColumns []\n . dataColumn \"Spot\" (Numbers spots)\n . dataColumn \"Call\" (Numbers calls)\n . dataColumn \"Put\" (Numbers puts)\n . dataColumn \"Call Spread\" (Numbers callSpreads)\n . dataColumn \"Put Spread\" (Numbers putSpreads)\n . dataColumn \"Straddle\" (Numbers straddles)\n\n enc = encoding\n . position X [PName \"Spot\", PmType Quantitative]\n encVanillaCall = enc\n . position Y [PName \"Call\", PmType Quantitative]\n encVanillaPut = enc\n . position Y [PName \"Put\", PmType Quantitative]\n encCallSpread = enc\n . position Y [PName \"Call Spread\", PmType Quantitative]\n encPutSpread = enc\n . position Y [PName \"Put Spread\", PmType Quantitative]\n encStraddle = enc\n . position Y [PName \"Straddle\", PmType Quantitative]\n\n vl = toVegaLite [payouts [], vlConcat [ asSpec [encVanillaCall [], mark Line []]\n , asSpec [encVanillaPut [], mark Line []]\n , asSpec [encCallSpread [], mark Line []]\n , asSpec [encPutSpread [], mark Line []]\n , asSpec [encStraddle [], mark Line []]\n ]\n ]\n toHtmlFile \"/tmp/payouts.html\" vl\n\n-- Option delta is the sensitivity of the option to the underlying:\n-- \\(dV/dS\\).\n--\n-- for a fixed time and vol what is the delta per relative strike.\n-- How does delta look as a function of time\n-- How does delta look as a function of vol?\n\n\n\n-- How does delta look like as a function of the spot?\n-- Plot call delta against log relative strike.\n-- Plot put delta against log relative strike.\nstudyDelta :: IO ()\nstudyDelta = do\n let today = fromGregorian 2015 3 31\n expiry = YearFrac 1\n vol = 0.6\n spot = 100\n strikes = map Strike [80, 81..120]\n vols = [0.01,0.06..1]\n expiries = map YearFrac [0.1,0.2..2]\n relativeStrikes = [log (k/(atmf bs expiry)) | k <- strikes]\n r = 0.01\n bs = BlackScholes spot r vol\n delta cp k = vDelta (euOption bs expiry cp k)\n pv cp k = vPremium (euOption bs expiry cp k)\n row (vol,k,t) = [show today,\n show t,\n show $log (k / atmf bs t),\n show r,\n show vol,\n show $ pv Call k,\n show $ pv Put k,\n show $ delta Call k,\n show $ delta Put k\n ]\n header = [\"VD\",\"Expiry\",\"RelativeStrike\", \"IR\", \"Vol\", \"cPV\", \"pPV\", \"cDelta\", \"pDelta\"]\n\n QF.write (map row [(vol, k, t) | vol <- vols, k <- strikes, t <- expiries]) header \"/tmp/data/delta.csv\"\n\n let mydata = dataFromUrl \"delta.csv\" [Parse [ ( \"Expiry\", FoDate \"%Y-%m-%d\" ), ( \"VD\", FoDate \"%Y-%m-%d\" ) ]]\n\n -- !This is \\(dV/dS\\) for different strikes, same expiry, interest rate,\n let l1 = toVegaLite [mydata , layers, width 800, height 600, res, trans] where\n calls = encoding\n . position X [PName \"RelativeStrike\" , PmType Quantitative]\n . position Y [PName \"cDelta\" , PmType Quantitative, PTitle \"Calls\", PAxis [AxTitleColor \"green\"]]\n puts = encoding\n . position X [PName \"RelativeStrike\" , PmType Quantitative]\n . position Y [PName \"pDelta\" , PmType Quantitative, PTitle \"Puts\", PAxis [AxTitleColor \"red\"]]\n layers = layer [ asSpec [calls [], mark Line [MColor \"green\"]]\n , asSpec [puts [], mark Line [MColor \"red\"]]\n ]\n trans = transform . filter (FExpr \"datum.Expiry == datetime(2015,3,15)\") $ []\n res = resolve . resolution (RScale [(ChY, Independent)]) $ []\n\n toHtmlFile \"/tmp/data/deltas.html\" l1\n\n\n-- | Plot call option premiums, deltas, payoffs across a differnt\n-- range of strikes.\nplotCallOptions :: IO ()\nplotCallOptions = do\n let today = fromGregorian 2015 3 31\n expiry = YearFrac 1.0\n spot = 100\n r = 0\n vol = 0.01\n bs = BlackScholes spot r vol\n k = atmf bs expiry\n cp = Call\n let strikes = [95, 95.01..105]\n values = [] -- map (vPremium . euOption cp bs expiry) strikes\n deltas = [] --map (vDelta . euOption cp bs expiry) strikes\n pvs = dataFromColumns []\n . dataColumn \"Strikes\" (Numbers strikes)\n . dataColumn \"Premiums\" (Numbers values)\n . dataColumn \"Deltas\" (Numbers deltas)\n let encPvs = encoding\n . position X [PName \"Strikes\", PmType Quantitative]\n . position Y [PName \"Premiums\" , PmType Quantitative]\n encDeltas = encoding\n . position X [PName \"Strikes\", PmType Quantitative]\n . position Y [PName \"Deltas\", PmType Quantitative]\n layers = layer [ asSpec [ encPvs [], mark Line [MColor \"blue\"]]\n , asSpec [ encDeltas [], mark Line [MColor \"red\"]]\n ]\n res = resolve . resolution (RScale [(ChY, Independent)])\n vl = toVegaLite [pvs [], layers, width 800, res [], height 400]\n toHtmlFile \"/tmp/callOptions.html\" vl\n\n\n\ntestPlot = do\n let dvals = dataSequenceAs 0 6.28 0.1 \"x\"\n trans = transform\n . calculateAs \"sin(datum.x)\" \"sinX\"\n . calculateAs \"cos(datum.x)\" \"cosX\"\n enc = encoding\n . position X [PName \"x\", PmType Quantitative]\n encCos = enc . position Y [PName \"cosX\", PmType Quantitative]\n encSin = enc . position Y [PName \"sinX\", PmType Quantitative]\n\n vl = toVegaLite [ dvals\n , trans []\n , vlConcat [ asSpec [encCos [], mark Line []]\n , asSpec [encSin [], mark Line []]\n ]\n ]\n toHtmlFile \"/tmp/test.html\" vl\n\nplotTrajectories :: IO ()\nplotTrajectories = do\n let dt = 1/365\n today = fromGregorian 2015 3 31\n dates = [d | d <- fmap (flip addDays today) [0, 365]]\n dts = tail $ map (\\d -> dcYearFraction ThirtyUSA today d) dates\n n = 64000\n ids = mconcat $ fmap (replicate $ length dates) [T.pack $ show id | id <- [1..n]]\n trajectories <- sample $ trajectories n (Euler dt) gbm (100::Double) dts (repeat stdNormal)\n let trajectories' = dataFromColumns [ Parse [ ( \"Date\", FoDate \"%Y%m%d\" ) ] ]\n . dataColumn \"Date\" (Strings (mconcat (replicate n (map dayToString dates))))\n . dataColumn \"St\" (Numbers $ mconcat trajectories)\n . dataColumn \"ID\" (Strings ids)\n calls = mark Line\n enc = encoding\n . position X [ PName \"Date\", PmType Temporal]\n . position Y [ PName \"St\", PmType Quantitative, PScale [SDomain (DNumbers [50, 150])] ]\n . color [ MName \"ID\", MmType Nominal, MLegend []]\n vl = toVegaLite [trajectories' [], enc [], mark Line [], width 1000, height 600]\n toHtmlFile \"/tmp/a.html\" vl\n\n\n\nmain = undefined\n\n\n\n", "meta": {"hexsha": "9657bec3e48f7eb35d52ab0d4c7abc381dfe515e", "size": 9211, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "ghais/lowq", "max_stars_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-01T17:50:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T18:06:22.000Z", "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "ghais/lowq", "max_issues_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "ghais/lowq", "max_forks_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.577092511, "max_line_length": 111, "alphanum_fraction": 0.5494517425, "num_tokens": 2389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5926716674107905}} {"text": "{- MDP.hs Code for CS 533, Mini-Project 2.\n -\n - Copyright \u00a9 2012 Loren B. Davis. ALL RIGHTS RESERVED. I hereby release\n - this code under the MIT License: (http://www.opensource.org/licenses/MIT).\n - Since this is an assigned exercise, remember your academic integrity!\n -}\n\nmodule MDP {- ( MarkovDP, State, Action, policyIterate, showUpdates, test4x3,\n showT, decodeT, whenToPass, whenToPark, parkingProblem,\n ParkingState, encodeState, decodeState ) -}\n where\nimport Data.Array.Unboxed (UArray, (!), accumArray, assocs, listArray)\nimport Data.List (maximumBy, (\\\\))\nimport Data.Ord ()\nimport Numeric.LinearAlgebra (Matrix, Vector, build, linearSolveSVD, toLists)\n-- import Numeric.LinearAlgebra hiding (i)\n-- import Numeric.LinearAlgebra.Algorithms hiding (i)\nimport Prelude hiding(pi)\n{- This program uses the hmatrix package (cabal install hmatrix) rather than\n - attempt to reinvent the wheel. You might also need to install libgsl,\n - liblapack, and possibly MKL or ATLAS.\n -}\n\ntype State = Int\ntype Action = Int\ntype MarkovDP = ( Int,\n Int,\n UArray State Double,\n UArray (State,Action,State) Double\n )\n{- n = The number of states. S = {0,...,n-1}\n - m = The number of actions. A = {0,...,m-1}\n - r = An array of size n representing the reward function. r[s] is the\n - reward associated with state s.\n - t = A three-dimensional array representing the transition function, such\n - that T(s,a,s') = t ! (s,a,s'). Note that the values are between 0 and\n - 1, each row sums to 1, and that the matrices will typically be sparse.\n -}\ntype PIUpdate = [(State, Action)]\n{- The update of each step of the policy iteration algorithm is the list\n - of pairs (s,a) such that the new policy will take action a in state s.\n -}\n\npolicyIterate :: MarkovDP ->\n Double ->\n (UArray State Double, UArray State Action, [String])\n{- Parameters:\n - process = The Markov decision process to solve, in the form\n - (|S|,|A|,R,T)\n - gamma = The discount parameter, between 0 and 1.\n -\n - Returns (v, pi, updates) where\n - v = A size-n array representing the value function. The expect-\n - ed value of being in state s is v[s].\n - pi = A size-n array representing the policy. The action that pi\n - will take in state s is pi[s].\n - updates = A human-readable list of update strings, one per step of the\n - iteration.\n -\n - This implementation always starts with a policy of taking the first action\n - in any situation. This is not really correct (the algorithm in the text\n - says to try a \"random\" policy), but saves me from dealing with stateful\n - computation in this program. To specify a different initial policy, call\n - policyIterate1. It does not attempt any asynchronous policy iteration.\n -}\npolicyIterate (n, m, r, t) gamma = (v', pi'', translatePIUpdates updates'' )\n where\n ( v', pi'', updates'' ) = seq ((n,m,r,t), gamma, naive)\n (policyIterate1 naive [])\n naive = (initialPolicy n)\n policyIterate1 :: UArray State Action ->\n [PIUpdate] ->\n (UArray State Double, UArray State Action, [PIUpdate])\n{- Parameters:\n - pi = The initial policy to attempt to improve.\n - updates = The previous iterations' updates.\n -\n - Returns (v, pi) where\n - v = A size-n array representing the value function. The expected value\n - of being in state s is v[s].\n - pi' = A size-n array representing the policy. The action that pi' will\n - take in state s is pi[s].\n - updates' = The list of updates for all iterations of the algorithm. When\n - there are no further updates, the algorithm terminates.\n -}\n policyIterate1 pi updates | diff == [] = (v, pi', updates')\n | otherwise = policyIterate1 pi' $! updates'\n where\n states :: [State]\n states = [0..n-1]\n actions :: [Action]\n actions = [0..m-1]\n v :: UArray State Double\n{- The updated value function. This is based on eq. 17.10 in (Russell &\n - Norvig 2010), rather than the modified-policy-iteration algorithm in fig.\n - 17.7. It uses LAPACK to solve the system of linear equations in O(n^3)\n - time.\n -}\n v = let\n updateHelper :: Double -> Double -> Double\n updateHelper w z = gamma * (t!(i,pi!i,j)) -\n (if i == j then 1.0 else 0.0)\n where\n i :: Int\n i = truncate w\n j :: Int\n j = truncate z\n a :: Matrix Double\n a = build (n,n) updateHelper\n b :: Matrix Double\n b = build (n,1) (\\y _ -> let i = truncate y :: Int in - (r!i))\n x :: Matrix Double\n x = linearSolveSVD a b\n in\n listArray (0,n-1) (concat . toLists $ x)\n pi' :: UArray Int Action\n{- The updated policy pi' is the best action to take in any state (determined\n - by one-step lookahead). Q.v. eq. 17.4 in (Russell & Norvig 2010).\n -}\n pi' = seq v (listArray (0, n-1)\n (map (\\i -> maximumBy (argmax i) actions)\n states))\n argmax :: State -> Action -> Action -> Ordering\n{- A helper function that compares the expected value of actions a1 and a2\n - from state s0.\n -}\n argmax s0 a1 a2 = let\n u1 = sum .\n map (\\s' -> t!(s0,a1,s') * v!s') $\n states\n u2 = sum .\n map (\\s' -> t!(s0,a2,s') * v!s') $\n states\n in compare u1 u2\n diff :: PIUpdate\n diff = seq pi' ((assocs pi') \\\\ (assocs pi))\n updates' :: [PIUpdate]\n updates' = seq diff (updates ++ [diff])\n\ninitialPolicy :: Int -> UArray Int Action\n{- A policy for a MDP with n states that always takes action zero. This is\n - not the same as the \"random\" policy I'm supposed to use for the algorithm,\n - but is simpler to write in this language.\n -}\ninitialPolicy n = listArray (0, n-1) (take n (repeat 0))\n\ninitialVF :: Int -> UArray Int Double\n{- A value function initialized to n zeroes. Unlike the above, this is corr-\n - ect. (But unused in policy iteration.)\n -}\ninitialVF n = listArray (0, n-1) (take n (repeat 0.0))\n\ntranslatePIUpdates :: [PIUpdate] -> [String]\ntranslatePIUpdates u =\n map (\\i -> \"Step \" ++ show (i+1) ++ \": \" ++ translatePIUpdate (u !! i))\n [0 .. (length u) - 1]\n\ntranslatePIUpdate :: PIUpdate -> String\ntranslatePIUpdate [] = \"Done.\"\ntranslatePIUpdate [(s,a)] = \"take action \" ++\n show a ++\n \" in state \" ++\n show s ++\n \".\"\ntranslatePIUpdate ((s,a):xs) = \"take action \" ++\n show a ++\n \" in state \" ++\n show s ++\n \"; \" ++\n translatePIUpdate xs\n\n-- Display the returned update messages:\nshowUpdates :: (UArray State Double, UArray State Action, [String]) ->\n IO ()\nshowUpdates (_,_,u) = putStrLn . unlines $ u\n\n-- A useful means of displaying only the nonzero entries of the sparse array\n-- t:\nshowT :: MarkovDP -> [((State,Action,State),Double)]\nshowT (_,_,_,t) = filter ((> 0.0) . snd) (assocs t)\n\n-- The parking-lot world:\n\n{- The decoded values of a state of the parking-lot world. Note that Exit\n - in this implementation is a terminal state that the park action automat-\n - ically reaches, not a third action. Crash is another world state, always\n - and only reached by attempting to park in a filled spot.\n -\n - A i True is the state in which the agent is in front of row A, space i,\n - which is filled. A i False is similar, but the spot is empty; likewise\n - for row B. I take advantage of the symmetry between parking in row A and\n - in row B to define P i as the state of being parked i spaces from the\n - store. This reduces the size of the state space from 8n to 5n+1. The\n - range of i is 1 to n.\n -}\ndata ParkingState = A Int Bool | B Int Bool | P Int | Exit | Crash\n deriving (Eq, Show)\n\nencodeState :: Int -> ParkingState -> State\n{- Converts a ParkingState into an index suitable for the PolicyIterate algo-\n - rithm. The encoding depends on the number of rows, n.\n -}\nencodeState _ Exit = 0\nencodeState _ Crash = 1\nencodeState _ (P i) = 1 + i\nencodeState n (A i True) = 1 + n + i\nencodeState n (A i False) = 1 + 2*n + i\nencodeState n (B i True) = 1 + 3*n + i\nencodeState n (B i False) = 1 + 4*n + i\n\ndecodeState :: Int -> State -> ParkingState\n{- The inverse of the mapping above.\n -}\ndecodeState _ 0 = Exit\ndecodeState _ 1 = Crash\ndecodeState n m | m <= 1 + n = P (m-1)\n | m <= 1 + 2*n = A (m-n-1) True\n | m <= 1 + 3*n = A (m-2*n-1) False\n | m <= 1 + 4*n = B (m-3*n-1) True\n | m <= 1 + 5*n = B (m-4*n-1) False\n | otherwise = error $ \"Invalid state \" ++ show m ++ \".\"\n\n-- Decode an association from t:\ndecodeT' :: Int ->\n ((State,Action,State),Double) ->\n ((ParkingState,String,ParkingState),Double)\ndecodeT' c ((s,a,s'),p) = ((decodeState c s,\n if (a == 1) then \"Park\" else \"Move\",\n decodeState c s'),\n p)\n\n-- Show the condensed, human-readable transition function.\ndecodeT :: Int ->\n [((State,Action,State),Double)] ->\n [((ParkingState,String,ParkingState),Double)]\ndecodeT c = map (decodeT' c)\n\n-- Display the states in which the policy tells the agent to keep looking.\nwhenToPass :: Int ->\n (UArray State Double, UArray State Action, [String]) ->\n [ParkingState]\nwhenToPass c (_,pi,_) = map (decodeState c) .\n filter (> 1+c) .\n map fst .\n filter ((==) 0 . snd) .\n assocs $\n pi\n\n-- And when to park.\nwhenToPark :: Int ->\n (UArray State Double, UArray State Action, [String]) ->\n [ParkingState]\nwhenToPark c (_,pi,_) = map (decodeState c) .\n filter (> 1+c) .\n map fst .\n filter ((==) 1 . snd) .\n assocs $\n pi\n\nparkingProblem :: Int ->\n Double ->\n Double ->\n Double ->\n Double ->\n Double ->\n Double ->\n MarkovDP\n{- Generates a MDP representing a parking problem with the given parameters:\n -\n - c = The number of parking spaces per row.\n - alpha = The probability that a handicap spot will be empty. Should be be-\n - low, but close to, 1.0.\n - beta = The penalty for parking in a handicap spot. Should be a large neg-\n - ative number.\n - delta = A parameter representing the rate at which a shopper loses utility\n - for distance. I represent the utility of parking as inversely \n - proportional to the square of the distance. Should be a positive\n - number.\n - iota = The rate of utility loss for driving around. Should be a\n - small positive number.\n - kappa = The penalty for crashing into another car. Should be a larger\n - negative number than beta.\n - lambda = A parameter determining the probability that a non-handicap spot\n - will be empty. I represent this as a Poisson-like distribution, as\n - we can model the spaces as filling in from the closest on out, with\n - cars entering as independent events and leaving after a certain\n - period of time. Therefore, this parameter should be a positive\n - number, equal to the expected number of cars parked in the lot.\n -}\nparkingProblem c alpha beta delta iota kappa lambda = let\n n = c*5 + 2\n r = listArray (0,n-1) ([0, kappa, beta] ++\n [delta/(fromIntegral i) | i <- [2..c]] ++\n (repeat (-iota)))\n t = accumArray (+) 0 ((0,0,0),(n-1,1,n-1)) (\n-- Exit is a terminal state.\n [((0,0,0),1.0), ((0,1,0),1.0)] ++\n-- Crashing or parking always obviates any further reward.\n [((i,0,0),1.0) | i <- [1..c+1]] ++ [((i,1,0),1.0) | i <- [1..c+1]] ++\n-- Attempting to park in any occupied space always crashes the car.\n [((encodeState c (A i True),1,1),1.0) | i <- [1..c]] ++\n [((encodeState c (B i True),1,1),1.0) | i <- [1..c]] ++\n-- However, parking in a free space succeeds.\n [((encodeState c (A i False),1,(encodeState c (P i))),1.0) | i <- [1..c]] ++\n [((encodeState c (B i False),1,(encodeState c (P i))),1.0) | i <- [1..c]] ++\n-- An agent at A[1] can only move to B[1], which could be free or not. The\n-- probability that it is free is alpha.\n [((encodeState c (A 1 False),0,encodeState c (B 1 True)),1.0-alpha),\n ((encodeState c (A 1 True),0,encodeState c (B 1 True)),1.0-alpha),\n ((encodeState c (A 1 False),0,encodeState c (B 1 False)),alpha),\n ((encodeState c (A 1 True),0,encodeState c (B 1 False)),alpha)] ++\n-- An agent at A[2] can only move to A[1], which again is free with probabil-\n-- ity alpha.\n [((encodeState c (A 2 False),0,encodeState c (A 1 True)),1.0-alpha),\n ((encodeState c (A 2 True),0,encodeState c (A 1 True)),1.0-alpha),\n ((encodeState c (A 2 False),0,encodeState c (A 1 False)),alpha),\n ((encodeState c (A 2 True),0,encodeState c (A 1 False)),alpha)] ++\n-- An agent at any other A[i] can only move to A[i-1].\n [((encodeState c (A i False),0,encodeState c (A (i-1) False)),quasiPoisson lambda (i-1)) | i <- [3..c]] ++\n [((encodeState c (A i True),0,encodeState c (A (i-1) False)),quasiPoisson lambda (i-1)) | i <- [3..c]] ++\n [((encodeState c (A i False),0,encodeState c (A (i-1) True)),1.0 - quasiPoisson lambda (i-1)) | i <- [3..c]] ++\n [((encodeState c (A i True),0,encodeState c (A (i-1) True)),1.0 - quasiPoisson lambda (i-1)) | i <- [3..c]] ++\n-- An agent at B[i], where i < c, can only move to B[i+1].\n [((encodeState c (B i False),0,encodeState c (B (i+1) False)),quasiPoisson lambda (i+1)) | i <- [1..(c-1)]] ++\n [((encodeState c (B i True),0,encodeState c (B (i+1) False)),quasiPoisson lambda (i+1)) | i <- [1..(c-1)]] ++\n [((encodeState c (B i False),0,encodeState c (B (i+1) True)),1.0-quasiPoisson lambda (i+1)) | i <- [1..(c-1)]] ++\n [((encodeState c (B i True),0,encodeState c (B (i+1) True)),1.0-quasiPoisson lambda (i+1)) | i <- [1..(c-1)]] ++\n-- Finally, an agent at B[c] can only move to A[c].\n [((encodeState c (B c False),0,encodeState c (A c True)),1.0-quasiPoisson lambda c),\n ((encodeState c (B c True),0,encodeState c (A c True)),1.0-quasiPoisson lambda c),\n ((encodeState c (B c False),0,encodeState c (A c False)),quasiPoisson lambda c),\n ((encodeState c (B c True),0,encodeState c (A c False)),quasiPoisson lambda c)]\n )\n in (n, 2, r, t)\n\npoisson :: Double -> Int -> Double\n-- The pmf of a Poisson distribution.\npoisson lambda i = (exp (-lambda)) *\n (lambda^i) /\n (fromIntegral (factorial i))\n\npoissonCMF :: Double -> Int -> Double\n-- The memoized cmf of a Poisson distribution.\npoissonCMF lambda = ((scanl1 (+) (map (poisson lambda) [0..])) !!)\n\nquasiPoisson :: Double -> Int -> Double\n{- Take into account that there are two rows to fill. The parameter gamma\n - should be the expected number of parked cars; the parameter i should be\n - at least 2.\n -}\nquasiPoisson lambda i = ((poissonCMF lambda (i*2-4)) + \n (poissonCMF lambda (i*2-3)))\n / 2.0\n\nfactorial :: Int -> Integer\n-- A memoized factorial function.\nfactorial = ((scanl (*) 1 [1..]) !!)\n\n-- Test data:\n\n-- The 4x3 world in fig. 17.3 of (Russell & Norvig 2010):\n\ntest4x3 :: MarkovDP\ntest4x3 = ( 12, -- The 11 states in the example, plus a terminal state 0.\n 4, -- Left, right, up, down\n listArray (0,11)\n [0,\n -0.04, -0.04, -0.04, 1.0,\n -0.04, -0.04, -1.0,\n -0.04, -0.04, -0.04, -0.04],\n accumArray (+) 0.0 ((0,0,0),(11,3,11)) [\n -- The synthetic terminal state:\n ((0,0,0),1.0),((0,1,0),1.0),((0,2,0),1.0),((0,3,0),1.0),\n -- Position (1,1):\n ((1,0,1),1.0),((1,1,2),1.0),((1,2,1),1.0),((1,3,5),1.0),\n -- Position (1,2):\n ((2,0,1),1.0),((2,1,3),1.0),((2,2,2),1.0),((2,3,2),1.0),\n -- Position (1,3):\n ((3,0,2),1.0),((3,1,4),1.0),((3,2,3),1.0),((3,3,6),1.0),\n -- Position (1,4):\n ((4,0,0),1.0),((4,1,0),1.0),((4,2,0),1.0),((4,3,0),1.0),\n -- Position (2,1):\n ((5,0,5),1.0),((5,1,5),1.0),((5,2,1),1.0),((5,3,8),1.0),\n -- Position (2,2) does not exist.\n -- Position (2,3):\n ((6,0,6),1.0),((6,1,7),1.0),((6,2,3),1.0),((6,3,10),1.0),\n -- Position (2,4):\n ((7,0,0),1.0),((7,1,0),1.0),((7,2,0),1.0),((7,3,0),1.0),\n -- Position (3,1):\n ((8,0,8),1.0),((8,1,9),1.0),((8,2,5),1.0),((8,3,8),1.0),\n -- Position (3,2):\n ((9,0,8),1.0),((9,1,10),1.0),((9,2,9),1.0),((9,3,9),1.0),\n -- Position (3,3):\n ((10,0,9),1.0),((10,1,11),1.0),((10,2,6),1.0),((10,3,10),1.0),\n -- Position (3,4):\n ((11,0,10),1.0),((11,1,11),1.0),((11,2,7),1.0),((11,3,11),1.0)\n ]\n )\n\n-- The three-state world in problem 17.10 in (Russell & Norvig 2010):\ntest3 :: MarkovDP\ntest3 = ( 3, -- There are three states in the example. I rename 3 to 0.\n 2, -- and two actions, a and b.\n listArray (0,2) [0,-1,-2],\n accumArray (+) 0.0 ((0,0,0),(2,1,2)) [\n -- State 0 is a terminal state.\n ((0,0,0),1.0), ((0,1,0),1.0),\n -- In state 1, action a goes to state 2 (p=0.8) or state 1 (p=0.2)\n -- Action b goes to state 0 (p=0.1) or state 1 (p=0.9)\n ((1,0,2),0.8), ((1,0,1),0.2), ((1,1,0),0.1), ((1,1,1),0.9),\n -- In state 2, action a goes to state 1 (p=0.8) or state 2 (p=0.2)\n -- Action b goes to state 0 (p=0.1) or state 1 (p=0.9)\n ((2,0,1),0.8), ((2,0,2),0.2), ((2,1,0),0.1), ((2,1,2),0.9)\n ]\n )\n\n-- The 101 x 3 world from exercise 17.8 in (Russell & Norvig 2010):\n{- This example is useful because I\u2019ve already solved the critical values of\n - gamma for it, and because it contains a larger number of states.\n -}\ntest101 :: MarkovDP\ntest101 = ( 204, -- The start state, an immediate reward state on top followed\n -- by 100 penalties, an immediate penalty state on the bottom\n -- followed by 100 rewards, and a synthetic terminal state.\n 2, -- Up or down at the start. Both move the agent right any-\n -- where else.\n listArray (0,203)\n ((0:50.0:(take 100 (repeat (-1.0))))++(-50.0:(take 100 (repeat 1.0)))++[0]),\n accumArray (+) 0.0 ((0,0,0),(203,1,203))\n-- In the start state, up goes to state 1, down to state 102.\n ([((0,0,1),1.0), ((0,1,102),1.0)] ++\n-- In states 1-100, any action moves the agent to the next consecutive state.\n [((i,0,i+1), 1.0) | i <- [1..100]] ++ [((i,1,i+1), 1.0) | i <- [1..100]] ++\n-- State 101 always sends the agent to terminal state 203.\n [((101,0,203),1.0),((101,1,203),1.0)] ++\n-- States 102-202 also send the agent to the next consecutive state:\n [((i,0,i+1), 1.0) | i <- [102..202]] ++\n [((i,1,i+1), 1.0) | i <- [102..202]] ++\n-- Finally, state 203 is terminal:\n [((203,0,203),1.0),((203,1,203),1.0)])\n )\n", "meta": {"hexsha": "c782264a2cb9622356384553dc719621ef4b4a1c", "size": 19597, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MDP.hs", "max_stars_repo_name": "Davislor/markov", "max_stars_repo_head_hexsha": "49e9c9379a09a8a970991091b6654c5aa0c08dc2", "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/MDP.hs", "max_issues_repo_name": "Davislor/markov", "max_issues_repo_head_hexsha": "49e9c9379a09a8a970991091b6654c5aa0c08dc2", "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/MDP.hs", "max_forks_repo_name": "Davislor/markov", "max_forks_repo_head_hexsha": "49e9c9379a09a8a970991091b6654c5aa0c08dc2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3371040724, "max_line_length": 117, "alphanum_fraction": 0.556258611, "num_tokens": 6014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.592671666945952}} {"text": "import Data.Map.Strict ((!))\nimport Numeric.LinearAlgebra hiding ((!))\nimport LeastSquares\n\nleastSquaresEstimate :: Vector R\nleastSquaresEstimate = result ! \"x\"\n where result = minimize (SumSquares x) [c * x :==: d]\n c = Mat $ (2><3) [3.0, 7.0, -1.5, 2.8, 10.0, -5.3]\n d = Vec $ vector [-1.0, 3.5]\n x = Var \"x\" 3\n", "meta": {"hexsha": "480507e488b22f3a86a4239619df960f50d2a383", "size": 335, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/example_least_norm.hs", "max_stars_repo_name": "tridao/leastsquares", "max_stars_repo_head_hexsha": "05847fd78e68892b5af3e12b04200e4ff3ad17e4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-21T05:14:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T05:14:02.000Z", "max_issues_repo_path": "app/example_least_norm.hs", "max_issues_repo_name": "tridao/leastsquares", "max_issues_repo_head_hexsha": "05847fd78e68892b5af3e12b04200e4ff3ad17e4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/example_least_norm.hs", "max_forks_repo_name": "tridao/leastsquares", "max_forks_repo_head_hexsha": "05847fd78e68892b5af3e12b04200e4ff3ad17e4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-12-13T22:03:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T05:14:09.000Z", "avg_line_length": 30.4545454545, "max_line_length": 58, "alphanum_fraction": 0.5820895522, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5924568033208917}} {"text": "module Fractals (pMandelbrot, pJulia) where\n\nimport Data.Complex\n\ndata PointResult = Convergent | Divergent Int (Complex Double)\n\n-- Calculates a point in the Mandelbrot set\npMandelbrot :: Bool -> Double -> Int -> Double -> Complex Double -> Maybe Double\npMandelbrot aa pixelSize maxIterations power point =\n fPoint aa pixelSize maxIterations power (\\d z -> z ** (d :+ 0) + point) point\n\n-- Calculates a point in the Julia set\npJulia :: Bool -> Double -> Int -> Double -> Complex Double -> Complex Double -> Maybe Double\npJulia aa pixelSize maxIterations power c point =\n fPoint aa pixelSize maxIterations power (\\d z -> z ** (d :+ 0) + c) point\n\nfPoint\n :: Bool\n -> Double\n -> Int\n -> Double\n -> (Double -> Complex Double -> Complex Double)\n -> Complex Double\n -> Maybe Double\nfPoint bAAEnabled pixelSize maxIterations power f z0 = if not bAAEnabled\n then normalize $ iterPoint 0 z0\n else\n (\\(sum, count', isConvergent) ->\n if isConvergent then Nothing else Just $ (sum / (numberOfSubpoints - count'))\n )\n $ foldl\n (\\(sum, countConv, isConvergent) y -> if countConv > maxConvergent\n then (sum, countConv, True)\n else case normalize . iterPoint 0 $ z0 + y of\n Nothing -> (sum, countConv + 1, False)\n Just z -> (sum + z, countConv, False)\n )\n (0, 0, False)\n [ (-size') :+ (-size'), (-size') :+ 0, (-size') :+ size'\n , 0 :+ (-size'), 0 :+ 0, 0 :+ size'\n , size' :+ (-size'), size' :+ 0, size' :+ size'\n ]\n where\n maxMagnitude = 50\n -- Main iteration function\n iterPoint n z | n > maxIterations = Convergent\n | magnitude z > maxMagnitude = Divergent n z\n | otherwise = iterPoint (n + 1) (f power z)\n -- Prevents the aliasing present in generators which color based purely on escape time\n normalize Convergent = Nothing\n normalize (Divergent 0 _) = Just 0\n normalize (Divergent iterations final) =\n Just . (fromIntegral iterations + 1 -) . logBase power . logBase maxMagnitude . magnitude $ final\n size' = pixelSize / 3\n numberOfSubpoints = 9\n maxConvergent = 4\n", "meta": {"hexsha": "a1d42ae2eab43fdc776d9d7036815a07979ba6ab", "size": 2295, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Fractals.hs", "max_stars_repo_name": "MaygeKyatt/Fractals", "max_stars_repo_head_hexsha": "e5f2102fd74c02e6290dc75d138f8962850ebd26", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Fractals.hs", "max_issues_repo_name": "MaygeKyatt/Fractals", "max_issues_repo_head_hexsha": "e5f2102fd74c02e6290dc75d138f8962850ebd26", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Fractals.hs", "max_forks_repo_name": "MaygeKyatt/Fractals", "max_forks_repo_head_hexsha": "e5f2102fd74c02e6290dc75d138f8962850ebd26", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2631578947, "max_line_length": 102, "alphanum_fraction": 0.5821350763, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5922816245075091}} {"text": "-- |\n-- Module : Statistics.Distribution.Dirichlet\n-- Description : Multivariate Dirichlet distribution\n-- Copyright : (c) Dominik Schrempf, 2021\n-- License : GPL-3.0-or-later\n--\n-- Maintainer : dominik.schrempf@gmail.com\n-- Stability : unstable\n-- Portability : portable\n--\n-- Creation date: Tue Oct 20 10:10:39 2020.\nmodule Statistics.Distribution.Dirichlet\n ( -- * Dirichlet distribution\n DirichletDistribution (ddGetParameters),\n dirichletDistribution,\n dirichletDensity,\n dirichletSample,\n\n -- * Symmetric Dirichlet distribution\n DirichletDistributionSymmetric (ddSymGetParameter),\n dirichletDistributionSymmetric,\n dirichletDensitySymmetric,\n dirichletSampleSymmetric,\n )\nwhere\n\nimport Control.Monad.Primitive\nimport qualified Data.Vector.Unboxed as V\nimport Numeric.Log\nimport Numeric.SpecFunctions\nimport System.Random.MWC\nimport System.Random.MWC.Distributions\n\n-- | The [Dirichlet distribution](https://en.wikipedia.org/wiki/Dirichlet_distribution).\ndata DirichletDistribution = DirichletDistribution\n { ddGetParameters :: V.Vector Double,\n _getDimension :: Int,\n _getNormConst :: Log Double\n }\n deriving (Eq, Show)\n\n-- Check if vector is strictly positive.\nisNegativeOrZero :: V.Vector Double -> Bool\nisNegativeOrZero = V.any (<= 0)\n\n-- Inverse multivariate beta function. Does not check if parameters are valid!\ninvBeta :: V.Vector Double -> Log Double\ninvBeta v = Exp $ logDenominator - logNominator\n where\n logNominator = V.sum $ V.map logGamma v\n logDenominator = logGamma (V.sum v)\n\n-- | Create a Dirichlet distribution from the given parameter vector.\n--\n-- Return Left if:\n--\n-- - The parameter vector has less then two elements.\n--\n-- - One or more parameters are negative or zero.\ndirichletDistribution :: V.Vector Double -> Either String DirichletDistribution\ndirichletDistribution v\n | V.length v < 2 =\n Left \"dirichletDistribution: Parameter vector is too short.\"\n | isNegativeOrZero v =\n Left \"dirichletDistribution: One or more parameters are negative or zero.\"\n | otherwise = Right $ DirichletDistribution v (V.length v) (invBeta v)\n\n-- Tolerance.\neps :: Double\neps = 1e-14\n\n-- Check if vector is normalized with tolerance 'eps'.\nisNormalized :: V.Vector Double -> Bool\nisNormalized v\n | abs (V.sum v - 1.0) > eps = False\n | otherwise = True\n\n-- | Density of the Dirichlet distribution evaluated at a given value vector.\n--\n-- Return 0 if:\n--\n-- - The value vector has a different length than the parameter vector.\n--\n-- - The value vector has elements being negative or zero.\n--\n-- - The value vector does not sum to 1.0 (with tolerance @eps = 1e-14@).\ndirichletDensity :: DirichletDistribution -> V.Vector Double -> Log Double\ndirichletDensity (DirichletDistribution as k c) xs\n | k /= V.length xs = 0\n | isNegativeOrZero xs = 0\n | not (isNormalized xs) = 0\n | otherwise = c * Exp logXsPow\n where\n logXsPow = V.sum $ V.zipWith (\\a x -> log $ x ** (a - 1.0)) as xs\n\n-- | Sample a value vector from the Dirichlet distribution.\ndirichletSample :: PrimMonad m => DirichletDistribution -> Gen (PrimState m) -> m (V.Vector Double)\ndirichletSample (DirichletDistribution as _ _) g = do\n ys <- V.mapM (\\a -> gamma a 1.0 g) as\n let s = V.sum ys\n return $ V.map (/ s) ys\n\n-- | See 'DirichletDistribution' but with parameter vector @replicate DIM VAL@.\ndata DirichletDistributionSymmetric = DirichletDistributionSymmetric\n { ddSymGetParameter :: Double,\n _symGetDimension :: Int,\n _symGetNormConst :: Log Double\n }\n deriving (Eq, Show)\n\n-- Inverse multivariate beta function. Does not check if parameters are valid!\ninvBetaSym :: Int -> Double -> Log Double\ninvBetaSym k a = Exp $ logDenominator - logNominator\n where\n logNominator = fromIntegral k * logGamma a\n logDenominator = logGamma (fromIntegral k * a)\n\n-- | Create a symmetric Dirichlet distribution of given dimension and parameter.\n--\n-- Return Left if:\n--\n-- - The given dimension is smaller than two.\n--\n-- - The parameter is negative or zero.\ndirichletDistributionSymmetric :: Int -> Double -> Either String DirichletDistributionSymmetric\ndirichletDistributionSymmetric k a\n | k < 2 =\n Left \"dirichletDistributionSymmetric: The dimension is smaller than two.\"\n | a <= 0 =\n Left \"dirichletDistributionSymmetric: The parameter is negative or zero.\"\n | otherwise = Right $ DirichletDistributionSymmetric a k (invBetaSym k a)\n\n-- | Density of the symmetric Dirichlet distribution evaluated at a given value\n-- vector.\n--\n-- Return 0 if:\n--\n-- - The value vector has a different dimension.\n--\n-- - The value vector has elements being negative or zero.\n--\n-- - The value vector does not sum to 1.0 (with tolerance @eps = 1e-14@).\ndirichletDensitySymmetric :: DirichletDistributionSymmetric -> V.Vector Double -> Log Double\ndirichletDensitySymmetric (DirichletDistributionSymmetric a k c) xs\n | k /= V.length xs = 0\n | isNegativeOrZero xs = 0\n | not (isNormalized xs) = 0\n | otherwise = c * Exp logXsPow\n where\n logXsPow = V.sum $ V.map (\\x -> log $ x ** (a - 1.0)) xs\n\n-- | Sample a value vector from the symmetric Dirichlet distribution.\ndirichletSampleSymmetric ::\n PrimMonad m =>\n DirichletDistributionSymmetric ->\n Gen (PrimState m) ->\n m (V.Vector Double)\ndirichletSampleSymmetric (DirichletDistributionSymmetric a k _) g = do\n ys <- V.replicateM k (gamma a 1.0 g)\n let s = V.sum ys\n return $ V.map (/ s) ys\n", "meta": {"hexsha": "fecb99d8a14e1a752f2f34df60015eca1acefa67", "size": 5415, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Distribution/Dirichlet.hs", "max_stars_repo_name": "dschrempf/dirichlet", "max_stars_repo_head_hexsha": "0b221c816ca88aacfa2252e89ed45c5044b85c7e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-24T16:34:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T16:34:57.000Z", "max_issues_repo_path": "src/Statistics/Distribution/Dirichlet.hs", "max_issues_repo_name": "dschrempf/dirichlet", "max_issues_repo_head_hexsha": "0b221c816ca88aacfa2252e89ed45c5044b85c7e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Distribution/Dirichlet.hs", "max_forks_repo_name": "dschrempf/dirichlet", "max_forks_repo_head_hexsha": "0b221c816ca88aacfa2252e89ed45c5044b85c7e", "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.4259259259, "max_line_length": 99, "alphanum_fraction": 0.7202216066, "num_tokens": 1473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583167, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5919668283911446}} {"text": "-- O(n log n) multiply polynomials by Cooley-Tukey FFT \uff08Mutable Vector)\n-- 448 ms in atc001-c\n-- cf. http://wwwa.pikara.ne.jp/okojisan/stockham/cooley-tukey.html\nmodule FFT where\n\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\nimport Data.Complex\nimport Data.Function\nimport Control.Monad\nimport Control.Monad.Primitive\nimport Control.Monad.ST\n\n-- This function computes polynomial coefficient of (f * g)(x)\n-- f & g are polynomial coefficient array of f(x) & g(x)\nmultiply :: VU.Vector Int -> VU.Vector Int -> VU.Vector Int\nmultiply f g = runST $ do\n let len = VU.length f + VU.length g - 1\n let sz = fix (\\rec k -> if k >= len then k else rec (k * 2)) 1\n tf <- VU.thaw (VU.map fromIntegral f :: VU.Vector (Complex Double))\n nf <- VUM.grow tf (sz - VU.length f)\n tg <- VU.thaw (VU.map fromIntegral g :: VU.Vector (Complex Double))\n ng <- VUM.grow tg (sz - VU.length g)\n fft sz nf\n fft sz ng\n forM_ [0 .. sz - 1] $ \\i -> do\n y <- VUM.read ng i\n VUM.modify nf (* y) i\n ifft sz nf\n ret <- VU.freeze nf\n return $ VU.map (round . realPart) $ VU.take len ret\n{-# INLINE multiply #-}\n\nfft\n :: PrimMonad m\n => Int -- length\n -> VUM.MVector (PrimState m) (Complex Double) -- target data of FFT\n -> m ()\nfft n = cooleyTukey n 1 0 0\n{-# INLINE fft #-}\n\nifft\n :: PrimMonad m\n => Int -- length\n -> VUM.MVector (PrimState m) (Complex Double) -- target data of FFT\n -> m ()\nifft n x = do\n forM_ [0 .. n - 1] $ VUM.modify x conjugate\n cooleyTukey n 1 0 0 x\n forM_ [0 .. n - 1] $ VUM.modify x ((/ fromIntegral n) . conjugate)\n{-# INLINE ifft #-}\n\ncooleyTukey\n :: PrimMonad m\n => Int -- length\n -> Int -- stride\n -> Int -- start position of block\n -> Int -- temp var for bit reverse position in start position of block\n -> VUM.MVector (PrimState m) (Complex Double) -- target data of FFT\n -> m ()\ncooleyTukey n s q d x\n | n > 1 = do\n let m = n `div` 2\n let \u03b80 = 2 * pi / fromIntegral n\n forM_ [0 .. m - 1] $ \\p -> do\n let wp = cos (fromIntegral p * \u03b80) :+ (-sin (fromIntegral p * \u03b80))\n a <- VUM.read x (q + p + 0)\n b <- VUM.read x (q + p + m)\n VUM.write x (q + p + 0) (a + b)\n VUM.write x (q + p + m) ((a - b) * wp)\n cooleyTukey m (2 * s) (q + 0) (d + 0) x\n cooleyTukey m (2 * s) (q + m) (d + s) x\n | q > d = VUM.swap x q d\n | otherwise = return ()\n{-# INLINE cooleyTukey #-}", "meta": {"hexsha": "3b530f8c2087965b494927a80a9626dbe8ad27a8", "size": 2449, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "library/src/Math/Algorithms/FFT.hs", "max_stars_repo_name": "matonix/atcoder", "max_stars_repo_head_hexsha": "a5a65c68159900318adad898916c862119ab49ef", "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": "library/src/Math/Algorithms/FFT.hs", "max_issues_repo_name": "matonix/atcoder", "max_issues_repo_head_hexsha": "a5a65c68159900318adad898916c862119ab49ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-12-08T14:07:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T16:23:24.000Z", "max_forks_repo_path": "library/src/Math/Algorithms/FFT.hs", "max_forks_repo_name": "matonix/atcoder", "max_forks_repo_head_hexsha": "a5a65c68159900318adad898916c862119ab49ef", "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.6533333333, "max_line_length": 72, "alphanum_fraction": 0.5900367497, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5913319894997248}} {"text": "{-# LANGUAGE FlexibleContexts, TypeFamilies #-}\nmodule Main where\n\nimport Data.Complex (Complex(..), magnitude)\nimport qualified Diagrams.Prelude as D\n\nimport qualified Diagrams.Backend.Rasterific.CmdLine as CmdLine\n\nmain :: IO ()\nmain = CmdLine.mainWith (picture 32 2.0)\n\ntype C = Complex Double\n\n-- calc\nmandelbrotSet :: Traversable t =>\n Int -> Double -> t C -> t Bool\nmandelbrotSet n inf lst = fmap (testMandelbrot n inf) lst\n\ntestMandelbrot :: Int -> Double -> C -> Bool\ntestMandelbrot n inf c = isDiverged (mandelbrot c) n inf\n\nisDiverged :: (C -> C) -> Int -> Double -> Bool\nisDiverged fn n inf = filter (\\z -> magnitude z > inf) seq == []\n where seq = take n $ iterate fn 0\n\nmandelbrot :: C -> C -> C\nmandelbrot c z = z*z + c\n\n-- draw\ntoPixel :: Bool -> Int\ntoPixel True = 0\ntoPixel False = 1\n\ntoSquare n =\n D.opacity (fromIntegral n)\n $ D.fc D.black\n $ D.lw D.medium\n $ D.square 1\n\nside n v0 v1 =\n let sv = (v1 - v0) / fromIntegral n\n in [v0, (v0 + sv) .. v1]\n\ngrid :: Int -> Double -> Double -> [[C]]\ngrid n v0 v1 = map (\\y -> map (:+ y) s) s\n where s = side n v0 v1\n\nimage n inf = map (map (toSquare . toPixel . (testMandelbrot n inf))) $ grid 64 (-2) 2\n\npicture :: Int -> Double -> D.Diagram CmdLine.B\npicture n inf = D.bgFrame 3 D.pink $ (D.vcat . map D.hcat $ image n inf)\n", "meta": {"hexsha": "07f6b818c020ea02edce0e871c31fbdc762eb395", "size": 1314, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "cormojs/simple-mandelbrot", "max_stars_repo_head_hexsha": "1c140a79d061f01fdc5994de1e8418ca96d1782c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "cormojs/simple-mandelbrot", "max_issues_repo_head_hexsha": "1c140a79d061f01fdc5994de1e8418ca96d1782c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "cormojs/simple-mandelbrot", "max_forks_repo_head_hexsha": "1c140a79d061f01fdc5994de1e8418ca96d1782c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2692307692, "max_line_length": 86, "alphanum_fraction": 0.6347031963, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5913164307876777}} {"text": "module Scheme.Primitives.Numbers\n ( numericPrimitives,\n unwrapNumber,\n )\nwhere\n\nimport Control.Exception (throw)\nimport Control.Monad.Except (MonadError (throwError))\nimport Data.Complex (imagPart, realPart)\nimport Data.Ratio (denominator, numerator)\nimport Data.Text (Text)\nimport Scheme.Operators (unOp)\nimport Scheme.Types (Number (..), SchemeError (..), SchemeResult, SchemeVal (..))\n\nnumericPrimitives :: [(Text, [SchemeVal] -> SchemeResult SchemeVal)]\nnumericPrimitives =\n [ (\"number?\", unOp isNumber),\n (\"complex?\", unOp isComplex),\n (\"real?\", unOp isReal),\n (\"rational?\", unOp isRational),\n (\"integer?\", unOp isInteger),\n (\"exact?\", unOp isExact),\n (\"inexact?\", unOp isInexact),\n (\"exact-integer?\", unOp isExactInteger),\n (\"finite?\", unOp isFinite),\n (\"infinite?\", unOp isInfinite'),\n (\"nan?\", unOp isNaN'),\n (\"=\", numericBoolOp (==)),\n (\"<\", numericBoolOp (<)),\n (\">\", numericBoolOp (>)),\n (\"<=\", numericBoolOp (<=)),\n (\">=\", numericBoolOp (>=)),\n (\"+\", add),\n (\"-\", sub),\n (\"*\", multiply),\n (\"/\", division),\n (\"abs\", unOp numAbs),\n (\"floor/\", floorInt),\n (\"floor-quotient\", floorQuot),\n (\"floor-remainder\", floorRem),\n (\"truncate/\", truncateInt),\n (\"truncate-quotient\", truncateQuot),\n (\"truncate-remainder\", truncateRem),\n (\"quotient\", truncateQuot),\n (\"remainder\", truncateRem),\n (\"modulo\", floorRem),\n (\"gcd\", numGcd),\n (\"lcm\", numLcm)\n ]\n\nisNumber :: SchemeVal -> SchemeVal\nisNumber (Number (Integer _)) = Boolean True\nisNumber (Number (Real _)) = Boolean True\nisNumber (Number (Rational _)) = Boolean True\nisNumber (Number (Complex _)) = Boolean True\nisNumber _ = Boolean False\n\nisComplex :: SchemeVal -> SchemeVal\nisComplex (Number (Integer _)) = Boolean True\nisComplex (Number (Real _)) = Boolean True\nisComplex (Number (Rational _)) = Boolean True\nisComplex (Number (Complex _)) = Boolean True\nisComplex _ = Boolean False\n\nisReal :: SchemeVal -> SchemeVal\nisReal (Number (Real _)) = Boolean True\nisReal (Number (Rational _)) = Boolean True\nisReal (Number (Integer _)) = Boolean True\nisReal (Number (Complex x)) = if imagPart x == 0 then Boolean True else Boolean False\nisReal _ = Boolean False\n\nisRational :: SchemeVal -> SchemeVal\nisRational (Number (Rational _)) = Boolean True\nisRational (Number (Integer _)) = Boolean True\nisRational (Number (Real x)) = Boolean (not $ isInfinite x)\nisRational _ = Boolean False\n\nisInteger :: SchemeVal -> SchemeVal\nisInteger (Number (Integer _)) = Boolean True\nisInteger (Number (Real x)) = Boolean (isDoubleInt x)\nisInteger (Number (Rational x)) = Boolean (numerator x >= denominator x && numerator x `mod` denominator x == 0)\nisInteger (Number (Complex x)) = Boolean (isDoubleInt (realPart x) && isDoubleInt (imagPart x))\nisInteger _ = Boolean False\n\nisExact :: SchemeVal -> SchemeVal\nisExact (Number (Integer _)) = Boolean True\nisExact (Number (Rational _)) = Boolean True\nisExact _ = Boolean False\n\nisInexact :: SchemeVal -> SchemeVal\nisInexact (Number (Real _)) = Boolean True\nisInexact _ = Boolean False\n\nisExactInteger :: SchemeVal -> SchemeVal\nisExactInteger x = case (isExact x, isInteger x) of\n (Boolean True, Boolean True) -> Boolean True\n _ -> Boolean False\n\nisFinite :: SchemeVal -> SchemeVal\nisFinite (Number (Real x)) = Boolean (not (isInfinite x || isNaN x))\nisFinite (Number (Complex x)) = Boolean (not (isInfinite imag || isInfinite real || isNaN real || isNaN imag))\n where\n imag = imagPart x\n real = realPart x\nisFinite _ = Boolean True\n\nisInfinite' :: SchemeVal -> SchemeVal\nisInfinite' (Number (Real x)) = Boolean (isInfinite x || isNaN x)\nisInfinite' (Number (Complex x)) = Boolean (isInfinite imag || isInfinite real || isNaN real || isNaN imag)\n where\n imag = imagPart x\n real = realPart x\nisInfinite' _ = Boolean False\n\nisNaN' :: SchemeVal -> SchemeVal\nisNaN' (Number (Real x)) = Boolean (isNaN x)\nisNaN' (Number (Complex x)) = Boolean (isNaN (imagPart x) || isNaN (realPart x))\nisNaN' _ = Boolean False\n\nadd :: [SchemeVal] -> SchemeResult SchemeVal\nadd [] = pure $ Number $ Integer 0\nadd xs = do\n nums <- mapM unwrapNumber xs\n return $ Number (sum nums)\n\nmultiply :: [SchemeVal] -> SchemeResult SchemeVal\nmultiply [] = pure $ Number $ Integer 1\nmultiply xs = do\n nums <- mapM unwrapNumber xs\n return $ Number (product nums)\n\nsub :: [SchemeVal] -> SchemeResult SchemeVal\nsub [] = throwError $ ArgumentLengthMismatch 1 []\nsub [x] = do\n num <- unwrapNumber x\n return $ Number (negate num)\nsub xs = do\n nums <- mapM unwrapNumber xs\n return $ Number (foldl1 (-) nums)\n\ndivision :: [SchemeVal] -> SchemeResult SchemeVal\ndivision [] = throwError $ ArgumentLengthMismatch 1 []\ndivision [x] = do\n num <- unwrapNumber x\n return $ Number (recip num)\ndivision xs = do\n nums <- mapM unwrapNumber xs\n return $ Number (foldl1 (/) nums)\n\nnumAbs :: SchemeVal -> SchemeVal\nnumAbs (Number n) = Number $ abs n\nnumAbs x = throw $ TypeMismatch \"number\" x\n\nfloorInt :: [SchemeVal] -> SchemeResult SchemeVal\nfloorInt [Number (Integer x), Number (Integer y)] = return $ List [Number $ Integer x', Number $ Integer y']\n where\n (x', y') = x `divMod` y\nfloorInt [x, Number (Integer _)] = throwError $ TypeMismatch \"integer\" x\nfloorInt [Number (Integer _), x] = throwError $ TypeMismatch \"integer\" x\nfloorInt _ = throwError $ ArgumentLengthMismatch 2 []\n\nfloorQuot :: [SchemeVal] -> SchemeResult SchemeVal\nfloorQuot [Number (Integer x), Number (Integer y)] = return $ Number $ Integer (x `div` y)\nfloorQuot [x, Number (Integer _)] = throwError $ TypeMismatch \"integer\" x\nfloorQuot [Number (Integer _), x] = throwError $ TypeMismatch \"integer\" x\nfloorQuot _ = throwError $ ArgumentLengthMismatch 2 []\n\nfloorRem :: [SchemeVal] -> SchemeResult SchemeVal\nfloorRem [Number (Integer x), Number (Integer y)] = return $ Number $ Integer (x `mod` y)\nfloorRem [x, Number (Integer _)] = throwError $ TypeMismatch \"integer\" x\nfloorRem [Number (Integer _), x] = throwError $ TypeMismatch \"integer\" x\nfloorRem _ = throwError $ ArgumentLengthMismatch 2 []\n\ntruncateInt :: [SchemeVal] -> SchemeResult SchemeVal\ntruncateInt [Number (Integer x), Number (Integer y)] = return $ List [Number $ Integer x', Number $ Integer y']\n where\n (x', y') = x `quotRem` y\ntruncateInt [x, Number (Integer _)] = throwError $ TypeMismatch \"integer\" x\ntruncateInt [Number (Integer _), x] = throwError $ TypeMismatch \"integer\" x\ntruncateInt _ = throwError $ ArgumentLengthMismatch 2 []\n\ntruncateQuot :: [SchemeVal] -> SchemeResult SchemeVal\ntruncateQuot [Number (Integer x), Number (Integer y)] = return $ Number $ Integer (x `quot` y)\ntruncateQuot [x, Number (Integer _)] = throwError $ TypeMismatch \"integer\" x\ntruncateQuot [Number (Integer _), x] = throwError $ TypeMismatch \"integer\" x\ntruncateQuot _ = throwError $ ArgumentLengthMismatch 2 []\n\ntruncateRem :: [SchemeVal] -> SchemeResult SchemeVal\ntruncateRem [Number (Integer x), Number (Integer y)] = return $ Number $ Integer (x `rem` y)\ntruncateRem [x, Number (Integer _)] = throwError $ TypeMismatch \"integer\" x\ntruncateRem [Number (Integer _), x] = throwError $ TypeMismatch \"integer\" x\ntruncateRem _ = throwError $ ArgumentLengthMismatch 2 []\n\nnumGcd :: [SchemeVal] -> SchemeResult SchemeVal\nnumGcd [] = return $ Number (Integer 0)\nnumGcd [x] = return x\nnumGcd xs = do\n ints <- mapM unwrapToInt xs\n return $ Number $ Integer (foldl1 gcd ints)\n\nnumLcm :: [SchemeVal] -> SchemeResult SchemeVal\nnumLcm [] = return $ Number (Integer 1)\nnumLcm [x] = return x\nnumLcm xs = do\n ints <- mapM unwrapToInt xs\n return $ Number $ Integer (foldl1 lcm ints)\n\nnumericBoolOp :: (Number -> Number -> Bool) -> [SchemeVal] -> Either SchemeError SchemeVal\nnumericBoolOp _ [] = throwError $ ArgumentLengthMismatch 1 []\nnumericBoolOp _ [x] = case isNaN' x of\n Boolean True -> return $ Boolean False\n _ -> return $ Boolean True\nnumericBoolOp op xs = do\n nums <- mapM unwrapNumber xs\n return $ Boolean $ and $ zipWith op nums $ drop 1 nums\n\nisDoubleInt :: Double -> Bool\nisDoubleInt d = (ceiling d :: Integer) == (floor d :: Integer)\n\nunwrapToInt :: SchemeVal -> SchemeResult Integer\nunwrapToInt (Number (Integer x)) = pure x\nunwrapToInt (Number (Real x)) = pure $ floor x\nunwrapToInt (Number (Rational x)) = pure $ floor x\nunwrapToInt x = throwError $ TypeMismatch \"integer\" x\n\nunwrapNumber :: SchemeVal -> SchemeResult Number\nunwrapNumber (Number x) = pure x\nunwrapNumber (List [x]) = unwrapNumber x\nunwrapNumber x = throwError $ TypeMismatch \"number\" x\n", "meta": {"hexsha": "a6a57700d86d432a1e9e7b06a893d40434a11b9d", "size": 8453, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Scheme/Primitives/Numbers.hs", "max_stars_repo_name": "sondr3/scheme-hs", "max_stars_repo_head_hexsha": "8bf2481ff617a7103f93b12e112b643fb5a8f173", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-04T10:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T10:40:57.000Z", "max_issues_repo_path": "lib/Scheme/Primitives/Numbers.hs", "max_issues_repo_name": "sondr3/scheme-hs", "max_issues_repo_head_hexsha": "8bf2481ff617a7103f93b12e112b643fb5a8f173", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Scheme/Primitives/Numbers.hs", "max_forks_repo_name": "sondr3/scheme-hs", "max_forks_repo_head_hexsha": "8bf2481ff617a7103f93b12e112b643fb5a8f173", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.752173913, "max_line_length": 112, "alphanum_fraction": 0.6939548089, "num_tokens": 2334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5913164290395452}} {"text": "module Main where\nimport Data.NeuralNetwork.Backend.BLASHS.Utils\nimport qualified Data.Vector.Storable as SV\nimport Numeric.LinearAlgebra\nimport Test.QuickCheck (generate)\nimport Test.Utils\nimport Test.Gen\n\nmain = t3\n\nt1 = do\n ms <- test_corr2_arr 0 ks mt\n mapM_ (putStrLn . show) ms\n putStrLn \"Good ones are:\"\n let m4s = map (\\k -> good_corr2 0 k mt) ks\n mapM_ (putStrLn . show) m4s\n\nt2 = do\n let m1 = (3><3) [0, 1, 0,\n 1, 0, 1,\n 0 ,1, 0] :: Matrix Float\n let ma = (3><3) [1, 0, 1,\n 0, 1, 0,\n 1 ,0, 1] :: Matrix Float\n let mb = (3><3) [0, 0, 0,\n 0, 0, 0,\n 0 ,0, 1] :: Matrix Float\n let mc = (3><3) [0, 0, 0,\n 0, 1, 0,\n 0 ,0, 0] :: Matrix Float\n let md = (3><3) [1, 0, 0,\n 0, 0, 0,\n 0 ,0, 0] :: Matrix Float\n let m3 = (4><4) [4,3,2,1,\n 1,2,3,4,\n 2,4,6,8,\n 1,3,5,7] :: Matrix Float\n m3s <- test_corr2_arr 0 [m1, ma, mb, mc, md] m3\n mapM_ (putStrLn . show) m3s\n\nt3 = do\n ks <- generate $ sequence $ replicate 4 $ squared_real_matrices 45\n mt <- generate $ squared_real_matrices 488\n test_corr2_arr 2 ks mt\n\nks = [(3><3) [ -2.2182608, -2.65496, -4.452847\n , -0.50510013, 1.1137468, 0.5881784\n , -2.162154, -0.26882064, -0.21511263 ]\n ,(3><3) [ -168.82103, -235.06078, 4.6464214\n , 3.0136368, 0.9492494, 605.85254\n , -482.5887, 14.835919, -5.846858 ]\n ,(3><3) [ -1.3539604, 8.014306, -4.851793\n , 0.84038895, -0.77802753, 1.4430395\n , 0.5361183, -1.2853559, 1.04196 ]\n ,(3><3) [ -2.6642451, -2.149097, -4.7066493\n , 1.040131, 1.52895, -5.823082\n , -5.870729, 2.996159, 1.2088959 ]\n ,(3><3) [ -2.5846646, 2.2002325, -2.7979004\n , 0.5225487, 0.9918108, 0.85764366\n , -0.56938225, -0.14684846, 0.8047059 ]]\nmt = (7><7) [ 3.4427254, 0.7416965, 1.2416595, 0.8233356, -1.565333, 0.89987564, 0.8893491\n , -1.3306698, -3.9727004, -1.4404364, 8.25734e-2, 1.0835173, -6.5956297, 0.95600057\n , -5.312902, -9.969063e-2, 0.94423944, 0.25942376, -1.177719, -219.11214, 0.7662355\n , -3.0743675, 0.16589901, -1.338092, 1.2396933, -2.8903048, -0.2627482, 0.64401335\n , 6.0397525, -0.6807962, -0.36770278, 1.416498, 1.8280395, -0.5226003, 0.98356235\n , -1.1980977, -0.5414966, -0.18184663, 0.20523632, 1.2170252, 1.2050351, 1.1030668\n , 0.673801, 0.95085037, -2.3031695, 0.4833055, 1.8391184, 1.117064, -1.7435362 ]\n", "meta": {"hexsha": "d14be89882d1a9d60e2a89a7353e0a90360940c2", "size": 2759, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Backend-blashs/Test/S2.hs", "max_stars_repo_name": "pierric/neural-network", "max_stars_repo_head_hexsha": "406ecaf334cde9b10c9324e1f6c4b8663eae58d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-05-24T17:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T22:25:52.000Z", "max_issues_repo_path": "Backend-blashs/Test/S2.hs", "max_issues_repo_name": "pierric/neural-network", "max_issues_repo_head_hexsha": "406ecaf334cde9b10c9324e1f6c4b8663eae58d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Backend-blashs/Test/S2.hs", "max_forks_repo_name": "pierric/neural-network", "max_forks_repo_head_hexsha": "406ecaf334cde9b10c9324e1f6c4b8663eae58d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-26T19:28:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T19:28:38.000Z", "avg_line_length": 40.5735294118, "max_line_length": 103, "alphanum_fraction": 0.5019934759, "num_tokens": 1243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5911796405816089}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Statistics.Distribution.Beta\n-- Copyright : (C) 2012 Edward Kmett,\n-- License : BSD-style (see the file LICENSE)\n--\n-- Maintainer : Edward Kmett \n-- Stability : provisional\n-- Portability : DeriveDataTypeable\n--\n----------------------------------------------------------------------------\nmodule Statistics.Distribution.Beta\n ( BetaDistribution\n -- * Constructor\n , betaDistr\n , betaDistrE\n , improperBetaDistr\n , improperBetaDistrE\n -- * Accessors\n , bdAlpha\n , bdBeta\n ) where\n\nimport Control.Applicative\nimport Data.Aeson (FromJSON(..), ToJSON, Value(..), (.:))\nimport Data.Binary (Binary(..))\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.SpecFunctions (\n incompleteBeta, invIncompleteBeta, logBeta, digamma, log1p)\nimport Numeric.MathFunctions.Constants (m_NaN,m_neg_inf)\nimport qualified Statistics.Distribution as D\nimport Statistics.Internal\n\n\n-- | The beta distribution\ndata BetaDistribution = BD\n { bdAlpha :: {-# UNPACK #-} !Double\n -- ^ Alpha shape parameter\n , bdBeta :: {-# UNPACK #-} !Double\n -- ^ Beta shape parameter\n } deriving (Eq, Typeable, Data, Generic)\n\ninstance Show BetaDistribution where\n showsPrec n (BD a b) = defaultShow2 \"improperBetaDistr\" a b n\ninstance Read BetaDistribution where\n readPrec = defaultReadPrecM2 \"improperBetaDistr\" improperBetaDistrE\n\ninstance ToJSON BetaDistribution\ninstance FromJSON BetaDistribution where\n parseJSON (Object v) = do\n a <- v .: \"bdAlpha\"\n b <- v .: \"bdBeta\"\n maybe (fail $ errMsgI a b) return $ improperBetaDistrE a b\n parseJSON _ = empty\n\ninstance Binary BetaDistribution where\n put (BD a b) = put a >> put b\n get = do\n a <- get\n b <- get\n maybe (fail $ errMsgI a b) return $ improperBetaDistrE a b\n\n\n-- | Create beta distribution. Both shape parameters must be positive.\nbetaDistr :: Double -- ^ Shape parameter alpha\n -> Double -- ^ Shape parameter beta\n -> BetaDistribution\nbetaDistr a b = maybe (error $ errMsg a b) id $ betaDistrE a b\n\n-- | Create beta distribution. Both shape parameters must be positive.\nbetaDistrE :: Double -- ^ Shape parameter alpha\n -> Double -- ^ Shape parameter beta\n -> Maybe BetaDistribution\nbetaDistrE a b\n | a > 0 && b > 0 = Just (BD a b)\n | otherwise = Nothing\n\nerrMsg :: Double -> Double -> String\nerrMsg a b = \"Statistics.Distribution.Beta.betaDistr: \"\n ++ \"shape parameters must be positive. Got a = \"\n ++ show a\n ++ \" b = \"\n ++ show b\n\n\n-- | Create beta distribution. Both shape parameters must be\n-- non-negative. So it allows to construct improper beta distribution\n-- which could be used as improper prior.\nimproperBetaDistr :: Double -- ^ Shape parameter alpha\n -> Double -- ^ Shape parameter beta\n -> BetaDistribution\nimproperBetaDistr a b\n = maybe (error $ errMsgI a b) id $ improperBetaDistrE a b\n\n-- | Create beta distribution. Both shape parameters must be\n-- non-negative. So it allows to construct improper beta distribution\n-- which could be used as improper prior.\nimproperBetaDistrE :: Double -- ^ Shape parameter alpha\n -> Double -- ^ Shape parameter beta\n -> Maybe BetaDistribution\nimproperBetaDistrE a b\n | a >= 0 && b >= 0 = Just (BD a b)\n | otherwise = Nothing\n\nerrMsgI :: Double -> Double -> String\nerrMsgI a b\n = \"Statistics.Distribution.Beta.betaDistr: \"\n ++ \"shape parameters must be non-negative. Got a = \" ++ show a\n ++ \" b = \" ++ show b\n\n\n\ninstance D.Distribution BetaDistribution where\n cumulative (BD a b) x\n | x <= 0 = 0\n | x >= 1 = 1\n | otherwise = incompleteBeta a b x\n complCumulative (BD a b) x\n | x <= 0 = 1\n | x >= 1 = 0\n -- For small x we use direct computation to avoid precision loss\n -- when computing (1-x)\n | x < 0.5 = 1 - incompleteBeta a b x\n -- Otherwise we use property of incomplete beta:\n -- > I(x,a,b) = 1 - I(1-x,b,a)\n | otherwise = incompleteBeta b a (1-x)\n\ninstance D.Mean BetaDistribution where\n mean (BD a b) = a / (a + b)\n\ninstance D.MaybeMean BetaDistribution where\n maybeMean = Just . D.mean\n\ninstance D.Variance BetaDistribution where\n variance (BD a b) = a*b / (apb*apb*(apb+1))\n where apb = a + b\n\ninstance D.MaybeVariance BetaDistribution where\n maybeVariance = Just . D.variance\n\ninstance D.Entropy BetaDistribution where\n entropy (BD a b) =\n logBeta a b\n - (a-1) * digamma a\n - (b-1) * digamma b\n + (a+b-2) * digamma (a+b)\n\ninstance D.MaybeEntropy BetaDistribution where\n maybeEntropy = Just . D.entropy\n\ninstance D.ContDistr BetaDistribution where\n density (BD a b) x\n | a <= 0 || b <= 0 = m_NaN\n | x <= 0 = 0\n | x >= 1 = 0\n | otherwise = exp $ (a-1)*log x + (b-1) * log1p (-x) - logBeta a b\n logDensity (BD a b) x\n | a <= 0 || b <= 0 = m_NaN\n | x <= 0 = m_neg_inf\n | x >= 1 = m_neg_inf\n | otherwise = (a-1)*log x + (b-1)*log1p (-x) - logBeta a b\n\n quantile (BD a b) p\n | p == 0 = 0\n | p == 1 = 1\n | p > 0 && p < 1 = invIncompleteBeta a b p\n | otherwise =\n error $ \"Statistics.Distribution.Gamma.quantile: p must be in [0,1] range. Got: \"++show p\n\ninstance D.ContGen BetaDistribution where\n genContVar = D.genContinuous\n", "meta": {"hexsha": "01ce39ebe2393d6e5af9304d4594e72485bf829a", "size": 5627, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Beta.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:39:40.000Z", "max_issues_repo_path": "Statistics/Distribution/Beta.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T14:21:32.000Z", "max_forks_repo_path": "Statistics/Distribution/Beta.hs", "max_forks_repo_name": "infinity0/statistics", "max_forks_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2015-02-13T00:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:19:16.000Z", "avg_line_length": 32.1542857143, "max_line_length": 97, "alphanum_fraction": 0.6097387596, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5910745125821422}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\nmodule Data.Array.ShapedS.MatMul(matMul) where\nimport Prelude hiding ((<>))\nimport GHC.Stack\nimport GHC.TypeLits\nimport Data.Array.Internal(valueOf)\nimport Data.Array.ShapedS\nimport Numeric.LinearAlgebra as N\n\nmatMul :: forall m n o a .\n (HasCallStack, N.Numeric a, KnownNat m, KnownNat n, KnownNat o) =>\n Array [m, n] a -> Array [n, o] a -> Array [m, o] a\nmatMul x y =\n let n = valueOf @n\n o = valueOf @o\n x' = N.reshape n $ toVector x\n y' = N.reshape o $ toVector y\n xy' = x' N.<> y'\n xy = fromVector $ N.flatten xy'\n in xy\n", "meta": {"hexsha": "0783ca19ba2dfad7c50f036d0a7428eab02a4bb5", "size": 670, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Array/ShapedS/MatMul.hs", "max_stars_repo_name": "augustss/orthotope-hmatrix", "max_stars_repo_head_hexsha": "4806a67ac5228ffc1dab317b3df2cda36d4679d6", "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": "Data/Array/ShapedS/MatMul.hs", "max_issues_repo_name": "augustss/orthotope-hmatrix", "max_issues_repo_head_hexsha": "4806a67ac5228ffc1dab317b3df2cda36d4679d6", "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": "Data/Array/ShapedS/MatMul.hs", "max_forks_repo_name": "augustss/orthotope-hmatrix", "max_forks_repo_head_hexsha": "4806a67ac5228ffc1dab317b3df2cda36d4679d6", "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": 29.1304347826, "max_line_length": 76, "alphanum_fraction": 0.6328358209, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952893703478, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5910582766593313}} {"text": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\n\nmodule UnboxedSpec where\n\nimport Data.Complex\nimport Data.Proxy\n\nimport Test.QuickCheck\n\nimport Category\nimport Functor\nimport Hask()\nimport Unboxed\n\n\n\ntype UA = Int *#* Float\ntype UB = Double\ntype UC = Complex Double\ntype UD = Int\n\nprop_Unboxed_Discretization_inv :: Fun UA UB -> FnProp UA\nprop_Unboxed_Discretization_inv f =\n checkFnEqual (law_Discretization_inv (UQCFun f))\n\nprop_Unboxed_Discretization_approx :: Fun UA UB -> FnProp UA\nprop_Unboxed_Discretization_approx (Fn f) =\n checkFnEqual (law_Discretization_approx (Proxy @(-#>)) f)\n\n\n\nprop_Unboxed_MId_id :: UA -> Property\nprop_Unboxed_MId_id = law_MId_id (Proxy @Unboxed)\n\nprop_Unboxed_MCompose_compose :: Fun UB UC -> Fun UA UB -> UA -> Property\nprop_Unboxed_MCompose_compose f g = law_MCompose_compose (UQCFun f) (UQCFun g)\n\nprop_Unboxed_MCompose_left_id :: Fun UA UB -> UA -> Property\nprop_Unboxed_MCompose_left_id f = law_MCompose_left_id (UQCFun f)\n\nprop_Unboxed_MCompose_right_id :: Fun UA UB -> UA -> Property\nprop_Unboxed_MCompose_right_id f = law_MCompose_right_id (UQCFun f)\n\nprop_Unboxed_MCompose_assoc ::\n Fun UC UD -> Fun UB UC -> Fun UA UB -> UA -> Property\nprop_Unboxed_MCompose_assoc f g h =\n law_MCompose_assoc (UQCFun f) (UQCFun g) (UQCFun h)\n\n\n\nprop_Unboxed_Functor_id :: FnProp (Float *#* UA)\nprop_Unboxed_Functor_id = checkFnEqual law_Functor_id\n\nprop_Unboxed_Functor_comp ::\n (UB -#> UC) -> (UA -#> UB) -> FnProp (Float *#* UA)\nprop_Unboxed_Functor_comp f g = checkFnEqual (law_Functor_comp f g)\n", "meta": {"hexsha": "dbaa99fc5e14cbaffabec2c551d965d409408230", "size": 1540, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/UnboxedSpec.hs", "max_stars_repo_name": "eschnett/wavetoy6", "max_stars_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/UnboxedSpec.hs", "max_issues_repo_name": "eschnett/wavetoy6", "max_issues_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/UnboxedSpec.hs", "max_forks_repo_name": "eschnett/wavetoy6", "max_forks_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0175438596, "max_line_length": 78, "alphanum_fraction": 0.7597402597, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5908430893458209}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Foreign.BLAS.Level1\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Vector operations.\n--\n\nmodule Foreign.BLAS.Level1 (\n BLAS1(..),\n ) where\n \nimport Foreign( Storable, Ptr, peek, with )\nimport Foreign.Storable.Complex()\nimport Data.Complex( Complex(..) )\n\nimport Foreign.VMath.VFractional( VFractional )\nimport Foreign.BLAS.Double \nimport Foreign.BLAS.Zomplex\n \n-- | Types with vector-vector operations.\nclass (Storable a, VFractional a) => BLAS1 a where\n copy :: Int -> Ptr a -> Int -> Ptr a -> Int -> IO () \n swap :: Int -> Ptr a -> Int -> Ptr a -> Int -> IO ()\n dotc :: Int -> Ptr a -> Int -> Ptr a -> Int -> IO a\n dotu :: Int -> Ptr a -> Int -> Ptr a -> Int -> IO a \n nrm2 :: Int -> Ptr a -> Int -> IO Double\n asum :: Int -> Ptr a -> Int -> IO Double\n iamax :: Int -> Ptr a -> Int -> IO Int\n \n scal :: Int -> a -> Ptr a -> Int -> IO () \n\n axpy :: Int -> a -> Ptr a -> Int -> Ptr a -> Int -> IO ()\n\n rotg :: Ptr a -> Ptr a -> Ptr a -> Ptr a -> IO ()\n rot :: Int -> Ptr a -> Int -> Ptr a -> Int -> Double -> Double -> IO ()\n\n\nwithEnum :: (Enum a, Storable a) => Int -> (Ptr a -> IO b) -> IO b\nwithEnum = with . toEnum\n{-# INLINE withEnum #-}\n\ninstance BLAS1 Double where\n copy n px incx py incy =\n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n dcopy pn px pincx py pincy\n {-# INLINE copy #-}\n\n swap n px incx py incy = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n dswap pn px pincx py pincy\n {-# INLINE swap #-}\n\n dotc n px incx py incy = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n ddot pn px pincx py pincy\n {-# INLINE dotc #-}\n\n dotu = dotc\n {-# INLINE dotu #-}\n \n nrm2 n px incx = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n dnrm2 pn px pincx\n {-# INLINE nrm2 #-}\n\n asum n px incx = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n dasum pn px pincx\n {-# INLINE asum #-}\n\n iamax n px incx = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx -> do\n i <- idamax pn px pincx\n return $! fromEnum (i - 1)\n {-# INLINE iamax #-}\n\n axpy n alpha px incx py incy = \n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n daxpy pn palpha px pincx py pincy\n {-# INLINE axpy #-}\n \n scal n alpha px incx = \n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n dscal pn palpha px pincx\n {-# INLINE scal #-}\n\n rotg = drotg\n {-# INLINE rotg #-}\n \n rot n px incx py incy c s = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n with c $ \\pc ->\n with s $ \\ps ->\n drot pn px pincx py pincy pc ps\n {-# INLINE rot #-}\n\n\ninstance BLAS1 (Complex Double) where\n copy n px incx py incy =\n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n zcopy pn px pincx py pincy\n {-# INLINE copy #-}\n\n swap n px incx py incy = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n zswap pn px pincx py pincy\n {-# INLINE swap #-}\n \n dotc n px incx py incy =\n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n with 0 $ \\pdotc -> do\n zdotc pdotc pn px pincx py pincy\n peek pdotc\n {-# INLINE dotc #-}\n\n dotu n px incx py incy =\n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n with 0 $ \\pdotu -> do\n zdotu pdotu pn px pincx py pincy\n peek pdotu\n {-# INLINE dotu #-}\n\n nrm2 n px incx = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n znrm2 pn px pincx\n {-# INLINE nrm2 #-}\n\n asum n px incx = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n zasum pn px pincx\n {-# INLINE asum #-}\n\n iamax n px incx = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx -> do\n i <- izamax pn px pincx\n return $! fromEnum (i - 1)\n {-# INLINE iamax #-}\n\n axpy n alpha px incx py incy = \n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n zaxpy pn palpha px pincx py pincy\n {-# INLINE axpy #-}\n \n scal n alpha px incx = \n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n zscal pn palpha px pincx\n {-# INLINE scal #-}\n\n rotg = zrotg\n {-# INLINE rotg #-}\n \n rot n px incx py incy c s = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n with c $ \\pc ->\n with s $ \\ps ->\n zdrot pn px pincx py pincy pc ps\n {-# INLINE rot #-}\n", "meta": {"hexsha": "773e4073eafc08c94e5174102019f0c4faf185b4", "size": 5402, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Foreign/BLAS/Level1.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Foreign/BLAS/Level1.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Foreign/BLAS/Level1.hs", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 27.421319797, "max_line_length": 77, "alphanum_fraction": 0.4907441688, "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5908430885997505}} {"text": "module Main where\nimport Plot\nimport Graphics.GD\nimport Data.Complex\n\nimageDim :: Size\nimageDim = (600,600)\n\n-- How many iterations before we declare the point doesn't diverge\nmaxIter = 255\n\n-- Coordinates in the complex plane to graph\n-- First coordinate must be top left\nmbWindow :: Window\nmbWindow = ( (-1.8, 0.02), (-1.7, -0.08) ) -- smaller ship on horizon\n\nmain :: IO ()\nmain = drawPlot drawShip imageDim mbWindow \"burning-ship.png\"\n\ndrawShip :: Coordinate -> Color\ndrawShip (x,y) = colorIterations $ ship (x :+ y) (0 :+ 0) 0\n\n-- Count number of iterations for the given point to diverge\n-- Non-diverging points return 0\nship :: Complex Double -- Coordinate to test\n -> Complex Double -- Iterating Z value\n -> Int -- Current iteration\n -> Int -- Iterations before diverging\nship c z iter\n | iter > maxIter = 0\n | otherwise = let z' = (abs(realPart z) :+ abs(imagPart z))^2 + c in\n if magnitude z' > 2\n then iter\n else ship c z' (iter+1)\n\ncolorIterations :: Int -> Color\ncolorIterations x\n | x > maxIter = rgb 255 255 255\n | otherwise = rgb x x x\n", "meta": {"hexsha": "5a7b00be279b3221a5ccfe7c1a6a9560d029f575", "size": 1146, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "executables/burning_ship.hs", "max_stars_repo_name": "typeclasses/fractal-sets", "max_stars_repo_head_hexsha": "b5ac9b52a5857078bb242c92cc1837869e8741de", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-06-02T04:34:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T06:24:07.000Z", "max_issues_repo_path": "executables/burning_ship.hs", "max_issues_repo_name": "typeclasses/fractal-sets", "max_issues_repo_head_hexsha": "b5ac9b52a5857078bb242c92cc1837869e8741de", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-03-08T21:44:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-05T21:14:53.000Z", "max_forks_repo_path": "executables/burning_ship.hs", "max_forks_repo_name": "typeclasses/fractal-sets", "max_forks_repo_head_hexsha": "b5ac9b52a5857078bb242c92cc1837869e8741de", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-28T22:49:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-28T22:49:21.000Z", "avg_line_length": 28.65, "max_line_length": 72, "alphanum_fraction": 0.6361256545, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206198, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5906630979687288}} {"text": "module Titanic where\n\nimport Numeric.LinearAlgebra (col, disp, Matrix, R, rand, scale, toLists, tr, Vector, (><))\nimport Numeric.LinearAlgebra.HMatrix (mul, matrix, sumElements)\nimport Text.Read (readMaybe)\n\ntype Gender = Double\ntype Age = Double\ntype SibSp = Double\ntype Embarked = Double\ntype PClass = Double\ntype Survived = Double\n\ndata Row = Row Gender Age PClass Embarked\n\nprocessRow :: [[Char]] -> [Double]\nprocessRow row = [gender, age] ++ pclass ++ embarked where\n gender = getGender row\n age = getAge row\n pclass = getPClass row\n embarked = getEmbarked row\n\nprocessFeatures :: [[[Char]]] -> Matrix Double\nprocessFeatures inputs = matrix 8 $ concat [processRow x | x <- inputs]\n\nprocessGender :: [[[Char]]] -> Matrix Gender\nprocessGender inputs = do\n col [getGender x | x <- inputs]\n\nprocessTargets :: [[[Char]]] -> Matrix Survived\nprocessTargets inputs = do\n col [getTarget x | x <- inputs]\n\ngetAge :: [[Char]] -> Age\ngetAge row = case (readMaybe (row !! 6)) of\n -- 80 is the maximum age in the dataset. We divide the age by it to\n -- keep it between 0.0 and 1.0\n Just x -> x / 80\n Nothing -> 0.0\n\ngetPClass :: [[Char]] -> [PClass]\ngetPClass row = case (row !! 2) of\n \"1\" -> [1.0, 0.0, 0.0]\n \"2\" -> [0.0, 1.0, 0.0]\n \"3\" -> [0.0, 0.0, 1.0]\n \"\" -> [0.0, 0.0, 0.0]\n\ngetEmbarked :: [[Char]] -> [Embarked]\ngetEmbarked row = case (readMaybe (row !! 12)) of\n Just x -> case x of\n \"C\" -> [1.0, 0.0, 0.0]\n \"Q\" -> [0.0, 1.0, 0.0]\n \"S\" -> [0.0, 0.0, 1.0]\n Nothing -> [0.0, 0.0, 0.0]\n\ngetGender :: [[Char]] -> Gender\ngetGender row = case (row !! 5) of\n \"male\" -> -1.0\n \"female\" -> 1.0\n\ngetTarget :: [[Char]] -> Survived\ngetTarget row = fromIntegral $ read $ row !! 1\n\n", "meta": {"hexsha": "679a24c0bbef2ba3adea037131302b3426ad741e", "size": 1820, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Titanic.hs", "max_stars_repo_name": "staturecrane/haskell-ml", "max_stars_repo_head_hexsha": "13177bf6f951500e8221fc125902929f7feb5e38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-14T20:47:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-14T20:47:58.000Z", "max_issues_repo_path": "src/Titanic.hs", "max_issues_repo_name": "staturecrane/haskell-ml", "max_issues_repo_head_hexsha": "13177bf6f951500e8221fc125902929f7feb5e38", "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/Titanic.hs", "max_forks_repo_name": "staturecrane/haskell-ml", "max_forks_repo_head_hexsha": "13177bf6f951500e8221fc125902929f7feb5e38", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4375, "max_line_length": 115, "alphanum_fraction": 0.5774725275, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5903553103147932}} {"text": "{-# language BangPatterns #-}\n{-# language LambdaCase #-}\n{-# language MagicHash #-}\n{-# language ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -Wall #-}\n\nmodule Streaming.FFT\n ( -- * streaming fft\n streamFFT\n \n -- * Types\n , Transform(..)\n , Window(..)\n ) where\n\nimport GHC.Classes (modInt#)\nimport Streaming.FFT.Types\nimport qualified Data.Complex as Complex\nimport qualified Data.Primitive.Contiguous as Contiguous\nimport qualified Data.Primitive.Contiguous.FFT as Contiguous\nimport qualified Streaming.Prelude as S\nimport Control.Monad.Trans.Class (lift)\n\nintToDouble :: Int -> Double\n{-# inline intToDouble #-}\nintToDouble = fromIntegral\n\ncissy :: Double -> Double -> Complex Double\ncissy k n = Complex.cis (2 * pi * k / n)\n\nwindowSize :: Window -> Int\nwindowSize = \\case\n Window64 -> 64\n Window128 -> 128\n Window256 -> 256\n Window512 -> 512\n Window1024 -> 1024\n\n-- | Only safe when the second argument is not 0\nunsafeMod :: Int -> Int -> Int\nunsafeMod (I# x#) (I# y#) = I# (modInt# x# y#)\n{-# inline unsafeMod #-} -- this should happen anyway. trust but verify.\n\n-- | Compute the FFT of a previously computed FFT given a new sample.\n-- This operation is done in-place.\n--\n-- /O(n)/\nsubFFT :: forall m. PrimMonad m\n => Complex Double -- ^ newest signal, x_{k+N}\n -> Transform m\n -> m ()\nsubFFT x_k_plus_N (Transform f1) = do\n n <- Contiguous.sizeMutable f1\n x_k <- Contiguous.read f1 0\n let go :: Int -> m ()\n go !f = if f < n\n then do {\n atIx <- Contiguous.read f1 f\n ; let expTerm = cissy (intToDouble $ (n + 1) * f) (intToDouble n)\n res = expTerm * (atIx + x_k_plus_N - x_k)\n ; Contiguous.write f1 f res\n ; go (f + 1) \n }\n else pure ()\n go 0\n\nloadInitial :: forall m b. (PrimMonad m)\n => MutablePrimArray (PrimState m) (Complex Double)\n -> Window -- ^ window size\n -> Int -- ^ index\n -> Int -- ^ have we finished consuming the signal\n -> Stream (Of (Complex Double)) m b -- ^ first part of stream\n -> m (Stream (Of (Complex Double)) m b) -- ^ stream minus original signal\nloadInitial marr sig !ix !untilSig stream =\n if (untilSig >= windowSize sig)\n then pure stream\n else do {\n S.next stream >>= \\case\n Left _ -> pure stream\n Right (x,rest) -> if ix == 0\n then loadInitial marr sig (ix + 1) untilSig stream\n else do {\n Contiguous.write marr (unsafeMod (ix - 1 + untilSig) (windowSize sig)) x\n ; loadInitial marr sig (ix + 1) (untilSig + 1) rest\n } \n }\n\nthereafter :: forall m b c. (PrimMonad m)\n => (Transform m -> m c)\n -> Window\n -> Int -- ^ have we filled the window size\n -> Transform m -- ^ transform\n -> Stream (Of (Complex Double)) m b\n -> Stream (Of c) m b\nthereafter extract win !untilWin trans st =\n if (untilWin >= windowSize win)\n then thereafter extract win 0 trans st\n else do {\n e <- lift $ S.next st\n ; case e of {\n Left r -> pure r\n ; Right (x,rest) -> do {\n lift $ subFFT x trans\n ; info <- lift $ extract trans\n ; S.yield info\n ; thereafter extract win (untilWin + 1) trans rest\n }\n }\n }\n\nstreamFFT :: forall m b c. (PrimMonad m)\n => (Transform m -> m c)\n -> Window\n -> Stream (Of (Complex Double)) m b\n -> Stream (Of c) m b\nstreamFFT extract win stream = do\n -- Allocate the one array \n marr <- lift $ Contiguous.new (windowSize win)\n\n -- Grab the first signal from the stream\n streamMinusFirst <- lift $ loadInitial marr win 0 0 stream\n \n -- Get our first transform\n initialT :: Transform m <- lift $ do { Contiguous.mfft marr; pure $ Transform marr }\n\n -- Extract information from that transform\n initialInfo <- lift $ extract initialT\n\n -- Yield that information to the new stream\n S.yield initialInfo\n\n -- Now go\n thereafter extract win 0 initialT streamMinusFirst\n", "meta": {"hexsha": "223c274bc87b25fa0db7944b443d94f4ad2f5139", "size": 3950, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Streaming/FFT.hs", "max_stars_repo_name": "chessai/streaming-fft", "max_stars_repo_head_hexsha": "d81d9f12fc68e0051a2464f530d1b78424ca3bfb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-06-26T23:11:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T05:33:17.000Z", "max_issues_repo_path": "src/Streaming/FFT.hs", "max_issues_repo_name": "chessai/streaming-fft", "max_issues_repo_head_hexsha": "d81d9f12fc68e0051a2464f530d1b78424ca3bfb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-07-02T19:24:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-12T14:48:21.000Z", "max_forks_repo_path": "src/Streaming/FFT.hs", "max_forks_repo_name": "chessai/streaming-fft", "max_forks_repo_head_hexsha": "d81d9f12fc68e0051a2464f530d1b78424ca3bfb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-27T12:31:28.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-27T12:31:28.000Z", "avg_line_length": 29.2592592593, "max_line_length": 86, "alphanum_fraction": 0.6088607595, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5902385790045633}} {"text": "-- |\n-- Module: Math.NumberTheory.DirichletCharacters\n-- Copyright: (c) 2018 Bhavik Mehta\n-- Licence: MIT\n-- Maintainer: Bhavik Mehta \n--\n-- Implementation and enumeration of Dirichlet characters.\n--\n\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ViewPatterns #-}\n\nmodule Math.NumberTheory.DirichletCharacters\n (\n -- * Roots of unity\n RootOfUnity\n -- ** Conversions\n , toRootOfUnity\n , fromRootOfUnity\n , toComplex\n -- * An absorbing semigroup\n , OrZero, pattern Zero, pattern NonZero\n , orZeroToNum\n -- * Dirichlet characters\n , DirichletCharacter\n -- ** Construction\n , indexToChar\n , indicesToChars\n , characterNumber\n , allChars\n , fromTable\n -- ** Evaluation\n , eval\n , evalGeneral\n , evalAll\n -- ** Special Dirichlet characters\n , principalChar\n , isPrincipal\n , orderChar\n -- ** Real Dirichlet characters\n , RealCharacter\n , isRealCharacter\n , getRealChar\n , toRealFunction\n , jacobiCharacter\n -- ** Primitive characters\n , PrimitiveCharacter\n , isPrimitive\n , getPrimitiveChar\n , induced\n , makePrimitive\n , WithNat(..)\n -- * Debugging\n , validChar\n ) where\n\n#if !MIN_VERSION_base(4,12,0)\nimport Control.Applicative (liftA2)\n#endif\nimport Data.Bits (Bits(..))\nimport Data.Complex (Complex(..), cis)\nimport Data.Foldable (for_)\nimport Data.Functor.Identity (Identity(..))\nimport Data.List (mapAccumL, foldl', sort, find, unfoldr)\nimport Data.Maybe (mapMaybe, fromJust, fromMaybe)\n#if MIN_VERSION_base(4,12,0)\nimport Data.Monoid (Ap(..))\n#endif\nimport Data.Proxy (Proxy(..))\nimport Data.Ratio ((%), numerator, denominator)\nimport Data.Semigroup (Semigroup(..), Product(..))\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Mutable as MV\nimport Data.Vector (Vector, (!))\nimport GHC.TypeNats.Compat (Nat, SomeNat(..), natVal, someNatVal)\nimport Numeric.Natural (Natural)\n\nimport Math.NumberTheory.ArithmeticFunctions (totient)\nimport Math.NumberTheory.Moduli.Chinese\nimport Math.NumberTheory.Moduli.Class (KnownNat, Mod, getVal)\nimport Math.NumberTheory.Moduli.Internal (isPrimitiveRoot', discreteLogarithmPP)\nimport Math.NumberTheory.Moduli.Multiplicative (MultMod(..), isMultElement)\nimport Math.NumberTheory.Moduli.Singleton (Some(..), cyclicGroupFromFactors)\nimport Math.NumberTheory.Powers.Modular (powMod)\nimport Math.NumberTheory.Primes (Prime(..), UniqueFactorisation, factorise, nextPrime)\nimport Math.NumberTheory.Utils.FromIntegral (wordToInt)\nimport Math.NumberTheory.Utils\n\n-- | A Dirichlet character mod \\(n\\) is a group homomorphism from \\((\\mathbb{Z}/n\\mathbb{Z})^*\\)\n-- to \\(\\mathbb{C}^*\\), represented abstractly by `DirichletCharacter`. In particular, they take\n-- values at roots of unity and can be evaluated using `eval`.\n-- A Dirichlet character can be extended to a completely multiplicative function on \\(\\mathbb{Z}\\)\n-- by assigning the value 0 for \\(a\\) sharing a common factor with \\(n\\), using `evalGeneral`.\n--\n-- There are finitely many possible Dirichlet characters for a given modulus, in particular there\n-- are \\(\\phi(n)\\) characters modulo \\(n\\), where \\(\\phi\\) refers to Euler's `totient` function.\n-- This gives rise to `Enum` and `Bounded` instances.\nnewtype DirichletCharacter (n :: Nat) = Generated [DirichletFactor]\n\n-- | The group (Z/nZ)^* decomposes to a product (Z/2^k0 Z)^* x (Z/p1^k1 Z)^* x ... x (Z/pi^ki Z)^*\n-- where n = 2^k0 p1^k1 ... pi^ki, and the pj are odd primes, k0 possibly 0. Thus, a group\n-- homomorphism from (Z/nZ)^* is characterised by group homomorphisms from each of these factor\n-- groups. Furthermore, for odd p, we have (Z/p^k Z)^* isomorphic to Z / p^(k-1)*(p-1) Z, an\n-- additive group, where an isomorphism is specified by a choice of primitive root.\n-- Similarly, for k >= 2, (Z/2^k Z)^* is isomorphic to Z/2Z * (Z / 2^(k-2) Z) (and for k < 2\n-- it is trivial). (See `lambda` for this isomorphism).\n-- Thus, to specify a Dirichlet character, it suffices to specify the value of generators\n-- of each of these cyclic groups, when primitive roots are given. This data is given by a\n-- DirichletFactor.\n-- We have the invariant that the factors must be given in strictly increasing order, and the\n-- generator is as given by `generator`, and are each non-trivial. These conditions are verified\n-- using `validChar`.\ndata DirichletFactor = OddPrime { _getPrime :: Prime Natural\n , _getPower :: Word\n , _getGenerator :: Natural\n , _getValue :: RootOfUnity\n }\n | TwoPower { _getPower2 :: Int -- this ought to be Word, but many applications\n -- needed to use wordToInt, so Int is cleaner\n -- Required to be >= 2\n , _getFirstValue :: RootOfUnity\n , _getSecondValue :: RootOfUnity\n }\n | Two\n\ninstance Eq (DirichletCharacter n) where\n Generated a == Generated b = a == b\n\ninstance Eq DirichletFactor where\n TwoPower _ x1 x2 == TwoPower _ y1 y2 = x1 == y1 && x2 == y2\n OddPrime _ _ _ x == OddPrime _ _ _ y = x == y\n Two == Two = True\n _ == _ = False\n\n-- | A representation of : complex\n-- numbers \\(z\\) for which there is \\(n\\) such that \\(z^n=1\\).\nnewtype RootOfUnity =\n RootOfUnity { -- | Every root of unity can be expressed as \\(e^{2 \\pi i q}\\) for some\n -- rational \\(q\\) satisfying \\(0 \\leq q < 1\\), this function extracts it.\n fromRootOfUnity :: Rational }\n deriving (Eq)\n\ninstance Show RootOfUnity where\n show (RootOfUnity q)\n | n == 0 = \"1\"\n | d == 1 = \"-1\"\n | n == 1 = \"e^(\u03c0i/\" ++ show d ++ \")\"\n | otherwise = \"e^(\" ++ show n ++ \"\u03c0i/\" ++ show d ++ \")\"\n where n = numerator (2*q)\n d = denominator (2*q)\n\n-- | Given a rational \\(q\\), produce the root of unity \\(e^{2 \\pi i q}\\).\ntoRootOfUnity :: Rational -> RootOfUnity\ntoRootOfUnity q = RootOfUnity ((n `rem` d) % d)\n where n = numerator q\n d = denominator q\n -- effectively q `mod` 1\n -- This smart constructor ensures that the rational is always in the range 0 <= q < 1.\n\n-- | This Semigroup is in fact a group, so @'stimes'@ can be called with a negative first argument.\ninstance Semigroup RootOfUnity where\n RootOfUnity q1 <> RootOfUnity q2 = toRootOfUnity (q1 + q2)\n stimes k (RootOfUnity q) = toRootOfUnity (q * fromIntegral k)\n\ninstance Monoid RootOfUnity where\n mappend = (<>)\n mempty = RootOfUnity 0\n\n-- | Convert a root of unity into an inexact complex number. Due to floating point inaccuracies,\n-- it is recommended to avoid use of this until the end of a calculation. Alternatively, with\n-- the [cyclotomic](http://hackage.haskell.org/package/cyclotomic-0.5.1) package, one can use\n-- @[polarRat](https://hackage.haskell.org/package/cyclotomic-0.5.1/docs/Data-Complex-Cyclotomic.html#v:polarRat)\n-- 1 . @'fromRootOfUnity' to convert to a cyclotomic number.\ntoComplex :: Floating a => RootOfUnity -> Complex a\ntoComplex (RootOfUnity t)\n | t == 1/2 = (-1) :+ 0\n | t == 1/4 = 0 :+ 1\n | t == 3/4 = 0 :+ (-1)\n | otherwise = cis . (2*pi*) . fromRational $ t\n\n-- | For primes, define the canonical primitive root as the smallest such. For prime powers \\(p^k\\),\n-- either the smallest primitive root \\(g\\) mod \\(p\\) works, or \\(g+p\\) works.\ngenerator :: (Integral a, UniqueFactorisation a) => Prime a -> Word -> a\ngenerator p k\n | k == 1 = modP\n | otherwise = if powMod modP (p'-1) (p'*p') == 1 then modP + p' else modP\n where p' = unPrime p\n modP = case cyclicGroupFromFactors [(p,k)] of\n Just (Some cg) -> head $ filter (isPrimitiveRoot' cg) [2..p'-1]\n _ -> error \"illegal\"\n\n-- | Implement the function \\(\\lambda\\) from page 5 of\n-- https://www2.eecs.berkeley.edu/Pubs/TechRpts/1984/CSD-84-186.pdf\nlambda :: Integer -> Int -> Integer\nlambda x e = ((powMod x (2*modulus) largeMod - 1) `shiftR` (e+1)) .&. (modulus - 1)\n where modulus = bit (e-2)\n largeMod = bit (2*e - 1)\n\n-- | For elements of the multiplicative group \\((\\mathbb{Z}/n\\mathbb{Z})^*\\), a Dirichlet\n-- character evaluates to a root of unity.\neval :: DirichletCharacter n -> MultMod n -> RootOfUnity\neval (Generated ds) m = foldMap (evalFactor m') ds\n where m' = getVal $ multElement m\n\n-- | Evaluate each factor of the Dirichlet character.\nevalFactor :: Integer -> DirichletFactor -> RootOfUnity\nevalFactor m =\n \\case\n OddPrime (toInteger . unPrime -> p) k (toInteger -> a) b ->\n discreteLogarithmPP p k a (m `rem` p^k) `stimes` b\n TwoPower k s b -> (if testBit m 1 then s else mempty)\n <> lambda (thingy k m) k `stimes` b\n Two -> mempty\n\nthingy :: (Bits p, Num p) => Int -> p -> p\nthingy k m = if testBit m 1\n then bit k - m'\n else m'\n where m' = m .&. (bit k - 1)\n\n-- | A character can evaluate to a root of unity or zero: represented by @Nothing@.\nevalGeneral :: KnownNat n => DirichletCharacter n -> Mod n -> OrZero RootOfUnity\nevalGeneral chi t = case isMultElement t of\n Nothing -> Zero\n Just x -> NonZero $ eval chi x\n\n-- | Give the principal character for this modulus: a principal character mod \\(n\\) is 1 for\n-- \\(a\\) coprime to \\(n\\), and 0 otherwise.\nprincipalChar :: KnownNat n => DirichletCharacter n\nprincipalChar = minBound\n\nmulChars :: DirichletCharacter n -> DirichletCharacter n -> DirichletCharacter n\nmulChars (Generated x) (Generated y) = Generated (zipWith combine x y)\n where combine :: DirichletFactor -> DirichletFactor -> DirichletFactor\n combine Two Two = Two\n combine (OddPrime p k g n) (OddPrime _ _ _ m) =\n OddPrime p k g (n <> m)\n combine (TwoPower k a n) (TwoPower _ b m) =\n TwoPower k (a <> b) (n <> m)\n combine _ _ = error \"internal error: malformed DirichletCharacter\"\n\n-- | This Semigroup is in fact a group, so @stimes@ can be called with a negative first argument.\ninstance Semigroup (DirichletCharacter n) where\n (<>) = mulChars\n stimes = stimesChar\n\ninstance KnownNat n => Monoid (DirichletCharacter n) where\n mempty = principalChar\n mappend = (<>)\n\nstimesChar :: Integral a => a -> DirichletCharacter n -> DirichletCharacter n\nstimesChar s (Generated xs) = Generated (map mult xs)\n where mult :: DirichletFactor -> DirichletFactor\n mult (OddPrime p k g n) = OddPrime p k g (s `stimes` n)\n mult (TwoPower k a b) = TwoPower k (s `stimes` a) (s `stimes` b)\n mult Two = Two\n\n-- | We define `succ` and `pred` with more efficient implementations than\n-- @`toEnum` . (+1) . `fromEnum`@.\ninstance KnownNat n => Enum (DirichletCharacter n) where\n toEnum = indexToChar . fromIntegral\n fromEnum = fromIntegral . characterNumber\n succ x = makeChar x (characterNumber x + 1)\n pred x = makeChar x (characterNumber x - 1)\n\n enumFromTo x y = bulkMakeChars x [fromEnum x..fromEnum y]\n enumFrom x = bulkMakeChars x [fromEnum x..]\n enumFromThenTo x y z = bulkMakeChars x [fromEnum x, fromEnum y..fromEnum z]\n enumFromThen x y = bulkMakeChars x [fromEnum x, fromEnum y..]\n\ninstance KnownNat n => Bounded (DirichletCharacter n) where\n minBound = indexToChar 0\n maxBound = indexToChar (totient n - 1)\n where n = natVal (Proxy :: Proxy n)\n\n-- | We have a (non-canonical) enumeration of dirichlet characters.\ncharacterNumber :: DirichletCharacter n -> Integer\ncharacterNumber (Generated y) = foldl' go 0 y\n where go x (OddPrime p k _ a) = x * m + numerator (fromRootOfUnity a * fromIntegral m)\n where p' = fromIntegral (unPrime p)\n m = p'^(k-1)*(p'-1)\n go x (TwoPower k a b) = x' * 2 + numerator (fromRootOfUnity a * 2)\n where m = bit (k-2) :: Integer\n x' = x `shiftL` (k-2) + numerator (fromRootOfUnity b * fromIntegral m)\n go x Two = x\n\n-- | Give the dirichlet character from its number.\n-- Inverse of `characterNumber`.\nindexToChar :: forall n. KnownNat n => Natural -> DirichletCharacter n\nindexToChar = runIdentity . indicesToChars . Identity\n\n-- | Give a collection of dirichlet characters from their numbers. This may be more efficient than\n-- `indexToChar` for multiple characters, as it prevents some internal recalculations.\nindicesToChars :: forall n f. (KnownNat n, Functor f) => f Natural -> f (DirichletCharacter n)\nindicesToChars = fmap (Generated . unroll t . (`mod` m))\n where n = natVal (Proxy :: Proxy n)\n (Product m, t) = mkTemplate n\n\n-- | List all characters for the modulus. This is preferred to using @[minBound..maxBound]@.\nallChars :: forall n. KnownNat n => [DirichletCharacter n]\nallChars = indicesToChars [0..m-1]\n where m = totient $ natVal (Proxy :: Proxy n)\n\n-- | The same as `indexToChar`, but if we're given a character we can create others more efficiently.\nmakeChar :: Integral a => DirichletCharacter n -> a -> DirichletCharacter n\nmakeChar x = runIdentity . bulkMakeChars x . Identity\n\n-- | Use one character to make many more: better than indicesToChars since it avoids recalculating\n-- some primitive roots\nbulkMakeChars :: (Integral a, Functor f) => DirichletCharacter n -> f a -> f (DirichletCharacter n)\nbulkMakeChars x = fmap (Generated . unroll t . (`mod` m) . fromIntegral)\n where (Product m, t) = templateFromCharacter x\n\n-- We assign each natural a unique Template, which can be decorated (eg in `unroll`) to\n-- form a DirichletCharacter. A Template effectively holds the information carried around\n-- in a DirichletFactor which depends only on the modulus of the character.\ndata Template = OddTemplate { _getPrime' :: Prime Natural\n , _getPower' :: Word\n , _getGenerator' :: !Natural\n , _getModulus' :: !Natural\n }\n | TwoPTemplate { _getPower2' :: Int\n , _getModulus' :: !Natural\n } -- the modulus is derivable from the other values, but calculation\n -- may be expensive, so we pre-calculate it\n -- morally getModulus should be a prefactored but seems to be\n -- pointless here\n | TwoTemplate\n\ntemplateFromCharacter :: DirichletCharacter n -> (Product Natural, [Template])\ntemplateFromCharacter (Generated t) = traverse go t\n where go (OddPrime p k g _) = (Product m, OddTemplate p k g m)\n where p' = unPrime p\n m = p'^(k-1)*(p'-1)\n go (TwoPower k _ _) = (Product (2*m), TwoPTemplate k m)\n where m = bit (k-2)\n go Two = (Product 1, TwoTemplate)\n\nmkTemplate :: Natural -> (Product Natural, [Template])\nmkTemplate = go . sort . factorise\n where go :: [(Prime Natural, Word)] -> (Product Natural, [Template])\n go ((unPrime -> 2, 1): xs) = (Product 1, [TwoTemplate]) <> traverse odds xs\n go ((unPrime -> 2, wordToInt -> k): xs) = (Product (2*m), [TwoPTemplate k m]) <> traverse odds xs\n where m = bit (k-2)\n go xs = traverse odds xs\n odds :: (Prime Natural, Word) -> (Product Natural, Template)\n odds (p, k) = (Product m, OddTemplate p k (generator p k) m)\n where p' = unPrime p\n m = p'^(k-1)*(p'-1)\n\n-- the validity of the producted dirichletfactor list here requires the template to be valid\nunroll :: [Template] -> Natural -> [DirichletFactor]\nunroll t m = snd (mapAccumL func m t)\n where func :: Natural -> Template -> (Natural, DirichletFactor)\n func a (OddTemplate p k g n) = (a1, OddPrime p k g (toRootOfUnity $ (toInteger a2) % (toInteger n)))\n where (a1,a2) = quotRem a n\n func a (TwoPTemplate k n) = (b1, TwoPower k (toRootOfUnity $ (toInteger a2) % 2) (toRootOfUnity $ (toInteger b2) % (toInteger n)))\n where (a1,a2) = quotRem a 2\n (b1,b2) = quotRem a1 n\n func a TwoTemplate = (a, Two)\n\n-- | Test if a given Dirichlet character is prinicpal for its modulus: a principal character mod\n-- \\(n\\) is 1 for \\(a\\) coprime to \\(n\\), and 0 otherwise.\nisPrincipal :: DirichletCharacter n -> Bool\nisPrincipal chi = characterNumber chi == 0\n\n-- | Induce a Dirichlet character to a higher modulus. If \\(d \\mid n\\), then \\(a \\bmod{n}\\) can be\n-- reduced to \\(a \\bmod{d}\\). Thus, the multiplicative function on \\(\\mathbb{Z}/d\\mathbb{Z}\\)\n-- induces a multiplicative function on \\(\\mathbb{Z}/n\\mathbb{Z}\\).\n--\n-- >>> :set -XTypeApplications\n-- >>> chi = indexToChar 5 :: DirichletCharacter 45\n-- >>> chi2 = induced @135 chi\n-- >>> :t chi2\n-- Maybe (DirichletCharacter 135)\ninduced :: forall n d. (KnownNat d, KnownNat n) => DirichletCharacter d -> Maybe (DirichletCharacter n)\ninduced (Generated start) = if n `rem` d == 0\n then Just (Generated (combine (snd $ mkTemplate n) start))\n else Nothing\n where n = natVal (Proxy :: Proxy n)\n d = natVal (Proxy :: Proxy d)\n combine :: [Template] -> [DirichletFactor] -> [DirichletFactor]\n combine [] _ = []\n combine ts [] = map newFactor ts\n combine (t:xs) (y:ys) = case (t,y) of\n (TwoTemplate, Two) -> Two: combine xs ys\n (TwoTemplate, _) -> Two: combine xs (y:ys)\n (TwoPTemplate k _, Two) -> TwoPower k mempty mempty: combine xs ys\n (TwoPTemplate k _, TwoPower _ a b) -> TwoPower k a b: combine xs ys\n (TwoPTemplate k _, _) -> TwoPower k mempty mempty: combine xs (y:ys)\n (OddTemplate p k _ _, OddPrime q _ g a) | p == q -> OddPrime p k g a: combine xs ys\n (OddTemplate p k g _, OddPrime q _ _ _) | p < q -> OddPrime p k g mempty: combine xs (y:ys)\n _ -> error \"internal error in induced: please report this as a bug\"\n newFactor :: Template -> DirichletFactor\n newFactor TwoTemplate = Two\n newFactor (TwoPTemplate k _) = TwoPower k mempty mempty\n newFactor (OddTemplate p k g _) = OddPrime p k g mempty\n -- rest (p,k) = OddPrime p k (generator p k) mempty\n\n-- | The gives a real Dirichlet\n-- character for odd moduli.\njacobiCharacter :: forall n. KnownNat n => Maybe (RealCharacter n)\njacobiCharacter = if odd n\n then Just $ RealChar $ Generated $ map go $ snd $ mkTemplate n\n else Nothing\n where n = natVal (Proxy :: Proxy n)\n go :: Template -> DirichletFactor\n go (OddTemplate p k g _) = OddPrime p k g $ toRootOfUnity ((toInteger k) % 2)\n -- jacobi symbol of a primitive root mod p over p is always -1\n go _ = error \"internal error in jacobiCharacter: please report this as a bug\"\n -- every factor of n should be odd\n\n-- | A Dirichlet character is real if it is real-valued.\nnewtype RealCharacter n = RealChar { -- | Extract the character itself from a `RealCharacter`.\n getRealChar :: DirichletCharacter n\n }\n deriving Eq\n\n-- | Test if a given `DirichletCharacter` is real, and if so give a `RealCharacter`.\nisRealCharacter :: DirichletCharacter n -> Maybe (RealCharacter n)\nisRealCharacter t@(Generated xs) = if all real xs then Just (RealChar t) else Nothing\n where real :: DirichletFactor -> Bool\n real (OddPrime _ _ _ a) = a <> a == mempty\n real (TwoPower _ _ b) = b <> b == mempty\n real Two = True\n\n-- TODO: it should be possible to calculate this without eval/evalGeneral\n-- and thus avoid using discrete log calculations: consider the order of m\n-- inside each of the factor groups?\n-- | Evaluate a real Dirichlet character, which can only take values \\(-1,0,1\\).\ntoRealFunction :: KnownNat n => RealCharacter n -> Mod n -> Int\ntoRealFunction (RealChar chi) m = case evalGeneral chi m of\n Zero -> 0\n NonZero t | t == mempty -> 1\n NonZero t | t == RootOfUnity (1 % 2) -> -1\n _ -> error \"internal error in toRealFunction: please report this as a bug\"\n -- A real character should not be able to evaluate to\n -- anything other than {-1,0,1}, so should not reach this branch\n\n-- | Test if the internal DirichletCharacter structure is valid.\nvalidChar :: forall n. KnownNat n => DirichletCharacter n -> Bool\nvalidChar (Generated xs) = correctDecomposition && all correctPrimitiveRoot xs && all validValued xs\n where correctDecomposition = sort (factorise n) == map getPP xs\n getPP (TwoPower k _ _) = (two, fromIntegral k)\n getPP (OddPrime p k _ _) = (p, k)\n getPP Two = (two,1)\n correctPrimitiveRoot (OddPrime p k g _) = g == generator p k\n correctPrimitiveRoot _ = True\n validValued (TwoPower k a b) = a <> a == mempty && (bit (k-2) :: Integer) `stimes` b == mempty\n validValued (OddPrime (unPrime -> p) k _ a) = (p^(k-1)*(p-1)) `stimes` a == mempty\n validValued Two = True\n n = natVal (Proxy :: Proxy n)\n two = nextPrime 2\n\n-- | Get the order of the Dirichlet Character.\norderChar :: DirichletCharacter n -> Integer\norderChar (Generated xs) = foldl' lcm 1 $ map orderFactor xs\n where orderFactor (TwoPower _ (RootOfUnity a) (RootOfUnity b)) = denominator a `lcm` denominator b\n orderFactor (OddPrime _ _ _ (RootOfUnity a)) = denominator a\n orderFactor Two = 1\n\n-- | Test if a Dirichlet character is .\nisPrimitive :: DirichletCharacter n -> Maybe (PrimitiveCharacter n)\nisPrimitive t@(Generated xs) = if all primitive xs then Just (PrimitiveCharacter t) else Nothing\n where primitive :: DirichletFactor -> Bool\n primitive Two = False\n -- for odd p, we're testing if phi(p^(k-1)) `stimes` a is 1, since this means the\n -- character can come from some the smaller modulus p^(k-1)\n primitive (OddPrime _ 1 _ a) = a /= mempty\n primitive (OddPrime (unPrime -> p) k _ a) = (p^(k-2)*(p-1)) `stimes` a /= mempty\n primitive (TwoPower 2 a _) = a /= mempty\n primitive (TwoPower k _ b) = (bit (k-3) :: Integer) `stimes` b /= mempty\n\n-- | A Dirichlet character is primitive if cannot be 'induced' from any character with\n-- strictly smaller modulus.\nnewtype PrimitiveCharacter n = PrimitiveCharacter { -- | Extract the character itself from a `PrimitiveCharacter`.\n getPrimitiveChar :: DirichletCharacter n\n }\n deriving Eq\n\ndata WithNat (a :: Nat -> *) where\n WithNat :: KnownNat m => a m -> WithNat a\n\n-- | This function also provides access to the new modulus on type level, with a KnownNat instance\nmakePrimitive :: DirichletCharacter n -> WithNat PrimitiveCharacter\nmakePrimitive (Generated xs) =\n case someNatVal (product mods) of\n SomeNat (Proxy :: Proxy m) -> WithNat (PrimitiveCharacter (Generated ys) :: PrimitiveCharacter m)\n where (mods,ys) = unzip (mapMaybe prim xs)\n prim :: DirichletFactor -> Maybe (Natural, DirichletFactor)\n prim Two = Nothing\n prim (OddPrime p' k g a) = case find works options of\n Nothing -> error \"invalid character\"\n Just (0,_) -> Nothing\n Just (i,_) -> Just (p^i, OddPrime p' i g a)\n where options = (0,1): [(i,p^(i-1)*(p-1)) | i <- [1..k]]\n works (_,phi) = phi `stimes` a == mempty\n p = unPrime p'\n prim (TwoPower k a b) = case find worksb options of\n Nothing -> error \"invalid character\"\n Just (2,_) | a == mempty -> Nothing\n Just (i,_) -> Just (bit i :: Natural, TwoPower i a b)\n where options = [(i, bit (i-2) :: Natural) | i <- [2..k]]\n worksb (_,phi) = phi `stimes` b == mempty\n\n#if !MIN_VERSION_base(4,12,0)\nnewtype Ap f a = Ap { getAp :: f a }\n deriving (Eq, Functor, Applicative, Monad)\n\ninstance (Applicative f, Semigroup a) => Semigroup (Ap f a) where\n (<>) = liftA2 (<>)\n\ninstance (Applicative f, Semigroup a, Monoid a) => Monoid (Ap f a) where\n mempty = pure mempty\n mappend = (<>)\n#endif\n\n-- | Similar to Maybe, but with different Semigroup and Monoid instances.\ntype OrZero a = Ap Maybe a\npattern Zero :: OrZero a\npattern Zero = Ap Nothing\n\npattern NonZero :: a -> OrZero a\npattern NonZero x = Ap (Just x)\n{-# COMPLETE Zero, NonZero #-}\n\n-- | Interpret an `OrZero` as a number, taking the `Zero` case to be 0.\norZeroToNum :: Num a => (b -> a) -> OrZero b -> a\norZeroToNum _ Zero = 0\norZeroToNum f (NonZero x) = f x\n\n-- | In general, evaluating a DirichletCharacter at a point involves solving the discrete logarithm\n-- problem, which can be hard: the implementations here are around O(sqrt n).\n-- However, evaluating a dirichlet character at every point amounts to solving the discrete\n-- logarithm problem at every point also, which can be done together in O(n) time, better than\n-- using a complex algorithm at each point separately. Thus, if a large number of evaluations\n-- of a dirichlet character are required, `evalAll` will be better than `evalGeneral`, since\n-- computations can be shared.\nevalAll :: forall n. KnownNat n => DirichletCharacter n -> Vector (OrZero RootOfUnity)\nevalAll (Generated xs) = V.generate (fromIntegral n) func\n where n = natVal (Proxy :: Proxy n)\n vectors = map mkVector xs\n func :: Int -> OrZero RootOfUnity\n func m = foldMap go vectors\n where go :: (Int, Vector (OrZero RootOfUnity)) -> OrZero RootOfUnity\n go (modulus,v) = v ! (m `mod` modulus)\n mkVector :: DirichletFactor -> (Int, Vector (OrZero RootOfUnity))\n mkVector Two = (2, V.fromList [Zero, mempty])\n mkVector (OddPrime p k (fromIntegral -> g) a) = (modulus, w)\n where\n p' = unPrime p\n modulus = fromIntegral (p'^k) :: Int\n w = V.create $ do\n v <- MV.replicate modulus Zero\n -- TODO: we're in the ST monad here anyway, could be better to use STRefs to manage\n -- this loop, the current implementation probably doesn't fuse well\n let powers = iterateMaybe go (1,mempty)\n go (m,x) = if m' > 1\n then Just (m', x<>a)\n else Nothing\n where m' = m*g `mod` modulus\n for_ powers $ \\(m,x) -> MV.unsafeWrite v m (NonZero x)\n -- don't bother with bounds check since m was reduced mod p^k\n return v\n -- for powers of two we use lambda directly instead, since the generators of the cyclic\n -- groups aren't obvious; it's possible to get them though:\n -- 5^(lambda(5)^{-1} mod 2^(p-2)) mod 2^p\n mkVector (TwoPower k a b) = (modulus, w)\n where\n modulus = bit k\n w = V.generate modulus f\n f m\n | even m = Zero\n | otherwise = NonZero ((if testBit m 1 then a else mempty) <> lambda (toInteger m'') k `stimes` b)\n where m'' = thingy k m\n\n-- somewhere between unfoldr and iterate\niterateMaybe :: (a -> Maybe a) -> a -> [a]\niterateMaybe f x = unfoldr (fmap (\\t -> (t, f t))) (Just x)\n\n-- | Attempt to construct a character from its table of values.\n-- An inverse to `evalAll`, defined only on its image.\nfromTable :: forall n. KnownNat n => Vector (OrZero RootOfUnity) -> Maybe (DirichletCharacter n)\nfromTable v = if length v == fromIntegral n\n then Generated <$> traverse makeFactor tmpl >>= check\n else Nothing\n where n = natVal (Proxy :: Proxy n)\n n' = fromIntegral n :: Integer\n tmpl = snd (mkTemplate n)\n check :: DirichletCharacter n -> Maybe (DirichletCharacter n)\n check chi = if evalAll chi == v then Just chi else Nothing\n makeFactor :: Template -> Maybe DirichletFactor\n makeFactor TwoTemplate = Just Two\n makeFactor (TwoPTemplate k _) = TwoPower k <$> getValue (-1,bit k) <*> getValue (exp4 k, bit k)\n makeFactor (OddTemplate p k g _) = OddPrime p k g <$> getValue (toInteger g, toInteger (unPrime p)^k)\n getValue :: (Integer,Integer) -> Maybe RootOfUnity\n getValue (g,m) = getAp (v ! fromInteger (fromJust (chineseCoprime (g,m) (1,n' `quot` m)) `mod` n'))\n\nexp4terms :: [Rational]\nexp4terms = [4^k % product [1..k] | k <- [0..]]\n\n-- For reasons that aren't clear to me, `exp4` gives the inverse of 1 under lambda, so it gives the generator\n-- This is the same as https://oeis.org/A320814\n-- In particular, lambda (exp4 n) n == 1 (for n >= 3)\n-- I've verified this for 3 <= n <= 2000, so the reasoning in fromTable should be accurate for moduli below 2^2000\nexp4 :: Int -> Integer\nexp4 n = (`mod` bit n) $ sum $ map (`mod` bit n) $ map (\\q -> numerator q * fromMaybe (error \"error in exp4\") (recipMod (denominator q) (bit n))) $ take n $ exp4terms\n", "meta": {"hexsha": "f4896ef72db6f2dd15441f9f756e750ea059c1d7", "size": 30596, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/NumberTheory/DirichletCharacters.hs", "max_stars_repo_name": "b-mehta/arithmoi", "max_stars_repo_head_hexsha": "54a4448a577bd2782e6ed786dae0966e6c9b8f99", "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": "Math/NumberTheory/DirichletCharacters.hs", "max_issues_repo_name": "b-mehta/arithmoi", "max_issues_repo_head_hexsha": "54a4448a577bd2782e6ed786dae0966e6c9b8f99", "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": "Math/NumberTheory/DirichletCharacters.hs", "max_forks_repo_name": "b-mehta/arithmoi", "max_forks_repo_head_hexsha": "54a4448a577bd2782e6ed786dae0966e6c9b8f99", "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": 49.7495934959, "max_line_length": 166, "alphanum_fraction": 0.6047849392, "num_tokens": 8141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.589955469587542}} {"text": "import Debug.Trace\n-- import Control.Monad.State.Lazy\n\nimport System.Environment (getArgs)\nimport System.IO (readFile)\nimport qualified Data.Set as S\nimport qualified Data.Map.Strict as M\nimport Data.Set (Set)\nimport Data.Map.Strict (Map)\nimport Data.Tuple (swap)\nimport Data.Complex (Complex((:+)), polar)\n\nimport Data.List (sort, nub)\n\n\nreadMap :: [[Char]] -> [(Int, Int)]\nreadMap rows = [(x, y) | (y, row) <- zip [0 ..] rows\n , (x, c) <- zip [0 ..] row\n , c == '#']\n\nanalyzeMap :: [(Int, Int)] -> (Int, (Int, Int))\nanalyzeMap points = maximum [(length $ nub angles, p)\n | p <- points\n , let angles = map (fst . polarDirection p) points]\n \npolarDirection :: (Int, Int) -> (Int, Int) -> (Float, Float)\npolarDirection origin@(x0,y0) pt@(x1,y1) = -- (angle_from_vertical, distance)\n swap -- angle first\n $ positiveAngle -- polar's angle is from -pi to pi, convert to 0 to 2pi so that we can sort by angle\n $ polar -- convert to (magnitude, phase)\n $ fromIntegral (-1 * y) :+ fromIntegral x -- make complex, normally\n -- the positive x axis is phase 0, but here we want to go\n -- clockwise from vertical, so swap x and y and change y's\n -- sign to correct for the fact that the coordinates\n -- increase in the down direction.\n where (x, y) = (x1-x0,y1-y0) -- point from perspective of origin\n positiveAngle (m,p) | p < 0 = (m, 2 * pi + p)\n | otherwise = (m, p)\n\nmain = do\n [mapFile] <- getArgs\n m <- readFile mapFile\n let points = readMap $ lines m\n let (reachable, station) = analyzeMap points\n putStrLn $ \"Part 1: \" ++ show (reachable, station)\n let polarPoints = -- traceShowId $ \n sort -- [(round, angle, xy)] in order\n $ foldl (\\l ((angle, distance), xy) ->\n (if null l then 0\n else let (round0, angle0, pt0) = head l\n in if angle == angle0 then round0 + 1\n else 0,\n angle, xy):l) ([]::[(Int, Float, Int)])\n -- $ traceShowId\n $ sort -- [((angle, distance), xy)] in order\n $ map (\\(x,y) -> (polarDirection station (x,y),100*x+y))\n $ filter (/= station) points\n \n putStrLn $ \"Part 2: \" ++ show (polarPoints!!199)\n --putStrLn $ \"Part 2: \" ++ (show $ head $ drop 199 polarPoints)\n \n\n\n\n", "meta": {"hexsha": "a6e8df8176b43a3012a545c14ca2a6ca48f9df37", "size": 2475, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "10.hs", "max_stars_repo_name": "dpatru/aoc2019", "max_stars_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-30T21:19:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T21:19:29.000Z", "max_issues_repo_path": "10.hs", "max_issues_repo_name": "dpatru/aoc2019", "max_issues_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "10.hs", "max_forks_repo_name": "dpatru/aoc2019", "max_forks_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0769230769, "max_line_length": 102, "alphanum_fraction": 0.5418181818, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5899429972742716}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE OverloadedLists #-}\n{-# LANGUAGE CPP #-}\n\n\nmodule Main where\n\n\n\nimport qualified Data.Vector.Unboxed as U\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector as V\n\n-- DLA\nimport qualified Statistics.Matrix as M\nimport qualified Statistics.Matrix.Fast as MF\nimport qualified Statistics.Matrix.Fast.Algorithms as A\n\n-- hmatrix\nimport qualified Numeric.LinearAlgebra as H\n\n-- numhask\nimport qualified NumHask.Array as NH\nimport qualified NumHask.Prelude as NP\n\n-- data.matrix from matrix\nimport qualified Data.Matrix as DMX\n\n-- massiv\nimport qualified Data.Massiv.Array as MA\n\nimport qualified System.Random.MWC as Mwc\n\nimport qualified Criterion.Main as C\n\n#define N 10\n#define N2 100\n\nn :: Int\nn = N\n\nvectorGen :: IO (Vector Double)\nvectorGen = do \n gen <- Mwc.create\n Mwc.uniformVector gen (n*n)\n\nmatrixDLA :: IO M.Matrix\nmatrixDLA = do\n vec <- vectorGen\n return $ M.Matrix n n vec\n\nmatrixH :: IO (H.Matrix H.R)\nmatrixH = do\n vec <- vectorGen\n return $ (n H.>< n) $ U.toList $ vec \n\nidentH :: Int -> H.Matrix Double\nidentH = H.ident\n\nidentDMX :: Int -> DMX.Matrix Double\nidentDMX = DMX.identity\n\nelemZero :: Double -> Double\nelemZero = const 0\n\nelemSqr :: Double -> Double\nelemSqr x = x*x\n\nmapH :: (Double -> Double) -> H.Matrix Double -> H.Matrix Double\nmapH = H.cmap\n\nmain :: IO ()\nmain = do \n\n vDLA' <- vectorGen\n uDLA' <- vectorGen\n\n let \n\n --\n subDLA' = U.take n vDLA'\n aDLA' = M.Matrix n n vDLA'\n bDLA' = M.Matrix n n uDLA'\n \n --\n vList = U.toList vDLA'\n uList = U.toList uDLA'\n \n --\n aH' = (n H.>< n) vList\n bH' = (n H.>< n) uList\n\n subH' = H.fromList . take n $ vList\n vH' = H.fromList vList\n\n --\n aNH' = NP.fromList vList :: NH.Array V.Vector '[N, N] Double\n bNH' = NP.fromList uList :: NH.Array V.Vector '[N, N] Double\n\n vNH' = NP.fromList vList :: NH.Array V.Vector '[N2] Double\n\n --\n aDMX' = DMX.fromList n n vList\n bDMX' = DMX.fromList n n uList\n\n --\n vMA' = MA.fromList MA.Seq vList :: MA.Array MA.P MA.Ix1 Double\n aMA' = MA.resize' (MA.Sz (n MA.:. n)) vMA' :: MA.Array MA.P MA.Ix2 Double\n bMA' = MA.resize' (MA.Sz (n MA.:. n)) $ MA.fromList MA.Seq uList :: MA.Array MA.P MA.Ix2 Double\n\n C.defaultMain [ \n C.env (pure (aDLA', bDLA', subDLA', vDLA')) $ \\ ~(aDLA, bDLA, subDLA, vDLA) ->\n C.bgroup \"DLA\" [ \n C.bench \"multiplication\" $ C.nf (MF.multiply aDLA) bDLA,\n C.bench \"repeated multiplication\" $ C.nf (U.sum . (flip M.row) 1 . MF.multiply bDLA . MF.multiply aDLA . MF.multiply aDLA ) bDLA,\n C.bench \"multiplicationV\" $ C.nf (MF.multiplyV aDLA) subDLA,\n C.bench \"qr factorization\" $ C.nf A.qr aDLA,\n C.bench \"transpose\" $ C.nf MF.transpose aDLA,\n C.bench \"norm\" $ C.nf MF.norm vDLA,\n C.bench \"row\" $ C.nf (M.row aDLA) 0,\n C.bench \"column\" $ C.nf (M.column aDLA) 0,\n C.bench \"identity\" $ C.nf M.ident n, \n C.bench \"diag\" $ C.nf M.diag subDLA, \n C.bench \"map const 0\" $ C.nf (M.map elemZero) aDLA,\n C.bench \"map sqr\" $ C.nf (M.map elemSqr) aDLA\n ],\n\n C.env (pure (aH', bH', subH', vH')) $ \\ ~(aH, bH, subH, vH) ->\n C.bgroup \"Hmatrix\" [ \n C.bench \"multiplication\" $ C.nf ((<>) aH) bH,\n C.bench \"repeated multiplication\" $ C.nf ( H.sumElements . flip (H.?) [1] . (<>) bH . (<>) aH . (<>) aH) bH,\n C.bench \"multiplicationV\" $ C.nf ((H.#>) aH) subH,\n C.bench \"qr factorization\" $ C.nf H.qr aH,\n C.bench \"transpose\" $ C.nf H.tr aH,\n C.bench \"norm\" $ C.nf H.norm_2 vH,\n C.bench \"row\" $ C.nf ((H.?) aH) [0],\n C.bench \"column\" $ C.nf ((H.\u00bf) aH) [0], \n C.bench \"identity\" $ C.nf identH n,\n C.bench \"diag\" $ C.nf H.diag subH,\n C.bench \"map const 0\" $ C.nf (mapH elemZero) aH,\n C.bench \"map sqr\" $ C.nf (mapH elemSqr) aH\n ],\n\n C.env (pure (aNH', bNH', vNH')) $ \\ ~(aNH, bNH, vNH) ->\n C.bgroup \"NumHask\" [ \n C.bench \"multiplication\" $ C.nf (NH.mmult aNH) bNH,\n C.bench \"repeated multiplication\" $ C.nf ( (\\(NH.Array a) -> V.sum a) . NH.row (NP.Proxy :: NP.Proxy 1) . NH.mmult bNH . NH.mmult aNH . NH.mmult aNH ) bNH,\n C.bench \"transpose\" $ C.nf NH.transpose aNH,\n C.bench \"norm\" $ C.nf (sqrt . (NP.<.> vNH)) vNH,\n C.bench \"row\" $ C.nf (NH.row (NP.Proxy :: NP.Proxy 0)) aNH,\n C.bench \"column\" $ C.nf (NH.col (NP.Proxy :: NP.Proxy 0)) aNH\n ],\n\n C.env (pure (aMA', bMA', vMA')) $ \\ ~(aMA, bMA, vMA) ->\n C.bgroup \"Massiv\" [\n C.bench \"multiplication\" $ C.nf ((MA.|*|) aMA) bMA,\n C.bench \"multiplication (Par)\" $ C.nf ((MA.|*|) (MA.setComp MA.Par aMA)) bMA,\n C.bench \"repeated multiplication\" $ C.nf ( MA.foldlS (+) 0 . flip (MA.!>) 1 . (MA.|*|) bMA . (MA.|*|) aMA . (MA.|*|) aMA) bMA,\n C.bench \"repeated multiplication (Par)\" $ C.nf ( MA.foldlS (+) 0 . flip (MA.!>) 1 . (MA.|*|) bMA . (MA.|*|) aMA . (MA.|*|) (MA.setComp MA.Par aMA)) bMA,\n C.bench \"norm\" $ C.nf (sqrt . MA.foldlS (+) 0 . (MA.zipWith (*) vMA)) vMA,\n C.bench \"transpose\" $ C.nf (MA.computeAs MA.P . MA.transpose) aMA,\n C.bench \"row\" $ C.nf (MA.computeAs MA.P . (MA.!>) aMA) 0,\n C.bench \"column\" $ C.nf (MA.computeAs MA.P . (MA.\n C.bgroup \"Matrix\" [ \n C.bench \"multiplication\" $ C.nf (DMX.multStrassenMixed aDMX) bDMX,\n C.bench \"transpose\" $ C.nf DMX.transpose aDMX,\n C.bench \"row\" $ C.nf (DMX.getRow 1) aDMX,\n C.bench \"column\" $ C.nf (DMX.getCol 1) aDMX,\n C.bench \"identity\" $ C.nf identDMX n\n ]\n ]\n", "meta": {"hexsha": "cfc9313e79bfc317f26b63b09050ad9f86399f63", "size": 6806, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/Runtime.hs", "max_stars_repo_name": "ocramz/fastest-matrices", "max_stars_repo_head_hexsha": "c5b07d2bbf824b92e39a1f3b9a672f54b9f8a92e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-05-25T07:46:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-04T14:22:31.000Z", "max_issues_repo_path": "bench/Runtime.hs", "max_issues_repo_name": "ocramz/fastest-matrices", "max_issues_repo_head_hexsha": "c5b07d2bbf824b92e39a1f3b9a672f54b9f8a92e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-05-25T15:57:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-29T22:48:13.000Z", "max_forks_repo_path": "bench/Runtime.hs", "max_forks_repo_name": "ocramz/fastest-matrices", "max_forks_repo_head_hexsha": "c5b07d2bbf824b92e39a1f3b9a672f54b9f8a92e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-05-25T07:49:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:41:44.000Z", "avg_line_length": 38.8914285714, "max_line_length": 186, "alphanum_fraction": 0.4754628269, "num_tokens": 2060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5898398495731333}} {"text": "{-# LANGUAGE TypeFamilies #-}\n\nimport Test.HUnit\nimport Test.Framework\nimport Test.Framework.Providers.HUnit\n\nimport Numeric.LinearAlgebra.HMatrix\nimport Numeric.Minimization.QuadProgPP\n\nimport Numeric.AD\n\nimport Data.SQP\n\nqpTest :: Assertion\nqpTest =\n -- From example here:\n -- http://www.mathworks.com/help/optim/ug/quadprog.html#zmw57dd0e69051\n let a = matrix 2 [1, (-1), (-1), 2]\n b = vector [(-2), (-6)]\n e = matrix 2 [ (-1), (-1)\n , 1, (-2)\n , (-2), (-1)\n , 1, 0\n , 0, 1 ]\n f = vector [2, 2, 3, 0, 0]\n result = solveQuadProg (a, b) Nothing $ Just (e, f)\n in result @?= Right (vector [0.6666666666666669,\n 1.3333333333333335],\n -8.22222222222222)\n\n-- sqpTest :: Assertion\n-- sqpTest =\n-- let a = matrix 2 [1, (-1), (-1), 2]\n-- b = vector [(-2), (-6)]\n-- e = matrix 2 [ (1), (1)\n-- , (-1), (2)\n-- , (2), (1)\n-- , (-1), 0\n-- , 0, (-1) ]\n-- f = vector [(-2), (-2), (-3), 0, 0]\n-- affineIneqs x = (e, f)\n-- ineqs x = (e #> x) + f\n-- cost x = (x `dot` ((0.5 * (a #> x)) + b)) + 0.0\n-- problem = Problem\n-- { _cost = cost\n-- , _approxCost = const (a, b, 0)\n-- , _trueIneqs = ineqs\n-- , _approxAffineIneqs = affineIneqs\n-- , _numVariables = 2\n-- , _numIneqs = 5\n-- }\n-- (xResult, fResult) = optimize problem (vector [0, 0])\n-- (xTrue, fTrue) = (vector [0.6666666666666669,\n-- 1.3333333333333335],\n-- -8.22222222222222)\n-- xError = norm_2 $ xTrue - xResult\n-- fError = abs $ fTrue - fResult\n-- in (xError < 1e-8, fError < 1e-8) @?= (True, True)\n\ngetQuadraticApproximation :: ([Double] -> Double)\n -> ([Double] -> [Double])\n -> ([Double] -> [[Double]])\n -> Vector Double\n -> (Matrix Double, Vector Double, Double)\ngetQuadraticApproximation fL fL' fL'' x =\n let xL = toList x\n f' = fromList $ fL' xL\n f'' = makeSymmetric $ fromLists $ fL'' xL\n c = fL xL - (x `dot` f') + 0.5 * (x `dot` (f'' #> x))\n in ( f'', f' - (f'' #> x), c)\n\ngetLinearApproximation :: ([Double] -> [Double])\n -> ([Double] -> [[Double]])\n -> Vector Double\n -> (Matrix Double, Vector Double)\ngetLinearApproximation fL fL' x =\n let xL = toList x\n f' = fromLists $ fL' xL\n in (f', vector (fL xL) - (f' #> x))\n\n-- rosenbrockTest :: Assertion\n-- rosenbrockTest =\n-- -- From: http://www.mathworks.com/help/optim/ug/constrained-nonlinear-optimization-algorithms.html#f26633\n-- let f [x, y] = (1 - x)^(2 :: Int) + 100*(y - x^(2 :: Int))^(2 :: Int)\n-- cost x = let xL = toList x in f xL\n-- convexCost = getQuadraticApproximation f\n-- g [x, y] = x^(2 :: Int) + y^(2 :: Int) - 1.5\n-- ineqs x = let xL = toList x in vector [g xL]\n-- convexIneqs = getLinearApproximation f\n-- problem = Problem\n-- { _cost = cost\n-- , _approxCost = convexCost\n-- , _trueIneqs = ineqs\n-- , _approxAffineIneqs = convexIneqs\n-- , _numVariables = 2\n-- , _numIneqs = 1\n-- }\n-- (xResult, fResult) = optimize problem (vector [(-1.9), 2.0])\n-- (xTrue, fTrue) = (vector [0.9072, 0.8228],\n-- 0.00861632761)\n-- xError = norm_2 $ xTrue - xResult\n-- fError = abs $ fTrue - fResult\n-- in (xError < 1e-4, fError < 1e-4) @?= (True, True)\n\nmakeSymmetric :: Matrix Double -> Matrix Double\nmakeSymmetric m =\n let upperTriIxs = concat\n [ [(r, c) | c <- [(r + 1)..(cols m - 1)]] | r <- [0..(rows m - 1)] ]\n symElems (r, c) = [ ((r, c), m ! r ! c)\n , ((c, r), m ! r ! c) ]\n in (diag . takeDiag) m + assoc (size m) 0.0 (concatMap symElems upperTriIxs)\n\n-- From: http://www.mathworks.com/help/optim/ug/nonlinear-equality-and-inequality-constraints.html\nnonlinearEqTest :: Assertion\nnonlinearEqTest =\n let f [x, y] = exp(x) * (4*x*x + 2*y*y + 4*x*y + 2*y + 1)\n g [x, y] = [negate (x * y) - 10]\n h [x, y] = [(x * x) + y - 1]\n\n cost = f . toList\n approxCost = getQuadraticApproximation f (grad f) (hessian f)\n ineq = vector . g . toList\n approxIneq = getLinearApproximation g (jacobian g)\n eq = vector . h . toList\n approxEq = getLinearApproximation h (jacobian h)\n problem = Problem\n { _cost = cost\n , _approxCost = approxCost\n , _trueIneqs = ineq\n , _approxAffineIneqs = approxIneq\n , _eqs = eq\n , _approxEqs = approxEq\n , _numVariables = 2\n , _numIneqs = 1\n , _numEqs = 1\n }\n (xResult, fResult) = optimize problem $ vector [(-1.0), 1.0]\n (xTrue, fTrue) = (vector [(-0.7529), 0.4332], 1.5093)\n in (xResult, fResult) @?= (xTrue, fTrue)\n\nmain = defaultMain tests\n where tests = [ -- testCase \"qp-test\" qpTest\n -- , testCase \"sqp-test\" sqpTest\n -- , testCase \"rosenbrock-test\" rosenbrockTest\n testCase \"nonlineareq-test\" nonlinearEqTest\n ]\n", "meta": {"hexsha": "d820c15da0f130261bada0dcd0d0817193f6a1a9", "size": 5514, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app-src/test/QP.hs", "max_stars_repo_name": "giogadi/hs-trajopt", "max_stars_repo_head_hexsha": "3860780bb3d4d8b91f87c2c7d28e80388b66062b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app-src/test/QP.hs", "max_issues_repo_name": "giogadi/hs-trajopt", "max_issues_repo_head_hexsha": "3860780bb3d4d8b91f87c2c7d28e80388b66062b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app-src/test/QP.hs", "max_forks_repo_name": "giogadi/hs-trajopt", "max_forks_repo_head_hexsha": "3860780bb3d4d8b91f87c2c7d28e80388b66062b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5102040816, "max_line_length": 110, "alphanum_fraction": 0.4756982227, "num_tokens": 1794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5896858965367848}} {"text": "module RotationPath where\n\nimport Control.Monad.Writer (Writer)\nimport qualified Control.Monad.Writer as Writer\nimport Data.DList (DList)\nimport qualified Data.DList as DList\nimport Numeric.LinearAlgebra ((<>))\n\nimport Cube (Cube)\nimport qualified Cube as Cube\nimport Rotation (MatrixRotation)\nimport qualified Rotation as Rotation\n\ntype RotationPath a = Writer (DList MatrixRotation) a\ntype CubeMutation = Cube -> RotationPath Cube\n\nrotate :: MatrixRotation -> CubeMutation\nrotate rotation cube = do\n let cube' = Rotation.toCubeRotation (Rotation.toVectorRotation rotation) cube\n Writer.tell $ DList.singleton rotation\n return cube'\n\nbetween :: MatrixRotation -> MatrixRotation -> CubeMutation -> CubeMutation\nbetween prefix suffix \u03bb cube = do\n let (cube', rotationLog) = Writer.runWriter . \u03bb $ Rotation.rotate prefix cube\n Writer.tell $ DList.map (\\r -> suffix <> r <> prefix) rotationLog\n return $ Rotation.rotate suffix cube'\n\nrotations :: [MatrixRotation] -> CubeMutation\nrotations [] cube = return cube\nrotations (r:rs) cube = rotate r cube >>= rotations rs\n", "meta": {"hexsha": "2b266deef66573869ec0167e7b81eb8fad203a32", "size": 1070, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "RotationPath.hs", "max_stars_repo_name": "runjak/hRubiks", "max_stars_repo_head_hexsha": "28798a2a07871c81843490ed95eb5377921c1be5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RotationPath.hs", "max_issues_repo_name": "runjak/hRubiks", "max_issues_repo_head_hexsha": "28798a2a07871c81843490ed95eb5377921c1be5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RotationPath.hs", "max_forks_repo_name": "runjak/hRubiks", "max_forks_repo_head_hexsha": "28798a2a07871c81843490ed95eb5377921c1be5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4375, "max_line_length": 79, "alphanum_fraction": 0.7672897196, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5893085417220668}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\nmodule Nudge (\n nudgeProp\n , nudgeProp2\n ) where\n\nimport Control.Monad\nimport Data.Bifunctor\nimport Data.Finite\nimport Data.Kind\nimport Data.Maybe\nimport Data.Proxy\nimport GHC.TypeLits\nimport Hedgehog\nimport Lens.Micro\nimport Lens.Micro.Platform ()\nimport Numeric.Backprop\nimport qualified Data.Ix as Ix\nimport qualified Data.Vector.Sized as SV\nimport qualified Hedgehog.Gen as Gen\nimport qualified Hedgehog.Range as Range\nimport qualified Numeric.LinearAlgebra as HU\nimport qualified Numeric.LinearAlgebra.Static as H\nimport qualified Numeric.LinearAlgebra.Static.Backprop as B\n\nnudge :: Double\nnudge = 1e-6\n\neps :: Double\neps = 1e-11\n\nclass (Backprop c, Show c, Show (TIx c)) => Testing c where\n type TIx c :: Type\n allIx :: c -> [TIx c]\n ixLens :: TIx c -> Lens' c Double\n scalarize :: Reifies s W => BVar s c -> BVar s Double\n genTest :: Gen c\n\nsized\n :: forall s t d. H.Sized t s d\n => Lens' s (d t)\nsized f = fmap (fromJust . H.create) . f . H.extract\n\nixContainer\n :: forall t d. HU.Container d t\n => HU.IndexOf d\n -> Lens' (d t) t\nixContainer i = lens (`HU.atIndex` i)\n (\\xs x -> HU.accum xs (\\_ _ -> x) [(i, x)])\n\ninstance Testing Double where\n type TIx Double = ()\n allIx _ = [()]\n ixLens _ = id\n scalarize = abs\n genTest = Gen.filter ((> eps) . (**2)) $\n Gen.double (Range.linearFracFrom 0 (-5) 5)\n\ninstance KnownNat n => Testing (H.R n) where\n type TIx (H.R n) = Int\n allIx v = [0 .. H.size v - 1]\n ixLens i = sized . ixContainer i\n scalarize = B.norm_2V\n genTest = H.vector <$> replicateM n genTest\n where\n n = fromInteger $ natVal (Proxy @n)\n\ninstance (KnownNat n, KnownNat m) => Testing (H.L n m) where\n type TIx (H.L n m) = (Int, Int)\n allIx m = Ix.range ((0,0), bimap pred pred (H.size m))\n ixLens i = sized . ixContainer i\n scalarize = sqrt . B.sumElements . (**2)\n genTest = H.matrix <$> replicateM nm genTest\n where\n nm = fromInteger $ natVal (Proxy @n) * natVal (Proxy @m)\n\ninstance Testing (HU.Vector Double) where\n type TIx (HU.Vector Double) = Int\n allIx v = [0 .. HU.size v - 1]\n ixLens = ixContainer\n scalarize = liftOp1 . op1 $ \\xs -> (HU.sumElements xs, (`HU.konst` HU.size xs))\n genTest = HU.fromList <$> replicateM 3 genTest\n\ninstance Testing (HU.Matrix Double) where\n type TIx (HU.Matrix Double) = (Int, Int)\n allIx m = Ix.range ((0,0), bimap pred pred (HU.size m))\n ixLens = ixContainer\n scalarize = liftOp1 . op1 $ \\xs -> (HU.sumElements xs, (`HU.konst` HU.size xs))\n genTest = HU.fromLists <$> (replicateM 3 . replicateM 2) genTest\n\ninstance (KnownNat n, Testing a, Num a) => Testing (SV.Vector n a) where\n type TIx (SV.Vector n a) = (Finite n, TIx a)\n allIx = fst . SV.imapM (\\i x -> ((fromIntegral i,) <$> allIx x , x))\n ixLens (i,j) = SV.ix i . ixLens j\n scalarize = scalarize . liftOp1 o . (^ (2 :: Int))\n where\n o :: Op '[SV.Vector n a] a\n o = op1 $ \\xs -> (SV.sum xs, SV.replicate)\n genTest = SV.replicateM genTest\n\ninstance (Testing a, Testing b) => Testing (a, b) where\n type TIx (a, b) = Either (TIx a) (TIx b)\n allIx (x, y) = (Left <$> allIx x)\n ++ (Right <$> allIx y)\n ixLens (Left i) = _1 . ixLens i\n ixLens (Right j) = _2 . ixLens j\n scalarize t = B.norm_2V (B.vec2 (scalarize (t ^^. _1))\n (scalarize (t ^^. _2))\n )\n genTest = (,) <$> genTest <*> genTest\n\ninstance (Testing a, Testing b, Testing c) => Testing (a, b, c) where\n type TIx (a, b, c) = Either (TIx a) (Either (TIx b) (TIx c))\n allIx (x, y, z) = (Left <$> allIx x)\n ++ (Right . Left <$> allIx y)\n ++ (Right . Right <$> allIx z)\n ixLens (Left i ) = _1 . ixLens i\n ixLens (Right (Left j)) = _2 . ixLens j\n ixLens (Right (Right k)) = _3 . ixLens k\n scalarize t = B.norm_2V (B.vec3 (scalarize (t ^^. _1))\n (scalarize (t ^^. _2))\n (scalarize (t ^^. _3))\n )\n genTest = (,,) <$> genTest <*> genTest <*> genTest\n\nvalidGrad\n :: Monad m\n => Lens' c Double\n -> c\n -> c\n -> (c -> Double)\n -> PropertyT m (Double, Double)\nvalidGrad l x0 g f = forAll $ Gen.double (Range.constantFrom 0 (-nudge) nudge) <&> \\d ->\n let x = x0 & l %~ (+d)\n old = f x0 + (g ^. l) * d\n new = f x\n in (old, new)\n\nnudgeProp\n :: forall c d. (Testing c, Testing d)\n => (forall s. Reifies s W => BVar s c -> BVar s d)\n -> Property\nnudgeProp f = property $ do\n (inp, i) <- forAll $ do\n inp <- genTest\n i <- Gen.element (allIx inp)\n return (inp, i)\n let (r,gr) = backprop (scalarize . f) inp\n when (r**2 < eps) discard\n (old, new) <- validGrad (ixLens i) inp gr (evalBP (scalarize . f))\n footnoteShow (r, gr, old, new, (old - new)**2, ((old - new)/old)**2)\n assert $ ((old - new)/old)**2 < eps\n\nnudgeProp2\n :: forall c d e. (Testing c, Testing d, Testing e)\n => (forall s. Reifies s W => BVar s c -> BVar s d -> BVar s e)\n -> Property\nnudgeProp2 f = property $ do\n (inpC, inpD, i) <- forAll $ do\n inpC <- genTest\n inpD <- genTest\n i <- Gen.element (allIx (inpC, inpD))\n return (inpC, inpD, i)\n let (r, gr) = backprop2 (\\x -> scalarize . f x) inpC inpD\n when (r**2 < eps) discard\n (old, new) <- validGrad (ixLens i) (inpC, inpD) gr\n (evalBP (\\t -> scalarize $ f (t ^^. _1) (t ^^. _2)))\n footnoteShow (r, gr, old, new, (old - new)**2, ((old - new)/old)**2)\n assert $ ((old - new)/old)**2 < eps\n\ninstance (HU.Container HU.Vector a, Num a) => Backprop (HU.Matrix a) where\n -- TODO: make more efficient?\n zero = HU.cmap (const 0)\n add = HU.add\n one = HU.cmap (const 1)\n\ninstance (KnownNat n, Num a) => Backprop (SV.Vector n a) where\n zero = (0 <$)\n add = (+)\n one = (1 <$)\n", "meta": {"hexsha": "1039bf9d65bb446c2f725c3c716ac5cd0f2e6bd9", "size": 6650, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Nudge.hs", "max_stars_repo_name": "mstksg/hmatrix-backprop", "max_stars_repo_head_hexsha": "91661e0f02012146aa7be323d05c27921fb16c72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-02-06T06:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T07:55:31.000Z", "max_issues_repo_path": "test/Nudge.hs", "max_issues_repo_name": "mstksg/hmatrix-backprop", "max_issues_repo_head_hexsha": "91661e0f02012146aa7be323d05c27921fb16c72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-29T14:21:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-09T22:54:47.000Z", "max_forks_repo_path": "test/Nudge.hs", "max_forks_repo_name": "mstksg/hmatrix-backprop", "max_forks_repo_head_hexsha": "91661e0f02012146aa7be323d05c27921fb16c72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-03T20:57:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T16:47:46.000Z", "avg_line_length": 34.6354166667, "max_line_length": 88, "alphanum_fraction": 0.5427067669, "num_tokens": 2073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5891477788518695}} {"text": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Criterion.Main\nimport Data.Massiv.Array as A\n--import Data.Massiv.Array.SIMD\n--import Data.Massiv.Array.Manifest.Vector as A\nimport Data.Massiv.Array.Unsafe as A\nimport Data.Massiv.Bench as A\nimport Prelude as P hiding ((<>))\nimport Data.Semigroup\n\n--import Statistics.Matrix as S\n--import Statistics.Matrix.Fast as SF\n\n\nmultArrsAlt :: Array U Ix2 Double -> Array U Ix2 Double -> Array U Ix2 Double\nmultArrsAlt arr1 arr2\n | n1 /= m2 =\n error $\n \"(|*|): Inner array dimensions must agree, but received: \" ++\n show (size arr1) ++ \" and \" ++ show (size arr2)\n | otherwise = compute $\n makeArrayR D (getComp arr1 <> getComp arr2) (Sz (m1 :. n2)) $ \\(i :. j) ->\n A.foldlS (+) 0 (A.zipWith (*) (unsafeOuterSlice arr1 i) (unsafeOuterSlice arr2' j))\n where\n Sz2 m1 n1 = size arr1\n Sz2 m2 n2 = size arr2\n arr2' = computeAs U $ A.transpose arr2\n{-# INLINE multArrsAlt #-}\n\n\nmain :: IO ()\nmain = do\n let !sz@(Sz2 _m _n) = Sz2 600 600\n !arr = arrRLightIx2 U Seq sz\n -- !arr2 = computeAs U arr\n -- !mat = S.Matrix m n $ A.toVector arr\n -- !mat' = S.transpose mat\n -- !arrV = arrRLightIx2 V Seq sz\n -- !arrV2 = computeAs V arrV\n defaultMain\n [ env (return (computeAs U (A.transpose arr))) $ \\ arr' ->\n bgroup\n \"Mult\"\n [ bgroup\n \"Seq\"\n [ bench \"(|*|)\" $ whnfIO (setComp Seq arr |*| arr')\n -- , bench \"multiplyTranspose\" $\n -- whnf (computeAs U . multiplyTransposed (setComp Seq arr)) arr2\n -- , bench \"multiplyTransposeSIMD\" $\n -- whnf (computeAs P . multiplyTransposedSIMD arrV) arrV2\n , bench \"multArrsAlt\" $ whnf (multArrsAlt (setComp Seq arr)) arr'\n --, bench \"multiply (dense-linear-algebra)\" $ whnf (SF.multiply mat) mat'\n ]\n , bgroup\n \"Par\"\n [ bench \"(|*|)\" $ whnfIO (setComp Par arr |*| arr')\n , bench \"fused (|*|)\" $ whnfIO (setComp Par arr |*| A.transpose arr)\n -- , bench \"multiplyTranspose\" $\n -- whnf (computeAs U . multiplyTransposed (setComp Par arr)) arr2\n -- , bench \"multiplyTransposeSIMD\" $\n -- whnf (computeAs P . multiplyTransposedSIMD (setComp Par arrV)) arrV2\n , bench \"multArrsAlt\" $ whnf (multArrsAlt (setComp Par arr)) arr'\n ]\n ]\n ]\n", "meta": {"hexsha": "bf301abc8600984f6c7521db280b6299e580866d", "size": 2452, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "massiv-bench/bench/Mult.hs", "max_stars_repo_name": "bef0/massiv", "max_stars_repo_head_hexsha": "2631c03ef2b177cadd56b35cf8ada74f1153724b", "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": "massiv-bench/bench/Mult.hs", "max_issues_repo_name": "bef0/massiv", "max_issues_repo_head_hexsha": "2631c03ef2b177cadd56b35cf8ada74f1153724b", "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": "massiv-bench/bench/Mult.hs", "max_forks_repo_name": "bef0/massiv", "max_forks_repo_head_hexsha": "2631c03ef2b177cadd56b35cf8ada74f1153724b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0588235294, "max_line_length": 89, "alphanum_fraction": 0.5701468189, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5889643345190952}} {"text": "module NNSpec where\n\nimport Numeric.LinearAlgebra as LA\nimport Test.Hspec\nimport NN\n\nspec :: Spec\nspec =\n describe \"Toy Neural Network\" $\n\n-- it \"Train Point\" $ do\n-- let wT1 = (3 >< 2) $ repeat 1.0\n-- b1 = (3 >< 1) $ repeat 0.0\n-- vT1 = (1 >< 3) $ repeat 1.0\n-- learningRate = 0.001\n-- res = trainPoint wT1 b1 vT1 learningRate 2 1 10\n-- res `shouldBe` (wT1, b1, vT1)\n \n it \"Test\" $ do\n let wT = (3 >< 2) $ repeat 1.0\n b = (3 >< 1) $ repeat 0.0\n vT = (1 >< 3) $ repeat 1.0\n learningRate = 0.001\n epochs = 10\n xyPairs = [((2.0, 1.0), 10.0), ((3.0, 3.0), 21.0), ((4.0, 5.0), 32.0), ((6.0, 6.0), 42.0)]\n (wT', b', vT') = trainNeuralNetwork xyPairs wT b vT learningRate epochs\n x = [(1.0,1.0), (2.0,2.0), (3.0,3.0), (5.0,5.0), (10.0,10.0)]\n expected = fmap (snd . fmap (* 7)) x\n res = testNeuralNetwork x wT' b' vT' learningRate\n res' = map ((< 0.1) . abs) $ zipWith (-) res expected\n res' `shouldBe` [True, True, True, True, True]\n", "meta": {"hexsha": "9c9372e6a68482427aef60b1ca157f89303f2997", "size": 1118, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/NNSpec.hs", "max_stars_repo_name": "ph1lblair/haskell-ml", "max_stars_repo_head_hexsha": "1b26fe94ae9751d4a3ce6ffd630dc203492d384a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/NNSpec.hs", "max_issues_repo_name": "ph1lblair/haskell-ml", "max_issues_repo_head_hexsha": "1b26fe94ae9751d4a3ce6ffd630dc203492d384a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/NNSpec.hs", "max_forks_repo_name": "ph1lblair/haskell-ml", "max_forks_repo_head_hexsha": "1b26fe94ae9751d4a3ce6ffd630dc203492d384a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9375, "max_line_length": 102, "alphanum_fraction": 0.476744186, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5888722185176308}} {"text": "{-# LANGUAGE AllowAmbiguousTypes, DataKinds, RankNTypes, TypeFamilies,\n TypeOperators #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\nmodule TestMnistCNN (testTrees, shortTestForCITrees) where\n\nimport Prelude\n\nimport Control.Arrow (first)\nimport Control.Monad (foldM)\nimport qualified Data.Array.DynamicS as OT\nimport Data.Array.Internal (valueOf)\nimport qualified Data.Array.Shaped as OSB\nimport qualified Data.Array.ShapedS as OS\nimport Data.Proxy (Proxy (Proxy))\nimport qualified Data.Vector.Generic as V\nimport GHC.TypeLits (KnownNat, SomeNat (..), someNatVal, type (<=))\nimport Numeric.LinearAlgebra (Matrix, Vector)\nimport qualified Numeric.LinearAlgebra as HM\nimport System.IO (hPutStrLn, stderr)\nimport System.Random\nimport Test.Tasty\nimport Test.Tasty.HUnit hiding (assert)\nimport Test.Tasty.QuickCheck hiding (label, scale, shuffle)\nimport Text.Printf\n\nimport HordeAd\nimport HordeAd.Core.DualClass (HasRanks (dKonst2), IsPrimal (dZero))\nimport HordeAd.Tool.MnistCnnShaped\nimport HordeAd.Tool.MnistTools\n\nimport TestCommon\n\ntestTrees :: [TestTree]\ntestTrees = [ mnistCNNTestsShort\n , mnistCNNTestsLong\n ]\n\nshortTestForCITrees :: [TestTree]\nshortTestForCITrees = [ mnistCNNTestsShort\n ]\n\n-- * The simplest possible convolutional net, based on\n-- https://www.ritchieng.com/machine-learning/deep-learning/tensorflow/convnets/#Problem-1\n-- but with different initialization and no batches and the picture size\n-- evolves differently (@conv2@ used instead of @convSame2@). Theirs is not\n-- real convolution but, most likely, correlation, and their padding\n-- only preserves size, while ours in @conv2@ increases it,\n-- not to put less weigth onto information from the outer rows and columns.\n\npatch_size, depth0, num_hidden0, final_image_size :: Int\npatch_size = 5\ndepth0 = 16\nnum_hidden0 = 64\nfinal_image_size = 10 -- if size was not increased: 7, see below\n\nlenMnistCNN :: Int -> Int -> Int -> (Int, [Int], [(Int, Int)], [OT.ShapeL])\nlenMnistCNN final_image_sz depth num_hidden =\n ( depth + depth\n , [num_hidden, sizeMnistLabel]\n , replicate (depth + depth * depth) (patch_size, patch_size)\n ++ [(num_hidden, final_image_sz * final_image_sz * depth)]\n ++ [(sizeMnistLabel, num_hidden)]\n , []\n )\n\n-- This is simple convolution with depth 1.\nconvDataMnistCNN :: DualMonad d r m\n => DualNumberVariables d r -> Matrix r -> Int\n -> m (DualNumber d (Matrix r))\nconvDataMnistCNN variables x offset = do\n let ker = var2 variables offset\n bias = var0 variables offset\n yConv@(D u _) <- conv2 ker (D x (dKonst2 dZero (HM.size x))) -- == (scalar x)\n yRelu <- reluAct $ yConv + konst2 bias (HM.size u)\n maxPool2 2 2 yRelu\n\n-- This simulates convolution of nontrivial depth, without using tensors.\nconvMiddleMnistCNN :: DualMonad d r m\n => Int -> DualNumberVariables d r\n -> [DualNumber d (Matrix r)] -> Int\n -> m (DualNumber d (Matrix r))\nconvMiddleMnistCNN depth variables ms1 k = do\n let conv (m, n) = do\n let ker = var2 variables ((1 + k) * depth + n)\n conv2 ker m\n ms2 <- mapM conv $ zip ms1 [0 ..]\n yConv@(D u _) <- returnLet $ sum ms2\n let bias = var0 variables (depth + k)\n yRelu <- reluAct $ yConv + konst2 bias (HM.size u)\n maxPool2 2 2 yRelu\n\nconvMnistCNN :: DualMonad d r m\n => Int -> Matrix r -- 28x28\n -> DualNumberVariables d r\n -> m (DualNumber d (Vector r))\nconvMnistCNN depth x variables = do\n ms1 <- mapM (convDataMnistCNN variables x) [0 .. depth - 1]\n ms3 <- mapM (convMiddleMnistCNN depth variables ms1) [0 .. depth - 1]\n let flattenAppend m = append1 (flatten1 m)\n v <- returnLet $ foldr flattenAppend (seq1 V.empty) ms3\n let weigthsDense = var2 variables (depth + depth * depth)\n biasesDense = var1 variables 0\n denseLayer = weigthsDense #>! v + biasesDense\n denseRelu <- reluAct denseLayer\n let weigthsReadout = var2 variables (depth + depth * depth + 1)\n biasesReadout = var1 variables 1\n returnLet $ weigthsReadout #>! denseRelu + biasesReadout\n\nconvMnistLossCNN :: DualMonad d r m\n => Int -> MnistData2 r\n -> DualNumberVariables d r\n -> m (DualNumber d r)\nconvMnistLossCNN depth (x, target) variables = do\n result <- convMnistCNN depth x variables\n lossSoftMaxCrossEntropyV target result\n\nconvMnistTestCNN\n :: forall r. IsScalar 'DModeGradient r\n => Proxy r -> Int -> [MnistData2 r] -> Domains r -> r\nconvMnistTestCNN _ depth inputs parameters =\n let matchesLabels :: MnistData2 r -> Bool\n matchesLabels (glyph, label) =\n let nn variables = do\n m <- convMnistCNN depth glyph variables\n softMaxActV m\n value = primalValue nn parameters\n in V.maxIndex value == V.maxIndex label\n in fromIntegral (length (filter matchesLabels inputs))\n / fromIntegral (length inputs)\n{-# SPECIALIZE convMnistTestCNN :: Proxy Double -> Int -> [MnistData2 Double] -> Domains Double -> Double #-}\n\n-- Here, unlike in\n-- https://www.ritchieng.com/machine-learning/deep-learning/tensorflow/convnets/#Problem-1\n-- we don't batch yet.\nconvMnistTestCaseCNN\n :: String\n -> Int\n -> Int\n -> (Int\n -> MnistData2 Double\n -> DualNumberVariables 'DModeGradient Double\n -> DualMonadGradient Double (DualNumber 'DModeGradient Double))\n -> (Proxy Double -> Int -> [MnistData2 Double]\n -> Domains Double -> Double)\n -> Int\n -> Int\n -> Int\n -> Double\n -> Double\n -> TestTree\nconvMnistTestCaseCNN prefix epochs maxBatches trainWithLoss testLoss\n final_image_sz widthHidden widthHidden2 gamma expected =\n let ( (nParams0, nParams1, nParams2, nParamsX)\n , totalParams, range, parameters0 ) =\n initializerFixed 44 0.05\n (lenMnistCNN final_image_sz widthHidden widthHidden2)\n name = prefix ++ \": \"\n ++ unwords [ show epochs, show maxBatches\n , show widthHidden, show widthHidden2\n , show nParams0, show nParams1, show nParams2\n , show nParamsX\n , show totalParams, show gamma, show range]\n in testCase name $ do\n hPutStrLn stderr $ printf \"\\n%s: Epochs to run/max batches per epoch: %d/%d\"\n prefix epochs maxBatches\n trainData <- loadMnistData2 trainGlyphsPath trainLabelsPath\n testData <- loadMnistData2 testGlyphsPath testLabelsPath\n -- Mimic how backprop tests and display it, even though tests\n -- should not print, in principle.\n let runBatch :: Domains Double\n -> (Int, [MnistData2 Double])\n -> IO (Domains Double)\n runBatch (!params0, !params1, !params2, !paramsX) (k, chunk) = do\n let f = trainWithLoss widthHidden\n res = fst $ sgd gamma f chunk\n (params0, params1, params2, paramsX)\n !trainScore = testLoss (Proxy @Double)\n widthHidden chunk res\n !testScore = testLoss (Proxy @Double)\n widthHidden testData res\n !lenChunk = length chunk\n hPutStrLn stderr $ printf \"\\n%s: (Batch %d with %d points)\" prefix k lenChunk\n hPutStrLn stderr $ printf \"%s: Training error: %.2f%%\" prefix ((1 - trainScore) * 100)\n hPutStrLn stderr $ printf \"%s: Validation error: %.2f%%\" prefix ((1 - testScore ) * 100)\n return res\n let runEpoch :: Int\n -> Domains Double\n -> IO (Domains Double)\n runEpoch n params2 | n > epochs = return params2\n runEpoch n params2 = do\n hPutStrLn stderr $ printf \"\\n%s: [Epoch %d]\" prefix n\n let trainDataShuffled = shuffle (mkStdGen $ n + 5) trainData\n chunks = take maxBatches\n $ zip [1 ..] $ chunksOf 5000 trainDataShuffled\n !res <- foldM runBatch params2 chunks\n runEpoch (succ n) res\n res <- runEpoch 1 parameters0\n let testErrorFinal = 1 - testLoss (Proxy @Double)\n widthHidden testData res\n testErrorFinal @?= expected\n\n\n-- * Another flavour of the simplest possible convolutional net, based on\n-- https://www.ritchieng.com/machine-learning/deep-learning/tensorflow/convnets/#Problem-1\n-- but with different initialization and no batches.\n-- Also, if @conv2@ was used instead of @convSame2@,\n-- the picture size would evolve differently. Theirs is not\n-- real convolution but, most likely, correlation, and their padding\n-- only preserves size, while ours in @conv2@ increases it,\n-- not to put less weigth onto information from the outer rows and columns.\n\nfinal_image_sizeS :: Int\nfinal_image_sizeS = 7\n\n-- This is simple convolution with depth 1.\nconvDataMnistCNNS :: DualMonad d r m\n => DualNumberVariables d r -> Matrix r -> Int\n -> m (DualNumber d (Matrix r))\nconvDataMnistCNNS variables x offset = do\n let ker = var2 variables offset\n bias = var0 variables offset\n yConv@(D u _) <- convSame2 ker (constant x)\n yRelu <- reluAct $ yConv + konst2 bias (HM.size u)\n maxPool2 2 2 yRelu\n\n-- This simulates convolution of nontrivial depth, without using tensors.\nconvMiddleMnistCNNS :: DualMonad d r m\n => Int -> DualNumberVariables d r\n -> [DualNumber d (Matrix r)] -> Int\n -> m (DualNumber d (Matrix r))\nconvMiddleMnistCNNS depth variables ms1 k = do\n let conv (m, n) = do\n let ker = var2 variables ((1 + k) * depth + n)\n convSame2 ker m\n ms2 <- mapM conv $ zip ms1 [0 ..]\n yConv@(D u _) <- returnLet $ sum ms2\n let bias = var0 variables (depth + k)\n yRelu <- reluAct $ yConv + konst2 bias (HM.size u)\n maxPool2 2 2 yRelu\n\nconvMnistCNNS :: DualMonad d r m\n => Int -> Matrix r -- 28x28\n -> DualNumberVariables d r\n -> m (DualNumber d (Vector r))\nconvMnistCNNS depth x variables = do\n ms1 <- mapM (convDataMnistCNNS variables x) [0 .. depth - 1]\n ms3 <- mapM (convMiddleMnistCNNS depth variables ms1) [0 .. depth - 1]\n let flattenAppend m = append1 (flatten1 m)\n v <- returnLet $ foldr flattenAppend (seq1 V.empty) ms3\n let weigthsDense = var2 variables (depth + depth * depth)\n biasesDense = var1 variables 0\n denseLayer = weigthsDense #>! v + biasesDense\n denseRelu <- reluAct denseLayer\n let weigthsReadout = var2 variables (depth + depth * depth + 1)\n biasesReadout = var1 variables 1\n returnLet $ weigthsReadout #>! denseRelu + biasesReadout\n\nconvMnistLossCNNS :: DualMonad d r m\n => Int -> MnistData2 r\n -> DualNumberVariables d r\n -> m (DualNumber d r)\nconvMnistLossCNNS depth (x, target) variables = do\n result <- convMnistCNNS depth x variables\n lossSoftMaxCrossEntropyV target result\n\nconvMnistTestCNNS\n :: forall r. IsScalar 'DModeGradient r\n => Proxy r -> Int -> [MnistData2 r] -> Domains r -> r\nconvMnistTestCNNS _ depth inputs parameters =\n let matchesLabels :: MnistData2 r -> Bool\n matchesLabels (glyph, label) =\n let nn variables = do\n m <- convMnistCNNS depth glyph variables\n softMaxActV m\n value = primalValue nn parameters\n in V.maxIndex value == V.maxIndex label\n in fromIntegral (length (filter matchesLabels inputs))\n / fromIntegral (length inputs)\n{-# SPECIALIZE convMnistTestCNNS :: Proxy Double -> Int -> [MnistData2 Double] -> Domains Double -> Double #-}\n\n\n-- * A variant of @convMnistCNN@ with @conv2'@.\n\n-- This is simple convolution with depth 1.\nconvDataMnistCNNP :: DualMonad d r m\n => DualNumberVariables d r -> Matrix r -> Int\n -> m (DualNumber d (Matrix r))\nconvDataMnistCNNP variables x offset = do\n let ker = var2 variables offset\n bias = var0 variables offset\n yConv@(D u _) <-\n returnLet $ conv2' ker (D x (dKonst2 dZero (HM.size x))) -- == (scalar x)\n yRelu <- reluAct $ yConv + konst2 bias (HM.size u)\n maxPool2 2 2 yRelu\n\n-- This simulates convolution of nontrivial depth, without using tensors.\nconvMiddleMnistCNNP :: DualMonad d r m\n => Int -> DualNumberVariables d r\n -> [DualNumber d (Matrix r)] -> Int\n -> m (DualNumber d (Matrix r))\nconvMiddleMnistCNNP depth variables ms1 k = do\n let conv (m, n) = do\n let ker = var2 variables ((1 + k) * depth + n)\n returnLet $ conv2' ker m\n ms2 <- mapM conv $ zip ms1 [0 ..]\n yConv@(D u _) <- returnLet $ sum ms2\n let bias = var0 variables (depth + k)\n yRelu <- reluAct $ yConv + konst2 bias (HM.size u)\n maxPool2 2 2 yRelu\n\nconvMnistCNNP :: DualMonad d r m\n => Int -> Matrix r -- 28x28\n -> DualNumberVariables d r\n -> m (DualNumber d (Vector r))\nconvMnistCNNP depth x variables = do\n ms1 <- mapM (convDataMnistCNNP variables x) [0 .. depth - 1]\n ms3 <- mapM (convMiddleMnistCNNP depth variables ms1) [0 .. depth - 1]\n let flattenAppend m = append1 (flatten1 m)\n v <- returnLet $ foldr flattenAppend (seq1 V.empty) ms3\n let weigthsDense = var2 variables (depth + depth * depth)\n biasesDense = var1 variables 0\n denseLayer = weigthsDense #>! v + biasesDense\n denseRelu <- reluAct denseLayer\n let weigthsReadout = var2 variables (depth + depth * depth + 1)\n biasesReadout = var1 variables 1\n returnLet $ weigthsReadout #>! denseRelu + biasesReadout\n\nconvMnistLossCNNP :: DualMonad d r m\n => Int -> MnistData2 r\n -> DualNumberVariables d r\n -> m (DualNumber d r)\nconvMnistLossCNNP depth (x, target) variables = do\n result <- convMnistCNNP depth x variables\n lossSoftMaxCrossEntropyV target result\n\nconvMnistTestCNNP\n :: forall r. IsScalar 'DModeGradient r\n => Proxy r -> Int -> [MnistData2 r] -> Domains r -> r\nconvMnistTestCNNP _ depth inputs parameters =\n let matchesLabels :: MnistData2 r -> Bool\n matchesLabels (glyph, label) =\n let nn variables = do\n m <- convMnistCNNP depth glyph variables\n softMaxActV m\n value = primalValue nn parameters\n in V.maxIndex value == V.maxIndex label\n in fromIntegral (length (filter matchesLabels inputs))\n / fromIntegral (length inputs)\n{-# SPECIALIZE convMnistTestCNNP :: Proxy Double -> Int -> [MnistData2 Double] -> Domains Double -> Double #-}\n\n\n-- * A variant of @convMnistCNN@ with shaped tensors, including mini-batches\n\nconvMnistTestCaseCNNT\n :: forall kheight_minus_1 kwidth_minus_1 num_hidden out_channels\n in_height in_width batch_size d r m.\n ( KnownNat kheight_minus_1, KnownNat kwidth_minus_1\n , KnownNat num_hidden, KnownNat out_channels\n , KnownNat in_height, KnownNat in_width, KnownNat batch_size\n , 1 <= kheight_minus_1\n , 1 <= kwidth_minus_1\n , r ~ Double, d ~ 'DModeGradient, m ~ DualMonadGradient Double )\n => String\n -> Int\n -> Int\n -> (forall kheight_minus_1' kwidth_minus_1' num_hidden' out_channels'\n in_height' in_width' batch_size'.\n ( KnownNat kheight_minus_1', KnownNat kwidth_minus_1'\n , KnownNat num_hidden', KnownNat out_channels'\n , KnownNat in_height', KnownNat in_width', KnownNat batch_size'\n , 1 <= kheight_minus_1'\n , 1 <= kwidth_minus_1'\n , DualMonad d r m )\n => Proxy kheight_minus_1'\n -> Proxy kwidth_minus_1'\n -> Proxy num_hidden'\n -> Proxy out_channels'\n -> ( OS.Array '[batch_size', in_height', in_width'] r\n , OS.Array '[batch_size', SizeMnistLabel] r )\n -> DualNumberVariables d r\n -> m (DualNumber d r))\n -> (forall kheight_minus_1' kwidth_minus_1' num_hidden' out_channels'\n in_height' in_width'.\n ( KnownNat kheight_minus_1', KnownNat kwidth_minus_1'\n , KnownNat num_hidden', KnownNat out_channels'\n , KnownNat in_height', KnownNat in_width'\n , 1 <= kheight_minus_1'\n , 1 <= kwidth_minus_1'\n , IsScalar d r )\n => Proxy r\n -> Proxy kheight_minus_1'\n -> Proxy kwidth_minus_1'\n -> Proxy num_hidden'\n -> Proxy out_channels'\n -> [( OS.Array '[in_height', in_width'] r\n , OS.Array '[SizeMnistLabel] r )]\n -> Domains r\n -> r)\n -> (forall kheight_minus_1' kwidth_minus_1' num_hidden' out_channels'\n in_height' in_width'.\n ( KnownNat kheight_minus_1', KnownNat kwidth_minus_1'\n , KnownNat num_hidden', KnownNat out_channels'\n , KnownNat in_height', KnownNat in_width' )\n => Proxy kheight_minus_1'\n -> Proxy kwidth_minus_1'\n -> Proxy num_hidden'\n -> Proxy out_channels'\n -> Proxy in_height'\n -> Proxy in_width'\n -> (Int, [Int], [(Int, Int)], [OT.ShapeL]))\n -> Double\n -> Double\n -> TestTree\nconvMnistTestCaseCNNT prefix epochs maxBatches trainWithLoss ftest flen\n gamma expected =\n let proxy_kheight_minus_1 = Proxy @kheight_minus_1\n proxy_kwidth_minus_1 = Proxy @kwidth_minus_1\n proxy_num_hidden = Proxy @num_hidden\n proxy_out_channels = Proxy @out_channels\n proxy_in_height = Proxy @in_height\n proxy_in_width = Proxy @in_width\n batch_size = valueOf @batch_size\n ((_, _, _, nParamsX), totalParams, range, parametersInit) =\n initializerFixed 44 0.05\n (flen proxy_kheight_minus_1 proxy_kwidth_minus_1\n proxy_num_hidden proxy_out_channels\n proxy_in_height proxy_in_width)\n name = prefix ++ \": \"\n ++ unwords [ show epochs, show maxBatches\n , show (valueOf @num_hidden :: Int), show batch_size\n , show nParamsX, show totalParams\n , show gamma, show range ]\n packBatchS :: [( OS.Array '[in_height, in_width] r\n , OS.Array '[SizeMnistLabel] r )]\n -> ( OS.Array '[batch_size, in_height, in_width] r\n , OS.Array '[batch_size, SizeMnistLabel] r )\n packBatchS l =\n let (inputs, targets) = unzip l\n in (OS.ravel $ OSB.fromList inputs, OS.ravel $ OSB.fromList targets)\n shapeBatchS :: MnistData r\n -> ( OS.Array '[in_height, in_width] r\n , OS.Array '[SizeMnistLabel] r )\n shapeBatchS (input, target) = (OS.fromVector input, OS.fromVector target)\n in testCase name $ do\n hPutStrLn stderr $ printf \"\\n%s: Epochs to run/max batches per epoch: %d/%d\"\n prefix epochs maxBatches\n trainData <- map shapeBatchS\n <$> loadMnistData trainGlyphsPath trainLabelsPath\n testData <- take 100 -- TODO: reduced for now, because too slow\n . map shapeBatchS\n <$> loadMnistData testGlyphsPath testLabelsPath\n -- There is some visual feedback, because some of these take long.\n let runBatch :: Domains r\n -> (Int, [( OS.Array '[in_height, in_width] r\n , OS.Array '[SizeMnistLabel] r )])\n -> IO (Domains r)\n runBatch parameters@(!_, !_, !_, !_) (k, chunk) = do\n let f = trainWithLoss proxy_kheight_minus_1 proxy_kwidth_minus_1\n proxy_num_hidden proxy_out_channels\n chunkS = map packBatchS\n $ filter (\\ch -> length ch >= batch_size)\n $ chunksOf batch_size chunk\n res = fst $ sgd gamma f chunkS parameters\n !trainScore = ftest (Proxy @r)\n proxy_kheight_minus_1 proxy_kwidth_minus_1\n proxy_num_hidden proxy_out_channels\n chunk res\n !testScore = ftest (Proxy @r)\n proxy_kheight_minus_1 proxy_kwidth_minus_1\n proxy_num_hidden proxy_out_channels\n testData res\n !lenChunk = length chunk\n hPutStrLn stderr $ printf \"\\n%s: (Batch %d with %d points)\" prefix k lenChunk\n hPutStrLn stderr $ printf \"%s: Training error: %.2f%%\" prefix ((1 - trainScore) * 100)\n hPutStrLn stderr $ printf \"%s: Validation error: %.2f%%\" prefix ((1 - testScore ) * 100)\n return res\n let runEpoch :: Int -> Domains r -> IO (Domains r)\n runEpoch n params2 | n > epochs = return params2\n runEpoch n params2 = do\n hPutStrLn stderr $ printf \"\\n%s: [Epoch %d]\" prefix n\n let trainDataShuffled = shuffle (mkStdGen $ n + 5) trainData\n chunks = take maxBatches\n $ zip [1 ..]\n $ chunksOf (2 * batch_size) trainDataShuffled\n -- TODO: (10 * batch_size) takes forever\n !res <- foldM runBatch params2 chunks\n runEpoch (succ n) res\n res <- runEpoch 1 parametersInit\n let testErrorFinal = 1 - ftest (Proxy @r)\n proxy_kheight_minus_1 proxy_kwidth_minus_1\n proxy_num_hidden proxy_out_channels\n testData res\n testErrorFinal @?= expected\n\nmnistCNNTestsLong :: TestTree\nmnistCNNTestsLong = testGroup \"MNIST CNN long tests\"\n [ {-convMnistTestCaseCNN \"artificial 5 4 3 2 1\" 5 4\n convMnistLossCNN convMnistTestCNN final_image_size\n 3 2 1 0.8991\n , convMnistTestCaseCNN \"S artificial 5 4 3 2 1\" 5 4\n convMnistLossCNNS convMnistTestCNNS final_image_sizeS\n 3 2 1 0.8991\n , -}convMnistTestCaseCNN \"P artificial 5 4 3 2 1\" 5 4\n convMnistLossCNNP convMnistTestCNNP final_image_size\n 3 2 1 0.8991\n , convMnistTestCaseCNNT @4 @4 @2 @3 @SizeMnistHeight @SizeMnistWidth @1\n \"T artificial 5 4 3 2 1\" 5 4\n convMnistLossFusedS convMnistTestS convMnistLenS\n 0.02 0.98\n , convMnistTestCaseCNN \"1 epoch 1 batch\" 1 1\n convMnistLossCNN convMnistTestCNN\n final_image_size depth0 num_hidden0\n 0.02 5.989999999999995e-2\n{-\n , convMnistTestCaseCNN \"2 epochs but only 1 batch\" 2 1\n convMnistLossCNN convMnistTestCNN\n final_image_size depth0 num_hidden0\n 0.02 8.879999999999999e-2 -- dummy results everywhere\n , convMnistTestCaseCNN \"1 epoch all batches\" 1 99\n convMnistLossCNN convMnistTestCNN\n final_image_size depth0 num_hidden0\n 0.02 5.1100000000000034e-2\n-}\n , convMnistTestCaseCNN \"S1 epoch 1 batch\" 1 1\n convMnistLossCNNS convMnistTestCNNS\n final_image_sizeS depth0 num_hidden0\n 0.02 4.800000000000004e-2\n{-\n , convMnistTestCaseCNN \"S2 epochs but only 1 batch\" 2 1\n convMnistLossCNNS convMnistTestCNNS\n final_image_sizeS depth0 num_hidden0\n 0.02 8.879999999999999e-2\n , convMnistTestCaseCNN \"S1 epoch all batches\" 1 99\n convMnistLossCNNS convMnistTestCNNS\n final_image_sizeS depth0 num_hidden0\n 0.02 5.1100000000000034e-2\n-}\n , convMnistTestCaseCNN \"P1 epoch 1 batch\" 1 1\n convMnistLossCNNP convMnistTestCNNP\n final_image_size depth0 num_hidden0\n 0.02 5.989999999999995e-2\n{-\n , convMnistTestCaseCNN \"P2 epochs but only 1 batch\" 2 1\n convMnistLossCNNP convMnistTestCNNP\n final_image_size depth0 num_hidden0\n 0.02 4.94e-2\n , convMnistTestCaseCNN \"P1 epoch all batches\" 1 99\n convMnistLossCNNP convMnistTestCNNP\n final_image_size depth0 num_hidden0\n 0.02 2.7000000000000024e-2\n-}\n , convMnistTestCaseCNNT @4 @4 @64 @16 @SizeMnistHeight @SizeMnistWidth @16\n \"T1 epoch 1 batch\" 1 1\n convMnistLossFusedS convMnistTestS convMnistLenS\n 0.02 0.8200000000000001\n , testProperty \"Compare gradients and two forward derivatives for a single 2d convolution implemented from primitive operations and as a hardwired primitive\" $\n forAll (choose (1, 30)) $ \\seed ->\n forAll (choose (1, 50)) $ \\seedDs ->\n forAll (choose (1, 100)) $ \\widthHidden ->\n forAll (choose (1, 150)) $ \\widthHidden2 ->\n forAll (choose (0, seed + widthHidden - 2)) $ \\ix1 ->\n forAll (choose (0, seedDs + widthHidden2 - 2)) $ \\ix2 ->\n forAll (choose (0.01, 10)) $ \\range ->\n forAll (choose (0.01, 10)) $ \\rangeDs ->\n let paramShape =\n (0, [], [(seed, widthHidden2), (widthHidden, seedDs)], [])\n (_, _, _, parameters) = initializerFixed seed range paramShape\n (_, _, _, ds) = initializerFixed seedDs rangeDs paramShape\n (_, _, _, parametersPerturbation) =\n initializerFixed (seed + seedDs) 1e-7 paramShape\n f, fP :: forall d r m. (DualMonad d r m)\n => DualNumberVariables d r -> m (DualNumber d r)\n f variables = do\n let ker = var2 variables 0\n x = var2 variables 1\n c <- conv2 ker x\n cx <- returnLet $ from2X c\n cx1 <- returnLet $ indexX cx ix1\n cx2 <- returnLet $ indexX cx1 ix2\n returnLet $ fromX0 cx2\n fP variables = do\n let ker = var2 variables 0\n x = var2 variables 1\n c <- returnLet $ conv2' ker x\n cx <- returnLet $ from2X c\n cx1 <- returnLet $ indexX cx ix1\n cx2 <- returnLet $ indexX cx1 ix2\n returnLet $ fromX0 cx2\n in\n qcPropDom f parameters ds parametersPerturbation 1 .&&.\n qcPropDom fP parameters ds parametersPerturbation 1 .&&.\n cmpTwoSimple f fP parameters ds\n\n , testProperty \"Compare gradients and two forward derivatives for convMnistTestCNN and convMnistTestCNNP\" $\n \\seed ->\n forAll (choose (0, sizeMnistLabel - 1)) $ \\seedDs ->\n forAll (choose (1, 20)) $ \\depth ->\n forAll (choose (1, 30)) $ \\num_hidden ->\n forAll (choose (0.01, 0.5)) $ \\range ->\n forAll (choose (0.01, 10)) $ \\rangeDs ->\n let createRandomVector n seedV = HM.randomVector seedV HM.Uniform n\n glyph = HM.reshape 28 $ createRandomVector (28 * 28) seed\n label = HM.konst 0 sizeMnistLabel V.// [(seedDs, 1)]\n mnistData :: MnistData2 Double\n mnistData = (glyph, label)\n paramShape = lenMnistCNN final_image_size depth num_hidden\n (_, _, _, parameters) = initializerFixed seed range paramShape\n (_, _, _, ds) = initializerFixed seedDs rangeDs paramShape\n (_, _, _, parametersPerturbation) =\n initializerFixed (seed + seedDs) 1e-7 paramShape\n f, fP, fT :: forall d r m. (DualMonad d r m, r ~ Double)\n => DualNumberVariables d r -> m (DualNumber d r)\n f = convMnistLossCNN depth mnistData\n fP = convMnistLossCNNP depth mnistData\n fT = case ( someNatVal $ toInteger num_hidden\n , someNatVal $ toInteger depth ) of\n ( Just (SomeNat proxy_num_hidden)\n ,Just (SomeNat proxy_out_channel) ) ->\n convMnistLossFusedS (Proxy @4) (Proxy @4)\n proxy_num_hidden proxy_out_channel\n (packBatch @1 [shapeBatch\n $ first HM.flatten mnistData])\n _ -> error \"fT panic\"\n paramsToT (p0, p1, p2, _) =\n let qX = V.fromList\n [ OT.fromVector [depth, 1, 5, 5]\n $ V.concat $ map HM.flatten\n $ take depth $ V.toList p2\n , OT.fromVector [depth] $ V.take depth p0\n , OT.fromVector [depth, depth, 5, 5]\n $ V.concat $ map HM.flatten\n $ take (depth * depth) (drop depth $ V.toList p2)\n , OT.fromVector [depth] $ V.drop depth p0\n , let m = p2 V.! (depth + depth * depth)\n in OT.fromVector [num_hidden, HM.cols m]\n $ HM.flatten m\n , OT.fromVector [num_hidden] $ p1 V.! 0\n , OT.fromVector [sizeMnistLabel, num_hidden]\n $ HM.flatten\n $ p2 V.! (depth + depth * depth + 1)\n , OT.fromVector [sizeMnistLabel] $ p1 V.! 1\n ]\n in (V.empty, V.empty, V.empty, qX)\n parametersT = paramsToT parameters\n dsT = paramsToT ds\n in\n qcPropDom f parameters ds parametersPerturbation 1 .&&.\n qcPropDom fP parameters ds parametersPerturbation 1 .&&.\n qcPropDom fT parametersT dsT parametersPerturbation 1 .&&.\n cmpTwoSimple f fP parameters ds .&&.\n cmpTwo f fT parameters parametersT ds dsT\n ]\n\nmnistCNNTestsShort :: TestTree\nmnistCNNTestsShort = testGroup \"MNIST CNN short tests\"\n [ convMnistTestCaseCNN \"artificial 1 1 1 1 1\" 1 1\n convMnistLossCNN convMnistTestCNN final_image_size\n 1 1 1 0.9026\n , convMnistTestCaseCNN \"S artificial 1 1 1 1 1\" 1 1\n convMnistLossCNNS convMnistTestCNNS final_image_sizeS\n 1 1 1 0.9026\n , convMnistTestCaseCNN \"P artificial 1 1 1 1 1\" 1 1\n convMnistLossCNNP convMnistTestCNNP final_image_size\n 1 1 1 0.9026\n , convMnistTestCaseCNNT @4 @4 @1 @1 @SizeMnistHeight @SizeMnistWidth @1\n \"T artificial 1 1 1 1 1\" 1 1\n convMnistLossFusedS convMnistTestS convMnistLenS\n 1 0.85\n{-\n , convMnistTestCaseCNN \"artificial 1 2 3 4 5\" 1 2\n convMnistLossCNN convMnistTestCNN final_image_size\n 3 4 5 0.902\n , convMnistTestCaseCNN \"S artificial 1 2 3 4 5\" 1 2\n convMnistLossCNNS convMnistTestCNNS final_image_sizeS\n 3 4 5 0.902\n , convMnistTestCaseCNN \"P artificial 1 2 3 4 5\" 1 2\n convMnistLossCNNP convMnistTestCNNP final_image_size\n 3 4 5 0.8972\n-}\n , convMnistTestCaseCNNT @4 @4 @4 @3 @SizeMnistHeight @SizeMnistWidth @5\n \"T artificial 1 2 3 4 5\" 1 2\n convMnistLossFusedS convMnistTestS convMnistLenS\n 6 0.92\n ]\n", "meta": {"hexsha": "1c1157351442d9054120a8a236e4dc97a9c84165", "size": 31249, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/common/TestMnistCNN.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/common/TestMnistCNN.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "test/common/TestMnistCNN.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": 45.5524781341, "max_line_length": 161, "alphanum_fraction": 0.5969791033, "num_tokens": 8394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639065, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5888193576043371}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-|\n\nModule : Grenade.Layers.Dropout\nDescription : Defines the Dropout Layer\n\nDropout is a regularization method used to prevent overfitting \nof the network to the training dataset. \nIt works by randomly \"dropping out\", i.e. ignoring, outputs of \na percentage of neurons.\nThis is strategy is effective in preventing overfitting as it \nforces a NN not to rely on a single feature for computing the \noutput of a neural network\n-}\nmodule Grenade.Layers.Dropout (\n Dropout (..)\n , randomDropout\n ) where\n\nimport Control.DeepSeq\nimport Control.Monad.Primitive (PrimBase, PrimState)\nimport Data.Proxy\nimport Data.Serialize\nimport GHC.Generics hiding (R)\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra.Static hiding (Seed)\nimport System.Random.MWC\n\nimport Grenade.Core\n\n-- Dropout layer help to reduce overfitting.\n-- Idea here is that the vector is a shape of 1s and 0s, which we multiply the input by.\n-- After backpropogation, we return a new matrix/vector, with different bits dropped out.\n-- The provided argument is the proportion to drop in each training iteration (like 1% or\n-- 5% would be reasonable).\ndata Dropout (pct :: Nat) =\n Dropout\n { dropoutActive :: Bool -- ^ Add possibility to deactivate dropout\n , dropoutSeed :: !Int -- ^ Seed\n }\n deriving (Generic)\n\ninstance NFData (Dropout pct) where rnf (Dropout a s) = rnf a `seq` rnf s\ninstance Show (Dropout pct) where show (Dropout _ _) = \"Dropout\"\ninstance Serialize (Dropout pct) where\n put (Dropout act seed) = put act >> put seed\n get = Dropout <$> get <*> get\n\ninstance UpdateLayer (Dropout pct) where\n type Gradient (Dropout pct) = ()\n runUpdate _ (Dropout act seed) _ = Dropout act (seed+1)\n runSettingsUpdate set (Dropout _ seed) = Dropout (setDropoutActive set) seed\n reduceGradient _ = ()\n\ninstance RandomLayer (Dropout pct) where\n createRandomWith _ = randomDropout\n\nrandomDropout :: (PrimBase m) => Gen (PrimState m) -> m (Dropout pct)\nrandomDropout gen = Dropout True <$> uniform gen\n\ninstance (KnownNat pct, KnownNat i) => Layer (Dropout pct) ('D1 i) ('D1 i) where\n type Tape (Dropout pct) ('D1 i) ('D1 i) = R i\n runForwards (Dropout act seed) (S1D x)\n | not act = (v, S1D $ dvmap (rate *) x) -- multily with rate to normalise throughput\n | otherwise = (v, S1D $ v * x)\n where\n rate = (/100) $ fromIntegral $ max 0 $ min 100 $ natVal (Proxy :: Proxy pct)\n v = dvmap mask $ randomVector seed Uniform\n mask r\n | not act || r < rate = 1\n | otherwise = 0\n runBackwards (Dropout _ _) v (S1D x) = ((), S1D $ x * v)\n", "meta": {"hexsha": "12d5d308d005dc9ee7658b60e370752673728d53", "size": 2912, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Dropout.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/Dropout.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Dropout.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3333333333, "max_line_length": 89, "alphanum_fraction": 0.6607142857, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5888107417773253}} {"text": "module Sound.Filter\n(\n lzero2cp\n , lpole2cp\n , rlzero2cp\n , rlpole2cp\n , Cx\n , Z\n)\nwhere\n\nimport qualified Data.Complex as Cp\n\nimport Sound.InfList\nimport Sound.Time\n\nlpole2cp :: Z -> L Double -> L Double\nlpole2cp p x0 =\n y0\n where\n y0 = lzip3 (\\ sy1 sy2 sx0 -> a * sy1 - b * sy2 + sx0) y1 y2 x0\n y1 = ldelay y0\n y2 = ldelay y1\n r = Cp.realPart p\n i = Cp.imagPart p\n a = 2 * r\n b = r * r + i * i\n\nrlpole2cp :: Z -> Rated (L Double) -> Rated (L Double)\nrlpole2cp p = rmap (lpole2cp p)\n\nlzero2cp :: Z -> L Double -> L Double\nlzero2cp p x0 =\n lzip3 (\\ sx0 sx1 sx2 -> sx0 - a * sx1 + b * sx2) x0 x1 x2\n where\n x1 = ldelay x0\n x2 = ldelay x1\n r = Cp.realPart p\n i = Cp.imagPart p\n a = 2 * r\n b = r * r + i * i\n\nrlzero2cp :: Z -> Rated (L Double) -> Rated (L Double)\nrlzero2cp p = rmap (lzero2cp p)\n\n-- | complex number\ntype Cx = Cp.Complex Double\n\n-- | z-plane coordinate\ntype Z = Cx\n", "meta": {"hexsha": "651527754a5360324342e9781be32cbe2e1557bb", "size": 1000, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "archive/sound/src/Sound/Filter.hs", "max_stars_repo_name": "edom/work", "max_stars_repo_head_hexsha": "df55868caa436efc631e145a43e833220b8da1d0", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.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": "archive/sound/src/Sound/Filter.hs", "max_issues_repo_name": "edom/work", "max_issues_repo_head_hexsha": "df55868caa436efc631e145a43e833220b8da1d0", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-02T18:37:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T00:55:32.000Z", "max_forks_repo_path": "archive/sound/src/Sound/Filter.hs", "max_forks_repo_name": "edom/work", "max_forks_repo_head_hexsha": "df55868caa436efc631e145a43e833220b8da1d0", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-02T15:20:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T15:20:22.000Z", "avg_line_length": 19.6078431373, "max_line_length": 70, "alphanum_fraction": 0.541, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5887257046647613}} {"text": "module LayersSpec\n ( spec\n ) where\n\nimport Control.Monad\nimport qualified Data.Set as Set\nimport Data.Tuple.Extra\nimport Debug.Trace\nimport Foundation.Monad\nimport Layers\nimport Learn\nimport Mnist\nimport Numeric.LinearAlgebra as A\nimport Synapse\nimport Test.Hspec\nimport Test.Hspec.QuickCheck (prop)\nimport Test.QuickCheck\nimport Test.QuickCheck.Gen\nimport Test.QuickCheck.Monadic\n\nrunTest :: IO ()\nrunTest = hspec spec\n\nspec :: Spec\nspec = do\n describe \"predict\" propsPredict\n describe \"evaluate\" propsEvaluate\n describe \"Affine\" propsAffine\n describe \"Sigmoid\" propsSigmoid\n describe \"ReLU\" propsReLU\n describe \"Joined\" propsJoined\n describe \"Matrix\" propsMatrix\n\npropsPredict =\n prop \"index\" $\n forAll (genVectorN 100) $ \\v ->\n let r = predict ReLUForward v\n a = maxIndex v\n in r `shouldBe` a\n\npropsEvaluate = do\n prop \"100%\" $\n forAll (vectorOf 100 $ genVectorN 100) $ \\vs ->\n let ns = map maxIndex vs\n r = evaluate ReLUForward $ zip ns vs\n in r `shouldBe` 1\n prop \"0%\" $\n forAll (vectorOf 100 $ genVectorN 100) $ \\vs ->\n let ns = map ((+ 1) . maxIndex) vs\n r = evaluate ReLUForward $ zip ns vs\n in r `shouldBe` 0\n prop \"50%\" $\n forAll (vectorOf 100 $ genVectorN 100) $ \\vs ->\n let (vA, vB) = splitAt 50 vs\n nA = map maxIndex vA\n nB = map ((+ 1) . maxIndex) vB\n ns = nA ++ nB\n r = evaluate ReLUForward $ zip ns vs\n in r `shouldBe` 0.5\n\npropsAffine = do\n prop \"forward\" $\n forAll\n (do a <- choose (10, 100)\n b <- choose (10, 100)\n c <- choose (10, 100)\n f <- genAffine a b\n s <- genMatrix c a\n return (f, s)) $ \\(af, x) ->\n let AffineForward weights bias = af\n (AffineBackward rW rB rX, r) = forward af x\n e = affinem weights bias x\n in (rW, rB, rX, r) `shouldBe` (weights, bias, x, e)\n prop \"backward\" $\n forAll\n (do a <- choose (10, 100)\n b <- choose (10, 100)\n c <- choose (10, 100)\n d <- genMatrix c b\n f <- genAffine a b\n s <- genMatrix c a\n return (f, s, d)) $ \\(af, x, d) ->\n let AffineForward w b = af\n rate = 1.0\n (AffineForward w' b', d') = backward rate (AffineBackward w b x) d\n (dx, dw, db) = affinemBackward w x d\n rW = w - dw\n rB = b - db\n in (w', b', d') `shouldBe` (rW, rB, dx)\n prop \"backward with rate\" $\n forAll\n (do a <- choose (10, 100)\n b <- choose (10, 100)\n c <- choose (10, 100)\n r <- arbitrary `suchThat` (\\a -> 0 < a && a < 1)\n d <- genMatrix c b\n f <- genAffine a b\n s <- genMatrix c a\n return (r, f, s, d)) $ \\(rate, af, x, d) ->\n let AffineForward w b = af\n (AffineForward w' b', d') = backward rate (AffineBackward w b x) d\n (dx, dw, db) = affinemBackward w x d\n rW = w - A.scale rate dw\n rB = b - A.scale rate db\n in (w', b', d') `shouldBe` (rW, rB, dx)\n\npropsSigmoid = do\n prop \"forward\" $\n forAll\n (do a <- choose (10, 100)\n b <- choose (10, 100)\n genMatrix a b) $ \\x ->\n let (SigmoidBackward y, r) = forward SigmoidForward x\n e = sigmoidm x\n in (y, r) `shouldBe` (r, e)\n prop \"backward\" $\n forAll\n (do a <- choose (10, 100)\n b <- choose (10, 100)\n d <- genMatrix a b\n y <- genMatrix a b\n return (y, d)) $ \\(y, d) ->\n let (SigmoidForward, d') = backward 0 (SigmoidBackward y) d\n e = sigmoidBackward y d\n in d' `shouldBe` e\n\npropsReLU = do\n prop \"forward\" $\n forAll\n (do a <- choose (10, 100)\n b <- choose (10, 100)\n genMatrix a b) $ \\x ->\n let (ReLUBackward y, r) = forward ReLUForward x\n e = relum x\n in (y, r) `shouldBe` (x, e)\n prop \"backward\" $\n forAll\n (do a <- choose (10, 100)\n b <- choose (10, 100)\n x <- genMatrix a b\n d <- genMatrix a b\n return (x, d)) $ \\(x, d) ->\n let (ReLUForward, d') = backward 0 (ReLUBackward x) d\n e = relumBackward x d\n in d' `shouldBe` e\n\npropsJoined = do\n prop \"forward\" $\n forAll\n (do a <- choose (10, 100)\n b <- choose (10, 100)\n c <- choose (10, 100)\n f <- genAffine a b\n x <- genMatrix c a\n return (f, x)) $ \\(fL1, x) ->\n let fL2 = SigmoidForward\n fJ = fL1 ~> fL2\n (JoinedBackwardLayer bL1 bL2, y) = forward fJ x\n (bL1', yL1) = forward fL1 x\n (bL2', yL2) = forward fL2 yL1\n in (bL1, bL2, y) `shouldBe` (bL1', bL2', yL2)\n prop \"backward\" $\n forAll\n (do a <- choose (10, 100)\n b <- choose (10, 100)\n c <- choose (10, 100)\n d <- genMatrix c b\n y <- genMatrix c b\n x <- genMatrix c a\n fL1 <- genAffine a b\n let AffineForward weights bias = fL1\n let bL1 = AffineBackward weights bias x\n return (bL1, SigmoidBackward y, d)) $ \\(bL1, bL2, d) ->\n let bJ = bL1 <~ bL2\n (JoinedForwardLayer fL1 SigmoidForward, bD) = backward 1.0 bJ d\n (SigmoidForward, dL2) = backward 1.0 bL2 d\n (fL1', dL1) = backward 1.0 bL1 dL2\n in (fL1, bD) `shouldBe` (fL1', dL1)\n\npropsMatrix = do\n prop \"scale\" $\n forAll genElements $ \\(a, b, x, y) ->\n let m = b `A.scale` toMatrix x y a\n m' = toMatrix x y (a * b)\n in m `shouldBe` m'\n prop \"multiply\" $\n forAll genElements $ \\(a, b, x, y) ->\n let m = toMatrix x y b * toMatrix x y a\n m' = toMatrix x y (a * b)\n in m `shouldBe` m'\n prop \"subtract\" $\n forAll genElements $ \\(a, b, x, y) ->\n let m = toMatrix x y a - toMatrix x y b\n m' = toMatrix x y (a - b)\n in m `shouldBe` m'\n prop \"add\" $\n forAll genElements $ \\(a, b, x, y) ->\n let m = toMatrix x y a + toMatrix x y b\n m' = toMatrix x y (a + b)\n in m `shouldBe` m'\n where\n toMatrix x y a = fromLists $ replicate x $ replicate y a\n genElements = do\n a <- arbitrary\n b <- arbitrary\n x <- choose (10, 100)\n y <- choose (10, 100)\n return (a :: R, b, x, y)\n\ngenVectorN :: Int -> Gen (Vector R)\ngenVectorN n = fmap fromList $ vectorOf n $ choose (1, 100)\n\ngenAffine :: Int -> Int -> Gen (ForwardLayer R)\ngenAffine nIn nOut = do\n weights <- fmap fromLists $ vectorOf nIn $ vectorOf nOut arbitrary\n bias <- fromList <$> vectorOf nOut arbitrary\n return $ AffineForward weights bias\n\ngenMatrix :: Int -> Int -> Gen (Matrix R)\ngenMatrix nRows nCols =\n fmap fromLists $ vectorOf nRows $ vectorOf nCols arbitrary\n", "meta": {"hexsha": "05ca92b6d19e57e54f0b4a492151e565e4737105", "size": 6833, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/LayersSpec.hs", "max_stars_repo_name": "sawatani/simple_mnist", "max_stars_repo_head_hexsha": "3aa8f9ccaa9a3a58fed123a81e24ce7feab3e977", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/LayersSpec.hs", "max_issues_repo_name": "sawatani/simple_mnist", "max_issues_repo_head_hexsha": "3aa8f9ccaa9a3a58fed123a81e24ce7feab3e977", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/LayersSpec.hs", "max_forks_repo_name": "sawatani/simple_mnist", "max_forks_repo_head_hexsha": "3aa8f9ccaa9a3a58fed123a81e24ce7feab3e977", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7792792793, "max_line_length": 76, "alphanum_fraction": 0.5231962535, "num_tokens": 2235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5883885237027319}} {"text": "{-# LANGUAGE TypeApplications #-}\n\nmodule SSSFNProps where\n\nimport Data.VectorSpace\nimport qualified GHC.Exts as GHC\nimport Numeric.LinearAlgebra hiding ((#>), (===), inv)\nimport SSSFN\nimport Test.QuickCheck\n\n--------------------------------------------------------------------------------\n\ninfix 4 ~~~\n\n(~~~) ::\n (GHC.IsList as, Show as, a ~ GHC.Item as, RealFloat a, Show a) =>\n as ->\n as ->\n Property\nxs ~~~ ys =\n let xs' = GHC.toList xs\n ys' = GHC.toList ys\n sc = 1 `max` maximum (map abs xs') `max` maximum (map abs ys')\n di = maximum (zipWith absdiff xs' ys')\n in counterexample\n ( show xs\n ++ \" ~~~ \"\n ++ show ys\n ++ \" (difference \"\n ++ show di\n ++ \", scale \"\n ++ show sc\n ++ \")\"\n )\n (length xs' == length ys' && di <= eps * sc)\n where\n absdiff x y = abs (x - y)\n eps = 100 * peps\n\n--------------------------------------------------------------------------------\n\nprop_Grid_add_assoc :: Grid Double -> Grid Double -> Grid Double -> Property\nprop_Grid_add_assoc x y z = (x ^+^ y) ^+^ z ~~~ x ^+^ (y ^+^ z)\n\nprop_Grid_add_lunit :: Grid Double -> Property\nprop_Grid_add_lunit x = zeroV ^+^ x ~~~ x\n\nprop_Grid_add_runit :: Grid Double -> Property\nprop_Grid_add_runit x = x ~~~ x ^+^ zeroV\n\nprop_Grid_add_comm :: Grid Double -> Grid Double -> Property\nprop_Grid_add_comm x y = x ^+^ y ~~~ y ^+^ x\n\nprop_Grid_add_linv :: Grid Double -> Property\nprop_Grid_add_linv x = negateV x ^+^ x ~~~ zeroV\n\nprop_Grid_add_rinv :: Grid Double -> Property\nprop_Grid_add_rinv x = x ^+^ negateV x ~~~ zeroV\n\nprop_Grid_add_scale_dist :: Double -> Grid Double -> Grid Double -> Property\nprop_Grid_add_scale_dist a x y = a *^ (x ^+^ y) ~~~ a *^ x ^+^ a *^ y\n\nprop_Grid_scale_assoc :: Double -> Double -> Grid Double -> Property\nprop_Grid_scale_assoc a b x = a *^ (b *^ x) ~~~ (a * b) *^ x\n\nprop_Grid_scale_lunit :: Grid Double -> Property\nprop_Grid_scale_lunit x = 1 *^ x ~~~ x\n\nprop_Grid_scale_szero :: Grid Double -> Property\nprop_Grid_scale_szero x = 0 *^ x ~~~ zeroV\n\nprop_Grid_scale_zero :: Double -> Property\nprop_Grid_scale_zero a = a *^ (zeroV :: Grid Double) ~~~ zeroV\n\nprop_Grid_scale_comm :: Double -> Double -> Grid Double -> Property\nprop_Grid_scale_comm a b x = a *^ (b *^ x) ~~~ b *^ (a *^ x)\n\nprop_Grid_scale_Grid_add_dist :: Double -> Double -> Grid Double -> Property\nprop_Grid_scale_Grid_add_dist a b x = (a + b) *^ x ~~~ a *^ x ^+^ b *^ x\n\n--------------------------------------------------------------------------------\n\nprop_Op_add_assoc :: Op Double -> Op Double -> Op Double -> Property\nprop_Op_add_assoc x y z = (x + y) + z ~~~ x + (y + z)\n\nprop_Op_add_lunit :: Op Double -> Property\nprop_Op_add_lunit x = 0 + x ~~~ x\n\nprop_Op_add_runit :: Op Double -> Property\nprop_Op_add_runit x = x ~~~ x + 0\n\nprop_Op_add_comm :: Op Double -> Op Double -> Property\nprop_Op_add_comm x y = x + y ~~~ y + x\n\nprop_Op_add_linv :: Op Double -> Property\nprop_Op_add_linv x = negate x + x ~~~ 0\n\nprop_Op_add_rinv :: Op Double -> Property\nprop_Op_add_rinv x = x + negate x ~~~ 0\n\nprop_Op_add_scale_dist :: Double -> Op Double -> Op Double -> Property\nprop_Op_add_scale_dist a x y = a *^ (x + y) ~~~ a *^ x + a *^ y\n\nprop_Op_mul_assoc :: Op Double -> Op Double -> Op Double -> Property\nprop_Op_mul_assoc x y z = (x * y) * z ~~~ x * (y * z)\n\nprop_Op_mul_lunit :: Op Double -> Property\nprop_Op_mul_lunit x = 1 * x ~~~ x\n\nprop_Op_mul_runit :: Op Double -> Property\nprop_Op_mul_runit x = x ~~~ x * 1\n\nprop_Op_mul_scale_assoc :: Double -> Op Double -> Op Double -> Property\nprop_Op_mul_scale_assoc a x y = a *^ (x * y) ~~~ (a *^ x) * y\n\nprop_Op_scale_assoc :: Double -> Double -> Op Double -> Property\nprop_Op_scale_assoc a b x = a *^ (b *^ x) ~~~ (a * b) *^ x\n\nprop_Op_scale_lunit :: Op Double -> Property\nprop_Op_scale_lunit x = 1 *^ x ~~~ x\n\nprop_Op_scale_lzero :: Op Double -> Property\nprop_Op_scale_lzero x = 0 *^ x ~~~ 0\n\nprop_Op_scale_rzero :: Double -> Property\nprop_Op_scale_rzero a = a *^ (0 :: Op Double) ~~~ 0\n\nprop_Op_scale_comm :: Double -> Double -> Op Double -> Property\nprop_Op_scale_comm a b x = a *^ (b *^ x) ~~~ b *^ (a *^ x)\n\nprop_Op_scale_add_dist :: Double -> Double -> Op Double -> Property\nprop_Op_scale_add_dist a b x = (a + b) *^ x ~~~ (a *^ x) + (b *^ x)\n", "meta": {"hexsha": "0eb3439ba29e5f02b45176bb9c5ba73f2304d910", "size": 4288, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/SSSFNProps.hs", "max_stars_repo_name": "eschnett/sssfn", "max_stars_repo_head_hexsha": "7e00b54460e23fde7a6dd70ac74098958f54e5a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/SSSFNProps.hs", "max_issues_repo_name": "eschnett/sssfn", "max_issues_repo_head_hexsha": "7e00b54460e23fde7a6dd70ac74098958f54e5a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/SSSFNProps.hs", "max_forks_repo_name": "eschnett/sssfn", "max_forks_repo_head_hexsha": "7e00b54460e23fde7a6dd70ac74098958f54e5a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2406015038, "max_line_length": 80, "alphanum_fraction": 0.5893190299, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.588253081033663}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n-- | Pearson's chi squared test.\nmodule Statistics.Test.ChiSquared (\n chi2test\n -- * Data types\n , TestType(..)\n , TestResult(..)\n ) where\n\nimport Prelude hiding (sum)\nimport Statistics.Distribution\nimport Statistics.Distribution.ChiSquared\nimport Statistics.Function (square)\nimport Statistics.Sample.Internal (sum)\nimport Statistics.Test.Types\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\n\n\n-- | Generic form of Pearson chi squared tests for binned data. Data\n-- sample is supplied in form of tuples (observed quantity,\n-- expected number of events). Both must be positive.\nchi2test :: (G.Vector v (Int,Double), G.Vector v Double)\n => Double -- ^ p-value\n -> Int -- ^ Number of additional degrees of\n -- freedom. One degree of freedom\n -- is due to the fact that the are\n -- N observation in total and\n -- accounted for automatically.\n -> v (Int,Double) -- ^ Observation and expectation.\n -> TestResult\nchi2test p ndf vec\n | ndf < 0 = error $ \"Statistics.Test.ChiSquare.chi2test: negative NDF \" ++ show ndf\n | n < 0 = error $ \"Statistics.Test.ChiSquare.chi2test: too short data sample\"\n | p > 0 && p < 1 = significant $ complCumulative d chi2 < p\n | otherwise = error $ \"Statistics.Test.ChiSquare.chi2test: bad p-value: \" ++ show p\n where\n n = G.length vec - ndf - 1\n chi2 = sum $ G.map (\\(o,e) -> square (fromIntegral o - e) / e) vec\n d = chiSquared n\n{-# SPECIALIZE\n chi2test :: Double -> Int -> U.Vector (Int,Double) -> TestResult #-}\n{-# SPECIALIZE\n chi2test :: Double -> Int -> V.Vector (Int,Double) -> TestResult #-}\n", "meta": {"hexsha": "9cd3b82cd16a06bab9670c62cde5081922c5341e", "size": 1893, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Test/ChiSquared.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "Statistics/Test/ChiSquared.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Test/ChiSquared.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.152173913, "max_line_length": 92, "alphanum_fraction": 0.6069730586, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5881480271706343}} {"text": "{-# LANGUAGE OverloadedStrings, RecordWildCards, NamedFieldPuns #-}\nmodule Numeric.LP where\n\nimport Control.Monad\nimport Data.Array.IArray (Array, (//))\nimport qualified Data.Array.IArray as A\nimport Data.Maybe\nimport qualified Data.Text.Lazy as T\nimport qualified Data.Text.Lazy.Builder as TB\nimport qualified Formatting as F\nimport Numeric.LinearAlgebra (I, Matrix, Vector, atIndex, cols,\n flatten, ident, minIndex, rows,\n subMatrix, subVector, (!), (><),\n (?), (|||), (\u00bf))\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Devel (atM', modifyMatrix, runSTMatrix,\n thawMatrix)\nimport Text.UnicodeTable\n\ndata LP = LP {\n a :: Matrix Double,\n lhs, rhs :: Vector I}\n\nlp2Table :: Int -> Int -> LP -> Table\nlp2Table nPrec nColW LP{..} = mkTable ta cws hs vs\n where rN = rows a\n cN = cols a\n taElem r c | r>0 && c>0 = F.bprint (F.fixed nPrec) $ a `atIndex` (r-1, c-1)\n | r==0 && c>1 = TB.fromString $ \"x\"++show (rhs!(c-1))\n | r==1 && c==0 = TB.fromString \"z\"\n | r>1 && c==0 = TB.fromString $ \"x\"++show (lhs!(r-1))\n | otherwise = TB.fromString \"\"\n ta = A.array ((0,0), (rN, cN)) [((r,c), taElem r c) | r <- [0..rN], c <- [0..cN]]\n cws = A.listArray (0,cN) (replicate (cN+1) nColW)\n hs = konstArray0 (rN+2) NoLine // [(0, SingleLine), (1, DoubleLine), (rN+1, SingleLine)]\n vs = konstArray0 (cN+2) NoLine // [(0, SingleLine), (1, DoubleLine), (cN+1, SingleLine)]\n\nkonstArray0 :: Int -> e -> Array Int e\nkonstArray0 n x = A.listArray (0,n-1) (replicate n x)\n\ninstance Show LP where\n show = T.unpack . TB.toLazyText . fromTable . lp2Table 4 15\n\ntransfromToEquationalForm :: Matrix Double -> Matrix Double\ntransfromToEquationalForm a = a ||| (ident (rows a))\n\nchoosePivot :: LP -> Maybe (Int, Int)\nchoosePivot LP {..} =\n let c = subVector 1 (cols a-1) (flatten $ a ? [0])\n b = subVector 1 (cols a-1) (flatten $ a \u00bf [0])\n a' = subMatrix (1,1) (rows a-1, cols a-1) a\n in case LA.find (>0) c of\n s:_ ->\n let as = flatten $ a' \u00bf [s] -- column s as a vector\n in Just (1 + minIndex (b / as), 1+s)\n _ -> Nothing\n\n-- see \n-- Let's solve the following problem:\n-- maximize $c^t x$ subject to\n-- Ax \u2264 b\n-- \u2200i, x\u1d62 \u2265 0\n-- x,c \u2208 \u211d\u207f, b \u2208 \u211d^p, A \u2208 \u211d^pxn\n\nex1 :: LP\nex1 = LP {a = (3><3)[0,2,-4, 2,-6,1, 8,3,-4],\n lhs = LA.fromList [0,1,4],\n rhs = LA.fromList [0,2,3]\n }\n\nsimplexStep :: LP -> Int -> Int -> LP\nsimplexStep (LP {..}) sr sc =\n let theta = atM' a sr sc -- save the pivot element\n pc = flatten $ a \u00bf [sc] -- save the whole pivot column\n a' = runSTMatrix\n (do\n a'm <- thawMatrix a\n -- replace each row -- except the pivot row -- by that linear combination\n -- of itself and the pivot row which makes its pivot column entry zero.\n forM_ [r | r <- [0..(rows a - 1)], r /= sr] $ \\r -> do\n let m = (-1) * (a `atIndex` (r,sc)) / theta\n forM_ [0..(cols a - 1)] $\u00a0\\i -> do\n modifyMatrix a'm r i (\\x -> x + m * (a `atIndex` (sr,i)))\n -- divide the pivot row by the negative of the pivot\n forM_ [0..(cols a - 1)] $\u00a0\\i -> do\n modifyMatrix a'm sr i (\\x -> x/(-theta))\n -- replace the pivot by the negative of its saved reciprocal\n modifyMatrix a'm sr sc (\\_ -> 1/theta)\n -- replace the other elements of the pivot column by its saved values divided\n -- by the saved pivot element\n forM_ [r | r <- [0..(rows a - 1)], r /= sr] $\u00a0\\j -> do\n modifyMatrix a'm j sc (\\_ -> pc!j/theta)\n return a'm)\n in LP a' lhs rhs\n\nmain :: IO ()\nmain = do\n putStrLn (show ex1)\n let (LP {..}) = ex1\n let (sr, sc) = fromJust $ choosePivot ex1\n putStrLn (\"Pivot row/column: \"++(show sr)++\", \"++(show sc))\n let theta = atM' a sr sc\n putStrLn (\"Pivot element: \"++(show theta))\n\n", "meta": {"hexsha": "deb1ac4be02e5ef94079dbd3d53d289e8fcb8484", "size": 4510, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LP.hs", "max_stars_repo_name": "tkemps/int-prog", "max_stars_repo_head_hexsha": "59e9a0972b9f013e651c4864e6601b1e01ebc27e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/LP.hs", "max_issues_repo_name": "tkemps/int-prog", "max_issues_repo_head_hexsha": "59e9a0972b9f013e651c4864e6601b1e01ebc27e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LP.hs", "max_forks_repo_name": "tkemps/int-prog", "max_forks_repo_head_hexsha": "59e9a0972b9f013e651c4864e6601b1e01ebc27e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9523809524, "max_line_length": 98, "alphanum_fraction": 0.4973392461, "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5880633546670461}} {"text": "import Numeric.LinearAlgebra\nimport System.Random ( mkStdGen )\nimport Learning ( nrmse )\n\nimport RC.NTC as RC\n\n-- Get training data\ntakePast :: Element a => Int -> Matrix a -> Matrix a\ntakePast horizon xs = xs ?? (All, Take (len - horizon))\n where\n len = cols xs\n\n-- Get target data\ntakeFuture :: Element a => Int -> Matrix a -> Matrix a\ntakeFuture horizon = (?? (All, Drop horizon))\n\n-- Manipulate the data matrix: horizontal split\nsplitAtRatio :: Element a => Double -> Matrix a -> (Matrix a, Matrix a)\nsplitAtRatio ratio m = splitAt' spl m\n where\n total = cols m\n spl = round $ ratio * fromIntegral total\n\nsplitAt' :: Element a => Int -> Matrix a -> (Matrix a, Matrix a)\nsplitAt' i m = (m ?? (All, Take i), m ?? (All, Drop i))\n\nmain :: IO ()\nmain = do\n -- Load and transpose time series to predict\n dta <- tr <$> loadMatrix \"examples/data/mg.txt\"\n\n -- Train on 50% of data\n let (train, validate) = splitAtRatio 0.50 dta\n\n -- Configure a new NTC network\n let p = RC.par0 { RC._inputWeightsRange = (0.1, 0.3) }\n g = mkStdGen 1111\n ntc = RC.new g p (1, 1000, 1)\n\n -- 20 steps ahead prediction horizon\n let horizon = 20\n\n let train' = takePast horizon train -- Past series\n trainTeacher = takeFuture horizon train -- Predicted series\n\n let forgetPts = 300 -- Washout\n\n -- Train\n case RC.learn ntc forgetPts train' trainTeacher of\n Left s -> error s\n Right ntc' -> do\n let target = (takeFuture horizon validate) ?? (All, Drop forgetPts)\n\n -- Predict\n case RC.predict ntc' forgetPts (takePast horizon validate) of\n Left s -> error s\n Right prediction -> do\n let tgt' = flatten target\n predic' = flatten prediction\n err = nrmse tgt' predic'\n\n putStrLn $ \"Error: \" ++ show err\n\n let result = (tr target) ||| (tr prediction)\n\n saveMatrix \"examples/NTC/result.txt\" \"%g\" result\n", "meta": {"hexsha": "58849221bca6bfd9e214538cc852e3b635e68622", "size": 1948, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/NTC/Main.hs", "max_stars_repo_name": "masterdezign/rc", "max_stars_repo_head_hexsha": "0a37c27aff70a096d010d2043ef6eab33dee2dc8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-02-24T22:31:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T11:44:32.000Z", "max_issues_repo_path": "examples/NTC/Main.hs", "max_issues_repo_name": "masterdezign/rc", "max_issues_repo_head_hexsha": "0a37c27aff70a096d010d2043ef6eab33dee2dc8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/NTC/Main.hs", "max_forks_repo_name": "masterdezign/rc", "max_forks_repo_head_hexsha": "0a37c27aff70a096d010d2043ef6eab33dee2dc8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-05-16T01:08:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-16T01:08:19.000Z", "avg_line_length": 29.0746268657, "max_line_length": 73, "alphanum_fraction": 0.6160164271, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5880439214250536}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE RebindableSyntax #-}\nmodule Models.RSA2d where\n\nimport Prelude (Double,Int, ($), (.), fmap, Ord(..), toRational, putStrLn, IO,String,show,unwords,unlines,writeFile,Integer)\nimport Algebra.Linear.Chebyshev\nimport Algebra.Linear.Vector\nimport Algebra.Classes\nimport Data.Complex\nimport Data.Foldable\nimport Models.Gnuplot\n\ntype Ivl = (Double,Double)\n\ntype F2 a = Double -> Double -> a\ntype S2 a = Samples (Samples a)\n-- type P2 a = Polynomial (Polynomial a)\n\ntype C = Complex Double\n\nnormal :: Transcendental a => a -> a -> a -> a\nnormal \u03bc \u03c3 x = recip (\u03c3 * sqrt (2 * pi)) * exp (-0.5 * ((\u03bc - x) / \u03c3) ^+ 2)\n\nprior :: Transcendental a => a -> p -> a\nprior h u = normal 68 3 h\n\ngroundFun :: (Ord t, Transcendental t) => t -> t -> t\ngroundFun h u = if h < u then 0 else prior h u\n \n\nsize__ :: Int\nsize__ = 256\n\nivlH :: (Double, Double)\nivlH = (68-10, 68+10)\n\nivlU :: (Double, Double)\nivlU = (68-20, 68+10)\n\nground :: S2 Double\nground = sample' groundFun\n\nsample' :: F2 Double -> S2 Double\nsample' = sample2d size__ ivlH ivlU\n\nsample2d :: Int -> Ivl -> Ivl -> F2 Double -> S2 Double\nsample2d n (lo1,hi1) (lo2,hi2) f =\n sample @Double n lo1 hi1 $ \\x ->\n sample @Double n lo2 hi2 $ \\y ->\n f x y\n\nnormalizeS :: Samples Double -> Samples Double\nnormalizeS v = (recip (integralUnitIvl @Double $ fmap realPart $ samplesToPoly @C $ fmap (:+ 0) v)) *^ v\n\n-- fit2 :: S2 Double -> P2 Double\n-- fit2 = fmap (fmap realPart) . samplesToPoly @C . fmap (samplesToPoly @C . fmap (:+ 0) )\n\n\nget :: Samples (Samples a) -> Int -> Int -> a\nget m i j = fromSamples (fromSamples m ! i) ! j\n\npts :: Vec Double\npts = chebPoints size__\n\n\nnormalizeH :: Samples (Samples Double) -> Samples (Samples Double)\nnormalizeH = xpose . fmap normalizeS . xpose\n where\n xpose :: Samples (Samples Double) -> Samples (Samples Double)\n xpose m = Samples $ generate (size__+1) $ \\i -> Samples $ generate (size__+1) $ \\ j -> get m j i\n\nmkSamples :: (Int -> Int -> a) -> Samples (Samples a)\nmkSamples f = Samples $ generate (size__+1) $ \\i -> Samples $ generate (size__+1) $ \\ j -> f i j\n\nnormalizeU :: Samples (Samples Double) -> Samples (Samples Double)\nnormalizeU = fmap normalizeS\n\nl0 :: Samples (Samples Double)\nl0 = normalizeH ground\n\n\u03b1 :: Natural\n\u03b1 = 40\n\ns1 :: Samples (Samples Double)\ns1 = normalizeU (fmap (fmap (^+ \u03b1)) l0)\n\nl1 :: Samples (Samples Double)\nl1 = normalizeH $ mkSamples $ \\h u -> get s1 h u * get (sample' $ prior) h u\n\n-- >>> toGnuPlot \"ground.dat\" ground\n-- >>> toGnuPlot \"l0.dat\" l0\n-- >>> toGnuPlot \"s1.dat\" s1\n-- >>> toGnuPlot \"l1.dat\" l1\n\n\n\n", "meta": {"hexsha": "a6f85b9fba656c742dd56a71d101d9fdda44e2b8", "size": 2691, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Models/RSA2d.hs", "max_stars_repo_name": "juliangrove/grove-bernardy-bayesian-semantics-tlc", "max_stars_repo_head_hexsha": "70efc3f8fcdf28a4560c77a9a4c089f3e978ff74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Models/RSA2d.hs", "max_issues_repo_name": "juliangrove/grove-bernardy-bayesian-semantics-tlc", "max_issues_repo_head_hexsha": "70efc3f8fcdf28a4560c77a9a4c089f3e978ff74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Models/RSA2d.hs", "max_forks_repo_name": "juliangrove/grove-bernardy-bayesian-semantics-tlc", "max_forks_repo_head_hexsha": "70efc3f8fcdf28a4560c77a9a4c089f3e978ff74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.91, "max_line_length": 124, "alphanum_fraction": 0.646228168, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5880439182051167}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeOperators #-}\n{-# OPTIONS_GHC -Wno-redundant-constraints #-}\n\nmodule Backprop.Learn.Loss (\n -- * Loss functions\n Loss\n , crossEntropy, crossEntropy1\n , squaredError, absError, totalSquaredError, squaredErrorV\n -- , totalCov\n -- ** Manipulate loss functions\n , scaleLoss\n , sumLoss\n , sumLossDecay\n , lastLoss\n , zipLoss\n , t2Loss\n -- * Regularization\n , Regularizer\n , l2Reg\n , l1Reg\n , noReg\n -- ** Manipulate regularizers\n , addReg\n , scaleReg\n ) where\n\nimport Backprop.Learn.Regularize\nimport Control.Applicative\nimport Data.Coerce\nimport Data.Finite\nimport Data.Type.Tuple\nimport GHC.TypeNats\nimport Lens.Micro\nimport Numeric.Backprop\nimport Numeric.LinearAlgebra.Static.Backprop\nimport qualified Data.Vector.Sized as SV\nimport qualified Prelude.Backprop as B\n\ntype Loss a = forall s. Reifies s W => a -> BVar s a -> BVar s Double\n\ncrossEntropy :: KnownNat n => Loss (R n)\ncrossEntropy targ res = -(log res <.> auto targ)\n\ncrossEntropy1 :: Loss Double\ncrossEntropy1 targ res = -(log res * auto targ + log (1 - res) * auto (1 - targ))\n\nsquaredErrorV :: KnownNat n => Loss (R n)\nsquaredErrorV targ res = e <.> e\n where\n e = res - auto targ\n\ntotalSquaredError\n :: (Backprop (t Double), Num (t Double), Foldable t, Functor t)\n => Loss (t Double)\ntotalSquaredError targ res = B.sum (e * e)\n where\n e = auto targ - res\n\nsquaredError :: Loss Double\nsquaredError targ res = (res - auto targ) ** 2\n\nabsError :: Loss Double\nabsError targ res = abs (res - auto targ)\n\n-- -- | Sum of covariances between matching components. Not sure if anyone\n-- -- uses this.\n-- totalCov :: (Backprop (t Double), Foldable t, Functor t) => Loss (t Double)\n-- totalCov targ res = -(xy / fromIntegral n - (x * y) / fromIntegral (n * n))\n-- where\n-- x = auto $ sum targ\n-- y = B.sum res\n-- xy = B.sum (auto targ * res)\n-- n = length targ\n\n-- klDivergence :: Loss Double\n-- klDivergence =\n\nsumLoss\n :: (Traversable t, Applicative t, Backprop a)\n => Loss a\n -> Loss (t a)\nsumLoss l targ = sum . liftA2 l targ . sequenceVar\n\nzipLoss\n :: (Traversable t, Applicative t, Backprop a)\n => t Double\n -> Loss a\n -> Loss (t a)\nzipLoss xs l targ = sum\n . liftA3 (\\\u03b1 t -> (* auto \u03b1) . l t) xs targ\n . sequenceVar\n\nsumLossDecay\n :: forall n a. (KnownNat n, Backprop a)\n => Double\n -> Loss a\n -> Loss (SV.Vector n a)\nsumLossDecay \u03b2 = zipLoss $ SV.generate (\\i -> \u03b2 ** (fromIntegral i - n))\n where\n n = fromIntegral $ maxBound @(Finite n)\n\nlastLoss\n :: forall n a. (KnownNat (n + 1), Backprop a)\n => Loss a\n -> Loss (SV.Vector (n + 1) a)\nlastLoss l targ = l (SV.last targ)\n . viewVar (coerced . SV.ix @(n + 1) maxBound)\n . B.coerce @_ @(ABP (SV.Vector (n + 1)) a)\n\ncoerced :: Coercible a b => Lens' a b\ncoerced f x = coerce <$> f (coerce x)\n{-# INLINE coerced #-}\n\n-- | Scale the result of a loss function.\nscaleLoss :: Double -> Loss a -> Loss a\nscaleLoss \u03b2 l x = (* auto \u03b2) . l x\n\n-- | Lift and sum a loss function over the components of a ':&'.\nt2Loss\n :: (Backprop a, Backprop b)\n => Loss a -- ^ loss on first component\n -> Loss b -- ^ loss on second component\n -> Loss (a :# b)\nt2Loss f g (xT :# yT) (xR :## yR) = f xT xR + g yT yR\n\n", "meta": {"hexsha": "cfbbdfd98a2f0ef0d66ad41ef12a8f44f6cccfa7", "size": 3706, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Backprop/Learn/Loss.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "src/Backprop/Learn/Loss.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "src/Backprop/Learn/Loss.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 28.2900763359, "max_line_length": 81, "alphanum_fraction": 0.5833783055, "num_tokens": 1073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5876698384710861}} {"text": "import Data.Map.Strict (Map)\nimport Numeric.LinearAlgebra\nimport LeastSquares\n\ntype VarName = String\ndata LinExpr = Var VarName Int\n | ...\ninfix 4 :==:\ndata LinContr = LinExpr :==: LinExpr\ndata QuadExpr = SumSquares LinExpr\n | ProdQuad Double QuadExpr\n | SumQuad QuadExpr QuadExpr\n\nminimize :: QuadExpr -> [LinContr]\n -> Map VarName (Vector R)\n", "meta": {"hexsha": "56c250a3a6af6fdba8db15a805306d457d9b2e0c", "size": 397, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/example1.hs", "max_stars_repo_name": "tridao/leastsquares", "max_stars_repo_head_hexsha": "05847fd78e68892b5af3e12b04200e4ff3ad17e4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-21T05:14:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T05:14:02.000Z", "max_issues_repo_path": "app/example1.hs", "max_issues_repo_name": "tridao/leastsquares", "max_issues_repo_head_hexsha": "05847fd78e68892b5af3e12b04200e4ff3ad17e4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/example1.hs", "max_forks_repo_name": "tridao/leastsquares", "max_forks_repo_head_hexsha": "05847fd78e68892b5af3e12b04200e4ff3ad17e4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-12-13T22:03:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T05:14:09.000Z", "avg_line_length": 24.8125, "max_line_length": 41, "alphanum_fraction": 0.6397984887, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5874014116994594}} {"text": "{- |\nDescription : DNA Markov models (substitution models or mutation models)\nCopyright : (c) Dominik Schrempf 2017\nLicense : GPLv3\n\nMaintainer : dominik.schrempf@gmail.com\nStability : unstable\nPortability : non-portable (not tested)\n\nThis module provides rate matrices for the most common DNA substitution models\n(they will be added according to need). They are also used as mutation models by\nthe boundary mutation model.\n\n* Changelog\n\n-}\n\nmodule DNAModel\n ( DNAModelSpec(..)\n , DNAModel(..)\n , Nuc\n , getDNAModelInfoStr\n , rateMatrix\n , dnaModelSpecGetStateFreqVec\n , dnaModelScale\n ) where\n\nimport Data.List (intercalate)\nimport Numeric.LinearAlgebra\nimport RateMatrix\n\n-- | The nucleotides.\ndata Nuc = A | C | G | T deriving (Eq, Show, Read, Ord, Bounded, Enum)\n\nnNucs :: Int\nnNucs = 1 + fromEnum (maxBound :: Nuc)\n\n-- | The DNA model specifications. E.g., for the HKY model, we only have kappa.\ndata DNAModelSpec = JC |\n -- | HKY model with transition to transversion ratio kappa.\n HKY Double StationaryDist |\n -- | GTR model with five params and state frequency vector.\n GTR Double Double Double Double Double StationaryDist\n\ninstance Show DNAModelSpec where\n show JC = \"JC\"\n show (HKY k f) = \"HKY[\" ++ show k ++ \"]\" ++ show f\n show (GTR a b c d e f) = \"GTR[\" ++ paramsStr ++ \"]\" ++ show f\n where paramsStr = intercalate \",\" (map show [a,b,c,d,e])\n\n-- | Extract stationary frequency vector of a DNA model specification 'DNAModelSpec'.\ndnaModelSpecGetStateFreqVec :: DNAModelSpec -> StationaryDist\ndnaModelSpecGetStateFreqVec JC = vector $ replicate nNucs 0.25\ndnaModelSpecGetStateFreqVec (HKY _ f) = f\ndnaModelSpecGetStateFreqVec (GTR _ _ _ _ _ f) = f\n\n-- | A rate matrix of a DNA models is called DNAModel.\ndata DNAModel = DNAModel { dnaRateMatrix :: RateMatrix\n , dnaModelSpec :: DNAModelSpec }\n\n-- | The matrix of exchangeabilities; diagonal entries are not set.\nexchangeabilityMatrix :: DNAModelSpec -> Matrix R\nexchangeabilityMatrix JC = (4><4)\n [ 0.0, 1.0, 1.0, 1.0\n , 1.0, 0.0, 1.0, 1.0\n , 1.0, 1.0, 0.0, 1.0\n , 1.0, 1.0, 1.0, 0.0 ]\nexchangeabilityMatrix (HKY k _) = (4><4)\n [ 0.0, 1.0, k, 1.0\n , 1.0, 0.0, 1.0, k\n , k, 1.0, 0.0, 1.0\n , 1.0, k, 1.0, 0.0 ]\nexchangeabilityMatrix (GTR a b c d e _) = (4><4)\n [ 0.0, a, b, c\n , a, 0.0, d, e\n , b, d, 0.0, 1.0\n , c, e, 1.0, 0.0 ]\n-- exchangeabilityMatrix _ = error \"Model not yet supported.\"\n\n-- | DNA model rate matrix normalized so that one mutation happens per unit time.\nrateMatrix :: DNAModelSpec -> DNAModel\nrateMatrix s = DNAModel rm s\n where\n f = dnaModelSpecGetStateFreqVec s\n exch = exchangeabilityMatrix s\n rm = normalizeRates f $ setDiagonal $ exch <> diag f\n-- rateMatrix _ _ = error \"Model not yet supported.\"\n\n-- | Report a specific model.\ngetDNAModelInfoStr :: DNAModel -> String\ngetDNAModelInfoStr (DNAModel m s) =\n case s of\n JC -> unlines\n [ \"JC model with rate matrix\"\n , show m ]\n (HKY k f) -> unlines\n [ \"HKY model\"\n , reportRateMatrix\n , reportExchangeabilityMatrix\n , reportStateFreqVec f\n , \"And a kappa value of: \" ++ show k ]\n (GTR a b c d e f) -> unlines\n [ \"GTR model\"\n , reportRateMatrix\n , reportExchangeabilityMatrix\n , reportStateFreqVec f\n , \"And parameters: \" ++ intercalate \", \" (map show [a,b,c,d,e]) ]\n -- _ -> error \"Model not yet supported.\"\n where reportRateMatrix = \"Rate matrix \" ++ show m\n reportStateFreqVec f = \"This corresponds to state frequencies (A, C, G, T): \" ++ show f\n reportExchangeabilityMatrix = \"Exchangeability matrix (diagonal set to 0.0) \" ++\n show (exchangeabilityMatrix s)\n\n-- | Scale a DNA model.\ndnaModelScale :: Double -> DNAModel -> DNAModel\ndnaModelScale s (DNAModel rm spec) = DNAModel (scale s rm) scaledSpec\n where scaledSpec = case spec of\n JC -> JC\n HKY k f -> HKY (s*k) f\n GTR a b c d e f -> GTR (s*a) (s*b) (s*c) (s*d) (s*e) f\n", "meta": {"hexsha": "74d7ca1d70c9927dc6446c5624d0484a00e419a9", "size": 4252, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/DNAModel.hs", "max_stars_repo_name": "dschrempf/bmm-simulate", "max_stars_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-14T15:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T15:53:08.000Z", "max_issues_repo_path": "src/DNAModel.hs", "max_issues_repo_name": "pomo-dev/bmm-simulate", "max_issues_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DNAModel.hs", "max_forks_repo_name": "pomo-dev/bmm-simulate", "max_forks_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1404958678, "max_line_length": 95, "alphanum_fraction": 0.6119473189, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5871840171452931}} {"text": "module Utils where\n\nimport Data.Random.Normal\nimport Numeric.LinearAlgebra\nimport System.Random\n--import Test.QuickCheck\n\ngenNormal :: (Random a, Floating a) => [a]\ngenNormal = let g = mkStdGen 1001 in\n normals g\n\ntestGenNormal :: (Random a, Floating a) => [a]\ntestGenNormal = let g = mkStdGen 1001 in\n take 10 (normals g)\n\ngetAverageMat :: Matrix R -> Double\ngetAverageMat mat =\n let r_f = fromIntegral $ rows mat\n c_f = fromIntegral $ cols mat\n sumMat = sumElements mat in\n sumMat / (r_f * c_f)\n\n", "meta": {"hexsha": "98320690ed26598298e0b4d1cc1a38028902b844", "size": 512, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "vortex/Utils.hs", "max_stars_repo_name": "neutronest/vortex", "max_stars_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-03-16T06:51:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-06T05:07:06.000Z", "max_issues_repo_path": "vortex/Utils.hs", "max_issues_repo_name": "neutronest/vortex", "max_issues_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "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": "vortex/Utils.hs", "max_forks_repo_name": "neutronest/vortex", "max_forks_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2608695652, "max_line_length": 46, "alphanum_fraction": 0.705078125, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5869749286030413}} {"text": "{-# OPTIONS_GHC -fwarn-unused-imports #-}\n\nmodule Main(main) where\n\nimport Control.Monad.Par \nimport Control.Monad.Par.Internal (runParAsync)\nimport Control.Monad.Par.Stream as S\nimport Control.Monad.Par.Logging\nimport Control.Exception\nimport Data.Complex\nimport GHC.Conc as Conc\nimport Debug.Trace\nimport Math.FFT (dft)\n\ntype Elt = Complex Double\n\nfft_kern :: Window Elt -> Window Elt\nfft_kern arr = dft arr\n\n-- -- TEMP, evaluate one element to make sure the fft really gets called:\n-- -- trace (\"One elt sample: \"++ show (arr!10)) $\n-- case arr2 ! 10 of _ -> arr2\n-- where arr2 = dft arr\n\n--------------------------------------------------------------------------------\n-- Main script\n\n-- target = maxBound\ntarget = 10 * 1000 * 1000\nbufsize = 1024\n\nmain = do\n putStrLn$ \"numCapabilities: \"++ show numCapabilities\n putStrLn$ \" Frequency in measurable ticks: \"++ commaint oneSecond ++ \"\\n\"\n\n\n putStrLn$ \"Performing FFT of \"++ commaint target ++\" numbers windowed into buffers of size \"++ show bufsize ++\"\\n\"\n\n results <- evaluate $ runParAsync$ do \n\n strm1 <- countupWin bufsize target :: Par (WStream Elt)\n\n print_$ \"\\n Next, applying FFT filter... \"\n strm2 <- streamMap fft_kern strm1 \n\n-- Make a pipeline of 10 stages:\n-- strm2 <- foldl (\\ s _ -> streamMap kern0) strm1 [1..10]\n\n print_$ \"\\n Stream graph constructed, returning from Par computation... \"\n return strm2\n\n measureRate results\n putStrLn$ \"End of stream reached. All done.\"\n\n\nprint_ msg = trace msg $ return ()\n\n-- work pop 1 peek N push 1 \n-- float->float filter \n-- firFilter n coefs = \n-- {\n\n-- float sum = 0;\n-- for (int i = 0; i < N; i++)\n-- sum += peek(i) * COEFF[N-1-i];\n-- pop();\n-- push(sum);\n-- }\n-- }\n\n\n{-\n Notes:\n\n\n\n -}\n", "meta": {"hexsha": "2fd9b92bd546c7d2a77f6f74c64e525992f49b62", "size": 1775, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/stream/fft_pipeline.hs", "max_stars_repo_name": "tpetricek/Haskell.ParMonad", "max_stars_repo_head_hexsha": "83a64b9f4bf5f80cb254eb92fb5db61271756e9c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-01-20T05:54:40.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-20T05:54:40.000Z", "max_issues_repo_path": "examples/stream/fft_pipeline.hs", "max_issues_repo_name": "tpetricek/Haskell.ParMonad", "max_issues_repo_head_hexsha": "83a64b9f4bf5f80cb254eb92fb5db61271756e9c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/stream/fft_pipeline.hs", "max_forks_repo_name": "tpetricek/Haskell.ParMonad", "max_forks_repo_head_hexsha": "83a64b9f4bf5f80cb254eb92fb5db61271756e9c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7564102564, "max_line_length": 116, "alphanum_fraction": 0.6118309859, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5869522967219097}} {"text": "module Optimization where\n\nimport Numeric.LinearAlgebra\n\nclass Optimize a where\n --optimizeInit :: a -> Double -> Double -> (Int, Int) -> a\n paramUpdate :: a -> a\n\ndata SGD = SGD {\n sgdLearningRate :: Double,\n sgdDecay :: Double,\n sgdMomentum :: Double,\n sgdParams :: [Matrix R],\n sgdGparams :: [Matrix R],\n sgdDeltaPre :: [Matrix R],\n sgdBatchSize :: Double\n } \n\ninstance Optimize SGD where\n paramUpdate sgd =\n let learningRate = sgdLearningRate sgd in\n let decay = sgdDecay sgd in\n let momentum = sgdMomentum sgd in\n let params = sgdParams sgd in\n let gparams = sgdGparams sgd in\n let deltaPre = sgdDeltaPre sgd in\n let batchSize = sgdBatchSize sgd in\n let _sgd (px:pxs) (gx: gxs) (dx:dxs) paUpdate deUpdate gaZeros =\n let r = rows gx in\n let c = cols gx in\n let lrMat = (r >< c) [learningRate..]:: (Matrix R) in\n let batchSizeMat = (r >< c) [batchSize..] :: (Matrix R) in\n let momMat = (r >< c) [momentum..] :: (Matrix R) in\n let gUp = gx * lrMat / batchSizeMat in\n let ugd = momMat * dx - gx in\n let pu = px + ugd in _sgd pxs gxs dxs (paUpdate++[pu]) (deUpdate++[ugd]) (gaZeros++[(r >< c) [0..]])\n _sgd [] [] [] paUpdate deUpdate gaZeros = SGD {\n sgdLearningRate=learningRate,\n sgdDecay=decay,\n sgdMomentum=momentum,\n sgdParams=paUpdate,\n sgdGparams=gaZeros,\n sgdDeltaPre=deUpdate,\n sgdBatchSize=0\n } in\n _sgd params gparams deltaPre [] [] []\n\n\ndata Adadelta = Adadelta {\n adaDecay :: Double,\n adaEpsilon :: Double,\n adaBatchSize :: Double,\n adaParams :: [Matrix R],\n adaGparams :: [Matrix R],\n adaAccGrad :: [Matrix R],\n adaAccDelta :: [Matrix R]\n }\n\n\ninstance Optimize Adadelta where\n paramUpdate ada =\n let decay = adaDecay ada in\n let epsilon = adaEpsilon ada in\n let batchSize = adaBatchSize ada in\n let params = adaParams ada in\n let gparams = adaGparams ada in\n let accGrad = adaAccGrad ada in\n let accDelta = adaAccDelta ada in\n let _ada (px:pxs) (gx:gxs) (accgx:accgxs) (accdx:accdxs) paUpdate gradUpdate deltaUpdate gaZeros =\n let r = rows px in\n let c = cols px in\n let decayMat = (r >< c) [decay ..] :: (Matrix R) in\n let epsilonMat = (r >< c) [epsilon ..] :: (Matrix R) in\n let batchSizeMat = (r >< c) [batchSize ..] :: (Matrix R) in\n let oneMat = (r >< c) [1.0 ..]:: (Matrix R) in\n let gUp = accgx / batchSizeMat in \n let gradUp = decayMat * accgx + (oneMat - decayMat) * gUp * gUp in\n let ugd = (cmap (\\x -> -(sqrt x)) (accdx + epsilonMat)) / (cmap (\\x -> sqrt x) (accgx + epsilonMat)) * gUp in\n let deltaUp = decayMat * accdx + (oneMat - decayMat) * ugd * ugd in\n let pu = px + ugd in\n _ada pxs gxs accgxs accdxs (pu:paUpdate) (gradUp:gradUpdate) (deltaUp:deltaUpdate) (((r >< c)[0.0 ..]):gaZeros)\n _ada [] [] [] [] paUpdate gradUpdate deltaUpdate gaZeros = Adadelta {\n adaDecay=decay,\n adaEpsilon=epsilon,\n adaBatchSize=batchSize,\n adaParams=(reverse paUpdate),\n adaGparams=(reverse gaZeros),\n adaAccGrad=(reverse gradUpdate),\n adaAccDelta=(reverse deltaUpdate)\n }\n in _ada params gparams accGrad accDelta [] [] [] [] \n", "meta": {"hexsha": "86e19ff32edfa6408dc8f84e29680c24ec6995ea", "size": 3455, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "vortex/Optimization.hs", "max_stars_repo_name": "neutronest/vortex", "max_stars_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-03-16T06:51:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-06T05:07:06.000Z", "max_issues_repo_path": "vortex/Optimization.hs", "max_issues_repo_name": "neutronest/vortex", "max_issues_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "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": "vortex/Optimization.hs", "max_forks_repo_name": "neutronest/vortex", "max_forks_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5543478261, "max_line_length": 121, "alphanum_fraction": 0.5742402315, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471132, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5869502935329439}} {"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module : Statistics.Distribution.Normal\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- The normal distribution. This is a continuous probability\n-- distribution that describes data that cluster around a mean.\n\nmodule Statistics.Distribution.Normal\n (\n NormalDistribution\n -- * Constructors\n -- , normalDistr\n --, normalDistrE\n , standard\n ) where\n\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.MathFunctions.Constants (m_sqrt_2, m_sqrt_2_pi)\nimport Numeric.SpecFunctions (erfc, invErfc)\n\nimport qualified Statistics.Distribution as D\nimport Statistics.Internal\n\n\n-- | The normal distribution.\ndata NormalDistribution = ND {\n mean :: {-# UNPACK #-} !Double\n , stdDev :: {-# UNPACK #-} !Double\n , ndPdfDenom :: {-# UNPACK #-} !Double\n , ndCdfDenom :: {-# UNPACK #-} !Double\n } deriving (Eq, Typeable, Data, Generic)\n\ninstance Show NormalDistribution where\n showsPrec i (ND m s _ _) = defaultShow2 \"normalDistr\" m s i\ninstance Read NormalDistribution where\n readPrec = defaultReadPrecM2 \"normalDistr\" normalDistrE\n\ninstance D.Distribution NormalDistribution where\n cumulative = cumulative\n complCumulative = complCumulative\n\ninstance D.ContDistr NormalDistribution where\n logDensity = logDensity\n quantile = quantile\n complQuantile = complQuantile\n\n-- | Standard normal distribution with mean equal to 0 and variance equal to 1\nstandard :: NormalDistribution\nstandard = ND { mean = 0.0\n , stdDev = 1.0\n , ndPdfDenom = log m_sqrt_2_pi\n , ndCdfDenom = m_sqrt_2\n }\n\n-- | Create normal distribution from parameters.\n--\n-- IMPORTANT: prior to 0.10 release second parameter was variance not\n-- standard deviation.\nnormalDistrE :: Double -- ^ Mean of distribution\n -> Double -- ^ Standard deviation of distribution\n -> Maybe NormalDistribution\nnormalDistrE m sd\n | sd > 0 = Just ND { mean = m\n , stdDev = sd\n , ndPdfDenom = log $ m_sqrt_2_pi * sd\n , ndCdfDenom = m_sqrt_2 * sd\n }\n | otherwise = Nothing\n\nlogDensity :: NormalDistribution -> Double -> Double\nlogDensity d x = (-xm * xm / (2 * sd * sd)) - ndPdfDenom d\n where xm = x - mean d\n sd = stdDev d\n\ncumulative :: NormalDistribution -> Double -> Double\ncumulative d x = erfc ((mean d - x) / ndCdfDenom d) / 2\n\ncomplCumulative :: NormalDistribution -> Double -> Double\ncomplCumulative d x = erfc ((x - mean d) / ndCdfDenom d) / 2\n\nquantile :: NormalDistribution -> Double -> Double\nquantile d p\n | p == 0 = -inf\n | p == 1 = inf\n | p == 0.5 = mean d\n | p > 0 && p < 1 = x * ndCdfDenom d + mean d\n | otherwise =\n error $ \"Statistics.Distribution.Normal.quantile: p must be in [0,1] range. Got: \"++show p\n where x = - invErfc (2 * p)\n inf = 1/0\n\ncomplQuantile :: NormalDistribution -> Double -> Double\ncomplQuantile d p\n | p == 0 = inf\n | p == 1 = -inf\n | p == 0.5 = mean d\n | p > 0 && p < 1 = x * ndCdfDenom d + mean d\n | otherwise =\n error $ \"Statistics.Distribution.Normal.complQuantile: p must be in [0,1] range. Got: \"++show p\n where x = invErfc (2 * p)\n inf = 1/0\n", "meta": {"hexsha": "dc1d20a375338be78d350fcdd59cce0726dd3024", "size": 3642, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "statistics/Statistics/Distribution/Normal.hs", "max_stars_repo_name": "runeksvendsen/hs-gauge", "max_stars_repo_head_hexsha": "496a8b99e7fee3039fd89ecef7305d31eb5d5a6d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 94, "max_stars_repo_stars_event_min_datetime": "2017-10-29T16:51:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T08:36:20.000Z", "max_issues_repo_path": "statistics/Statistics/Distribution/Normal.hs", "max_issues_repo_name": "runeksvendsen/hs-gauge", "max_issues_repo_head_hexsha": "496a8b99e7fee3039fd89ecef7305d31eb5d5a6d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 77, "max_issues_repo_issues_event_min_datetime": "2017-09-30T15:11:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T09:34:12.000Z", "max_forks_repo_path": "statistics/Statistics/Distribution/Normal.hs", "max_forks_repo_name": "runeksvendsen/hs-gauge", "max_forks_repo_head_hexsha": "496a8b99e7fee3039fd89ecef7305d31eb5d5a6d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-11-04T13:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T05:44:23.000Z", "avg_line_length": 32.8108108108, "max_line_length": 99, "alphanum_fraction": 0.6131246568, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5869268962884945}} {"text": "import HVX\nimport Numeric.LinearAlgebra\n\n-- declare a symbolic variable\nx = EVar \"x\"\n-- give x a value (a 4-element column vector)\nvars = [(\"x\", (4><1) [0,-3,1,2])]\n-- define the expression to sudifferentiate: max(abs(x))\nmyexpr = hmax(habs(x))\n-- compute the subgradient\nmysubgrad = jacobianWrtVar myexpr vars \"x\"\n", "meta": {"hexsha": "30e297b0181752eb91ef77007d84223bcb1178d5", "size": 315, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/subgrad.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": "examples/subgrad.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": "examples/subgrad.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": 26.25, "max_line_length": 56, "alphanum_fraction": 0.7015873016, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5868985911271369}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule LinAlg where\n\nimport qualified Numeric.LinearAlgebra as L\n\nimport Data.Complex\nimport Data.List\n\nclass Vector v where\n -- vector addition\n (<+>) :: v -> v -> v \n -- scalar multiplication\n (<**>) :: Complex Double -> v -> v\n -- additive inverse \n vneg :: v -> v\n (<~>) :: v -> v -> v\n -- vector subtraction for convenience\n u <~> v = u <+> vneg v\n\nclass Vector v => Hilbert v where\n -- Inner product\n (<.>) :: v -> v -> Complex Double\n -- Vector norm, default definition generates norm\n -- from inner product\n norm :: v -> Double\n norm v = sqrt . magnitude $ v <.> v\n\n-- Data structure representing a generic linear operator\n-- in some representation\nnewtype Operator r = Operator {\n repr :: r \n} \n\ninstance Functor Operator where\n fmap f (Operator r) = Operator $ f r\n\ninstance Applicative Operator where\n pure = Operator\n (Operator f) <*> op = f <$> op\n\n-- Type alias for matrix representation of operator\ntype MatOp = Operator (L.Matrix (Complex Double))\n\n-- Allow operators to be composed\ninstance Semigroup r => Semigroup (Operator r) where\n (Operator r1) <> (Operator r2) = Operator (r1 <> r2)\n\n-- Operators are vectors\ninstance Vector MatOp where\n o1 <+> o2 = Operator (repr o1 + repr o2)\n a <**> o = L.cmap (*a) <$> o\n vneg o = negate <$> o\n\n-- Trace of an operator \ntrace :: MatOp -> Complex Double\ntrace = L.sumElements . L.takeDiag . repr", "meta": {"hexsha": "00a8b2bd42249c1925ede531e507610d88d97c80", "size": 1556, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/LinAlg.hs", "max_stars_repo_name": "Jvanrhijn/optiqs", "max_stars_repo_head_hexsha": "6473f8b75bd43b6e6407dfc0b137feeee6592dee", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LinAlg.hs", "max_issues_repo_name": "Jvanrhijn/optiqs", "max_issues_repo_head_hexsha": "6473f8b75bd43b6e6407dfc0b137feeee6592dee", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinAlg.hs", "max_forks_repo_name": "Jvanrhijn/optiqs", "max_forks_repo_head_hexsha": "6473f8b75bd43b6e6407dfc0b137feeee6592dee", "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": 25.9333333333, "max_line_length": 56, "alphanum_fraction": 0.6362467866, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.586730283641098}} {"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}\n\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule Test.Grenade.Layers.Add where\n\nimport Data.Constraint\nimport Data.Maybe (fromJust)\nimport Data.Proxy\nimport Unsafe.Coerce\n\nimport GHC.TypeLits\n\nimport Grenade.Core\nimport Grenade.Layers.Add\n\nimport Numeric.LinearAlgebra hiding (R, konst, randomVector,\n uniformSample, (===), reshape)\nimport qualified Numeric.LinearAlgebra.Data as D\nimport Numeric.LinearAlgebra.Static (L, R)\nimport qualified Numeric.LinearAlgebra.Static as H\n\nimport Hedgehog\n\nimport Test.Hedgehog.Compat\nimport Test.Hedgehog.Hmatrix\n\nprop_add_zero_does_nothing = property $ do\n height :: Int <- forAll $ choose 2 100\n width :: Int <- forAll $ choose 2 100\n channels :: Int <- forAll $ choose 2 100\n\n case (someNatVal (fromIntegral height), someNatVal (fromIntegral width), someNatVal (fromIntegral channels)) of\n (Just (SomeNat (Proxy :: Proxy h)), Just (SomeNat (Proxy :: Proxy w)), Just (SomeNat (Proxy :: Proxy c))) -> do\n input :: S ('D3 h w c) <- forAll genOfShape\n\n let layer = initAdd :: Add c 1 1\n S3D out = snd $ runForwards layer input :: S ('D3 h w c)\n S3D inp' = input :: S ('D3 h w c)\n\n H.extract inp' === H.extract out\n\nprop_add_per_channel_words_as_expected = property $ do\n height :: Int <- forAll $ choose 2 100\n width :: Int <- forAll $ choose 2 100\n\n case (someNatVal (fromIntegral height), someNatVal (fromIntegral width)) of\n (Just (SomeNat (Proxy :: Proxy h)), Just (SomeNat (Proxy :: Proxy w))) ->\n case ( unsafeCoerce (Dict :: Dict ()) :: Dict ( (h * 3) ~ (h + h + h) ) ) of\n Dict -> do\n channel_one :: R (h * w) <- forAll randomVector\n channel_two :: R (h * w) <- forAll randomVector\n channel_three :: R (h * w) <- forAll randomVector\n bias :: R 3 <- forAll randomVector\n\n let reshape = fromJust . H.create . (D.reshape width) . H.extract\n c1 = reshape channel_one :: L h w\n c2 = reshape channel_two :: L h w\n c3 = reshape channel_three :: L h w\n\n bias' = H.extract bias\n\n o1 = H.dmmap (\\a -> a + bias' ! 0) c1 :: L h w\n o2 = H.dmmap (\\a -> a + bias' ! 1) c2 :: L h w\n o3 = H.dmmap (\\a -> a + bias' ! 2) c3 :: L h w\n\n out = o1 H.=== o2 H.=== o3 :: L (h * 3) w\n inp = c1 H.=== c2 H.=== c3 :: L (h * 3) w\n\n layer = Add bias :: Add 3 1 1\n inp' = S3D inp :: S ('D3 h w 3)\n S3D out' = snd $ runForwards layer inp' :: S ('D3 h w 3)\n\n H.extract out === H.extract out'\n\ntests :: IO Bool\ntests = checkParallel $$(discover)\n", "meta": {"hexsha": "766dc6f4a57dfc131bb27d1c6e0208f4382f2d52", "size": 3290, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Layers/Add.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "test/Test/Grenade/Layers/Add.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Test/Grenade/Layers/Add.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.816091954, "max_line_length": 115, "alphanum_fraction": 0.5455927052, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5866814625919596}} {"text": "{-# LANGUAGE OverloadedStrings, NoImplicitPrelude, BangPatterns #-}\nimport ClassyPrelude hiding (head, tail)\nimport Prelude (head, tail)\nimport Test.Hspec\nimport Test.QuickCheck\nimport qualified Criterion.Main as Criterion\nimport Lens.Micro\n\nimport Control.Exception (evaluate)\nimport qualified Data.Vector.Storable as SVec\nimport qualified Data.Vector.Generic as Vec\nimport qualified Data.Binary as Bin\n\nimport NLP.Albemarle\nimport qualified NLP.Albemarle.Tokens as Tokens\nimport NLP.Albemarle.Dict (Dict, counts, ids)\nimport qualified NLP.Albemarle.Dict as Dict\nimport NLP.Albemarle.LSA (termvectors, topicweights)\nimport qualified NLP.Albemarle.LSA as LSA\nimport qualified NLP.Albemarle.Bench.Maps\nimport qualified NLP.Albemarle.Test.Dict\nimport qualified NLP.Albemarle.Test.GloVe\nimport qualified NLP.Albemarle.Test.LanguageModelEntropy\nimport qualified NLP.Albemarle.Examples.Webpage\n\nimport System.CPUTime\nimport Text.Printf\nimport Data.Text.Encoding.Error (lenientDecode)\nimport System.Directory (doesFileExist)\n\nimport qualified Data.Text as Text\nimport qualified Data.HashSet as HashSet\nimport qualified Data.HashMap.Strict as HashMap\nimport System.IO.Streams (InputStream, OutputStream)\nimport qualified System.IO.Streams as Streams\nimport Numeric.LinearAlgebra (Matrix)\nimport qualified Numeric.LinearAlgebra as HMatrix\n\nmain :: IO ()\nmain = hspec $ do\n NLP.Albemarle.Examples.Webpage.test\n NLP.Albemarle.Test.Dict.test\n NLP.Albemarle.Test.GloVe.test\n NLP.Albemarle.Test.LanguageModelEntropy.test\n\n let sentences = words <$> [\n \"Maybe not today. Maybe not tomorrow. But soon.\",\n \"Pay no attention to the man behind the curtain.\",\n \"Life is like a box of chocolates.\"]:: [[Text]]\n\n describe \"Streaming (semi-Gensim) Style Topic Analysis\" $ do\n let mean :: SVec.Vector Double -> Double\n mean x = Vec.sum x / fromIntegral (Vec.length x)\n -- Root mean squared error\n rmse l r = mean (Vec.zipWith (\\x y -> (x-y)**2) (flat l) (flat r)) ** 0.5\n -- Mean signal to noise ratio\n -- - we tank the PSNR because most things are really close to 0\n -- - in fact we avoid handling 0's altogether\n msnr l r = mean $ Vec.zipWith (\\x y -> abs $ x-y / max 1 (min x y)) (flat l) (flat r)\n flat = HMatrix.flatten\n mult u s vt = mconcat [u, HMatrix.diag s, HMatrix.tr vt] :: HMatrix.Matrix Double\n\n it \"performs sparse stochastic truncated SVD with SVDLIBC\" $ do\n let termdoc = \"termdoc.small.nonzero.txt\"\n [zippedfile, originalfile] <- sequence $ doesFileExist <$> [termdoc++\".gz\", termdoc]\n when ( zippedfile && not originalfile ) $\n Streams.withFileAsInput \"termdoc.small.nonzero.txt.gz\" $ \\infl ->\n Streams.withFileAsOutput \"termdoc.small.nonzero.txt\" $ \\outfl ->\n Streams.gunzip infl >>= Streams.connectTo outfl\n matrix <- HMatrix.loadMatrix \"termdoc.small.nonzero.txt\"\n let (u, sigma, vt) = LSA.batchLSA 100 $ LSA.sparsify matrix\n -- typically -> RMSE: 0.06464712163523892\n -- printf \"RMSE: %f\\n\" $ rmse (mconcat [u, HMatrix.diag sigma, HMatrix.tr vt]) matrix\n rmse (mult u sigma vt) matrix < 0.12 `shouldBe` True\n -- typically -> MSNR: 0.010548326765305554\n -- printf \"MSNR: %f\\n\" $ msnr (mconcat [u, HMatrix.diag sigma, HMatrix.tr vt]) matrix\n msnr (mult u sigma vt) matrix < 0.02 `shouldBe` True\n\n it \"performs topic analysis starting from text\" $ do\n (final_dict, model) <- Streams.withFileAsInput \"kjv.verses.txt.gz\" $ \\file ->\n Streams.gunzip file\n >>= Streams.lines\n >>= Streams.decodeUtf8With lenientDecode\n >>= Streams.map Tokens.wordTokenize\n >>= Streams.chunkList 373 -- Yep, I'm making this stuff up.\n >>= Streams.map (\\chunk -> let\n dict = Dict.dictifyAllWords chunk\n sparsem = Dict.asSparseMatrix dict chunk\n lsa = LSA.lsa 222 sparsem -- Too many topics. Should not cause errors\n in (dict, lsa))\n >>= Streams.fold (\\(!d1, !lsa1) (d2, lsa2) -> let\n d3 = Dict.filterDict 2 0.5 100 $ d1 <> d2 -- Not nearly enough words\n lsa3 = LSA.rebase d1 d3 lsa1 <> LSA.rebase d2 d3 lsa2\n in (d3, lsa3)) (mempty, mempty)\n\n -- It should use all 100 words allowed plus the unknown\n HashMap.size (final_dict^.counts) `shouldBe` 101\n -- It should have a full size LSA as well\n HMatrix.size (model^.termvectors) `shouldBe` (222, 101)\n -- Plus topic weights\n HMatrix.size (model^.topicweights) `shouldBe` 222\n\n describe \"Monoid style Topic Analysis\" $\n it \"creates LSA Models\" $ do\n let dict = Dict.dictifyAllWords sentences\n let lsavecs = LSA.lsa 2\n $ Dict.asSparseMatrix dict sentences\n -- Sadly, I can't think of much to assert in this test so let's use size\n -- There are 21 unique words plus one unknown\n HMatrix.size (lsavecs^.termvectors) `shouldBe` (2,22)\n -- It should use both topics\n HMatrix.size (lsavecs^.topicweights) `shouldBe` 2\n\n-- Thanks to Ying He for the following example text and proper\n-- tokenizations.\n--weightGain :: Text\n--weightGain = unwords [\n-- \"Independent of current body composition, IGF-I levels at 5 yr were \",\n-- \"significantly associated with rate of weight gain between 0-2 yr\",\n-- \"(beta = 0.19; P < 0.0005), and children who showed postnatal\",\n-- \"catch-up growth (i.e. those who showed gains in weight or length\",\n-- \"between 0-2 yr by >0.67 SD score) had higher IGF-I levels than other\",\n-- \"children (P = 0.02).\"]\n\n--weightGainTokens :: [Text]\n--weightGainTokens = words $ unwords [\n-- \"Independent of current body composition , IGF - I levels at 5 yr were\",\n-- \"significantly associated with rate of weight gain between 0 - 2 yr ( beta\",\n-- \"= 0.19 ; P < 0.0005 ) , and children who showed postnatal catch - up\",\n-- \"growth ( i.e . those who showed gains in weight or length between 0 - 2 yr\",\n-- \"by > 0.67 SD score ) had higher IGF - I levels than other children\",\n-- \"( P = 0.02 ) .\"] -- i.e. is wrong, but we're calling this close enough.\n", "meta": {"hexsha": "99487ff2d8517ebd20eb21214cef6073df7b982d", "size": 6064, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/NLP/Albemarle/Spec.hs", "max_stars_repo_name": "SeanTater/albemarle", "max_stars_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-07-16T15:06:24.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-19T00:51:45.000Z", "max_issues_repo_path": "test/NLP/Albemarle/Spec.hs", "max_issues_repo_name": "SeanTater/albemarle", "max_issues_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-05-05T14:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-04T14:04:54.000Z", "max_forks_repo_path": "test/NLP/Albemarle/Spec.hs", "max_forks_repo_name": "SeanTater/albemarle", "max_forks_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5939849624, "max_line_length": 93, "alphanum_fraction": 0.6835422164, "num_tokens": 1715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969193, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5865067891958627}} {"text": "module Gradient\n (numericalDiff\n ) where\n\nimport Numeric.LinearAlgebra\n\nnumericalDiff :: Fractional a => (a -> a) -> a -> a\nnumericalDiff f x = (f (x+h) - f (x-h)) / (2*h)\n where h = 1e-4\n", "meta": {"hexsha": "12c052f03143a16dd24d1c88dada2d03250d5220", "size": 197, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Gradient.hs", "max_stars_repo_name": "ku00/deep-learning-practice", "max_stars_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-03T05:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T05:32:58.000Z", "max_issues_repo_path": "src/Gradient.hs", "max_issues_repo_name": "ku00/deep-learning-practice", "max_issues_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Gradient.hs", "max_forks_repo_name": "ku00/deep-learning-practice", "max_forks_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7, "max_line_length": 51, "alphanum_fraction": 0.5989847716, "num_tokens": 70, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.5859352473952018}} {"text": "{-# LANGUAGE TypeOperators #-}\nmodule Vect\n ( module Vect\n ) where\n\nimport Control.Arrow (first, second)\nimport Control.Monad (ap)\nimport Data.Complex\nimport Data.List (intercalate, sortOn)\nimport GHC.TypeLits\n\nimport QBasis\n\ntype C = Complex Double\n\n-- |Free vector space over field\nnewtype Vect k b = V [(b, k)] deriving (Eq, Ord)\n\ninstance (Show k, Show b) => Show (Vect k b) where\n show (V xs) = intercalate \" + \" $ map (\\(e, c) -> show c ++ show e) xs\n\ninstance Functor (Vect k) where\n fmap f (V xs) = V $ map (first f) xs\n\ninstance Num k => Applicative (Vect k) where\n pure = return\n (<*>) = ap\n\ninstance Num k => Monad (Vect k) where\n return a = V [(a, 1)]\n V ts >>= f = V $ concat [ [(b, y*x) | let V us = f a, (b, y) <- us] | (a, x) <- ts]\n\n-- |Convert an element of Vect k b into normal form. Normal form consists in having the basis elements in ascending order,\n-- with no duplicates, and all coefficients non-zero\nnf :: (Ord b, Eq k, Num k) => Vect k b -> Vect k b\nnf (V ts) = V $ nf' $ sortOn fst ts where\n nf' ((b1,x1):(b2,x2):ts) =\n case compare b1 b2 of\n LT -> if x1 == 0 then nf' ((b2,x2):ts) else (b1,x1) : nf' ((b2,x2):ts)\n EQ -> if x1+x2 == 0 then nf' ts else nf' ((b1,x1+x2):ts)\n GT -> error \"nf': not pre-sorted\"\n nf' [(b,x)] = if x == 0 then [] else [(b,x)]\n nf' [] = []\n\n-- |The zero vector\nzero :: Vect k b\nzero = V []\n\n-- |Vector addition\nadd :: (Ord b, Num k, Eq k) => Vect k b -> Vect k b -> Vect k b\nadd (V ts) (V us) = V $ addmerge ts us\n where addmerge axs@((a,x):xs) bxs@((b,y):ys) =\n case compare a b of\n LT -> (a,x) : addmerge xs bxs\n EQ -> if x+y == 0\n then addmerge xs ys\n else (a, x+y) : addmerge xs ys\n GT -> (b,y) : addmerge axs ys\n addmerge xs [] = xs\n addmerge [] ys = ys\n\n-- |(Left) Scalar multiplication\nsmult :: (Eq k, Num k) => k -> Vect k b -> Vect k b\nsmult 0 _ = zero\nsmult k (V xs) = V $ map (second (k*)) xs\n\n-- |Linear application to basis elements\nlinear :: (Ord b, Eq k, Num k) => (a -> Vect k b) -> Vect k a -> Vect k b\nlinear f v = nf $ v >>= f\n\n-- |Tensor product of two free vector spaces\nte :: (Num k, Eq k) => Vect k (QBasis m) -> Vect k (QBasis n) -> Vect k (QBasis (m+n))\nte (V u) (V v) = V [(a `tb` b, x*y) | (a,x) <- u, (b,y) <- v]\n\n-- |Tensor product of two functions between free vector spaces\ntf :: (Num k, Eq k, KnownNat m) =>\n (Vect k (QBasis m) -> Vect k (QBasis m)) ->\n (Vect k (QBasis n) -> Vect k (QBasis n)) ->\n Vect k (QBasis (m+n))-> Vect k (QBasis (m+n))\ntf f g (V ts) = sum [let (a,b) = bt basis in smult x (f (return a) `te` g (return b)) | (basis,x) <- ts]\n where sum = foldl add zero", "meta": {"hexsha": "6892154d4d2e64c2ffe9b66de84831addf1451fb", "size": 2787, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Vect.hs", "max_stars_repo_name": "caldwellwg/Aqua", "max_stars_repo_head_hexsha": "d7e2eb41981428c95690253cdf2fae5227c0ce7a", "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/Vect.hs", "max_issues_repo_name": "caldwellwg/Aqua", "max_issues_repo_head_hexsha": "d7e2eb41981428c95690253cdf2fae5227c0ce7a", "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/Vect.hs", "max_forks_repo_name": "caldwellwg/Aqua", "max_forks_repo_head_hexsha": "d7e2eb41981428c95690253cdf2fae5227c0ce7a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4074074074, "max_line_length": 122, "alphanum_fraction": 0.5407247937, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5857966295593453}} {"text": "import Data.Complex\n\nmain = do\n let a = 1.0 :+ 2.0 -- complex number 1+2i\n let b = 4 -- complex number 4+0i\n -- 'b' is inferred to be complex because it's used in\n -- arithmetic with 'a' below.\n putStrLn $ \"Add: \" ++ show (a + b)\n putStrLn $ \"Subtract: \" ++ show (a - b)\n putStrLn $ \"Multiply: \" ++ show (a * b)\n putStrLn $ \"Divide: \" ++ show (a / b)\n putStrLn $ \"Negate: \" ++ show (-a)\n putStrLn $ \"Inverse: \" ++ show (recip a)\n putStrLn $ \"Conjugate:\" ++ show (conjugate a)\n", "meta": {"hexsha": "3bcc29321b4c7fb264c3c56634b30f1add5148c6", "size": 512, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lang/Haskell/arithmetic-complex.hs", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "lang/Haskell/arithmetic-complex.hs", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Haskell/arithmetic-complex.hs", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 34.1333333333, "max_line_length": 55, "alphanum_fraction": 0.55078125, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5857094738655775}} {"text": "{-# OPTIONS_GHC -Wall #-}\n\n-- | Ring classes. A distinguishment is made between Rings and Commutative Rings.\nmodule Plankton.Ring\n ( Semiring\n , Ring\n , CRing\n ) where\n\nimport Data.Complex (Complex(..))\nimport Plankton.Additive\nimport Plankton.Distribution\nimport Plankton.Multiplicative\nimport Protolude (Bool(..), Double, Float, Int, Integer)\n\n-- | Semiring\nclass (MultiplicativeAssociative a, MultiplicativeUnital a, Distribution a) =>\n Semiring a\n\ninstance Semiring Double\n\ninstance Semiring Float\n\ninstance Semiring Int\n\ninstance Semiring Integer\n\ninstance Semiring Bool\n\ninstance (AdditiveGroup a, Semiring a) => Semiring (Complex a)\n\n-- | Ring\n-- a summary of the laws inherited from the ring super-classes\n--\n-- > zero + a == a\n-- > a + zero == a\n-- > (a + b) + c == a + (b + c)\n-- > a + b == b + a\n-- > a - a = zero\n-- > negate a = zero - a\n-- > negate a + a = zero\n-- > a + negate a = zero\n-- > one `times` a == a\n-- > a `times` one == a\n-- > (a `times` b) `times` c == a `times` (b `times` c)\n-- > a `times` (b + c) == a `times` b + a `times` c\n-- > (a + b) `times` c == a `times` c + b `times` c\n-- > a `times` zero == zero\n-- > zero `times` a == zero\nclass ( AdditiveGroup a\n , MultiplicativeAssociative a\n , MultiplicativeUnital a\n , Distribution a\n ) =>\n Ring a\n\ninstance Ring Double\n\ninstance Ring Float\n\ninstance Ring Int\n\ninstance Ring Integer\n\ninstance (Ring a) => Ring (Complex a)\n\n-- | CRing is a Ring with Multiplicative Commutation. It arises often due to '*' being defined as a multiplicative commutative operation.\nclass (Multiplicative a, Ring a) =>\n CRing a\n\ninstance CRing Double\n\ninstance CRing Float\n\ninstance CRing Int\n\ninstance CRing Integer\n\ninstance (CRing a) => CRing (Complex a)\n", "meta": {"hexsha": "f81e1319cf24dfb0b8b37be46f9db26bb336efe8", "size": 1755, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Plankton/Ring.hs", "max_stars_repo_name": "chessai/plankton", "max_stars_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T05:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T05:38:15.000Z", "max_issues_repo_path": "src/Plankton/Ring.hs", "max_issues_repo_name": "chessai/plankton", "max_issues_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "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/Plankton/Ring.hs", "max_forks_repo_name": "chessai/plankton", "max_forks_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9375, "max_line_length": 138, "alphanum_fraction": 0.6524216524, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.585489997205791}} {"text": "-- Modulo destinado a todas as funcoes relativas a execucao da Rede.\n\nmodule Execution\n(execute,\n feedforward) where\n\nimport InputOutput\nimport Types\nimport Numeric.LinearAlgebra.HMatrix\n\ntype Image = [Double]\ntype Sample = (Int, Image)\n\n-- execute, por retornar IO, pode interagir chamando outras IO Actions como\n-- leitura dos weights, biases e input da Rede, por exemplo.\nexecute :: IO String -- mero esqueleto da funcao de execucao\nexecute = do \n network <- readIn\n let image = [1.0 .. 784.0]\n executedNetwork = feedforward image network\n do definitiveAnswer executedNetwork \n\n-- recebe a imagem, a network e computa os calculos,\n-- retornando a nova data com os valores de ativacao\n-- e zeta do hidden e output alterados.\nfeedforward :: Image -> Data -> Data \nfeedforward image network = let zH = add ((wHidden network) #> (fromList image)) (bHidden network)\n aH = fromList $ sigV (toList zH)\n zO = add ((wOutput network) #> aH) (bOutput network)\n aO = fromList $ sigV (toList zO) \n in Data (wHidden network) (bHidden network) aH zH (wOutput network) (bOutput network) aO zO", "meta": {"hexsha": "8ae1661da611d0c4e9726970e14dd59ab39a1997", "size": 1242, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Haskell/src/Execution.hs", "max_stars_repo_name": "Thulio-Carvalho/NedeReural_Haskell", "max_stars_repo_head_hexsha": "6469552ba35358aa0ffb85d36e7fe2bdd8fad477", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Haskell/src/Execution.hs", "max_issues_repo_name": "Thulio-Carvalho/NedeReural_Haskell", "max_issues_repo_head_hexsha": "6469552ba35358aa0ffb85d36e7fe2bdd8fad477", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Haskell/src/Execution.hs", "max_forks_repo_name": "Thulio-Carvalho/NedeReural_Haskell", "max_forks_repo_head_hexsha": "6469552ba35358aa0ffb85d36e7fe2bdd8fad477", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.064516129, "max_line_length": 119, "alphanum_fraction": 0.6425120773, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.5853544786023644}} {"text": "module Ch01.Broadcast where\n\nimport Numeric.LinearAlgebra\n\nas = matrix 2 [1,2,3,4]\nbs = matrix 2 [10,20]\nr = as * bs\n\nxs :: Matrix Int\nxs = (3><2) [51,55,14,19,0,4]\n\n", "meta": {"hexsha": "95c4f5e9a5b7236964ce12effc01990d87217268", "size": 166, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Ch01/Bloadcast.hs", "max_stars_repo_name": "knih/deep-learning-from-scratch-in-haskell", "max_stars_repo_head_hexsha": "1a92a98a958744da2a04d534319b599d25225dd4", "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/Ch01/Bloadcast.hs", "max_issues_repo_name": "knih/deep-learning-from-scratch-in-haskell", "max_issues_repo_head_hexsha": "1a92a98a958744da2a04d534319b599d25225dd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Ch01/Bloadcast.hs", "max_forks_repo_name": "knih/deep-learning-from-scratch-in-haskell", "max_forks_repo_head_hexsha": "1a92a98a958744da2a04d534319b599d25225dd4", "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": 13.8333333333, "max_line_length": 29, "alphanum_fraction": 0.6385542169, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5850526058715299}} {"text": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\n\nmodule VectorSpec where\n\nimport Data.Complex\n\nimport Test.QuickCheck\nimport Test.QuickCheck.Poly\n\nimport Category\nimport Comonad\nimport Functor\nimport Unboxed\nimport Vector\n\n\n\nprop_Vector_Functor_id :: FnProp (Vector A)\nprop_Vector_Functor_id = checkFnEqual law_Functor_id\n\nprop_Vector_Functor_comp :: Fun B C -> Fun A B -> FnProp (Vector A)\nprop_Vector_Functor_comp f g = checkFnEqual (law_Functor_comp f g)\n\nprop_Vector_Semicomonad_comm ::\n Fun (Vector B) C -> Fun (Vector A) B -> FnProp (Vector A)\nprop_Vector_Semicomonad_comm f g = checkFnEqual (law_Semicomonad_comm f g)\n\nprop_Vector_Semicomonad1_comm ::\n Fun (Vector B) C -> Fun (Vector A) B -> FnProp (Vector A)\nprop_Vector_Semicomonad1_comm f g = checkFnEqual (law_Semicomonad1_comm f g)\n\nprop_Vector_Semicomonad1_comm' ::\n Fun (Vector B) C -> Fun (Vector A) B -> FnProp (Vector A)\nprop_Vector_Semicomonad1_comm' (Fn f) (Fn g) =\n checkFnEqual (law_Semicomonad1_comm' f g)\n\n\n\ntype UA = Int\ntype UB = Double\ntype UC = Complex Double\n\nprop_UVector_Functor_id :: FnProp (UVector UA)\nprop_UVector_Functor_id = checkFnEqual law_Functor_id\n\nprop_UVector_Functor_comp ::\n (UB -#> UC) -> (UA -#> UB) -> FnProp (UVector UA)\nprop_UVector_Functor_comp f g = checkFnEqual (law_Functor_comp f g)\n\nprop_UVector_Semicomonad1_comm' ::\n Fun (UVector UB) UC -> Fun (UVector UA) UB -> FnProp (UVector UA)\nprop_UVector_Semicomonad1_comm' (Fn f) (Fn g) =\n checkFnEqual (law_Semicomonad1_comm' f g)\n", "meta": {"hexsha": "14a8881d572a26638a87bd0709571e2399fc7646", "size": 1501, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/VectorSpec.hs", "max_stars_repo_name": "eschnett/wavetoy6", "max_stars_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/VectorSpec.hs", "max_issues_repo_name": "eschnett/wavetoy6", "max_issues_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/VectorSpec.hs", "max_forks_repo_name": "eschnett/wavetoy6", "max_forks_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7962962963, "max_line_length": 76, "alphanum_fraction": 0.7541638907, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.7154239957834732, "lm_q1q2_score": 0.584912411329019}} {"text": "{-# LANGUAGE RecordWildCards #-}\n{-\nThe shape of a triangle can be represented by two explicit points (ie vectors)\nand a third implicit point at (0,0). A triangle defined by three points can be\nconverted by subtracting one of the points from the others:\n shape (p1,p2,p3) = (p2-p1, p3-p1)\nThis keeps the shape intact but drops the position of the triangle.\n\nIf P and Q are two such triangles, there exists a matrix A that transforms\nP into Q: AP = Q\nThe 'A' matrix can be calculated by multiplying Q and the inverse of P:\n A = QP_inv\n\nSo, if we have a set of triangles, we can drop their positional information\nand compute their shape transformation matrices. But can we do it in reverse?\nCan we start with a set of transformation matrices (which don't give us the\npositions of the triangles) and compute a set of points that represent triangles\nwith the right transformation?\nIn other words, if we have a set of triangles (with absolute position) and\na transformation matrix for each triangle, can we compute new absolute positions\nsuch that AP=Q?\n\nSolving this is not straightforward as moving a single point will change the\ntransformation of multiple triangles. Fortunately, though, this problem can be\nexpression as linear equations and solved quickly with LAPACK.\n\nTo express the problem as a linear system, we need 4 equations for each\ntriangle and 2 unknowns for each point.\n\nThe system has this shape: Mx=B\nWe're trying to find 'x' which are the positions of the new points.\n'M' is a matrix that transforms points into transformation matrices.\n'B' is the target transformation matrices.\n\nWith a bit of rewriting, we can reduce 'A = QP_inv' to 4 linear equations\nwith 6 unknowns. The 6 unknowns are the x and y positions for the three corners\nin a triangle.\nThis is just another way of calculating the transformation matrix 'A' and we\ncan verify it by looking at the output of:\n * computeA src dst\n * applyCoeff (coeffOfB src) dst\nThe output should be the same because they're both computing 'A'.\n\n'applyCoeff' simply multiplies the coefficients by a 6x1 matrix containing\nthe x and y positions for 'dst'.\n\nSo, this means we have roughly the right shape: Mx=B. M is the coefficients\nwe found for 'src', 'x' is dst, and 'B' is the transformation matrix that\nturns 'src' into 'dst'.\nWe can get the coefficients for each triangle and place them together in a\nsingle large matrix. Then we can put the desired transformation matrices in 'B'\nand ask a linear solver to find 'x' which satisfies the equations.\n\nPhew, step one is done. We now have the machinery for turning arbitrary\ntransformation matrices into proper, connected triangles. Next step is figuring\nout which rotational matrices to use. At the two extremes, we have the identity\nmatrices (representing our starting shape) and the matrices computed from the\ntarget triangles (represetning out target shape). How can these two matrices be\ninterpolated for a smooth morph?\n\nThere are several ways of interpolating matrices. Linear interpolation is\npossible. But, it looks prettier if we separate rotation from shear. Then we\ncan use spherical linear interpolation on the rotation and linear interpolation\non the shear.\n\n-}\nmodule Reanimate.Morph.Rigid where\n\nimport Data.Foldable (toList)\nimport Data.Vector (Vector)\nimport qualified Data.Vector as V\nimport Linear.Quaternion\nimport Linear.Vector\nimport Linear.V2\nimport Linear.V3\nimport qualified Numeric.LinearAlgebra as Matrix\nimport Numeric.LinearAlgebra.HMatrix (GMatrix, Matrix,\n toLists, (!), (><))\n\ntype P = V2 Double\ntype Trig = (P,P,P)\ntype RelTrig = (Int,Int,Int)\n\ndata Mesh = Mesh\n { meshPointsA :: Vector P\n , meshPointsB :: Vector P\n , meshOutline :: Vector Int\n -- , meshSteiner :: Vector Int\n , meshTriangles :: Vector RelTrig }\n\n-- applyA (computeA a b) a = b + some_constant_translation\n-- A = Q P_inv\ncomputeA :: Trig -> Trig -> Matrix Double\ncomputeA p q = matQ <> Matrix.inv matP\n where\n matP = trigToMatrix p\n matQ = trigToMatrix q\n\n-- A = UDV = U(VV_t)DV = (UV)(V_tDV) = RS\n-- R = UV\n-- S = V_tDV\ncomputeRS :: Matrix Double -> (Matrix Double, Matrix Double)\ncomputeRS a = (r, s)\n where\n (u,d,vt) = Matrix.svd a\n v = Matrix.tr vt\n r = u <> v\n s = vt <> Matrix.diag d <> v\n\nmatrixToQuaternion :: Matrix Double -> Quaternion Double\nmatrixToQuaternion r = q\n where\n w = 0.5 * sqrt (1 + r!0!0 + r!1!1 + 1)\n z = 1/(4*w) * (r!0!1 - r!1!0)\n q = Quaternion w (V3 0 0 z)\n\nquaternionToMatrix :: Quaternion Double -> Matrix Double\nquaternionToMatrix q = (2><2)\n [ 1 - 2*(qj*qj + qk*qk), 2*(qi*qj+qk*qr)\n , 2*(qi*qj - qk*qr), 1 - 2*(qi*qi + qk*qk) ]\n where\n [qr,qi,qj,qk] = toList q\n\n-- A = R((1-t)I + tS)\ncomputeA_RSt :: Matrix Double -> Matrix Double -> Double -> Matrix Double\ncomputeA_RSt r s t = r_t <> (realToFrac (1-t) * Matrix.ident 2 + realToFrac t * s)\n where\n i = Quaternion 1 0\n q = slerp i (matrixToQuaternion r) t\n r_t = quaternionToMatrix q\n\napplyA :: Matrix Double -> Trig -> Trig\napplyA a p =\n case toLists (a <> matP) of\n [ [x1, x2], [y1, y2] ] -> (V2 0 0, V2 x1 y1, V2 x2 y2)\n _ -> error \"invalid matrix\"\n where\n matP = trigToMatrix p\n\ncoeffOfB :: Trig -> Matrix Double\ncoeffOfB p = (4><6)\n [ -a0-a2, 0, a0, 0, a2, 0\n , -a1-a3, 0, a1, 0, a3, 0\n , 0, -a0-a2, 0, a0, 0, a2\n , 0, -a1-a3, 0, a1, 0, a3 ]\n where\n [[a0,a1],[a2,a3]] = toLists (Matrix.inv (trigToMatrix p))\n\napplyCoeff :: Matrix Double -> Trig -> Matrix Double\napplyCoeff b (V2 x1 y1, V2 x2 y2, V2 x3 y3) = b <> matQ\n where\n matQ = (6><1) [ x1, y1, x2, y2, x3, y3]\n\ntrigToMatrix :: Trig -> Matrix Double\ntrigToMatrix (p1,p2,p3) = matP\n where\n V2 p12x p12y = p2-p1\n V2 p13x p13y = p3-p1\n matP = (2><2)\n [p12x, p13x\n ,p12y, p13y]\n\n\n\ndata Prep = Prep\n { prepPivot :: (P, P)\n , prepPointsA :: Vector P\n , prepPointsB :: Vector P\n , prepRS :: Vector (Matrix Double, Matrix Double)\n , prepRSRev :: Vector (Matrix Double, Matrix Double)\n , prepUToB :: GMatrix\n }\n\nsymmetric :: Bool\nsymmetric = True\n\nprepare :: Mesh -> Prep\nprepare Mesh{..} = Prep\n { prepPivot = (aOrigin, bOrigin)\n , prepPointsA =\n V.map (subtract aOrigin) $\n V.take pivotIdx meshPointsA <> V.drop (pivotIdx+1) meshPointsA\n , prepPointsB =\n V.map (subtract bOrigin) $\n V.take pivotIdx meshPointsB <> V.drop (pivotIdx+1) meshPointsB\n , prepRS = rsList\n , prepRSRev = rsRevList\n , prepUToB = Matrix.mkSparse uToB }\n where\n aOrigin = meshPointsA V.! pivotIdx\n bOrigin = meshPointsB V.! pivotIdx\n pivotIdx = case V.head meshTriangles of\n (a,_,_) -> a\n mkAbs p (a,b,c) = (p V.! a,p V.! b,p V.! c)\n absATrigs = V.map (mkAbs meshPointsA) meshTriangles\n absBTrigs = V.map (mkAbs meshPointsB) meshTriangles\n aList = V.zipWith computeA absATrigs absBTrigs\n rsList = V.map computeRS aList\n revList = V.zipWith computeA absBTrigs absATrigs\n rsRevList = V.map computeRS revList\n n = length meshTriangles\n -- nT = if symmetric then n*2 else n\n -- pivotToB = ((nT*4)><2) $ concat\n -- [ [ fromMaybe 0 (lookup (x,pivotIdx*2) bigM)\n -- , fromMaybe 0 (lookup (x,pivotIdx*2+1) bigM)]\n -- | x <- [0..(nT*4)-1] ]\n uToB =\n [ ((x,y-2),key) | ((x,y),key) <- bigM, y /= pivotIdx*2 && y /= pivotIdx*2+1 ]\n bigM =\n concat (zipWith worker [0..] (V.toList meshTriangles)) ++\n if symmetric\n then concat $ zipWith workerRev [n..] (V.toList meshTriangles)\n else []\n worker i src@(a,b,c) = concat $\n let effs = coeffOfB (mkAbs meshPointsA src) in\n [ [((i*4+h, e*2), effs!h!(j*2))\n ,((i*4+h, e*2+1), effs!h!(j*2+1))]\n | h <- [0..3]\n , (e,j) <- zip [a,b,c] [0..]\n ]\n workerRev i dst@(a,b,c) = concat $\n let effs = coeffOfB (mkAbs meshPointsB dst) in\n [ [((i*4+h, e*2), effs!h!(j*2))\n ,((i*4+h, e*2+1), effs!h!(j*2+1))]\n | h <- [0..3]\n , (e,j) <- zip [a,b,c] [0..]\n ]\n\ninterpolate :: Prep -> Double -> Vector P\ninterpolate Prep{..} t = V.fromList $\n pivot : worker (Matrix.toList solution)\n where\n -- solution = Matrix.cgSolve False prepUToB b\n solution = Matrix.cgx $ last solutions\n solutions = Matrix.cgSolve'\n False\n 1e-9\n 1e-9\n 1000\n prepUToB\n b\n (Matrix.fromList $ concat [ [x,y] | V2 x y <- V.toList target ])\n -- 0\n target = if t < 0.5\n then prepPointsA\n else prepPointsB\n worker (x:y:xs) = V2 x y ^+^ pivot : worker xs\n worker _ = []\n pivot = case prepPivot of\n (src, dst) -> lerp t dst src\n n = V.length prepRS\n b = Matrix.vector $\n [ concat (toLists a)!!j\n | i <- [0..n-1]\n , let (r,s) = prepRS V.! i\n , let a = computeA_RSt r s t\n , j <- [0..3]\n ] ++\n [ concat (toLists a)!!j\n | symmetric\n , i <- [0..n-1]\n , let (r,s) = prepRSRev V.! i\n , let a = computeA_RSt r s (1-t)\n , j <- [0..3]\n ]\n", "meta": {"hexsha": "381322f973685db357ece92fefd29fc63722d305", "size": 9125, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Reanimate/Morph/Rigid.hs", "max_stars_repo_name": "TristanCacqueray/reanimate", "max_stars_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Reanimate/Morph/Rigid.hs", "max_issues_repo_name": "TristanCacqueray/reanimate", "max_issues_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Reanimate/Morph/Rigid.hs", "max_forks_repo_name": "TristanCacqueray/reanimate", "max_forks_repo_head_hexsha": "8e34d9ca2f0ea747f9b7503c2f950cadd187ce80", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3045112782, "max_line_length": 83, "alphanum_fraction": 0.6352876712, "num_tokens": 2881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5847181990674506}} {"text": "{-|\nModule : Numeric.MCMC.Diagnostics\nDescription : Diagnostics for Markov Chain Monte Carlo Sampling\nCopyright : (c) Adam Conner-Sax 2019\nLicense : BSD\nMaintainer : adam_conner_sax@yahoo.com\nStability : experimental\n\nNumeric.MCMC.Diagnostics contains functions to analyze the convergence of MCMC sampling and to estimate the distribution of expectations computed\nusing a set of MCMC chains.\n-}\nmodule Numeric.MCMC.Diagnostics\n ( summarize\n , mpsrf\n , ExpectationSummary(..)\n , mannWhitneyUTest\n )\nwhere\n\nimport qualified Control.Foldl as FL\nimport qualified Statistics.Types as S\nimport qualified Data.List as L\n--import qualified Data.Vector.Generic as V\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Statistics.Test.MannWhitneyU as S\nimport qualified Numeric.LinearAlgebra as LA\n\n\ndata ExpectationSummary a = ExpectationSummary { mean :: a, confidence :: (a, a), rHat :: a } deriving (Show)\n-- all sub-chains should have same length here\n-- do we need to throw away first half of all the chains??\n{- |\nCompute the exepctation, confidence interval and\nPSRF statistic (from )\nfor a given confidence %, expectation function, and set of MCMC chains. In the version in the paper, each chain is\nhalved before the statistic is computed but it's not clear why. Here we assume that is \"burn-in\" and the user may\nchoose to do that or not before calling this function.\n\nAll sub-chains should have the same length here, though that is not checked.\n-}\nsummarize\n :: (RealFrac b, Ord b)\n => S.CL b -- ^ confidence interval to test\n -> (a -> b) -- ^ function to map a sample to a function under consideration\n -> [[a]] -- ^ list of chains\n -> Maybe (ExpectationSummary b) -- ^ @Maybe@ here in case chains aren't long enough\nsummarize confidence' expectationF chains = do\n let applied = fmap (fmap expectationF) chains\n allApplied = concat applied\n chainInterval :: Ord b => [b] -> Maybe (b, b)\n chainInterval c =\n let n = L.length c\n n' = round (realToFrac n * S.confidenceLevel confidence')\n d = (n - n') `div` 2\n c' = L.take n' $ L.drop d $ L.sort c\n in if length c' >= 2 then (head &&& last) <$> nonEmpty c' else Nothing\n-- intervalLength (a, b) = b - a\n intervals <- traverse chainInterval applied\n (lo, hi) <- chainInterval allApplied\n let (mLo, mHi) = FL.fold\n ((,) <$> FL.premap fst FL.mean <*> FL.premap snd FL.mean)\n intervals\n let rHat' = (hi - lo) / (mHi - mLo)\n mean' = FL.fold FL.mean allApplied\n return $ ExpectationSummary mean' (lo, hi) rHat'\n\n-- if the chain list is empty or chains have different sizes, etc. we return Nothing\nmpsrf :: [a -> Double] -> [[a]] -> Maybe Double\nmpsrf expectations chains = do\n let --mkVec :: a -> LA.Vector Double\n mkVec x = LA.fromList $ fmap ($ x) expectations\n m = length chains\n n <- length . head <$> nonEmpty chains --if m > 0 then Just (length $ head chains) else Nothing\n traverse_ (\\c -> if length c == n then Just () else Nothing) chains -- check that all chains are length n\n let\n sumVecsF = FL.Fold (+) (LA.vector $ L.replicate (length expectations) 0) id\n sumMatsF = FL.Fold (+) (LA.scale 0 $ LA.ident (length expectations)) id\n meanVecsF =\n (\\m' l -> LA.scale (1 / realToFrac l) m') <$> sumVecsF <*> FL.length\n avgVec = FL.fold meanVecsF\n phiChains = fmap (fmap mkVec) chains\n avgPhiEach = fmap avgVec phiChains\n diffProd :: LA.Vector Double -> LA.Vector Double -> LA.Matrix Double\n diffProd x y = (x - y) `LA.outer` (x - y)\n w1 = (\\(ap, ps) -> (`diffProd` ap) <$> ps) <$> zip avgPhiEach phiChains\n w =\n LA.scale (1 / (realToFrac m * realToFrac (n - 1)))\n $ FL.fold sumMatsF\n $ fmap (FL.fold sumMatsF) w1\n avgPhiAll = avgVec avgPhiEach\n b1 = fmap (`diffProd` avgPhiAll) avgPhiEach\n b = LA.scale (realToFrac n / realToFrac (m - 1)) $ FL.fold sumMatsF b1\n mat = LA.scale (1 / realToFrac n) $ LA.inv w LA.<> b\n eigen1 = LA.eigenvaluesSH (LA.trustSym mat) `LA.atIndex` 0\n rhat =\n (realToFrac (n - 1) / realToFrac n)\n + (realToFrac (m + 1) / realToFrac m)\n * eigen1\n return rhat\n\nmannWhitneyUTest\n :: (Ord b, VU.Unbox b)\n => S.PValue Double\n -> (a -> b)\n -> [a]\n -> [a]\n -> Maybe S.TestResult\nmannWhitneyUTest p f c1 c2 =\n let vOfF = VU.fromList . fmap f\n in S.mannWhitneyUtest S.SamplesDiffer p (vOfF c1) (vOfF c2)\n", "meta": {"hexsha": "70ded003e9484539d50396e536ec323eabcaa8e9", "size": 4604, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/MCMC/Diagnostics.hs", "max_stars_repo_name": "adamConnerSax/data-science-utils", "max_stars_repo_head_hexsha": "cedfd4041c26a85fb94199c634da4a1f179c2905", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/MCMC/Diagnostics.hs", "max_issues_repo_name": "adamConnerSax/data-science-utils", "max_issues_repo_head_hexsha": "cedfd4041c26a85fb94199c634da4a1f179c2905", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/MCMC/Diagnostics.hs", "max_forks_repo_name": "adamConnerSax/data-science-utils", "max_forks_repo_head_hexsha": "cedfd4041c26a85fb94199c634da4a1f179c2905", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4774774775, "max_line_length": 145, "alphanum_fraction": 0.6503040834, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.5846908075731172}} {"text": "{-|\nModule: MachineLearning.Classification.Binary\nDescription: Binary Classification.\nCopyright: (c) Alexander Ignatyev, 2016-2017\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n\nBinary Classification.\n-}\n\nmodule MachineLearning.Classification.Binary\n(\n Opt.MinimizeMethod(..)\n , module Log\n , module Model\n , predict\n , learn\n , MLC.calcAccuracy\n , Regularization(..)\n)\n\nwhere\n\nimport MachineLearning.Types (R, Vector, Matrix)\nimport MachineLearning.Regularization (Regularization(..))\nimport qualified MachineLearning.Optimization as Opt\nimport qualified MachineLearning.LogisticModel as Log\nimport qualified MachineLearning.Model as Model\nimport qualified MachineLearning.Classification.Internal as MLC\nimport qualified Data.Vector.Storable as V\nimport qualified Numeric.LinearAlgebra as LA\n\n\n-- | Binary Classification prediction function.\n-- Takes a matrix of features X and a vector theta.\n-- Returns predicted class.\npredict :: Matrix -> Vector -> Vector\npredict x theta = V.map (\\r -> if r >= 0.5 then 1 else 0) h\n where h = Model.hypothesis Log.Logistic x theta\n\n\n-- | Learns Binary Classification.\nlearn :: Opt.MinimizeMethod -- ^ (e.g. BFGS2 0.1 0.1)\n -> R -- ^ epsilon, desired precision of the solution;\n -> Int -- ^ maximum number of iterations allowed;\n -> Regularization -- ^ regularization parameter lambda;\n -> Matrix -- ^ matrix X;\n -> Vector -- ^ binary vector y;\n -> Vector -- ^ initial Theta;\n -> (Vector, Matrix) -- ^ solution vector and optimization path.\nlearn mm eps numIters lambda x y initialTheta = Opt.minimize mm Log.Logistic eps numIters lambda x y initialTheta\n", "meta": {"hexsha": "101355eb3b22f79d57ea63bf5e02406a75d91e5f", "size": 1745, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/Classification/Binary.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "src/MachineLearning/Classification/Binary.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "src/MachineLearning/Classification/Binary.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 32.9245283019, "max_line_length": 113, "alphanum_fraction": 0.6945558739, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5846530050660922}} {"text": "module LinReg (\n\n lsr, bulkPDs\n\n ) where\n\nimport Poly\nimport Data.List\nimport Data.Monoid\nimport Control.Arrow\nimport Data.Packed.Matrix\nimport Numeric.LinearAlgebra.LAPACK\n\ntype Data = [(Double,Double)]\n\n-- Data Acquisition - Very unsafe\n\ngetData :: PartialDerivitives -> ([[Double]], [Double])\ngetData = (map tail &&& map (negate . head)) . fun\n where\n fun = map (map (getNums . unSP) . unSS) . unPD\n getNums = foldl' getNum 1\n getNum x (SimpleNumber n) = n * x\n getNum x (SimpleConstant _) = x\n\n-- Concat Partialderivitives over data-points\n\nbulkPDs :: Int -> Data -> PartialDerivitives\nbulkPDs ord dat = pard\n where\n poly = polynomial_of_order ord\n dsqr = delta_squared_term poly\n ssss = mconcat $ map (point_result dsqr) dat\n pard = partial_derivatives ord ssss\n\npoint_result :: Expression -> (Double,Double) -> SimpleSum\npoint_result e (x,y) = normal (Env [(\"x\", x), (\"y\", y)]) e\n\nlsr :: Int -> Data -> [Double]\nlsr order points = concat $ toLists $ linearSolveR coefs values\n where\n linear = bulkPDs (order - 1) points\n (lhs, rhs) = getData linear\n coefs = (order >< order) (concat lhs)\n values = (order >< 1 ) rhs\n", "meta": {"hexsha": "f4046a55897310e2684c168b62bc7256e84520f9", "size": 1265, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "LinReg.hs", "max_stars_repo_name": "sordina/Simple-LSR", "max_stars_repo_head_hexsha": "55176bf9ad01a0acd3c5c26ef17491ecadb42420", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-08-29T07:13:22.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-02T13:34:01.000Z", "max_issues_repo_path": "LinReg.hs", "max_issues_repo_name": "sordina/Simple-LSR", "max_issues_repo_head_hexsha": "55176bf9ad01a0acd3c5c26ef17491ecadb42420", "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": "LinReg.hs", "max_forks_repo_name": "sordina/Simple-LSR", "max_forks_repo_head_hexsha": "55176bf9ad01a0acd3c5c26ef17491ecadb42420", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5, "max_line_length": 74, "alphanum_fraction": 0.6173913043, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5845393382763473}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Qubism.StateVecSpec (genStateVec, spec) where\n\nimport GHC.TypeLits\nimport Data.Singletons\n\nimport Test.Hspec\nimport Test.QuickCheck\nimport Test.QuickCheck.Monadic\nimport Control.Monad.Random\nimport Control.Monad.Trans.State\nimport qualified Numeric.LinearAlgebra as LA\nimport Data.Complex\n\nimport Qubism.AlgebraTests\nimport Qubism.StateVec\n\ngenC :: Gen (Complex Double)\ngenC = do\n a <- choose (-1, 1)\n b <- choose (-1, 1)\n pure $ a :+ b\n\ngenStateVec :: forall n . KnownNat n => Gen (StateVec n)\ngenStateVec = normalize . UnsafeMkStateVec . LA.fromList <$> vectorOf l genC\n where l = (2 ^) . fromIntegral . fromSing $ (sing :: Sing n)\n\n-- | I know, it's an orphan instance, but it's not relevant outside of this \n-- test suite, and never should be.\ninstance KnownNat n => Arbitrary (StateVec n) where\n arbitrary = genStateVec\n\npropIdempotent\n :: (Eq a, Show a, Eq b, Show b)\n => StateT a (Rand StdGen) b\n -> a\n -> PropertyM IO Expectation\npropIdempotent st a = do\n g <- lift getStdGen\n let one = runStateT st a `evalRand` g\n two = runStateT (st >> st) a `evalRand` g\n pure $ two `shouldBe` one\n\nspec :: Spec\nspec = do\n describe \"Quantum Registers\" $ do\n describe \"form a vector space\" $ isVectorSpace (T :: T (StateVec 1))\n describe \"form a hilbert space\" $ isHilbertSpace (T :: T (StateVec 1))\n describe \"measure\" $ \n it \"is idempotent\"\n $ property\n $ monadicIO\n $ forAllM (genStateVec :: Gen (StateVec 1)) \n $ propIdempotent measure\n describe \"measureQubit\" $ \n it \"is idempotent\"\n $ property\n $ monadicIO\n $ forAllM (genStateVec :: Gen (StateVec 1))\n $ propIdempotent (measureQubit 0)\n", "meta": {"hexsha": "6b5554142d037b178cebaaae3949468098939647", "size": 1817, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Qubism/StateVecSpec.hs", "max_stars_repo_name": "qubitrot/qubism", "max_stars_repo_head_hexsha": "41d2fd594d338affdfe1736aec422d75c2cc9401", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Qubism/StateVecSpec.hs", "max_issues_repo_name": "qubitrot/qubism", "max_issues_repo_head_hexsha": "41d2fd594d338affdfe1736aec422d75c2cc9401", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-09-17T20:07:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T03:29:45.000Z", "max_forks_repo_path": "test/Qubism/StateVecSpec.hs", "max_forks_repo_name": "qubitrot/qubism", "max_forks_repo_head_hexsha": "41d2fd594d338affdfe1736aec422d75c2cc9401", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8412698413, "max_line_length": 76, "alphanum_fraction": 0.6494221244, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289533, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5844198344494086}} {"text": "{-# LANGUAGE ParallelListComp #-}\nmodule Main where\n\nimport Numeric.LinearAlgebra.Data (fromList, toList, cmap)\nimport Numeric.GSL.Fitting.Linear (linear_w)\nimport Graphics.Rendering.Chart.Easy\nimport Graphics.Rendering.Chart.Backend.Cairo\nimport Text.Printf\n\nx = fromList [10, 100, 1000, 10000, 100000, 1000000]\ny = fromList [4772, 21148, 134194, 1343814, 13389821, 148509325]\nsigma = fromList [2112, 8194, 61719, 804762, 4853113, 42071732]\n\n(intercept, slope, _, _, _, chi_sq) = linear_w x (cmap (\\s -> 1 / s^2) sigma) y\n\nerrbars = liftEC $ do\n let values = [symErrPoint x' y' 0 dy\n | x' <- toList x\n | y' <- toList y\n | dy <- toList sigma\n ]\n plot_errbars_values .= values\n\nmain = toFile def \"benchmark-fit.png\" $ do\n setColors (map opaque [blue,red,green])\n layout_title .=\n printf \"t = %.2f (ns/element) n + %.2f (ns) [chi^2 = %.2f]\" slope intercept chi_sq\n layout_x_axis . laxis_generate .= autoScaledLogAxis def\n layout_y_axis . laxis_generate .= autoScaledLogAxis def\n plot errbars\n plot $ points \"Benchmark data\"\n (zip (toList x) (toList y))\n plot $ line \"Best fit\" [[\n (t, slope*t + intercept)\n | t <- map (10**) [0.5, 0.6 .. 6.5 ]\n ]]\n", "meta": {"hexsha": "4737f973d8e36d1e59286a0fa9774ab6db0a3b71", "size": 1283, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "make-plot/src/Main.hs", "max_stars_repo_name": "devonhollowood/radix-sort", "max_stars_repo_head_hexsha": "7148d85cd1056bb07fae900cd1286e26287ab1b9", "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": "make-plot/src/Main.hs", "max_issues_repo_name": "devonhollowood/radix-sort", "max_issues_repo_head_hexsha": "7148d85cd1056bb07fae900cd1286e26287ab1b9", "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": "make-plot/src/Main.hs", "max_forks_repo_name": "devonhollowood/radix-sort", "max_forks_repo_head_hexsha": "7148d85cd1056bb07fae900cd1286e26287ab1b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6756756757, "max_line_length": 90, "alphanum_fraction": 0.6173031956, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5842155737352341}} {"text": "#!/usr/bin/env stack\n-- stack --install-ghc runghc --resolver lts-10.4 --package hmatrix --package lens -- -Wall\n\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE TemplateHaskell #-}\n\n-- Imports for network logic\n\nimport Control.Lens hiding ((<.>))\nimport Numeric.LinearAlgebra.Static\n\n-- Imports for utility functions\n\nimport GHC.Generics (Generic)\nimport Numeric.OneLiner\n\ndata Net = N { _weights1 :: L 250 784\n , _bias1 :: R 250\n , _weights2 :: L 10 250\n , _bias2 :: R 10\n }\n deriving (Generic)\nmakeLenses ''Net\n\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n\nsoftMax\n :: R 10\n -> R 10\nsoftMax x = expx / konst (norm_1 expx)\n where\n expx = exp x\n\ncrossEntropy\n :: R 10\n -> R 10\n -> Double\ncrossEntropy targ res = -(log res <.> targ)\n\nrunNet\n :: Net\n -> R 784\n -> R 10\nrunNet n x = z\n where\n y = logistic $ (n ^. weights1) #> x + (n ^. bias1)\n z = softMax $ (n ^. weights2) #> y + (n ^. bias2)\n\nnetErr\n :: R 784\n -> R 10\n -> Net\n -> Double\nnetErr x targ n = crossEntropy targ (runNet n x)\n\nmain :: IO ()\nmain = return ()\n\ninstance Num Net where\n (+) = gPlus\n (-) = gMinus\n (*) = gTimes\n negate = gNegate\n abs = gAbs\n signum = gSignum\n fromInteger = gFromInteger\n\ninstance Fractional Net where\n (/) = gDivide\n recip = gRecip\n fromRational = gFromRational\n", "meta": {"hexsha": "1ff9c08916490147d523aabba1a3f0dcefd0a172", "size": 1545, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "code-samples/backprop/intro-normal.hs", "max_stars_repo_name": "mstksg/inCode", "max_stars_repo_head_hexsha": "e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2015-01-23T14:58:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:18:48.000Z", "max_issues_repo_path": "code-samples/backprop/intro-normal.hs", "max_issues_repo_name": "mstksg/inCode", "max_issues_repo_head_hexsha": "e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2016-05-25T21:35:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-28T22:26:17.000Z", "max_forks_repo_path": "code-samples/backprop/intro-normal.hs", "max_forks_repo_name": "mstksg/inCode", "max_forks_repo_head_hexsha": "e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2015-05-12T05:29:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:24.000Z", "avg_line_length": 20.8783783784, "max_line_length": 91, "alphanum_fraction": 0.5352750809, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5841510271547374}} {"text": "{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}\n\nmodule Data.Wavelets.Scaling where \nimport Prelude hiding (length,replicate,map,maximum,minimum)\n-- import Data.Wavelets \nimport Numeric.Statistics\nimport Statistics.Function\nimport Statistics.Sample\nimport GHC.Generics\nimport Data.Vector.Storable -- hiding (map)\nimport Data.Packed.Matrix\n-- import Linear\n\n{-| Scale factors are designed to make it possible to use a scaled wavelet to reconstruct an approximation \n of the original data series. ordinary least squares is used so that translation is available for approximation,\n in addition to scaling. \n\n\n|-}\n\n\ndata SeriesFactors = SeriesFactors { \n seriesMin :: Double ,\n seriesMax :: Double ,\n seriesMean :: Double ,\n seriesCount :: Int } deriving (Show,Generic)\n\ncomputeSeriesFactors :: Vector Double -> SeriesFactors\ncomputeSeriesFactors v = SeriesFactors mn mx avg tot\n where (mn, mx,avg, tot) = minMaxAndAverage v \n \n\nnewtype OldSeriesFactors = OSF SeriesFactors deriving (Show) \nnewtype NewSeriesFactors = NSF SeriesFactors deriving (Show) \nnewtype NewSeriesMatrix = NSM (Matrix Double) deriving (Show) \nnewtype OldSeriesMatrix = OSM (Matrix Double) deriving (Show) \n\n-- | x scaling matrix is B in Y = XB + e matrix formulation of ordinary least squares\n\nnewtype ScalingMatrix = SM (Matrix Double) deriving (Show)\n\ntype SeriesMatrix = Matrix Double \n\n\n-- ScaleMatrix is the scaling matrix for the least squares problem\ncomputeSeriesMatrix :: SeriesFactors -> SeriesMatrix\ncomputeSeriesMatrix (SeriesFactors mn mx amean _ ) = (fromColumns vlst)\n where onesList = replicate 3 1\n nsf' = fromList [mn,mx,amean]\n vlst = [onesList,nsf']\n\ncomputeNewSeriesMatrix :: NewSeriesFactors -> NewSeriesMatrix\ncomputeNewSeriesMatrix (NSF sf) = NSM $ computeSeriesMatrix sf\n\n\ncomputeSeriesResult :: SeriesFactors -> SeriesMatrix\ncomputeSeriesResult (SeriesFactors mn mx avg _ ) = (fromColumns vlst)\n where nsf' = fromList [mn,mx,avg]\n vlst = [nsf']\n\ncomputeOldSeriesMatrix :: OldSeriesFactors -> OldSeriesMatrix\ncomputeOldSeriesMatrix (OSF sf) = OSM $ computeSeriesResult sf\n\n\n-- | ordinary least squares estimation for the multivariate model\n-- Y = X B + e rows are observations, columns are elements\n-- mean e = 0, cov e = kronecker s I\n\ncomputeScalingMatrix :: NewSeriesFactors -> OldSeriesFactors -> ScalingMatrix\ncomputeScalingMatrix nsf osf = let (OSM _Y) = computeOldSeriesMatrix osf\n (NSM _X) = computeNewSeriesMatrix nsf \n (_B,_ ,_ ) = ols _X _Y \n in SM _B\n \n\n\n-- | compute the average of the absolute value of a foldable type by setting it up like \n-- foldl (\\(a,t) b -> absAvgItrFcn a b (t+1) ) (0,0) foldableThing\nabsAvgItrFcn ::(Num a, Fractional a)=> a -> a -> a -> (a,a)\nabsAvgItrFcn a b t = avgtuple\n where \n diff = (a - abs(b))\n dv = abs(diff/t)\n tot = a + dv \n avgtuple = (tot,t)\n\n\n-- | compute the maximum absolute value of a foldable type by setting it up like \n-- foldl (\\mx b -> absMaxItrFcn mx b ) 0 foldableThing\nabsMaxItrFcn :: (Num a, Ord a) => a -> a -> a\nabsMaxItrFcn a b = max a (abs b)\n\n\n-- | compute the max min and average of a Vector in one pass \n-- (avg, max, min, tot)\nminMaxAndAverage :: Vector Double -> (Double, Double ,Double , Int )\nminMaxAndAverage v = (mn,mx,av,l)\n where\n av = mean v\n (mn, mx) = minMax v\n l = length v\n\n\n\napplyScalingMatrix :: ScalingMatrix -> Vector Double -> Vector Double \napplyScalingMatrix (SM sm) v = map scaleFcn v\n where tCoef = sm @@> (0,0)\n sCoef = sm @@> (1,0)\n scaleFcn x = sCoef * x + tCoef \n\n\n \n", "meta": {"hexsha": "7594418b790b3bd205112f94e268e7bf02714fdd", "size": 3709, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Wavelets/Scaling.hs", "max_stars_repo_name": "smurphy8/wavelets", "max_stars_repo_head_hexsha": "353e3f43de33b992ef78cf7ce49655f763546d08", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-10T05:01:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-10T05:01:11.000Z", "max_issues_repo_path": "src/Data/Wavelets/Scaling.hs", "max_issues_repo_name": "smurphy8/wavelets", "max_issues_repo_head_hexsha": "353e3f43de33b992ef78cf7ce49655f763546d08", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/Wavelets/Scaling.hs", "max_forks_repo_name": "smurphy8/wavelets", "max_forks_repo_head_hexsha": "353e3f43de33b992ef78cf7ce49655f763546d08", "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.8230088496, "max_line_length": 115, "alphanum_fraction": 0.6823941763, "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5841397918949123}} {"text": "module SparseLinAlg (solve_tree) where\n\nimport Data.Bifunctor (bimap)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Data.Sparse.SpMatrix\nimport Data.Sparse.SpVector\nimport Numeric.LinearAlgebra.Sparse\n\nimport LinEq (Coeff, Var, Equation(..), remove_term, combine_terms, ltree_of_tree, equations_of_ltree)\nimport Sexp \nimport Tree\nimport Util (debug)\n\n-- Here our equations have a slightly different form, where the LHS is\n-- a linear combination of the variables and the RHS is a single\n-- rational value. E.g., 1x - 1/2y = 1/2.\ntype MatTerm = (Coeff, Var)\ntype MatEq = ([MatTerm], Double)\n\n-- mateq_of_equation :: Equation -> MatEq\n-- mateq_of_equation (Equation (x, tms)) =\n-- case remove_term Nothing $ combine_terms tms of\n-- Just (c, tms') -> (second fromJust <$> tms', c)\n-- Nothing -> (second fromJust <$> tms, 0)\n\nmateq_of_equation :: Equation -> MatEq\nmateq_of_equation (Equation (x, tms)) =\n case remove_term Nothing $ combine_terms tms of\n Just (c, tms') -> ((1, x) : (bimap negate fromJust <$> tms'), c)\n Nothing -> ((1, x) : (bimap negate fromJust <$> tms), 0)\n\nconstraint_matrix :: [MatEq] -> SpMatrix Double\nconstraint_matrix eqs =\n let l = concat $ f <$> zip [0..] eqs in\n debug (\"l: \" ++ show ((\\(x, y, z) -> (x, y, z)) <$> l)) $\n fromListSM (n, n) l\n where\n n = length eqs\n\n f :: (Int, MatEq) -> [(Int, Int, Double)]\n f (x, (tms, _)) = g x <$> tms\n\n g :: Int -> MatTerm -> (Int, Int, Double)\n g x (c, y) = (x, y, c)\n -- g x (c, y) = (y, x, c)\n\n-- tree_constraint_matrix :: Tree Bool -> SpMatrix Double\n-- tree_constraint_matrix =\n-- fmap fromRational . constraint_matrix . map mateq_of_equation .\n-- equations_of_ltree . ltree_of_tree\n\n-- tree_constraint_matrix :: Tree Bool -> SpMatrix Double\n-- tree_constraint_matrix =\n-- fmap fromRational .\n-- constraint_matrix .\n-- map (\\eq -> let mateq = mateq_of_equation eq in\n-- debug (\"eq: \" ++ show eq) $\n-- debug (\"mateq\" ++ show mateq) $\n-- mateq) .\n-- equations_of_ltree .\n-- ltree_of_tree\n\nmatrix_of_mateqs :: [MatEq] -> SpMatrix Double\nmatrix_of_mateqs = constraint_matrix\n\nrhs_of_mateqs :: [MatEq] -> SpVector Double\nrhs_of_mateqs eqs = fromListDenseSV n $ snd <$> eqs\n where n = length eqs\n\nsolve_system_gmres :: SpMatrix Double -> SpVector Double -> IO (SpVector Double)\nsolve_system_gmres mat rhs =\n debug (\"mat: \" ++ show mat) $\n debug (\"rhs: \" ++ show rhs) $\n debug (\"dense:\") $\n -- let _ = unsafePerformIO $ prd mat in\n -- mat <\\> (fromListDenseSV n )\n mat <\\> rhs\n -- where\n -- n = nrows mat -- should also be the length of the rhs vector\n\nsolve_tree :: Tree Double -> IO (SpVector Double)\nsolve_tree (Leaf x) = return $ fromListDenseSV 1 [x]\nsolve_tree t =\n let lt = ltree_of_tree t\n eqs = sort $ equations_of_ltree lt\n mateqs = mateq_of_equation <$> eqs\n (mat, rhs) = (matrix_of_mateqs mateqs, rhs_of_mateqs mateqs) in\n debug (\"eqs: \" ++ show eqs) $\n debug (\"mateqs: \" ++ show mateqs) $\n debug (\"ltree: \" ++ toSexp lt) $ do\n prd mat\n prd rhs\n sol <- solve_system_gmres mat rhs\n prd sol\n return sol\n\n-- infer_gmres :: Tree Bool -> Maybe Rational\n-- infer_gmres t =\n-- toRational <$>\n-- (lookupSV 0 $ unsafePerformIO $ solve_matrix $ tree_constraint_matrix t)\n\n-- [(0,[(0,1.0),(1,-0.5),(4,-0.5)]),\n-- (1,[(0,-0.5),(1,1.0),(3,-0.5)]),\n-- (2,[(1,-0.5),(3,1.0)]),\n-- (3,[(0,-0.5),(2,-0.5),(4,1.0)]),\n-- (4,[(2,1.0),(5,-0.5)]),\n-- (5,[(0,-0.5),(2,-0.5),(5,1.0)])]\n", "meta": {"hexsha": "f74dbb1c9634e5b56fd8723491145bc726c3e45e", "size": 3515, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SparseLinAlg.hs", "max_stars_repo_name": "OUPL/Zar", "max_stars_repo_head_hexsha": "9243f9d77d0c8af99afa4f536156a3e23b1c40e1", "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/SparseLinAlg.hs", "max_issues_repo_name": "OUPL/Zar", "max_issues_repo_head_hexsha": "9243f9d77d0c8af99afa4f536156a3e23b1c40e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-09-13T15:40:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-06T16:32:25.000Z", "max_forks_repo_path": "src/SparseLinAlg.hs", "max_forks_repo_name": "OUPL/Zar", "max_forks_repo_head_hexsha": "9243f9d77d0c8af99afa4f536156a3e23b1c40e1", "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.247706422, "max_line_length": 102, "alphanum_fraction": 0.6204836415, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5841397827606798}} {"text": "{-# OPTIONS_HADDOCK hide #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.LinearAlgebra.Types\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Basic type classes and enums.\n--\n\nmodule Numeric.LinearAlgebra.Types (\n\n -- * Matrix views\n Herm(..),\n Tri(..),\n\n -- * Matrix factorization views\n Chol(..),\n\n -- * Vector math types\n VNum,\n VFractional,\n VFloating,\n\n -- * BLAS element types\n BLAS1,\n BLAS2,\n BLAS3,\n \n -- * LAPACK element types\n LAPACK,\n \n -- * Enums\n Trans(..),\n Uplo(..),\n Side(..),\n Diag(..),\n\n -- * Algorithm-specific parameters\n CovMethod(..),\n\n -- * Re-export of Complex from Data.Complex\n module Data.Complex,\n\n -- * Re-export of Storable from Foreign.Storable\n module Foreign.Storable,\n \n ) where\n\nimport Foreign.VMath( VNum, VFractional, VFloating )\nimport Foreign.BLAS( Trans(..), Uplo(..), Side(..), Diag(..), BLAS1, BLAS2, BLAS3 )\nimport Foreign.LAPACK( LAPACK )\nimport Data.Complex( Complex(..) )\nimport Foreign.Storable( Storable() )\n\n-- | A hermitian view of an underlying matrix. The view can either be\n-- of the upper or lower triangular part of the matrix. The type arguments\n-- are as follows:\n--\n-- * @m@: the underlyting matrix type.\n--\n-- * @e@: the element type of the matrix.\n--\ndata Herm m e = Herm Uplo (m e) deriving (Show)\n\n-- | A triangular view of an underlying matrix. The view can either be\n-- upper or lower triangular, with a unit or non-unit diagonal. The type\n-- arguments are as follows:\n--\n-- * @m@: the underlyting matrix type.\n--\n-- * @e@: the element type of the matrix.\n--\ndata Tri m e = Tri Uplo Diag (m e) deriving (Show)\n\n-- | A Cholesky decomposition view of a matrix.\ndata Chol m e = Chol Uplo (m e) deriving (Show)\n\n-- | The method of scaling the sample covariance matrix.\ndata CovMethod =\n UnbiasedCov -- ^ This is the default behavior. Corresponds to a\n -- scaling of @n/(n-1)@ in the unweighed case, and\n -- @1/(1 - \\\\sum w_i^2)@ in the weighted case, where @w_i@\n -- is the normalized weight. Note the unweighted and\n -- weighted cases agree when @w_i = 1/n@.\n \n | MLCov -- ^ Returns the centered second moment matrix without\n -- scaling the result.\n deriving (Eq, Show)\n\n", "meta": {"hexsha": "22a528b200833557b3251331dd1c94522281bc1d", "size": 2557, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/Types.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra/Types.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Numeric/LinearAlgebra/Types.hs", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 27.4946236559, "max_line_length": 83, "alphanum_fraction": 0.5901447008, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.812867322370925, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5841218997598331}} {"text": "{-# LANGUAGE BangPatterns #-}\n-- # LANGUAGE UndecidableInstances #\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\nmodule Data.Network.FullyConnected\n (FeedForwardFC, FullyConnected(FC), Layers,\n weights, biases, activation,\n unGrad, unGradBatch, Grad(GradBatch, Grad))\nwhere\n\nimport Numeric.LinearAlgebra as LA hiding (fromList, toList)\nimport Numeric.LinearAlgebra.Devel\nimport qualified Data.Vector.Storable as V hiding (foldr, modify)\nimport System.Random\nimport Control.DeepSeq\n-- import Data.Foldable as F\nimport Data.Bifunctor\nimport Data.Network as Network\nimport Data.Network.Activation\nimport Algorithm.Training\nimport Algorithm.GradientDescent \nimport Data.Network.Utils (squeeze, (.*))\n\n\n-- Fully connected feedforward layer\ndata FullyConnected i a = FC {weights :: {-# UNPACK #-} !(Matrix a),\n biases :: {-# UNPACK #-} !(Vector a),\n activation :: ActivationFunction i\n }\n\ninstance (V.Storable a, NFData a) => NFData (FullyConnected i a) where\n rnf (FC w b a) = rnf w `deepseq` rnf b\n\ninstance Layer (Vector R) (FullyConnected (Vector R) R) where\n compute (FC weights biases _) input = biases + (input <# weights)\n run l@(FC weights biases af) input = unAct af (compute l input)\n makeRandomLayer g rf i o af = let rnds = (randomRs (0,1) g) :: [Double]\n rnds' = (rf rnds) \n rw = (i> (repeat 0)\n in (FC rw rb af)\n\ninstance Layer (Matrix R) (FullyConnected (Matrix R) R) where\n compute (FC weights biases _) input = (fromRows $ replicate (rows input) biases) + (input <> weights)\n run l@(FC _ _ af) input = unAct af (compute l input)\n makeRandomLayer g rf i o af = let rnds = (randomRs (0,1) g) :: [Double]\n rnds' = (rf rnds) \n rw = (i> (repeat 0)\n in (FC rw rb af)\n\n\ninstance (Container Matrix a, Container Vector a, Num a) => Show (FullyConnected i a) where\n show l = let (a,b) = size $ weights l\n in \"Layer \" ++ (show a) ++ \"x\" ++ (show b) ++ \" \" ++ (name $ activation l)\n\ninstance Floating a => Num (FullyConnected a Double) where\n (FC w b a) + (FC w' b' _) = FC (w + w') (b + b') a\n (FC w b a) - (FC w' b' _) = FC (w - w') (b - b') a\n (FC w b a) * (FC w' b' _) = FC (w * w') (b * b') a\n abs (FC w b a) = FC (abs w) (abs b) a\n signum (FC w b a) = FC (signum w) (signum b) a\n fromInteger x = FC (fromInteger x) (fromInteger x) (act id \"identity\")\n\ninstance Floating a => Fractional (FullyConnected a Double) where\n (FC w b a) / (FC w' b' _) = FC (w / w') (b / b') a\n recip (FC w b a) = FC (recip w) (recip b) a\n fromRational a = FC (fromRational a) (fromRational a) (act id \"identity\")\n\ninstance (Container Vector a, Container Matrix a) => Linear a (FullyConnected i) where\n scale x (FC w b a) = FC (scale x w) (scale x b) a\n\n-- Container Layer instance?\n\ninstance (Layer i (FullyConnected i Double)) => Network i (Layers (FullyConnected i Double)) where\n runNetwork (Output l) i = run l i\n runNetwork (l :=> n) i = runNetwork n (fst $ run l i)\n runLayers (Output l) i = [run l i]\n runLayers (l :=> n) i = let y = (run l i)\n in y:(runLayers n (fst y))\n\n makeRandomNetwork g t nt i [] (o, af) = let l = makeRandomLayer g t i o af\n in (Output l)\n makeRandomNetwork g t nt i ((h,haf):hs) o = let (g1,g2) = split g\n l = makeRandomLayer g1 t i h haf\n in nt $ l :=> (makeRandomNetwork g2 t nt h hs o)\n\ntype FeedForwardFC i = Layers (FullyConnected i Double)\n\ninstance (Monad m) => Backpropagation Data (NetworkEvaluator Data) (FeedForwardFC Data) m where\n backward lf n (out,tar) das = do\n let \u03b4out = (derivate lf (tar, out)) -- dE/dy\n deltas = scanr (\\(l, a') \u03b4 -> let w = weights l in a' * (w #> \u03b4)) \u03b4out (zip (tail $ toList n) das)\n return (deltas) -- deltas for computing bias\n\ninstance (Monad m) => Backpropagation Batch (NetworkEvaluator Batch) (FeedForwardFC Batch) m where\n backward lf n (out,tar) das = do\n let \u03b4out = tr (derivate lf (tar, out)) -- dE/dy\n deltas = scanr (\\(l, a') \u03b4 -> let w = weights l in (tr a') * (w <> \u03b4)) \u03b4out (zip (tail $ toList n) das)\n return (deltas) -- deltas for computing bias\n\n-- type instance Params lf = forall i. ((FeedForwardFC i), (i,i))\n\ninstance (Monad m) => GradientDescent (NetworkEvaluator Batch) ((FeedForwardFC Batch), (Batch,Batch)) m where\n -- parameters of loss function: Network(weights, biases, activation functions for each layer)\n -- and sample((input, output) pair)\n \n data Grad (NetworkEvaluator Batch) = GradBatch { unGradBatch :: ([Matrix Double], [Vector Double]) } deriving (Show)\n\n -- Gradients over parameters(weights, biases)\n grad lf (n, (i,t)) = do\n let (as, as') = unzip $ runLayers n i -- forward propagation: compute layers outputs and activation derivatives\n (out) = last as\n (ds) <- backward lf n (out, t) (init as') -- compute deltas with backpropagation\n let r = fromIntegral $ rows i -- size of minibatch\n let gs = zipWith (\\\u03b4 a -> tr (\u03b4 <> a)) ds (i:init as)\n return $ GradBatch ((recip r .*) <$> gs, ((recip r .*) . squeeze) <$> ds)\n\n move lr (n, (i,t)) (GradBatch (gs, ds)) = do\n -- update function\n -- divide by batch size\n let update = (\\(FC w b af) g \u03b4 -> FC (w + (lr).*g) (b + (lr).*\u03b4) af)\n n' = Network.fromList $ zipWith3 update (Network.toList n) gs ds -- new model\n return (n', (i,t))\n\ninstance (Monad m) => GradientDescent (NetworkEvaluator Data) ((FeedForwardFC Data), (Data,Data)) m where\n -- parameters of loss function: Network(weights, biases, activation functions for each layer)\n -- and sample((input, output) pair)\n \n data Grad (NetworkEvaluator Data) = Grad { unGrad :: ([Matrix Double], [Vector Double]) } deriving (Show)\n\n -- Gradients over parameters(weights, biases)\n grad lf (n, (i,t)) = do\n let aos = runLayers n i -- forward propagation: compute layers outputs and activation derivatives \n (as, as') = (unzip) aos -- juggle data to extract layers inputs and derivatives in right order\n out = last as\n (ds) <- backward lf n (out,t) (init as') -- compute gradients with backpropagation\n let gs = zipWith (\\\u03b4 i -> tr (\u03b4 `outer` i)) ds (i:as)\n return $ Grad (gs, ds)\n\n move lr (n, (i,t)) (Grad (gs, ds)) = do\n -- update function\n let update = (\\(FC w b af) g \u03b4 -> FC (w + lr.*g) (b + lr.* \u03b4) af)\n n' = Network.fromList $ zipWith3 update (Network.toList n) gs ds -- new model\n return (n', (i,t))\n\n", "meta": {"hexsha": "06c5be428837533e65c5155f0b641ae2831a4aeb", "size": 6997, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Network/FullyConnected.hs", "max_stars_repo_name": "DrPyser/NeuralNetwork", "max_stars_repo_head_hexsha": "17ca01505dab75235af8522d9b0674639e8a4524", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-10-28T14:35:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T17:57:12.000Z", "max_issues_repo_path": "src/Data/Network/FullyConnected.hs", "max_issues_repo_name": "DrPyser/NeuralNetwork", "max_issues_repo_head_hexsha": "17ca01505dab75235af8522d9b0674639e8a4524", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-06-18T07:52:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-02T18:00:22.000Z", "max_forks_repo_path": "src/Data/Network/FullyConnected.hs", "max_forks_repo_name": "DrPyser/NeuralNetwork", "max_forks_repo_head_hexsha": "17ca01505dab75235af8522d9b0674639e8a4524", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-09T18:36:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-14T20:52:39.000Z", "avg_line_length": 46.3377483444, "max_line_length": 118, "alphanum_fraction": 0.593683007, "num_tokens": 1998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5840991908388977}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeFamilies #-}\n--------------------------------------------------------------------------------\n-- |\n-- Robust Principal Component Analysis Outlier Detection a la Netflix/Surus\n---------------------------------------------------------------------------------\nmodule RobustPCA\n ( -- * Datatypes\n LR(..)\n , LRPenalty(..)\n , MaxIters(..)\n , FitIters(..)\n , Periodicity(..)\n , RobustPCA(..)\n , Sparse(..)\n , SparsePenalty(..)\n , Tolerance(..)\n -- * Fitting\n , runRobustPCA\n , optimize\n ) where\n\nimport Control.Foldl (fold)\nimport Control.Foldl.Statistics (LMVSK (..), fastLMVSKu, fastStdDev)\nimport Control.Lens (declareWrapped, makeLenses, use,\n (+=), (.=), (^.))\nimport Control.Monad (return)\nimport Control.Monad.Identity (runIdentity)\nimport Control.Monad.Loops (whileM_)\nimport Control.Monad.State (State, execStateT)\nimport Data.Functor (void, (<$>))\nimport Data.List (replicate, take)\nimport Numeric.LinearAlgebra (Matrix, R, cmap, cols, diag, flatten,\n rows, sumElements, thinSVD, toList,\n tr, (<>), (><))\nimport Prelude (Double, Int, Show, abs, div,\n fromIntegral, max, mod, ($), (&&),\n (*), (**), (+), (-), (.), (/), (<),\n (>))\nimport Utils (absL1Norm, frobeniusNorm,\n softThreshold)\n\n\n---------------------------------------------------------------------------------\n-- Datatypes --------------------------------------------------------------------\n---------------------------------------------------------------------------------\n\ndeclareWrapped [d|\n newtype LRPenalty = LRPenalty Double deriving Show\n newtype SparsePenalty = SparsePenalty Double deriving Show\n newtype Periodicity = Periodicity Int deriving Show\n newtype MaxIters = MaxIters Int deriving Show\n newtype FitIters = FitIters Int deriving Show\n newtype LR = LR [R] deriving Show\n newtype Sparse = Sparse [R] deriving Show\n newtype Tolerance = Tolerance [R] deriving Show\n |]\n\n-- |\n-- Optimization state\ndata RobustPCA\n = RobustPCA\n { _maxIters :: MaxIters\n -- ^ maximum optimization iterations\n , _lrPenalty :: LRPenalty\n -- ^ low rank fit penalty\n , _sparsePenalty :: SparsePenalty\n -- ^ sparse fit penalty\n , _normalizedData :: Matrix R\n -- ^ normalized input data matrix\n , _iters :: Int\n -- ^ iterations count\n , _obj :: R\n -- ^ objective\n , _tol :: R\n -- ^ tolerance\n , _diff :: R\n -- ^ difference\n , _mean :: R\n -- ^ input data mean\n , _stdDev :: R\n -- ^ input data standard deviation\n , _mu :: R\n -- ^ incoherence factor\n , _lr :: Matrix R\n -- ^ recovered low rank matrix (underlying data 'approximation')\n , _sparse :: Matrix R\n -- ^ sparse outliers matrix\n , _tolerance :: Matrix R\n -- ^ tolerated deviation of real data from the 'fit'\n } deriving (Show)\nmakeLenses ''RobustPCA\n\n-- | Fitting state monad\ntype RobustPCAM a = State RobustPCA a\n\n\n---------------------------------------------------------------------------------\n-- Fitting ----------------------------------------------------------------------\n---------------------------------------------------------------------------------\n\n-- |\n-- Run robust PCA optimization\nrunRobustPCA\n :: [R]\n -- ^ input 'Real' data\n -> LRPenalty\n -- ^ low rank fit penalty\n -> SparsePenalty\n -- ^ sparse fit penalty\n -> Periodicity\n -- ^ input data periodicity\n -> MaxIters\n -- ^ maximum iteration count allowed\n -> (LR, Sparse, Tolerance, FitIters)\nrunRobustPCA originalData lpen spen p mi =\n (LR lr', Sparse sparse', Tolerance tol', FitIters itrs)\n where rs = runIdentity $\n execStateT optimize $\n initState originalData lpen spen p mi\n mean' = rs^.mean\n stdDev' = rs^.stdDev\n lr' = toList $ flatten $ tr $ cmap ((mean' +) . (stdDev' *)) (rs^.lr)\n sparse' = toList $ flatten $ tr $ cmap (stdDev' *) (rs^.sparse)\n tol' = toList $ flatten $ tr $ cmap (stdDev' *) (rs^.tolerance)\n itrs = rs^.iters\n\n\n---------------------------------------------------------------------------------\n-- Internal Functions -----------------------------------------------------------\n---------------------------------------------------------------------------------\n\ninitState\n :: [R]\n -> LRPenalty\n -> SparsePenalty\n -> Periodicity\n -> MaxIters\n -> RobustPCA\ninitState originalData lp sp (Periodicity p) mi =\n RobustPCA mi lp sp normalizedData' 0 obj' tol' diff' m sdev mu' z z z\n where (LMVSK l m v _ _) = fold fastLMVSKu originalData\n sdev = v ** 0.5\n zeroMeanUnitVariance x = (x - m) / sdev\n paddedLength = l - (l `mod` p)\n normalizedData' =\n tr $ ((paddedLength `div` p) >< p)\n (zeroMeanUnitVariance <$> take paddedLength originalData)\n r = rows normalizedData'\n c = cols normalizedData'\n z = (r >< c) (replicate (r * c) 0.0)\n mu' =\n fromIntegral c * fromIntegral r / (4 * absL1Norm normalizedData')\n obj' = 0.5 * ((frobeniusNorm normalizedData') ** 2.0)\n tol' = 1e-8 * obj'\n diff' = 2.0 * tol'\n\noptimize :: RobustPCAM ()\noptimize = whileM_ checkTolerance go\n where go = do\n nuclearNorm <- computeSparse\n l1Norm <- computeLR\n l2Norm <- computeTol\n objPrev <- use obj\n let obj' = 0.5 * l2Norm + nuclearNorm + l1Norm\n diff .= abs (objPrev - obj')\n obj .= obj'\n void updateMu\n iters += 1\n checkTolerance = do\n iters' <- use iters\n MaxIters mi' <- use maxIters\n tol' <- use tol\n diff' <- use diff\n return $ diff' > tol' && iters' < mi'\n\ncomputeSparse :: RobustPCAM R\ncomputeSparse = do\n normalizedData' <- use normalizedData\n SparsePenalty spen <- use sparsePenalty\n mu' <- use mu\n lr' <- use lr\n let sparsePenalty' = spen * mu'\n let normalizedDataMinusLr = normalizedData' - lr'\n let penalizedSparse = softThreshold normalizedDataMinusLr sparsePenalty'\n sparse .= penalizedSparse\n return $ (absL1Norm penalizedSparse) * sparsePenalty'\n\ncomputeLR :: RobustPCAM R\ncomputeLR = do\n normalizedData' <- use normalizedData\n LRPenalty lpen <- use lrPenalty\n mu' <- use mu\n sparse' <- use sparse\n let lrPenalty' = lpen * mu'\n let normalizedDataMinusSparse = normalizedData' - sparse'\n let (u, svs, v) = thinSVD normalizedDataMinusSparse\n let penalizedD = softThreshold svs lrPenalty'\n let d' = diag penalizedD\n lr .= u <> d' <> (tr v)\n return $ (sumElements penalizedD) * lrPenalty'\n\ncomputeTol :: RobustPCAM R\ncomputeTol = do\n normalizedData' <- use normalizedData\n lr' <- use lr\n sparse' <- use sparse\n let tolerance' = normalizedData' - lr' - sparse'\n tolerance .= tolerance'\n return $ (frobeniusNorm tolerance') ** 2\n\nupdateMu :: RobustPCAM ()\nupdateMu = do\n tolerance' <- use tolerance\n let tdStdDev = fold fastStdDev (toList $ flatten tolerance')\n let m = rows tolerance'\n let n = cols tolerance'\n mu .= max 0.01 (tdStdDev * ((2.0 * (fromIntegral $ max m n)) ** 0.5))\n\n", "meta": {"hexsha": "2d1b876aa9b7a1111eb709f347d1aab207e540a0", "size": 8339, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/RobustPCA.hs", "max_stars_repo_name": "jamesthompson/robust-pca", "max_stars_repo_head_hexsha": "155e1ebaf4258ef1d3ec9c0290c1e9f0f2515b11", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-10-23T15:36:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-17T15:59:40.000Z", "max_issues_repo_path": "src/RobustPCA.hs", "max_issues_repo_name": "jamesthompson/robust-pca", "max_issues_repo_head_hexsha": "155e1ebaf4258ef1d3ec9c0290c1e9f0f2515b11", "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/RobustPCA.hs", "max_forks_repo_name": "jamesthompson/robust-pca", "max_forks_repo_head_hexsha": "155e1ebaf4258ef1d3ec9c0290c1e9f0f2515b11", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-05-26T19:48:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-21T19:42:34.000Z", "avg_line_length": 37.5630630631, "max_line_length": 81, "alphanum_fraction": 0.4692409162, "num_tokens": 1976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624791, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5840423510757321}} {"text": "{-# LANGUAGE GeneralisedNewtypeDeriving #-}\n-- |\n-- Module Orbital\n--\n-- A probability distribution for driver laptimes, initialised from\n-- Elo-like ratings.\n--\n-- In the PDF, t = 0 is taken to be the ideal laptime in a track.\n--\n-- The name \"orbital\" alludes to this PDF originally having been, modulo\n-- constant factors, the radial probability density of the 1s hydrogen atom\n-- orbital. The corresponding distribution can be obtained by setting the\n-- gamma shape parameter to 3.\nmodule Orbital\n ( deltaWP\n , eloWP\n , initialRating\n , kFromRating\n , ratingFromK\n , OrbitalDistribution\n , orbitalDistr\n , orbitalK\n ) where\n\nimport Numeric.SpecFunctions (choose)\nimport Statistics.Distribution\nimport Statistics.Distribution.Gamma\nimport Data.MemoTrie\nimport Data.List (foldl')\n\n-- | The base implementation of victory probabilities for performances\n-- modelled by gamma distributions with the same (integer) shape.\nratioWP :: Int -> Double -> Double\nratioWP gsh = \\w -> w^gsh * evalPoly (memoWpCoefficient gsh) (gsh-1) w\n\n-- | A strict pair type.\ndata SP a b = SP !a !b\n\n-- | A polynomial evaluator. For our immediate purposes, it performs slightly\n-- better than the one available in 'Numeric.Polynomial'.\nevalPoly :: (Int -> Double) -> Int -> Double -> Double\nevalPoly coef n x = y\n where\n SP xn y = foldl' alg (SP 1 0) [0..n]\n alg (SP xx s) m = SP (x * xx) (coef m * xx + s)\n\n-- | Coefficients of the polynomial used in the gamma winning probability\n-- calculation.\nwpCoefficient :: Int -> Int -> Double\nwpCoefficient gsh m =\n (-1)^m * choose gsh m * choose (2*gsh-1) (gsh-1)\n * fromIntegral (gsh-m) / fromIntegral (gsh+m)\n\n-- | Memoised version of 'wpCoefficient'.\nmemoWpCoefficient :: Int -> Int -> Double\nmemoWpCoefficient = memo2 wpCoefficient\n\n-- | Initial rating for new racers. Defined as a constant here for\n-- expediteness, taking into account that making it configurable isn't as\n-- essential as it is making other engine parameters configurable.\ninitialRating :: Double\ninitialRating = 1500\n\n-- | The base Elo exponent. In essence, a logistic growth factor for expected\n-- scores/winning probabilities. The denominator used here, 400, is standard\n-- for chess rating computations. Using it, a 0.6 expected score corresponds\n-- to a ~70.4 rating gap, and a 0.9 expected score, to a ~382 gap.\neloAlpha :: Double\neloAlpha = log 10 / 400\n\n-- | Adjusts the k values obtained from ratings depending on the gamma shape so\n-- that the same rating gaps correspond to approximately the same winning\n-- probabilities.\n--\n-- The formula used here is made of two factors:\n--\n-- - A base correction, which on its own would adjust the derivative of\n-- @deltaWP gsh@ to match that of @deltaWP 1@ at zero. This factor, which is\n-- the best adjustment for rating gaps close to zero, slightly increases\n-- the absolute excess winning probabilities over the entire range of gaps.\n--\n-- - An additional correction, which reduces the aforementioned bias. Its value\n-- is chosen to (approximately) minimise the sum of the squares of the\n-- differences between @ratioWP gsh@ and @ratioWP 1@ over the entire range\n-- of ratios.\neloGammaCorrection :: Int -> Double\neloGammaCorrection gsh = extraAdjustment * baseCorrection\n where\n gsh' = fromIntegral gsh\n baseCorrection = 4^(gsh-1) / (gsh' * choose (2*gsh-1) (gsh-1))\n fittedConstant = (2*sqrt 29 - 3)*pi\n extraAdjustment = 1 - (gsh'-1) / (gsh' * fittedConstant)\n\n-- | Elo conversion factor. Amounts to eloAlpha for shape 1, in which case the\n-- gamma model coincides with the conventional Elo system.\neloFactor :: Int -> Double\neloFactor gsh = eloGammaCorrection gsh * eloAlpha\n\n-- | Memoised Elo conversion factor.\nmemoEloFactor :: Int -> Double\nmemoEloFactor = memo eloFactor\n\n-- | Winning probabilities for (scaled) rating differences. Ratings are\n-- essentially logarithms of the gamma distribution rate parameters.\ndeltaWP :: Int -> Double -> Double\ndeltaWP gsh = \\d -> ratioWP gsh (1 / (1 + exp(- memoEloFactor gsh * d)))\n-- If ru = log u, rv = log v, and d = ru - rv, then\n-- u / (u + v) = 1 / (1 + exp (-d))\n-- Another way of expressing the ratio is given by\n-- 1 / (1 + exp(-d)) = (1 + tanh (d/2)) / 2\n\n-- | Elo-based winning probability. This version takes the ratings of the two\n-- racers. Only here for reference, at least for now.\neloWP :: Double -> Double -> Double\neloWP ru rv = deltaWP 1 (ru-rv)\n\n-- | Rating that corresponds to a gamma rate parameter of 1.\n--\n-- As far as the results go, the effect of 'referenceRating' is superficial.\n-- Since it adjusts all ratings in the same manner, changing it does not affect\n-- the overall results.\n--\n-- There used to be a counterpart @referenceK@ definition, which was removed\n-- for being redundant. It is worth noting that scaling the conversions to make\n-- the gamma rate (\"k\") values larger slows down the calculations, probably by\n-- making it harder for the gamma distribution algorithms.\nreferenceRating :: Double\nreferenceRating = initialRating\n\n-- | k-to-rating conversion. Only for reference, at least for now.\nratingFromK :: Int -> Double -> Double\nratingFromK gsh u = referenceRating + log u / eloFactor gsh\n\n-- | rating-to-k conversion.\nkFromRating :: Int -> Double -> Double\nkFromRating gsh r = exp ((r - referenceRating) * eloFactor gsh)\n-- Using memoEloFactor instead of eloFactor here doesn't seem to improve\n-- performance.\n\n-- | The model distribution is a special case of the gamma distribution, with\n-- theta = 1/k.\nnewtype OrbitalDistribution = OrbitalDistribution\n { orbitalGamma :: GammaDistribution }\n deriving (Eq, Show, Distribution, ContDistr, ContGen, MaybeEntropy\n , Variance, MaybeVariance, Mean, MaybeMean)\n\n-- | Sets up the model distribution given a rating.\norbitalDistr\n :: Int -- ^ Shape parameter to be used.\n -> Double -- ^ Elo-like rating.\n -> OrbitalDistribution\norbitalDistr gsh r = OrbitalDistribution\n (gammaDistr (fromIntegral gsh) (1 / kFromRating gsh r))\n\n-- | Recovers the k factor from the distribution.\norbitalK :: OrbitalDistribution -> Double\norbitalK distr = 1 / gdScale (orbitalGamma distr)\n\n-- | Recovers the shape parameter from the distribution.\norbitalShape :: OrbitalDistribution -> Double\norbitalShape distr = gdShape (orbitalGamma distr)\n", "meta": {"hexsha": "5d7fb80e6ee206f04272d37ee588f982f3e479c1", "size": 6304, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Orbital.hs", "max_stars_repo_name": "duplode/elo-zs", "max_stars_repo_head_hexsha": "1496a6a46f9aa62dc3bf16d14e3ae8bb497c4a9f", "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": "Orbital.hs", "max_issues_repo_name": "duplode/elo-zs", "max_issues_repo_head_hexsha": "1496a6a46f9aa62dc3bf16d14e3ae8bb497c4a9f", "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": "Orbital.hs", "max_forks_repo_name": "duplode/elo-zs", "max_forks_repo_head_hexsha": "1496a6a46f9aa62dc3bf16d14e3ae8bb497c4a9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9135802469, "max_line_length": 79, "alphanum_fraction": 0.71875, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5838823273998907}} {"text": "{-# OPTIONS_GHC -Wall -Wno-partial-type-signatures #-}\n\n{-# LANGUAGE QuasiQuotes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n\n-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.Sundials.ARKode.ODE\n-- Copyright : Dominic Steinitz 2018,\n-- Novadiscovery 2018\n-- License : BSD\n-- Maintainer : Dominic Steinitz\n-- Stability : provisional\n--\n-- Solution of ordinary differential equation (ODE) initial value problems.\n-- See for more detail.\n--\n-- A simple example:\n--\n-- <>\n--\n-- @\n-- import Numeric.Sundials.ARKode.ODE\n-- import Numeric.LinearAlgebra\n--\n-- import Plots as P\n-- import qualified Diagrams.Prelude as D\n-- import Diagrams.Backend.Rasterific\n--\n-- brusselator :: Double -> [Double] -> [Double]\n-- brusselator _t x = [ a - (w + 1) * u + v * u * u\n-- , w * u - v * u * u\n-- , (b - w) / eps - w * u\n-- ]\n-- where\n-- a = 1.0\n-- b = 3.5\n-- eps = 5.0e-6\n-- u = x !! 0\n-- v = x !! 1\n-- w = x !! 2\n--\n-- lSaxis :: [[Double]] -> P.Axis B D.V2 Double\n-- lSaxis xs = P.r2Axis &~ do\n-- let ts = xs!!0\n-- us = xs!!1\n-- vs = xs!!2\n-- ws = xs!!3\n-- P.linePlot' $ zip ts us\n-- P.linePlot' $ zip ts vs\n-- P.linePlot' $ zip ts ws\n--\n-- main = do\n-- let res1 = odeSolve brusselator [1.2, 3.1, 3.0] (fromList [0.0, 0.1 .. 10.0])\n-- renderRasterific \"diagrams/brusselator.png\"\n-- (D.dims2D 500.0 500.0)\n-- (renderAxis $ lSaxis $ [0.0, 0.1 .. 10.0]:(toLists $ tr res1))\n-- @\n--\n-- With Sundials ARKode, it is possible to retrieve the Butcher\n-- tableau for the solver. FIXME: Not available just now and hopefully\n-- normal service will be resumed soon.\n--\n-- @\n-- import Numeric.Sundials.ARKode.ODE\n-- import Numeric.LinearAlgebra\n--\n-- import Data.List (intercalate)\n--\n-- import Text.PrettyPrint.HughesPJClass\n--\n--\n-- butcherTableauTex :: ButcherTable -> String\n-- butcherTableauTex (ButcherTable m c b b2) =\n-- render $\n-- vcat [ text (\"\\n\\\\begin{array}{c|\" ++ (concat $ replicate n \"c\") ++ \"}\")\n-- , us\n-- , text \"\\\\hline\"\n-- , text bs <+> text \"\\\\\\\\\"\n-- , text b2s <+> text \"\\\\\\\\\"\n-- , text \"\\\\end{array}\"\n-- ]\n-- where\n-- n = rows m\n-- rs = toLists m\n-- ss = map (\\r -> intercalate \" & \" $ map show r) rs\n-- ts = zipWith (\\i r -> show i ++ \" & \" ++ r) (toList c) ss\n-- us = vcat $ map (\\r -> text r <+> text \"\\\\\\\\\") ts\n-- bs = \" & \" ++ (intercalate \" & \" $ map show $ toList b)\n-- b2s = \" & \" ++ (intercalate \" & \" $ map show $ toList b2)\n--\n-- main :: IO ()\n-- main = do\n--\n-- let res = butcherTable (SDIRK_2_1_2 undefined)\n-- putStrLn $ show res\n-- putStrLn $ butcherTableauTex res\n--\n-- let resA = butcherTable (KVAERNO_4_2_3 undefined)\n-- putStrLn $ show resA\n-- putStrLn $ butcherTableauTex resA\n--\n-- let resB = butcherTable (SDIRK_5_3_4 undefined)\n-- putStrLn $ show resB\n-- putStrLn $ butcherTableauTex resB\n-- @\n--\n-- Using the code above from the examples gives\n--\n-- KVAERNO_4_2_3\n--\n-- \\[\n-- \\begin{array}{c|cccc}\n-- 0.0 & 0.0 & 0.0 & 0.0 & 0.0 \\\\\n-- 0.871733043 & 0.4358665215 & 0.4358665215 & 0.0 & 0.0 \\\\\n-- 1.0 & 0.490563388419108 & 7.3570090080892e-2 & 0.4358665215 & 0.0 \\\\\n-- 1.0 & 0.308809969973036 & 1.490563388254106 & -1.235239879727145 & 0.4358665215 \\\\\n-- \\hline\n-- & 0.308809969973036 & 1.490563388254106 & -1.235239879727145 & 0.4358665215 \\\\\n-- & 0.490563388419108 & 7.3570090080892e-2 & 0.4358665215 & 0.0 \\\\\n-- \\end{array}\n-- \\]\n--\n-- SDIRK_2_1_2\n--\n-- \\[\n-- \\begin{array}{c|cc}\n-- 1.0 & 1.0 & 0.0 \\\\\n-- 0.0 & -1.0 & 1.0 \\\\\n-- \\hline\n-- & 0.5 & 0.5 \\\\\n-- & 1.0 & 0.0 \\\\\n-- \\end{array}\n-- \\]\n--\n-- SDIRK_5_3_4\n--\n-- \\[\n-- \\begin{array}{c|ccccc}\n-- 0.25 & 0.25 & 0.0 & 0.0 & 0.0 & 0.0 \\\\\n-- 0.75 & 0.5 & 0.25 & 0.0 & 0.0 & 0.0 \\\\\n-- 0.55 & 0.34 & -4.0e-2 & 0.25 & 0.0 & 0.0 \\\\\n-- 0.5 & 0.2727941176470588 & -5.036764705882353e-2 & 2.7573529411764705e-2 & 0.25 & 0.0 \\\\\n-- 1.0 & 1.0416666666666667 & -1.0208333333333333 & 7.8125 & -7.083333333333333 & 0.25 \\\\\n-- \\hline\n-- & 1.0416666666666667 & -1.0208333333333333 & 7.8125 & -7.083333333333333 & 0.25 \\\\\n-- & 1.2291666666666667 & -0.17708333333333334 & 7.03125 & -7.083333333333333 & 0.0 \\\\\n-- \\end{array}\n-- \\]\n-----------------------------------------------------------------------------\nmodule Numeric.Sundials.ARKode.ODE ( odeSolve\n , odeSolveV\n , odeSolveVWith\n , odeSolveVWith'\n , odeSolveWithEvents\n , ODEMethod(..)\n , StepControl(..)\n ) where\n\nimport qualified Language.C.Inline as C\nimport qualified Language.C.Inline.Unsafe as CU\n\nimport Data.Monoid ((<>))\nimport Data.Maybe (isJust)\n\nimport Foreign.C.Types (CDouble, CInt)\nimport Foreign.Ptr (Ptr)\nimport Foreign.Storable (poke, peek)\n\nimport qualified Data.Vector.Storable as V\n\nimport Data.Coerce (coerce)\nimport System.IO.Unsafe (unsafePerformIO)\nimport GHC.Generics (C1, Constructor, (:+:)(..), D1, Rep, Generic, M1(..),\n from, conName)\n\nimport Numeric.LinearAlgebra.Devel (createVector)\n\nimport Numeric.LinearAlgebra.HMatrix (Vector, Matrix, toList, rows,\n cols, toLists, size, reshape,\n (><))\n\nimport Numeric.Sundials.Types\nimport qualified Numeric.Sundials.Arkode as T\nimport Numeric.Sundials.Arkode (SunIndexType)\nimport Numeric.Sundials.Arkode (sDIRK_2_1_2,\n bILLINGTON_3_3_2,\n tRBDF2_3_3_2,\n kVAERNO_4_2_3,\n aRK324L2SA_DIRK_4_2_3,\n cASH_5_2_4,\n cASH_5_3_4,\n sDIRK_5_3_4,\n kVAERNO_5_3_4,\n aRK436L2SA_DIRK_6_3_4,\n kVAERNO_7_4_5,\n aRK548L2SA_DIRK_8_4_5,\n hEUN_EULER_2_1_2,\n bOGACKI_SHAMPINE_4_2_3,\n aRK324L2SA_ERK_4_2_3,\n zONNEVELD_5_3_4,\n aRK436L2SA_ERK_6_3_4,\n sAYFY_ABURUB_6_3_4,\n cASH_KARP_6_4_5,\n fEHLBERG_6_4_5,\n dORMAND_PRINCE_7_4_5,\n aRK548L2SA_ERK_8_4_5,\n vERNER_8_5_6,\n fEHLBERG_13_7_8)\n\n\nC.context (C.baseCtx <> C.vecCtx <> C.funCtx <> sunCtx)\n\nC.include \"\"\nC.include \"\"\nC.include \"\"\nC.include \"\" -- prototypes for ARKODE fcts., consts.\nC.include \"\"\nC.include \"\" -- serial N_Vector types, fcts., macros\nC.include \"\" -- access to dense SUNMatrix\nC.include \"\" -- access to dense SUNLinearSolver\nC.include \"\" -- definition of type realtype\nC.include \"\"\nC.include \"../../../helpers.h\"\nC.include \"Numeric/Sundials/Arkode_hsc.h\"\n\n\n-- | Stepping functions\ndata ODEMethod = SDIRK_2_1_2 Jacobian\n | SDIRK_2_1_2'\n | BILLINGTON_3_3_2 Jacobian\n | BILLINGTON_3_3_2'\n | TRBDF2_3_3_2 Jacobian\n | TRBDF2_3_3_2'\n | KVAERNO_4_2_3 Jacobian\n | KVAERNO_4_2_3'\n | ARK324L2SA_DIRK_4_2_3 Jacobian\n | ARK324L2SA_DIRK_4_2_3'\n | CASH_5_2_4 Jacobian\n | CASH_5_2_4'\n | CASH_5_3_4 Jacobian\n | CASH_5_3_4'\n | SDIRK_5_3_4 Jacobian\n | SDIRK_5_3_4'\n | KVAERNO_5_3_4 Jacobian\n | KVAERNO_5_3_4'\n | ARK436L2SA_DIRK_6_3_4 Jacobian\n | ARK436L2SA_DIRK_6_3_4'\n | KVAERNO_7_4_5 Jacobian\n | KVAERNO_7_4_5'\n | ARK548L2SA_DIRK_8_4_5 Jacobian\n | ARK548L2SA_DIRK_8_4_5'\n | HEUN_EULER_2_1_2 Jacobian\n | HEUN_EULER_2_1_2'\n | BOGACKI_SHAMPINE_4_2_3 Jacobian\n | BOGACKI_SHAMPINE_4_2_3'\n | ARK324L2SA_ERK_4_2_3 Jacobian\n | ARK324L2SA_ERK_4_2_3'\n | ZONNEVELD_5_3_4 Jacobian\n | ZONNEVELD_5_3_4'\n | ARK436L2SA_ERK_6_3_4 Jacobian\n | ARK436L2SA_ERK_6_3_4'\n | SAYFY_ABURUB_6_3_4 Jacobian\n | SAYFY_ABURUB_6_3_4'\n | CASH_KARP_6_4_5 Jacobian\n | CASH_KARP_6_4_5'\n | FEHLBERG_6_4_5 Jacobian\n | FEHLBERG_6_4_5'\n | DORMAND_PRINCE_7_4_5 Jacobian\n | DORMAND_PRINCE_7_4_5'\n | ARK548L2SA_ERK_8_4_5 Jacobian\n | ARK548L2SA_ERK_8_4_5'\n | VERNER_8_5_6 Jacobian\n | VERNER_8_5_6'\n | FEHLBERG_13_7_8 Jacobian\n | FEHLBERG_13_7_8'\n deriving Generic\n\nconstrName :: (HasConstructor (Rep a), Generic a)=> a -> String\nconstrName = genericConstrName . from\n\nclass HasConstructor (f :: * -> *) where\n genericConstrName :: f x -> String\n\ninstance HasConstructor f => HasConstructor (D1 c f) where\n genericConstrName (M1 x) = genericConstrName x\n\ninstance (HasConstructor x, HasConstructor y) => HasConstructor (x :+: y) where\n genericConstrName (L1 l) = genericConstrName l\n genericConstrName (R1 r) = genericConstrName r\n\ninstance Constructor c => HasConstructor (C1 c f) where\n genericConstrName x = conName x\n\ninstance Show ODEMethod where\n show x = constrName x\n\n-- FIXME: We can probably do better here with generics\ngetMethod :: ODEMethod -> Int\ngetMethod (SDIRK_2_1_2 _) = sDIRK_2_1_2\ngetMethod (SDIRK_2_1_2') = sDIRK_2_1_2\ngetMethod (BILLINGTON_3_3_2 _) = bILLINGTON_3_3_2\ngetMethod (BILLINGTON_3_3_2') = bILLINGTON_3_3_2\ngetMethod (TRBDF2_3_3_2 _) = tRBDF2_3_3_2\ngetMethod (TRBDF2_3_3_2') = tRBDF2_3_3_2\ngetMethod (KVAERNO_4_2_3 _) = kVAERNO_4_2_3\ngetMethod (KVAERNO_4_2_3') = kVAERNO_4_2_3\ngetMethod (ARK324L2SA_DIRK_4_2_3 _) = aRK324L2SA_DIRK_4_2_3\ngetMethod (ARK324L2SA_DIRK_4_2_3') = aRK324L2SA_DIRK_4_2_3\ngetMethod (CASH_5_2_4 _) = cASH_5_2_4\ngetMethod (CASH_5_2_4') = cASH_5_2_4\ngetMethod (CASH_5_3_4 _) = cASH_5_3_4\ngetMethod (CASH_5_3_4') = cASH_5_3_4\ngetMethod (SDIRK_5_3_4 _) = sDIRK_5_3_4\ngetMethod (SDIRK_5_3_4') = sDIRK_5_3_4\ngetMethod (KVAERNO_5_3_4 _) = kVAERNO_5_3_4\ngetMethod (KVAERNO_5_3_4') = kVAERNO_5_3_4\ngetMethod (ARK436L2SA_DIRK_6_3_4 _) = aRK436L2SA_DIRK_6_3_4\ngetMethod (ARK436L2SA_DIRK_6_3_4') = aRK436L2SA_DIRK_6_3_4\ngetMethod (KVAERNO_7_4_5 _) = kVAERNO_7_4_5\ngetMethod (KVAERNO_7_4_5') = kVAERNO_7_4_5\ngetMethod (ARK548L2SA_DIRK_8_4_5 _) = aRK548L2SA_DIRK_8_4_5\ngetMethod (ARK548L2SA_DIRK_8_4_5') = aRK548L2SA_DIRK_8_4_5\ngetMethod (HEUN_EULER_2_1_2 _) = hEUN_EULER_2_1_2\ngetMethod (HEUN_EULER_2_1_2') = hEUN_EULER_2_1_2\ngetMethod (BOGACKI_SHAMPINE_4_2_3 _) = bOGACKI_SHAMPINE_4_2_3\ngetMethod (BOGACKI_SHAMPINE_4_2_3') = bOGACKI_SHAMPINE_4_2_3\ngetMethod (ARK324L2SA_ERK_4_2_3 _) = aRK324L2SA_ERK_4_2_3\ngetMethod (ARK324L2SA_ERK_4_2_3') = aRK324L2SA_ERK_4_2_3\ngetMethod (ZONNEVELD_5_3_4 _) = zONNEVELD_5_3_4\ngetMethod (ZONNEVELD_5_3_4') = zONNEVELD_5_3_4\ngetMethod (ARK436L2SA_ERK_6_3_4 _) = aRK436L2SA_ERK_6_3_4\ngetMethod (ARK436L2SA_ERK_6_3_4') = aRK436L2SA_ERK_6_3_4\ngetMethod (SAYFY_ABURUB_6_3_4 _) = sAYFY_ABURUB_6_3_4\ngetMethod (SAYFY_ABURUB_6_3_4') = sAYFY_ABURUB_6_3_4\ngetMethod (CASH_KARP_6_4_5 _) = cASH_KARP_6_4_5\ngetMethod (CASH_KARP_6_4_5') = cASH_KARP_6_4_5\ngetMethod (FEHLBERG_6_4_5 _) = fEHLBERG_6_4_5\ngetMethod (FEHLBERG_6_4_5' ) = fEHLBERG_6_4_5\ngetMethod (DORMAND_PRINCE_7_4_5 _) = dORMAND_PRINCE_7_4_5\ngetMethod (DORMAND_PRINCE_7_4_5') = dORMAND_PRINCE_7_4_5\ngetMethod (ARK548L2SA_ERK_8_4_5 _) = aRK548L2SA_ERK_8_4_5\ngetMethod (ARK548L2SA_ERK_8_4_5') = aRK548L2SA_ERK_8_4_5\ngetMethod (VERNER_8_5_6 _) = vERNER_8_5_6\ngetMethod (VERNER_8_5_6') = vERNER_8_5_6\ngetMethod (FEHLBERG_13_7_8 _) = fEHLBERG_13_7_8\ngetMethod (FEHLBERG_13_7_8') = fEHLBERG_13_7_8\n\ngetJacobian :: ODEMethod -> Maybe Jacobian\ngetJacobian (SDIRK_2_1_2 j) = Just j\ngetJacobian (BILLINGTON_3_3_2 j) = Just j\ngetJacobian (TRBDF2_3_3_2 j) = Just j\ngetJacobian (KVAERNO_4_2_3 j) = Just j\ngetJacobian (ARK324L2SA_DIRK_4_2_3 j) = Just j\ngetJacobian (CASH_5_2_4 j) = Just j\ngetJacobian (CASH_5_3_4 j) = Just j\ngetJacobian (SDIRK_5_3_4 j) = Just j\ngetJacobian (KVAERNO_5_3_4 j) = Just j\ngetJacobian (ARK436L2SA_DIRK_6_3_4 j) = Just j\ngetJacobian (KVAERNO_7_4_5 j) = Just j\ngetJacobian (ARK548L2SA_DIRK_8_4_5 j) = Just j\ngetJacobian (HEUN_EULER_2_1_2 j) = Just j\ngetJacobian (BOGACKI_SHAMPINE_4_2_3 j) = Just j\ngetJacobian (ARK324L2SA_ERK_4_2_3 j) = Just j\ngetJacobian (ZONNEVELD_5_3_4 j) = Just j\ngetJacobian (ARK436L2SA_ERK_6_3_4 j) = Just j\ngetJacobian (SAYFY_ABURUB_6_3_4 j) = Just j\ngetJacobian (CASH_KARP_6_4_5 j) = Just j\ngetJacobian (FEHLBERG_6_4_5 j) = Just j\ngetJacobian (DORMAND_PRINCE_7_4_5 j) = Just j\ngetJacobian (ARK548L2SA_ERK_8_4_5 j) = Just j\ngetJacobian (VERNER_8_5_6 j) = Just j\ngetJacobian (FEHLBERG_13_7_8 j) = Just j\ngetJacobian _ = Nothing\n\n-- | A version of 'odeSolveVWith' with reasonable default step control.\nodeSolveV\n :: ODEMethod\n -> Maybe Double -- ^ initial step size - by default, ARKode\n -- estimates the initial step size to be the\n -- solution \\(h\\) of the equation\n -- \\(\\|\\frac{h^2\\ddot{y}}{2}\\| = 1\\), where\n -- \\(\\ddot{y}\\) is an estimated value of the\n -- second derivative of the solution at \\(t_0\\)\n -> Double -- ^ absolute tolerance for the state vector\n -> Double -- ^ relative tolerance for the state vector\n -> (Double -> Vector Double -> Vector Double) -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> Vector Double -- ^ initial conditions\n -> Vector Double -- ^ desired solution times\n -> Matrix Double -- ^ solution\nodeSolveV meth hi epsAbs epsRel f y0 ts =\n odeSolveVWith meth (X epsAbs epsRel) hi g y0 ts\n where\n g t x0 = coerce $ f t x0\n\n-- | A version of 'odeSolveV' with reasonable default parameters and\n-- system of equations defined using lists. FIXME: we should say\n-- something about the fact we could use the Jacobian but don't for\n-- compatibility with hmatrix-gsl.\nodeSolve :: (Double -> [Double] -> [Double]) -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> [Double] -- ^ initial conditions\n -> Vector Double -- ^ desired solution times\n -> Matrix Double -- ^ solution\nodeSolve f y0 ts =\n -- FIXME: These tolerances are different from the ones in GSL\n odeSolveVWith SDIRK_5_3_4' (XX' 1.0e-6 1.0e-10 1 1) Nothing g (V.fromList y0) (V.fromList $ toList ts)\n where\n g t x0 = V.fromList $ f t (V.toList x0)\n\nodeSolveVWith ::\n ODEMethod\n -> StepControl\n -> Maybe Double -- ^ initial step size - by default, ARKode\n -- estimates the initial step size to be the\n -- solution \\(h\\) of the equation\n -- \\(\\|\\frac{h^2\\ddot{y}}{2}\\| = 1\\), where\n -- \\(\\ddot{y}\\) is an estimated value of the second\n -- derivative of the solution at \\(t_0\\)\n -> (Double -> V.Vector Double -> V.Vector Double) -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> V.Vector Double -- ^ Initial conditions\n -> V.Vector Double -- ^ Desired solution times\n -> Matrix Double -- ^ Error code or solution\nodeSolveVWith method control initStepSize f y0 tt =\n case odeSolveVWith' opts method control initStepSize f y0 tt of\n Left (c, _v) -> error $ show c -- FIXME\n Right (v, _d) -> v\n where\n opts = ODEOpts { maxNumSteps = 10000\n , minStep = 1.0e-12\n , maxFail = 10\n , odeMethod = error \"ARKode: unexpected use of ODEOpts.odeMethod\"\n , stepControl = error \"ARKode: unexpected use of ODEOpts.stepControl\"\n , initStep = error \"ARKode: unexpected use of ODEOpts.initStep\"\n }\n\nodeSolveVWith' ::\n ODEOpts ODEMethod\n -> ODEMethod\n -> StepControl\n -> Maybe Double -- ^ initial step size - by default, ARKode\n -- estimates the initial step size to be the\n -- solution \\(h\\) of the equation\n -- \\(\\|\\frac{h^2\\ddot{y}}{2}\\| = 1\\), where\n -- \\(\\ddot{y}\\) is an estimated value of the second\n -- derivative of the solution at \\(t_0\\)\n -> (Double -> V.Vector Double -> V.Vector Double) -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> V.Vector Double -- ^ Initial conditions\n -> V.Vector Double -- ^ Desired solution times\n -> Either (Matrix Double, Int) (Matrix Double, SundialsDiagnostics) -- ^ Error code or solution\nodeSolveVWith' opts method control initStepSize f y0 tt =\n case solveOdeC (fromIntegral $ maxFail opts)\n (fromIntegral $ maxNumSteps opts) (coerce $ minStep opts)\n (fromIntegral $ getMethod method) (coerce initStepSize) jacH (scise control)\n (coerce f) (coerce y0) (coerce tt) of\n Left (v, c) -> Left (reshape l (coerce v), fromIntegral c)\n Right (v, d)\n | V.null y0 -> Right ((V.length tt >< 0) [], emptyDiagnostics)\n | otherwise -> Right (reshape l (coerce v), d)\n where\n l = size y0\n scise (X aTol rTol) = coerce (V.replicate l aTol, rTol)\n scise (X' aTol rTol) = coerce (V.replicate l aTol, rTol)\n scise (XX' aTol rTol yScale _yDotScale) = coerce (V.replicate l aTol, yScale * rTol)\n -- FIXME; Should we check that the length of ss is correct?\n scise (ScXX' aTol rTol yScale _yDotScale ss) = coerce (V.map (* aTol) ss, yScale * rTol)\n jacH = fmap (\\g t v -> matrixToSunMatrix $ g (coerce t) (coerce v)) $\n getJacobian method\n matrixToSunMatrix m = T.SunMatrix { T.rows = nr, T.cols = nc, T.vals = vs }\n where\n nr = fromIntegral $ rows m\n nc = fromIntegral $ cols m\n -- FIXME: efficiency\n vs = V.fromList $ map coerce $ concat $ toLists m\n\n-- | This function implements the same interface as\n-- 'Numeric.Sundials.CVode.ODE.odeSolveWithEvents', although it does not\n-- currently support events.\nodeSolveWithEvents\n :: ODEOpts ODEMethod\n -> [EventSpec]\n -- ^ Event specifications\n -> Int\n -- ^ Maximum number of events\n -> (Double -> V.Vector Double -> V.Vector Double)\n -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> Maybe (Double -> Vector Double -> Matrix Double)\n -- ^ The Jacobian (optional)\n -> V.Vector Double\n -- ^ Initial conditions\n -> V.Vector Double\n -- ^ Desired solution times\n -> Either Int SundialsSolution\n -- ^ Either an error code or a solution\nodeSolveWithEvents opts events _ rhs _mb_jac y0 times\n | (not . null) events =\n -- Call error rather than return a Left because this is a programming\n -- error, not just a runtime issue.\n error $ \"ARKode called with a non-empty list of events (\" ++ show (length events) ++\n \" in total).\\\n \\ ARKode does not support events at this point and should not be passed any.\"\n | otherwise =\n let\n result :: Either (Matrix Double, Int)\n (Matrix Double, SundialsDiagnostics)\n result =\n odeSolveVWith' opts\n (odeMethod opts)\n (stepControl opts)\n (initStep opts)\n rhs y0 times\n in\n case result of\n Left (_, code) -> Left code\n Right (mx, diagn) ->\n Right $ SundialsSolution\n { actualTimeGrid = times\n , solutionMatrix =\n -- Note: at this time, ARKode's output matrix does not\n -- include the time column, so we're not dropping it\n -- here unlike in CVode. If/when we add event support\n -- to ARKode, this is going to change.\n mx\n , eventInfo = []\n , diagnostics = diagn\n }\n\nsolveOdeC ::\n CInt ->\n SunIndexType ->\n CDouble ->\n CInt ->\n Maybe CDouble ->\n (Maybe (CDouble -> V.Vector CDouble -> T.SunMatrix)) ->\n (V.Vector CDouble, CDouble) ->\n (CDouble -> V.Vector CDouble -> V.Vector CDouble) -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> V.Vector CDouble -- ^ Initial conditions\n -> V.Vector CDouble -- ^ Desired solution times\n -> Either (V.Vector CDouble, CInt) (V.Vector CDouble, SundialsDiagnostics) -- ^ Partial solution and error code or\n -- solution and diagnostics\nsolveOdeC maxErrTestFails maxNumSteps_ minStep_ method initStepSize\n jacH (aTols, rTol) fun f0 ts\n | V.null f0 = -- 0-dimensional (empty) system\n Right (V.empty, emptyDiagnostics)\n | otherwise =\n unsafePerformIO $ do\n let isInitStepSize :: CInt\n isInitStepSize = fromIntegral $ fromEnum $ isJust initStepSize\n ss :: CDouble\n ss = case initStepSize of\n -- It would be better to put an error message here but\n -- inline-c seems to evaluate this even if it is never\n -- used :(\n Nothing -> 0.0\n Just x -> x\n\n let dim = V.length f0\n nEq :: SunIndexType\n nEq = fromIntegral dim\n nTs :: CInt\n nTs = fromIntegral $ V.length ts\n quasiMatrixRes <- createVector ((fromIntegral dim) * (fromIntegral nTs))\n qMatMut <- V.thaw quasiMatrixRes\n diagMut :: V.MVector _ SunIndexType <- V.thaw =<< createVector 10 -- FIXME\n -- We need the types that sundials expects. These are tied together\n -- in 'CLangToHaskellTypes'. FIXME: The Haskell type is currently empty!\n let funIO :: CDouble -> Ptr T.SunVector -> Ptr T.SunVector -> Ptr () -> IO CInt\n funIO t y f _ptr = do\n sv <- peek y\n poke f $ T.SunVector { T.sunVecN = T.sunVecN sv\n , T.sunVecVals = fun t (T.sunVecVals sv)\n }\n [CU.exp| int{ 0 } |]\n let isJac :: CInt\n isJac = fromIntegral $ fromEnum $ isJust jacH\n jacIO :: CDouble -> Ptr T.SunVector -> Ptr T.SunVector -> Ptr T.SunMatrix ->\n Ptr () -> Ptr T.SunVector -> Ptr T.SunVector -> Ptr T.SunVector ->\n IO CInt\n jacIO t y _fy jacS _ptr _tmp1 _tmp2 _tmp3 = do\n case jacH of\n Nothing -> error \"Numeric.Sundials.ARKode.ODE: Jacobian not defined\"\n Just jacI -> do j <- jacI t <$> (T.sunVecVals <$> peek y)\n poke jacS j\n -- FIXME: I don't understand what this comment means\n -- Unsafe since the function will be called many times.\n [CU.exp| int{ 0 } |]\n\n res <- [C.block| int {\n /* general problem variables */\n\n int flag; /* reusable error-checking flag */\n int i, j; /* reusable loop indices */\n N_Vector y = NULL; /* empty vector for storing solution */\n N_Vector tv = NULL; /* empty vector for storing absolute tolerances */\n SUNMatrix A = NULL; /* empty matrix for linear solver */\n SUNLinearSolver LS = NULL; /* empty linear solver object */\n void *arkode_mem = NULL; /* empty ARKode memory structure */\n realtype t;\n long nst, nst_a, nfe, nfi, nsetups, nje, nfeLS, nni, ncfn, netf;\n\n /* general problem parameters */\n\n realtype T0 = RCONST(($vec-ptr:(double *ts))[0]); /* initial time */\n sunindextype NEQ = $(sunindextype nEq); /* number of dependent vars. */\n\n /* Initialize data structures */\n\n y = N_VNew_Serial(NEQ); /* Create serial vector for solution */\n if (check_flag((void *)y, \"N_VNew_Serial\", 0)) return 1;\n /* Specify initial condition */\n for (i = 0; i < NEQ; i++) {\n NV_Ith_S(y,i) = ($vec-ptr:(double *f0))[i];\n };\n\n tv = N_VNew_Serial(NEQ); /* Create serial vector for absolute tolerances */\n if (check_flag((void *)tv, \"N_VNew_Serial\", 0)) return 1;\n /* Specify tolerances */\n for (i = 0; i < NEQ; i++) {\n NV_Ith_S(tv,i) = ($vec-ptr:(double *aTols))[i];\n };\n\n /* Call ARKStepCreate to initialize the ARK timestepper module and */\n /* specify the right-hand side function in y'=f(t,y), the inital time */\n /* T0, and the initial dependent variable vector y. Note: since this */\n /* problem is fully implicit, we set f_E to NULL and f_I to f. */\n\n /* Here we use the C types defined in helpers.h which tie up with */\n /* the Haskell types defined in CLangToHaskellTypes */\n if ($(int method) < MIN_DIRK_NUM) {\n arkode_mem = ARKStepCreate($fun:(int (* funIO) (double t, SunVector y[], SunVector dydt[], void * params)), NULL, T0, y);\n if (check_flag((void *)arkode_mem, \"ARKStepCreate\", 0)) return 1;\n } else {\n arkode_mem = ARKStepCreate(NULL, $fun:(int (* funIO) (double t, SunVector y[], SunVector dydt[], void * params)), T0, y);\n if (check_flag(&flag, \"ARKStepCreate\", 0)) return 1;\n }\n\n flag = ARKStepSetMinStep(arkode_mem, $(double minStep_));\n if (check_flag(&flag, \"ARKStepSetMinStep\", 1)) return 1;\n flag = ARKStepSetMaxNumSteps(arkode_mem, $(sunindextype maxNumSteps_));\n if (check_flag(&flag, \"ARKStepSetMaxNumSteps\", 1)) return 1;\n flag = ARKStepSetMaxErrTestFails(arkode_mem, $(int maxErrTestFails));\n if (check_flag(&flag, \"ARKStepSetMaxErrTestFails\", 1)) return 1;\n\n /* Set routines */\n flag = ARKStepSVtolerances(arkode_mem, $(double rTol), tv);\n if (check_flag(&flag, \"ARKStepSVtolerances\", 1)) return 1;\n\n /* Initialize dense matrix data structure and solver */\n A = SUNDenseMatrix(NEQ, NEQ);\n if (check_flag((void *)A, \"SUNDenseMatrix\", 0)) return 1;\n LS = SUNDenseLinearSolver(y, A);\n if (check_flag((void *)LS, \"SUNDenseLinearSolver\", 0)) return 1;\n\n /* Attach matrix and linear solver */\n flag = ARKStepSetLinearSolver(arkode_mem, LS, A);\n if (check_flag(&flag, \"ARKStepSetLinearSolver\", 1)) return 1;\n\n /* Set the initial step size if there is one */\n if ($(int isInitStepSize)) {\n /* FIXME: We could check if the initial step size is 0 */\n /* or even NaN and then throw an error */\n flag = ARKStepSetInitStep(arkode_mem, $(double ss));\n if (check_flag(&flag, \"ARKStepSetInitStep\", 1)) return 1;\n }\n\n /* Set the Jacobian if there is one */\n if ($(int isJac)) {\n flag = ARKStepSetJacFn(arkode_mem, $fun:(int (* jacIO) (double t, SunVector y[], SunVector fy[], SunMatrix Jac[], void * params, SunVector tmp1[], SunVector tmp2[], SunVector tmp3[])));\n if (check_flag(&flag, \"ARKStepSetJacFn\", 1)) return 1;\n }\n\n /* Store initial conditions */\n for (j = 0; j < NEQ; j++) {\n ($vec-ptr:(double *qMatMut))[0 * $(int nTs) + j] = NV_Ith_S(y,j);\n }\n\n /* Explicitly set the method */\n if ($(int method) >= MIN_DIRK_NUM) {\n flag = ARKStepSetTableNum(arkode_mem, $(int method), -1);\n if (check_flag(&flag, \"ARKStepSetTableNum\", 1)) return 1;\n } else {\n flag = ARKStepSetTableNum(arkode_mem, -1, $(int method));\n if (check_flag(&flag, \"ERKStepSetTableNum\", 1)) return 1;\n }\n\n /* Main time-stepping loop: calls ARKStep to perform the integration */\n /* Stops when the final time has been reached */\n for (i = 1; i < $(int nTs); i++) {\n\n flag = ARKStepEvolve(arkode_mem, ($vec-ptr:(double *ts))[i], y, &t, ARK_NORMAL); /* call integrator */\n if (check_flag(&flag, \"ARKStep solver failure, stopping integration\", 1)) return 1;\n\n /* Store the results for Haskell */\n for (j = 0; j < NEQ; j++) {\n ($vec-ptr:(double *qMatMut))[i * NEQ + j] = NV_Ith_S(y,j);\n }\n }\n\n /* Get some final statistics on how the solve progressed */\n\n flag = ARKStepGetNumSteps(arkode_mem, &nst);\n check_flag(&flag, \"ARKStepGetNumSteps\", 1);\n ($vec-ptr:(sunindextype *diagMut))[0] = nst;\n\n flag = ARKStepGetNumStepAttempts(arkode_mem, &nst_a);\n check_flag(&flag, \"ARKStepGetNumStepAttempts\", 1);\n ($vec-ptr:(sunindextype *diagMut))[1] = nst_a;\n\n flag = ARKStepGetNumRhsEvals(arkode_mem, &nfe, &nfi);\n check_flag(&flag, \"ARKStepGetNumRhsEvals\", 1);\n ($vec-ptr:(sunindextype *diagMut))[2] = nfe;\n ($vec-ptr:(sunindextype *diagMut))[3] = nfi;\n\n flag = ARKStepGetNumLinSolvSetups(arkode_mem, &nsetups);\n check_flag(&flag, \"ARKStepGetNumLinSolvSetups\", 1);\n ($vec-ptr:(sunindextype *diagMut))[4] = nsetups;\n\n flag = ARKStepGetNumErrTestFails(arkode_mem, &netf);\n check_flag(&flag, \"ARKStepGetNumErrTestFails\", 1);\n ($vec-ptr:(sunindextype *diagMut))[5] = netf;\n\n flag = ARKStepGetNumNonlinSolvIters(arkode_mem, &nni);\n check_flag(&flag, \"ARKStepGetNumNonlinSolvIters\", 1);\n ($vec-ptr:(sunindextype *diagMut))[6] = nni;\n\n flag = ARKStepGetNumNonlinSolvConvFails(arkode_mem, &ncfn);\n check_flag(&flag, \"ARKStepGetNumNonlinSolvConvFails\", 1);\n ($vec-ptr:(sunindextype *diagMut))[7] = ncfn;\n\n flag = ARKStepGetNumJacEvals(arkode_mem, &nje);\n check_flag(&flag, \"ARKStepGetNumJacEvals\", 1);\n ($vec-ptr:(sunindextype *diagMut))[8] = nje;\n\n flag = ARKStepGetNumLinRhsEvals(arkode_mem, &nfeLS);\n check_flag(&flag, \"ARKStepGetNumLinRhsEvals\", 1);\n ($vec-ptr:(sunindextype *diagMut))[9] = nfeLS;\n\n /* Clean up and return */\n N_VDestroy(y); /* Free y vector */\n N_VDestroy(tv); /* Free tv vector */\n ARKStepFree(&arkode_mem); /* Free integrator memory */\n SUNLinSolFree(LS); /* Free linear solver */\n SUNMatDestroy(A); /* Free A matrix */\n\n return flag;\n } |]\n preD <- V.freeze diagMut\n let d = SundialsDiagnostics (fromIntegral $ preD V.!0)\n (fromIntegral $ preD V.!1)\n (fromIntegral $ preD V.!2)\n (fromIntegral $ preD V.!3)\n (fromIntegral $ preD V.!4)\n (fromIntegral $ preD V.!5)\n (fromIntegral $ preD V.!6)\n (fromIntegral $ preD V.!7)\n (fromIntegral $ preD V.!8)\n (fromIntegral $ preD V.!9)\n m <- V.freeze qMatMut\n if res == 0\n then do\n return $ Right (m, d)\n else do\n return $ Left (m, res)\n", "meta": {"hexsha": "4736d98aa444ccbc4519f56c4321dd3f01ed0488", "size": 35425, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Sundials/ARKode/ODE.hs", "max_stars_repo_name": "idontgetoutmuch/hmatrix-sundials", "max_stars_repo_head_hexsha": "af279b7b16e9f4586c67c61954c6c847a8caf815", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-22T06:07:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-22T06:07:25.000Z", "max_issues_repo_path": "src/Numeric/Sundials/ARKode/ODE.hs", "max_issues_repo_name": "idontgetoutmuch/hmatrix-sundials", "max_issues_repo_head_hexsha": "af279b7b16e9f4586c67c61954c6c847a8caf815", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Sundials/ARKode/ODE.hs", "max_forks_repo_name": "idontgetoutmuch/hmatrix-sundials", "max_forks_repo_head_hexsha": "af279b7b16e9f4586c67c61954c6c847a8caf815", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8279430789, "max_line_length": 212, "alphanum_fraction": 0.5279604799, "num_tokens": 10381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5835212818616524}} {"text": "import Data.Complex\n\n#include \"../Prelude.hs\"\n\nf :: Int -> Complex Double\nf n = mkPolar 1 ((2 Prelude.* Prelude.pi) / Prelude.fromIntegral n) Prelude.^ n\n\nrealPart'Double = realPart :: Complex Double -> Double\nadd'ComplexDouble = (Prelude.+) :: Complex Double -> Complex Double -> Complex Double\nlit0'ComplexDouble = 0 :: Complex Double\n", "meta": {"hexsha": "fd2597301b8f89df16ee9627063c1194c7acc05b", "size": 337, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/imaginary/X2N1.hs", "max_stars_repo_name": "batterseapower/chsc", "max_stars_repo_head_hexsha": "45940e4e93b97a5bb6137538e68a8fd58194dc69", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-03-16T17:02:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-21T15:08:02.000Z", "max_issues_repo_path": "examples/imaginary/X2N1.hs", "max_issues_repo_name": "batterseapower/chsc", "max_issues_repo_head_hexsha": "45940e4e93b97a5bb6137538e68a8fd58194dc69", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/imaginary/X2N1.hs", "max_forks_repo_name": "batterseapower/chsc", "max_forks_repo_head_hexsha": "45940e4e93b97a5bb6137538e68a8fd58194dc69", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-05-28T19:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-06T11:42:52.000Z", "avg_line_length": 30.6363636364, "max_line_length": 85, "alphanum_fraction": 0.7091988131, "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5834959346690869}} {"text": "\nmodule Solve (\n\tverboseSolve\n\t) where\n\nimport qualified Data.DList as D\nimport qualified Data.IntMap.Lazy as M\nimport Data.Complex (realPart, Complex((:+)))\nimport Control.Monad.Trans.Writer\nimport Control.Monad.Trans.State\n\nimport Data.MyPolynomial\nimport Data.MyPolynomial.Print\n\ntype ComplexF = Complex Float\ntype ShowD = D.DList Char\ndata Solvability b = IsBroad b | Degree | Clear\n\n\n\n\n\nsToShowD :: String -> D.DList ShowD\nsToShowD s = (D.singleton . D.fromList) s\n\ntoShowD :: [String] -> D.DList ShowD\ntoShowD ls = ( D.fromList . ( fmap D.fromList ) ) ls\n\n\n\n\n\ndiscriminantSpeech :: Float -> Writer (D.DList ShowD) ()\ndiscriminantSpeech d = let s = case (compare d 0) of\tLT -> \"strictly negative, the two complex solutions are:\\n\"\n\t\t\t\t\t\t\tGT -> \"strictly positive, the two real solutions are:\\n\"\n\t\t\t\t\t\t\tEQ -> \"null, the unique solution is:\\n\"\n\t\t\t\tin tell $ toShowD [\"The discriminant is \", s]\n\n\n\n\nunrootableSpeech :: Solvability BroadSol -> Writer (D.DList ShowD) ()\nunrootableSpeech (IsBroad Absurd) = tell $ sToShowD \"Cannot solve: absurd.\\n\"\nunrootableSpeech (IsBroad Real) = tell $ sToShowD \"The solution is |R itself.\\n\"\nunrootableSpeech Degree = tell $ sToShowD \"The polynomial degree is strictly greater than 2, I can't solve.\"\nunrootableSpeech _ = return ()\n\n\n\n\ndegSolvability :: Int -> Solvability b\ndegSolvability d | d >= 0 && d <= 2\t= Clear\n\t\t | otherwise\t\t= Degree\n\n\n -- Tells solution/root(s) with mention of exclusion.\ntellSolutions :: Maybe Float -> Roots -> [ComplexF] -> Writer (D.DList ShowD) ()\ntellSolutions delta (c1, c2) badRoots\n\t| delta == Just 0 = tell $ toShowD $ tellBad [c1] badRoots \"root\" []\n\t| Nothing <- delta = tell $ toShowD $ tellBad [c1] badRoots \"solution\" []\n\t| otherwise = tell $ toShowD $ tellBad [c1, c2] badRoots \"root\" []\n where\n tellBad (rt:rts) bad w =\n \tcase rt `elem` bad of\tTrue -> ([prettyComplex rt, \" (excluded \" ++ w ++ \")\"] ++) . next\n \t\t\t\t_ -> ([prettyComplex rt] ++) . next\n \t where\n \t next = case rts of\t(r:_) -> ([\"\\n\"] ++) . tellBad rts bad w\n \t \t\t\t[] -> ([] ++)\n\n\n\ntellReduced :: Int -> M.IntMap Float -> Writer (D.DList ShowD) ()\ntellReduced deg map = tell $ toShowD [\"Reduced form: \", porcelainPolynomialSM dMap \"\", \" = 0\\n\"]\n\twhere dMap = M.filterWithKey (\\k _ -> k <= deg) map\n\ntellNatural :: M.IntMap Float -> Writer (D.DList ShowD) ()\ntellNatural map = tell $ toShowD [\"Natural reduced form: \", prettyPolynomialM map, \" = 0\\n\"]\n\n\ntellForbidden :: [ComplexF] -> Writer (D.DList ShowD) ()\ntellForbidden [] = return ()\ntellForbidden frts = tell $ toShowD $ [\"Excluded roots/solutions:\\n\"] ++ (showForbidden frts [])\n where\n showForbidden [] = ([] ++)\n showForbidden (fr:fs) = ([prettyComplex fr, \"\\n\"]++) . showForbidden fs\n\n\n\n\n\nverboseSolve :: Equation -> Writer (D.DList ShowD) (Equation, Maybe Solution)\nverboseSolve eq = do\n\ttellReduced deg mapPol\n\ttellNatural mapPol\n\ttell $ toShowD [\"Polynomial degree: \", show deg, \"\\n\"]\n\ttellForbidden badRoots\n\tcase degSolvability deg of\tClear -> doSolve\n\t\t\t\t\tDegree -> quit Degree\n where\n Eq (cl, cr) = canonify eq\n (straightP, badRoots) = runState ( handleNegativePowers cl ) []\n ceq = Eq (straightP, cr)\t-- canonified equation with negative powers lifted\n mapPol = toMap straightP\t-- left polynomial as an IntMap\n deg = degree mapPol\t\t-- left polynomial degree\n\n -- doSolve :: Writer (D.DList ShowD) (Equation, Maybe Solution)\n doSolve = do\n \tlet sol = solveEquation ceq\n\t in case sol of\tQuadratic _\t-> result sol\n\t\t\t\tSimple _\t-> result sol\n\t\t\t\tBroad b\t\t-> quit (IsBroad b)\n\n -- quit :: Solvability b -> Writer (D.DList ShowD) (Equation, Maybe Solution)\n quit sb = do\n \tunrootableSpeech sb\n\tlet ret = case sb of\tDegree -> Nothing\n\t\t\t\tIsBroad b -> Just (Broad b)\n\treturn (ceq, ret)\n\n -- result :: Solution s -> Writer (D.DList ShowD) (Equation, Maybe Solution)\n result sol@(Quadratic rts) = do\n\tlet delta = discriminantQuadratic mapPol\n\tdiscriminantSpeech delta\n\ttellSolutions (Just delta) rts badRoots\n\treturn ( ceq, Just sol )\n result sol@(Simple fl) = do\n\ttell $ toShowD [ \"The solution is:\\n\" ]\n\ttellSolutions Nothing (fl :+ 0, 0 :+ 0) badRoots\n\treturn ( ceq, Just sol )\n\n\n", "meta": {"hexsha": "cceeab4c14f1511bd13e26ae711099b3edb91223", "size": 4166, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Solve.hs", "max_stars_repo_name": "flhorizon/haskell101-mysolver", "max_stars_repo_head_hexsha": "cbe765aece45877cf27392e0acd7423f816652a4", "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/Solve.hs", "max_issues_repo_name": "flhorizon/haskell101-mysolver", "max_issues_repo_head_hexsha": "cbe765aece45877cf27392e0acd7423f816652a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-16T23:02:36.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-16T23:02:36.000Z", "max_forks_repo_path": "src/Solve.hs", "max_forks_repo_name": "flhorizon/haskell101-solver", "max_forks_repo_head_hexsha": "cbe765aece45877cf27392e0acd7423f816652a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5606060606, "max_line_length": 112, "alphanum_fraction": 0.6656265002, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5832064774375152}} {"text": "module Math.IRT.Model.TwoPLM\n ( TwoPLM (..)\n ) where\n\nimport Statistics.Distribution\n\nimport Math.IRT.Internal.Distribution\nimport Math.IRT.Internal.LogLikelihood\nimport Math.IRT.Model.FourPLM ( FourPLM(..) )\nimport Math.IRT.Model.Generic\n\n\ndata TwoPLM = TwoPLM { discrimination :: !Double\n , difficulty :: !Double\n } deriving (Show)\n\ninstance Distribution TwoPLM where\n cumulative = cumulative . toFourPLM\n\ninstance ContDistr TwoPLM where\n density = density . toFourPLM\n quantile _ = error \"This shouldn't be needed\"\n\ninstance DensityDeriv TwoPLM where\n densityDeriv = densityDeriv . toFourPLM\n\ninstance GenericModel TwoPLM where\n fromRasch b = TwoPLM 1.0 b\n fromOnePLM b = TwoPLM 1.7 b\n fromTwoPLM = TwoPLM\n fromThreePLM a b _ = TwoPLM a b\n fromFourPLM a b _ _ = TwoPLM a b\n\ninstance LogLikelihood TwoPLM where\n logLikelihood b = logLikelihood b . toFourPLM\n\ntoFourPLM :: TwoPLM -> FourPLM\ntoFourPLM (TwoPLM sa sb) = FourPLM sa sb 0.0 1.0\n", "meta": {"hexsha": "360d27d43a616ccaa4fd7dc521b3f95cfeb2088b", "size": 1049, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/IRT/Model/TwoPLM.hs", "max_stars_repo_name": "argiopetech/irt", "max_stars_repo_head_hexsha": "ee136da44235bf7ecde4d516adfa8b22899ca0b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-06T08:31:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T08:31:33.000Z", "max_issues_repo_path": "Math/IRT/Model/TwoPLM.hs", "max_issues_repo_name": "argiopetech/irt", "max_issues_repo_head_hexsha": "ee136da44235bf7ecde4d516adfa8b22899ca0b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/IRT/Model/TwoPLM.hs", "max_forks_repo_name": "argiopetech/irt", "max_forks_repo_head_hexsha": "ee136da44235bf7ecde4d516adfa8b22899ca0b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8974358974, "max_line_length": 49, "alphanum_fraction": 0.683508103, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.58301972314698}} {"text": "module HLearn.Models.Distributions.Multivariate.MultiNormalFast\n ( MultiNormal \n , covar\n )\n where\n\nimport Control.DeepSeq\nimport qualified Data.Foldable as F\nimport qualified Data.Semigroup as SG\n\nimport Foreign.Storable\nimport Numeric.LinearAlgebra hiding ((<>))\nimport qualified Numeric.LinearAlgebra as LA\n\nimport HLearn.Algebra\nimport HLearn.Models.Distributions.Common\n\n-------------------------------------------------------------------------------\n-- data types \n\ntype MultiNormal dp = AddUnit1 MultiNormal' dp\n\ndata MultiNormal' dp = MultiNormal' \n { raw :: !(RawMoments dp)\n , meanV :: Vector (Ring dp)\n , covarM :: Matrix (Ring dp)\n , invcovarM :: Matrix (Ring dp)\n , pdfdenom :: Ring dp\n }\n\nderiving instance (Element (Ring dp), Read (Ring dp)) => Read (MultiNormal' dp)\nderiving instance (Element (Ring dp), Show (Ring dp)) => Show (MultiNormal' dp)\n\ninstance (NFData (Ring dp), Storable (Ring dp)) => NFData (MultiNormal' dp) where\n rnf m = deepseq (raw m) \n $ deepseq (meanV m) \n $ deepseq (covarM m) \n $ deepseq (invcovarM m) \n $ rnf (pdfdenom m)\n\n---------------------------------------\n\ndata RawMoments dp = RawMoments\n { m0 :: !(Ring dp)\n , m1 :: !(Vector (Ring dp))\n , m2 :: !(Matrix (Ring dp))\n }\n\nderiving instance (Element (Ring dp), Read (Ring dp)) => Read (RawMoments dp)\nderiving instance (Element (Ring dp), Show (Ring dp)) => Show (RawMoments dp)\n\ninstance NFData (RawMoments dp) where\n rnf rm = seq (m0 rm) \n $ seq (m1 rm) \n $ seq (m2 rm) ()\n\n---------------------------------------\n\ncovar :: MultiNormal dp -> Matrix (Ring dp)\ncovar (UnitLift1 m) = covarM m\n\nmkMultiNormal' :: \n ( Storable (Ring dp)\n , Element (Ring dp)\n , Field (Ring dp)\n , Floating (Ring dp)\n ) => RawMoments dp -> MultiNormal' dp\nmkMultiNormal' raw = MultiNormal'\n { raw = raw\n , meanV = meanV' \n , covarM = covarM'\n , invcovarM = inv covarM'\n , pdfdenom = 1/(sqrt $ det covarM' * (2*pi)^d)\n }\n where\n n = m0 raw\n d = dim $ m1 raw\n meanV' = mapVector (/n) (m1 raw)\n covarM' = mapMatrixWithIndex (\\(i,j) mij -> (mij/n-(meanV' @> j)*(meanV' @> i))) (m2 raw)\n\n-------------------------------------------------------------------------------\n-- algebra\n\ninstance \n ( Container Matrix (Ring dp)\n , Container Vector (Ring dp)\n , Field (Ring dp)\n , Floating (Ring dp)\n ) => SG.Semigroup (MultiNormal' dp) \n where\n d1 <> d2 = mkMultiNormal' $ RawMoments \n { m0 = m0 (raw d1) + m0 (raw d2)\n , m1 = m1 (raw d1) `LA.add` m1 (raw d2)\n , m2 = m2 (raw d1) `LA.add` m2 (raw d2)\n }\n\n-------------------------------------------------------------------------------\n-- training \n\ninstance Num a => HasRing [a] where \n type Ring [a] = a\n\ninstance \n ( Element r \n , Container Vector r\n , Field r\n , Floating r\n , Ring (dp r) ~ r\n , F.Foldable dp\n ) => HomTrainer (MultiNormal (dp r)) \n where\n type Datapoint (MultiNormal (dp r)) = dp r\n\n train1dp dp = UnitLift1 . mkMultiNormal' $ RawMoments\n { m0 = 1\n , m1 = fromList $ F.toList dp \n , m2 = n> PDF (MultiNormal (dp r)) \n where\n pdf (UnitLift1 dist) dp = pdfdenom dist * (exp $ (-1/2) * top) \n where\n x = fromList $ F.toList dp\n top=minElement $ ((asRow x) `sub` (asRow $ meanV dist)) \n LA.<> (invcovarM dist) \n LA.<> ((asColumn x) `sub` (asColumn $ meanV dist))\n", "meta": {"hexsha": "b7ca0a04f5a3b35a1858dfc41905d03990c4552a", "size": 4010, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HLearn/Models/Distributions/Multivariate/MultiNormalFast.hs", "max_stars_repo_name": "silky/HLearn", "max_stars_repo_head_hexsha": "86423d1c9ed7939640efba7db40628dbd21797fd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T11:33:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T11:33:36.000Z", "max_issues_repo_path": "src/HLearn/Models/Distributions/Multivariate/MultiNormalFast.hs", "max_issues_repo_name": "silky/HLearn", "max_issues_repo_head_hexsha": "86423d1c9ed7939640efba7db40628dbd21797fd", "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/HLearn/Models/Distributions/Multivariate/MultiNormalFast.hs", "max_forks_repo_name": "silky/HLearn", "max_forks_repo_head_hexsha": "86423d1c9ed7939640efba7db40628dbd21797fd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.041958042, "max_line_length": 97, "alphanum_fraction": 0.5149625935, "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.582858417521826}} {"text": "-- Copyright 2021 Google LLC\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{-# OPTIONS_GHC -Wall #-}\nmodule LeastSquaresVoting\n ( vote\n ) where\n\nimport Control.Arrow\nimport Data.HashMap.Strict ( HashMap )\nimport qualified Data.HashMap.Strict as M\nimport Data.Hashable ( Hashable(..) )\nimport Data.List ( sortBy )\nimport Data.Maybe ( fromMaybe )\nimport Data.Monoid ( Sum(..) )\nimport Data.Ord ( comparing )\nimport Numeric.LinearAlgebra ( (><)\n , Matrix\n , flatten\n , linearSolveSVD\n , toList\n )\n\nimport Types\n\n-- | Let _(u, v)_ be a pair of candidates in a voter's ordered list. This means\n-- that the voter's intent is that _u_ is ideally ranked a unit _D_ (1V) higher\n-- than _v_. When their potentials are _U_ and _V_, the difference from the intent\n-- will be _(U-V)-1_.\n--\n-- The **heat** (corresponding to the heat dissipated by an electrical\n-- resistor) is the square of the difference multiplied by a unit conductivity\n-- _G_ (which represents the voter's ability to influence the outcome).\n--\n-- ((U-V)-D)^2 G.\n--\n-- Partial derivatives\n-- d/dU ... = 2 G (U-V-D)\n-- d/dV ... = - 2 G (U-V-D)\nedge :: (Integral c, Num n) => c -> a -> a -> [(a, [(a, n)], n)]\nedge count u v =\n let c = fromIntegral count\n in [(u, [(u, c), (v, -c)], -c), (v, [(u, -c), (v, c)], c)]\n\nnewtype IndexedMonoid i m = IndexedMonoid (HashMap i m)\n deriving (Eq, Show, Read)\n\ninstance (Eq i, Hashable i, Semigroup m) => Semigroup (IndexedMonoid i m) where\n IndexedMonoid m1 <> IndexedMonoid m2 = IndexedMonoid $ M.unionWith (<>) m1 m2\n\ninstance (Eq i, Hashable i, Monoid m) => Monoid (IndexedMonoid i m) where\n mempty = IndexedMonoid M.empty\n\ninsert :: (Eq i, Hashable i, Semigroup m) => i -> m -> IndexedMonoid i m\ninsert i m = IndexedMonoid $ M.singleton i m\n\nilookup :: (Eq i, Hashable i, Monoid m) => i -> IndexedMonoid i m -> m\nilookup i (IndexedMonoid m) = fromMaybe mempty $ M.lookup i m\n\nsize :: (Hashable i) => IndexedMonoid i m -> Int\nsize (IndexedMonoid m) = M.size m\n\nindices :: (Hashable i) => IndexedMonoid i m -> [i]\nindices (IndexedMonoid m) = M.keys m\n\ntype LinearSystem a n = IndexedMonoid a (IndexedMonoid a (Sum n), (Sum n))\n\nsumEdges :: (Hashable a, Eq a, Num n) => [(a, [(a, n)], n)] -> LinearSystem a n\nsumEdges = foldMap\n (\\(c, ls, r) -> insert c (foldMap (uncurry insert . second Sum) ls, Sum r))\n\n\nequations\n :: (Hashable a, Eq a)\n => [a]\n -> LinearSystem a Double\n -> (Matrix Double, Matrix Double)\nequations is m =\n ( (n >< n)\n [ getSum $ ilookup col (fst (ilookup row m)) | row <- is, col <- is ]\n , (n >< 1) [ getSum $ snd (ilookup row m) | row <- is ]\n )\n where n = size m\n\nsolve :: (Hashable a, Eq a) => LinearSystem a Double -> [(a, Double)]\nsolve m =\n sortBy (comparing snd)\n . zip is\n . toList\n . flatten\n . uncurry linearSolveSVD\n . equations is\n $ m\n where is = indices m\n\nvote :: (Eq a, Hashable a, Integral n) => Prefs a n -> [(a, Double)]\nvote (Prefs []) = []\nvote (Prefs prefs@((_, cs) : _)) | null edges = zip cs (repeat 0)\n | otherwise = solve . sumEdges $ edges\n where\n edges =\n [ e\n | (count, order) <- prefs\n , (u , v ) <- zip order (tail order)\n , e <- edge count u v\n ]\n", "meta": {"hexsha": "80ca0040dccad86eeee63d8104ed4e8e0fcd5c4a", "size": 4179, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/LeastSquaresVoting.hs", "max_stars_repo_name": "ppetr/least-squares-electric-voting", "max_stars_repo_head_hexsha": "9d4634885b46b5affd675bbf2ddcf2e24647af8c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LeastSquaresVoting.hs", "max_issues_repo_name": "ppetr/least-squares-electric-voting", "max_issues_repo_head_hexsha": "9d4634885b46b5affd675bbf2ddcf2e24647af8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LeastSquaresVoting.hs", "max_forks_repo_name": "ppetr/least-squares-electric-voting", "max_forks_repo_head_hexsha": "9d4634885b46b5affd675bbf2ddcf2e24647af8c", "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": 35.4152542373, "max_line_length": 82, "alphanum_fraction": 0.5680784877, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5828254631411319}} {"text": "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE StrictData #-}\n\n------------------------------------------------\n-- |\n-- Module : Numeric.Matrix.Integral.NormalForms\n-- Copyright : (c) Jun Yoshida 2019\n-- License : BSD3\n--\n-- Hermite Normal form and Smith normal form.\n-- The functions are implemented with C; see the source files in src/Internal/C.\n--\n------------------------------------------------\n\nmodule Numeric.Matrix.Integral.NormalForms (\n hermiteNFST,\n hermiteNF,\n smithNFST,\n smithNF,\n smithRepST,\n smithRep\n ) where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Unsafe\n\nimport Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Devel\n\nimport System.IO.Unsafe (unsafePerformIO)\nimport Foreign.C.Types (CLong(..), CInt(..))\nimport Foreign.Ptr (Ptr)\n\n-------------------------------------------------------------\n-- Copied from the source of hmatrix package.\ninfixr 5 :>, ::>\ntype (:>) t r = CInt -> Ptr t -> r\ntype (::>) t r = CInt -> CInt -> CInt -> CInt -> Ptr t -> r\ntype Ok = IO CInt\n\n--------------------------------------------------------------\n\n-- | Hermite normal form\nforeign import ccall unsafe \"c_hermiteNF_LLL\" cHermiteNF :: Z ::> Z ::> Z ::> Ok\n\nhermiteNFST :: STMatrix s Z -> STMatrix s Z -> STMatrix s Z -> ST s ()\nhermiteNFST stU stUi stH = do\n u <- unsafeFreezeMatrix stU\n ui <- unsafeFreezeMatrix stUi\n h <- unsafeFreezeMatrix stH\n unsafeIOToST (apply u (apply ui (apply h id)) cHermiteNF #| \"cHermiteNF\")\n\nhermiteNFDecomp :: Matrix Z -> (Matrix Z, Matrix Z, Matrix Z)\nhermiteNFDecomp mat = runST $ do\n stMat <- thawMatrix mat\n stU <- thawMatrix $ ident (rows mat)\n stUi <- thawMatrix $ ident (rows mat)\n hermiteNFST stU stUi stMat\n (\\x y z -> (x,y,z)) <$!> unsafeFreezeMatrix stU <*> unsafeFreezeMatrix stUi <*> unsafeFreezeMatrix stMat\n\nhermiteNF :: Matrix Z -> (Matrix Z, Matrix Z)\nhermiteNF = p . hermiteNFDecomp\n where\n p (x,y,z) = (y,z)\n\nhermiteDecomp :: Matrix Z -> (Matrix Z, Matrix Z)\nhermiteDecomp = p . hermiteNFDecomp\n where\n p (x,y,z) = (x,z)\n\n-- | Smith normal form\nforeign import ccall unsafe \"c_smithNF\" cSmithNF :: Z ::> Z ::> Z ::> Ok\n\nsmithNFST :: STMatrix s LA.Z -> STMatrix s LA.Z -> STMatrix s LA.Z -> ST s ()\nsmithNFST stU stM stV = do\n u <- unsafeFreezeMatrix stU\n m <- unsafeFreezeMatrix stM\n v <- unsafeFreezeMatrix stV\n unsafeIOToST (apply u (apply m (apply v id)) cSmithNF #| \"cSmithNF\")\n\nsmithNF :: Matrix Z -> (Matrix Z, Matrix Z, Matrix Z)\nsmithNF mat = runST $ do\n stMat <- thawMatrix mat\n stU <- thawMatrix $ ident (rows mat)\n stV <- thawMatrix $ ident (cols mat)\n smithNFST stU stMat stV\n (\\x y z -> (x,y,z))\n <$> unsafeFreezeMatrix stU\n <*> unsafeFreezeMatrix stMat\n <*> unsafeFreezeMatrix stV\n\n-- | Smith representation\nforeign import ccall unsafe \"c_smithRep\" cSmithRep :: Z ::> Z ::> Z::> Ok\n\nsmithRepST :: STMatrix s LA.Z -> STMatrix s LA.Z -> STMatrix s LA.Z -> ST s ()\nsmithRepST stA stM stB = do\n a <- unsafeFreezeMatrix stA\n m <- unsafeFreezeMatrix stM\n b <- unsafeFreezeMatrix stB\n unsafeIOToST (apply a (apply m (apply b id)) cSmithRep #| \"cSmithRep\")\n\nsmithRep :: Matrix Z -> (Matrix Z, Matrix Z, Matrix Z)\nsmithRep mat = runST $ do\n stMat <- thawMatrix mat\n stU <- thawMatrix $ ident (rows mat)\n stV <- thawMatrix $ ident (cols mat)\n smithRepST stU stMat stV\n (\\x y z -> (x,y,z))\n <$> unsafeFreezeMatrix stU\n <*> unsafeFreezeMatrix stMat\n <*> unsafeFreezeMatrix stV\n", "meta": {"hexsha": "4318cf06016b4711dfe6a9babf05496416b5a98e", "size": 3505, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Matrix/Integral/NormalForms.hs", "max_stars_repo_name": "Junology/linkedgram", "max_stars_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-21T06:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:54:21.000Z", "max_issues_repo_path": "src/Numeric/Matrix/Integral/NormalForms.hs", "max_issues_repo_name": "Junology/linkedgram", "max_issues_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Matrix/Integral/NormalForms.hs", "max_forks_repo_name": "Junology/linkedgram", "max_forks_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4782608696, "max_line_length": 106, "alphanum_fraction": 0.6296718973, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5827985806839175}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE InstanceSigs #-}\n\nmodule BraKet where\n\nimport Data.Complex\nimport qualified Numeric.LinearAlgebra as L\n\nimport LinAlg\n\n-- Ket is a ket vector\n-- is the coefficient type\n-- in which the Ket is written\nnewtype Ket c = Ket (L.Vector c)\n deriving (Show, Eq)\n\n-- Function used to act on a Ket with an operator\nact :: MatOp -> Ket (Complex Double) -> Ket (Complex Double)\nact op ket = Ket $ repr op L.#> getCoeffs ket\n\ngetCoeffs :: Ket c -> L.Vector c\ngetCoeffs (Ket cs) = cs\n\nmapKet :: (L.Vector a -> L.Vector a) -> Ket a -> Ket a\nmapKet f (Ket cs) = Ket $ f cs\n\ninstance Vector (Ket (Complex Double)) where\n -- Negation: just negate all coefficients\n vneg = mapKet negate\n -- Addition: add coefficients element-wise\n (Ket exp1) <+> (Ket exp2) = Ket $ exp1 + exp2\n -- Scalar multiplication: multiply all coefficients\n (<**>) a = mapKet (L.cmap (*a))\n\ninstance Hilbert (Ket (Complex Double)) where\n -- Inner product: Like l2 inner product; multiply coefficients \n -- and sum\n (Ket coeffs1) <.> (Ket coeffs2) = coeffs1 L.<.> coeffs2\n\nouterProduct :: Ket (Complex Double) -> Ket (Complex Double) \n -> MatOp \nouterProduct (Ket cs1) (Ket cs2) = Operator $ cs1 `L.outer` cs2", "meta": {"hexsha": "60c92afe3c05159cf88519543db68dbb6ff9fc85", "size": 1375, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/BraKet.hs", "max_stars_repo_name": "Jvanrhijn/optiqs", "max_stars_repo_head_hexsha": "6473f8b75bd43b6e6407dfc0b137feeee6592dee", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BraKet.hs", "max_issues_repo_name": "Jvanrhijn/optiqs", "max_issues_repo_head_hexsha": "6473f8b75bd43b6e6407dfc0b137feeee6592dee", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BraKet.hs", "max_forks_repo_name": "Jvanrhijn/optiqs", "max_forks_repo_head_hexsha": "6473f8b75bd43b6e6407dfc0b137feeee6592dee", "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": 30.5555555556, "max_line_length": 67, "alphanum_fraction": 0.6538181818, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5824492294202872}} {"text": "module Mnist where\n\nimport Data.List (nub, sort, intercalate)\nimport Codec.Compression.GZip (decompress)\nimport qualified Data.ByteString.Lazy as BS\nimport Numeric.LinearAlgebra (vector, Vector, R, Z, reshape, Matrix, toList, toRows, fromRows)\n\n-- | typeclass that represents a dataset\nclass DataSet a where\n groupByLabel :: a -> [Matrix R]\n distinctLabels :: a -> [R]\n dataLabel :: a -> [(Vector R, R)] -- pair the data and label for each sample\n -- oneHotLabel :: a -> Matrix Z\n\nimg_header_size = 16\nlabel_header_size = 8\nwidth = 28\nimg_size = 784\n\n-- labeled data consists of data and their label\ndata LabeledData = LabeledData\n { dat :: !(Matrix R) -- this has num_data >< data_dimension\n , label :: !(Vector R)\n }\n\n-- define LabeledData as instance of DataSet typeclass\ninstance DataSet LabeledData where\n distinctLabels = sort . nub . toList . label\n groupByLabel ld = [\n -- extract index that matches the label, and cherrypicks them from data rows\n fromRows [dataRows !! idx | idx <- extractIdx lab]\n | lab <- distinctLabels ld ]\n where\n dataRows = toRows $ dat ld -- represent matrix as list of rows\n labels = toList $ label ld -- represent vector to list of values\n labelIdx = zip labels [0..] -- zip it with index\n extractIdx targetLabel = map snd $ filter ((== targetLabel) . fst) labelIdx\n dataLabel ld = zip (toRows $ dat ld) (toList $ label ld)\n\n-- mnist dataset consists of train set and a test set\ndata Mnist = Mnist\n { trainData :: LabeledData\n , testData :: LabeledData\n }\n\n-- render a single number\nrender :: Vector R -> String\nrender s = intercalate \"\\n\" $ splitted $ map (intensity . floor) (toList s) -- insert \\n every 28 chars\n where\n chars = \" ..:oO0@\"\n intensity n = chars !! (n * length chars `div` 256)\n splitted :: [a] -> [[a]]\n splitted [] = []\n splitted v = (take width v) : (splitted $ drop width v) -- split by 28\n\n-- convert byteString to vector -- in this case, bytestring is read as numbers byte by byte\nbyteStringToVector :: BS.ByteString -> Vector R\nbyteStringToVector = vector . map fromIntegral . BS.unpack\n\nreadDataFile :: String -> IO BS.ByteString\nreadDataFile filepath = decompress <$> BS.readFile filepath\n\n-- make label data represented as Vector\nmakeLabelData :: BS.ByteString -> Vector R\nmakeLabelData = byteStringToVector . BS.drop 8 -- 8-byte header\n\n-- make image data represented as Matrix\nmakeImgData :: BS.ByteString -> Matrix R\nmakeImgData = reshape img_size . byteStringToVector . BS.drop 16 -- 16-byte header\n\n-- reads the file and creates a labeled data\nreadData :: String -> String -> IO LabeledData\nreadData imgfile labelfile = do\n imgData <- makeImgData <$> decompress <$> BS.readFile imgfile\n labelData <- makeLabelData <$> decompress <$> BS.readFile labelfile\n return $ LabeledData imgData labelData\n\nreadMnist :: IO Mnist\nreadMnist = do\n trainDataset <- readData \"train-images-idx3-ubyte.gz\" \"train-labels-idx1-ubyte.gz\"\n testDataset <- readData \"t10k-images-idx3-ubyte.gz\" \"t10k-labels-idx1-ubyte.gz\"\n return $ Mnist trainDataset testDataset\n\n-- ByteString is an optimized representation of Word8.\n-- BS.readFile :: FilePath -> IO ByteString\n-- decompress :: ByteString -> ByteString\nreadMnistAndShow :: IO ()\nreadMnistAndShow = do\n imgData <- makeImgData <$> decompress <$> BS.readFile \"train-images-idx3-ubyte.gz\"\n labelData <- makeLabelData <$> decompress <$> BS.readFile \"train-labels-idx1-ubyte.gz\"\n putStrLn $ show $ labelData\n", "meta": {"hexsha": "2ff61dd4e971c69098b06321711ed904c66107f7", "size": 3529, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Mnist.hs", "max_stars_repo_name": "deNsuh/hasml", "max_stars_repo_head_hexsha": "1890aa113b1c85797816d3c44a865990016d6d3e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-28T05:16:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-28T05:16:19.000Z", "max_issues_repo_path": "src/Mnist.hs", "max_issues_repo_name": "deNsuh/hasml", "max_issues_repo_head_hexsha": "1890aa113b1c85797816d3c44a865990016d6d3e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mnist.hs", "max_forks_repo_name": "deNsuh/hasml", "max_forks_repo_head_hexsha": "1890aa113b1c85797816d3c44a865990016d6d3e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3586956522, "max_line_length": 104, "alphanum_fraction": 0.6956644942, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5823544241993791}} {"text": "\n-- | The Metropolis transition.\n\nmodule Strategy.Metropolis (metropolis) where\n\nimport Control.Monad.State.Strict\nimport Data.Maybe\nimport Numeric.LinearAlgebra\nimport Math.Probably.Sampler\nimport Math.Probably.Types\nimport Math.Probably.Utils\n\n-- | The Metropolis transition for a symmetric proposal. Uses a simple\n-- spherical Gaussian with standard deviation specified by the first\n-- argument.\nmetropolis :: Maybe Double -> Transition Double\nmetropolis e = do\n Chain current@(ds, cs) target _ t <- get\n let sd = fromMaybe t e\n pcs <- lift $ perturb cs sd\n zc <- lift unit\n let next = nextState target current (ds, pcs) sd zc\n put $ Chain next target (logObjective target next) sd\n return next\n\nperturb :: ContinuousParams -> Double -> Prob (ContinuousParams)\nperturb q sd = fmap fromList $ mapM (`normal` sd) (toList q)\n\nacceptRatio :: Target -> Parameters -> Parameters -> Double -> Double\nacceptRatio target c@(_, current) p@(_, proposed) sd = exp . min 0 $\n logObjective target p + log (sphereGauss current proposed sd)\n - logObjective target c - log (sphereGauss proposed current sd)\n\nnextState\n :: Target\n -> Parameters\n -> Parameters\n -> Double\n -> Double\n -> Parameters\nnextState target current proposed sd z\n | z < acceptProb = proposed\n | otherwise = current\n where\n ratio = acceptRatio target current proposed sd \n acceptProb | isNaN ratio = 0\n | otherwise = ratio\n \n", "meta": {"hexsha": "9dd8029d1b30ac07babffcead9bd94a5048fbd96", "size": 1439, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Strategy/Metropolis.hs", "max_stars_repo_name": "glutamate/probably-baysig", "max_stars_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-02-12T05:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:37.000Z", "max_issues_repo_path": "src/Strategy/Metropolis.hs", "max_issues_repo_name": "silky/probably-baysig", "max_issues_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Strategy/Metropolis.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 29.3673469388, "max_line_length": 71, "alphanum_fraction": 0.7102154274, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.5823253160783407}} {"text": "module Malliavin where\n\nimport Data.Random.Distribution.Normal\nimport Numeric.LinearAlgebra.HMatrix as H\nimport Data.Ratio\n\ndata L2Map a = L2Map {eval :: a -> Double,\n norm_l2 :: a -> Double}\nl2_1 = L2Map {eval = (\\t -> 1), norm_l2 = id}\nl2id = L2Map {eval = id, norm_l2 = (\\x -> x ^ 3 / 3)}\n\ndata L1Map a = L1Map {norm_l1 :: a -> Double}\nl1_1 = L1Map {eval = (\\t -> 1), norm_l1 = id}\nl1id = L1Map {eval = id, norm_l1 = (\\x -> x ^ 2 / 2)}\n\n\n-- | 'hermite' is an infinite list of Hermite polynomials for given x\nhermite :: (Enum a, Num a) => a -> [a]\nhermite x = s\n where s@(_:ts) = 1 : x : zipWith3 (\\hn2 hn1 n1 -> x * hn1 - n1 * hn2) s ts [1..]\n\n\n-- | 'gaussianProcess' samples from Gaussian process\ngaussianProcess :: Seed -- random state\n -> Int -- number of samples m\n -> Int -- number of dimensions n\n -> ((Int, Int) -> Double) -- function that maps indices of the matrix into dot products of its elements\n -> [Vector Double] -- m n-th dimensional samples of Gaussian process\ngaussianProcess seed 0 _ _ = []\ngaussianProcess seed m 0 _ = replicate m $ vector []\ngaussianProcess seed m n dotProducts = toRows $ gaussianSample seed m mean cov_matrix\n where mean = n |> repeat 0\n cov_matrix = H.sym $ (n> dotProducts (quot i n, rem i n)) [0..]\n\n\n-- | 'second' function takes a list and gives each second element of it\nsecond (x:y:xs) = y : second xs\nsecond _ = []\n\n\n-- | 'coinTossExpansion' is a Wiener chaos expansion for coin-toss r.v. to n-th element\ncoinTossExpansion :: Int -- number of elements in the sum\n -> Double -- gaussian random variable\n -> Double -- the sum\ncoinTossExpansion n xi = sum (take n $ 0.5 : zipWith (*) fn (second $ hermite xi))\n where fn = 1.0 / (sqrt $ 2 * pi) : zipWith (\\fn1 k -> -fn1 * k / (k ^ 2 + 3 * k + 2)) fn [1, 3..]\n\n\n-- | 'coinTossSequence' is a coin-toss sequence of given size\ncoinTossSequence :: Seed -- random state \u03c9\n -> Int -- size of resulting sequence m\n -> [Int] -- coin-toss sequence of size m\ncoinTossSequence seed m = map (round.coinTossExpansion 100) (toList nvec)\n where nvec = gaussianProcess seed m 1 (\\(i,j) -> 1) !! 0\n\n\n-- | 'mapOverInterval' map function f over the interval [0, T]\nmapOverInterval :: (Fractional a) => Int -- n, size of the output list\n -> a -- T, end of the time interval\n -> (a -> b) -- f, function that maps from fractional numbers to some abstract space\n -> [b] -- list of values f(t), t \\in [0, T]\nmapOverInterval n endT fn = [fn $ (endT * fromIntegral i) / fromIntegral (n - 1) | i <- [0..(n-1)]]\n\n\ntype ItoIntegral = Seed -- \u03c9, random state\n -> Int -- n, sample size\n -> Double -- T, end of the time interval\n -> L2Map Double -- h, L2-function\n -> [Double] -- list of values sampled from Ito integral\n\n\n-- | 'itoIntegral'' trajectory of Ito integral on the time interval [0, T]\nitoIntegral' :: ItoIntegral\nitoIntegral' seed n endT h = 0 : (toList $ gp !! 0)\n where gp = gaussianProcess seed 1 (n-1) (\\(i, j) -> norm_l2 h $ fromIntegral (min i j + 1) * t)\n t = endT / fromIntegral n\n\n\n-- | 'itoIntegral' faster implementation of itoIntegral' function\nitoIntegral :: ItoIntegral\nitoIntegral seed 0 _ _ = []\nitoIntegral seed n endT h = scanl (+) 0 increments\n where increments = toList $ sigmas * gaussianVector\n gaussianVector = flatten $ gaussianSample seed (n-1) (vector [0]) (H.sym $ matrix 1 [1])\n sigmas = fromList $ zipWith (\\x y -> sqrt(x-y)) (tail hnorms) hnorms\n hnorms = mapOverInterval n endT $ norm_l2 h\n\n\n-- | 'brownianMotion' trajectory of Brownian motion a.k.a. Wiener process on the time interval [0, T]\nbrownianMotion :: Seed -- \u03c9, random state\n -> Int -- n, sample size\n -> Double -- T, end of the time interval\n -> [Double] -- list of values sampled from Brownian motion\nbrownianMotion seed n endT = itoIntegral seed n endT l2_1\n\n\ntype DiffusionProcess = Seed -- \u03c9, random state\n -> Int -- n, sample size\n -> Double -- T, end of the time interval\n -> L1Map Double -- function \\mu with L1 norm\n -> L2Map Double -- function \\sigma with L2 norm\n -> [Double] -- list of values sampled from stochastic diffusion process X(t)\n\n-- | 'diffusionProcess' stochastic process, defined by SDE: dX(t) = \\mu(t)dt + \\sigma(t)dB(t)\ndiffusionProcess :: DiffusionProcess\ndiffusionProcess seed n endT mu sigma = zipWith (+) trend noise\n where trend = mapOverInterval n endT $ norm_l1 mu\n noise = itoIntegral seed n endT sigma\n\n\n-- | 'multipleItoIntegral' multiple m-th Ito integral of m-th tensor power of h\nmultipleItoIntegral :: Seed -- \u03c9, random state\n -> Int -- m, tensor power\n -> Int -- n, sample size\n -> Double -- T, end of the time interval\n -> L2Map Double -- function h with L2 norm\n -> [Double] -- list of values sampled from multiple m-th Wiener-Ito integral of h^(\u2297m)\nmultipleItoIntegral seed m n endT h = zipWith fn itoTrajectory hnorm\n where itoTrajectory = itoIntegral seed n endT h\n hnorm = mapOverInterval n endT $ norm_l2 h\n fn :: Double -> Double -> Double\n fn _ 0 = 0\n fn x y = (y ^ m) * (hermite (x / y) !! m)\n\nmultipleBrownianMotion :: Seed -- \u03c9, random state\n -> Int -- m, tensor power\n -> Int -- n, sample size\n -> Double -- T, end of the time interval\n -> [Double] -- list of values sampled from Brownian motion\nmultipleBrownianMotion seed m n endT = multipleItoIntegral seed m n endT l2_1\n\n\n-- | 'totalVariation' calculates total variation of the sample process X(t)\ntotalVariation :: [Double] -- process trajectory X(t)\n -> Double -- V(X(t))\ntotalVariation x@(_:tx) = sum $ zipWith (\\x xm1 -> abs $ x - xm1) tx x\n\n\n-- | 'quadraticVariation' calculates quadratic variation of the sample process X(t)\nquadraticVariation :: [Double] -- process trajectory X(t)\n -> Double -- [X(t)]\nquadraticVariation x@(_:tx) = sum $ zipWith (\\x xm1 -> (x - xm1) ^ 2) tx x\n", "meta": {"hexsha": "b22e74c006bd6951d298c02506207fef437c6c1a", "size": 6598, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Malliavin.hs", "max_stars_repo_name": "vishalbelsare/Malliavin", "max_stars_repo_head_hexsha": "659524dbae9c69a4779cf2b001cc17c5eed2a6b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-29T16:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-29T16:30:30.000Z", "max_issues_repo_path": "Malliavin.hs", "max_issues_repo_name": "vishalbelsare/Malliavin", "max_issues_repo_head_hexsha": "659524dbae9c69a4779cf2b001cc17c5eed2a6b5", "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": "Malliavin.hs", "max_forks_repo_name": "vishalbelsare/Malliavin", "max_forks_repo_head_hexsha": "659524dbae9c69a4779cf2b001cc17c5eed2a6b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-29T16:30:32.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-30T10:56:44.000Z", "avg_line_length": 46.1398601399, "max_line_length": 119, "alphanum_fraction": 0.5782055168, "num_tokens": 1829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385542, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.5823028531293039}} {"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RecordWildCards #-}\n\nmodule Q.Options.BlackScholes (\n BlackScholes(..)\n , atmf\n , euOption\n , eucall\n , euput\n , module Q.Options\n) where\n\nimport Control.Monad.State\nimport Data.Random hiding (Gamma)\nimport Data.Time\nimport Numeric.RootFinding\nimport Q.ContingentClaim.Options\nimport Q.MonteCarlo\nimport Q.Options\nimport Q.Stochastic.Discretize\nimport Q.Stochastic.Process\nimport Q.Time\nimport Q.Types\nimport Statistics.Distribution (cumulative, density)\nimport Statistics.Distribution.Normal (standard)\nimport qualified Q.Options.Black76 as B76\n\ndcf = dcYearFraction ThirtyUSA\n\n-- | Parameters for a simplified black scholes equation.\ndata BlackScholes = BlackScholes {\n bsSpot :: Spot -- ^ The asset's spot on the valuation date.\n , bsRate :: Rate -- ^ Risk free rate.\n , bsVol :: Vol -- ^ Volatility.\n} deriving Show\n\n\n\ninstance Model BlackScholes Double where\n discountFactor BlackScholes{..} t1 t2 = return $ exp (scale dt bsRate)\n where dt = t2 - t1\n\n evolve (BlackScholes spot (Rate r) (Vol sigma)) (YearFrac t) = do\n (YearFrac t0, s0) <- get\n let dt = t - t0\n dw <- (lift stdNormal)::StateT (YearFrac, Double) RVar Double\n let st = s0 * exp ((r - 0.5 * sigma * sigma) * dt + sigma * dw * sqrt dt)\n put (YearFrac t, st)\n return st\n\natmf :: BlackScholes -> YearFrac -> Strike\natmf BlackScholes{..} t = Strike $ s / d where\n (Rate d) = exp (scale t (-bsRate))\n (Spot s) = bsSpot\n\n\n\n-- | European option valuation with black scholes.\neuOption :: BlackScholes -> YearFrac -> OptionType -> Strike ->Valuation\neuOption bs@BlackScholes{..} t cp k =\n let b76 = B76.Black76 {\n b76F = forward bs t\n , b76DF = Q.Types.discountFactor t bsRate\n , b76T = t\n , b76Vol = bsVol\n }\n in B76.euOption b76 cp k\n\n-- | see 'euOption'\neuput bs t = euOption bs t Put\n \n-- | see 'euOption'\neucall bs t = euOption bs t Call\n\nforward BlackScholes{..} (YearFrac t) = Forward $ s * exp (r * t)\n where (Spot s) = bsSpot\n (Rate r) = bsRate\n\ncorradoMillerIniitalGuess bs@BlackScholes{..} cp (Strike k) (YearFrac t) (Premium premium) =\n (recip $ sqrt t) * ((sqrt (2 * pi)/ (s + discountedStrike)) + (premium - (s - discountedStrike)/2) + sqrt ((premium - (s - discountedStrike)/2)**2 - ((s - discountedStrike)**2/pi))) where\n discountedStrike = k * (exp $ (-r) * t)\n (Rate r) = bsRate\n (Spot s) = bsSpot\n\n\n", "meta": {"hexsha": "cb8a7e227a87d594f40e6c4f9ddbbd46e58e3d1f", "size": 2598, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Q/Options/BlackScholes.hs", "max_stars_repo_name": "ghais/lowq", "max_stars_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-01T17:50:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T18:06:22.000Z", "max_issues_repo_path": "src/Q/Options/BlackScholes.hs", "max_issues_repo_name": "ghais/lowq", "max_issues_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Q/Options/BlackScholes.hs", "max_forks_repo_name": "ghais/lowq", "max_forks_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2093023256, "max_line_length": 189, "alphanum_fraction": 0.6200923788, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5820434531072856}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Data.Pass.Util.Beta\n-- Copyright : (C) 2012-2013 Edward Kmett\n-- License : BSD-style (see the file LICENSE)\n--\n-- Maintainer : Edward Kmett \n-- Stability : experimental\n-- Portability : non-portable (GADTs, Rank2Types)\n--\n----------------------------------------------------------------------------\nmodule Data.Pass.Util.Beta\n ( Beta(..)\n , cumulative\n , density\n , quantile\n ) where\n\nimport Numeric.SpecFunctions\nimport Numeric.MathFunctions.Constants (m_NaN)\n\ndata Beta = Beta {-# UNPACK #-} !Double {-# UNPACK #-} !Double\n deriving (Eq,Read,Show)\n\ncumulative :: Beta -> Double -> Double\ncumulative (Beta a b) x\n | x <= 0 = 0\n | otherwise = incompleteBeta a b x\n{-# INLINE cumulative #-}\n\n-- invert a monotone function\ninvertMono :: (Double -> Double) -> Double -> Double -> Double -> Double\ninvertMono f l0 h0 b = go l0 h0 where\n go l h\n | h - l < epsilon = m\n | otherwise = case compare (f m) b of\n LT -> go m h\n EQ -> m\n GT -> go l m\n where m = l + (h-l)/2\n epsilon = 1e-12\n{-# INLINE invertMono #-}\n\ndensity :: Beta -> Double -> Double\ndensity (Beta a b) x\n | a <= 0 || b <= 0 = m_NaN\n | x <= 0 = 0\n | x >= 1 = 0\n | otherwise = exp $ (a-1)*log x + (b-1)*log (1-x) - logBeta a b\n{-# INLINE density #-}\n\nquantile :: Beta -> Double -> Double\nquantile d p\n | p < 0 = error $ \"probability must be positive. Got \" ++ show p\n | p > 1 = error $ \"probability must be less than 1. Got \" ++ show p\n | otherwise = invertMono (cumulative d) 0 1 p\n{-# INLINE quantile #-}\n", "meta": {"hexsha": "ec57acc35f02de365796f4441547169024001fb7", "size": 1646, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Pass/Util/Beta.hs", "max_stars_repo_name": "ekmett/multipass", "max_stars_repo_head_hexsha": "18ce305f7196f9b386472582a2efaaac1d180bc1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-11-08T11:43:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T02:47:39.000Z", "max_issues_repo_path": "Data/Pass/Util/Beta.hs", "max_issues_repo_name": "ekmett/multipass", "max_issues_repo_head_hexsha": "18ce305f7196f9b386472582a2efaaac1d180bc1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data/Pass/Util/Beta.hs", "max_forks_repo_name": "ekmett/multipass", "max_forks_repo_head_hexsha": "18ce305f7196f9b386472582a2efaaac1d180bc1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3793103448, "max_line_length": 77, "alphanum_fraction": 0.5394896719, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5816630215506806}} {"text": "{-# LANGUAGE DataKinds #-}\n\nmodule MNIST where\nimport Control.DeepSeq\nimport Control.Exception.Base\nimport Control.Monad\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Maybe\nimport Control.Monad.Trans.State\nimport Data.Bitraversable\nimport Data.IDX\nimport Data.Traversable\nimport Data.Tuple\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as VG\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Numeric.LinearAlgebra as HM -- non-backprop hmatrix\nimport qualified Numeric.LinearAlgebra.Data as HMD\nimport qualified Numeric.LinearAlgebra.Static as HMS -- hmatrix with type-checked operations :D\n\nloadMNIST\n :: FilePath\n -> FilePath\n -> IO (Maybe [(HMS.L 28 28, HMS.R 10)])\nloadMNIST fpI fpL = runMaybeT $ do\n i <- MaybeT $ decodeIDXFile fpI\n l <- MaybeT $ decodeIDXLabelsFile fpL\n d <- MaybeT . return $ labeledIntData l i\n r <- MaybeT . return $ for d (bitraverse mkImage mkLabel . swap)\n liftIO . evaluate $ force r\n where\n mkImage :: VU.Vector Int -> Maybe (HMS.L 28 28)\n mkImage = HMS.create . HMD.reshape 28 . VG.convert . VG.map (\\i -> fromIntegral i / 255)\n mkLabel :: Int -> Maybe (HMS.R 10)\n mkLabel n = HMS.create $ HM.build 10 (\\i -> if round i == n then 1 else 0)\n\n", "meta": {"hexsha": "55b83756e956a5413771852c79357d7a14068365", "size": 1514, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MNIST.hs", "max_stars_repo_name": "staturecrane/haskell-ml", "max_stars_repo_head_hexsha": "13177bf6f951500e8221fc125902929f7feb5e38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-14T20:47:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-14T20:47:58.000Z", "max_issues_repo_path": "src/MNIST.hs", "max_issues_repo_name": "staturecrane/haskell-ml", "max_issues_repo_head_hexsha": "13177bf6f951500e8221fc125902929f7feb5e38", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MNIST.hs", "max_forks_repo_name": "staturecrane/haskell-ml", "max_forks_repo_head_hexsha": "13177bf6f951500e8221fc125902929f7feb5e38", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9189189189, "max_line_length": 102, "alphanum_fraction": 0.6010568032, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5815206052128573}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n\n{-|\nModule : Numeric.LinearAlgebra.Static.RList\nDescription : List of static vectors (`R`s)\nCopyright : (c) Ryan Orendorff, 2020\nLicense : BSD3\nStability : experimental\n-}\nmodule Numeric.LinearAlgebra.Static.RList\n ( RList(..)\n , LList(..)\n , Sum\n , exRList\n , concat\n , blockDiag\n , mapRListSquare\n , applyLList\n )\nwhere\n\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra.Static\nimport Prelude hiding (concat)\n\n\n-- TODO: Make a fold function, then this can be abstracted.\n-- | Sum a type level list of naturals\ntype family Sum (xs :: [Nat]) where\n Sum '[] = 0\n Sum (n ': ns) = n + Sum ns\n\n-- | A non-empty list of `R` vectors of different sizes.\n-- The list is non-empty since we cannot create a vector of size 0 in a\n-- reasonable way when using Data.Vector as the backend (as HMatrix).\ndata RList (ns :: [Nat]) where\n ROne :: (KnownNat n) => R n -> RList '[n]\n (:::) :: (KnownNat n) => R n -> RList ns -> RList (n ': ns)\n\ninfixr 6 :::\n\n-- | An example of how to construct an RList.\nexRList :: RList '[2, 3]\nexRList = konst 1 ::: ROne (konst 2)\n\n-- There is no null vector. Also the HMatrix library does the wrong thing\n-- with this example.\n--\n-- \u03bb> (konst 4 :: R 2) # (konst 0 :: R 0)\n-- (vector [4.0,4.0,0.0] :: R 2)\n\n-- | Concatenate an RList of vectors\n--\n-- Thank you Christiaan Baaij for figuring out how to do concat! This is\n-- basically his solution to the problem, with a modification to work with\n-- the non-empty version of RList. See the following gist for more details:\n-- https://gist.github.com/ryanorendorff/d05c378b71829e3c0c33de462cb9a973\nconcat :: RList ns -> R (Sum ns)\nconcat rs = case concatWorker rs of\n RWorker rsW -> rsW\n\ndata RWorker n where\n RWorker :: KnownNat n => R n -> RWorker n\n\nconcatWorker :: RList ns -> RWorker (Sum ns)\nconcatWorker (ROne r) = RWorker r\nconcatWorker (r ::: rs) = case concatWorker rs of\n RWorker rsW -> RWorker (r # rsW)\n\n\n-- | A non-empty list of `L` matrices of different sizes.\n-- The list is non-empty since we cannot create a matrix of size 0 in a\n-- reasonable way when using Data.Vector as the backend (as HMatrix).\ndata LList (ms :: [Nat]) (ns :: [Nat]) where\n LOne :: (KnownNat m, KnownNat n) => L m n -> LList '[m] '[n]\n (:-:) :: (KnownNat m, KnownNat n) => L m n -> LList ms ns\n -> LList (m ': ms) (n ': ns)\n\n\n-- | Concatenate a LList of matrices as a block diagonal.\nblockDiag :: LList ms ns -> L (Sum ms) (Sum ns)\nblockDiag ls = case blockDiagWorker ls of\n LWorker lsW -> lsW\n\ndata LWorker m n where\n LWorker :: (KnownNat m, KnownNat n) => L m n -> LWorker m n\n\nblockDiagWorker :: LList ms ns -> LWorker (Sum ms) (Sum ns)\nblockDiagWorker (LOne l) = LWorker l\nblockDiagWorker (l :-: ls) = case blockDiagWorker ls of\n LWorker lsW -> LWorker (l ||| konst 0 === konst 0 ||| lsW)\n\n-- | Map some function that preserves the dimension of the vector (a square\n-- matrix) over a list of vectors.\nmapRListSquare :: (forall n. KnownNat n => R n -> R n)\n -> RList ns -> RList ns\nmapRListSquare f (ROne r) = ROne (f r)\nmapRListSquare f (r ::: rs) = f r ::: mapRListSquare f rs\n\n-- I have not proved that the LList and RList are the same length, so GHC\n-- complains that I have non-exhaustive patterns that cannot be constructed.\n-- TODO: Add comment on how this would work in Agda to show how this type\n-- of error would be avoided.\n-- | Apply a list of static matrices over a list of static vectors\napplyLList :: LList ms ns -> RList ns -> RList ms\napplyLList (LOne _) (_ ::: _) = error \"This case is impossible\"\napplyLList (_ :-: _) (ROne _) = error \"This case is impossible\"\napplyLList (LOne l) (ROne r) = ROne (l #> r)\napplyLList (l :-: ls) (r ::: rs) = (l #> r) ::: applyLList ls rs\n\n-- This function is more complicated, may need to reflect out the position\n-- we are in the list in order to write this function.\n-- splitRList :: R (Sum ns) -> RList ns\n-- splitRList vec = let (r, rs) = split vec in r ::: (splitRList rs)\n", "meta": {"hexsha": "90e78576b573fa37abb0ece094d370b516ffa0dc", "size": 4415, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/Static/RList.hs", "max_stars_repo_name": "ryanorendorff/convex", "max_stars_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-06-13T21:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T15:53:28.000Z", "max_issues_repo_path": "src/Numeric/LinearAlgebra/Static/RList.hs", "max_issues_repo_name": "ryanorendorff/convex", "max_issues_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LinearAlgebra/Static/RList.hs", "max_forks_repo_name": "ryanorendorff/convex", "max_forks_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "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.0396825397, "max_line_length": 76, "alphanum_fraction": 0.6545866365, "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888478, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.581461745016517}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE OverloadedLists #-}\n\n\nmodule Main where\n\n\n\nimport qualified Data.Vector.Unboxed as U\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector as V\n\n-- DLA\nimport qualified Statistics.Matrix as M\nimport qualified Statistics.Matrix.Fast as MF\nimport qualified Statistics.Matrix.Fast.Algorithms as A\n\n-- hmatrix\nimport qualified Numeric.LinearAlgebra as H\n\n-- numhask\nimport qualified NumHask.Array as NH\nimport qualified NumHask.Prelude as NP\n\n-- data.matrix from matrix\nimport qualified Data.Matrix as DMX\n\n-- massiv\nimport qualified Data.Massiv.Array as MA\n\nimport qualified System.Random.MWC as Mwc\n\nimport qualified Weigh as W\n\nn :: Int\nn = 100\n\nvectorGen :: IO (Vector Double)\nvectorGen = do \n gen <- Mwc.create\n Mwc.uniformVector gen (n*n)\n\nmatrixDLA :: IO M.Matrix\nmatrixDLA = do\n vec <- vectorGen\n return $ M.Matrix n n vec\n\nmatrixH :: IO (H.Matrix H.R)\nmatrixH = do\n vec <- vectorGen\n return $ (n H.>< n) $ U.toList $ vec \n\nidentH :: Int -> H.Matrix Double\nidentH = H.ident\n\nidentDMX :: Int -> DMX.Matrix Double\nidentDMX = DMX.identity\n\n\nelemZero :: Double -> Double\nelemZero = const 0\n\nelemSqr :: Double -> Double\nelemSqr x = x*x\n\nmapH :: (Double -> Double) -> H.Matrix Double -> H.Matrix Double\nmapH = H.cmap\n\nmain :: IO ()\nmain = do \n\n let \n\n vDLA <- vectorGen\n uDLA <- vectorGen\n\n let \n\n --\n subDLA = U.take n vDLA\n aDLA = M.Matrix n n vDLA\n bDLA = M.Matrix n n uDLA\n \n --\n vList = U.toList vDLA\n uList = U.toList uDLA\n \n --\n aH = (n H.>< n) vList\n bH = (n H.>< n) uList\n\n subH = H.fromList . take n $ vList\n vH = H.fromList vList\n\n --\n aNH = NP.fromList vList :: NH.Array V.Vector '[50, 50] Double\n bNH = NP.fromList uList :: NH.Array V.Vector '[50, 50] Double\n\n subNH = NP.fromList . take n $ vList :: NH.Array V.Vector '[50] Double\n vNH = NP.fromList vList :: NH.Array V.Vector '[2500] Double\n\n --\n aDMX = DMX.fromList n n vList\n bDMX = DMX.fromList n n uList\n\n -- \n vMA = MA.fromList MA.Seq vList :: MA.Array MA.P MA.Ix1 Double\n aMA = MA.resize' (MA.Sz (n MA.:. n)) vMA :: MA.Array MA.P MA.Ix2 Double\n bMA = MA.resize' (MA.Sz (n MA.:. n)) $ MA.fromList MA.Seq uList :: MA.Array MA.P MA.Ix2 Double\n\n\n W.mainWith (do \n W.func \"DLA - multiplication\" (MF.multiply aDLA) bDLA\n W.func \"DLA - qr factorization\" A.qr aDLA\n W.func \"DLA - transpose\" M.transpose aDLA\n W.func \"DLA - norm\" MF.norm vDLA\n W.func \"DLA - row\" (M.row aDLA) 0\n W.func \"DLA - column\" (M.column aDLA) 0\n W.func \"DLA - identity\" M.ident n\n\n W.func \"Hmatrix - multiplication\" ((<>) aH) bH\n W.func \"Hmatrix - qr factorization\" H.qr aH\n W.func \"Hmatrix - transpose\" H.tr aH\n W.func \"Hmatrix - norm\" H.norm_2 vH\n W.func \"Hmatrix - row\" ((H.?) aH) [0]\n W.func \"Hmatrix - column\" ((H.\u00bf) aH) [0]\n W.func \"Hmatrix - identity\" identH n\n\n W.func \"NumHask Array - multiplication\" (NH.mmult aNH) bNH\n W.func \"NumHask Array - transpose\" NH.transpose aNH\n W.func \"NumHask Array - norm\" (sqrt . (NP.<.> vNH)) vNH\n W.func \"NumHask Array - row\" (NH.row (NP.Proxy :: NP.Proxy 0)) aNH\n W.func \"NumHask Array - column\" (NH.col (NP.Proxy :: NP.Proxy 0)) aNH\n\n W.func \"Massiv - norm\" (sqrt . MA.foldlS (+) 0 . MA.zipWith (*) vMA) vMA\n W.func \"Massiv - multiplication\" ((MA.|*|) aMA) bMA\n W.func \"Massiv - transpose\" (MA.computeAs MA.P . MA.transpose) aMA\n W.func \"Massiv - row\" (MA.computeAs MA.P . (MA.!>) aMA) 0\n\n W.func \"matrix - multiplication\" (DMX.multStrassenMixed aDMX) bDMX\n W.func \"matrix - transpose\" DMX.transpose aDMX\n W.func \"matrix - row\" (DMX.getRow 1) aDMX\n W.func \"matrix - column\" (DMX.getCol 1) aDMX\n W.func \"matrix - identity\" identDMX n\n )\n", "meta": {"hexsha": "ba9465a235714b6c6785f408afae87fa7dd44cff", "size": 4148, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/Alloc.hs", "max_stars_repo_name": "lehins/fastest-matrices", "max_stars_repo_head_hexsha": "31223a96bbecd0c15c6efe9511f7162950dea57d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bench/Alloc.hs", "max_issues_repo_name": "lehins/fastest-matrices", "max_issues_repo_head_hexsha": "31223a96bbecd0c15c6efe9511f7162950dea57d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/Alloc.hs", "max_forks_repo_name": "lehins/fastest-matrices", "max_forks_repo_head_hexsha": "31223a96bbecd0c15c6efe9511f7162950dea57d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4109589041, "max_line_length": 100, "alphanum_fraction": 0.5769045323, "num_tokens": 1262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5813200853890578}} {"text": "import Data.Complex\n\n-- Polynomial type\ntype Poly a = [Complex a]\n\n__fftAux :: (RealFloat a) => a -> Poly a -> Poly a\n__fftAux _ [] = []\n__fftAux _ [x] = [x]\n__fftAux c poly = uncurry (++) res\n where\n n = length poly\n ls = __fftAux c [ x | (x, i) <- zip poly [1..], odd i ]\n rs = __fftAux c [ x | (x, i) <- zip poly [1..], even i ]\n res = combine ls rs 1\n where\n ang = c * 2 * pi / fromIntegral n\n wn = cos ang :+ sin ang\n combine [] [] _ = ([], [])\n combine (x:xs) (y:ys) w = (x + w * y : rxs, x - w * y : rys)\n where\n (rxs, rys) = combine xs ys (w * wn)\n\n__closestPowerOf2 :: Int -> Int\n__closestPowerOf2 n = compute 1\n where\n compute x\n | x >= n = x\n | otherwise = compute $ 2 * x\n\n__fftWrapper :: (RealFloat a) => a -> Poly a -> Poly a\n__fftWrapper c poly\n | oddf (length poly) == 1 = __fftAux c poly\n | otherwise = error \"FFT: size is not a power of 2!\"\n where\n oddf x\n | odd x = x\n | otherwise = oddf $ x `div` 2\n\nfft :: (RealFloat a) => Poly a -> Poly a\nfft = __fftWrapper 1\n\nifft :: (RealFloat a) => Poly a -> Poly a\nifft poly = map (/n) $ __fftWrapper (-1) poly\n where\n n = fromIntegral $ length poly\n\nmultiply :: (RealFloat a) => Poly a -> Poly a -> Poly a\nmultiply ps qs = ifft $ zipWith (*) (fft $ pad ps) (fft $ pad qs)\n where\n size = __closestPowerOf2 $ length ps + length qs - 1\n pad xs = xs ++ replicate (size - length xs) 0\n\nmultiplyReal :: (RealFloat a) => [a] -> [a] -> [a]\nmultiplyReal ps qs = map realPart $ multiply (conv ps) (conv qs)\n where\n conv = map (:+ 0)\n\nmultiplyIntegral :: (Integral a) => [a] -> [a] -> [a]\nmultiplyIntegral ps qs = map round $ multiplyReal (conv ps) (conv qs)\n where\n conv = map fromIntegral\n", "meta": {"hexsha": "fb814f55c76db91a94e28ae6480a6448edfdd0fb", "size": 1765, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Templates/Math/FFT.hs", "max_stars_repo_name": "anurudhp/CPHaskell", "max_stars_repo_head_hexsha": "c71b638983cfbab565403c6a6b6c28edf3d9242f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-04-01T23:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T17:47:07.000Z", "max_issues_repo_path": "Templates/Math/FFT.hs", "max_issues_repo_name": "anurudhp/CPHaskell", "max_issues_repo_head_hexsha": "c71b638983cfbab565403c6a6b6c28edf3d9242f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-12T00:02:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T06:33:02.000Z", "max_forks_repo_path": "Templates/Math/FFT.hs", "max_forks_repo_name": "anurudhp/CPHaskell", "max_forks_repo_head_hexsha": "c71b638983cfbab565403c6a6b6c28edf3d9242f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4677419355, "max_line_length": 69, "alphanum_fraction": 0.5575070822, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5810256200526098}} {"text": "module Reanimate.Morph.Triagulate where\n\n-- import Graphics.SvgTree\nimport Linear.V2\nimport Linear.Vector\n-- import Reanimate\nimport Numeric.LinearAlgebra\n-- import Numeric.LinearAlgebra.Sparse\n-- import Data.Sparse.SpMatrix\n-- import Data.Sparse.SpVector\n\ntype Poly = [V2 Double]\n\n-- renderPolygon :: Poly -> SVG\n-- renderPolygon = undefined\n\ntriangulate :: Poly -> Poly -> ([Poly],[Poly])\ntriangulate = undefined\n\ntype Point = V2 Double\n\np1,p2,p3,p4 :: Point\np1 = V2 0 0\np2 = V2 2 0\np3 = V2 1 2\np4 = V2 1 1\n\n-- let (t1,t2,t3) = barycentricCoordinates p1 p2 p3 p4\n-- p4 = t1*p1 + t2*p2 + t3*p3\n--\n--\n-- [ t1\n-- , t2\n-- , t3 ]\n-- [ [p1_x, p2_x, p3_x ] [ p4_x\n-- , [p1_y, p2_y, p3_y ] , p4_y\n-- , [1, 1, 1] ] , 1 ]\n-- barycentricCoordinates :: Point -> Point -> Point -> Point -> (Double, Double, Double)\nbarycentricCoordinates (V2 p1x p1y) (V2 p2x p2y) (V2 p3x p3y) (V2 p4x p4y) =\n linearSolve m v\n -- (m, v)\n where\n m = (3><3) [p1x, p2x, p3x, p1y, p2y, p3y, 1, 1, 1 :: Double]\n v = (3><1) [ p4x, p4y, 1 :: Double ]\n\nbCoords (V2 x1 y1) (V2 x2 y2) (V2 x3 y3) (V2 x y) =\n (lam1, lam2, lam3)\n where\n lam1 = ((y2-y3)*(x-x3) + (x3 - x2)*(y-y3)) /\n ((y2-y3)*(x1-x3) + (x3-x2)*(y1-y3))\n lam2 = ((y3-y1)*(x-x3) + (x1-x3)*(y-y3)) /\n ((y2-y3)*(x1-x3) + (x3-x2)*(y1-y3))\n lam3 = 1 - lam1 - lam2\n", "meta": {"hexsha": "04850f78b2877aa543383df7772ab5f3ff0ddf08", "size": 1404, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Reanimate/Morph/Triangulate.hs", "max_stars_repo_name": "sureyeaah/reanimate", "max_stars_repo_head_hexsha": "9cf33b9444c5212f47e42497ad6e38d8e5e3b0d8", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Reanimate/Morph/Triangulate.hs", "max_issues_repo_name": "sureyeaah/reanimate", "max_issues_repo_head_hexsha": "9cf33b9444c5212f47e42497ad6e38d8e5e3b0d8", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Reanimate/Morph/Triangulate.hs", "max_forks_repo_name": "sureyeaah/reanimate", "max_forks_repo_head_hexsha": "9cf33b9444c5212f47e42497ad6e38d8e5e3b0d8", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 89, "alphanum_fraction": 0.5484330484, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5809303160417536}} {"text": "{-# LANGUAGE TypeOperators #-}\n\n--------------------------------------------------------------------------------\n{- |\nModule : Numeric.LinearAlgebra.Data\nCopyright : (c) Alberto Ruiz 2015\nLicense : BSD3\nMaintainer : Alberto Ruiz\nStability : provisional\n\nThis module provides functions for creation and manipulation of vectors and matrices, IO, and other utilities.\n\n-}\n--------------------------------------------------------------------------------\n\nmodule Numeric.LinearAlgebra.Data(\n\n -- * Elements\n R,C,I,Z,type(./.),\n\n -- * Vector\n {- | 1D arrays are storable vectors directly reexported from the vector package.\n -}\n\n fromList, toList, (|>), vector, range, idxs,\n\n -- * Matrix\n\n {- | The main data type of hmatrix is a 2D dense array defined on top of\n a storable vector. The internal representation is suitable for direct\n interface with standard numeric libraries.\n -}\n\n (><), matrix, tr, tr',\n\n -- * Dimensions\n\n size, rows, cols,\n\n -- * Conversion from\\/to lists\n\n fromLists, toLists,\n row, col,\n\n -- * Conversions vector\\/matrix\n\n flatten, reshape, asRow, asColumn,\n fromRows, toRows, fromColumns, toColumns,\n\n -- * Indexing\n\n atIndex,\n Indexable(..),\n\n -- * Construction\n scalar, Konst(..), Build(..), assoc, accum, linspace, -- ones, zeros,\n\n -- * Diagonal\n ident, diag, diagl, diagRect, takeDiag,\n\n -- * Vector extraction\n subVector, takesV, vjoin,\n\n -- * Matrix extraction\n Extractor(..), (??),\n\n (?), (\u00bf), fliprl, flipud,\n\n subMatrix, takeRows, dropRows, takeColumns, dropColumns,\n\n remap,\n\n -- * Block matrix\n fromBlocks, (|||), (===), diagBlock, repmat, toBlocks, toBlocksEvery,\n\n -- * Mapping functions\n conj, cmap, cmod,\n\n step, cond,\n\n -- * Find elements\n find, maxIndex, minIndex, maxElement, minElement,\n sortVector, sortIndex,\n\n -- * Sparse\n AssocMatrix, toDense,\n mkSparse, mkDiagR, mkDense,\n\n -- * IO\n disp,\n loadMatrix, loadMatrix', saveMatrix,\n latexFormat,\n dispf, disps, dispcf, format,\n dispDots, dispBlanks, dispShort,\n-- * Element conversion\n Convert(..),\n roundVector,\n fromInt,toInt,fromZ,toZ,\n -- * Misc\n arctan2,\n separable,\n fromArray2D,\n module Data.Complex,\n Mod,\n Vector, Matrix, GMatrix, nRows, nCols\n\n) where\n\nimport Internal.Vector\nimport Internal.Vectorized\nimport Internal.Matrix hiding (size)\nimport Internal.Element\nimport Internal.IO\nimport Internal.Numeric\nimport Internal.Container\nimport Internal.Util hiding ((&))\nimport Data.Complex\nimport Internal.Sparse\nimport Internal.Modular\n\n\n", "meta": {"hexsha": "a389aacd574caa26d701a92c572fb481ffd79cd9", "size": 2649, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/Data.hs", "max_stars_repo_name": "schnecki/hmatrix-float", "max_stars_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/LinearAlgebra/Data.hs", "max_issues_repo_name": "schnecki/hmatrix-float", "max_issues_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LinearAlgebra/Data.hs", "max_forks_repo_name": "schnecki/hmatrix-float", "max_forks_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-12T02:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T02:51:35.000Z", "avg_line_length": 21.7131147541, "max_line_length": 110, "alphanum_fraction": 0.6055115138, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.5807444271495974}} {"text": "{-# LANGUAGE TypeApplications #-}\n\nmodule MinkowskiScalarWave where\n\nimport qualified Data.Vector.Unboxed as U\nimport Data.VectorSpace\nimport qualified Numeric.LinearAlgebra as L\nimport SSSFN\n\n--------------------------------------------------------------------------------\n\n-- | Scalar wave in double-null coordinates:\n-- > (- dt^2 + dx^2) u = 0\n-- > t = v + u dt = dv + du\n-- > x = v - u dx = dv - du\n-- > (- (dv + du)^2 + (dv - du)^2) u = 0\n-- > - 4 dv du u = 0\ndalembert :: (Eq a, L.Field a, U.Unbox a) => Op a\ndalembert = -4 *^ (derivV * derivU)\n\nincomingU :: forall a. (L.Container L.Vector a, Fractional a, Ord a) => Op a\nincomingU = omap isneg (bndU @a)\n where\n isneg a = fromIntegral (fromEnum (a < 0))\n\nincomingV :: forall a. (L.Container L.Vector a, Fractional a, Ord a) => Op a\nincomingV = omap isneg (bndV @a)\n where\n isneg a = fromIntegral (fromEnum (a < 0))\n\noriginUV :: forall a. (L.Container L.Vector a, Fractional a, Ord a) => Op a\noriginUV = ozipWith (*) incomingU incomingV\n\npotential :: forall a. (L.Container L.Vector a, Floating a) => Grid a\npotential = gzipWith (\\u v -> 0) (coordU @a) (coordV @a)\n\nincoming :: forall a. (L.Container L.Vector a, Floating a) => Grid a\nincoming = gsample bcond\n\n--------------------------------------------------------------------------------\n\nop :: (L.Field a, Ord a, U.Unbox a) => Op a\nop = intr * dalembert + bndu * incomingU + bndv * incomingV + orig * originUV\n where\n bndu = incomingU - originUV\n bndv = incomingV - originUV\n orig = originUV\n intr = 1 - (bndu + bndv + orig)\n\nrhs :: (Floating a, L.Numeric a, Ord a) => Grid a\nrhs =\n intr #> potential\n ^+^ bndu #> incoming\n ^+^ bndv #> incoming\n ^+^ orig #> incoming\n where\n bndu = incomingU - originUV\n bndv = incomingV - originUV\n orig = originUV\n intr = 1 - (bndu + bndv + orig)\n\n--------------------------------------------------------------------------------\n\nbcond :: Floating a => (a, a) -> a\nbcond (u, v) = cos (pi / 4 * t) * cos (pi / 4 * x)\n where\n t = v + u\n x = v - u\n\n--------------------------------------------------------------------------------\n\nmain :: IO ()\nmain =\n do\n putStrLn \"1+1D Scalar Field in the Minkowski spacetime in double-Null coordinates\"\n -- putStrLn $ \"intr \" ++ show (intr :: Op Double)\n -- putStrLn $ \"bndu \" ++ show (bndu :: Op Double)\n -- putStrLn $ \"bndv \" ++ show (bndv :: Op Double)\n -- putStrLn $ \"orig \" ++ show (orig :: Op Double)\n -- putStrLn $ \"dal \" ++ show (omap approx (dalembert @Double))\n -- putStrLn $ \"op \" ++ show (omap approx (op @Double))\n -- let inc = incoming @Double\n -- putStrLn $ \"inc \" ++ show (gmap approx inc)\n -- putStrLn $ \"rhs \" ++ show (gmap approx (rhs @Double))\n -- let ires = dalembert #> inc\n -- putStrLn $ \"ires \" ++ show (gmap approx ires)\n -- putStrLn $ \"|ires| \" ++ show (gmaxabs ires)\n -- let jres = op #> inc ^-^ rhs\n -- putStrLn $ \"jres \" ++ show (gmap approx jres)\n -- putStrLn $ \"|jres| \" ++ show (gmaxabs jres)\n\n let sol = solve op (rhs @Double)\n putStrLn $ \"sol \" ++ show (gmap approx sol)\n let res = op #> sol ^-^ rhs\n putStrLn $ \"res \" ++ show (gmap approx res)\n putStrLn $ \"|res| \" ++ show (gmaxabs res)\n let err = sol ^-^ incoming\n putStrLn $ \"err \" ++ show (gmap approx err)\n putStrLn $ \"|err| \" ++ show (gmaxabs err)\n putStrLn \"Done.\"\n where\n approx :: RealFrac a => a -> a\n approx x = fromInteger (round (1.0e+4 * x)) / 1.0e+4\n-- intr = 1 - (incomingU + incomingV - originUV)\n-- bndu = incomingU - originUV\n-- bndv = incomingV - originUV\n-- orig = originUV\n\n--------------------------------------------------------------------------------\n\n-- quantum measurements: the quantum system measures the state of the\n-- classical system\n\n-- Beatrice Bonga: conserved current from varying boundary term from\n-- lagrangian \n", "meta": {"hexsha": "bba5869685c7f49ca75d05f37a4574bfd2915c07", "size": 3890, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MinkowskiScalarWave.hs", "max_stars_repo_name": "eschnett/sssfn", "max_stars_repo_head_hexsha": "7e00b54460e23fde7a6dd70ac74098958f54e5a5", "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/MinkowskiScalarWave.hs", "max_issues_repo_name": "eschnett/sssfn", "max_issues_repo_head_hexsha": "7e00b54460e23fde7a6dd70ac74098958f54e5a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MinkowskiScalarWave.hs", "max_forks_repo_name": "eschnett/sssfn", "max_forks_repo_head_hexsha": "7e00b54460e23fde7a6dd70ac74098958f54e5a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5344827586, "max_line_length": 86, "alphanum_fraction": 0.5375321337, "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5804855595280148}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n-----------------------------------------------------------------------------\n-- |\n-- A class for semirings (types with two binary operations, one commutative and one associative, and two respective identities), with various general-purpose instances.\n--\n-----------------------------------------------------------------------------\n\nmodule Data.Semiring\n ( -- * Semiring typeclass\n Semiring(..)\n , (+)\n , (*)\n , (^)\n , foldMapP\n , foldMapT\n , sum\n , product\n , sum'\n , product'\n , isZero\n , isOne\n\n -- * Types\n , Add(..)\n , Mul(..)\n , WrappedNum(..)\n , Mod2(..)\n#if defined(VERSION_containers)\n , IntSetOf(..)\n , IntMapOf(..)\n#endif\n\n -- * Ring typeclass\n , Ring(..)\n , fromInteger\n , fromIntegral\n , minus\n , (-)\n ) where\n\nimport Control.Applicative (Applicative(..), Const(..), liftA2)\nimport Data.Bits (Bits)\nimport Data.Bool (Bool(..), (||), (&&), otherwise)\nimport Data.Coerce (Coercible, coerce)\nimport Data.Complex (Complex(..))\nimport Data.Eq (Eq(..))\nimport Data.Fixed (Fixed, HasResolution)\nimport Data.Foldable (Foldable(foldMap))\nimport qualified Data.Foldable as Foldable\nimport Data.Function ((.), const, id)\n#if defined(VERSION_unordered_containers) || defined(VERSION_containers)\nimport Data.Function (flip)\n#endif\nimport Data.Functor (Functor(..))\n#if MIN_VERSION_base(4,12,0)\nimport Data.Functor.Contravariant (Predicate(..), Equivalence(..), Op(..))\n#endif\nimport Data.Functor.Identity (Identity(..))\n#if defined(VERSION_unordered_containers)\nimport Data.Hashable (Hashable)\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.HashSet (HashSet)\nimport qualified Data.HashSet as HashSet\n#endif\nimport Data.Int (Int, Int8, Int16, Int32, Int64)\nimport Data.Maybe (Maybe(..))\n#if MIN_VERSION_base(4,12,0)\nimport Data.Monoid (Ap(..))\n#endif\n#if defined(VERSION_containers)\n#if MIN_VERSION_base(4,7,0)\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n#endif\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n#endif\nimport Data.Monoid (Monoid(..), Dual(..))\nimport Data.Ord (Ord((<)), (>=))\nimport Data.Ord (Down(..))\nimport Data.Proxy (Proxy(..))\nimport Data.Ratio (Ratio, Rational, (%))\nimport Data.Semigroup.Compat (Semigroup(..))\n#if defined(VERSION_containers)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n#endif\nimport Data.Traversable (Traversable)\nimport Data.Typeable (Typeable)\nimport Data.Word (Word, Word8, Word16, Word32, Word64)\nimport Foreign.C.Types\n (CChar, CClock, CDouble, CFloat, CInt,\n CIntMax, CIntPtr, CLLong, CLong,\n CPtrdiff, CSChar, CSUSeconds, CShort,\n CSigAtomic, CSize, CTime, CUChar, CUInt,\n CUIntMax, CUIntPtr, CULLong, CULong,\n CUSeconds, CUShort, CWchar)\nimport Foreign.Ptr (IntPtr, WordPtr)\nimport Foreign.Storable (Storable)\nimport GHC.Enum (Enum, Bounded)\nimport GHC.Err (error)\nimport GHC.Float (Float, Double)\nimport GHC.Generics (Generic,Generic1)\nimport GHC.IO (IO)\nimport GHC.Integer (Integer)\nimport qualified GHC.Num as Num\nimport GHC.Read (Read)\nimport GHC.Real (Integral, Fractional, Real, RealFrac)\nimport qualified GHC.Real as Real\nimport GHC.Show (Show)\nimport Numeric.Natural (Natural)\n\n#ifdef mingw32_HOST_OS\n#define HOST_OS_WINDOWS 1\n#else\n#define HOST_OS_WINDOWS 0\n#endif\n\n#if !HOST_OS_WINDOWS\nimport System.Posix.Types\n (CCc, CDev, CGid, CIno, CMode, CNlink,\n COff, CPid, CRLim, CSpeed, CSsize,\n CTcflag, CUid, Fd)\n#endif\n\ninfixl 7 *, `times`\ninfixl 6 +, `plus`, -, `minus`\ninfixr 8 ^\n\n{--------------------------------------------------------------------\n Helpers\n--------------------------------------------------------------------}\n\n-- | Raise a number to a non-negative integral power.\n-- If the power is negative, this will call 'error'.\n{-# SPECIALISE [1] (^) ::\n Integer -> Integer -> Integer,\n Integer -> Int -> Integer,\n Int -> Int -> Int #-}\n{-# INLINABLE [1] (^) #-} -- See note [Inlining (^)]\n(^) :: (Semiring a, Integral b) => a -> b -> a\nx ^ y\n | y < 0 = error \"Data.Semiring.^: negative power\"\n | y == 0 = one\n | otherwise = getMul (stimes y (Mul x))\n\n{- Note [Inlining (^)]\n ~~~~~~~~~~~~~~~~~~~\n The INLINABLE pragma allows (^) to be specialised at its call sites.\n If it is called repeatedly at the same type, that can make a huge\n difference, because of those constants which can be repeatedly\n calculated.\n\n Currently the fromInteger calls are not floated because we get\n \\d1 d2 x y -> blah\n after the gentle round of simplification.\n-}\n\n{- Rules for powers with known small exponent\n see Trac #5237\n For small exponents, (^) is inefficient compared to manually\n expanding the multiplication tree.\n Here, rules for the most common exponent types are given.\n The range of exponents for which rules are given is quite\n arbitrary and kept small to not unduly increase the number of rules.\n It might be desirable to have corresponding rules also for\n exponents of other types (e.g., Word), but it's doubtful they\n would fire, since the exponents of other types tend to get\n floated out before the rule has a chance to fire. (Why?)\n\n Note: Trying to save multiplication by sharing the square for\n exponents 4 and 5 does not save time, indeed, for Double, it is\n up to twice slower, so the rules contain flat sequences of\n multiplications.\n-}\n\n{-# RULES\n\"^0/Int\" forall x. x ^ (0 :: Int) = one\n\"^1/Int\" forall x. x ^ (1 :: Int) = let u = x in u\n\"^2/Int\" forall x. x ^ (2 :: Int) = let u = x in u*u\n\"^3/Int\" forall x. x ^ (3 :: Int) = let u = x in u*u*u\n\"^4/Int\" forall x. x ^ (4 :: Int) = let u = x in u*u*u*u\n\"^5/Int\" forall x. x ^ (5 :: Int) = let u = x in u*u*u*u*u\n\"^0/Integer\" forall x. x ^ (0 :: Integer) = one\n\"^1/Integer\" forall x. x ^ (1 :: Integer) = let u = x in u\n\"^2/Integer\" forall x. x ^ (2 :: Integer) = let u = x in u*u\n\"^3/Integer\" forall x. x ^ (3 :: Integer) = let u = x in u*u*u\n\"^4/Integer\" forall x. x ^ (4 :: Integer) = let u = x in u*u*u*u\n\"^5/Integer\" forall x. x ^ (5 :: Integer) = let u = x in u*u*u*u*u\n #-}\n\n-- | Infix shorthand for 'plus'.\n(+) :: Semiring a => a -> a -> a\n(+) = plus\n{-# INLINE (+) #-}\n\n-- | Infix shorthand for 'times'.\n(*) :: Semiring a => a -> a -> a\n(*) = times\n{-# INLINE (*) #-}\n\n-- | Infix shorthand for 'minus'.\n(-) :: Ring a => a -> a -> a\n(-) = minus\n{-# INLINE (-) #-}\n\n-- | Map each element of the structure to a semiring, and combine the results\n-- using 'plus'.\nfoldMapP :: (Foldable t, Semiring s) => (a -> s) -> t a -> s\nfoldMapP f = Foldable.foldr (plus . f) zero\n{-# INLINE foldMapP #-}\n\n-- | Map each element of the structure to a semiring, and combine the results\n-- using 'times'.\nfoldMapT :: (Foldable t, Semiring s) => (a -> s) -> t a -> s\nfoldMapT f = Foldable.foldr (times . f) one\n{-# INLINE foldMapT #-}\n\ninfixr 9 #.\n(#.) :: Coercible b c => (b -> c) -> (a -> b) -> a -> c\n(#.) _ = coerce\n\n-- | The 'sum' function computes the additive sum of the elements in a structure.\n-- This function is lazy. For a strict version, see 'sum''.\nsum :: (Foldable t, Semiring a) => t a -> a\nsum = getAdd #. foldMap Add\n{-# INLINE sum #-}\n\n-- | The 'product' function computes the product of the elements in a structure.\n-- This function is lazy. for a strict version, see 'product''.\nproduct :: (Foldable t, Semiring a) => t a -> a\nproduct = getMul #. foldMap Mul\n{-# INLINE product #-}\n\n-- | The 'sum'' function computes the additive sum of the elements in a structure.\n-- This function is strict. For a lazy version, see 'sum'.\nsum' :: (Foldable t, Semiring a) => t a -> a\nsum' = Foldable.foldl' plus zero\n{-# INLINE sum' #-}\n\n-- | The 'product'' function computes the additive sum of the elements in a structure.\n-- This function is strict. For a lazy version, see 'product'.\nproduct' :: (Foldable t, Semiring a) => t a -> a\nproduct' = Foldable.foldl' times one\n{-# INLINE product' #-}\n\n-- | Monoid under 'plus'. Analogous to 'Data.Monoid.Sum', but\n-- uses the 'Semiring' constraint rather than 'Num.Num'.\nnewtype Add a = Add { getAdd :: a }\n deriving\n ( Bounded\n , Enum\n , Eq\n , Foldable\n , Fractional\n , Functor\n , Generic\n , Generic1\n , Num.Num\n , Ord\n , Read\n , Real\n , RealFrac\n , Show\n , Storable\n , Traversable\n , Typeable\n )\n\ninstance Semiring a => Semigroup (Add a) where\n Add a <> Add b = Add (a + b)\n stimes n (Add a) = Add (fromNatural (Real.fromIntegral n) * a)\n {-# INLINE (<>) #-}\n\ninstance Semiring a => Monoid (Add a) where\n mempty = Add zero\n mappend = (<>)\n {-# INLINE mempty #-}\n {-# INLINE mappend #-}\n\n-- | This is an internal type, solely for purposes\n-- of default implementation of 'fromNatural'.\nnewtype Add' a = Add' { getAdd' :: a }\n\ninstance Semiring a => Semigroup (Add' a) where\n Add' a <> Add' b = Add' (a + b)\n\n-- | Monoid under 'times'. Analogous to 'Data.Monoid.Product', but\n-- uses the 'Semiring' constraint rather than 'Num.Num'.\nnewtype Mul a = Mul { getMul :: a }\n deriving\n ( Bounded\n , Enum\n , Eq\n , Foldable\n , Fractional\n , Functor\n , Generic\n , Generic1\n , Num.Num\n , Ord\n , Read\n , Real\n , RealFrac\n , Show\n , Storable\n , Traversable\n , Typeable\n )\n\ninstance Semiring a => Semigroup (Mul a) where\n Mul a <> Mul b = Mul (a * b)\n {-# INLINE (<>) #-}\n\ninstance Semiring a => Monoid (Mul a) where\n mempty = Mul one\n mappend = (<>)\n {-# INLINE mempty #-}\n {-# INLINE mappend #-}\n\n-- | Provide Semiring and Ring for an arbitrary 'Num.Num'. It is useful with GHC 8.6+'s DerivingVia extension.\nnewtype WrappedNum a = WrapNum { unwrapNum :: a }\n deriving\n ( Bounded\n , Enum\n , Eq\n , Foldable\n , Fractional\n , Functor\n , Generic\n , Generic1\n , Num.Num\n , Ord\n , Read\n , Real\n , RealFrac\n , Show\n , Storable\n , Traversable\n , Typeable\n , Bits\n )\n\ninstance Num.Num a => Semiring (WrappedNum a) where\n plus = (Num.+)\n zero = 0\n times = (Num.*)\n one = 1\n fromNatural = Real.fromIntegral\n\ninstance Num.Num a => Ring (WrappedNum a) where\n negate = Num.negate\n\n-- | 'Mod2' represents the integers mod 2.\n--\n-- It is useful in the computing of .\nnewtype Mod2 = Mod2 { getMod2 :: Bool }\n deriving\n ( Bounded\n , Enum\n , Eq\n , Ord\n , Read\n , Show\n , Generic\n )\n\ninstance Semiring Mod2 where\n -- we inline the definition of 'xor'\n -- on Bools, since the instance did not exist until\n -- base-4.7.0.\n plus (Mod2 x) (Mod2 y) = Mod2 (x /= y)\n times (Mod2 x) (Mod2 y) = Mod2 (x && y)\n zero = Mod2 False\n one = Mod2 True\n\ninstance Ring Mod2 where\n negate = id\n {-# INLINE negate #-}\n\n\n{--------------------------------------------------------------------\n Classes\n--------------------------------------------------------------------}\n\n-- | The class of semirings (types with two binary\n-- operations and two respective identities). One\n-- can think of a semiring as two monoids of the same\n-- underlying type, with the first being commutative.\n-- In the documentation, you will often see the first\n-- monoid being referred to as @additive@, and the second\n-- monoid being referred to as @multiplicative@, a typical\n-- convention when talking about semirings.\n--\n-- For any type R with a 'Num.Num'\n-- instance, the additive monoid is (R, 'Prelude.+', 0)\n-- and the multiplicative monoid is (R, 'Prelude.*', 1).\n--\n-- For 'Prelude.Bool', the additive monoid is ('Prelude.Bool', 'Prelude.||', 'Prelude.False')\n-- and the multiplicative monoid is ('Prelude.Bool', 'Prelude.&&', 'Prelude.True').\n--\n-- Instances should satisfy the following laws:\n--\n-- [/additive left identity/]\n-- @'zero' '+' x = x@\n-- [/additive right identity/]\n-- @x '+' 'zero' = x@\n-- [/additive associativity/]\n-- @x '+' (y '+' z) = (x '+' y) '+' z@\n-- [/additive commutativity/]\n-- @x '+' y = y '+' x@\n-- [/multiplicative left identity/]\n-- @'one' '*' x = x@\n-- [/multiplicative right identity/]\n-- @x '*' 'one' = x@\n-- [/multiplicative associativity/]\n-- @x '*' (y '*' z) = (x '*' y) '*' z@\n-- [/left-distributivity of '*' over '+'/]\n-- @x '*' (y '+' z) = (x '*' y) '+' (x '*' z)@\n-- [/right-distributivity of '*' over '+'/]\n-- @(x '+' y) '*' z = (x '*' z) '+' (y '*' z)@\n-- [/annihilation/]\n-- @'zero' '*' x = x '*' 'zero' = 'zero'@\n\nclass Semiring a where\n#if __GLASGOW_HASKELL__ >= 708\n {-# MINIMAL plus, times, (zero, one | fromNatural) #-}\n#endif\n plus :: a -> a -> a -- ^ Commutative Operation\n zero :: a -- ^ Commutative Unit\n zero = fromNatural 0\n times :: a -> a -> a -- ^ Associative Operation\n one :: a -- ^ Associative Unit\n one = fromNatural 1\n fromNatural :: Natural -> a -- ^ Homomorphism of additive semigroups\n fromNatural 0 = zero\n fromNatural n = getAdd' (stimes n (Add' one))\n\n-- | The class of semirings with an additive inverse.\n--\n-- @'negate' a '+' a = 'zero'@\n\nclass Semiring a => Ring a where\n#if __GLASGOW_HASKELL__ >= 708\n {-# MINIMAL negate #-}\n#endif\n negate :: a -> a\n\n-- | Subtract two 'Ring' values. For any type @R@ with\n-- a 'Num.Num' instance, this is the same as '(Prelude.-)'.\n--\n-- @x `minus` y = x '+' 'negate' y@\nminus :: Ring a => a -> a -> a\nminus x y = x + negate y\n{-# INLINE minus #-}\n\n-- | Convert from integer to ring.\n--\n-- When @{-#@ @LANGUAGE RebindableSyntax #-}@ is enabled,\n-- this function is used for desugaring integer literals.\n-- This may be used to facilitate transition from 'Num.Num' to 'Ring':\n-- no need to replace 0 and 1 with 'one' and 'zero'\n-- or to cast numeric literals.\nfromInteger :: Ring a => Integer -> a\nfromInteger x\n | x >= 0 = fromNatural (Num.fromInteger x)\n | otherwise = negate (fromNatural (Num.fromInteger (Num.negate x)))\n{-# INLINE fromInteger #-}\n\n-- | Convert from integral to ring.\nfromIntegral :: (Integral a, Ring b) => a -> b\nfromIntegral x\n | x >= 0 = fromNatural (Real.fromIntegral x)\n | otherwise = negate (fromNatural (Real.fromIntegral (Num.negate x)))\n{-# INLINE fromIntegral #-}\n\n{--------------------------------------------------------------------\n Instances (base)\n--------------------------------------------------------------------}\n\ninstance Semiring b => Semiring (a -> b) where\n plus f g = \\x -> f x `plus` g x\n zero = const zero\n times f g = \\x -> f x `times` g x\n one = const one\n fromNatural = const . fromNatural\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\ninstance Ring b => Ring (a -> b) where\n negate f x = negate (f x)\n {-# INLINE negate #-}\n\ninstance Semiring () where\n plus _ _ = ()\n zero = ()\n times _ _ = ()\n one = ()\n fromNatural _ = ()\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\ninstance Ring () where\n negate _ = ()\n {-# INLINE negate #-}\n\ninstance Semiring (Proxy a) where\n plus _ _ = Proxy\n zero = Proxy\n times _ _ = Proxy\n one = Proxy\n fromNatural _ = Proxy\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\ninstance Semiring Bool where\n plus = (||)\n zero = False\n times = (&&)\n one = True\n fromNatural 0 = False\n fromNatural _ = True\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\ninstance Semiring a => Semiring (Maybe a) where\n zero = Nothing\n one = Just one\n\n plus Nothing y = y\n plus x Nothing = x\n plus (Just x) (Just y) = Just (plus x y)\n\n times Nothing _ = Nothing\n times _ Nothing = Nothing\n times (Just x) (Just y) = Just (times x y)\n\n fromNatural 0 = Nothing\n fromNatural n = Just (fromNatural n)\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\ninstance Semiring a => Semiring (IO a) where\n zero = pure zero\n one = pure one\n plus = liftA2 plus\n times = liftA2 times\n fromNatural = pure . fromNatural\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\ninstance Ring a => Ring (IO a) where\n negate = fmap negate\n {-# INLINE negate #-}\n\ninstance Semiring a => Semiring (Dual a) where\n zero = Dual zero\n Dual x `plus` Dual y = Dual (y `plus` x)\n one = Dual one\n Dual x `times` Dual y = Dual (y `times` x)\n fromNatural = Dual . fromNatural\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\ninstance Ring a => Ring (Dual a) where\n negate (Dual x) = Dual (negate x)\n {-# INLINE negate #-}\n\ninstance Semiring a => Semiring (Const a b) where\n zero = Const zero\n one = Const one\n plus (Const x) (Const y) = Const (x `plus` y)\n times (Const x) (Const y) = Const (x `times` y)\n fromNatural = Const . fromNatural\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\ninstance Ring a => Ring (Const a b) where\n negate (Const x) = Const (negate x)\n {-# INLINE negate #-}\n\n-- | This instance can suffer due to floating point arithmetic.\ninstance Ring a => Semiring (Complex a) where\n zero = zero :+ zero\n one = one :+ zero\n plus (x :+ y) (x' :+ y') = plus x x' :+ plus y y'\n times (x :+ y) (x' :+ y')\n = (x * x' - (y * y')) :+ (x * y' + y * x')\n fromNatural n = fromNatural n :+ zero\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\ninstance Ring a => Ring (Complex a) where\n negate (x :+ y) = negate x :+ negate y\n {-# INLINE negate #-}\n\n#if MIN_VERSION_base(4,12,0)\ninstance (Semiring a, Applicative f) => Semiring (Ap f a) where\n zero = pure zero\n one = pure one\n plus = liftA2 plus\n times = liftA2 times\n fromNatural = pure . fromNatural\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\ninstance (Ring a, Applicative f) => Ring (Ap f a) where\n negate = fmap negate\n {-# INLINE negate #-}\n#endif\n\n#if MIN_VERSION_base(4,12,0)\nderiving instance Semiring (Predicate a)\n\nderiving instance Semiring a => Semiring (Equivalence a)\n\nderiving instance Semiring a => Semiring (Op a b)\nderiving instance Ring a => Ring (Op a b)\n#endif\n\n#define deriveSemiring(ty) \\\ninstance Semiring (ty) where { \\\n zero = 0 \\\n; one = 1 \\\n; plus x y = (Num.+) x y \\\n; times x y = (Num.*) x y \\\n; fromNatural = Real.fromIntegral \\\n; {-# INLINE zero #-} \\\n; {-# INLINE one #-} \\\n; {-# INLINE plus #-} \\\n; {-# INLINE times #-} \\\n; {-# INLINE fromNatural #-} \\\n}\n\nderiveSemiring(Int)\nderiveSemiring(Int8)\nderiveSemiring(Int16)\nderiveSemiring(Int32)\nderiveSemiring(Int64)\nderiveSemiring(Integer)\nderiveSemiring(Word)\nderiveSemiring(Word8)\nderiveSemiring(Word16)\nderiveSemiring(Word32)\nderiveSemiring(Word64)\nderiveSemiring(Float)\nderiveSemiring(Double)\nderiveSemiring(CUIntMax)\nderiveSemiring(CIntMax)\nderiveSemiring(CUIntPtr)\nderiveSemiring(CIntPtr)\nderiveSemiring(CSUSeconds)\nderiveSemiring(CUSeconds)\nderiveSemiring(CTime)\nderiveSemiring(CClock)\nderiveSemiring(CSigAtomic)\nderiveSemiring(CWchar)\nderiveSemiring(CSize)\nderiveSemiring(CPtrdiff)\nderiveSemiring(CDouble)\nderiveSemiring(CFloat)\nderiveSemiring(CULLong)\nderiveSemiring(CLLong)\nderiveSemiring(CULong)\nderiveSemiring(CLong)\nderiveSemiring(CUInt)\nderiveSemiring(CInt)\nderiveSemiring(CUShort)\nderiveSemiring(CShort)\nderiveSemiring(CUChar)\nderiveSemiring(CSChar)\nderiveSemiring(CChar)\nderiveSemiring(IntPtr)\nderiveSemiring(WordPtr)\n\n#if !HOST_OS_WINDOWS\nderiveSemiring(CCc)\nderiveSemiring(CDev)\nderiveSemiring(CGid)\nderiveSemiring(CIno)\nderiveSemiring(CMode)\nderiveSemiring(CNlink)\nderiveSemiring(COff)\nderiveSemiring(CPid)\nderiveSemiring(CRLim)\nderiveSemiring(CSpeed)\nderiveSemiring(CSsize)\nderiveSemiring(CTcflag)\nderiveSemiring(CUid)\nderiveSemiring(Fd)\n#endif\n\nderiveSemiring(Natural)\n\ninstance Integral a => Semiring (Ratio a) where\n {-# SPECIALIZE instance Semiring Rational #-}\n zero = 0 % 1\n one = 1 % 1\n plus = (Num.+)\n times = (Num.*)\n fromNatural n = Real.fromIntegral n % 1\n {-# INLINE zero #-}\n {-# INLINE one #-}\n {-# INLINE plus #-}\n {-# INLINE times #-}\n {-# INLINE fromNatural #-}\nderiving instance Semiring a => Semiring (Identity a)\nderiving instance Semiring a => Semiring (Down a)\ninstance HasResolution a => Semiring (Fixed a) where\n zero = 0\n one = 1\n plus = (Num.+)\n times = (Num.*)\n fromNatural = Real.fromIntegral\n {-# INLINE zero #-}\n {-# INLINE one #-}\n {-# INLINE plus #-}\n {-# INLINE times #-}\n {-# INLINE fromNatural #-}\n\n#define deriveRing(ty) \\\ninstance Ring (ty) where { \\\n negate = Num.negate \\\n; {-# INLINE negate #-} \\\n}\n\nderiveRing(Int)\nderiveRing(Int8)\nderiveRing(Int16)\nderiveRing(Int32)\nderiveRing(Int64)\nderiveRing(Integer)\nderiveRing(Word)\nderiveRing(Word8)\nderiveRing(Word16)\nderiveRing(Word32)\nderiveRing(Word64)\nderiveRing(Float)\nderiveRing(Double)\nderiveRing(CUIntMax)\nderiveRing(CIntMax)\nderiveRing(CUIntPtr)\nderiveRing(CIntPtr)\nderiveRing(CSUSeconds)\nderiveRing(CUSeconds)\nderiveRing(CTime)\nderiveRing(CClock)\nderiveRing(CSigAtomic)\nderiveRing(CWchar)\nderiveRing(CSize)\nderiveRing(CPtrdiff)\nderiveRing(CDouble)\nderiveRing(CFloat)\nderiveRing(CULLong)\nderiveRing(CLLong)\nderiveRing(CULong)\nderiveRing(CLong)\nderiveRing(CUInt)\nderiveRing(CInt)\nderiveRing(CUShort)\nderiveRing(CShort)\nderiveRing(CUChar)\nderiveRing(CSChar)\nderiveRing(CChar)\nderiveRing(IntPtr)\nderiveRing(WordPtr)\n\n#if !HOST_OS_WINDOWS\nderiveRing(CCc)\nderiveRing(CDev)\nderiveRing(CGid)\nderiveRing(CIno)\nderiveRing(CMode)\nderiveRing(CNlink)\nderiveRing(COff)\nderiveRing(CPid)\nderiveRing(CRLim)\nderiveRing(CSpeed)\nderiveRing(CSsize)\nderiveRing(CTcflag)\nderiveRing(CUid)\nderiveRing(Fd)\n#endif\n\ninstance Integral a => Ring (Ratio a) where\n negate = Num.negate\n {-# INLINE negate #-}\n\nderiving instance Ring a => Ring (Down a)\nderiving instance Ring a => Ring (Identity a)\ninstance HasResolution a => Ring (Fixed a) where\n negate = Num.negate\n {-# INLINE negate #-}\n\n{--------------------------------------------------------------------\n Instances (containers)\n--------------------------------------------------------------------}\n\n#if defined(VERSION_containers)\n\n-- | The multiplication laws are satisfied for\n-- any underlying 'Monoid', so we require a\n-- 'Monoid' constraint instead of a 'Semiring'\n-- constraint since 'times' can use\n-- the context of either.\ninstance (Ord a, Monoid a) => Semiring (Set a) where\n zero = Set.empty\n one = Set.singleton mempty\n plus = Set.union\n times xs ys = Foldable.foldMap (flip Set.map ys . mappend) xs\n fromNatural 0 = zero\n fromNatural _ = one\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\n-- | Wrapper to mimic 'Set' ('Data.Semigroup.Sum' 'Int'),\n-- 'Set' ('Data.Semigroup.Product' 'Int'), etc.,\n-- while having a more efficient underlying representation.\nnewtype IntSetOf a = IntSetOf { getIntSet :: IntSet }\n deriving\n ( Eq\n , Generic\n , Generic1\n , Ord\n , Read\n , Show\n , Typeable\n , Semigroup\n , Monoid\n )\n\ninstance (Coercible Int a, Monoid a) => Semiring (IntSetOf a) where\n zero = coerce IntSet.empty\n one = coerce IntSet.singleton (mempty :: a)\n plus = coerce IntSet.union\n xs `times` ys\n = coerce IntSet.fromList\n [ mappend k l\n | k :: a <- coerce IntSet.toList xs\n , l :: a <- coerce IntSet.toList ys\n ]\n fromNatural 0 = zero\n fromNatural _ = one\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\n-- | The multiplication laws are satisfied for\n-- any underlying 'Monoid' as the key type,\n-- so we require a 'Monoid' constraint instead of\n-- a 'Semiring' constraint since 'times' can use\n-- the context of either.\ninstance (Ord k, Monoid k, Semiring v) => Semiring (Map k v) where\n zero = Map.empty\n one = Map.singleton mempty one\n plus = Map.unionWith (+)\n xs `times` ys\n = Map.fromListWith (+)\n [ (mappend k l, v * u)\n | (k,v) <- Map.toList xs\n , (l,u) <- Map.toList ys\n ]\n fromNatural 0 = zero\n fromNatural n = Map.singleton mempty (fromNatural n)\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\n-- | Wrapper to mimic 'Map' ('Data.Semigroup.Sum' 'Int') v,\n-- 'Map' ('Data.Semigroup.Product' 'Int') v, etc.,\n-- while having a more efficient underlying representation.\nnewtype IntMapOf k v = IntMapOf { getIntMap :: IntMap v }\n deriving\n ( Eq\n , Generic\n , Generic1\n , Ord\n , Read\n , Show\n , Typeable\n , Semigroup\n , Monoid\n )\n\ninstance (Coercible Int k, Monoid k, Semiring v) => Semiring (IntMapOf k v) where\n zero = coerce (IntMap.empty :: IntMap v)\n one = coerce (IntMap.singleton :: Int -> v -> IntMap v) (mempty :: k) (one :: v)\n plus = coerce (IntMap.unionWith (+) :: IntMap v -> IntMap v -> IntMap v)\n xs `times` ys\n = coerce (IntMap.fromListWith (+) :: [(Int, v)] -> IntMap v)\n [ (mappend k l, v * u)\n | (k :: k, v :: v) <- coerce (IntMap.toList :: IntMap v -> [(Int, v)]) xs\n , (l :: k, u :: v) <- coerce (IntMap.toList :: IntMap v -> [(Int, v)]) ys\n ]\n fromNatural 0 = zero\n fromNatural n = coerce (IntMap.singleton :: Int -> v -> IntMap v) (mempty :: k) (fromNatural n :: v)\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\n#endif\n\n{--------------------------------------------------------------------\n Instances (unordered-containers)\n--------------------------------------------------------------------}\n\n#if defined(VERSION_unordered_containers)\n\n-- | The multiplication laws are satisfied for\n-- any underlying 'Monoid', so we require a\n-- 'Monoid' constraint instead of a 'Semiring'\n-- constraint since 'times' can use\n-- the context of either.\ninstance (Eq a, Hashable a, Monoid a) => Semiring (HashSet a) where\n zero = HashSet.empty\n one = HashSet.singleton mempty\n plus = HashSet.union\n times xs ys = Foldable.foldMap (flip HashSet.map ys . mappend) xs\n fromNatural 0 = zero\n fromNatural _ = one\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n\n-- | The multiplication laws are satisfied for\n-- any underlying 'Monoid' as the key type,\n-- so we require a 'Monoid' constraint instead of\n-- a 'Semiring' constraint since 'times' can use\n-- the context of either.\ninstance (Eq k, Hashable k, Monoid k, Semiring v) => Semiring (HashMap k v) where\n zero = HashMap.empty\n one = HashMap.singleton mempty one\n plus = HashMap.unionWith (+)\n xs `times` ys\n = HashMap.fromListWith (+)\n [ (mappend k l, v * u)\n | (k,v) <- HashMap.toList xs\n , (l,u) <- HashMap.toList ys\n ]\n fromNatural 0 = zero\n fromNatural n = HashMap.singleton mempty (fromNatural n)\n {-# INLINE plus #-}\n {-# INLINE zero #-}\n {-# INLINE times #-}\n {-# INLINE one #-}\n {-# INLINE fromNatural #-}\n#endif\n\n-- | Is the value 'zero'?\nisZero :: (Eq a, Semiring a) => a -> Bool\nisZero x = x == zero\n{-# INLINEABLE isZero #-}\n\n-- | Is the value 'one'?\nisOne :: (Eq a, Semiring a) => a -> Bool\nisOne x = x == one\n{-# INLINEABLE isOne #-}\n", "meta": {"hexsha": "f914f2fa592b18e0affed9ac1199d41cd5e76673", "size": 28713, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Semiring.hs", "max_stars_repo_name": "incertia/semirings", "max_stars_repo_head_hexsha": "342eb592ed40f2c2f12004489a7d2867ab1637b0", "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": "Data/Semiring.hs", "max_issues_repo_name": "incertia/semirings", "max_issues_repo_head_hexsha": "342eb592ed40f2c2f12004489a7d2867ab1637b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data/Semiring.hs", "max_forks_repo_name": "incertia/semirings", "max_forks_repo_head_hexsha": "342eb592ed40f2c2f12004489a7d2867ab1637b0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2886699507, "max_line_length": 168, "alphanum_fraction": 0.5997631735, "num_tokens": 8175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5804855448855097}} {"text": "module Main where\n\nimport Data.Ord (comparing)\nimport qualified Data.Vector.Algorithms.Intro as Intro\nimport qualified Data.Vector.Storable as VS\nimport Data.Vector.Storable.Mutable (IOVector)\nimport Numeric.LinearAlgebra hiding (eig, vector)\nimport Numeric.LinearAlgebra.Arnoldi\nimport Test.Hspec\nimport Test.QuickCheck\n\nmain :: IO ()\nmain = hspec $ do\n describe \"Numeric.LinearAlgebra.Arnoldi.eig\" $ do\n\n it \"returns the diagonal of an arbitrary diagonal matrix\" $ property $ do\n dim <- arbitrary `suchThat` (> 3)\n diagonal <- VS.fromList <$> vector dim\n let\n _matrix = diag diagonal :: Matrix Double\n nev = dim - 3\n options = Options { which = SR\n , number = nev\n , maxIterations = Nothing\n }\n sort = VS.modify Intro.sort\n actual = (sort . fst) (eig options dim (multiply _matrix))\n expected = (VS.take nev . sort) diagonal\n relative = VS.maximum (VS.zipWith (%) expected actual)\n pure (counterexample (show (expected, actual)) (relative < 1E-4))\n\n it \"returns the diagonal of an arbitrary diagonal matrix\" $ property $ do\n dim <- arbitrary `suchThat` (> 3)\n diagonal <- VS.fromList <$> vector dim\n let\n _matrix = diag diagonal :: Matrix (Complex Double)\n nev = dim - 3\n options = Options { which = SR\n , number = nev\n , maxIterations = Nothing\n }\n sort = VS.modify (Intro.sortBy (comparing realPart))\n actual = (sort . fst) (eig options dim (multiply _matrix))\n expected = (VS.take nev . sort) diagonal\n relative = VS.maximum (VS.zipWith (%%) expected actual)\n pure (counterexample (show (expected, actual)) (relative < 1E-4))\n\nmultiply :: Numeric a => Matrix a -> IOVector a -> IOVector a -> IO ()\nmultiply _matrix dst src = do\n x <- VS.freeze src\n let y = _matrix #> x\n VS.copy dst y\n\n(%) :: Double -> Double -> Double\n(%) a b =\n let a_plus_b = a + b\n in if a_plus_b /= 0\n then abs ((a - b) / a_plus_b)\n else a - b\n\n(%%) :: Complex Double -> Complex Double -> Double\n(%%) a b =\n let a_plus_b = a + b\n in if a_plus_b /= 0\n then magnitude ((a - b) / a_plus_b)\n else magnitude (a - b)\n", "meta": {"hexsha": "79a51fbca0c39ffb7e622a1f10882f6200ce408e", "size": 2306, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/tests.hs", "max_stars_repo_name": "ttuegel/arpack", "max_stars_repo_head_hexsha": "004b7b4444f2ab7b2b1c07ed6aecf279e330f9a5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-17T01:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-17T01:05:40.000Z", "max_issues_repo_path": "tests/tests.hs", "max_issues_repo_name": "ttuegel/arpack", "max_issues_repo_head_hexsha": "004b7b4444f2ab7b2b1c07ed6aecf279e330f9a5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-09-30T09:59:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-30T19:56:06.000Z", "max_forks_repo_path": "tests/tests.hs", "max_forks_repo_name": "ttuegel/arpack", "max_forks_repo_head_hexsha": "004b7b4444f2ab7b2b1c07ed6aecf279e330f9a5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4179104478, "max_line_length": 77, "alphanum_fraction": 0.5928013877, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.5803978326918692}} {"text": "{-# LANGUAGE FlexibleContexts, FlexibleInstances, TypeFamilies #-}\n\nmodule Tests.ApproxEq\n (\n ApproxEq(..)\n ) where\n\nimport Data.Complex (Complex(..), realPart)\nimport Data.List (intersperse)\nimport Data.Maybe (catMaybes)\nimport Numeric.MathFunctions.Constants (m_epsilon)\nimport Statistics.Matrix hiding (map, toList)\nimport Test.QuickCheck\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\nimport qualified Statistics.Matrix as M\n\nclass (Eq a, Show a) => ApproxEq a where\n type Bounds a\n\n eq :: Bounds a -> a -> a -> Bool\n eql :: Bounds a -> a -> a -> Property\n eql eps a b = counterexample (show a ++ \" /=~ \" ++ show b) (eq eps a b)\n\n (=~) :: a -> a -> Bool\n\n (==~) :: a -> a -> Property\n a ==~ b = counterexample (show a ++ \" /=~ \" ++ show b) (a =~ b)\n\ninstance ApproxEq Double where\n type Bounds Double = Double\n\n eq eps a b\n | a == 0 && b == 0 = True\n | otherwise = abs (a - b) <= eps * max (abs a) (abs b)\n (=~) = eq m_epsilon\n\ninstance ApproxEq (Complex Double) where\n type Bounds (Complex Double) = Double\n\n eq eps a@(ar :+ ai) b@(br :+ bi)\n | a == 0 && b == 0 = True\n | otherwise = abs (ar - br) <= eps * d\n && abs (ai - bi) <= eps * d\n where\n d = max (realPart $ abs a) (realPart $ abs b)\n\n (=~) = eq m_epsilon\n\ninstance ApproxEq [Double] where\n type Bounds [Double] = Double\n\n eq eps (x:xs) (y:ys) = eq eps x y && eq eps xs ys\n eq _ [] [] = True\n eq _ _ _ = False\n\n eql = eqll length id id\n (=~) = eq m_epsilon\n (==~) = eql m_epsilon\n\ninstance ApproxEq (U.Vector Double) where\n type Bounds (U.Vector Double) = Double\n\n eq = eqv\n (=~) = eq m_epsilon\n eql = eqlv\n (==~) = eqlv m_epsilon\n\ninstance ApproxEq (V.Vector Double) where\n type Bounds (V.Vector Double) = Double\n\n eq = eqv\n (=~) = eq m_epsilon\n eql = eqlv\n (==~) = eqlv m_epsilon\n\ninstance ApproxEq Matrix where\n type Bounds Matrix = Double\n\n eq eps (Matrix r1 c1 e1 v1) (Matrix r2 c2 e2 v2) =\n (r1,c1,e1) == (r2,c2,e2) && eq eps v1 v2\n (=~) = eq m_epsilon\n eql eps a b = eqll dimension M.toList (`quotRem` cols a) eps a b\n (==~) = eql m_epsilon\n\neqv :: (ApproxEq a, G.Vector v Bool, G.Vector v a) =>\n Bounds a -> v a -> v a -> Bool\neqv eps a b = G.length a == G.length b && G.and (G.zipWith (eq eps) a b)\n\neqlv :: (ApproxEq [a], G.Vector v a) => Bounds [a] -> v a -> v a -> Property\neqlv eps a b = eql eps (G.toList a) (G.toList b)\n\neqll :: (ApproxEq l, ApproxEq a, Show c, Show d, Eq d, Bounds l ~ Bounds a) =>\n (l -> d) -> (l -> [a]) -> (Int -> c) -> Bounds l -> l -> l -> Property\neqll dim toList coord eps a b = counterexample fancy $ eq eps a b\n where\n fancy\n | la /= lb = \"size mismatch: \" ++ show la ++ \" /= \" ++ show lb\n | length summary < length full = summary\n | otherwise = full\n summary = concat . intersperse \", \" . catMaybes $\n zipWith3 whee (map coord [(0::Int)..]) xs ys\n full | '\\n' `elem` sa = sa ++ \" /=~\\n\" ++ sb\n | otherwise = sa ++ \" /=~\" ++ sb\n (sa, sb) = (show a, show b)\n (xs, ys) = (toList a, toList b)\n (la, lb) = (dim a, dim b)\n whee i x y | eq eps x y = Nothing\n | otherwise = Just $ show i ++ \": \" ++ show x ++ \" /=~ \" ++ show y\n", "meta": {"hexsha": "ba8ee0b32d0a91713f546829b3ffa8aaa171b2df", "size": 3426, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Tests/ApproxEq.hs", "max_stars_repo_name": "harendra-kumar/statistics", "max_stars_repo_head_hexsha": "d3c4743c28fdd83d578039867f1a046596f77140", "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": "tests/Tests/ApproxEq.hs", "max_issues_repo_name": "harendra-kumar/statistics", "max_issues_repo_head_hexsha": "d3c4743c28fdd83d578039867f1a046596f77140", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Tests/ApproxEq.hs", "max_forks_repo_name": "harendra-kumar/statistics", "max_forks_repo_head_hexsha": "d3c4743c28fdd83d578039867f1a046596f77140", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8648648649, "max_line_length": 82, "alphanum_fraction": 0.5461179218, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.580288760984371}} {"text": "module Brain\n(\n NetworkWithSamples (..)\n, constructNeuralNetwork\n, trainN\n, activate\n)\n\nwhere\n\n--------------------------------------------------------------------------------\n\nimport AI.HNN.FF.Network ( Network\n , Samples\n , createNetwork\n , trainNTimes\n , tanh\n , tanh'\n , output )\nimport Numeric.LinearAlgebra.Data ( Vector )\nimport Debug.Trace\n\n\n--------------------------------------------------------------------------------\n\ntype Network' = Network Double\ntype Samples' = Samples Double\n\ndata NetworkWithSamples = NetworkWithSamples { network :: Network'\n , samples :: Samples' }\n deriving (Show)\n\n\nconstructNeuralNetwork :: Int -> [Int] -> Int -> Samples' -> IO (NetworkWithSamples)\nconstructNeuralNetwork i h o s = do\n net <- createNetwork i h o\n return NetworkWithSamples { network = net, samples = s }\n\n\ntrainN :: NetworkWithSamples -> Int -> NetworkWithSamples\ntrainN nn n = nn { network = nn' }\n where nn' = trainNTimes n 0.05 tanh tanh' (network nn) (samples nn)\n\n\nactivate :: NetworkWithSamples -> Vector Double -> Vector Double\nactivate n s = output (network n) tanh s\n", "meta": {"hexsha": "868283894b2a0327760175c556db9b3178a4ca7f", "size": 1369, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Brain.hs", "max_stars_repo_name": "robmcl4/A-Neural", "max_stars_repo_head_hexsha": "7eb283de2d5602787c7919e15da4f0d77af08844", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-05-13T06:21:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-06T05:07:55.000Z", "max_issues_repo_path": "src/Brain.hs", "max_issues_repo_name": "robmcl4/A-Neural", "max_issues_repo_head_hexsha": "7eb283de2d5602787c7919e15da4f0d77af08844", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Brain.hs", "max_forks_repo_name": "robmcl4/A-Neural", "max_forks_repo_head_hexsha": "7eb283de2d5602787c7919e15da4f0d77af08844", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-31T14:56:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T14:56:23.000Z", "avg_line_length": 29.1276595745, "max_line_length": 84, "alphanum_fraction": 0.4828341855, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5802737645995031}} {"text": "{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n-- | Minimil linear algebra lib.\nmodule Math.Regression.Simple.LinAlg (\n -- * Operations\n Add (..),\n Eye (..),\n Mult (..),\n Det (..),\n Inv (..),\n -- * Zeros\n zerosLin,\n zerosQuad,\n optimaQuad,\n -- * Two dimensions\n V2 (..),\n M22 (..),\n SM22 (..),\n -- * Three dimensions\n V3 (..),\n M33 (..),\n SM33 (..),\n) where\n\nimport Control.DeepSeq (NFData (..))\nimport Data.Complex (Complex (..))\n\n-------------------------------------------------------------------------------\n-- Classes\n-------------------------------------------------------------------------------\n\n-- | Addition\nclass Add a where\n zero :: a\n add :: a -> a -> a\n\n-- | Identity\nclass Eye a where\n eye :: a\n\n-- | Multiplication of different things.\nclass Eye a => Mult a b c | a b -> c where\n mult :: a -> b -> c\n\n-- | Determinant\nclass Eye a => Det a where\n det :: a -> Double\n\n-- | Inverse\nclass Det a => Inv a where\n inv :: a -> a\n\ninfixl 6 `add`\ninfixl 7 `mult`\n\ninstance Eye Double where\n eye = 1\n\ninstance Add Double where\n zero = 0\n add = (+)\n\ninstance Mult Double Double Double where\n mult = (*)\n\ninstance Det Double where\n det = id\n\ninstance Inv Double where\n inv = recip\n\n-------------------------------------------------------------------------------\n-- Zeros\n-------------------------------------------------------------------------------\n\n-- | Solve linear equation.\n--\n-- >>> zerosLin (V2 1 2)\n-- -2.0\n--\nzerosLin :: V2 -> Double\nzerosLin (V2 a b) = negate (b / a)\n\n-- | Solve quadratic equation.\n--\n-- >>> zerosQuad (V3 2 0 (-1))\n-- Right (-0.7071067811865476,0.7071067811865476)\n--\n-- >>> zerosQuad (V3 2 0 1)\n-- Left ((-0.0) :+ (-0.7071067811865476),(-0.0) :+ 0.7071067811865476)\n--\n-- Double root is not treated separately:\n--\n-- >>> zerosQuad (V3 1 0 0)\n-- Right (-0.0,0.0)\n--\n-- >>> zerosQuad (V3 1 (-2) 1)\n-- Right (1.0,1.0)\n--\nzerosQuad :: V3 -> Either (Complex Double, Complex Double) (Double, Double)\nzerosQuad (V3 a b c)\n | delta < 0 = Left ((-b/da) :+ (-sqrtNDelta/da), (-b/da) :+ (sqrtNDelta/da))\n | otherwise = Right ((- b - sqrtDelta) / da, (-b + sqrtDelta) / da)\n where\n delta = b*b - 4 * a * c\n sqrtDelta = sqrt delta\n sqrtNDelta = sqrt (- delta)\n da = 2 * a\n\n-- | Find an optima point.\n--\n-- >>> optimaQuad (V3 1 (-2) 0)\n-- 1.0\n--\n-- compare to\n--\n-- >>> zerosQuad (V3 1 (-2) 0)\n-- Right (0.0,2.0)\n--\noptimaQuad :: V3 -> Double\noptimaQuad (V3 a b _) = zerosLin (V2 (2 * a) b)\n\n-------------------------------------------------------------------------------\n-- 2 dimensions\n-------------------------------------------------------------------------------\n\n-- | 2d vector. Strict pair of 'Double's.\n--\n-- Also used to represent linear polynomial: @V2 a b@ \\(= a x + b\\).\n--\ndata V2 = V2 !Double !Double\n deriving (Eq, Show)\n\ninstance NFData V2 where\n rnf V2 {} = ()\n\ninstance Add V2 where\n zero = V2 0 0\n add (V2 x y) (V2 x' y') = V2 (x + x') (y + y')\n {-# INLINE zero #-}\n {-# INLINE add #-}\n\ninstance Mult Double V2 V2 where\n mult k (V2 x y) = V2 (k * x) (k * y)\n {-# INLINE mult #-}\n\n-- | 2\u00d72 matrix.\ndata M22 = M22 !Double !Double !Double !Double\n deriving (Eq, Show)\n\ninstance NFData M22 where\n rnf M22 {} = ()\n\ninstance Add M22 where\n zero = M22 0 0 0 0\n add (M22 a b c d) (M22 a' b' c' d') = M22 (a + a') (b + b') (c + c') (d + d')\n {-# INLINE zero #-}\n {-# INLINE add #-}\n\ninstance Eye M22 where\n eye = M22 1 0 0 1\n {-# INLINE eye #-}\n\ninstance Det M22 where det = det2\ninstance Inv M22 where inv = inv2\n\ninstance Mult Double M22 M22 where\n mult k (M22 a b c d) = M22 (k * a) (k * b) (k * c) (k * d)\n {-# INLINE mult #-}\n\ninstance Mult M22 V2 V2 where\n mult (M22 a b c d) (V2 u v) = V2 (a * u + b * v) (c * u + d * v)\n {-# INLINE mult #-}\n\n-- | >>> M22 1 2 3 4 `mult` eye @M22\n-- M22 1.0 2.0 3.0 4.0\ninstance Mult M22 M22 M22 where\n mult (M22 a b c d) (M22 x y z w) = M22\n (a * x + b * z) (a * y + b * w)\n (c * x + d * z) (c * y + d * w)\n {-# INLINE mult #-}\n\ndet2 :: M22 -> Double\ndet2 (M22 a b c d) = a * d - b * c\n{-# INLINE det2 #-}\n\ninv2 :: M22 -> M22\ninv2 m@(M22 a b c d) = M22\n ( d / detm) (- b / detm)\n (- c / detm) ( a / detm)\n where\n detm = det2 m\n{-# INLINE inv2 #-}\n\n-- | Symmetric 2x2 matrix.\ndata SM22 = SM22 !Double !Double !Double\n deriving (Eq, Show)\n\ninstance NFData SM22 where\n rnf SM22 {} = ()\n\ninstance Add SM22 where\n zero = SM22 0 0 0\n add (SM22 a b d) (SM22 a' b' d') = SM22 (a + a') (b + b') (d + d')\n {-# INLINE zero #-}\n {-# INLINE add #-}\n\ninstance Eye SM22 where\n eye = SM22 1 0 1\n {-# INLINE eye #-}\n\ninstance Det SM22 where det = detS2\ninstance Inv SM22 where inv = invS2\n\ninstance Mult Double SM22 SM22 where\n mult k (SM22 a b d) = SM22 (k * a) (k * b) (k * d)\n {-# INLINE mult #-}\n\ninstance Mult SM22 V2 V2 where\n mult (SM22 a b d) (V2 u v) = V2 (a * u + b * v) (b * u + d * v)\n {-# INLINE mult #-}\n\ndetS2 :: SM22 -> Double\ndetS2 (SM22 a b d) = a * d - b * b\n{-# INLINE detS2 #-}\n\ninvS2 :: SM22 -> SM22\ninvS2 m@(SM22 a b d) = SM22\n ( d / detm)\n (- b / detm) ( a / detm)\n where\n detm = detS2 m\n{-# INLINE invS2 #-}\n\n-------------------------------------------------------------------------------\n-- 3 dimensions\n-------------------------------------------------------------------------------\n\n-- | 3d vector. Strict triple of 'Double's.\n--\n-- Also used to represent quadratic polynomial: @V3 a b c@ \\(= a x^2 + b x + c\\).\ndata V3 = V3 !Double !Double !Double\n deriving (Eq, Show)\n\ninstance NFData V3 where\n rnf V3 {} = ()\n\ninstance Add V3 where\n zero = V3 0 0 0\n add (V3 x y z) (V3 x' y' z') = V3 (x + x') (y + y') (z + z')\n {-# INLINE zero #-}\n {-# INLINE add #-}\n\ninstance Mult Double V3 V3 where\n mult k (V3 x y z) = V3 (k * x) (k * y) (k * z)\n {-# INLINE mult #-}\n\n-- | 3\u00d73 matrix.\ndata M33 = M33\n !Double !Double !Double\n !Double !Double !Double\n !Double !Double !Double\n deriving (Eq, Show)\n\ninstance NFData M33 where\n rnf M33 {} = ()\n\ninstance Add M33 where\n zero = M33 0 0 0 0 0 0 0 0 0\n\n add (M33 a b c d e f g h i) (M33 a' b' c' d' e' f' g' h' i') = M33\n (a + a') (b + b') (c + c')\n (d + d') (e + e') (f + f')\n (g + g') (h + h') (i + i')\n {-# INLINE zero #-}\n {-# INLINE add #-}\n\ninstance Eye M33 where\n eye = M33 1 0 0\n 0 1 0\n 0 0 1\n {-# INLINE eye #-}\n\ninstance Det M33 where det = det3\ninstance Inv M33 where inv = inv3\n\ninstance Mult Double M33 M33 where\n mult k (M33 a b c d e f g h i) = M33\n (k * a) (k * b) (k * c)\n (k * d) (k * e) (k * f)\n (k * g) (k * h) (k * i)\n {-# INLINE mult #-}\n\ninstance Mult M33 V3 V3 where\n mult (M33 a b c\n d e f\n g h i) (V3 u v w) = V3\n (a * u + b * v + c * w)\n (d * u + e * v + f * w)\n (g * u + h * v + i * w)\n {-# INLINE mult #-}\n\n-- TODO: instance Mult M33 M33 M33 where\n\ndet3 :: M33 -> Double\ndet3 (M33 a b c\n d e f\n g h i)\n = a * (e*i-f*h) - d * (b*i-c*h) + g * (b*f-c*e)\n{-# INLINE det3 #-}\n\ninv3 :: M33 -> M33\ninv3 m@(M33 a b c\n d e f\n g h i)\n = M33 a' b' c'\n d' e' f'\n g' h' i'\n where\n a' = cofactor e f h i / detm\n b' = cofactor c b i h / detm\n c' = cofactor b c e f / detm\n d' = cofactor f d i g / detm\n e' = cofactor a c g i / detm\n f' = cofactor c a f d / detm\n g' = cofactor d e g h / detm\n h' = cofactor b a h g / detm\n i' = cofactor a b d e / detm\n cofactor q r s t = det2 (M22 q r s t)\n detm = det3 m\n{-# INLINE inv3 #-}\n\n-- | Symmetric 3\u00d73 matrix.\ndata SM33 = SM33\n !Double\n !Double !Double\n !Double !Double !Double\n deriving (Eq, Show)\n\ninstance NFData SM33 where\n rnf SM33 {} = ()\n\ninstance Add SM33 where\n zero = SM33 0 0 0 0 0 0\n\n add (SM33 a d e g h i) (SM33 a' d' e' g' h' i') = SM33\n (a + a')\n (d + d') (e + e')\n (g + g') (h + h') (i + i')\n {-# INLINE zero #-}\n {-# INLINE add #-}\n\ninstance Eye SM33 where\n eye = SM33 1\n 0 1\n 0 0 1\n {-# INLINE eye #-}\n\ninstance Det SM33 where det = detS3\ninstance Inv SM33 where inv = invS3\n\ninstance Mult Double SM33 SM33 where\n mult k (SM33 a d e g h i) = SM33\n (k * a)\n (k * d) (k * e)\n (k * g) (k * h) (k * i)\n {-# INLINE mult #-}\n\ninstance Mult SM33 V3 V3 where\n mult (SM33 a\n d e\n g h i) (V3 u v w) = V3\n (a * u + d * v + g * w)\n (d * u + e * v + h * w)\n (g * u + h * v + i * w)\n {-# INLINE mult #-}\n\ndetS3 :: SM33 -> Double\ndetS3 (SM33 a\n d e\n g h i)\n = a * (e*i-h*h) - d * (d*i-g*h) + g * (d*h-g*e)\n{-# INLINE detS3 #-}\n\ninvS3 :: SM33 -> SM33\ninvS3 m@(SM33 a\n d e\n g h i)\n = SM33 a'\n d' e'\n g' h' i'\n where\n a' = cofactor e h h i / detm\n d' = cofactor h d i g / detm\n e' = cofactor a g g i / detm\n g' = cofactor d e g h / detm\n h' = cofactor d a h g / detm\n i' = cofactor a d d e / detm\n cofactor q r s t = det2 (M22 q r s t)\n detm = detS3 m\n{-# INLINE invS3 #-}\n", "meta": {"hexsha": "72fc9b06c312b8777ec9225874cb24c3561149dd", "size": 9305, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Regression/Simple/LinAlg.hs", "max_stars_repo_name": "phadej/regression-simple", "max_stars_repo_head_hexsha": "fe01455f0904fa2c244cff8ed925c20547ce9520", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-11-27T04:32:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T22:33:23.000Z", "max_issues_repo_path": "src/Math/Regression/Simple/LinAlg.hs", "max_issues_repo_name": "phadej/regression-simple", "max_issues_repo_head_hexsha": "fe01455f0904fa2c244cff8ed925c20547ce9520", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/Regression/Simple/LinAlg.hs", "max_forks_repo_name": "phadej/regression-simple", "max_forks_repo_head_hexsha": "fe01455f0904fa2c244cff8ed925c20547ce9520", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0893300248, "max_line_length": 82, "alphanum_fraction": 0.4666308436, "num_tokens": 3293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5801707418877062}} {"text": "module NeuralNetwork\n () where\n\nimport Control.Monad (mapM)\nimport qualified Data.Sequence as Seq\nimport Debug.Trace\nimport Numeric.LinearAlgebra ((<>), (><))\nimport qualified Numeric.LinearAlgebra as LA\n\ntype MatrixNum = LA.Matrix Double\ntype Cache = ((MatrixNum, MatrixNum, MatrixNum), MatrixNum)\n\ndata Parameter = Parameter\n { weightsParam :: MatrixNum\n , biasesParam :: MatrixNum\n }\n\n-- Utils\nemptyx :: MatrixNum\nemptyx = (0><0) []\n\nemptyCache :: Cache\nemptyCache = ((emptyx, emptyx, emptyx), emptyx)\n\n-- Activation functions\nrelu :: MatrixNum -> MatrixNum\nrelu = LA.cmap (max 0)\n\nsigmoid :: MatrixNum -> MatrixNum\nsigmoid = LA.cmap (\\x -> (1 / (1 + exp (-1 * x))))\n\nrelu' :: MatrixNum -> MatrixNum\nrelu' = LA.cmap f\n where\n f x | x < 0 = 0\n | otherwise = 1\n\nsigmoid' :: MatrixNum -> MatrixNum\nsigmoid' xw = (sigmoid xw) * (1 - sigmoid xw)\n\n-- | Initialize parameters. Randomize weights and zeroes biases\ninitParams :: [Int] -> IO [Parameter]\ninitParams layerDims =\n (fmap . fmap) (\\(bx, wx) -> Parameter wx bx) ((zip biases) <$> weights)\n where\n weights = mapM genParams layerDims'\n layerDims' = (zip layerDims (tail layerDims))\n genParams (prevDim, currentDim) = LA.randn currentDim prevDim\n biases =\n fmap\n (\\(_, currentDim) -> (currentDim><1) (replicate currentDim 0))\n layerDims'\n\n-- | Propagate forward to next layer. Calulates next a\nlinearForward axPrev wx bx activationFun =\n let zx = linearForward' axPrev wx bx\n ax = activationFun zx\n cache = ((axPrev, wx, bx), zx)\n linearForward' axPrev wx bx = (wx <> axPrev) + bx :: MatrixNum\n in (ax, cache)\n\n-- | Complete forward propagation. Calculates final ax\npropagateForward :: MatrixNum\n -> [Parameter]\n -> (MatrixNum, [Cache])\npropagateForward xx params =\n (outputAx, hiddenCache ++ [outputCache])\n where\n params' = take ((length params) - 1) params\n f (aPrev, _) (Parameter wx bx) = linearForward aPrev wx bx relu\n hidden = scanl f (xx, emptyCache) params'\n hiddenCache = drop 1 (fmap snd hidden)\n (lastHiddenAx, _) = last hidden\n Parameter wxLast bxLast = last params\n (outputAx, outputCache) = linearForward lastHiddenAx wxLast bxLast sigmoid\n\n\n-- | Propagate backward to previous layer\nlinearBackward :: MatrixNum -> Cache -> (MatrixNum -> MatrixNum)\n -> (MatrixNum, MatrixNum, MatrixNum)\nlinearBackward dax ((axPrev, wx, bx), zx) af' =\n (daxPrev, dwx, dbx)\n where\n dzx = dax * af' zx\n m = fromIntegral $ (snd . LA.size) axPrev\n dwx = (dzx <> (LA.tr axPrev)) / m\n sums = fmap sum (LA.toLists dzx)\n layerSize = (fst . LA.size) wx\n dbx = ((layerSize><1) sums) / m\n daxPrev = (LA.tr wx) <> dzx\n\n-- | Complete backpropagation. Computes gradients (dax, dwx, dbx)\n-- of each layer\npropagateBackward :: MatrixNum -> (LA.Vector Double) -> [Cache]\n -> [(MatrixNum, MatrixNum, MatrixNum)]\npropagateBackward axOut yx caches =\n let l = length caches\n yx' = LA.reshape 1 yx\n daxOut = - (yx' / axOut) - ((1 - yx') / (1 - axOut))\n gradOut = linearBackward daxOut (last caches) sigmoid'\n hiddenCaches = reverse $ take (length caches - 1) caches\n grads = scanl f gradOut hiddenCaches\n f (dax, _, _) cache = linearBackward dax cache relu'\n in reverse grads\n\n-- | Perform gradient descent. Computes new decreased gradients (dax, dwx, dbx)\nupdateParameters :: [Parameter]\n -> [(MatrixNum, MatrixNum, MatrixNum)]\n -> Double\n -> [Parameter]\nupdateParameters params grads eta = fmap fun (zip params grads)\n where fun ((Parameter wx bx), (_, dwx, dbx)) =\n Parameter\n (wx - (LA.scalar eta) * dwx)\n (bx - (LA.scalar eta) * dbx)\n\ntrain :: MatrixNum\n -> LA.Vector Double\n -> [Int]\n -> Double\n -> Int\n -> IO [Parameter]\ntrain xx yx layerDims eta iterations =\n do\n params <- initParams layerDims\n return $ train' params iterations\n where\n train' params 0 = params\n train' params times =\n let (ax, caches) = propagateForward xx params\n grads = propagateBackward ax yx caches\n newParams = updateParameters params grads eta\n in train' newParams (times - 1)\n", "meta": {"hexsha": "c1935d7d700c953a4bc893ab96dbcd07d318591d", "size": 4341, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NeuralNetwork.hs", "max_stars_repo_name": "abs-zero/haskellml", "max_stars_repo_head_hexsha": "9a8e40a4c06d4a9be8d439400e2722b8b2e3bf48", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-28T01:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-29T02:38:10.000Z", "max_issues_repo_path": "src/NeuralNetwork.hs", "max_issues_repo_name": "abs-zero/haskellml", "max_issues_repo_head_hexsha": "9a8e40a4c06d4a9be8d439400e2722b8b2e3bf48", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NeuralNetwork.hs", "max_forks_repo_name": "abs-zero/haskellml", "max_forks_repo_head_hexsha": "9a8e40a4c06d4a9be8d439400e2722b8b2e3bf48", "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.3955223881, "max_line_length": 80, "alphanum_fraction": 0.6219765031, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5798974713767494}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad\nimport Data.Bifunctor\nimport Data.Maybe\nimport Hedgehog\nimport Lens.Micro\nimport Nudge\nimport Numeric.Backprop\nimport Numeric.LinearAlgebra.Static (L, R)\nimport System.Exit\nimport System.IO\nimport qualified Numeric.LinearAlgebra.Static.Backprop as B\n\nprop_vec2 :: Property\nprop_vec2 = nudgeProp2 B.vec2\n\nprop_vec3 :: Property\nprop_vec3 = nudgeProp @(Double, Double, Double)\n (\\t -> B.vec3 (t ^^. _1) (t ^^. _2) (t ^^. _3))\n\nprop_vec4 :: Property\nprop_vec4 = nudgeProp2 @(Double, Double) @(Double, Double)\n (\\x y -> B.vec4 (x ^^. _1) (x ^^. _2) (y ^^. _1) (y ^^. _2))\n\nprop_snoc :: Property\nprop_snoc = nudgeProp2 @(R 3) (B.&)\n\nprop_append :: Property\nprop_append = nudgeProp2 @(R 3) @(R 2) (B.#)\n\nprop_split1 :: Property\nprop_split1 = nudgeProp @(R 3) (fst . B.split @2)\n\nprop_split2 :: Property\nprop_split2 = nudgeProp @(R 3) (snd . B.split @2)\n\nprop_headTail1 :: Property\nprop_headTail1 = nudgeProp @(R 3) (fst . B.headTail)\n\nprop_headTail2 :: Property\nprop_headTail2 = nudgeProp @(R 3) (snd . B.headTail)\n\nprop_vector :: Property\nprop_vector = nudgeProp (B.vector @3 . sequenceVar)\n\nprop_linspace :: Property\nprop_linspace = nudgeProp2 (B.linspace @3)\n\nprop_row :: Property\nprop_row = nudgeProp @(R 3) B.row\n\nprop_col :: Property\nprop_col = nudgeProp @(R 3) B.col\n\nprop_horzcat :: Property\nprop_horzcat = nudgeProp2 @(L 3 2) @(L 3 1) (B.|||)\n\nprop_vertcat :: Property\nprop_vertcat = nudgeProp2 @(L 2 3) @(L 1 3) (B.===)\n\nprop_splitRows1 :: Property\nprop_splitRows1 = nudgeProp @(L 2 3) (fst . B.splitRows @1)\n\nprop_splitRows2 :: Property\nprop_splitRows2 = nudgeProp @(L 2 3) (snd . B.splitRows @1)\n\nprop_splitCols1 :: Property\nprop_splitCols1 = nudgeProp @(L 3 2) (fst . B.splitCols @1)\n\nprop_splitCols2 :: Property\nprop_splitCols2 = nudgeProp @(L 3 2) (snd . B.splitCols @1)\n\nprop_unrow :: Property\nprop_unrow = nudgeProp @(L 1 3) B.unrow\n\nprop_uncol :: Property\nprop_uncol = nudgeProp @(L 3 1) B.uncol\n\nprop_tr :: Property\nprop_tr = nudgeProp @(L 3 2) B.tr\n\nprop_diag :: Property\nprop_diag = nudgeProp @(R 3) B.diag\n\nprop_svd :: Property\nprop_svd = nudgeProp @(L 3 2) B.svd\n\nprop_svd_ :: Property\nprop_svd_ = nudgeProp @(L 3 2) ((\\(_,x,_) -> x) . B.svd_)\n\nprop_eigensystem1 :: Property\nprop_eigensystem1 = nudgeProp @(L 3 2) (fst . B.eigensystem . B.mTm)\n\nprop_eigensystem2 :: Property\nprop_eigensystem2 = nudgeProp @(L 3 2) (snd . B.eigensystem . B.mTm)\n\nprop_eigenvalues :: Property\nprop_eigenvalues = nudgeProp @(L 3 2) (B.eigenvalues . B.mTm)\n\nprop_chol :: Property\nprop_chol = nudgeProp @(L 3 2) (B.chol . B.mTm)\n\nprop_norm_0V :: Property\nprop_norm_0V = nudgeProp @(R 3) B.norm_0\n\nprop_norm_0M :: Property\nprop_norm_0M = nudgeProp @(L 3 2) B.norm_0\n\nprop_norm_1V :: Property\nprop_norm_1V = nudgeProp @(R 3) B.norm_1V\n\nprop_norm_1M :: Property\nprop_norm_1M = nudgeProp @(L 3 2) B.norm_1M\n\nprop_norm_2V :: Property\nprop_norm_2V = nudgeProp @(R 3) B.norm_2V\n\nprop_norm_2M :: Property\nprop_norm_2M = nudgeProp @(L 3 2) B.norm_2M\n\nprop_norm_InfV :: Property\nprop_norm_InfV = nudgeProp @(R 3) B.norm_InfV\n\nprop_norm_InfM :: Property\nprop_norm_InfM = nudgeProp @(L 3 2) B.norm_InfM\n\nprop_mean :: Property\nprop_mean = nudgeProp @(R 3) B.mean\n\nprop_meanCov1 :: Property\nprop_meanCov1 = nudgeProp @(L 3 2) (fst . B.meanCov)\n\nprop_meanCov2 :: Property\nprop_meanCov2 = nudgeProp @(L 3 2) (B.unSym . snd . B.meanCov)\n\nprop_meanL :: Property\nprop_meanL = nudgeProp @(L 3 2) B.meanL\n\nprop_cov :: Property\nprop_cov = nudgeProp @(L 3 2) (B.unSym . B.cov)\n\nprop_mul :: Property\nprop_mul = nudgeProp2 @(L 3 2) @(L 2 3) B.mul\n\nprop_app :: Property\nprop_app = nudgeProp2 @(L 3 2) @(R 2) B.app\n\nprop_dot :: Property\nprop_dot = nudgeProp2 @(R 3) @(R 3) B.dot\n\nprop_cross :: Property\nprop_cross = nudgeProp2 @(R 3) B.cross\n\n-- TODO: bug in diagR?\n-- prop_diagR :: Property\n-- prop_diagR = nudgeProp2 genDouble (genVec @3) (B.diagR @5 @4)\n\n-- TODO: Mappers\n-- , dvmap\n-- , dvmap'\n-- , dmmap\n-- , dmmap'\n\nprop_outer :: Property\nprop_outer = nudgeProp2 @(R 3) @(R 2) B.outer\n\n-- TODO: Zippers\n-- , zipWithVector\n-- , zipWithVector'\n\nprop_det :: Property\nprop_det = nudgeProp @(L 3 3) B.det\n\nprop_invlndet1 :: Property\nprop_invlndet1 = nudgeProp @(L 3 3) (fst . B.invlndet)\n\nprop_invlndet2 :: Property\nprop_invlndet2 = nudgeProp @(L 3 3) (fst . snd . B.invlndet)\n\nprop_invlndet3 :: Property\nprop_invlndet3 = nudgeProp @(L 3 3) (snd . snd . B.invlndet)\n\nprop_lndet :: Property\nprop_lndet = nudgeProp @(L 3 3) B.lndet\n\n-- TODO: more general invertible matrix\nprop_inv :: Property\nprop_inv = nudgeProp @(L 3 2) (B.inv . B.unSym . B.mTm)\n\nprop_toRows :: Property\nprop_toRows = nudgeProp @(L 3 2) (collectVar . B.toRows)\n\nprop_toColumns :: Property\nprop_toColumns = nudgeProp @(L 2 3) (collectVar . B.toColumns)\n\nprop_fromRows :: Property\nprop_fromRows = nudgeProp (B.fromRows @3 @2 . sequenceVar)\n\nprop_fromColumns :: Property\nprop_fromColumns = nudgeProp (B.fromColumns @2 @3 . sequenceVar)\n\nprop_konstV :: Property\nprop_konstV = nudgeProp (B.konst @_ @(B.R 3))\n\nprop_konstM :: Property\nprop_konstM = nudgeProp (B.konst @_ @(B.L 3 2))\n\nprop_sumElementsV :: Property\nprop_sumElementsV = nudgeProp @(R 3) B.sumElements\n\nprop_sumElementsM :: Property\nprop_sumElementsM = nudgeProp @(L 3 2) B.sumElements\n\nprop_extractV :: Property\nprop_extractV = nudgeProp (B.extractV @_ @(R 3))\n\nprop_extractM :: Property\nprop_extractM = nudgeProp (B.extractM @_ @(L 3 2))\n\nprop_createV :: Property\nprop_createV = nudgeProp (fromMaybe 0 . B.create @_ @(R 3))\n\nprop_createM :: Property\nprop_createM = nudgeProp (fromMaybe 0 . B.create @_ @(L 3 2))\n\nprop_takeDiag :: Property\nprop_takeDiag = nudgeProp @(L 3 3) B.takeDiag\n\nprop_sym :: Property\nprop_sym = nudgeProp @(L 3 3) (B.unSym . B.sym)\n\nprop_mTm :: Property\nprop_mTm = nudgeProp @(L 3 2) (B.unSym . B.mTm)\n\nprop_unSym :: Property\nprop_unSym = nudgeProp @(L 3 3) (B.unSym . B.sym)\n\ntryGroup :: (forall a. Num a => a) -> Group -> Group\ntryGroup n Group{..} =\n Group groupName\n ((map . second) (withDiscards n . withTests n)\n groupProperties\n )\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout LineBuffering\n hSetBuffering stderr LineBuffering\n\n results <- checkParallel (tryGroup 100 $$(discover))\n\n unless results exitFailure\n\n", "meta": {"hexsha": "64eadc2cbcdcfe6196291eae890cb4d32bf8c282", "size": 6545, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Spec.hs", "max_stars_repo_name": "mstksg/hmatrix-backprop", "max_stars_repo_head_hexsha": "91661e0f02012146aa7be323d05c27921fb16c72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-02-06T06:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T07:55:31.000Z", "max_issues_repo_path": "test/Spec.hs", "max_issues_repo_name": "mstksg/hmatrix-backprop", "max_issues_repo_head_hexsha": "91661e0f02012146aa7be323d05c27921fb16c72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-29T14:21:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-09T22:54:47.000Z", "max_forks_repo_path": "test/Spec.hs", "max_forks_repo_name": "mstksg/hmatrix-backprop", "max_forks_repo_head_hexsha": "91661e0f02012146aa7be323d05c27921fb16c72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-03T20:57:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T16:47:46.000Z", "avg_line_length": 25.2702702703, "max_line_length": 76, "alphanum_fraction": 0.6808250573, "num_tokens": 2262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5796759519425136}} {"text": "module Mbrot where\nimport Codec.Picture.Types\nimport Coloring\nimport Control.Arrow ((***))\nimport Data.Complex\nimport ImageOutput\n\n-- |Size parameters\nsize :: (Int,Int)\nsize = (1400,800)\n\n-- |Floating point size, calculated\nsizef :: (Float,Float)\nsizef = (fromIntegral *** fromIntegral) size\n\n-- |Maximum iterations\nmaxIter :: Int\nmaxIter = 1000\n\n-- |Color step for integer esacpe coloring\nmult :: Float\nmult = 255 / fromIntegral maxIter\n\n-- |Color step for continuously colored\nmultg :: Float\nmultg = 400 / fromIntegral maxIter\n\n-- |Function for rendering pixel in greyscale\ndrawGreyscale :: Bool -- ^Continuously colored\n -> Int\n -> Int\n -> Pixel8\ndrawGreyscale c x y\n |c = fromIntegral (round(float * mult))\n |otherwise = fromIntegral(int * round mult)\n where int = mbrot maxIter (((x1/x2)-0.5) :+ (y1/y2))\n float = mbrotContinuous maxIter (((x1/x2)-0.5) :+ (y1/y2))\n x1 = 2 * (fromIntegral x - x2)\n y1 = 2 * (fromIntegral y - y2)\n x2 = fst sizef /2\n y2 = snd sizef /2\n\n-- |Deprecated. Use 'drawColorZoom' instead\ndrawColor :: Int -> Int -> PixelRGB8\ndrawColor x y = colorToPixel $ color (fromIntegral (int*400)/1000)\n where int = mbrot maxIter ((x1/x2) :+ (y1/y2))\n x1 = 1.75 * (fromIntegral x - x2)\n y1 = fromIntegral y - y2\n x2 = fst sizef /2\n y2 = snd sizef /2\n\n-- |Function for rendering pixel in color, with zoom level and focus\ndrawColorZoom :: Float -- ^ Zoom level\n -> (Float,Float) -- ^ Focus point (x,y)\n -> Int\n -> Int\n -> PixelRGB8\ndrawColorZoom zoom (fx, fy) x y = colorToPixel $ color (float*multg)\n where float = mbrotContinuous maxIter (((x1/x2)+fx) :+ ((y1/y2)+fy))\n x1 = 1.75 * (fromIntegral x - x2) / zoom\n y1 = (fromIntegral y - y2) / zoom\n x2 = fst sizef /2\n y2 = snd sizef /2\n\n-- |Function for drawing color gradient. Tests for correct linear interpolation of color\ndrawTestGradient :: Int -> Int -> PixelRGB8\ndrawTestGradient x _ = colorToPixel $ color (fromIntegral x *400/1000)\n\n-- |Function for integer escape time of mbrot set of Re(x) + Im(y)\nmbrot :: RealFloat x\n => Int -- ^ Maximum iterations\n -> Complex x -- ^ Re(x) + Im(y)\n -> Int\nmbrot n = mbrot' maxIter (0 :+ 0)\n where\n mbrot' :: RealFloat x => Int -> Complex x -> Complex x -> Int\n mbrot' n a c\n |magnitude newIter < 65535 && n > 0 = mbrot' (n-1) newIter c\n |otherwise = maxIter - n\n where\n newIter = a*a + c\n\n-- |Function for real floating escape time of mbrot set of Re(x) + Im(y)\nmbrotContinuous :: RealFloat x\n => Int -- ^ Maximum iterations\n -> Complex x -- ^ Re(x) + Im(y)\n -> x\nmbrotContinuous n = mbrot' maxIter (0 :+ 0)\n where\n mbrot' :: RealFloat x => Int -> Complex x -> Complex x -> x\n mbrot' n a c\n |magnitude newIter < 65535 && n > 0 = mbrot' (n-1) newIter c\n |otherwise = normalized\n where\n newIter = a*a + c\n normalized = if n > 0\n then\n fromIntegral(maxIter - n +1) - logBase 2 ( logBase 2 (magnitude newIter ^ 2) / 2 )\n --fromIntegral (maxIter - n +1) - (log (log (magnitude newIter)))/ log (2.0)\n else fromIntegral maxIter\n", "meta": {"hexsha": "273950b5143624c4d508d4b02d97eedb823b3842", "size": 3614, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Mbrot.hs", "max_stars_repo_name": "veniversum/fractal-haskell", "max_stars_repo_head_hexsha": "64fba58f15909c578a8a410ff1c5cea80363f0e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-11-25T00:53:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T04:20:07.000Z", "max_issues_repo_path": "src/Mbrot.hs", "max_issues_repo_name": "veniversum/fractal-haskell", "max_issues_repo_head_hexsha": "64fba58f15909c578a8a410ff1c5cea80363f0e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-11-25T00:47:12.000Z", "max_issues_repo_issues_event_max_datetime": "2015-12-14T04:02:07.000Z", "max_forks_repo_path": "src/Mbrot.hs", "max_forks_repo_name": "veniversum/fractal-haskell", "max_forks_repo_head_hexsha": "64fba58f15909c578a8a410ff1c5cea80363f0e5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-12-14T03:26:12.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-28T02:18:34.000Z", "avg_line_length": 35.7821782178, "max_line_length": 118, "alphanum_fraction": 0.5387382402, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5793046215173253}} {"text": "module MachineLearning.Classification.BinaryTest\n(\n tests\n , testOptPath\n)\n\nwhere\n\nimport Test.Framework (testGroup)\nimport Test.Framework.Providers.HUnit\nimport Test.HUnit\nimport Test.HUnit.Approx\nimport Test.HUnit.Plus\n\nimport MachineLearning.Types\nimport qualified Data.Vector as V\nimport qualified Numeric.LinearAlgebra as LA\n\nimport MachineLearning.DataSets (dataset2)\n\nimport qualified MachineLearning as ML\nimport MachineLearning.Classification.Binary\n\n(x, y) = ML.splitToXY dataset2\n\n\nprocessX muSigma x = ML.addBiasDimension $ ML.featureNormalization muSigma $ ML.mapFeatures 6 x\n\nmuSigma = ML.meanStddev (ML.mapFeatures 6 x)\nx1 = processX muSigma x\nzeroTheta = LA.konst 0 (LA.cols x1)\n\nxPredict = LA.matrix 2 [ -0.5, 0.5\n , 0.2, -0.2\n , 1, 1\n , 1, 0\n , 0, 0\n , 0, 1]\nxPredict1 = processX muSigma xPredict\nyExpected = LA.vector [1, 1, 0, 0, 1, 0]\n\neps = 0.0001\n\n\n-- Binary\n\n(thetaCGFR, optPathCGFR) = learn (ConjugateGradientFR 0.1 0.1) eps 50 (L2 0.5) x1 y zeroTheta\n(thetaCGPR, optPathCGPR) = learn (ConjugateGradientPR 0.1 0.1) eps 50 (L2 0.5) x1 y zeroTheta\n(thetaBFGS, optPathBFGS) = learn (BFGS2 0.1 0.1) eps 50 (L2 0.5) x1 y zeroTheta\n\n\nisInDescendingOrder :: V.Vector Double -> Bool\nisInDescendingOrder lst = V.and . snd . V.unzip $ V.scanl (\\(prev, _) current -> (current, prev-current > (-0.001))) (1/0, True) lst\n\ntestOptPath optPath = do\n let js = V.convert $ (LA.toColumns optPath) !! 1\n assertBool (\"non-increasing errors: \" ++ show js) $ isInDescendingOrder js\n\ntestAccuracyBinary theta eps = do\n let yPredicted = predict x1 theta\n accuracy = calcAccuracy y yPredicted\n assertApproxEqual \"\" eps 1 accuracy\n\ntests = [\n testGroup \"learn\" [\n testCase \"Conjugate Gradient FR\" $ assertVector \"\" 0.01 yExpected (predict xPredict1 thetaCGFR)\n , testCase \"Conjugate Gradient PR\" $ assertVector \"\" 0.01 yExpected (predict xPredict1 thetaCGPR)\n , testCase \"BFGS\" $ assertVector \"\" 0.01 yExpected (predict xPredict1 thetaBFGS)\n ]\n , testGroup \"optPath\" [\n testCase \"Conjugate Gradient FR\" $ testOptPath optPathCGFR\n , testCase \"Conjugate Gradient PR\" $ testOptPath optPathCGPR\n , testCase \"BFGS\" $ testOptPath optPathBFGS\n ]\n , testGroup \"accuracy\" [\n testCase \"Conjugate Gradient FR\" $ testAccuracyBinary thetaCGFR 0.2\n , testCase \"Conjugate Gradient PR\" $ testAccuracyBinary thetaCGPR 0.2\n , testCase \"BFGS\" $ testAccuracyBinary thetaBFGS 0.2\n ]\n ]\n", "meta": {"hexsha": "3368c94f215c0bfcccb3722620f894ac2fa32fd7", "size": 2559, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/MachineLearning/Classification/BinaryTest.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "test/MachineLearning/Classification/BinaryTest.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "test/MachineLearning/Classification/BinaryTest.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 31.5925925926, "max_line_length": 132, "alphanum_fraction": 0.6842516608, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382004, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5793046179748538}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE RecordWildCards #-}\n\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\nmodule Internal.CG(\n cgSolve, cgSolve',\n CGState(..), R, V\n) where\n\nimport Control.Arrow ((***))\nimport Internal.Algorithms (NormType (..), linearSolve, linearSolveLS, pnorm,\n relativeError)\nimport Internal.Container\nimport Internal.Element\nimport Internal.IO\nimport Internal.Matrix\nimport Internal.Numeric\nimport Internal.Sparse\nimport Internal.Vector\nimport Numeric.Vector ()\n\n{-\nimport Util.Misc(debug, debugMat)\n\n(//) :: Show a => a -> String -> a\ninfix 0 // -- , ///\na // b = debug b id a\n\n(///) :: V -> String -> V\ninfix 0 ///\nv /// b = debugMat b 2 asRow v\n-}\n\ntype V = Vector R\n\ndata CGState = CGState\n { cgp :: Vector R -- ^ conjugate gradient\n , cgr :: Vector R -- ^ residual\n , cgr2 :: R -- ^ squared norm of residual\n , cgx :: Vector R -- ^ current solution\n , cgdx :: R -- ^ normalized size of correction\n }\n\ncg :: Bool -> (V -> V) -> (V -> V) -> CGState -> CGState\ncg sym at a (CGState p r r2 x _) = CGState p' r' r'2 x' rdx\n where\n ap1 = a p\n ap | sym = ap1\n | otherwise = at ap1\n pap | sym = p <.> ap1\n | otherwise = norm2 ap1 ** 2\n alpha = r2 / pap\n dx = scale alpha p\n x' = x + dx\n r' = r - scale alpha ap\n r'2 = r' <.> r'\n beta = r'2 / r2\n p' = r' + scale beta p\n\n rdx = norm2 dx / max 1 (norm2 x)\n\nconjugrad\n :: Bool -> GMatrix -> V -> V -> R -> R -> [CGState]\nconjugrad sym a b = solveG sym (tr a !#>) (a !#>) (cg sym) b\n\nsolveG\n :: Bool\n -> (V -> V) -> (V -> V)\n -> ((V -> V) -> (V -> V) -> CGState -> CGState)\n -> V\n -> V\n -> R -> R\n -> [CGState]\nsolveG sym mat ma meth rawb x0' \u03f5b \u03f5x\n = takeUntil ok . iterate (meth mat ma) $ CGState p0 r0 r20 x0 1\n where\n a = if sym then ma else mat . ma\n b = if sym then rawb else mat rawb\n x0 = if x0' == 0 then konst 0 (dim b) else x0'\n r0 = b - a x0\n r20 = r0 <.> r0\n p0 = r0\n nb2 = b <.> b\n ok CGState {..}\n = cgr2 Bool) -> [a] -> [a]\ntakeUntil q xs = a++ take 1 b\n where\n (a,b) = break q xs\n\n-- | Solve a sparse linear system using the conjugate gradient method with default parameters.\ncgSolve\n :: Bool -- ^ is symmetric\n -> GMatrix -- ^ coefficient matrix\n -> Vector R -- ^ right-hand side\n -> Vector R -- ^ solution\ncgSolve sym a b = cgx $ last $ cgSolve' sym 1E-4 1E-3 n a b 0\n where\n n = max 10 (round $ sqrt (fromIntegral (dim b) :: Float))\n\n-- | Solve a sparse linear system using the conjugate gradient method with default parameters.\ncgSolve'\n :: Bool -- ^ symmetric\n -> R -- ^ relative tolerance for the residual (e.g. 1E-4)\n -> R -- ^ relative tolerance for \u03b4x (e.g. 1E-3)\n -> Int -- ^ maximum number of iterations\n -> GMatrix -- ^ coefficient matrix\n -> Vector R -- ^ initial solution\n -> Vector R -- ^ right-hand side\n -> [CGState] -- ^ solution\ncgSolve' sym er es n a b x = take n $ conjugrad sym a b x er es\n\n\n--------------------------------------------------------------------------------\n\ninstance Testable GMatrix\n where\n checkT _ = (ok,info)\n where\n sma = convo2 20 3\n x1 = vect [1..20]\n x2 = vect [1..40]\n sm = mkSparse sma\n dm = toDense sma\n\n s1 = sm !#> x1\n d1 = dm #> x1\n\n s2 = tr sm !#> x2\n d2 = tr dm #> x2\n\n sdia = mkDiagR 40 20 (vect [1..10])\n s3 = sdia !#> x1\n s4 = tr sdia !#> x2\n ddia = diagRect 0 (vect [1..10]) 40 20\n d3 = ddia #> x1\n d4 = tr ddia #> x2\n\n v = testb 40\n s5 = cgSolve False sm v\n d5 = denseSolve dm v\n\n symassoc = [((0,0),1.0),((1,1),2.0),((0,1),0.5),((1,0),0.5)]\n b = vect [3,4]\n d6 = flatten $ linearSolve (toDense symassoc) (asColumn b)\n s6 = cgSolve True (mkSparse symassoc) b\n\n info = do\n print sm\n disp (toDense sma)\n print s1; print d1\n print s2; print d2\n print s3; print d3\n print s4; print d4\n print s5; print d5\n print $ relativeError (pnorm Infinity) s5 d5\n print s6; print d6\n print $ relativeError (pnorm Infinity) s6 d6\n\n ok = s1==d1\n && s2==d2\n && s3==d3\n && s4==d4\n && relativeError (pnorm Infinity) s5 d5 < 1E-10\n && relativeError (pnorm Infinity) s6 d6 < 1E-10\n\n disp = putStr . dispf 2\n\n vect = fromList :: [Float] -> Vector Float\n\n convomat :: Int -> Int -> AssocMatrix\n convomat n k = [ ((i,j `mod` n),1) | i<-[0..n-1], j <- [i..i+k-1]]\n\n convo2 :: Int -> Int -> AssocMatrix\n convo2 n k = m1 ++ m2\n where\n m1 = convomat n k\n m2 = map (((+n) *** id) *** id) m1\n\n testb n = vect $ take n $ cycle ([0..10]++[9,8..1])\n\n denseSolve a = flatten . linearSolveLS a . asColumn\n\n -- mkDiag v = mkDiagR (dim v) (dim v) v\n\n", "meta": {"hexsha": "eda86a99eddcfda4f554a23becc941b22495beae", "size": 5267, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Internal/CG.hs", "max_stars_repo_name": "schnecki/hmatrix-float", "max_stars_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Internal/CG.hs", "max_issues_repo_name": "schnecki/hmatrix-float", "max_issues_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Internal/CG.hs", "max_forks_repo_name": "schnecki/hmatrix-float", "max_forks_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-12T02:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T02:51:35.000Z", "avg_line_length": 27.5759162304, "max_line_length": 94, "alphanum_fraction": 0.4970571483, "num_tokens": 1745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5793046081127892}} {"text": "import Data.Bool\nimport Data.Complex (Complex((:+)), magnitude)\n\nmandelbrot\n :: RealFloat a\n => Complex a -> Complex a\nmandelbrot a = iterate ((a +) . (^ 2)) 0 !! 50\n\nmain :: IO ()\nmain =\n mapM_\n putStrLn\n [ [ bool ' ' '*' (2 > magnitude (mandelbrot (x :+ y)))\n | x <- [-2,-1.9685 .. 0.5] ]\n | y <- [1,0.95 .. -1] ]\n", "meta": {"hexsha": "85a6c13961ddf5c5dc4ae49e5c81dcc0b6cd049f", "size": 333, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lang/Haskell/mandelbrot-set.hs", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "lang/Haskell/mandelbrot-set.hs", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Haskell/mandelbrot-set.hs", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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": 20.8125, "max_line_length": 58, "alphanum_fraction": 0.5105105105, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5791675240314473}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE BangPatterns #-}\n\n{-# OPTIONS_GHC -fno-warn-orphans #-} -- do not warn on local instance of Random for Complex\n\nmodule BBrotCompute(compute, selectCells, inSet) where\n\nimport Control.Monad.Par\nimport Data.Aeson(encode)\nimport Data.Array\nimport qualified Data.ByteString.Lazy as BS\nimport Data.Complex\nimport Data.List\nimport Data.Maybe\nimport Data.Time\nimport System.Environment\nimport System.Console.CmdArgs(whenNormal, whenLoud)\nimport System.Random\nimport Text.Printf\n\nimport BBrotConf\nimport BBrotSelection\n\n\ninstance Random (Complex Double) where\n randomR (!(x0 :+ y0), !(x1 :+ y1)) g = (r :+ i, g2)\n where (!r, !g1) = randomR (x0, x1) g\n (!i, !g2) = randomR (y0, y1) g1\n random = randomR (0.0 :+ 0.0, 1.0 :+ 1.0)\n\ndata GridPoint = GridPoint { xbase :: !Double\n , ybase :: !Double\n , inMandelbrotSet :: !Bool\n }\n deriving Show\n\n\nmakeGrid :: Double -> Int -> Array (Int, Int) GridPoint\nmakeGrid step bailout = array ((0, 0), (xsteps, ysteps)) points\n where (xmin :+ ymin) = loCorner\n (xmax :+ ymax) = hiCorner\n xsteps = floor $ (xmax - xmin) / step :: Int\n ysteps = floor $ (ymax - ymin) / step :: Int\n points = [ ((i,j), g i j) | i <- [0..xsteps], j <- [0..ysteps] ]\n g i j = GridPoint x y p\n where x = xmin + fromIntegral i * step\n y = ymin + fromIntegral j * step\n p = not $ inSet 0 bailout (x :+ y)\n\nselectCells :: Double -> Int -> [(Double, Double)]\nselectCells step bailout = [ (xbase g, ybase g) | g <- cells ]\n where !grid = makeGrid step bailout\n ((x0, y0), (xsteps, ysteps)) = bounds grid\n !cells = [ grid!(i,j) | i <- [x0 + 1 .. xsteps - 1],\n j <- [y0 + 1 .. ysteps - 1],\n isNearBorder i j ]\n isNearBorder i j = someIn && someOut\n where neighbours = [ grid!(i+a,j+b) | (a, b) <- range ((-1,-1), (1,1)) ]\n inMandel = map inMandelbrotSet neighbours\n someIn = or inMandel\n someOut = not $ and inMandel\n\n\niterations :: Int -> Double -> Double -> Double -> Double -> Int -> Int\niterations !maxK !x !y !x0 !y0 !k =\n let x2 = x * x\n y2 = y * y\n in\n if k == maxK || x2 + y2 > 4\n then k\n else iterations maxK (x2 - y2 + x0) (2 * x * y + y0) x0 y0 (k + 1)\n\ninCardioBulb :: Double -> Double -> Bool\ninCardioBulb !x !y = inCardio || inBulb\n where sqr a = a * a\n q = sqr (x - 1/4) + sqr y\n inCardio = q * (q + (x - 1/4)) < sqr y / 4\n inBulb = sqr (x + 1) + sqr y < 1 / 16\n\ntoMaybeBBPoint :: Int -> Int -> Complex Double -> Maybe BBPoint\ntoMaybeBBPoint !minK !maxK !z =\n let x = realPart z\n y = imagPart z\n k = iterations maxK x y x y 0\n in if not (inCardioBulb x y) && k >= minK && k < maxK\n then Just (BBPoint x y k)\n else Nothing\n\ninSet :: Int -> Int -> Complex Double -> Bool\ninSet !minK !maxK !z = p $ toMaybeBBPoint minK maxK z\n where p (Just _) = False\n p Nothing = True\n\ntoUnit :: Int -> String\ntoUnit n = show (n `div` d) ++ unit\n where pow :: Int -> Int -> Int\n pow x y = x ^ y\n l = [ (10 `pow` 9, \"G\"), (10 `pow` 6, \"M\"), (10 `pow` 3, \"K\") ]\n (d, unit) = fromMaybe (1, \"\") $ find ((<= n) . fst) l\n\ncompute :: BBrotConf -> IO ()\ncompute conf = do\n -- Pick random points in the complex plane, test their orbits,\n -- save the interesting ones.\n\n whenNormal $ putStrLn $ printf \"Sampling %s points...\" $ toUnit $ samples conf\n\n initRandGen <- case seed conf of\n Just s -> return $ mkStdGen s\n Nothing -> getStdGen\n\n let step = gridStep conf\n cells = selectCells step 255\n pointsPerCell = samples conf `div` length cells\n generators = iterate (fst . split) initRandGen\n genPoints (cell, gen) = take pointsPerCell $ randomRs (corners cell) gen\n corners (x, y) = ((x :+ y) - cellDiag / 2, (x :+ y) + cellDiag / 2)\n cellDiag = step :+ step\n\n let pointLists = map genPoints $ zip cells generators\n\n let selected = concat $ concat $ runPar $ parMap (map f) pointLists\n where f = maybeToList . toMaybeBBPoint (minIters conf) (maxIters conf)\n\n let cachefile = fromMaybe defPath (ocachepath conf)\n where defPath = printf \"/tmp/buddhabrot-%s-%s_%s.bbc\"\n (toUnit $ samples conf)\n (toUnit $ minIters conf)\n (toUnit $ maxIters conf)\n\n whenNormal $ do\n putStrLn $ \"Selected cells: \" ++ show (length cells)\n putStrLn $ \"Writing cache \" ++ cachefile ++ \" ...\"\n args <- getArgs\n currentTime <- getCurrentTime\n BS.writeFile cachefile $ encode $\n PointSelection selected (Just args) (Just $ show initRandGen) (Just $ show currentTime)\n whenLoud $ putStrLn $ \"selected points: \" ++ show (length selected)\n", "meta": {"hexsha": "4e4882a5a0fd695dab0936220e4b49df5537464e", "size": 4897, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "BBrotCompute.hs", "max_stars_repo_name": "saffroy/buddhabrot", "max_stars_repo_head_hexsha": "142d8db7d98da492f735badab01ffdad52cf3ca8", "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": "BBrotCompute.hs", "max_issues_repo_name": "saffroy/buddhabrot", "max_issues_repo_head_hexsha": "142d8db7d98da492f735badab01ffdad52cf3ca8", "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": "BBrotCompute.hs", "max_forks_repo_name": "saffroy/buddhabrot", "max_forks_repo_head_hexsha": "142d8db7d98da492f735badab01ffdad52cf3ca8", "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.2302158273, "max_line_length": 92, "alphanum_fraction": 0.57239126, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5789526817922541}} {"text": "{-|\nModule : Univariate\nDescription : Univariate polynomials (notably cyclotomics)\nCopyright : (c) Matthew Amy, 2020\nMaintainer : matt.e.amy@gmail.com\nStability : experimental\nPortability : portable\n-}\n\nmodule Feynman.Algebra.Polynomial.Univariate(\n Univariate,\n Cyclotomic,\n var,\n constant,\n (*|),\n primitiveRoot,\n evaluate\n )\nwhere\n\nimport Data.List\nimport Data.Map(Map)\nimport qualified Data.Map as Map\nimport Data.Complex\nimport Data.Maybe(maybe)\n\nimport qualified Feynman.Util.Unicode as Unicode\nimport Feynman.Algebra.Base\nimport Feynman.Algebra.Polynomial\n\n{-------------------------------\n Univariate polynomials\n -------------------------------}\n\n-- | Univariate polynomials over the ring 'r'\ndata Univariate r = Univariate { getCoeffs :: !(Map Integer r) } deriving (Eq, Ord)\n\ninstance (Eq r, Num r, Show r) => Show (Univariate r) where\n show = showWithName \"x\"\n\ninstance Degree (Univariate r) where\n degree = maybe 0 (fromIntegral . fst) . Map.lookupMax . getCoeffs\n\n-- | Print a univariate polynomial with a particular variable name\nshowWithName :: (Eq r, Num r, Show r) => String -> Univariate r -> String\nshowWithName x p\n | p == 0 = \"0\"\n | otherwise = intercalate \" + \" $ map showTerm (Map.assocs $ getCoeffs p)\n where showTerm (expt, a)\n | expt == 0 = show a\n | a == 1 = showExpt expt\n | a == -1 = \"-\" ++ showExpt expt\n | otherwise = show a ++ showExpt expt\n showExpt expt\n | expt == 1 = x\n | otherwise = Unicode.sup x expt\n\ninstance (Eq r, Num r) => Num (Univariate r) where\n (+) = add\n (*) = mult\n negate = Univariate . Map.map negate . getCoeffs\n abs = id\n signum = id\n fromInteger 0 = Univariate Map.empty\n fromInteger i = Univariate $ Map.singleton 0 (fromInteger i)\n\n-- | Normalize a univariate polynomial\nnormalize :: (Eq r, Num r) => Univariate r -> Univariate r\nnormalize = Univariate . Map.filter (/=0) . getCoeffs\n\n-- | The unique univariate variable\nvar :: Num r => Univariate r\nvar = Univariate $ Map.singleton 1 1\n\n-- | Constant polynomial\nconstant :: (Eq r, Num r) => r -> Univariate r\nconstant a\n | a == 0 = Univariate $ Map.empty\n | otherwise = Univariate $ Map.singleton 0 a\n\n-- | Multiply by a scalar\n(*|) :: (Eq r, Num r) => r -> Univariate r -> Univariate r\n(*|) 0 = \\_p -> zero\n(*|) a = Univariate . Map.map (a*) . getCoeffs\n\n-- | Add two univariate polynomials\nadd :: (Eq r, Num r) => Univariate r -> Univariate r -> Univariate r\nadd p = normalize . Univariate . Map.unionWith (+) (getCoeffs p) . getCoeffs\n\n-- | Multiply two univariate polynomials\nmult :: (Eq r, Num r) => Univariate r -> Univariate r -> Univariate r\nmult p = normalize . Map.foldrWithKey (\\expt a -> add (mulTerm expt a)) 0 . getCoeffs\n where mulTerm expt a = Univariate . Map.mapKeysMonotonic (+ expt) . Map.map (* a) $ getCoeffs p\n\n{-------------------------------\n Cyclotomics\n -------------------------------}\n-- | Cyclotomic polynomials over the ring 'r'\ndata Cyclotomic r = Cyc { getOrder :: !Integer, getPoly :: !(Univariate r) } deriving (Eq, Ord)\n\ninstance (Eq r, Num r, Show r) => Show (Cyclotomic r) where\n show p = showWithName (Unicode.sub Unicode.zeta (getOrder p)) $ getPoly p\n\ninstance Degree (Cyclotomic r) where\n degree = degree . getPoly\n\ninstance (Eq r, Num r) => Num (Cyclotomic r) where\n p + q = reduceOrder $ Cyc m (p' + q')\n where (Cyc m p', Cyc _ q') = unifyOrder p q\n p * q = reduceOrder $ Cyc m (p' * q')\n where (Cyc m p', Cyc _ q') = unifyOrder p q\n negate (Cyc m p) = Cyc m $ negate p\n abs p = p\n signum p = p\n fromInteger i = Cyc 1 (fromInteger i)\n\n-- | Unify the order of two cyclotomics\nunifyOrder :: Cyclotomic r -> Cyclotomic r -> (Cyclotomic r, Cyclotomic r)\nunifyOrder (Cyc n p) (Cyc m q)\n | n == m = (Cyc n p, Cyc m q)\n | otherwise = (Cyc r p', Cyc r q')\n where r = lcm n m\n p' = Univariate . Map.mapKeysMonotonic ((r `div` n) *) $ getCoeffs p\n q' = Univariate . Map.mapKeysMonotonic ((r `div` m) *) $ getCoeffs q\n\n-- | Rewrite the cyclotomic in lowest order\nreduceOrder :: (Eq r, Num r) => Cyclotomic r -> Cyclotomic r\nreduceOrder (Cyc m c) = Cyc m' c'\n where m' = m `div` d\n c' = Univariate . Map.mapKeysMonotonic (`div` d) $ getCoeffs c\n d = foldr gcd m . Map.keys $ getCoeffs c\n\n-- | Construct the cyclotomic polynomial \\(\\zeta_i\\)\nprimitiveRoot :: Num r => Integer -> Cyclotomic r\nprimitiveRoot i = Cyc i var\n\n-- | Convert to a complex number\nevaluate :: (Real r, RealFloat f) => Cyclotomic r -> Complex f\nevaluate (Cyc m p) = Map.foldrWithKey f (0.0 :+ 0.0) $ getCoeffs p\n where f root coeff = (mkPolar (realToFrac coeff) (expnt root) +)\n expnt root = 2.0*pi*(fromInteger root)/(fromInteger m)\n", "meta": {"hexsha": "d4ad375211bdb00bffc0cecfc8b0e430bdc766bb", "size": 4784, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Feynman/Algebra/Polynomial/Univariate.hs", "max_stars_repo_name": "PariaNaghavi/feynman", "max_stars_repo_head_hexsha": "74f3b7694b8883315bf30a6a28b6b70c505f5fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2018-03-09T20:12:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T11:55:36.000Z", "max_issues_repo_path": "src/Feynman/Algebra/Polynomial/Univariate.hs", "max_issues_repo_name": "PariaNaghavi/feynman", "max_issues_repo_head_hexsha": "74f3b7694b8883315bf30a6a28b6b70c505f5fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-16T11:31:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T18:49:56.000Z", "max_forks_repo_path": "src/Feynman/Algebra/Polynomial/Univariate.hs", "max_forks_repo_name": "PariaNaghavi/feynman", "max_forks_repo_head_hexsha": "74f3b7694b8883315bf30a6a28b6b70c505f5fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-08-23T16:58:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T14:08:55.000Z", "avg_line_length": 33.6901408451, "max_line_length": 97, "alphanum_fraction": 0.6231187291, "num_tokens": 1471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5788693856813711}} {"text": "import Graphics.Gloss\nimport Graphics.Gloss.Juicy\nimport Codec.Picture\nimport Codec.Picture.RGBA8\nimport Data.Complex\n\nwidth = 512\nheight = width `div` 2\n\nmandelbrotness :: Complex Float -> Complex Float -> Float\nmandelbrotness c s = (fromIntegral $ length $ takeWhile (\\c -> magnitude c <= 2) $ take maxIter $ z c) / (fromIntegral maxIter) where\n z c = iterate (\\x -> x^2 + c) s\n maxIter = 32\n\nimage :: Float -> Image PixelRGB8\nimage time = generateImage (\\x y -> let [x',y',w,h] = map fromIntegral [x,y,width,height] in mandelbrotColor ((4*x'/w - 2.5) :+ (2*y'/h - 1)) (0.1*time :+ 0) ) width height where\n mandelbrotColor c s = PixelRGB8 (floor $ 255 * mandelbrotness c s) 120 120\n\nmain :: IO ()\nmain = animate (InWindow \"Mandelbrot\" (width,height) (0,0)) black (fromImageRGB8 . image)", "meta": {"hexsha": "ebe4100f8a56f15980b204e679d44380e3017487", "size": 791, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Haskell/Gloss/mandelbrot/app/Main.hs", "max_stars_repo_name": "cirquit/random-code", "max_stars_repo_head_hexsha": "2fddf21f1d884ab51e0b5a323da81a8fb4f0c6be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-09T05:31:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T05:31:07.000Z", "max_issues_repo_path": "Haskell/Gloss/mandelbrot/app/Main.hs", "max_issues_repo_name": "cirquit/Personal-Repository", "max_issues_repo_head_hexsha": "2fddf21f1d884ab51e0b5a323da81a8fb4f0c6be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Haskell/Gloss/mandelbrot/app/Main.hs", "max_forks_repo_name": "cirquit/Personal-Repository", "max_forks_repo_head_hexsha": "2fddf21f1d884ab51e0b5a323da81a8fb4f0c6be", "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.55, "max_line_length": 178, "alphanum_fraction": 0.6839443742, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5788175745451027}} {"text": "module Mobius where\n\nimport Data.Complex\n\nmoebius :: (Floating a, Fractional a, Eq a) => a -> a -> a -> a -> a -> a\nmoebius a b c d z \n | a*d - b*c == 0 = undefined\n | otherwise = (a*z + b) / (c*z + d)\n\nlambdamoebius :: (RealFloat a, Fractional a, Eq a) => \n Complex a -> Complex a -> Complex a\nlambdamoebius a z = (z - a) / (1 - ((conjugate a) * z))\n\ncircular :: (RealFloat a, Fractional a) => Complex a -> Complex a\ncircular z = m\u00f6bius 0 (-1) 1 0 z\n\nelliptic :: (Floating a, Fractional a, Eq a) => a -> a -> a\nelliptic theta z = m\u00f6bius (cos a) (-sin a) (sin a) (cos a) z --(cis theta) * z\n where a = theta\n\nparabolic :: (Floating a, Fractional a) => a -> a -> a\nparabolic a z = z + a -- translation\n\nhyperbolic :: (Floating a, Fractional a) => a -> a -> a\nhyperbolic theta z = (exp theta) * z\n\nloxodromic :: (Floating a, Fractional a) => a -> a -> a \nloxodromic a z = a * z -- S-shaped path\n\nprojection :: (Floating a, Fractional a) => a -> a \nprojection z = tanh \n", "meta": {"hexsha": "4aaca8242552fb7486faa2ec11971067333552ed", "size": 980, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Mobius.hs", "max_stars_repo_name": "Vetii/Fractal", "max_stars_repo_head_hexsha": "253dbcbccfcd3ee0ac05c08d72d1e80cf27016bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-04-06T04:52:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-06T04:52:50.000Z", "max_issues_repo_path": "Mobius.hs", "max_issues_repo_name": "Vetii/Fractal", "max_issues_repo_head_hexsha": "253dbcbccfcd3ee0ac05c08d72d1e80cf27016bb", "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": "Mobius.hs", "max_forks_repo_name": "Vetii/Fractal", "max_forks_repo_head_hexsha": "253dbcbccfcd3ee0ac05c08d72d1e80cf27016bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.625, "max_line_length": 78, "alphanum_fraction": 0.587755102, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132749, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5787321419828108}} {"text": "-- |\n-- Module : BattleHack.Utilities.Vector\n-- Description :\n-- Copyright : (c) Jonatan H Sundqvist, 2015\n-- License : MIT\n-- Maintainer : Jonatan H Sundqvist\n-- Stability : experimental|stable\n-- Portability : POSIX (not sure)\n--\n\n-- Created September 14 2015\n\n-- TODO | - Is it silly to use Complex Double for everything because of Cairo (yes it is; fixed) (\u2713)\n-- - Many of these functions should probably be moved to Southpaw\n\n-- SPEC | -\n-- -\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- GHC Pragmas\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- API\n--------------------------------------------------------------------------------------------------------------------------------------------\nmodule BattleHack.Utilities.Vector where\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- We'll need these\n--------------------------------------------------------------------------------------------------------------------------------------------\nimport Data.Complex\n\nimport BattleHack.Types\nimport BattleHack.Lenses\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- |\ndotwise :: (a -> a -> a) -> Complex a -> Complex a -> Complex a\ndotwise f (x:+y) (x':+y') = f x x':+f y y'\n\n\n-- |\ndotmap :: (a -> a) -> Complex a -> Complex a\ndotmap f (x:+y) = f x:+f y\n\n\n-- |\ntoscalar :: (a -> a -> a) -> Complex a -> a\ntoscalar f (x:+y) = f x y\n\n\n-- | Converts a 2-tuple to a vector\ntovector :: (a, a) -> Complex a\ntovector = uncurry (:+)\n\n\n-- |\nvectorise :: RealFloat f => (f -> f -> a) -> Complex f -> a\nvectorise f (x:+y) = f x y\n", "meta": {"hexsha": "5b2d08d0e47ebc57e8186b5b991d29e459f974fb", "size": 2241, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/BattleHack/Utilities/Vector.hs", "max_stars_repo_name": "SwiftsNamesake/BattleHack-2015", "max_stars_repo_head_hexsha": "14b47f3482dc80ee1469161a0cebb5a0e1b16a05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BattleHack/Utilities/Vector.hs", "max_issues_repo_name": "SwiftsNamesake/BattleHack-2015", "max_issues_repo_head_hexsha": "14b47f3482dc80ee1469161a0cebb5a0e1b16a05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BattleHack/Utilities/Vector.hs", "max_forks_repo_name": "SwiftsNamesake/BattleHack-2015", "max_forks_repo_head_hexsha": "14b47f3482dc80ee1469161a0cebb5a0e1b16a05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5633802817, "max_line_length": 140, "alphanum_fraction": 0.2962962963, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5785818747648938}} {"text": "{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE DataKinds, PolyKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE FlexibleContexts, FlexibleInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nmodule TensorHMatrix where\n\nimport Nats\nimport Numeric.LinearAlgebra hiding ((!))\nimport Data.Vector.Storable\nimport Data.Default\nimport Data.Singletons.Prelude\n\nimport Data.Vinyl\n\nimport Prelude hiding (zipWith)\n\ntype Usable a = (Element a, Num a, Numeric a, Num (Vector a), Container Vector a)\n\ntype IntegralK (p :: KProxy k) = (SingKind p, Integral (DemoteRep p))\ntype IntegralN (n :: k) = IntegralK ('KProxy :: KProxy k)\n\nnatVal' :: (Num a, IntegralN n) => Sing n -> a\nnatVal' = fromIntegral . fromSing\n\ndata Tensor (dims :: [k]) a where\n Scalar :: a -> Tensor '[] a\n Vector :: Vector a -> Tensor '[n] a\n Matrix :: Matrix a -> Tensor '[n, m] a\n\nderiving instance (Show a, Element a) => Show (Tensor dims a)\n\ninstance (Default a) => Default (Tensor '[] a) where\n def = Scalar def\n\nfill1 :: forall a n. (SingI n, IntegralN n, Usable a) => a -> Tensor '[n] a\nfill1 a = Vector $ konst a (natVal' (sing::Sing n))\n\ninstance (SingI n, IntegralN n, Default a, Usable a) => Default (Tensor '[n] a) where\n def = fill1 def\n\ninstance (SingI n, IntegralN n, SingI m, Default a, Usable a) => Default (Tensor '[n, m] a) where\n def = Matrix $ konst def (natVal' (sing::Sing n), natVal' (sing::Sing m))\n\n--type instance IndexOf (Tensor l) = Rec LT l\n--type instance IndexOf (Tensor l) = Rec (Const Int) l\n--type instance IndexOf (Tensor l) = Vec (Length l) Int\n\n{- Fails backwards fundep :(\ninstance Indexable (Tensor (n ': l) a) (Tensor l a) where\n Matrix m ! i = Vector (m ! i)\n Vector v ! i = Scalar (v ! i)\n-}\n\nselect :: Storable a => Int -> Tensor '[n] a -> a\nselect i (Vector v) = v ! i\n\n-- pretty much all of these instances should be automatically derivable\n\ninstance Num a => Num (Tensor '[] a) where\n Scalar a + Scalar b = Scalar (a + b)\n Scalar a - Scalar b = Scalar (a - b)\n Scalar a * Scalar b = Scalar (a * b)\n negate (Scalar a) = Scalar (negate a)\n abs (Scalar a) = Scalar (abs a)\n signum (Scalar a) = Scalar (signum a)\n fromInteger n = Scalar (fromInteger n)\n\ninstance (SingI n, IntegralN n, Usable a) => Num (Tensor '[n] a) where\n Vector a + Vector b = Vector (a + b)\n Vector a - Vector b = Vector (a - b)\n Vector a * Vector b = Vector (a * b)\n negate (Vector a) = Vector (negate a)\n abs (Vector a) = Vector (abs a)\n signum (Vector a) = Vector (signum a)\n fromInteger n = Vector $ konst (fromInteger n) (natVal' (sing::Sing n))\n\ninstance (SingI n, IntegralN n, SingI m, Usable a) => Num (Tensor '[n, m] a) where\n Matrix a + Matrix b = Matrix (a + b)\n Matrix a - Matrix b = Matrix (a - b)\n Matrix a * Matrix b = Matrix (a * b)\n negate (Matrix a) = Matrix (negate a)\n abs (Matrix a) = Matrix (abs a)\n signum (Matrix a) = Matrix (signum a)\n fromInteger n = Matrix $ konst (fromInteger n) (natVal' (sing::Sing n), natVal' (sing::Sing m))\n\ninstance Fractional a => Fractional (Tensor '[] a) where\n Scalar a / Scalar b = Scalar (a / b)\n recip (Scalar a) = Scalar (recip a)\n fromRational r = Scalar (fromRational r)\n\ninstance (SingI n, IntegralN n, Numeric a, Fractional a, Fractional (Vector a)) => Fractional (Tensor '[n] a) where\n Vector a / Vector b = Vector (a / b)\n recip (Vector a) = Vector (recip a)\n fromRational r = Vector $ konst (fromRational r) (natVal' (sing::Sing n))\n\ninstance Floating a => Floating (Tensor '[] a) where\n pi = Scalar pi\n exp (Scalar a) = Scalar (exp a)\n log (Scalar a) = Scalar (log a)\n sqrt (Scalar a) = Scalar (sqrt a)\n Scalar a ** Scalar b = Scalar (a ** b)\n logBase (Scalar a) (Scalar b) = Scalar (logBase a b)\n sin (Scalar a) = Scalar (sin a)\n cos (Scalar a) = Scalar (cos a)\n tan (Scalar a) = Scalar (tan a)\n asin (Scalar a) = Scalar (asin a)\n acos (Scalar a) = Scalar (acos a)\n atan (Scalar a) = Scalar (atan a)\n sinh (Scalar a) = Scalar (sinh a)\n cosh (Scalar a) = Scalar (cosh a)\n tanh (Scalar a) = Scalar (tanh a)\n asinh (Scalar a) = Scalar (asinh a)\n acosh (Scalar a) = Scalar (acosh a)\n atanh (Scalar a) = Scalar (atanh a)\n\ninstance (SingI n, IntegralN n, Usable a, Floating a, Floating (Vector a)) => Floating (Tensor '[n] a) where\n pi = fill1 pi\n exp (Vector a) = Vector (exp a)\n log (Vector a) = Vector (log a)\n sqrt (Vector a) = Vector (sqrt a)\n Vector a ** Vector b = Vector (a ** b)\n logBase (Vector a) (Vector b) = Vector (logBase a b)\n sin (Vector a) = Vector (sin a)\n cos (Vector a) = Vector (cos a)\n tan (Vector a) = Vector (tan a)\n asin (Vector a) = Vector (asin a)\n acos (Vector a) = Vector (acos a)\n atan (Vector a) = Vector (atan a)\n sinh (Vector a) = Vector (sinh a)\n cosh (Vector a) = Vector (cosh a)\n tanh (Vector a) = Vector (tanh a)\n asinh (Vector a) = Vector (asinh a)\n acosh (Vector a) = Vector (acosh a)\n atanh (Vector a) = Vector (atanh a)\n\ntmap :: (Container Vector a, Num a, Element b) => (a -> b) -> Tensor dims a -> Tensor dims b\ntmap f (Scalar a) = Scalar $ f a\ntmap f (Vector v) = Vector $ cmap f v\ntmap f (Matrix m) = Matrix $ cmap f m\n\ntZipWith :: (Storable a, Storable b, Storable c) => (a -> b -> c) -> Tensor '[n] a -> Tensor '[n] b -> Tensor '[n] c\ntZipWith f (Vector a) (Vector b) = Vector (zipWith f a b)\n\ntranspose :: (Numeric a) => Tensor '[n, m] a -> Tensor '[m, n] a\ntranspose (Matrix m) = Matrix (tr' m)\n\nasCol :: Storable a => Tensor '[n] a -> Tensor '[n, FromInteger 1] a\nasCol (Vector v) = Matrix $ asColumn v\n\nasRow' :: Storable a => Tensor '[n] a -> Tensor '[FromInteger 1, n] a\nasRow' (Vector v) = Matrix $ asRow v\n\ndot :: (Storable a, Numeric a) => Tensor '[n] a -> Tensor '[n] a -> a\ndot (Vector a) (Vector b) = a <.> b\n\nmv :: Numeric a => Tensor '[n, m] a -> Tensor '[m] a -> Tensor '[n] a\nmv (Matrix m) (Vector v) = Vector $ m #> v\n\nmm :: Numeric a => Tensor '[n, m] a -> Tensor '[m, k] a -> Tensor '[n, k] a\nmm (Matrix m1) (Matrix m2) = Matrix $ m1 <> m2\n\ngradDot :: Numeric a => Tensor '[n] a -> Tensor '[n] a -> a -> (Tensor '[n] a, Tensor '[n] a)\ngradDot (Vector a) (Vector b) g = (Vector $ scale g b, Vector $ scale g a)\n\ngradMV :: Numeric a => Tensor '[n, m] a -> Tensor '[m] a -> Tensor '[n] a -> (Tensor '[n, m] a, Tensor '[m] a)\ngradMV m v g = (mm (asCol g) (asRow' v), mv (transpose m) g)\n\ngradMM :: Numeric a => Tensor '[n, m] a -> Tensor '[m, k] a -> Tensor '[n, k] a -> (Tensor '[n, m] a, Tensor '[m, k] a)\ngradMM a b g = (mm g (transpose b), mm (transpose a) g)\n\noneHot :: forall a n. (SingI n, IntegralN n, Usable a) => Int -> Tensor '[n] a\noneHot m = Vector $ (konst 0 (natVal' (sing::Sing n))) // [(m, 1)]\n\ngradSelect :: forall a n. (SingI n, IntegralN n, Usable a) => Int -> Tensor '[n] a -> a -> Tensor '[n] a\ngradSelect i _ a = Vector $ (konst 0 (natVal' (sing::Sing n))) // [(i, a)]\n\n", "meta": {"hexsha": "b8e1aea94e6d4a97555440a015ccc094e9eff797", "size": 6923, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "TensorHMatrix.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": "TensorHMatrix.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": "TensorHMatrix.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": 37.625, "max_line_length": 119, "alphanum_fraction": 0.6218402427, "num_tokens": 2292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5783539250084375}} {"text": "module School.Train.GradientDescent\n( gradientDescent ) where\n\nimport Conduit ((.|), ConduitM, mapMC, runConduit, sinkNull, takeWhileC)\nimport Control.Monad.State.Lazy (get)\nimport Data.Maybe (isJust)\nimport Numeric.LinearAlgebra (Matrix)\nimport School.Train.AppTrain (AppTrain, runAppTrain)\nimport School.Train.GradientDescentPass (gradientDescentPass)\nimport School.Train.IterationHandler (IterationHandler(..))\nimport School.Train.UpdateParams (UpdateParams)\nimport School.Train.StoppingCondition (StoppingCondition(..))\nimport School.Train.TrainState (TrainState)\nimport School.Unit.CostFunction (CostFunction(..))\nimport School.Unit.Unit (Unit)\nimport School.Unit.UnitBackward (BackwardStack)\n\nstopping :: StoppingCondition a\n -> ConduitM (BackwardStack a)\n (Maybe ())\n (AppTrain a)\n ()\nstopping condition = mapMC $ \\_ -> do\n state <- get\n if runCondition condition state\n then return Nothing\n else return (Just ())\n\ngradientDescent :: ConduitM () (Matrix a) (AppTrain a) ()\n -> [Unit a]\n -> CostFunction a (AppTrain a)\n -> UpdateParams a\n -> StoppingCondition a\n -> IterationHandler a\n -> TrainState a\n -> IO (Either String\n (TrainState a))\ngradientDescent source\n units\n cost\n update\n condition\n handler\n initState = do\n let pass = setupCost cost source\n .| gradientDescentPass units cost update\n .| runHandler handler\n .| stopping condition\n .| takeWhileC isJust\n .| sinkNull\n result <- runAppTrain initState . runConduit $ pass\n return $ snd <$> result\n", "meta": {"hexsha": "95d7af358fb92c5006b601db9b228ab559fe2d41", "size": 1810, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/School/Train/GradientDescent.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/School/Train/GradientDescent.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/School/Train/GradientDescent.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1509433962, "max_line_length": 72, "alphanum_fraction": 0.6138121547, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915618, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5779792054165327}} {"text": "module HLearn.Metrics.Mahalanobis.Normal\n where\n\nimport Control.DeepSeq\nimport qualified Data.Vector.Generic as VG\n\nimport Foreign.Storable\nimport Numeric.LinearAlgebra hiding ((<>))\nimport qualified Numeric.LinearAlgebra as LA\n\nimport HLearn.Algebra\nimport HLearn.Metrics.Mahalanobis\nimport HLearn.Models.Distributions.Multivariate.MultiNormalFast\n\n-------------------------------------------------------------------------------\n-- data types\n\nnewtype MahalanobisParams dp = MahalanobisParams\n { normal :: MultiNormal dp\n }\n\nderiving instance Show (MultiNormal dp) => Show (MahalanobisParams dp)\nderiving instance Read (MultiNormal dp) => Read (MahalanobisParams dp)\nderiving instance Eq (MultiNormal dp) => Eq (MahalanobisParams dp)\nderiving instance Ord (MultiNormal dp) => Ord (MahalanobisParams dp)\nderiving instance NFData (MultiNormal dp) => NFData (MahalanobisParams dp)\n\n-------------------------------------------------------------------------------\n-- algebra\n\nderiving instance Monoid (MultiNormal dp) => Monoid (MahalanobisParams dp)\n\ninstance HasRing dp => HasRing (MahalanobisParams dp) where\n type Ring (MahalanobisParams dp) = Ring dp\n\n-------------------------------------------------------------------------------\n-- training\n\ninstance HomTrainer (MultiNormal dp) => HomTrainer (MahalanobisParams dp) where\n type Datapoint (MahalanobisParams dp) = Datapoint (MultiNormal dp) \n\n train1dp dp = MahalanobisParams $ train1dp dp\n train dps = MahalanobisParams $ train dps\n\n-------------------------------------------------------------------------------\n-- metric\n\ninstance\n ( VG.Vector dp r\n , Ring (dp r) ~ r\n , LA.Product r\n , Field r\n ) => MkMahalanobis (MahalanobisParams (dp r)) \n where\n type MetricDatapoint (MahalanobisParams (dp r)) = dp r\n mkMahalanobis (MahalanobisParams m) dp = Mahalanobis\n { rawdp = dp\n , moddp = VG.fromList $ toList $ flatten $ inv (covar m) LA.<> asColumn v\n }\n where\n v = fromList $ VG.toList dp\n\n-- mkMahalanobis :: \n-- ( VG.Vector dp r\n-- , Ring (dp r) ~ r\n-- , LA.Product r\n-- ) => MahalanobisParams (dp r) -> dp r -> Mahalanobis (dp r)\n-- mkMahalanobis (MahalanobisParams m) dp = Mahalanobis\n-- { rawdp = dp\n-- , moddp = VG.fromList $ toList $ flatten $ covar m LA.<> asColumn v\n-- }\n-- where\n-- v = fromList $ VG.toList dp\n", "meta": {"hexsha": "83300a6c7d42aec33f8b5e53dce99d4f8c460898", "size": 2405, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HLearn/Metrics/Mahalanobis/Normal.hs", "max_stars_repo_name": "silky/HLearn", "max_stars_repo_head_hexsha": "86423d1c9ed7939640efba7db40628dbd21797fd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T11:33:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T11:33:36.000Z", "max_issues_repo_path": "src/HLearn/Metrics/Mahalanobis/Normal.hs", "max_issues_repo_name": "silky/HLearn", "max_issues_repo_head_hexsha": "86423d1c9ed7939640efba7db40628dbd21797fd", "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/HLearn/Metrics/Mahalanobis/Normal.hs", "max_forks_repo_name": "silky/HLearn", "max_forks_repo_head_hexsha": "86423d1c9ed7939640efba7db40628dbd21797fd", "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.5, "max_line_length": 81, "alphanum_fraction": 0.5991683992, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5778973684943907}} {"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule SentimentAnalysis where\n\nimport Numeric.LinearAlgebra as LA\nimport Data.Bifunctor (Bifunctor(bimap))\nimport Data.List.Split (splitOn)\n\nhingeLossSingle :: (Ord a, Numeric a) => Vector a -> a -> Vector a -> a -> a\nhingeLossSingle x y theta theta0 = max 0 (1 - y * (theta LA.<.> x + theta0))\n\nhingeLossFull :: (Numeric a, Ord a, Num (Vector a), Fractional a) => Matrix a -> Vector a -> Vector a -> a -> a\nhingeLossFull x y theta theta0 = loss\n where\n theta0s = size y |> repeat theta0\n ones = size y |> repeat 1.0\n agreement = y * (theta LA.<# LA.tr' x + theta0s)\n losses = LA.cmap (max 0) (ones - agreement)\n loss = sumElements losses / fromIntegral (size losses)\n\nperceptronSingleStepUpdate :: (Ord b, Numeric b, Num (Vector b)) => Vector b -> b -> Vector b -> b -> (Vector b, b)\nperceptronSingleStepUpdate x y theta theta0 = \n if y * (theta LA.<.> x + theta0) <= 0\n then (theta + (scalar y * x), theta0 + y)\n else (theta, theta0)\n\nperceptronUpdate :: (Ord t, Numeric t, Num (Vector t)) => [Vector t] -> [t] -> Vector t -> t -> [Int] -> (Vector t, t)\nperceptronUpdate _ _ theta theta0 [] = (theta, theta0)\nperceptronUpdate xs ys theta theta0 (z:zs) = \n let (theta', theta0') = perceptronSingleStepUpdate (xs !! z) (ys !! z) theta theta0\n in perceptronUpdate xs ys theta' theta0' zs\n \nperceptron :: (Ord t, Numeric t, Num (Vector t)) => Matrix t -> Vector t -> Int -> [Int] -> (Vector t, t)\nperceptron x y t indices = iterate step (cols x |> repeat 0, 0) !! t\n where step (theta, theta0) = perceptronUpdate (toRows x) (toList y) theta theta0 indices\n\naveragePerceptronUpdate :: (Ord t, Numeric t, Num (Vector t)) \n => [Vector t] -> [t] -> Vector t -> t -> [Int] -> [(Vector t, t)]\naveragePerceptronUpdate _ _ theta theta0 [] = []\naveragePerceptronUpdate xs ys theta theta0 (z:zs) = \n let (theta', theta0') = perceptronSingleStepUpdate (xs !! z) (ys !! z) theta theta0\n in (theta', theta0') : averagePerceptronUpdate xs ys theta' theta0' zs\n\naveragePerceptronList :: (Ord t, Numeric t, Num (Vector t)) => Matrix t -> Vector t -> [Int] -> [[(Vector t, t)]]\naveragePerceptronList x y indices = iterate step [(cols x |> repeat 0, 0)]\n where\n step xs = averagePerceptronUpdate (toRows x) (toList y) theta theta0 indices\n where (theta, theta0) = last xs\n\naveragePerceptron :: (Fractional t, Ord t, Numeric t, Num (Vector t))\n => Matrix t -> Vector t -> Int -> [Int] -> (Vector t, t)\naveragePerceptron x y t indices = (bimap ((/ scalar n) . sum) ((/ n) . sum) . unzip . concat) xss\n where \n n = fromIntegral $ t * rows x\n xss = drop 1 $ take (t + 1) $ averagePerceptronList x y indices\n\npegasosSingleStepUpdate :: (Ord e, Numeric e, Num (Vector e)) => Vector e -> e -> e -> e -> Vector e -> e -> (Vector e, e)\npegasosSingleStepUpdate x y lambda eta theta theta0 = \n if y * (theta LA.<.> x + theta0) <= 1\n then\n (scalar (1 - eta * lambda) * theta + scalar (eta * y) * x, theta0 + eta * y)\n else \n (scalar (1 - eta * lambda) * theta, theta0)\n\npegasosUpdate :: (Ord t, Numeric t, Num (Vector t), Floating t)\n => [Vector t] -> [t] -> t -> t -> Vector t -> t -> [Int] -> (Vector t, t, t)\npegasosUpdate _ _ lambda i theta theta0 [] = (theta, theta0, i)\npegasosUpdate xs ys lambda i theta theta0 (z:zs) = \n let (theta', theta0') = pegasosSingleStepUpdate (xs !! z) (ys !! z) lambda (1 / sqrt i) theta theta0 \n in pegasosUpdate xs ys lambda (i + 1) theta' theta0' zs\n \npegasos :: (Ord t, Numeric t, Floating t, Num (Vector t)) => Matrix t -> Vector t -> Int -> t -> [Int] -> (Vector t, t)\npegasos x y t lambda indices = (theta', theta0')\n where\n (theta', theta0', i') = iterate step (cols x |> repeat 0, 0, 1.0) !! t\n step (theta, theta0, i) = pegasosUpdate (toRows x) (toList y) lambda i theta theta0 indices\n\nmain :: IO ()\nmain = do\n dta <- loadMatrix \"toy_data.tsv\"\n orderDta <- readFile \"200.txt\"\n \n let t = 10\n let lambda = 0.2\n let x = dta \u00bf [1, 2]\n let y = flatten $ dta \u00bf [0]\n let indices = map read $ splitOn \",\" orderDta\n \n let (theta, theta0) = perceptron x y t indices\n putStrLn \"Perceptron:\"\n print theta\n print theta0\n\n let (theta, theta0) = averagePerceptron x y t indices\n putStrLn \"Average Perceptron:\"\n print theta\n print theta0\n\n let (theta, theta0) = pegasos x y t lambda indices\n putStrLn \"Pegasos:\"\n print theta\n print theta0\n", "meta": {"hexsha": "7c6a2b3c5a7cf62f6956369aaaa35a56676cf3a4", "size": 4557, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SentimentAnalysis.hs", "max_stars_repo_name": "ph1lblair/haskell-ml", "max_stars_repo_head_hexsha": "1b26fe94ae9751d4a3ce6ffd630dc203492d384a", "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/SentimentAnalysis.hs", "max_issues_repo_name": "ph1lblair/haskell-ml", "max_issues_repo_head_hexsha": "1b26fe94ae9751d4a3ce6ffd630dc203492d384a", "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/SentimentAnalysis.hs", "max_forks_repo_name": "ph1lblair/haskell-ml", "max_forks_repo_head_hexsha": "1b26fe94ae9751d4a3ce6ffd630dc203492d384a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6764705882, "max_line_length": 122, "alphanum_fraction": 0.609392144, "num_tokens": 1431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.577894017641878}} {"text": "module Mnist\n ( Image\n , Label\n , DataSet\n , loadMnist\n ) where\n\nimport Control.Monad\nimport Numeric.LinearAlgebra\nimport Network.HTTP.Simple (parseRequest, httpLBS, getResponseBody)\nimport System.Directory (doesFileExist)\nimport qualified Data.ByteString.Lazy as BL\nimport qualified Codec.Compression.GZip as GZ (compress, decompress)\nimport Data.Binary (encode, decode)\n\ntype Image = Matrix R\ntype Label = Vector R\ntype DataSet = (Image, Label)\n\nbaseUrl = \"http://yann.lecun.com/exdb/mnist\"\nkeyFiles = [\n (\"train_img\", \"train-images-idx3-ubyte.gz\"),\n (\"train_label\", \"train-labels-idx1-ubyte.gz\"),\n (\"test_img\", \"t10k-images-idx3-ubyte.gz\"),\n (\"test_label\", \"t10k-labels-idx1-ubyte.gz\")\n ]\n\nassetsDir = \"assets\"\npickleFile = \"mnist.dat\"\nimgSize = 784\n\ngeneratePath :: String -> String\ngeneratePath p = assetsDir ++ \"/\" ++ p\n\ndownload :: String -> IO ()\ndownload fn = do\n let p = generatePath fn\n\n e <- doesFileExist p\n unless e $ do\n putStrLn $ \"Downloading \" ++ fn ++ \" ...\"\n res <- httpLBS =<< parseRequest (baseUrl ++ \"/\" ++ fn)\n BL.writeFile p (getResponseBody res)\n putStrLn \"Done\"\n\ndownloadMnist :: [(String, String)] -> IO ()\ndownloadMnist [] = return ()\ndownloadMnist (x:xs) = do\n download $ snd x\n downloadMnist xs\n\ntoDoubleList :: BL.ByteString -> [Double]\ntoDoubleList = fmap (read . show . fromEnum) . BL.unpack\n\nloadLabel :: String -> IO Label\nloadLabel fn = do\n c <- fmap GZ.decompress (BL.readFile $ generatePath fn)\n return . vector . toDoubleList $ BL.drop 8 c\n\nloadImg :: String -> IO Image\nloadImg fn = do\n c <- fmap GZ.decompress (BL.readFile $ generatePath fn)\n return . matrix imgSize . toDoubleList $ BL.drop 16 c\n\nconvertDataset :: IO [DataSet]\nconvertDataset = do\n tri <- loadImg . snd . head $ keyFiles\n trl <- loadLabel . snd . (!!1) $ keyFiles\n ti <- loadImg . snd . (!!2) $ keyFiles\n tl <- loadLabel . snd . (!!3) $ keyFiles\n\n return [(tri, trl), (ti, tl)]\n\ncreatePickle :: String -> [DataSet] -> IO ()\ncreatePickle p ds = BL.writeFile p $ (GZ.compress . encode) ds\n\nloadPickle :: String -> IO [DataSet]\nloadPickle p = do\n eds <- BL.readFile p\n return $ (decode . GZ.decompress) eds\n\ninitMnist :: IO ()\ninitMnist = do\n downloadMnist keyFiles\n putStrLn \"Creating binary DataSet file ...\"\n createPickle (generatePath pickleFile) =<< convertDataset\n putStrLn \"Done\"\n\nnormalizeImg :: Bool -> [DataSet] -> IO [DataSet]\nnormalizeImg f ds@[tr, t]\n | f = return [ ((/255) $ fst tr, snd tr), ((/255) $ fst t, snd t) ]\n | otherwise = return ds\n\nloadMnist :: Bool -> IO [DataSet]\nloadMnist nml = do\n let p = generatePath pickleFile\n e <- doesFileExist p\n unless e initMnist\n\n normalizeImg nml =<< loadPickle p\n", "meta": {"hexsha": "ea54d60b02d0892ae0c4352ac29e76f5b195c7d2", "size": 2804, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Mnist.hs", "max_stars_repo_name": "ku00/deep-learning-practice", "max_stars_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-03T05:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T05:32:58.000Z", "max_issues_repo_path": "src/Mnist.hs", "max_issues_repo_name": "ku00/deep-learning-practice", "max_issues_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mnist.hs", "max_forks_repo_name": "ku00/deep-learning-practice", "max_forks_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7623762376, "max_line_length": 79, "alphanum_fraction": 0.6430099857, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.577894012849577}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module : Statistics.Distribution.Hypergeometric\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- The Hypergeometric distribution. This is the discrete probability\n-- distribution that measures the probability of /k/ successes in /l/\n-- trials, without replacement, from a finite population.\n--\n-- The parameters of the distribution describe /k/ elements chosen\n-- from a population of /l/, with /m/ elements of one type, and\n-- /l/-/m/ of the other (all are positive integers).\n\nmodule Statistics.Distribution.Hypergeometric\n (\n HypergeometricDistribution\n -- * Constructors\n , hypergeometric\n , hypergeometricE\n -- ** Accessors\n , hdM\n , hdL\n , hdK\n ) where\n\nimport Control.Applicative\nimport Data.Aeson (FromJSON(..), ToJSON, Value(..), (.:))\nimport Data.Binary (Binary(..))\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.MathFunctions.Constants (m_epsilon,m_neg_inf)\nimport Numeric.SpecFunctions (choose,logChoose)\n\nimport qualified Statistics.Distribution as D\nimport Statistics.Internal\n\n\ndata HypergeometricDistribution = HD {\n hdM :: {-# UNPACK #-} !Int\n , hdL :: {-# UNPACK #-} !Int\n , hdK :: {-# UNPACK #-} !Int\n } deriving (Eq, Typeable, Data, Generic)\n\ninstance Show HypergeometricDistribution where\n showsPrec i (HD m l k) = defaultShow3 \"hypergeometric\" m l k i\ninstance Read HypergeometricDistribution where\n readPrec = defaultReadPrecM3 \"hypergeometric\" hypergeometricE\n\ninstance ToJSON HypergeometricDistribution\ninstance FromJSON HypergeometricDistribution where\n parseJSON (Object v) = do\n m <- v .: \"hdM\"\n l <- v .: \"hdL\"\n k <- v .: \"hdK\"\n maybe (fail $ errMsg m l k) return $ hypergeometricE m l k\n parseJSON _ = empty\n\ninstance Binary HypergeometricDistribution where\n put (HD m l k) = put m >> put l >> put k\n get = do\n m <- get\n l <- get\n k <- get\n maybe (fail $ errMsg m l k) return $ hypergeometricE m l k\n\ninstance D.Distribution HypergeometricDistribution where\n cumulative = cumulative\n\ninstance D.DiscreteDistr HypergeometricDistribution where\n probability = probability\n logProbability = logProbability\n\ninstance D.Mean HypergeometricDistribution where\n mean = mean\n\ninstance D.Variance HypergeometricDistribution where\n variance = variance\n\ninstance D.MaybeMean HypergeometricDistribution where\n maybeMean = Just . D.mean\n\ninstance D.MaybeVariance HypergeometricDistribution where\n maybeStdDev = Just . D.stdDev\n maybeVariance = Just . D.variance\n\ninstance D.Entropy HypergeometricDistribution where\n entropy = directEntropy\n\ninstance D.MaybeEntropy HypergeometricDistribution where\n maybeEntropy = Just . D.entropy\n\nvariance :: HypergeometricDistribution -> Double\nvariance (HD m l k) = (k' * ml) * (1 - ml) * (l' - k') / (l' - 1)\n where m' = fromIntegral m\n l' = fromIntegral l\n k' = fromIntegral k\n ml = m' / l'\n\nmean :: HypergeometricDistribution -> Double\nmean (HD m l k) = fromIntegral k * fromIntegral m / fromIntegral l\n\ndirectEntropy :: HypergeometricDistribution -> Double\ndirectEntropy d@(HD m _ _)\n = negate . sum\n $ takeWhile (< negate m_epsilon)\n $ dropWhile (not . (< negate m_epsilon))\n [ let x = probability d n in x * log x | n <- [0..m]]\n\n\nhypergeometric :: Int -- ^ /m/\n -> Int -- ^ /l/\n -> Int -- ^ /k/\n -> HypergeometricDistribution\nhypergeometric m l k\n = maybe (error $ errMsg m l k) id $ hypergeometricE m l k\n\nhypergeometricE :: Int -- ^ /m/\n -> Int -- ^ /l/\n -> Int -- ^ /k/\n -> Maybe HypergeometricDistribution\nhypergeometricE m l k\n | not (l > 0) = Nothing\n | not (m >= 0 && m <= l) = Nothing\n | not (k > 0 && k <= l) = Nothing\n | otherwise = Just (HD m l k)\n\n\nerrMsg :: Int -> Int -> Int -> String\nerrMsg m l k\n = \"Statistics.Distribution.Hypergeometric.hypergeometric: \"\n ++ \"m=\" ++ show m\n ++ \"l=\" ++ show l\n ++ \"k=\" ++ show k\n ++ \" should hold: l>0 & m in [0,l] & k in (0,l]\"\n\n-- Naive implementation\nprobability :: HypergeometricDistribution -> Int -> Double\nprobability (HD mi li ki) n\n | n < max 0 (mi+ki-li) || n > min mi ki = 0\n -- No overflow\n | li < 1000 = choose mi n * choose (li - mi) (ki - n)\n / choose li ki\n | otherwise = exp $ logChoose mi n\n + logChoose (li - mi) (ki - n)\n - logChoose li ki\n\nlogProbability :: HypergeometricDistribution -> Int -> Double\nlogProbability (HD mi li ki) n\n | n < max 0 (mi+ki-li) || n > min mi ki = m_neg_inf\n | otherwise = logChoose mi n\n + logChoose (li - mi) (ki - n)\n - logChoose li ki\n\ncumulative :: HypergeometricDistribution -> Double -> Double\ncumulative d@(HD mi li ki) x\n | isNaN x = error \"Statistics.Distribution.Hypergeometric.cumulative: NaN argument\"\n | isInfinite x = if x > 0 then 1 else 0\n | n < minN = 0\n | n >= maxN = 1\n | otherwise = D.sumProbabilities d minN n\n where\n n = floor x\n minN = max 0 (mi+ki-li)\n maxN = min mi ki\n", "meta": {"hexsha": "7951c37d63ff1f9b516528172871273e39f80e8f", "size": 5396, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Hypergeometric.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:39:40.000Z", "max_issues_repo_path": "Statistics/Distribution/Hypergeometric.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T14:21:32.000Z", "max_forks_repo_path": "Statistics/Distribution/Hypergeometric.hs", "max_forks_repo_name": "infinity0/statistics", "max_forks_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2015-02-13T00:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:19:16.000Z", "avg_line_length": 31.5555555556, "max_line_length": 90, "alphanum_fraction": 0.6319495923, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5777136176367652}} {"text": "{-|\nModule : kMeans\nDescription : k-Means\nCopyright : (c) Fabr\u00edcio Olivetti, 2017\nLicense : GPL-3\nMaintainer : fabricio.olivetti@gmail.com\n\nk-Means Clustering algorithm\n-}\n\nmodule KMeansPar where\n\nimport Control.Parallel.Strategies\nimport Data.List\nimport Data.Ord\nimport Data.List.Split (chunksOf)\n--import qualified Numeric.LinearAlgebra as H \n\nimport Vector\nimport Dados\n\n-- |'parseFile' parses a space separated file \n-- to a list of lists of Double\nparseFile :: String -> [[Double]]\nparseFile file = map parseLine (lines file)\n where\n parseLine l = map toDouble (words l)\n toDouble w = read w :: Double\n\nfirstClusters idxs points = [ points !! i | i <- idxs ]\n\nkmeans :: Int -> ChunksOf [[Double]] -> [[Double]] \n -> [[Double]]\nkmeans it points clusters\n | it == 0 = clusters\n | clusters' == clusters = clusters\n | otherwise = kmeans (it-1) points clusters'\n where\n clusters' = emStep points clusters\n\nemStep :: ChunksOf [[Double]] -> [[Double]] -> [[Double]]\nemStep points clusters = map (\\(idx, (xs,n)) -> xs ./ n)\n $ mapReduceByKey (\\pi -> (assign pi clusters, (pi,1.0))) soma points\n where\n soma (xs1, y1) (xs2, y2) = (xs1 .+. xs2, y1+y2)\n \nassign :: [Double] -> [[Double]] -> Integer\nassign point clusters = closestTo point\n where\n closestTo p = argmin $ map (euclid p) clusters\n euclid pi ci = sum $ map (^2) $ zipWith (-) pi ci\n argmin xs = fst $ head $ sortByValue $ zip [0..] xs\n\n\n", "meta": {"hexsha": "0c6f0e7f6b23982541294f2853fe78f4613274c1", "size": 1493, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "09 - Agrupamento de Dados/KMeansPar.hs", "max_stars_repo_name": "douggribeiro/bigdata", "max_stars_repo_head_hexsha": "5f923b4f21bce48a1a202d5f8d984ac076059b5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-19T01:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-19T01:49:40.000Z", "max_issues_repo_path": "09 - Agrupamento de Dados/KMeansPar.hs", "max_issues_repo_name": "douggribeiro/bigdata", "max_issues_repo_head_hexsha": "5f923b4f21bce48a1a202d5f8d984ac076059b5b", "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": "09 - Agrupamento de Dados/KMeansPar.hs", "max_forks_repo_name": "douggribeiro/bigdata", "max_forks_repo_head_hexsha": "5f923b4f21bce48a1a202d5f8d984ac076059b5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-10-28T00:46:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-29T14:03:54.000Z", "avg_line_length": 27.1454545455, "max_line_length": 91, "alphanum_fraction": 0.6336235767, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5776125760542631}} {"text": "{-# LANGUAGE BangPatterns, CPP #-}\nimport System.Environment\nimport Control.Monad\nimport Control.Seq\nimport Data.Complex\nimport System.IO\nimport Debug.Trace\nimport Control.DeepSeq\nimport Control.Monad.Par\nimport Control.Exception\n\nimport PortablePixmap\nimport Control.Monad.Par.AList as A\n\nmandel :: Int -> Complex Double -> Int\nmandel max_depth c = loop 0 0\n where \n fn = magnitude\n loop i !z\n | i == max_depth = i\n | fn(z) >= 2.0 = i\n | otherwise = loop (i+1) (z*z + c)\n\n\nthreshold = 1\n\nrunMandel :: Double -> Double -> Double -> Double -> Int -> Int -> Int -> Par (AList [Int])\nrunMandel minX minY maxX maxY winX winY max_depth = do\n\n parBuildThreshM threshold (InclusiveRange 0 (winY-1)) $ \\y -> \n do\n let l = [ mandelStep y x | x <- [0.. winX-1] ]\n deepseq l (return l)\n\n where\n mandelStep i j = mandel max_depth z\n where z = ((fromIntegral j * r_scale) / fromIntegral winY + minY) :+\n ((fromIntegral i * c_scale) / fromIntegral winX + minX)\n\n r_scale = maxY - minY :: Double\n c_scale = maxX - minX :: Double\n\n\nmakeImage :: Integer -> Integer -> Int -> AList [Int] -> PixMap\nmakeImage x y depth ls =\n createPixmap x y depth \n (map prettyRGB (concat (toList ls)))\n where \n prettyRGB :: Int -> (Int,Int,Int)\n prettyRGB s = let t = (depth - s) in (s,t,t)\n\nsimple x y depth = \n runMandel 0 0 x' y' x y depth\n where \n x' = fromIntegral x\n y' = fromIntegral y \n\n--------------------------------------------------------------------------------\n\n-- A meaningless checksum.\nmandelCheck :: AList [Int] -> Int -> Int -> Int\nmandelCheck als max_col max_depth = loop 0 als 0\n where \n loop i als !sum | A.null als = sum\n loop i als !sum = loop (i+1) (A.tail als)\n\t\t (loop2 i 0 (A.head als) sum)\n loop2 i j [] !sum = sum\n loop2 i j (h:t) !sum | h == max_depth = loop2 i (j+1) t (sum + i*max_col + j)\n\t\t | otherwise = loop2 i (j+1) t sum\n\t \nmain = do args <- getArgs\n\n let (x,y,depth) = \n\t\tcase args of\n\t\t [] -> \n -- runPar $ simple 3 3 3\n\t\t (3,3,3)\n\n\t\t [x,y,depth] -> \n --\t\t simple (read x) (read y) (read depth)\n\t\t (read x, read y, read depth)\n\n\t\t -- [minX,minY,maxX,maxY,winX,winY,depth] ->\n\t\t -- runPar $ \n\t\t -- \t runMandel (read minX) (read minY)\n\t\t -- \t\t (read maxX) (read maxY)\n\t\t -- \t\t (read winX) (read winY) (read depth)\n\n let ls = runPar$ simple x y depth\n when (False) $ do \n\t hnd <- openFile \"mandel_image.ppm\" WriteMode\n\t hSetBinaryMode hnd True\n\t hPrint hnd (makeImage (fromIntegral x) (fromIntegral y) depth ls)\n\t hClose hnd\n\n putStrLn$ \"Spot check: \" ++ show (mandelCheck ls y depth)\n", "meta": {"hexsha": "aa27098c09c0de2dd84f2e65ee25377509adc26b", "size": 2718, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/mandel.hs", "max_stars_repo_name": "tpetricek/Haskell.ParMonad", "max_stars_repo_head_hexsha": "83a64b9f4bf5f80cb254eb92fb5db61271756e9c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-01-20T05:54:40.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-20T05:54:40.000Z", "max_issues_repo_path": "examples/mandel.hs", "max_issues_repo_name": "tpetricek/Haskell.ParMonad", "max_issues_repo_head_hexsha": "83a64b9f4bf5f80cb254eb92fb5db61271756e9c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/mandel.hs", "max_forks_repo_name": "tpetricek/Haskell.ParMonad", "max_forks_repo_head_hexsha": "83a64b9f4bf5f80cb254eb92fb5db61271756e9c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0206185567, "max_line_length": 91, "alphanum_fraction": 0.5695364238, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5775056199849834}} {"text": "module BackProp (\n backPropRegression,\n backPropClassification,\n backProp,\n sgdMethod\n ) where\n\nimport Numeric.LinearAlgebra\nimport Common\nimport ActivFunc\n\nsgdMethod :: Int -> (Matrix R, Matrix R) -> ((Matrix R, Matrix R) -> [Matrix R] -> [Matrix R]) -> [Matrix R] -> IO [Matrix R]\nsgdMethod n xy f ws = do\n nxy <- pickupSets n xy\n return $ f nxy ws\n\nbackPropRegression :: R -> (Matrix R -> Matrix R, Matrix R -> Matrix R) -> (Matrix R, Matrix R) -> [Matrix R] -> [Matrix R]\nbackPropRegression = backProp id\n\nbackPropClassification :: R -> (Matrix R -> Matrix R, Matrix R -> Matrix R) -> (Matrix R, Matrix R) -> [Matrix R] -> [Matrix R]\nbackPropClassification = backProp softmaxC\n\nbackProp :: (Matrix R -> Matrix R) -> R -> (Matrix R -> Matrix R, Matrix R -> Matrix R) -> (Matrix R, Matrix R) -> [Matrix R] -> [Matrix R]\nbackProp lf rate (f, df) (x, y) ws@(m:ms) = zipWith (-) ws (fmap (scalar rate *) dws)\n where\n dws = fmap (/ len) . zipWith (<>) ds $ fmap (tr . inputWithBias) vs\n len = fromIntegral $ cols x\n vs = x : fmap f rs -- length: L - 1\n ds = calcDeltas df (zip rs ms) dInit -- length: L - 1\n dInit = lf r - y\n (rs, r) = (init us, last us)\n us = forwards' f ms uInit -- length: L - 1\n uInit = m <> inputWithBias x\n\nforwards' :: (Matrix R -> Matrix R) -> [Matrix R] -> Matrix R -> [Matrix R]\nforwards' f ws u = scanl (flip $ forward' f) u ws\n\nforward' :: (Matrix R -> Matrix R) -> Matrix R -> Matrix R -> Matrix R\nforward' f w u = w <> inputWithBias (f u)\n\ncalcDeltas :: (Matrix R -> Matrix R) -> [(Matrix R, Matrix R)] -> Matrix R -> [Matrix R]\ncalcDeltas df uws d = scanr (calcDelta df) d uws\n\ncalcDelta :: (Matrix R -> Matrix R) -> (Matrix R, Matrix R) -> Matrix R -> Matrix R\ncalcDelta df (u, w) d = df u * tr (weightWithoutBias w) <> d\n", "meta": {"hexsha": "5d4534e8bc3e135c7ecb32ea8e6d04610b082f90", "size": 1793, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/BackProp.hs", "max_stars_repo_name": "pupuu/deep-neuralnet", "max_stars_repo_head_hexsha": "c32a517194e11a40a686c07ade27517a4d728f72", "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/BackProp.hs", "max_issues_repo_name": "pupuu/deep-neuralnet", "max_issues_repo_head_hexsha": "c32a517194e11a40a686c07ade27517a4d728f72", "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/BackProp.hs", "max_forks_repo_name": "pupuu/deep-neuralnet", "max_forks_repo_head_hexsha": "c32a517194e11a40a686c07ade27517a4d728f72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9782608696, "max_line_length": 139, "alphanum_fraction": 0.6134969325, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915994285382, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.577505597827902}} {"text": "------------------------------------------------\n-- |\n-- Module : Numeric.Matrix.Integral\n-- Copyright : (c) Jun Yoshida 2019\n-- License : BSD3\n--\n-- Operations on integer matrices\n--\n------------------------------------------------\n\nmodule Numeric.Matrix.Integral (\n -- Hermite normal form\n hermiteNF,\n -- Smith normal form\n smithNF,\n smithRep,\n ) where\n\nimport Control.Monad\nimport Control.Monad.ST (ST, runST)\nimport Control.Monad.Loops (whileM_)\nimport Data.STRef\n\nimport qualified Numeric.LinearAlgebra as LA\n\n--import Numeric.Matrix.Integral.HNFLLL\n--import Numeric.Matrix.Integral.SmithNF\nimport Numeric.Matrix.Integral.NormalForms\n\n\n-- Compute the submatrix containing all the non-zero diagonal entries\nextractMaxNZDiag :: LA.Matrix LA.Z -> (Int,LA.Matrix LA.Z)\nextractMaxNZDiag mx = runST $ do\n dRef <- newSTRef 0\n let p d = d < uncurry min (LA.size mx) && (mx LA.! d LA.! d) /= 0\n whileM_ (p <$> readSTRef dRef) $ modifySTRef' dRef (+1)\n d <- readSTRef dRef\n return (d,LA.subMatrix (0,0) (d,d) mx)\n\n-- D = P <> A <> Q\n-- | Return (d,ker,im) where\n-- d: the diagonal entries of Smith normal form\n-- ker: basis for the kernel\n-- im: basis for the image\nkerImOf :: LA.Matrix LA.Z -> (LA.Vector LA.Z,[LA.Vector LA.Z],[LA.Vector LA.Z])\nkerImOf mt =\n let (ul,h,ur) = smithNF mt\n (ull,_,ulr) = smithNF ul\n (rk,dmt) = extractMaxNZDiag h\n ker' = ur LA.\u00bf [rk..(LA.cols ur-1)]\n (_,kert) = hermiteNF (LA.tr' ker')\n im' = (ulr LA.<> ull LA.<> h) LA.\u00bf [0..rk-1]\n (_,imt) = hermiteNF (LA.tr' im')\n in (LA.takeDiag dmt, LA.toRows kert, LA.toRows imt)\n", "meta": {"hexsha": "43937780266302542d76615a168a948bc34c6f3f", "size": 1596, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Matrix/Integral.hs", "max_stars_repo_name": "Junology/linkedgram", "max_stars_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-21T06:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:54:21.000Z", "max_issues_repo_path": "src/Numeric/Matrix/Integral.hs", "max_issues_repo_name": "Junology/linkedgram", "max_issues_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Matrix/Integral.hs", "max_forks_repo_name": "Junology/linkedgram", "max_forks_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0181818182, "max_line_length": 79, "alphanum_fraction": 0.6140350877, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.577449849427836}} {"text": "module EndPointMarkovChain where\n\nimport Control.Monad as M\nimport Data.Array.Repa as R\nimport Data.List as L\nimport Graphics.Gnuplot.Simple\nimport Numeric.LinearAlgebra as NL\nimport System.Directory\nimport System.Environment\nimport System.FilePath (())\nimport Text.Printf\n\n{-# INLINE splitList #-}\nsplitList :: Int -> [a] -> [[a]]\nsplitList _ [] = []\nsplitList n xs = (L.take n xs) : splitList n (L.drop n xs)\n\n{-# INLINE makeMatrix #-}\nmakeMatrix :: Int -> Double -> R.Array D DIM2 Double\nmakeMatrix n p =\n fromFunction (Z :. (2 * n) :. (2 * n)) $ \\(Z :. i :. j) ->\n let a = div i 2\n b = div j 2\n c = mod i 2\n d = mod j 2\n in if abs (a - b) == 1\n then if a == 0\n then if d == 1\n then if c == 0\n then p\n else 1\n else 0\n else if a == n - 1\n then if d == 0\n then if c == 0\n then 1\n else p\n else 0\n else if b < a\n then if d == 0\n then if c == 0\n then 1\n else p\n else if c == 0 -- 0\n then p\n else 0\n else if d == 0\n then if c == 0 -- 0\n then 0\n else p\n else if c == 0\n then p\n else 1\n else 0\n\n{-# INLINE powerMethodIO #-}\npowerMethodIO :: Matrix Double -> Vector Double -> Int -> IO (Vector Double)\npowerMethodIO mat vec n = do\n let (m,_) = NL.size mat\n x = ((inv (mat - (0.1) * ident m)) #> vec)\n maxV = sumElements x -- maxElement x\n eigenVec = x / scalar maxV\n printf \"%d: %f\\n\" n (rayleighQuotient mat eigenVec)\n printf \"%03d: %s\" n (printList . sumVec . NL.toList $ eigenVec)\n return eigenVec\n\n\n{-# INLINE powerMethod #-}\npowerMethod :: Matrix Double -> Vector Double -> (Double, Vector Double)\npowerMethod mat vec =\n let x = mat #> vec\n maxV = maxElement x\n eigenVec = x / scalar maxV\n rq = rayleighQuotient mat eigenVec\n in (rq, eigenVec)\n\n{-# INLINE sumVec #-}\nsumVec :: [Double] -> [Double]\nsumVec [] = []\nsumVec (x:y:xs) = (x + y) : sumVec xs\n\n{-# INLINE printList #-}\nprintList :: [Double] -> String\nprintList [] = \"\\n\"\nprintList (x:xs) = printf \"%.3f \" x L.++ printList xs\n\n{-# INLINE rayleighQuotient #-}\nrayleighQuotient :: Matrix Double -> Vector Double -> Double\nrayleighQuotient mat vec = vec <.> (mat #> vec) / vec <.> vec\n\n{-# INLINE inverse #-}\ninverse :: Vector Double -> Vector Double\ninverse vec = cmap (\\x -> sumElements vec - x ) vec\n\n{-# INLINE timeReverse #-}\ntimeReverse :: [a] -> [a]\ntimeReverse [] = []\ntimeReverse (x:y:xs) = y : (x : timeReverse xs)\n\n\nmain = do\n args <- getArgs\n let (nStr:aStr:mStr:_) = args\n n = read nStr :: Int\n a = read aStr :: Double\n m = read mStr :: Int\n mat = (tr . ((2 * n) >< (2 * n)) . R.toList . makeMatrix n $ a) + (0.0) * ident (2 * n)\n -- mat = NL.fromLists . timeReverse . L.map timeReverse . NL.toLists $ mat'\n vec = vector . L.take (2 * n) $ [1,1 ..]\n (eigVal', eigVec') = eig mat\n (maxEigVal, maxEigVec) =\n (\\(x, y) -> (realPart x, sumVec $ L.map realPart y)) .\n L.maximumBy (\\x y -> compare (realPart $ fst x) (realPart $ fst y)) .\n L.zip (NL.toList eigVal') . L.map NL.toList . NL.toColumns $\n eigVec'\n (maxEigVal', maxEigVec') =\n (\\(x, y) -> (realPart x, L.map realPart y)) .\n L.maximumBy (\\x y -> compare (realPart $ fst x) (realPart $ fst y)) .\n L.zip (NL.toList eigVal') . L.map NL.toList . NL.toColumns $\n eigVec'\n maxV = L.maximumBy (\\x y -> compare (abs x) (abs y)) maxEigVec\n (rqs, eigVecs) =\n L.unzip $ L.scanl' (\\(_, v) _ -> powerMethod mat v) (0, vec) [1 .. m]\n -- eigVec = L.last eigVecs\n folderPath = \"output/test/EndPointMarkovChain\"\n createDirectoryIfMissing True folderPath\n -- eigVec <- M.foldM (powerMethodIO mat) vec [1 .. m]\n -- -- print . rayleighQuotient mat $ eigVec\n -- -- putStr . printList . sumVec . NL.toList $ eigVec\n -- -- print maxEigVal\n -- -- putStr . printList . L.map (/ maxV) $ maxEigVec\n -- printf\n -- \"%.3f: %s\"\n -- (rayleighQuotient mat eigVec)\n -- (printList . sumVec . NL.toList $ eigVec)\n -- printf\n -- \"%.3f: %s\"\n -- maxEigVal\n -- -- (L.sum . L.map (/ maxV) $ maxEigVec)\n -- (printList . L.map (/ maxV) $ maxEigVec)\n -- plotPathStyle\n -- [ PNG (folderPath \"RayleighQuotient.png\")\n -- , Title (\"Rayleigh Quotient\")\n -- , XLabel \"Iteration\"\n -- ]\n -- (defaultStyle {plotType = Lines, lineSpec = CustomStyle [LineTitle \"\"]}) .\n -- L.zip [1 ..] . L.tail $\n -- rqs\n -- let m = 10\n -- croppedVec =\n -- L.take (2 * m) . L.drop (div (2 * n - 2 * m) 2) $\n -- L.map (/ maxV) $ maxEigVec'\n -- print . L.sum $ croppedVec\n M.mapM_ print .\n L.map\n (\\(x, ys) ->\n let v = L.maximumBy (\\a b -> compare (abs a) (abs b)) ys\n in (x, L.map (/ v) ys)) .\n L.map (\\(x, y) -> (realPart x, sumVec $ L.map realPart y)) .\n L.sortBy (\\x y -> compare (realPart $ fst x) (realPart $ fst y)) .\n L.zip (NL.toList eigVal') . L.map NL.toList . NL.toColumns $\n eigVec'\n -- M.mapM_ print . NL.toLists $ (mat + 1 * ident 20)\n -- M.mapM_ print . NL.toLists . inv $ (mat + 1 * ident 20)\n -- M.mapM_ print . NL.toLists $ mat - (0.017) * ident (2 * n)\n -- putStrLn \"\"\n M.mapM_ (putStr . printList) . NL.toLists $ (inv $ (mat - (0.6) * ident (2*n))) / 59.592--2261.598 --494.987 -- 4962.166\n -- (mat + 0.001 * ident 20) NL.<> (tr $ (mat + 0.001 * ident 20))\n", "meta": {"hexsha": "84cbe541ccd30e8f77d5f5a1f0ef0ad6b3c1c601", "size": 6296, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/EndPointMarkovChain/EndPointMarkovChain.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/EndPointMarkovChain/EndPointMarkovChain.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/EndPointMarkovChain/EndPointMarkovChain.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": 37.2544378698, "max_line_length": 122, "alphanum_fraction": 0.4712515883, "num_tokens": 1852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5773876388470478}} {"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module : Statistics.Distribution.Lognormal\n-- Copyright : (c) 2020 Ximin Luo\n-- License : BSD3\n--\n-- Maintainer : infinity0@pwned.gg\n-- Stability : experimental\n-- Portability : portable\n--\n-- The Weibull distribution. This is a continuous probability\n-- distribution that describes the occurrence of a single event whose\n-- probability changes over time, controlled by the shape parameter.\n\nmodule Statistics.Distribution.Weibull\n (\n WeibullDistribution\n -- * Constructors\n , weibullDistr\n , weibullDistrErr\n , weibullStandard\n , weibullDistrApproxMeanStddevErr\n ) where\n\nimport Control.Applicative\nimport Data.Aeson (FromJSON(..), ToJSON, Value(..), (.:))\nimport Data.Binary (Binary(..))\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.MathFunctions.Constants (m_eulerMascheroni)\nimport Numeric.SpecFunctions (expm1, log1p, logGamma)\nimport qualified Data.Vector.Generic as G\n\nimport qualified Statistics.Distribution as D\nimport qualified Statistics.Sample as S\nimport Statistics.Internal\n\n\n-- | The Weibull distribution.\ndata WeibullDistribution = WD {\n wdShape :: {-# UNPACK #-} !Double\n , wdLambda :: {-# UNPACK #-} !Double\n } deriving (Eq, Typeable, Data, Generic)\n\ninstance Show WeibullDistribution where\n showsPrec i (WD k l) = defaultShow2 \"weibullDistr\" k l i\ninstance Read WeibullDistribution where\n readPrec = defaultReadPrecM2 \"weibullDistr\" $\n (either (const Nothing) Just .) . weibullDistrErr\n\ninstance ToJSON WeibullDistribution\ninstance FromJSON WeibullDistribution where\n parseJSON (Object v) = do\n k <- v .: \"wdShape\"\n l <- v .: \"wdLambda\"\n either fail return $ weibullDistrErr k l\n parseJSON _ = empty\n\ninstance Binary WeibullDistribution where\n put (WD k l) = put k >> put l\n get = do\n k <- get\n l <- get\n either fail return $ weibullDistrErr k l\n\ninstance D.Distribution WeibullDistribution where\n cumulative = cumulative\n complCumulative = complCumulative\n\ninstance D.ContDistr WeibullDistribution where\n logDensity = logDensity\n quantile = quantile\n complQuantile = complQuantile\n\ninstance D.MaybeMean WeibullDistribution where\n maybeMean = Just . D.mean\n\ninstance D.Mean WeibullDistribution where\n mean (WD k l) = l * exp (logGamma (1 + 1 / k))\n\ninstance D.MaybeVariance WeibullDistribution where\n maybeStdDev = Just . D.stdDev\n maybeVariance = Just . D.variance\n\ninstance D.Variance WeibullDistribution where\n variance (WD k l) = l * l * (exp (logGamma (1 + 2 * invk)) - q * q)\n where\n invk = 1 / k\n q = exp (logGamma (1 + invk))\n\ninstance D.Entropy WeibullDistribution where\n entropy (WD k l) = m_eulerMascheroni * (1 - 1 / k) + log (l / k) + 1\n\ninstance D.MaybeEntropy WeibullDistribution where\n maybeEntropy = Just . D.entropy\n\ninstance D.ContGen WeibullDistribution where\n genContVar d = D.genContinuous d\n\n-- | Standard Weibull distribution with scale factor (lambda) 1.\nweibullStandard :: Double -> WeibullDistribution\nweibullStandard k = weibullDistr k 1.0\n\n-- | Create Weibull distribution from parameters.\n--\n-- If the shape (first) parameter is @1.0@, the distribution is equivalent to a\n-- 'Statistics.Distribution.Exponential.ExponentialDistribution' with parameter\n-- @1 / lambda@ the scale (second) parameter.\nweibullDistr\n :: Double -- ^ Shape\n -> Double -- ^ Lambda (scale)\n -> WeibullDistribution\nweibullDistr k l = either error id $ weibullDistrErr k l\n\n-- | Create Weibull distribution from parameters.\n--\n-- If the shape (first) parameter is @1.0@, the distribution is equivalent to a\n-- 'Statistics.Distribution.Exponential.ExponentialDistribution' with parameter\n-- @1 / lambda@ the scale (second) parameter.\nweibullDistrErr\n :: Double -- ^ Shape\n -> Double -- ^ Lambda (scale)\n -> Either String WeibullDistribution\nweibullDistrErr k l | k <= 0 = Left $ errMsg k l\n | l <= 0 = Left $ errMsg k l\n | otherwise = Right $ WD k l\n\nerrMsg :: Double -> Double -> String\nerrMsg k l =\n \"Statistics.Distribution.Weibull.weibullDistr: both shape and lambda must be positive. Got shape \"\n ++ show k\n ++ \" and lambda \"\n ++ show l\n\n-- | Create Weibull distribution from mean and standard deviation.\n--\n-- The algorithm is from \"Methods for Estimating Wind Speed Frequency\n-- Distributions\", C. G. Justus, W. R. Hargreaves, A. Mikhail, D. Graber, 1977.\n-- Given the identity:\n--\n-- \\[\n-- (\\frac{\\sigma}{\\mu})^2 = \\frac{\\Gamma(1+2/k)}{\\Gamma(1+1/k)^2} - 1\n-- \\]\n--\n-- \\(k\\) can be approximated by\n--\n-- \\[\n-- k \\approx (\\frac{\\sigma}{\\mu})^{-1.086}\n-- \\]\n--\n-- \\(\\lambda\\) is then calculated straightforwardly via the identity\n--\n-- \\[\n-- \\lambda = \\frac{\\mu}{\\Gamma(1+1/k)}\n-- \\]\n--\n-- Numerically speaking, the approximation for \\(k\\) is accurate only within a\n-- certain range. We arbitrarily pick the range \\(0.033 \\le \\frac{\\sigma}{\\mu} \\le 1.45\\)\n-- where it is good to ~6%, and will refuse to create a distribution outside of\n-- this range. The paper does not cover these details but it is straightforward\n-- to check them numerically.\nweibullDistrApproxMeanStddevErr\n :: Double -- ^ Mean\n -> Double -- ^ Stddev\n -> Either String WeibullDistribution\nweibullDistrApproxMeanStddevErr m s = if r > 1.45 || r < 0.033\n then Left msg\n else weibullDistrErr k l\n where r = s / m\n k = (s / m) ** (-1.086)\n l = m / exp (logGamma (1 + 1/k))\n msg = \"Statistics.Distribution.Weibull.weibullDistr: stddev-mean ratio \"\n ++ \"outside approximation accuracy range [0.033, 1.45]. Got \"\n ++ \"stddev \" ++ show s ++ \" and mean \" ++ show m\n\n-- | Uses an approximation based on the mean and standard deviation in\n-- 'weibullDistrEstMeanStddevErr', with standard deviation estimated\n-- using maximum likelihood method (unbiased estimation).\n--\n-- Returns @Nothing@ if sample contains less than one element or\n-- variance is zero (all elements are equal), or if the estimated mean\n-- and standard-deviation lies outside the range for which the\n-- approximation is accurate.\ninstance D.FromSample WeibullDistribution Double where\n fromSample xs\n | G.length xs <= 1 = Nothing\n | v == 0 = Nothing\n | otherwise = either (const Nothing) Just $\n weibullDistrApproxMeanStddevErr m (sqrt v)\n where\n (m,v) = S.meanVarianceUnb xs\n\nlogDensity :: WeibullDistribution -> Double -> Double\nlogDensity (WD k l) x\n | x < 0 = 0\n | otherwise = log k + (k - 1) * log x - k * log l - (x / l) ** k\n\ncumulative :: WeibullDistribution -> Double -> Double\ncumulative (WD k l) x | x < 0 = 0\n | otherwise = -expm1 (-(x / l) ** k)\n\ncomplCumulative :: WeibullDistribution -> Double -> Double\ncomplCumulative (WD k l) x | x < 0 = 1\n | otherwise = exp (-(x / l) ** k)\n\nquantile :: WeibullDistribution -> Double -> Double\nquantile (WD k l) p\n | p == 0 = 0\n | p == 1 = inf\n | p > 0 && p < 1 = l * (-log1p (-p)) ** (1 / k)\n | otherwise =\n error $ \"Statistics.Distribution.Weibull.quantile: p must be in [0,1] range. Got: \" ++ show p\n where inf = 1 / 0\n\ncomplQuantile :: WeibullDistribution -> Double -> Double\ncomplQuantile (WD k l) q\n | q == 0 = inf\n | q == 1 = 0\n | q > 0 && q < 1 = l * (-log q) ** (1 / k)\n | otherwise =\n error $ \"Statistics.Distribution.Weibull.complQuantile: q must be in [0,1] range. Got: \" ++ show q\n where inf = 1 / 0\n", "meta": {"hexsha": "be0f37ef598dcc184f76f8f45e84cee48f8c599b", "size": 7692, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Weibull.hs", "max_stars_repo_name": "vaerksted/statistics", "max_stars_repo_head_hexsha": "435152619b968948733672a18946794b7fd92a98", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:39:40.000Z", "max_issues_repo_path": "Statistics/Distribution/Weibull.hs", "max_issues_repo_name": "vaerksted/statistics", "max_issues_repo_head_hexsha": "435152619b968948733672a18946794b7fd92a98", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T14:21:32.000Z", "max_forks_repo_path": "Statistics/Distribution/Weibull.hs", "max_forks_repo_name": "vaerksted/statistics", "max_forks_repo_head_hexsha": "435152619b968948733672a18946794b7fd92a98", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2015-02-13T00:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:19:16.000Z", "avg_line_length": 34.1866666667, "max_line_length": 102, "alphanum_fraction": 0.6576963079, "num_tokens": 2208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5773876309398002}} {"text": "module STCR2Z1T0_1 where\n\nimport Control.Monad as M\nimport Data.Array.Repa as R\nimport Data.Binary (decodeFile)\nimport Data.Complex\nimport Data.List as L\nimport DFT.Plan\nimport FokkerPlanck.DomainChange\nimport FokkerPlanck.MonteCarlo\nimport FokkerPlanck.Pinwheel\nimport Image.IO\nimport Image.Transform\nimport STC.CompletionField\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Types\nimport Utils.Array\n\nmain = do\n args@(numPointStr:numOrientationStr:sigmaStr:taoStr:lenStr:initStr:numTrailStr:maxTrailStr:theta0FreqsStr:thetaFreqsStr:initDistStr:histFilePath:alphaStr:pinwheelFlagStr:numThreadStr:_) <-\n getArgs\n print args\n let numPoint = read numPointStr :: Int\n numOrientation = read numOrientationStr :: Int\n sigma = read sigmaStr :: Double\n tao = read taoStr :: Double\n len = read lenStr :: Int\n init = read initStr :: (Double, Double, Double, Double, Double, Double)\n numTrail = read numTrailStr :: Int\n maxTrail = read maxTrailStr :: Int\n theta0Freq = read theta0FreqsStr :: Double\n theta0Freqs = [-theta0Freq .. theta0Freq]\n thetaFreq = read thetaFreqsStr :: Double\n thetaFreqs = [-thetaFreq .. thetaFreq]\n initDist = read initDistStr :: [R2S1RPPoint]\n alpha = read alphaStr :: Double\n pinwheelFlag = read pinwheelFlagStr :: Bool\n numThread = read numThreadStr :: Int\n sourceDist = L.take 1 initDist\n sinkDist = L.drop 1 initDist\n folderPath = \"output/test/STCR2Z1T0_1\"\n flag <- doesFileExist histFilePath\n arrR2Z1T0' <-\n if pinwheelFlag\n then computeR2Z1T0Array numPoint numPoint alpha thetaFreqs theta0Freqs\n else if flag\n then getNormalizedHistogramArr <$> decodeFile histFilePath\n else solveMonteCarloR2Z1T0\n numThread\n numTrail\n maxTrail\n numPoint\n numPoint\n sigma\n tao\n len\n theta0Freqs\n thetaFreqs\n histFilePath\n (emptyHistogram\n [ numPoint\n , numPoint\n , L.length theta0Freqs\n , L.length thetaFreqs\n ]\n 0)\n let arrR2Z1T0 =\n computeUnboxedS .\n pad [numPoint, numPoint, L.length theta0Freqs, L.length thetaFreqs] 0 .\n downsample [2, 2, 1, 1] $\n arrR2Z1T0'\n createDirectoryIfMissing True folderPath\n plan <- makeR2Z1T0Plan emptyPlan arrR2Z1T0\n sourceDistArr <-\n computeInitialDistributionR2Z1T0\n plan\n numPoint\n numPoint\n thetaFreqs\n theta0Freqs\n sourceDist\n sinkDistArr <-\n computeInitialDistributionR2Z1T0\n plan\n numPoint\n numPoint\n thetaFreqs\n theta0Freqs\n sinkDist\n arrR2Z1T0F <- dftR2Z1T0 plan . makeFilterR2Z1T0 $ arrR2Z1T0\n arrR2Z1T0TRF <-\n dftR2Z1T0 plan . makeFilterR2Z1T0 . timeReverseR2Z1T0 thetaFreqs theta0Freqs $\n arrR2Z1T0\n -- Source field\n sourceArr <- convolveR2Z1T0 plan arrR2Z1T0F sourceDistArr\n sourceR2 <- R.sumP . R.sumS . rotate4D . rotate4D $ sourceArr\n let sourceField =\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) $ sourceR2\n plotImageRepaComplex (folderPath \"Source.png\") . ImageRepa 8 $ sourceField\n -- Sink field\n sinkArr <- convolveR2Z1T0 plan arrR2Z1T0TRF sinkDistArr\n sinkR2 <- R.sumP . R.sumS . rotate4D . rotate4D $ sinkArr\n let sinkField = computeS . R.extend (Z :. (1 :: Int) :. All :. All) $ sinkR2\n plotImageRepaComplex (folderPath \"Sink.png\") . ImageRepa 8 $ sinkField\n -- Completion Filed\n completionFiled <- convolveR2Z1' plan thetaFreqs theta0Freqs sourceArr sinkArr\n completionFiledR2 <- R.sumP . R.sumS . rotate4D . rotate4D $ completionFiled\n plotImageRepa (folderPath \"Completion.png\") .\n ImageRepa 8 .\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.map magnitude $\n completionFiledR2\n", "meta": {"hexsha": "4b57c259f2a19bad66de9c976b9aa7d7460b8dd9", "size": 4261, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2Z1T0_1.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/STCR2Z1T0_1.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/STCR2Z1T0_1.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": 37.3771929825, "max_line_length": 190, "alphanum_fraction": 0.6139403896, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5773876291545463}} {"text": "module IQ where\n\nimport Data.Complex\n\ntype IQ = Complex Float\n", "meta": {"hexsha": "1b4bdd866ac65fadb836602ade55842280f979a8", "size": 62, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/IQ.hs", "max_stars_repo_name": "hexagonal-sun/ayeQ", "max_stars_repo_head_hexsha": "0dd484287ed785109867db4a06d1861cabb04062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-25T11:41:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T11:41:05.000Z", "max_issues_repo_path": "src/IQ.hs", "max_issues_repo_name": "hexagonal-sun/ayeQ", "max_issues_repo_head_hexsha": "0dd484287ed785109867db4a06d1861cabb04062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IQ.hs", "max_forks_repo_name": "hexagonal-sun/ayeQ", "max_forks_repo_head_hexsha": "0dd484287ed785109867db4a06d1861cabb04062", "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": 10.3333333333, "max_line_length": 23, "alphanum_fraction": 0.7741935484, "num_tokens": 15, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5772823222247634}} {"text": "{-# LANGUAGE DataKinds, ExistentialQuantification, FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TypeSynonymInstances #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Numeric.Algebra.Ring.Noetherian (Noetherian) where\nimport qualified Data.Complex as C\nimport Data.Function\nimport Data.Ord\nimport Data.Ratio\nimport Numeric.Algebra\nimport qualified Numeric.Algebra.Complex as NA\nimport Numeric.Algebra.Instances\nimport Prelude hiding (negate, subtract, (*), (+),\n (-))\nimport qualified Prelude as P\n-- | Noetherian ring (i.e. every ideal is finitely generated).\nclass (Commutative r, Ring r) => Noetherian r where\n\ninstance Noetherian Int where\n\ninstance Noetherian Integer where\n\ninstance (Commutative (NA.Complex r), Ring (NA.Complex r)) => Noetherian (NA.Complex r) where\ninstance (Commutative (C.Complex r), Ring (C.Complex r)) => Noetherian (C.Complex r) where\ninstance Integral n => Noetherian (Ratio n)\n\n", "meta": {"hexsha": "d1dca2025897e9df4b118e480921b17161c786b3", "size": 1182, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Algebra/Ring/Noetherian.hs", "max_stars_repo_name": "konn/algebra-extras", "max_stars_repo_head_hexsha": "40eb53fd84de278508e288c01fdd44d68c3b4689", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-05T09:46:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T09:46:01.000Z", "max_issues_repo_path": "src/Numeric/Algebra/Ring/Noetherian.hs", "max_issues_repo_name": "konn/algebra-extras", "max_issues_repo_head_hexsha": "40eb53fd84de278508e288c01fdd44d68c3b4689", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Algebra/Ring/Noetherian.hs", "max_forks_repo_name": "konn/algebra-extras", "max_forks_repo_head_hexsha": "40eb53fd84de278508e288c01fdd44d68c3b4689", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7777777778, "max_line_length": 93, "alphanum_fraction": 0.6370558376, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5772823126146179}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule BPTT where \n\nimport Control.Monad\nimport Control.Monad.Random\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Singletons\nimport Data.Singletons.Prelude\nimport Data.Singletons.TypeLits\nimport GHC.Show\nimport Numeric (showIntAtBase)\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Static\n\n-- dependently typed weights\ndata Weights i o = W {\n wBiases :: !(R o) \n , wNodes :: !(L o i)\n }\n\n-- an simple 3-layer RNN, including one recurrent layer,\n-- is not like the Network type discussed in Justin Le's \n-- blog series (because not all layers are just stacked\n-- one on top of the other.)\n-- Instead:\ndata RNN i h o = MkRNN {\n getU :: !(Weights i h)\n , getW :: !(Weights h h) \n , getV :: !(Weights h o)\n }\n\n-- If one were to leverage a.g. ad the Hackage library for \n-- autodifferentiable functions, then functions being used for\n-- activation could be provided in a symbolic form amenable to\n-- being automatically differentiated (for use in the backprop\n-- process.) Instead, each activation function used & its derivative\n-- are provided separately.\n\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n\nlogistic' :: Floating a => a -> a\nlogistic' x = logix * (1 - logix)\n where\n logix = logistic x\n\nsoftmax :: KnownNat v => R v -> R v \nsoftmax v = \n let vexp = exp v \n in vexp / (konst $ norm_1 vexp)\n\n-- The formula for the (x, y)-entry of softmax',\n-- which is a matrix, is \n--\n-- softmax'[x, y] = -softmax[x] * softmax[y], x /= y\n-- (1-softmax[x]) * softmax[y], x == y\n--\n-- which is the same as adding the vector \n-- 'softmax v' diagonally down the negative of \n-- said vector's outer product with itself.\n-- I would prefer to build this using 'build', but \n-- I don't know how right now.\nsoftmax' :: KnownNat v => R v -> L v v \nsoftmax' v = \n let s = softmax v \n in (diag s) + konst (-1) * (s `outer` s)\n\n-- runLayer is for performing the linear mapping\n-- due to a particular layer's set of parameters,\n-- on an appropriately sized vector\nrunLayer :: (KnownNat i, KnownNat o) \n => Weights i o \n -> R i -> R o \nrunLayer (W wB wN) v_in = \n wB + wN #> v_in\n\n-- Verbose 'run RNN', for exposing all intermediate computations.\n-- (R i, R h, R h, R o, R o)\n-- x_t h_t-1 h_t z_t y_t \n\n-- runRNN can be expressed in terms of this, if I locate / find \n-- generalized tuple accessors\nrunRNN_verbose :: (KnownNat i, KnownNat h, KnownNat o)\n => RNN i h o\n -> R i -> R h \n -> (R i, R h, R h, R o, R o)\nrunRNN_verbose (MkRNN rnn_U rnn_W rnn_V) \n x_t h_t_1 = \n let h_t = logistic $ \n -- recurrent parameters, weighting the prior hidden state\n (runLayer rnn_W h_t_1) + \n -- input parameters, weighting the current input\n (runLayer rnn_U x_t)\n -- output parameters, weighting the current hidden state\n z_t = runLayer rnn_V h_t \n -- the final activation provides the prediction \n y_t = logistic z_t \n in (x_t, h_t_1, h_t, z_t, y_t) \n\n-- Forward phase of training an RNN.\n-- No adjustments to the parameters (weights) are made.\n-- Instead, foldl is used to accumulate a list of tuples,\n-- each tuple bearing all input, intermediate and output vectors\n-- for one of the steps (t := 1, 2, ..., n) in the forward direction.\nforward_phase :: (KnownNat i, KnownNat h, KnownNat o)\n => RNN i h o -- RNN\n -> [(R i, R o)] -- list of training inputs paired with target outputs\n -> R h -- initial hidden state\n\n -- All tuples of resulting vectors, from every step carried out:\n -- For t ranging from 1 to n, n the number of training samples:\n -> [( R i, -- x_t\n R h, -- h_t-1\n R h, -- h_t\n R o, -- z_t\n R o, -- y_t\n R o)] -- tgt_t\nforward_phase \n rnn \n pairs \n h_0 = \n snd $ foldl unroll (h_0, []) pairs\n where \n -- unroll :: (R h, [(R i, R h, R h, R o, R o, R o)]) -> (R i, R o)\n -- -> (R h, [(R i, R h, R h, R o, R o, R o)])\n\n unroll (h_t_1, results) pair@(x_t, tgt_t) = \n -- ^ tgt_t plays no role in the forward direction,\n -- but we pattern-match on it so that we can re-package it\n -- up into this step's tuple for the result list\n let result@(_, _, h_t, z_t, y_t) = runRNN_verbose rnn x_t h_t_1 \n in (h_t, results ++ [(x_t, h_t_1, h_t, z_t, y_t, tgt_t)]) \n\n-- Backward phase of training an RNN.\n-- Backpropagation is required.\n-- There's a lot that goes into backprop!\n-- (Basically, everything that is used or \n-- produced at any point in the forward step.)\nbackward_phase :: (KnownNat i, KnownNat h, KnownNat o)\n => RNN i h o -- an RNN to train\n\n -- All tuples of resulting vectors, from every step carried out:\n -- For t ranging from 1 to n, n the number of training samples:\n -> [( R i, -- x_t\n R h, -- h_t-1\n R h, -- h_t\n R o, -- z_t\n R o, -- y_t\n R o)] -- tgt_t\n\n -- At every step #t of BPTT, there are *two* sources of \"delta-h_t\" the bump\n -- to h_t required for the sake of trying to bump down the error at that same step:\n -- a) a bump due to what W is at the current time, \"delta-h given W\", and\n -- b) a bump *propagated backwards* from the next step #(t+1).\n -- But in the base case, this dh_t_dh_t' is chosen as 0 (because it's undefined.)\n\n -- Note the *symmetry* with forward_phase:\n -- just as we 'primed' forward_phase with an initial hidden state, h_0 : 0,\n -- we also 'prime' backward_phase with an initial back-prop'ed dh, dh_n_dh_n' : 0.\n -> R h -- dh_n_dh_n'\n\n -> Double -- a training rate\n -> RNN i h o -- the trained RNN\nbackward_phase rnn intermediates dh_n_dh_n' rate =\n snd $ foldr bptt (dh_n_dh_n', rnn) intermediates \n where \n -- -- A BPTT step (at time t) consumes the following data:\n -- -- x_t, h_t, h_t_1, z_t, y_t, tgt_t\n -- bptt :: (R i, R h, R h, R o, R o, R o)\n -- -- It also \"accumulates\" by swapping out,\n -- -- based upon time-t data , rnn\n -- -> (R h, RNN i h o)\n -- -- the time-(t-1) data , rnn';\n -- -- in this way, the rnn' \"accumulates\" training bumps to the parameters\n -- -> (R h, RNN i h o)\n \n bptt (x_t, h_t, h_t_1, z_t, y_t, tgt_t) \n (dh_t_dh_t', MkRNN \n -- We'll pattern match into each Weights term u, w, v for convenience \n -- later in deriving the desired infinitesimal bumps.\n u@(W uB uN) \n w@(W wB wN) \n v@(W vB vN)) = \n -- We are hard-coding the use of squared-error for the error function:\n -- e(y_t) := (y_t - tgt_t) ^ 2\n -- whose derivative with respect to the pre-activation z_t is:\n\n {-\n de/dz = de/dy * dy/dz\n = (e' at y_t) * (y' at z_t)\n = 2 (y_t - tgt_t) * (logistic' z_t)\n These 2 factors appear (in reverse order) as 'dedz' below;\n the factor of 2 is discarded & we defer all control of the \n desired training rate to the scalar input param 'rate'.\n -}\n let dedz = logistic' z_t * (y_t - tgt_t)\n -- = softmax' z_t #> (y_t - tgt_t)\n\n {-\n Informally:\n dedz is a vector that reports, \n for a unit \"nudge\" to each component z_t(j) -> \n size / direction of resulting \"nudge\" for error component e_t(j).\n The choice of dz_t below corresponds to the following training strategy:\n a) bump each z-component in the direction that will *decrease* its \n matching e-component (thus, factor of '-1')\n b) but re-scaled based on the learning rate desired (thus, 'scale rate')\n -}\n dz_t = -1 * konst rate * dedz \n \n {-\n Informally:\n Having set out to make these infinitesimal changes to the z_t components,\n we need to figure out \n what changes to V, *given* what h_t is, and\n what changes to h_t, *given* what V is\n will help us accomplish that.\n\n Observe that \n z = vN h + vB \n therefore (product rule on 1st summand)\n dz = (dvN h) + (vN dh) + dvB\n\n we do *not* try to formally solve for dvN, dh, dvB in here, but rather use these\n as instructions for how to recombine the vectors dz_t / h_t and matrix V\n so as to arrive at dvN_h (\"bump to v's matrix part, given h\") and \n dh_vN (\"bump to h, given v's matrix part\").\n\n As for v's bias-vector part, vB, we simply nudge it directly by the dz (z-nudge)\n we worked out above. Why? Look at the infinitesimals equation above - a nudge \n dvB performed on the bias vector will show up directly in dz.\n -}\n dvB = dz_t\n {-\n Instead of trying to solve for dvN, dimensional considerations lead us to this formula\n for dvN in terms of dz_t, h_t:\n vN goes from h-vectors to o-vectors; i.e. o * h -matrix\n h_t an h-vector\n dz_t an o-vector\n so the way to combine these to get a \"bumps matrix\" compatible with vN is\n dz_t `outer` h_t <- \"column\" o-vector times \"row\" h-vector\n -}\n dvN_h = dz_t `outer` h_t \n {-\n Similar to the above, but for building a \"bumps h-vector\" out of o * h matrix \n and o-vector.\n -}\n dh_vN = tr vN #> dz_t \n {-\n See the note in the type signature of 'backward_phase' about the 2 sources of \n training bumps to h_t at every step t.\n Read dh_t_dh_t' as (bump to h at current time t,\n propped backwards from bump to h at future time t+1)\n -}\n dh_t = dh_vN + dh_t_dh_t' \n\n -- Having now characterized in what way we are going to bump the \n -- entries in the current hidden state h_t, so as to achieve\n -- a desired reduction in error (i.e. dh_t), we now use it to\n -- determine how we should modify the intermediate preactivation,\n -- calling it q, q_t := (W * h_t_1 + U * x_t) to achieve the same goal:\n\n -- de / dq = (de / dh) * (dh / dq) -- chain rule\n -- = dh_t * (dh / dq) -- back propagation\n -- = dh_t * (g' at q) -- h is the activation (g) of q\n\n dedq = dh_t * logistic' q \n where q = runLayer w h_t_1 + runLayer u x_t \n \n -- and work out a desired perturbation to q, based upon scaling dedq \n dq_t = (-1) * konst rate * dedq \n\n {-\n q = W * h_t_1 + U * x_t\n dq = (dW * h_t_1) + (W * dh_t_1) \n + (dU * x_t) + [the term in dx_t -> 0, since x constant]\n -}\n\n {-\n Recurrent contribution to time-t hidden state:\n q_t = wN h_t_1 + wB + ...\n dq_t = (dwN h_t_1) + (wN dh_t_1) + dwB + ...\n -}\n dwB = dq_t\n -- dq_t and h_t_1 both happen to be h-vectors having the same\n -- dimensionality, so here the driving intuition is that such\n -- \"matrix-bumps\" take the form [destination] `outer` [origin]\n dwN_h = dq_t `outer` h_t_1\n\n -- This is what will be given back from the current fold instance\n -- to the next one \n dh_t_1_dh_t = tr wN #> dq_t \n {-\n Input contribution to time-t hidden state:\n q_t = ... + uN x_t + uB \n dq_t = ... + (duN x_t) + (uN dx_t) + duB\n = ... + (duN x_t) + ZERO + duB\n -- ^ x_t, the training inputs, are constant!\n -}\n duB = dq_t \n duN_x = dq_t `outer` x_t\n\n\n -- Don't forget to apply all the RNN-training nudges!\n vB' = vB + dvB\n vN' = vN + dvN_h\n wB' = wB + dwB\n wN' = wN + dwN_h\n uB' = uB + duB\n uN' = uN + duN_x\n\n in (dh_t_1_dh_t, MkRNN (W uB' uN') \n (W wB' wN') \n (W vB' vN')) \n\n{-\n Making some simple training data. \n\n Here's a simple sentential grammar for producing \"sentences\"\n of ints, that later can go in an overall \"document\":\n\n ::= \n ::= a multiple of 20, 20 * s, for some s : 1 <= s <= 10\n ::= a sequence of l integers, for some l : 0 <= l <= 10\n that are derived from the sentence-start as \n s - m, (s - m) + n, (s - m + n) - m, (s - m + n - m) + n, ...\n for some choice of parameters m, n : 1 <= m, n <= 5\n ::= a multiple of 17, 17 * f, for some f : 1 <= f <= 10\n-}\n\n-- Generate a \"biarithmetic\" sequence for sentence-middle, given \n-- a base number s, a down size m, an up size n \nbiarithmetic :: Int -> Int -> Int -> [Int]\nbiarithmetic s m n = concat $ \n [ [ s - (j * m) + (k * n) | k <- [j-1 .. j] ] \n | j <- [1..] ]\n\n-- For use as a multiple of 20\ngenStartParam :: MonadRandom m => m Int \ngenStartParam = getRandomR (3, 10)\n\n-- For use as a mid-sequence length \ngenMiddleLenParam :: MonadRandom m => m Int \ngenMiddleLenParam = getRandomR (0, 10)\n\n-- For use as the down size and up size of a biarithmetic sequence\ngenMiddleDownUpParams :: MonadRandom m => m (Int, Int)\ngenMiddleDownUpParams = do \n m <- getRandomR (1, 5)\n n <- getRandomR (1, 5)\n return (m, n)\n\n-- For use as a multiple of 17\ngenFinishParam :: MonadRandom m => m Int \ngenFinishParam = getRandomR (1, 10)\n\n-- For use as a number of \"sentences\".\ngenSentenceCount :: MonadRandom m => m Int \ngenSentenceCount = getRandomR (500, 1000)\n\ntype Sentence = [Int]\n\ngenSentence :: MonadRandom m => m Sentence \ngenSentence = do \n -- 1. Get sentence-start\n s <- genStartParam\n let sent_0 = s * 20 \n -- 2. Get sentence-middle length\n l <- genMiddleLenParam\n -- 3. Get sentence up & down size params\n (m, n) <- genMiddleDownUpParams\n -- 4. Get sentence-middle\n let sent_mid = take l $ biarithmetic sent_0 m n \n -- 5. Get sentence-finish\n f <- genFinishParam\n let sent_f = f * 17\n -- 6. Return random sentence\n return (sent_0 : sent_mid ++ [sent_f])\n\ntype Document = [Sentence]\n\ngenDocument :: MonadRandom m => m Document \ngenDocument = do\n -- 1. Get number of sentences\n sent_count <- genSentenceCount\n -- 2. For as many sentences as 'sent_count', generate one \n -- random sentence each & then combine the results inside\n -- MonadRandom context\n let rand_sent_stream = repeat genSentence\n sentences <- sequenceA $ take sent_count rand_sent_stream\n return sentences \n\n{-\n Now that we have a way of generating \"documents\" made up out of \n numerical \"sentences\", we need to convert this into a form that\n would be characteristically used to train a neural net.\n Convert each integer to a (possibly sparse) vector. How? \n Every integer present in a (d :: Document) should always lie\n within the range (0 <= j <= 256), so we could use a binary representation\n taking up 8 bits (tossing in an extra 2 to get 10, for good measure)\n-}\n\n-- The full source module citation is probably forgivable if I only do it this once.\n-- Best practice is to 'import qualified' with an alias intToVector :: Int -> R 10 \nintToVector m = \n let binary_string = reverse $ showIntAtBase 2 intToDigit m \"\" -- :: [Char]\n binary_padded = binary_string ++ \n (take (10 - length binary_string) $ repeat '0')\n doubles_list = (fromIntegral . digitToInt) <$> binary_padded\n doubles_vect = Numeric.LinearAlgebra.Static.fromList doubles_list\n in doubles_vect\n\n-- The other way round, for casting RNN predictions back into Int's.\n-- This is unsafe in case the entries of any y_t end up rounding to\n-- numbers other than 0, 1.\n-- (Does the hmatrix API support a more direct way of casting from\n-- R 10 to the list of rounded numbers?)\nvectorToInt :: R 10 -> Int \nvectorToInt v = \n let bins = (fmap toInteger) <$> LA.toList \n $ LA.toZ \n $ LA.roundVector \n $ extract v \n in fromIntegral $ \n foldr (\\p@(bit, power) total -> \n bit * power + total) \n 0\n (zip bins [ 2^j | j <- [0..] ])\n\nzero_vec :: KnownNat n => R n\nzero_vec = 0\n\n-- via Justin Le's blog series on neural nets\nrandomWeights :: (MonadRandom m, KnownNat i, KnownNat o)\n => m (Weights i o)\nrandomWeights = do\n s1 :: Int <- getRandom\n s2 :: Int <- getRandom\n let wB = randomVector s1 Uniform * 2 - 1\n wN = uniformSample s2 (-1) 1\n return $ W wB wN\n\nrandomRNN :: (MonadRandom m, KnownNat i, KnownNat h, KnownNat o)\n => m (RNN i h o)\nrandomRNN = \n (pure MkRNN) <*> randomWeights\n <*> randomWeights\n <*> randomWeights\n\ntrainRNN :: (KnownNat i, KnownNat h, KnownNat o) \n => RNN i h o -- an RNN \n -> [(R i, R o)] -- the training data: pairs of inputs & training outputs\n -> Double \n -> RNN i h o -- an RNN with trained parameters\ntrainRNN rnn train_data rate = \n let intermediates = forward_phase rnn train_data zero_vec \n trained = backward_phase rnn intermediates zero_vec rate\n in trained\n\n-- Before re-formatting into a vector form suitable for use \n-- in training, we have Document ~ [Sentence] ~ [[Int]];\n-- now, turn each Int into a binary-repr vector, R 10\ngenSampleData :: MonadRandom m => m [[ R 10 ]]\ngenSampleData = do \n doc <- genDocument \n return $ (intToVector <$>) <$> doc\n\n-- Every sentence (sublist) in the document (list of lists) will\n-- furnish one sequence of training data for the RNN to \"unfold\"\n-- over and perform BPTT on. So, BPTT is performed once per sentence\n-- in the document overall.\npairEachWithNext :: [x] -> [(x, x)]\npairEachWithNext xs = \n zip (init xs) (tail xs)\n\n-- In the special case of an 'RNN i h o' where o = i,\n-- we can pipe back a prediction y_t due to x_t and an\n-- initial state h, to furnish the next x_(t+1) for further\n-- predictions. We'll use this to observe the way that a\n-- trained RNN behaves.\nrnnStep :: (KnownNat i, KnownNat h) \n => RNN i h i\n -> (R h, R i)\n -> (R h, R i)\nrnnStep rnn (h_t_1, x_t) = \n let full_output = runRNN_verbose rnn x_t h_t_1 \n third five@(_, _, x3, _, _) = x3 \n fifth five@(_, _, _, _, x5) = x5 \n in (third full_output, fifth full_output)\n\ngetDocumentIO :: IO Document \ngetDocumentIO = evalRandIO genDocument\n\ntakePredictions :: (KnownNat i, KnownNat h) \n => RNN i h i\n -> (R h, R i)\n -> Int \n -> [R i]\ntakePredictions rnn (h_0, x_1) n = \n let hxs_stream = take (n+1) $ iterate (rnnStep rnn) (h_0, x_1)\n in snd <$> hxs_stream\n\ntakePredsFromN :: KnownNat h\n => RNN 10 h 10\n -> Int -- word of a sentence\n -> Int -- number of predictions\n -> [R 10]\ntakePredsFromN rnn x_1 n = \n takePredictions rnn (zero_vec, intToVector x_1) n\n\ntrainRNNOnSentence :: KnownNat h\n => RNN 10 h 10 \n -> Sentence\n -> Double \n -> RNN 10 h 10 \ntrainRNNOnSentence rnn sent rate = \n let training_data = pairEachWithNext (intToVector <$> sent)\n in trainRNN rnn training_data rate \n\n-- trainRNNOnDocument has to be structured like a fold\n-- so that the trained RNN due to each sentence can be \n-- passed to the following sentence (at the same time,\n-- I think that hidden state \"restarts\" with the beginning\n-- of a new sentence.)\ntrainRNNOnDocument :: KnownNat h\n => RNN 10 h 10 \n -> Document \n -> Double \n -> RNN 10 h 10 \ntrainRNNOnDocument rnn sents rate = \n foldl (\\rnn sent -> trainRNNOnSentence rnn sent rate)\n rnn \n sents\n\nobserveUntrainedPredictions :: Int -- initial word\n -> Int -- number of predictions\n -> IO () -- action printing info to console\nobserveUntrainedPredictions n_0 num = do \n -- get an RNN of random parameters \n putStrLn \"Getting a random RNN ...\"\n (rnn :: RNN 10 300 10) <- evalRandIO randomRNN\n -- get a series of predictions from the untrained RNN\n putStrLn $ \"Producing: \" ++ show num ++ \n \" predictions, starting from: \" ++ show n_0\n let vs = takePredsFromN rnn n_0 num \n let ns = vectorToInt <$> vs \n putStrLn \"The RNN has predicted: \"\n print ns\n\nobserveTrainedPredictions :: Int -- initial word\n -> Int -- number of predictions\n -> Double -- learning rate\n -> IO () -- action printing info to console\nobserveTrainedPredictions n_0 num rate = do \n -- get an RNN of random parameters \n putStrLn \"Getting a random RNN ...\"\n (rnn :: RNN 10 300 10) <- evalRandIO randomRNN\n -- get a random document\n putStrLn \"Getting a random document to train on ...\"\n document <- evalRandIO genDocument\n -- train RNN on the document\n putStrLn \"Training the RNN on the document ...\"\n let rnn' = trainRNNOnDocument rnn document rate \n -- get a series of predictions from the trained RNN\n putStrLn $ \"Producing: \" ++ show num ++ \n \" predictions, starting from: \" ++ show n_0 ++\n \" and using a trained RNN\"\n let vs = takePredsFromN rnn' n_0 num \n let ns = vectorToInt <$> vs \n putStrLn \"The trained RNN has predicted: \"\n print ns\n\nobserveUntrainedVsTrained :: Int -- initial word\n -> Int -- number of predictions\n -> Double -- learning rate\n -> IO () -- action printing info to console\nobserveUntrainedVsTrained n_0 num rate = do \n -- get an RNN of random parameters \n putStrLn \"Getting a random RNN ...\"\n (rnn :: RNN 10 300 10) <- evalRandIO randomRNN\n -- get a series of predictions from the untrained RNN\n putStrLn $ \"Producing: \" ++ show num ++ \n \" predictions, starting from: \" ++ show n_0\n let vs = takePredsFromN rnn n_0 num \n let ns = vectorToInt <$> vs \n putStrLn \"The RNN has predicted: \"\n print ns\n -- get a random document\n putStrLn \"Getting a random document to train on ...\"\n document <- evalRandIO genDocument\n -- train RNN on the document\n putStrLn \"Training the RNN on the document ...\"\n let rnn' = trainRNNOnDocument rnn document rate \n -- get a series of predictions from the trained RNN\n putStrLn $ \"Producing: \" ++ show num ++ \n \" predictions, starting from: \" ++ show n_0 ++\n \" and using a trained RNN\"\n let vs' = takePredsFromN rnn' n_0 num \n let ns' = vectorToInt <$> vs' \n putStrLn \"The trained RNN has predicted: \"\n print ns'\n\n\n\n", "meta": {"hexsha": "8169339d24204bff756ed9c7e5a86a19eef9dbd2", "size": 25140, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/BPTT.hs", "max_stars_repo_name": "enlambdment/ffnn-vs-rnn", "max_stars_repo_head_hexsha": "ed2aa21d4eb6a598b14105c131baf00669c81135", "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/BPTT.hs", "max_issues_repo_name": "enlambdment/ffnn-vs-rnn", "max_issues_repo_head_hexsha": "ed2aa21d4eb6a598b14105c131baf00669c81135", "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/BPTT.hs", "max_forks_repo_name": "enlambdment/ffnn-vs-rnn", "max_forks_repo_head_hexsha": "ed2aa21d4eb6a598b14105c131baf00669c81135", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8780487805, "max_line_length": 105, "alphanum_fraction": 0.5437549722, "num_tokens": 6645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5772823070950949}} {"text": "module Marvin.API.Algorithms.Internal.GradientDescentSpec where\n\nimport Test.Hspec\n\nimport Marvin.API.Algorithms.Internal.GradientDescent hiding (learningRate)\nimport qualified Marvin.API.Algorithms.Internal.GradientDescent as GD\n\nimport Marvin.API.Fallible\nimport Marvin.API.Table.Internal\nimport Marvin.Test.TestUtils\n\nimport qualified Numeric.LinearAlgebra as LA\n\n-- todo lambda, addIntercept\nspec :: Spec\nspec =\n describe \"gradient descent\" $ do\n it \"computes cost\" $\n (linearRegressionCost fm rv tt) `shouldSatisfy` (isAround 50.376562500000006) . fst\n it \"does linear regression with lin.alg. lib\" $\n (let theta = gradientDescent gradDesc fm rv in\n ((fst . linearRegressionCost fm rv) theta, theta))\n `shouldSatisfy` \\(cost, theta) ->\n cost `isAround` 0.293648087854516 &&\n theta `isAround` (LA.fromList expectedTheta)\n where\n tt = initModelParams gradDesc fm rv\n fm = addInterceptFeature $ LA.fromRows $ fmap LA.vector xData\n rv = LA.vector yData\n xData = map init trainMatrix\n yData = map last trainMatrix\n gradDesc = defaultGradientDescent {\n numIter = 30000\n , GD.learningRate = 0.005\n , cost = linearRegressionCost\n , lambda = 0\n , addIntercept = False\n }\n expectedTheta =\n [13.781001191549892,\n 3.900308511353248e-2,\n -8.360245732382168e-2,\n 2.8699265280611834e-2,\n 2.7797762929208453e-2,\n 0.13913675368346703,\n 3.900308511353248e-2,\n 0.11340373429004338,\n 0.1166082670688832,\n 4.446542254295697e-2,\n 0.14211000816593214,\n 4.446542254295697e-2]\n", "meta": {"hexsha": "5d281aae0a927825a358a3f5a4d4bd5cf6609101", "size": 1614, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test-suite/Marvin/API/Algorithms/Internal/GradientDescentSpec.hs", "max_stars_repo_name": "gaborhermann/marvin", "max_stars_repo_head_hexsha": "5c616709f0645d4b1f13caa20820a39ee31774de", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-04-18T09:46:00.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-18T09:46:00.000Z", "max_issues_repo_path": "test-suite/Marvin/API/Algorithms/Internal/GradientDescentSpec.hs", "max_issues_repo_name": "gaborhermann/marvin", "max_issues_repo_head_hexsha": "5c616709f0645d4b1f13caa20820a39ee31774de", "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": "test-suite/Marvin/API/Algorithms/Internal/GradientDescentSpec.hs", "max_forks_repo_name": "gaborhermann/marvin", "max_forks_repo_head_hexsha": "5c616709f0645d4b1f13caa20820a39ee31774de", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-02T11:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-02T11:45:45.000Z", "avg_line_length": 31.0384615385, "max_line_length": 89, "alphanum_fraction": 0.6995043371, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5770440102521254}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE Strict #-}\nmodule FourierPinwheel.AsteriskGaussian where\n\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Generic as VG\nimport Data.Vector.Storable as VS\nimport Data.Vector.Unboxed as VU\nimport DFT.Plan\nimport Filter.Utils\nimport FourierPinwheel.Array\nimport FourierPinwheel.Hypergeo1F1\nimport Math.Gamma\nimport Pinwheel.FourierSeries2D\nimport Utils.Distribution\nimport Utils.Parallel\n\n\n-- The envelope in R2 is r ^ alpha, where -2 < alpha < -0.5\n{-# INLINE asteriskGaussian #-}\nasteriskGaussian ::\n ( VG.Vector vector (Complex e)\n , RealFloat e\n , NFData (vector (Complex e))\n , Gamma (Complex e)\n , Unbox e\n )\n => Int\n -> Int\n -> e\n -> e\n -> e\n -> e\n -> [vector (Complex e)]\nasteriskGaussian numR2Freqs thetaFreq alpha periodR2 periodEnv std =\n parMap\n rdeepseq\n (\\angularFreq ->\n let arr =\n R.map\n (* (sqrt (pi / std) *\n exp (fromIntegral angularFreq ^ 2 / (-4) / std) :+\n 0)) .\n centerHollowArray numR2Freqs $\n analyticalFourierCoefficients1\n numR2Freqs\n 1\n angularFreq\n 0\n alpha\n periodR2\n periodEnv\n in VG.convert . toUnboxed . computeS $ arr)\n [-thetaFreq .. thetaFreq]\n\n{-# INLINE asteriskGaussianEnvelope #-}\nasteriskGaussianEnvelope ::\n (R.Source s (Complex Double))\n => DFTPlan\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> R.Array s DIM2 (Complex Double)\n -> IO (VS.Vector (Complex Double))\nasteriskGaussianEnvelope plan numR2Freqs thetaFreq alpha periodR2 periodEnv stdTheta filter = do\n let planID = DFTPlanID DFT1DG [numR2Freqs, numR2Freqs] [0, 1]\n inversePlanID = DFTPlanID IDFT1DG [numR2Freqs, numR2Freqs] [0, 1]\n vecs =\n asteriskGaussian numR2Freqs thetaFreq alpha periodR2 periodEnv stdTheta\n filterF <-\n dftExecute plan planID . VU.convert . toUnboxed . computeS . makeFilter2D $\n filter\n asteriskGaussianF <- dftExecuteBatchP plan planID vecs\n fmap VS.concat .\n dftExecuteBatchP plan inversePlanID .\n parMap rdeepseq (VS.zipWith (*) filterF) $\n asteriskGaussianF\n\n-- The envelope is r^alpha X Gaussian\nasteriskGaussian2 ::\n DFTPlan\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> IO (VS.Vector (Complex Double))\nasteriskGaussian2 plan numR2Freqs thetaFreq alpha periodR2 periodEnv stdR2 stdTheta = do\n let centerFreq = div numR2Freqs 2\n gaussian2D =\n fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i' :. j') ->\n let i = i' - centerFreq\n j = j' - centerFreq\n in exp\n (pi * fromIntegral (i ^ 2 + j ^ 2) /\n ((-1) * periodR2 ^ 2 * stdR2 ^ 2)) /\n (2 * pi * stdR2 ^ 2) :+\n 0\n asteriskGaussianEnvelope\n plan\n numR2Freqs\n thetaFreq\n alpha\n periodR2\n periodEnv\n stdTheta\n gaussian2D\n\n-- The envelope is r^alpha X LowPass\nasteriskGaussianLowPass ::\n DFTPlan\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> IO (VS.Vector (Complex Double))\nasteriskGaussianLowPass plan numR2Freqs thetaFreq alpha periodR2 periodEnv stdTheta radius = do\n let lpf =\n fromUnboxed (Z :. numR2Freqs :. numR2Freqs) $\n idealLowPassFilter radius periodR2 numR2Freqs\n asteriskGaussianEnvelope\n plan\n numR2Freqs\n thetaFreq\n alpha\n periodR2\n periodEnv\n stdTheta\n lpf\n\n\n{-# INLINE asteriskGaussianFull #-}\nasteriskGaussianFull ::\n ( VG.Vector vector (Complex e)\n , RealFloat e\n , NFData (vector (Complex e))\n , Gamma (Complex e)\n , Unbox e\n )\n => Int\n -> Int\n -> Int\n -> e\n -> e\n -> e\n -> e\n -> e\n -> [vector (Complex e)]\nasteriskGaussianFull numR2Freqs thetaFreq rFreq alpha periodR2 periodEnv stdTheta stdR =\n let zeroVec = VG.replicate (numR2Freqs ^ 2) 0\n in parMap\n rdeepseq\n (\\(radialFreq, angularFreq) ->\n let pinwheel =\n analyticalFourierCoefficients1\n numR2Freqs\n 1\n angularFreq\n radialFreq\n alpha\n periodR2\n periodEnv\n -- arr =\n -- R.map\n -- (* ((-- gaussian1DFreq (fromIntegral angularFreq) stdTheta *\n -- gaussian1DFourierCoefficients\n -- (fromIntegral radialFreq)\n -- (log periodEnv)\n -- stdR\n -- :+\n -- 0) -- *\n -- -- cis\n -- -- (2 * pi / log periodEnv * fromIntegral radialFreq *\n -- -- log 0.5)\n -- )) $\n -- -- if radialFreq == 0 && angularFreq == 0\n -- -- then pinwheel\n -- -- else\n -- centerHollowArray numR2Freqs pinwheel\n arr =\n R.map\n (* ((1 / (1 + (2 * pi / log periodEnv * fromIntegral radialFreq )^2)) :+ 0)\n ) $\n centerHollowArray numR2Freqs pinwheel\n in if angularFreq == 0\n then VG.convert . toUnboxed . computeS $ arr\n else zeroVec)\n [ (radialFreq, angularFreq)\n | radialFreq <- [-rFreq .. rFreq]\n , angularFreq <- [-thetaFreq .. thetaFreq]\n ]\n\n\n{-# INLINE gaussianFull #-}\ngaussianFull ::\n ( VG.Vector vector (Complex e)\n , RealFloat e\n , NFData (vector (Complex e))\n , Gamma (Complex e)\n , Unbox e\n )\n => Int\n -> Int\n -> Int\n -> e\n -> e\n -> [vector (Complex e)]\ngaussianFull numR2Freqs thetaFreq rFreq periodR2 stdR2 =\n let zeroVec = VG.replicate (numR2Freqs ^ 2) 0\n periodEnv = periodR2 ^ 2 / 4\n in parMap\n rdeepseq\n (\\(radialFreq, angularFreq) ->\n if angularFreq == 0 -- && radialFreq == 0\n then VG.convert . toUnboxed . computeS $\n fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i' :. j') ->\n let i = fromIntegral $ i' - div numR2Freqs 2\n j = fromIntegral $ j' - div numR2Freqs 2\n in (gaussian2DFourierCoefficients i j periodR2 stdR2 :+ 0) /\n (1 :+ (2 * pi / log periodEnv * fromIntegral radialFreq)^2)\n else zeroVec)\n [ (radialFreq, angularFreq)\n | radialFreq <- [-rFreq .. rFreq]\n , angularFreq <- [-thetaFreq .. thetaFreq]\n ]\n\n\n{-# INLINE asteriskGaussianFullEnvelope #-}\nasteriskGaussianFullEnvelope ::\n (R.Source s (Complex Double))\n => DFTPlan\n -> Int\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> R.Array s DIM2 (Complex Double)\n -> IO (VS.Vector (Complex Double))\nasteriskGaussianFullEnvelope plan numR2Freqs thetaFreq rFreq alpha periodR2 periodEnv stdTheta stdR filter = do\n let planID = DFTPlanID DFT1DG [numR2Freqs, numR2Freqs] [0, 1]\n inversePlanID = DFTPlanID IDFT1DG [numR2Freqs, numR2Freqs] [0, 1]\n vecs =\n asteriskGaussianFull\n numR2Freqs\n thetaFreq\n rFreq\n alpha\n periodR2\n periodEnv\n stdTheta\n stdR\n -- vecs =\n -- gaussianFull\n -- numR2Freqs\n -- thetaFreq\n -- rFreq\n -- periodR2\n -- stdR\n filterF <-\n dftExecute plan planID . VU.convert . toUnboxed . computeS . makeFilter2D $\n filter\n asteriskGaussianF <- dftExecuteBatchP plan planID vecs\n fmap VS.concat .\n dftExecuteBatchP plan inversePlanID .\n parMap rdeepseq (VS.zipWith (*) filterF) $\n asteriskGaussianF\n -- return . VS.concat $ vecs\n\n\n-- The envelope is r^alpha X LowPass\nasteriskGaussianFullLowPass ::\n DFTPlan\n -> Int\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> IO (VS.Vector (Complex Double))\nasteriskGaussianFullLowPass plan numR2Freqs thetaFreq rFreq alpha periodR2 periodEnv stdTheta stdR radius = do\n let lpf =\n fromUnboxed (Z :. numR2Freqs :. numR2Freqs) $\n idealLowPassFilter radius periodR2 numR2Freqs\n asteriskGaussianFullEnvelope\n plan\n numR2Freqs\n thetaFreq\n rFreq\n alpha\n periodR2\n periodEnv\n stdTheta\n stdR\n lpf\n\n\n-- The envelope is r^alpha X LowPass\nasteriskGaussian2Full ::\n DFTPlan\n -> Int\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> IO (VS.Vector (Complex Double))\nasteriskGaussian2Full plan numR2Freqs thetaFreq rFreq alpha periodR2 periodEnv stdTheta stdR stdR2 = do\n let centerFreq = div numR2Freqs 2\n gaussian2D =\n fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i' :. j') ->\n let i = fromIntegral $ i' - centerFreq\n j = fromIntegral $ j' - centerFreq\n in gaussian2DFourierCoefficients i j periodR2 stdR2 :+ 0\n asteriskGaussianFullEnvelope\n plan\n numR2Freqs\n thetaFreq\n rFreq\n alpha\n periodR2\n periodEnv\n stdTheta\n stdR\n gaussian2D\n\n\nasteriskGaussianRFull ::\n DFTPlan\n -> Int\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> IO (VS.Vector (Complex Double))\nasteriskGaussianRFull plan numR2Freqs thetaFreq rFreq alpha periodR2 periodEnv stdTheta stdR stdR2 = do\n let planID = DFTPlanID DFT1DG [numR2Freqs, numR2Freqs] [0, 1]\n inversePlanID = DFTPlanID IDFT1DG [numR2Freqs, numR2Freqs] [0, 1]\n centerFreq = div numR2Freqs 2\n gaussian2D =\n fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i' :. j') ->\n let i = i' - centerFreq\n j = j' - centerFreq\n in exp\n (pi * fromIntegral (i ^ 2 + j ^ 2) /\n ((-1) * periodR2 ^ 2 * stdR2 ^ 2)) /\n (2 * pi * stdR2 ^ 2) :+\n 0\n r =\n centerHollowArray' numR2Freqs $ analyticalFourierCoefficients3 numR2Freqs 1 0 0 alpha periodR2 periodEnv\n vecs =\n asteriskGaussianFull\n numR2Freqs\n thetaFreq\n rFreq\n alpha\n periodR2\n periodEnv\n stdTheta\n stdR\n gaussian2DF <-\n dftExecute plan planID . VU.convert . toUnboxed . computeS . makeFilter2D $\n gaussian2D\n rF <-\n dftExecute plan planID . VU.convert . toUnboxed . computeS . makeFilter2D $\n r\n let filterF = VS.zipWith (\\x y -> x + y ^ 2) gaussian2DF rF\n asteriskGaussianF <- dftExecuteBatchP plan planID vecs\n fmap VS.concat .\n dftExecuteBatchP plan inversePlanID .\n parMap rdeepseq (VS.zipWith (*) filterF) $\n asteriskGaussianF\n", "meta": {"hexsha": "b2c77d16d1fa12f039ed547c2d6264503611ca24", "size": 11043, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FourierPinwheel/AsteriskGaussian.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FourierPinwheel/AsteriskGaussian.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/FourierPinwheel/AsteriskGaussian.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.9569620253, "max_line_length": 112, "alphanum_fraction": 0.5624377434, "num_tokens": 3245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5768603807605036}} {"text": "{-# LANGUAGE RankNTypes #-}\n\nmodule Observable.MCMC.MetropolisHastings (metropolisHastings) where\n\nimport Control.Monad.Primitive\nimport Control.Monad.State.Strict\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector.Unboxed as V\nimport Observable.Core\nimport Observable.Types\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal\n\nsphericalGaussian :: Vector Double -> Vector Double -> Double -> Double\nsphericalGaussian xs mu sd = product $ zipWith density normalDists xsAsList\n where\n xsAsList = V.toList xs\n muAsList = V.toList mu\n normalDists = map (`normalDistr` sd) muAsList\n\nperturb\n :: PrimMonad m\n => Vector Double\n -> Double\n -> Observable m (Vector Double)\nperturb q sd = V.mapM (`normal` sd) q\n\nacceptRatio\n :: Target Double -> Vector Double -> Vector Double -> Double -> Double\nacceptRatio target current proposed sd = exp . min 0 $\n logObjective target proposed + log (sphericalGaussian current proposed sd)\n - logObjective target current - log (sphericalGaussian proposed current sd)\n\nnextState\n :: Target Double\n -> Vector Double\n -> Vector Double\n -> Double\n -> Double\n -> Vector Double\nnextState target current proposed sd z\n | z < acceptProb = proposed\n | otherwise = current\n where\n ratio = acceptRatio target current proposed sd \n acceptProb | isNaN ratio = 0\n | otherwise = ratio\n\ngetStandardDeviation :: Maybe Double -> OptionalStore -> Double\ngetStandardDeviation (Just sd) _ = sd\ngetStandardDeviation Nothing store = sd where\n (ODouble sd) = HashMap.lookupDefault (ODouble 1.0) MH store\n\nupdateStandardDeviation :: Double -> OptionalStore -> OptionalStore\nupdateStandardDeviation sd = HashMap.insert MH (ODouble sd) \n\nmetropolisHastings :: PrimMonad m => Maybe Double -> Transition m Double\nmetropolisHastings e = do\n Chain current target _ store <- get\n let sd = getStandardDeviation e store\n proposed <- lift $ perturb current sd\n zc <- lift unit\n let next = nextState target current proposed sd zc\n newStore = updateStandardDeviation sd store\n put $ Chain next target (logObjective target next) newStore\n return next\n\n", "meta": {"hexsha": "2ca39c6cd96c95b0045240a5ad2b96273a1a5866", "size": 2250, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Observable/MCMC/MetropolisHastings.hs", "max_stars_repo_name": "jtobin/deprecated-observable", "max_stars_repo_head_hexsha": "66ef6b510896d66d812467e6bfbe96bcdc195340", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-10T03:12:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-10T03:12:49.000Z", "max_issues_repo_path": "src/Observable/MCMC/MetropolisHastings.hs", "max_issues_repo_name": "jtobin/deprecated-observable", "max_issues_repo_head_hexsha": "66ef6b510896d66d812467e6bfbe96bcdc195340", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Observable/MCMC/MetropolisHastings.hs", "max_forks_repo_name": "jtobin/deprecated-observable", "max_forks_repo_head_hexsha": "66ef6b510896d66d812467e6bfbe96bcdc195340", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1428571429, "max_line_length": 78, "alphanum_fraction": 0.7391111111, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5768603807605036}} {"text": "module Hw4\n (\n Vec(..),\n range,\n absolute,\n rd,\n dft,\n fft) where\n\nimport Data.Complex\nimport GHC.Base\n\nrange :: Double -> Double -> Double -> [Double]\nabsolute :: Vec (Complex Double) -> Vec Double\nrd :: Int -> Vec Double -> Vec Double\ndft :: [Double] -> Vec (Complex Double)\nfft :: [Double] -> Vec (Complex Double)\n\nnewtype Vec a = Vec {runVec :: [a]}\n\ninstance Show a => Show (Vec a) where\n show (Vec a) = \"[\" ++ show' a ++ \"]\"\n\nshow' :: Show a => [a] -> [Char]\nshow' [] = \"\"\nshow' [x] = show x\nshow' (x:xs) = show x ++ \" \" ++ show' xs\n\ninstance Functor Vec where\n fmap g x = Vec $ g <$> runVec x\n\ninstance Applicative Vec where\n pure x = Vec $ repeat x\n liftA2 f a b = Vec $ zipWith f (runVec a) (runVec b)\n\ninstance Semigroup (Vec a) where\n (<>) (Vec a) (Vec b) = Vec $ a ++ b\n\ninstance Monoid (Vec a) where\n mempty = Vec []\n\ninstance Num a => Num (Vec a) where\n fromInteger x = Vec $ pure $ fromInteger x\n (+) = liftA2 (+)\n (-) = liftA2 (-)\n (*) = liftA2 (*)\n negate (Vec a) = Vec $ fmap negate a\n abs (Vec a) = Vec $ fmap abs a\n signum (Vec a) = Vec $ fmap signum a\n\ninstance Fractional a => Fractional (Vec a) where\n (/) = liftA2 (/)\n fromRational x = Vec $ pure $ fromRational x\n\ninstance Floating a => Floating (Vec a) where\n exp (Vec a) = Vec (fmap exp a)\n log (Vec a) = Vec (fmap log a)\n sin (Vec a) = Vec (fmap sin a)\n cos (Vec a) = Vec (fmap cos a)\n asin (Vec a) = Vec (fmap asin a)\n acos (Vec a) = Vec (fmap acos a)\n atan (Vec a) = Vec (fmap atan a)\n sinh (Vec a) = Vec (fmap sinh a)\n cosh (Vec a) = Vec (fmap cosh a)\n asinh (Vec a) = Vec (fmap asinh a)\n acosh (Vec a) = Vec (fmap acosh a)\n atanh (Vec a) = Vec (fmap atanh a)\n pi = Vec $ pure pi\n\nrange from to count = fmap (\\x -> from + x * step) [0..count-1] \n where step = (to - from)/count\n\nabsolute = fmap (\\x -> sqrt(realPart x * realPart x + imagPart x * imagPart x))\n\nrd n = fmap (\\x -> fromIntegral (round $ c * x) / c)\n where c = 10^n\n\ndft x =\n let n = fromIntegral $ length x\n index = range 0 n n\n xn = x `zip` index\n\n f k = sum y \n where \n y = map factor xn\n factor (xi, j) = let y = 2 * pi * j * k / n \n in xi * cos y :+ (-xi * sin y)\n in\n Vec $ fmap f index\n\n\nfft x \n | n <= 16 = dft x\n | otherwise = \n let (even, odd) = split x \n (e, o) = (fft even, fft odd)\n t = -2 * pi / fromIntegral n\n\n g (e', o', k) = \n let \n y = t * fromIntegral k \n (fr, fi) = (cos y, sin y)\n (pr, pi) = (fr * realPart o' - fi * imagPart o', fr * imagPart o' + fi * realPart o')\n in\n ((realPart e' + pr) :+ (imagPart e' + pi), (realPart e' - pr) :+ (imagPart e' - pi))\n\n (lower, upper) = unzip $ fmap g $ zip3 (runVec e) (runVec o) [0..]\n in\n Vec (lower ++ upper)\n \n where \n n = length x\n split [] = ([], [])\n split [a] = ([a], [])\n split (a:b:c) = (a:x, b:y)\n where (x,y) = split c", "meta": {"hexsha": "e4f402f3828b1153fcb3fad7d5aeb0228ce09ae7", "size": 3284, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Hw4.hs", "max_stars_repo_name": "NikolaPeevski/Haskell-stuff", "max_stars_repo_head_hexsha": "b74684bfd7df53a53f11dd4a3c6f3475f2d9bcf8", "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/Hw4.hs", "max_issues_repo_name": "NikolaPeevski/Haskell-stuff", "max_issues_repo_head_hexsha": "b74684bfd7df53a53f11dd4a3c6f3475f2d9bcf8", "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/Hw4.hs", "max_forks_repo_name": "NikolaPeevski/Haskell-stuff", "max_forks_repo_head_hexsha": "b74684bfd7df53a53f11dd4a3c6f3475f2d9bcf8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3103448276, "max_line_length": 113, "alphanum_fraction": 0.4762484775, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5768603728957096}} {"text": "module Main where\n\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.Maybe\n\nimport Graphics.UI.WX hiding (Event)\nimport Reactive.Banana\nimport Reactive.Banana.WX\n \nimport AI.HNN.FF.Network\nimport Numeric.LinearAlgebra\n\nimport Data.List.Split\nimport Data.List (replicate)\n\nmain :: IO ()\nmain = start gui\n \ngui :: IO ()\ngui = do\n f <- frame [ text := \"Neural Network\" ]\n \n lEpocs <- staticText f [ text := \"Epocs\"]\n lMiddleLayers <- staticText f [ text := \"Middle & output layers\"]\n lLearningRate <- staticText f [ text := \"Learning rate\"]\n\n iEpocs <- textCtrlRich f [ text := \"1000\" ]\n iMiddleLayers <- textCtrlRich f [ text := \"2,2,1\"]\n iLearningRate <- textCtrlRich f [ text := \"0.8\"]\n\n bStart <- button f [ text := \"Start\" ]\n bQuit <- button f [ text := \"Quit\" ]\n\n set bStart [ on command := parseInputAndTrain f iEpocs iMiddleLayers iLearningRate]\n set bQuit [ on command := close f]\n \n set f [ layout := column 25 [ widget lEpocs, widget iEpocs, \n widget lMiddleLayers, widget iMiddleLayers, \n widget lLearningRate, widget iLearningRate, \n widget bStart, widget bQuit ] ]\n\nparseInputAndTrain :: (Paint w, Textual w1, Textual w2, Textual w3) => w -> w1 -> w2 -> w3 -> IO ()\nparseInputAndTrain f iEpocs iMiddleLayers iLearningRate = do\n epocsString <- get iEpocs text\n middleLayersString <- get iMiddleLayers text\n learningRateString <- get iLearningRate text\n let epocs = read epocsString :: Int\n let middleLayersSplited = splitOn \",\" middleLayersString\n let middleLayer = map (\\s -> read s :: Int) middleLayersSplited\n let learningRate = read learningRateString :: Double\n trainNeuralNetwork epocs 2 middleLayer 1 learningRate\n\ntrainNeuralNetwork :: Int -> Int -> [Int] -> Int -> Double -> IO()\ntrainNeuralNetwork epocs firstLayer middleLayers outputLayer learningRate = do\n\n xys <- readFile \"xy.txt\"\n zs <- readFile \"z.txt\"\n\n let list1 = parse xys\n let list2 = parse zs\n let list11 = map fromList list1\n let list22 = map fromList list2\n let samples2 = zip list11 list22\n\n putStrLn \"1------------------\"\n n <- createNetwork firstLayer middleLayers outputLayer :: IO (Network Double)\n mapM_ (putStrLn . show) samples2\n mapM_ (putStrLn . show . output n tanh . fst) samples2\n putStrLn \"2------------------\"\n let n' = trainNTimes epocs learningRate tanh tanh' n samples2\n mapM_ (putStrLn . show . output n' tanh . fst) samples2\n\nparse :: String -> [[Double]]\nparse a = map (map read . words) (lines a)\n\noneList :: [a] -> [b] -> [(a, b)]\noneList [] _ = []\noneList (x:xs) (y:ys) = (x, y) : oneList xs ys\n\nsamples :: Samples Double\nsamples = [ (fromList [0, 0], fromList [0])\n , (fromList [0, 1], fromList [1])\n , (fromList [1, 0], fromList [1])\n , (fromList [1, 1], fromList [0])\n ]\n \n", "meta": {"hexsha": "015d10f7403ff2457e252870e1204c2d8b515a5d", "size": 2998, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "final/Experiments.hs", "max_stars_repo_name": "tomymehdi/ai-haskell", "max_stars_repo_head_hexsha": "9693d687fb237dddcbfd22191a9bf26656d3d2f0", "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": "final/Experiments.hs", "max_issues_repo_name": "tomymehdi/ai-haskell", "max_issues_repo_head_hexsha": "9693d687fb237dddcbfd22191a9bf26656d3d2f0", "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": "final/Experiments.hs", "max_forks_repo_name": "tomymehdi/ai-haskell", "max_forks_repo_head_hexsha": "9693d687fb237dddcbfd22191a9bf26656d3d2f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0681818182, "max_line_length": 99, "alphanum_fraction": 0.6127418279, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5768603628742482}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE ViewPatterns #-}\n-- | Tests for Statistics.Math\nmodule Tests.SpecFunctions (\n tests\n ) where\n\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Vector as V\nimport Data.Vector ((!))\nimport qualified Data.Vector.Unboxed as U\n\nimport Test.QuickCheck hiding (choose,within)\nimport Test.Tasty\nimport Test.Tasty.QuickCheck (testProperty)\nimport Test.Tasty.HUnit\n\nimport Tests.Helpers\nimport Tests.SpecFunctions.Tables\nimport Numeric.SpecFunctions\nimport Numeric.SpecFunctions.Internal (factorialTable)\nimport Numeric.MathFunctions.Comparison (within,relativeError,ulpDistance)\nimport Numeric.MathFunctions.Constants (m_epsilon,m_tiny)\n\nerfTol,erfcTol,erfcLargeTol :: Int\n#if USE_SYSTEM_ERF && !defined(__GHCJS__)\nerfTol = 1\nerfcTol = 2\nerfcLargeTol = 2\n#else\nerfTol = 4\nerfcTol = 4\nerfcLargeTol = 64\n#endif\n\nisGHCJS :: Bool\n#if defined(__GHCJS__)\nisGHCJS = True\n#else\nisGHCJS = False\n#endif\n\ntests :: TestTree\ntests = testGroup \"Special functions\"\n [ testGroup \"erf\"\n [ -- implementation from numerical recipes loses presision for\n -- large arguments\n testCase \"erfc table\" $\n forTable \"tests/tables/erfc.dat\" $ \\[x, exact] ->\n checkTabularPure erfcTol (show x) exact (erfc x)\n , testCase \"erfc table [large]\" $\n forTable \"tests/tables/erfc-large.dat\" $ \\[x, exact] ->\n checkTabularPure erfcLargeTol (show x) exact (erfc x)\n --\n , testCase \"erf table\" $\n forTable \"tests/tables/erf.dat\" $ \\[x, exact] -> do\n checkTabularPure erfTol (show x) exact (erf x)\n , testProperty \"id = erfc . invErfc\" invErfcIsInverse\n , testProperty \"id = invErfc . erfc\" invErfcIsInverse2\n , testProperty \"invErf = erf^-1\" invErfIsInverse\n ]\n --\n , testGroup \"log1p & Co\"\n [ testCase \"expm1 table\" $\n forTable \"tests/tables/expm1.dat\" $ \\[x, exact] ->\n checkTabularPure 2 (show x) exact (expm1 x)\n , testCase \"log1p table\" $\n forTable \"tests/tables/log1p.dat\" $ \\[x, exact] ->\n checkTabularPure 1 (show x) exact (log1p x)\n ]\n ----------------\n , testGroup \"gamma function\"\n [ testCase \"logGamma table [fractional points\" $\n forTable \"tests/tables/loggamma.dat\" $ \\[x, exact] -> do\n checkTabularPure 2 (show x) exact (logGamma x)\n , testProperty \"Gamma(x+1) = x*Gamma(x)\" $ gammaReccurence\n , testCase \"logGamma is expected to be precise at 1e-15 level\" $\n forM_ [3..10000::Int] $ \\n -> do\n let exact = logFactorial (n-1)\n val = logGamma (fromIntegral n)\n checkTabular 8 (show n) exact val\n ]\n ----------------\n , testGroup \"incomplete gamma\"\n [ testCase \"incompleteGamma table\" $\n forTable \"tests/tables/igamma.dat\" $ \\[a,x,exact] -> do\n let err | a < 10 = 16\n | a <= 101 = if isGHCJS then 64 else 32\n | a == 201 = 200\n | otherwise = 32\n checkTabularPure err (show (a,x)) exact (incompleteGamma a x)\n , testProperty \"incomplete gamma - increases\" $\n \\(abs -> s) (abs -> x) (abs -> y) -> s > 0 ==> monotonicallyIncreases (incompleteGamma s) x y\n , testProperty \"0 <= gamma <= 1\" incompleteGammaInRange\n , testProperty \"gamma(1,x) = 1 - exp(-x)\" incompleteGammaAt1Check\n , testProperty \"invIncompleteGamma = gamma^-1\" invIGammaIsInverse\n ]\n ----------------\n , testGroup \"beta function\"\n [ testCase \"logBeta table\" $\n forTable \"tests/tables/logbeta.dat\" $ \\[p,q,exact] ->\n let errEst\n -- For Stirling approx. errors are very good\n | b > 10 = 2\n -- Partial Stirling approx\n | a > 10 = case () of\n _| b >= 1 -> 4\n | otherwise -> 2 * est\n -- sum of logGamma\n | otherwise = case () of\n _| a <= 1 && b <= 1 -> 8\n | a >= 1 && b >= 1 -> 8\n | otherwise -> 2 * est\n where\n a = max p q\n b = min p q\n --\n est = ceiling\n $ abs (logGamma a) + abs (logGamma b) + abs (logGamma (a + b))\n / abs (logBeta a b)\n in checkTabularPure errEst (show (p,q)) exact (logBeta p q)\n , testCase \"logBeta factorial\" betaFactorial\n , testProperty \"beta(1,p) = 1/p\" beta1p\n -- , testProperty \"beta recurrence\" betaRecurrence\n ]\n ----------------\n , testGroup \"incomplete beta\"\n [ testCase \"incompleteBeta table\" $\n forM_ tableIncompleteBeta $ \\(p,q,x,exact) ->\n checkTabular 64 (show (x,p,q)) (incompleteBeta p q x) exact\n , testCase \"incompleteBeta table with p > 3000 and q > 3000\" $\n forM_ tableIncompleteBetaP3000 $ \\(x,p,q,exact) ->\n checkTabular 7000 (show (x,p,q)) (incompleteBeta p q x) exact\n --\n , testProperty \"0 <= I[B] <= 1\" incompleteBetaInRange\n , testProperty \"ibeta symmetry\" incompleteBetaSymmetry\n -- XXX FIXME DISABLED due to failures\n -- , testProperty \"invIncompleteBeta = B^-1\" $ invIBetaIsInverse\n ]\n ----------------\n , testGroup \"digamma\"\n [ testAssertion \"digamma is expected to be precise at 1e-14 [integers]\"\n $ digammaTestIntegers 1e-14\n -- Relative precision is lost when digamma(x) \u2248 0\n , testCase \"digamma is expected to be precise at 1e-12\" $\n forTable \"tests/tables/digamma.dat\" $ \\[x, exact] ->\n checkTabularPure 2048\n (show x) (digamma x) exact\n ]\n ----------------\n , testGroup \"factorial\"\n [ testCase \"Factorial table\" $\n forM_ [0 .. 170] $ \\n -> do\n checkTabular 1\n (show n)\n (fromIntegral (factorial' n))\n (factorial (fromIntegral n :: Int))\n --\n , testCase \"Log factorial from integer\" $\n forM_ [2 .. 170] $ \\n -> do\n checkTabular 1\n (show n)\n (log $ fromIntegral $ factorial' n)\n (logFactorial (fromIntegral n :: Int))\n , testAssertion \"Factorial table is OK\"\n $ U.length factorialTable == 171\n , testCase \"Log factorial table\" $\n forTable \"tests/tables/factorial.dat\" $ \\[i,exact] ->\n checkTabularPure 3\n (show i) (logFactorial (round i :: Int)) exact\n ]\n ----------------\n , testGroup \"combinatorics\"\n [ testCase \"choose table\" $\n forM_ [0 .. 1000] $ \\n ->\n forM_ [0 .. n] $ \\k -> do\n checkTabular 2048\n (show (n,k))\n (fromIntegral $ choose' n k)\n (choose (fromInteger n) (fromInteger k))\n --\n , testCase \"logChoose == log . choose\" $\n forM_ [0 .. 1000] $ \\n ->\n forM_ [0 .. n] $ \\k -> do\n checkTabular 2\n (show (n,k))\n (log $ choose n k)\n (logChoose n k)\n ]\n ----------------------------------------------------------------\n -- Self tests\n , testGroup \"self-test\"\n [ testProperty \"Self-test: 0 <= range01 <= 1\" $ \\x -> let f = range01 x in f <= 1 && f >= 0\n ]\n ]\n\n----------------------------------------------------------------\n-- efr tests\n----------------------------------------------------------------\n\nroundtrip_erfc_invErfc,\n roundtrip_invErfc_erfc,\n roundtrip_erf_invErf\n :: (Double,Double)\n#if USE_SYSTEM_ERF && !defined(__GHCJS__)\nroundtrip_erfc_invErfc = (2,2)\nroundtrip_invErfc_erfc = (2,2)\nroundtrip_erf_invErf = (1,1)\n#else\nroundtrip_erfc_invErfc = (2,8)\nroundtrip_invErfc_erfc = (8,4)\nroundtrip_erf_invErf = (128,128)\n#endif\n\n-- id \u2248 erfc . invErfc\ninvErfcIsInverse :: Double -> Property\ninvErfcIsInverse ((*2) . range01 -> x)\n = (not $ isInfinite x) ==>\n ( counterexample (\"x = \" ++ show x )\n $ counterexample (\"y = \" ++ show y )\n $ counterexample (\"x' = \" ++ show x')\n $ counterexample (\"calc.err = \" ++ show (delta, delta-e'))\n $ counterexample (\"ulps = \" ++ show (ulpDistance x x'))\n $ ulpDistance x x' <= round delta\n )\n where\n (e,e') = roundtrip_erfc_invErfc\n delta = e' + e * abs ( y / x * 2 / sqrt pi * exp( -y*y ))\n y = invErfc x\n x' = erfc y\n\n-- id \u2248 invErfc . erfc\ninvErfcIsInverse2 :: Double -> Property\ninvErfcIsInverse2 x\n = (not $ isInfinite x') ==>\n (y > m_tiny) ==>\n (x /= 0) ==>\n counterexample (\"x = \" ++ show x )\n $ counterexample (\"y = \" ++ show y )\n $ counterexample (\"x' = \" ++ show x')\n $ counterexample (\"calc.err = \" ++ show delta)\n $ counterexample (\"ulps = \" ++ show (ulpDistance x x'))\n $ ulpDistance x x' <= delta\n where\n (e,e') = roundtrip_invErfc_erfc\n delta = round\n $ e' + e * abs (y / x / (2 / sqrt pi * exp( -x*x )))\n y = erfc x\n x' = invErfc y\n\n-- id \u2248 erf . invErf\ninvErfIsInverse :: Double -> Property\ninvErfIsInverse a\n = (x /= 0) ==>\n counterexample (\"x = \" ++ show x )\n $ counterexample (\"y = \" ++ show y )\n $ counterexample (\"x' = \" ++ show x')\n $ counterexample (\"calc.err = \" ++ show delta)\n $ counterexample (\"ulps = \" ++ show (ulpDistance x x'))\n $ ulpDistance x x' <= delta\n where\n (e,e') = roundtrip_erf_invErf\n delta = round\n $ e + e' * abs (y / x * 2 / sqrt pi * exp ( -y * y ))\n x | a < 0 = - range01 a\n | otherwise = range01 a\n y = invErf x\n x' = erf y\n\n----------------------------------------------------------------\n-- QC tests\n----------------------------------------------------------------\n\n-- B(p,q) = (x - 1)!(y-1)! / (x + y - 1)!\nbetaFactorial :: IO ()\nbetaFactorial = do\n forM_ prod $ \\(p,q,facP,facQ,facProd) -> do\n let exact = fromIntegral (facQ * facP)\n / fromIntegral facProd\n checkTabular 16 (show (p,q))\n (logBeta (fromIntegral p) (fromIntegral q))\n (log exact)\n where\n prod = [ (p,q,facP,facQ, factorial' (p + q - 1))\n | (p,facP) <- facList\n , (q,facQ) <- facList\n , p + q < 170\n , not (p == 1 && q== 1)\n ]\n facList = [(p,factorial' (p-1)) | p <- [1 .. 170]]\n\n-- B(1,p) = 1/p\nbeta1p :: Double -> Property\nbeta1p (abs -> p)\n = p > 2 ==>\n counterexample (\"p = \" ++ show p)\n $ counterexample (\"logB = \" ++ show lb)\n $ counterexample (\"err = \" ++ show d)\n $ d <= 24\n where\n lb = logBeta 1 p\n d = ulpDistance lb (- log p)\n\n{-\n-- B(p+1,q) = B(p,q) \u00b7 p/(p+q)\nbetaRecurrence :: Double -> Double -> Property\nbetaRecurrence (abs -> p) (abs -> q)\n = p > 0 && q > 0 ==>\n counterexample (\"p = \" ++ show p)\n $ counterexample (\"q = \" ++ show q)\n $ counterexample (\"log B(p,q) = \" ++ show (logBeta p q))\n $ counterexample (\"log B(p+1,q) = \" ++ show (logBeta (p+1) q))\n $ counterexample (\"err = \" ++ show d)\n $ d <= 128\n where\n logB = logBeta p q + log (p / (p + q))\n logB' = logBeta (p + 1) q\n d = ulpDistance logB logB'\n-}\n\n-- \u0393(x+1) = x\u00b7\u0393(x)\ngammaReccurence :: Double -> Property\ngammaReccurence x\n = x > 0 ==> err < errEst\n where\n g1 = logGamma x\n g2 = logGamma (x+1)\n err = abs (g2 - g1 - log x)\n -- logGamma apparently is not as precise for small x. See #59 for details\n errEst = max 1e-14\n $ 2 * m_epsilon * sum (map abs [ g1 , g2 , log x ])\n\n-- \u03b3(s,x) is in [0,1] range\nincompleteGammaInRange :: Double -> Double -> Property\nincompleteGammaInRange (abs -> s) (abs -> x) =\n x >= 0 && s > 0 ==> let i = incompleteGamma s x in i >= 0 && i <= 1\n\n-- \u03b3(1,x) = 1 - exp(-x)\n-- Since \u0393(1) = 1 normalization doesn't make any difference\nincompleteGammaAt1Check :: Double -> Bool\nincompleteGammaAt1Check (abs -> x) =\n ulpDistance (incompleteGamma 1 x) (-expm1(-x)) < 16\n\n-- invIncompleteGamma is inverse of incompleteGamma\ninvIGammaIsInverse :: Double -> Double -> Property\ninvIGammaIsInverse (abs -> a) (range01 -> p) =\n a > m_tiny && p > m_tiny && p < 1 && x > m_tiny ==>\n ( counterexample (\"a = \" ++ show a )\n $ counterexample (\"p = \" ++ show p )\n $ counterexample (\"x = \" ++ show x )\n $ counterexample (\"p' = \" ++ show p')\n $ counterexample (\"err = \" ++ show (ulpDistance p p'))\n $ counterexample (\"est = \" ++ show est)\n $ ulpDistance p p' <= est\n )\n where\n x = invIncompleteGamma a p\n f' = exp ( log x * (a-1) - x - logGamma a)\n p' = incompleteGamma a x\n -- FIXME: Test should be rechecked when #42 is fixed\n (e,e') = (32,32)\n est = round\n $ e' + e * abs (x / p * f')\n\n-- I(x;p,q) is in [0,1] range\nincompleteBetaInRange :: Double -> Double -> Double -> Property\nincompleteBetaInRange (abs -> p) (abs -> q) (range01 -> x) =\n p > 0 && q > 0 ==> let i = incompleteBeta p q x in i >= 0 && i <= 1\n\n-- I(0.5; p,p) = 0.5\nincompleteBetaSymmetry :: Double -> Property\nincompleteBetaSymmetry (abs -> p) =\n p > 0 ==>\n counterexample (\"p = \" ++ show p)\n $ counterexample (\"ib = \" ++ show ib)\n $ counterexample (\"err = \" ++ show d)\n $ counterexample (\"est = \" ++ show est)\n $ d <= est\n where\n est | p < 1 = 80\n | p < 10 = 200\n | otherwise = round $ 6 * p\n d = ulpDistance ib 0.5\n ib = incompleteBeta p p 0.5\n\n-- invIncompleteBeta is inverse of incompleteBeta\ninvIBetaIsInverse :: Double -> Double -> Double -> Property\ninvIBetaIsInverse (abs -> p) (abs -> q) (range01 -> x) =\n p > 0 && q > 0 ==> ( counterexample (\"p = \" ++ show p )\n $ counterexample (\"q = \" ++ show q )\n $ counterexample (\"x = \" ++ show x )\n $ counterexample (\"x' = \" ++ show x')\n $ counterexample (\"a = \" ++ show a)\n $ counterexample (\"err = \" ++ (show $ abs $ (x - x') / x))\n $ abs (x - x') <= 1e-12\n )\n where\n x' = incompleteBeta p q a\n a = invIncompleteBeta p q x\n\n-- Table for digamma function:\n--\n-- Uses equality \u03c8(n) = H_{n-1} - \u03b3 where\n-- H_{n} = \u03a3 1/k, k = [1 .. n] - harmonic number\n-- \u03b3 = 0.57721566490153286060 - Euler-Mascheroni number\ndigammaTestIntegers :: Double -> Bool\ndigammaTestIntegers eps\n = all (uncurry $ eq eps) $ take 3000 digammaInt\n where\n ok approx exact = approx\n -- Harmonic numbers starting from 0\n harmN = scanl (\\a n -> a + 1/n) 0 [1::Rational .. ]\n gam = 0.57721566490153286060\n -- Digamma values\n digammaInt = zipWith (\\i h -> (digamma i, realToFrac h - gam)) [1..] harmN\n\n\n----------------------------------------------------------------\n-- Unit tests\n----------------------------------------------------------------\n\n-- Lookup table for fact factorial calculation. It has fixed size\n-- which is bad but it's OK for this particular case\nfactorial_table :: V.Vector Integer\nfactorial_table = V.generate 2000 (\\n -> product [1..fromIntegral n])\n\n-- Exact implementation of factorial\nfactorial' :: Integer -> Integer\nfactorial' n = factorial_table ! fromIntegral n\n\n-- Exact albeit slow implementation of choose\nchoose' :: Integer -> Integer -> Integer\nchoose' n k = factorial' n `div` (factorial' k * factorial' (n-k))\n\n-- Truncate double to [0,1]\nrange01 :: Double -> Double\nrange01 = abs . (snd :: (Integer, Double) -> Double) . properFraction\n\n\nreadTable :: FilePath -> IO [[Double]]\nreadTable\n = fmap (fmap (fmap read . words) . lines)\n . readFile\n\nforTable :: FilePath -> ([Double] -> Maybe String) -> IO ()\nforTable path fun = do\n rows <- readTable path\n case mapMaybe fun rows of\n [] -> return ()\n errs -> assertFailure $ intercalate \"---\\n\" errs\n\ncheckTabular :: Int -> String -> Double -> Double -> IO ()\ncheckTabular prec x exact val =\n case checkTabularPure prec x exact val of\n Nothing -> return ()\n Just s -> assertFailure s\n\ncheckTabularPure :: Int -> String -> Double -> Double -> Maybe String\ncheckTabularPure prec x exact val\n | within prec exact val = Nothing\n | otherwise = Just $ unlines\n [ \" x = \" ++ x\n , \" expected = \" ++ show exact\n , \" got = \" ++ show val\n , \" ulps diff = \" ++ show (ulpDistance exact val)\n , \" err.est. = \" ++ show prec\n ]\n", "meta": {"hexsha": "83e5f610fda7a364cff3ef3b1f05ea97accf783c", "size": 16175, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Tests/SpecFunctions.hs", "max_stars_repo_name": "Shimuuar/math-functions", "max_stars_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Tests/SpecFunctions.hs", "max_issues_repo_name": "Shimuuar/math-functions", "max_issues_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Tests/SpecFunctions.hs", "max_forks_repo_name": "Shimuuar/math-functions", "max_forks_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3418259023, "max_line_length": 101, "alphanum_fraction": 0.5392890263, "num_tokens": 4947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5767489067351063}} {"text": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\n\nmodule NVectorSpec where\n\nimport Data.Complex\n\nimport Test.QuickCheck\nimport Test.QuickCheck.Poly\n\nimport Category\nimport Comonad\nimport Functor\nimport NVector\nimport Unboxed\n\n\n\ntype N = 10\n\nprop_NVector_Functor_id :: FnProp (NVector N A)\nprop_NVector_Functor_id = checkFnEqual law_Functor_id\n\nprop_NVector_Functor_comp :: Fun B C -> Fun A B -> FnProp (NVector N A)\nprop_NVector_Functor_comp f g = checkFnEqual (law_Functor_comp f g)\n\nprop_NVector_Semicomonad_comm ::\n Fun (NVector N B) C -> Fun (NVector N A) B -> FnProp (NVector N A)\nprop_NVector_Semicomonad_comm f g = checkFnEqual (law_Semicomonad_comm f g)\n\nprop_NVector_Semicomonad1_comm ::\n Fun (NVector N B) C -> Fun (NVector N A) B -> FnProp (NVector N A)\nprop_NVector_Semicomonad1_comm f g = checkFnEqual (law_Semicomonad1_comm f g)\n\nprop_NVector_Semicomonad1_comm' ::\n Fun (NVector N B) C -> Fun (NVector N A) B -> FnProp (NVector N A)\nprop_NVector_Semicomonad1_comm' (Fn f) (Fn g) =\n checkFnEqual (law_Semicomonad1_comm' f g)\n\n\n\ntype UA = Int\ntype UB = Double\ntype UC = Complex Double\n\nprop_NUVector_Functor_id :: FnProp (NUVector N UA)\nprop_NUVector_Functor_id = checkFnEqual law_Functor_id\n\nprop_NUVector_Functor_comp ::\n (UB -#> UC) -> (UA -#> UB) -> FnProp (NUVector N UA)\nprop_NUVector_Functor_comp f g = checkFnEqual (law_Functor_comp f g)\n\nprop_NUVector_Semicomonad1_comm' ::\n Fun (NUVector N UB) UC -> Fun (NUVector N UA) UB ->\n FnProp (NUVector N UA)\nprop_NUVector_Semicomonad1_comm' (Fn f) (Fn g) =\n checkFnEqual (law_Semicomonad1_comm' f g)\n", "meta": {"hexsha": "2e522bd024828a8642dcc75c13d81df4c7ea85cd", "size": 1584, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/NVectorSpec.hs", "max_stars_repo_name": "eschnett/wavetoy6", "max_stars_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/NVectorSpec.hs", "max_issues_repo_name": "eschnett/wavetoy6", "max_issues_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/NVectorSpec.hs", "max_forks_repo_name": "eschnett/wavetoy6", "max_forks_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7894736842, "max_line_length": 77, "alphanum_fraction": 0.7506313131, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5765086358142952}} {"text": "module MarkovChain\n ( \n markov\n ) where\n\nimport Numeric.LinearAlgebra\nimport Text.ParserCombinators.Parsec\n\nmatParse = sepBy line (char ';') \nline = sepBy cell (char ',' )\ncell = many ( noneOf \",\\n;\" )\n\nstringToTranstionMatrix :: String -> Either ParseError [[String]]\nstringToTranstionMatrix str = parse matParse \"unknown\" str\n\nmarkov matStr = stringToTranstionMatrix matStr\n", "meta": {"hexsha": "470504fd38c0a25243b22293d64f928feaacc437", "size": 385, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MarkovChain.hs", "max_stars_repo_name": "dilawar/MarkovChains", "max_stars_repo_head_hexsha": "7b5859c3dd02791dd4f394c1ee591b713b2a925a", "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/MarkovChain.hs", "max_issues_repo_name": "dilawar/MarkovChains", "max_issues_repo_head_hexsha": "7b5859c3dd02791dd4f394c1ee591b713b2a925a", "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/MarkovChain.hs", "max_forks_repo_name": "dilawar/MarkovChains", "max_forks_repo_head_hexsha": "7b5859c3dd02791dd4f394c1ee591b713b2a925a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6470588235, "max_line_length": 65, "alphanum_fraction": 0.7298701299, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5763384894343873}} {"text": "module SceneRandom where\n\nimport Numeric.Vector\nimport Numeric.Scalar (fromScalar, scalar)\nimport Control.Monad.State\nimport System.Random\nimport Types\nimport VecUtil\n\nrandDouble :: State SceneContext Double\nrandDouble = do\n ss <- get\n let (v, gen) = random (ss_getGen ss) :: (Double, StdGen)\n put $ ss { ss_getGen = gen }\n return v\n\nrandRange :: Double -> Double -> State SceneContext Double\nrandRange l h = randDouble >>= (\\v -> return $ v * (h - l) + l)\n\nrandNeg1To1 :: State SceneContext Double\nrandNeg1To1 = randRange (-1) 1\n\nrandVecSphere :: State SceneContext Vec3d\nrandVecSphere = do\n x <- randNeg1To1\n y <- randNeg1To1\n z <- randNeg1To1\n return $ normalized $ vec3 x y z\n\nrandVecHemisphere :: Vec3d -> State SceneContext Vec3d\nrandVecHemisphere normal = do\n let (tangent, bitangent) = tangentBitangent normal\n\n theta <- randRange 0 (2 * pi)\n phi <- randRange 0 (pi / 2)\n\n let t = fromScalar $ scalar $ sin theta * cos phi\n let b = fromScalar $ scalar $ cos theta * cos phi\n let n = fromScalar $ scalar $ sin phi\n return $ tangent * t + bitangent * b + normal * n\n\nrandVecDisc :: Vec3d -> Vec3d -> Double -> State SceneContext Vec3d\nrandVecDisc normal center radius = do\n let (tangent, bitangent) = tangentBitangent normal\n theta <- randRange 0 (2 * pi)\n let t = fromScalar $ scalar $ sin theta * radius\n let b = fromScalar $ scalar $ cos theta * radius\n return $ tangent * t + bitangent * b + center\n\n-- https://math.stackexchange.com/a/182936\nrandVecCone :: Double -> Vec3d -> State SceneContext Vec3d\nrandVecCone angle vector = do\n let (tangent, bitangent) = tangentBitangent vector\n z <- randRange (cos angle) 1\n phi <- randRange 0 (2 * pi)\n let theta = acos z\n let t = fromScalar $ scalar $ cos phi\n let b = fromScalar $ scalar $ sin phi\n let v = fromScalar $ scalar $ cos theta\n let sinTheta = fromScalar $ scalar $ sin theta\n return $ sinTheta * (t * tangent + b * tangent) + v * vector\n\nrandColor :: State SceneContext Vec3d\nrandColor = do\n r <- randDouble\n g <- randDouble\n b <- randDouble\n return $ vec3 r g b\n", "meta": {"hexsha": "43fe627f53373425e423ff1b8d04958e7fd5fd8e", "size": 2061, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SceneRandom.hs", "max_stars_repo_name": "craigmc08/haskell-raytracer", "max_stars_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SceneRandom.hs", "max_issues_repo_name": "craigmc08/haskell-raytracer", "max_issues_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SceneRandom.hs", "max_forks_repo_name": "craigmc08/haskell-raytracer", "max_forks_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8695652174, "max_line_length": 67, "alphanum_fraction": 0.6923823387, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5762682489734334}} {"text": "{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeInType #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE ViewPatterns #-}\n\nmodule Backprop.Learn.Model.Stochastic (\n dropout\n , rreLU\n , injectNoise, applyNoise\n , injectNoiseR, applyNoiseR\n ) where\n\nimport Backprop.Learn.Model.Function\nimport Backprop.Learn.Model.Types\nimport Control.Monad.Primitive\nimport Data.Bool\nimport GHC.TypeNats\nimport Numeric.Backprop\nimport Numeric.LinearAlgebra.Static.Backprop\nimport Numeric.LinearAlgebra.Static.Vector\nimport qualified Data.Vector.Storable.Sized as SVS\nimport qualified Statistics.Distribution as Stat\nimport qualified System.Random.MWC as MWC\nimport qualified System.Random.MWC.Distributions as MWC\n\n-- | Dropout layer. Parameterized by dropout percentage (should be between\n-- 0 and 1).\n--\n-- 0 corresponds to no dropout, 1 corresponds to complete dropout of all\n-- nodes every time.\ndropout\n :: KnownNat n\n => Double\n -> Model 'Nothing 'Nothing (R n) (R n)\ndropout r = Func\n { runFunc = (auto (realToFrac (1 - r)) *)\n , runFuncStoch = \\g x -> do\n (x *) . auto . vecR <$> SVS.replicateM (mask g)\n }\n where\n mask :: PrimMonad m => MWC.Gen (PrimState m) -> m Double\n mask = fmap (bool 1 0) . MWC.bernoulli r\n\n-- | Random leaky rectified linear unit\nrreLU\n :: (Stat.ContGen d, Stat.Mean d, KnownNat n)\n => d\n -> Model 'Nothing 'Nothing (R n) (R n)\nrreLU d = Func\n { runFunc = vmap' (preLU v)\n , runFuncStoch = \\g x -> do\n \u03b1 <- vecR <$> SVS.replicateM (Stat.genContVar d g)\n pure (zipWithVector preLU (constVar \u03b1) x)\n }\n where\n v :: BVar s Double\n v = auto (Stat.mean d)\n\n-- | Inject random noise. Usually used between neural network layers, or\n-- at the very beginning to pre-process input.\n--\n-- In non-stochastic mode, this adds the mean of the distribution.\ninjectNoise\n :: (Stat.ContGen d, Stat.Mean d, Fractional a)\n => d\n -> Model 'Nothing 'Nothing a a\ninjectNoise d = Func\n { runFunc = (realToFrac (Stat.mean d) +)\n , runFuncStoch = \\g x -> do\n e <- Stat.genContVar d g\n pure (realToFrac e + x)\n }\n\n-- | 'injectNoise' lifted to 'R'\ninjectNoiseR\n :: (Stat.ContGen d, Stat.Mean d, KnownNat n)\n => d\n -> Model 'Nothing 'Nothing (R n) (R n)\ninjectNoiseR d = Func\n { runFunc = (realToFrac (Stat.mean d) +)\n , runFuncStoch = \\g x -> do\n e <- vecR <$> SVS.replicateM (Stat.genContVar d g)\n pure (constVar e + x)\n }\n\n-- | Multply by random noise. Can be used to implement dropout-like\n-- behavior.\n--\n-- In non-stochastic mode, this scales by the mean of the distribution.\napplyNoise\n :: (Stat.ContGen d, Stat.Mean d, Fractional a)\n => d\n -> Model 'Nothing 'Nothing a a\napplyNoise d = Func\n { runFunc = (realToFrac (Stat.mean d) *)\n , runFuncStoch = \\g x -> do\n e <- Stat.genContVar d g\n pure (realToFrac e * x)\n }\n\n-- | 'applyNoise' lifted to 'R'\napplyNoiseR\n :: (Stat.ContGen d, Stat.Mean d, KnownNat n)\n => d\n -> Model 'Nothing 'Nothing (R n) (R n)\napplyNoiseR d = Func\n { runFunc = (realToFrac (Stat.mean d) *)\n , runFuncStoch = \\g x -> do\n e <- vecR <$> SVS.replicateM (Stat.genContVar d g)\n pure (constVar e * x)\n }\n", "meta": {"hexsha": "fcc0fb72ff674922b799832ae25c0d7cc7159472", "size": 3755, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Backprop/Learn/Model/Stochastic.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "src/Backprop/Learn/Model/Stochastic.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "src/Backprop/Learn/Model/Stochastic.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 31.0330578512, "max_line_length": 75, "alphanum_fraction": 0.6061251664, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5760093904004321}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Statistics.Classification.ROC (\n ROC(..)\n , ROCPoint(..)\n , rocPoint\n , efficientROC\n , roc\n ) where\n\nimport Data.List (foldl')\n\nimport Data.Csv ((.:), (.=), DefaultOrdered(..), FromNamedRecord(..), ToNamedRecord(..), header, namedRecord)\nimport qualified Data.Vector as V\n\nimport Statistics.Classification.ConfusionMatrix (ConfusionMatrix, trueConfMatrix, truePosRate, falsePosRate)\nimport Statistics.Classification.Types (ClassificationResult(..), ClassificationScore(..), sortByScore)\n\ndata ROC = ROC {\n rocAUC :: !Double\n , rocCurve :: !(V.Vector ROCPoint)\n } deriving (Eq, Show, Read)\n\ndata ROCPoint = ROCPoint {\n rocTruePos :: {-# UNPACK #-}!Double\n , rocFalsePos :: {-# UNPACK #-}!Double\n , rocCutoff :: {-# UNPACK #-}!Double\n , rocConfusion :: !ConfusionMatrix\n } deriving (Eq, Show, Read)\n\nrocPoint :: Double -> ConfusionMatrix -> ROCPoint\nrocPoint cutoff cm = ROCPoint {\n rocTruePos = truePosRate cm\n , rocFalsePos = falsePosRate cm\n , rocCutoff = cutoff\n , rocConfusion = cm\n }\n\ninstance DefaultOrdered ROCPoint where\n headerOrder _ = header [\n \"true_positive_rate\"\n , \"false_positive_rate\"\n , \"cutoff\"\n ] <> headerOrder (undefined :: ConfusionMatrix)\n\ninstance ToNamedRecord ROCPoint where\n toNamedRecord rp = namedRecord [\n \"true_positive_rate\" .= rocTruePos rp\n , \"false_positive_rate\" .= rocFalsePos rp\n , \"cutoff\" .= rocCutoff rp\n ] <> toNamedRecord (rocConfusion rp)\n\ninstance FromNamedRecord ROCPoint where\n parseNamedRecord r = ROCPoint <$>\n r .: \"true_positive_rate\"\n <*> r .: \"false_positive_rate\"\n <*> r .: \"cutoff\"\n <*> parseNamedRecord r\n\ndata EffRocState = EffRocState {\n effRocCutoff :: {-# UNPACK #-}!Double\n , effRocTP :: {-# UNPACK #-}!Int\n , effRocFP :: {-# UNPACK #-}!Int\n , effRocTPprev :: {-# UNPACK #-}!Int\n , effRocFPprev :: {-# UNPACK #-}!Int\n , effRocOut :: ![ROCPoint]\n , effRocAUC :: {-# UNPACK #-}!Double\n } deriving (Eq, Show, Read)\n\nemptyEffRocState :: EffRocState\nemptyEffRocState = EffRocState inf 0 0 0 0 [] 0\n where inf = 1 / 0\n\ntrapezoidArea :: Int -> Int -> Int -> Int -> Double\ntrapezoidArea x1 x2 y1 y2 = base * height\n where\n base = fromIntegral . abs $ x2 - x1\n height = 0.5 * fromIntegral y2 + 0.5 * fromIntegral y1\n\naddArea :: EffRocState -> EffRocState\naddArea s0 = s0 { effRocAUC = effRocAUC s0 + area }\n where\n area = trapezoidArea (effRocFP s0) (effRocFPprev s0) (effRocTP s0) (effRocTPprev s0)\n\nupdRocState :: Int -> Int -> EffRocState -> ClassificationScore Bool -> EffRocState\nupdRocState p n s r\n | effRocCutoff s /= cutoff = nextExample . nextCutoff $ addArea s\n | otherwise = nextExample s\n where\n cutoff = classifiedScore r\n actual = classifiedExample r\n nextCutoff s0 = s0 { effRocCutoff = cutoff, effRocTPprev = effRocTP s0, effRocFPprev = effRocFP s0 }\n nextExample s0 =\n let s1 = if actual then s0 { effRocTP = effRocTP s0 + 1 } else s0 { effRocFP = effRocFP s0 + 1 }\n cm = trueConfMatrix (ClassificationResult p (effRocTP s1)) (ClassificationResult n (n - effRocFP s1))\n in s1 { effRocOut = rocPoint cutoff cm : effRocOut s1 }\n\n-- O(n log n) ROC curve generation and AUC calculation\n-- Algorithm 1 and 2 in\n-- Fawcett, T., 2006. An Introduction to ROC Analysis. Pattern Recognition Letters 27 (861 - 874)\nefficientROC :: Foldable f => Int -> Int -> f (ClassificationScore Bool) -> ROC\nefficientROC p n = out . foldl' (updRocState p n) emptyEffRocState\n where\n finAUC effr\n | p == 0 || n == 0 = 0 -- degenerate case, no actual positive or negative examples.\n | otherwise = (effRocAUC effr + trapezoidArea n (effRocFPprev effr) p (effRocTPprev effr)) / fromIntegral (p * n)\n out s = ROC {\n rocAUC = finAUC s\n , rocCurve = V.fromList $ effRocOut s\n }\n\nroc :: V.Vector (ClassificationScore Bool) -> ROC\nroc v = efficientROC p n . V.reverse $ sortByScore v\n where\n p = V.length $ V.findIndices classifiedExample v\n n = V.length v - p\n", "meta": {"hexsha": "54712b12851e7ad5a020ece79093742f7ae9d3d1", "size": 4013, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Classification/ROC.hs", "max_stars_repo_name": "tsbattman/rochs", "max_stars_repo_head_hexsha": "b8a229ca906ae36a6b93e59db8de88d077644a55", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/Classification/ROC.hs", "max_issues_repo_name": "tsbattman/rochs", "max_issues_repo_head_hexsha": "b8a229ca906ae36a6b93e59db8de88d077644a55", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Classification/ROC.hs", "max_forks_repo_name": "tsbattman/rochs", "max_forks_repo_head_hexsha": "b8a229ca906ae36a6b93e59db8de88d077644a55", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2991452991, "max_line_length": 119, "alphanum_fraction": 0.6713182158, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5759997123372828}} {"text": "{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module : Statistics.Distribution.Geometric\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- The Geometric distribution. There are two variants of\n-- distribution. First is the probability distribution of the number\n-- of Bernoulli trials needed to get one success, supported on the set\n-- [1,2..] ('GeometricDistribution'). Sometimes it's referred to as\n-- the /shifted/ geometric distribution to distinguish from another\n-- one.\n--\n-- Second variant is probability distribution of the number of\n-- failures before first success, defined over the set [0,1..]\n-- ('GeometricDistribution0').\nmodule Statistics.Distribution.Geometric\n (\n GeometricDistribution\n , GeometricDistribution0\n -- * Constructors\n , geometric\n , geometric0\n -- ** Accessors\n , gdSuccess\n , gdSuccess0\n ) where\n\nimport Data.Aeson (FromJSON, ToJSON)\nimport Control.Applicative ((<$>))\nimport Control.Monad (liftM)\nimport Data.Binary (Binary)\nimport Data.Binary (put, get)\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.MathFunctions.Constants (m_pos_inf, m_neg_inf)\nimport qualified Statistics.Distribution as D\nimport qualified System.Random.MWC.Distributions as MWC\n\n----------------------------------------------------------------\n-- Distribution over [1..]\n\nnewtype GeometricDistribution = GD {\n gdSuccess :: Double\n } deriving (Eq, Read, Show, Typeable, Data, Generic)\n\ninstance FromJSON GeometricDistribution\ninstance ToJSON GeometricDistribution\n\ninstance Binary GeometricDistribution where\n get = GD <$> get\n put (GD x) = put x\n\ninstance D.Distribution GeometricDistribution where\n cumulative = cumulative\n\ninstance D.DiscreteDistr GeometricDistribution where\n probability (GD s) n\n | n < 1 = 0\n | otherwise = s * (1-s) ** (fromIntegral n - 1)\n logProbability (GD s) n\n | n < 1 = m_neg_inf\n | otherwise = log s + log (1-s) * (fromIntegral n - 1)\n\n\ninstance D.Mean GeometricDistribution where\n mean (GD s) = 1 / s\n\ninstance D.Variance GeometricDistribution where\n variance (GD s) = (1 - s) / (s * s)\n\ninstance D.MaybeMean GeometricDistribution where\n maybeMean = Just . D.mean\n\ninstance D.MaybeVariance GeometricDistribution where\n maybeStdDev = Just . D.stdDev\n maybeVariance = Just . D.variance\n\ninstance D.Entropy GeometricDistribution where\n entropy (GD s)\n | s == 0 = m_pos_inf\n | s == 1 = 0\n | otherwise = negate $ (s * log s + (1-s) * log (1-s)) / s\n\ninstance D.MaybeEntropy GeometricDistribution where\n maybeEntropy = Just . D.entropy\n\ninstance D.DiscreteGen GeometricDistribution where\n genDiscreteVar (GD s) g = MWC.geometric1 s g\n\ninstance D.ContGen GeometricDistribution where\n genContVar d g = fromIntegral `liftM` D.genDiscreteVar d g\n\n-- | Create geometric distribution.\ngeometric :: Double -- ^ Success rate\n -> GeometricDistribution\ngeometric x\n | x >= 0 && x <= 1 = GD x\n | otherwise =\n error $ \"Statistics.Distribution.Geometric.geometric: probability must be in [0,1] range. Got \" ++ show x\n\ncumulative :: GeometricDistribution -> Double -> Double\ncumulative (GD s) x\n | x < 1 = 0\n | isInfinite x = 1\n | isNaN x = error \"Statistics.Distribution.Geometric.cumulative: NaN input\"\n | otherwise = 1 - (1-s) ^ (floor x :: Int)\n\n\n----------------------------------------------------------------\n-- Distribution over [0..]\n\nnewtype GeometricDistribution0 = GD0 {\n gdSuccess0 :: Double\n } deriving (Eq, Read, Show, Typeable, Data, Generic)\n\ninstance FromJSON GeometricDistribution0\ninstance ToJSON GeometricDistribution0\n\ninstance Binary GeometricDistribution0 where\n get = GD0 <$> get\n put (GD0 x) = put x\n\ninstance D.Distribution GeometricDistribution0 where\n cumulative (GD0 s) x = cumulative (GD s) (x + 1)\n\ninstance D.DiscreteDistr GeometricDistribution0 where\n probability (GD0 s) n = D.probability (GD s) (n + 1)\n logProbability (GD0 s) n = D.logProbability (GD s) (n + 1)\n\ninstance D.Mean GeometricDistribution0 where\n mean (GD0 s) = 1 / s - 1\n\ninstance D.Variance GeometricDistribution0 where\n variance (GD0 s) = D.variance (GD s)\n\ninstance D.MaybeMean GeometricDistribution0 where\n maybeMean = Just . D.mean\n\ninstance D.MaybeVariance GeometricDistribution0 where\n maybeStdDev = Just . D.stdDev\n maybeVariance = Just . D.variance\n\ninstance D.Entropy GeometricDistribution0 where\n entropy (GD0 s) = D.entropy (GD s)\n\ninstance D.MaybeEntropy GeometricDistribution0 where\n maybeEntropy = Just . D.entropy\n\ninstance D.DiscreteGen GeometricDistribution0 where\n genDiscreteVar (GD0 s) g = MWC.geometric0 s g\n\ninstance D.ContGen GeometricDistribution0 where\n genContVar d g = fromIntegral `liftM` D.genDiscreteVar d g\n\n-- | Create geometric distribution.\ngeometric0 :: Double -- ^ Success rate\n -> GeometricDistribution0\ngeometric0 x\n | x >= 0 && x <= 1 = GD0 x\n | otherwise =\n error $ \"Statistics.Distribution.Geometric.geometric: probability must be in [0,1] range. Got \" ++ show x\n", "meta": {"hexsha": "bf2a767a3d2965259467aaf3a6dcf1b7e53ada1e", "size": 5239, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Geometric.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "Statistics/Distribution/Geometric.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Distribution/Geometric.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.371257485, "max_line_length": 109, "alphanum_fraction": 0.6865814087, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5759034838773633}} {"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule GrenadeExtras.GradNorm (\n GradNorm(..)\n) where\n\nimport Grenade (FullyConnected'(FullyConnected'), FullyConnected(FullyConnected), Tanh,\n Logit, Gradient, Relu, Gradients(GNil, (:/>)))\nimport Numeric.LinearAlgebra.Static ((<.>), toColumns)\nimport GHC.TypeLits (KnownNat)\n\nclass GradNorm x where\n normSquared :: x -> Double\n\ninstance (KnownNat i, KnownNat o) => GradNorm (FullyConnected' i o) where\n normSquared (FullyConnected' r l) = r <.> r + (sum . fmap (\\c->c<.>c) . toColumns $ l)\n\ninstance (KnownNat i, KnownNat o) => GradNorm (FullyConnected i o) where\n normSquared (FullyConnected w _) = normSquared w\n\ninstance GradNorm () where\n normSquared _ = 0\n\ninstance (GradNorm a, GradNorm b) => GradNorm (a, b) where\n normSquared (a, b) = normSquared a + normSquared b\n\ninstance GradNorm Logit where\n normSquared _ = 0\n\ninstance GradNorm Tanh where\n normSquared _ = 0\n\ninstance GradNorm Relu where\n normSquared _ = 0\n\ninstance GradNorm (Gradients '[]) where\n normSquared GNil = 0\n\ninstance (GradNorm l, GradNorm (Gradient l), GradNorm (Gradients ls)) => GradNorm (Gradients (l ': ls)) where\n normSquared (grad :/> grest) = normSquared grad + normSquared grest\n", "meta": {"hexsha": "8eaa9f40980bf3af32e626b2eb698df566747d80", "size": 1466, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/GrenadeExtras/GradNorm.hs", "max_stars_repo_name": "helq/haskell-binary-classification", "max_stars_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-10-02T06:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T11:49:35.000Z", "max_issues_repo_path": "src/GrenadeExtras/GradNorm.hs", "max_issues_repo_name": "helq/haskell-binary-classification", "max_issues_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GrenadeExtras/GradNorm.hs", "max_forks_repo_name": "helq/haskell-binary-classification", "max_forks_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T14:57:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T14:57:00.000Z", "avg_line_length": 31.1914893617, "max_line_length": 109, "alphanum_fraction": 0.6882673943, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5757292344878813}} {"text": "module Q.Options.Black76\n (\n Black76(..)\n , atmf\n , euOption\n , eucall\n , euput\n , dPlus\n , dMinus\n )\n where\n\n\nimport Numeric.GSL (derivCentral)\nimport Q.Options (DF, Delta (Delta), Forward (..), Gamma (Gamma), OptionType (..),\n Premium (Premium), Strike (..), TimeScaleable (scale), TotalVar (..),\n Valuation (Valuation, vPremium), Vega (Vega), Vol (..),\n YearFrac (YearFrac), discount)\nimport Q.Options.ImpliedVol.TimeSlice (TimeSlice (..))\nimport Statistics.Distribution (cumulative, density)\nimport Statistics.Distribution.Normal (standard)\nimport Q.Types (LogRelStrike)\n\n\ndata Black76 = Black76 {\n b76F :: Forward\n , b76DF :: DF\n , b76T :: YearFrac\n , b76Vol :: Vol\n}\n\n-- | At the money forward strike.\natmf :: Black76 -> Strike\natmf Black76{..} = Strike f\n where (Forward f) = b76F\n\n-- | European option valuation with black 76\neuOption :: Black76 -> OptionType -> Strike -> Valuation\neuOption Black76{..} cp k = Valuation premium delta vega gamma where\n (Forward f) = b76F\n n = cumulative standard\n (Vol sigmaSqt) = scale b76T b76Vol\n d1 = dPlus b76F b76Vol k b76T\n d2 = dMinus b76F b76Vol k b76T\n nd1 = n d1\n nd2 = n d2\n callDelta = b76DF `discount` nd1\n putDelta = b76DF `discount` (- (n (-d1)))\n vega = Vega $ b76DF `discount` density standard d1 * f * sigmaSqt\n gamma = Gamma $ b76DF `discount` density standard d1 / (f * sigmaSqt)\n premium = Premium $ case cp of\n Call -> b76DF `discount` (f * nd1 - nd2 * k')\n Put -> b76DF `discount` (n (-d2) * k' - n (-d1) * f)\n where (Strike k') = k\n delta | cp == Call = Delta callDelta\n | otherwise = Delta putDelta\n\n-- | see 'euOption'\neuput :: Black76 -> Strike -> Valuation\neuput b76 = euOption b76 Put\n\n-- | see 'euOption'\neucall :: Black76 -> Strike -> Valuation\neucall b76 = euOption b76 Call\n\ndPlus :: Forward -> Vol -> Strike -> YearFrac -> Double\ndPlus (Forward f) (Vol sigma) (Strike k) (YearFrac t) =\n recip (sigma * sqrt t) * (log (f/k) + 0.5 * sigma * sigma * t)\n\ndMinus :: Forward -> Vol -> Strike -> YearFrac -> Double\ndMinus (Forward f) (Vol sigma) (Strike k) (YearFrac t) =\n recip (sigma * sqrt t) * (log (f/k) - 0.5 * sigma * sigma * t)\n\n\ninstance TimeSlice Black76 Strike where\n totalVar Black76{..} _ = TotalVar $ vol * vol * t\n where (Vol vol) = b76Vol\n (YearFrac t) = b76T\n dW _ _ = 0\n d2W _ _ = 0\n\n impliedDensity b76 (Strike k) = let\n dk k' = fst (derivCentral 1e-4 (\\k2 -> let (Premium v) = vPremium (eucall b76 (Strike k2)) in v) k')\n in fst (derivCentral 1e-4 dk k)\n\ninstance TimeSlice Black76 LogRelStrike where\n totalVar Black76{..} _ = TotalVar $ vol * vol * t\n where (Vol vol) = b76Vol\n (YearFrac t) = b76T\n dW _ _ = 0\n d2W _ _ = 0\n\n impliedDensity bs k = impliedDensity f k where\n f :: LogRelStrike -> TotalVar\n f = totalVar bs\n", "meta": {"hexsha": "79aa0f6fc74b2b9c0943d340e2833871608ce372", "size": 3012, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Q/Options/Black76.hs", "max_stars_repo_name": "ghais/HQu", "max_stars_repo_head_hexsha": "442853bb951dde706838d6aa16c619777abb2422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Q/Options/Black76.hs", "max_issues_repo_name": "ghais/HQu", "max_issues_repo_head_hexsha": "442853bb951dde706838d6aa16c619777abb2422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Q/Options/Black76.hs", "max_forks_repo_name": "ghais/HQu", "max_forks_repo_head_hexsha": "442853bb951dde706838d6aa16c619777abb2422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.375, "max_line_length": 104, "alphanum_fraction": 0.5959495352, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5757195453091749}} {"text": "{-# LANGUAGE NamedFieldPuns, TemplateHaskell #-}\n\nmodule School.Unit.Test.MultiNoulli\n( multiNoulliTest ) where\n\nimport Conduit ((.|), await, liftIO, yield)\nimport Data.Default.Class (def)\nimport Numeric.LinearAlgebra ((><))\nimport School.TestUtils (addClasses, assertRight, diffCost, randomMatrix,\n randomNNInts, singleClassOutput, testState, unitCorrect)\nimport School.Train.AppTrain (AppTrain)\nimport School.Train.ForwardPass (forwardPass)\nimport School.Types.FloatEq ((~=))\nimport School.Types.Slinky (Slinky(..), slinkySingleton)\nimport School.Unit.CostFunction (CostFunction(..))\nimport School.Unit.CostParams (CostParams(..))\nimport School.Unit.LogSoftMax (logSoftMax)\nimport School.Unit.MultiNoulli\nimport School.Unit.Unit (Unit(..))\nimport School.Unit.UnitActivation (UnitActivation(..))\nimport School.Unit.UnitGradient (UnitGradient(..))\nimport School.Unit.UnitParams (UnitParams(..))\nimport School.Utils.LinearAlgebra (compareDoubleMatrix)\nimport School.Utils.Tuple (trd3)\nimport Test.Tasty (TestTree)\nimport Test.Tasty.QuickCheck hiding ((><))\nimport Test.Tasty.TH\nimport Test.QuickCheck.Monadic (monadicIO, assert, pre)\n\neps :: Double\neps = 1e-5\n\nprec :: Double\nprec = 5e-2\n\nmulti :: CostFunction Double (AppTrain a)\nmulti = multiNoulli Nothing Nothing\n\nprop_correct_classes :: (Positive Int) -> (Positive Int) -> Property\nprop_correct_classes (Positive c) (Positive b) = monadicIO $ do\n classes <- liftIO $ randomNNInts (c - 1) b\n let out = singleClassOutput c classes\n let params = slinkySingleton $ BatchClassTarget classes\n let cost = computeCost multi out params\n assert $ cost ~= Right (-1)\n\nprop_wrong_classes :: (Positive Int) -> (Positive Int) -> Property\nprop_wrong_classes (Positive c) (Positive b) = monadicIO $ do\n pre $ c > 1\n classes <- liftIO $ randomNNInts (c - 1) b\n let wrong = map (\\k -> mod (k + 1) c) classes\n let out = singleClassOutput c wrong\n let params = slinkySingleton $ BatchClassTarget classes\n let cost = computeCost multi out params\n assert $ cost == Right 0\n\nprop_norm :: (Positive Int) -> (Positive Int) -> Property\nprop_norm (Positive c) (Positive b) = monadicIO $ do\n classes <- liftIO $ randomNNInts (c - 1) b\n input <- liftIO $ BatchActivation <$> randomMatrix b c\n let out = apply logSoftMax EmptyParams input\n let params = slinkySingleton $ BatchClassTarget classes\n let cost = computeCost multi out params\n assertRight (>= (-1)) cost\n\nprop_numerical_deriv :: (Positive Int) -> (Positive Int) -> Property\nprop_numerical_deriv (Positive c) (Positive b) = monadicIO $ do\n pre $ b < 23 && c < 23\n classes <- liftIO $ slinkySingleton . BatchClassTarget <$> randomNNInts (c - 1) b\n input <- liftIO $ BatchActivation <$> randomMatrix b c\n let deriv = derivCost multi input classes\n let check = (b >< c) [ diffCost multi\n input\n eps\n (j, k)\n classes\n | j <- [0..b-1], k <- [0..c-1] ]\n assertRight (\\(BatchGradient g) -> compareDoubleMatrix prec g check)\n deriv\n\nprop_correct_forward_pass :: (Positive Int) -> (Positive Int) -> Property\nprop_correct_forward_pass (Positive c) (Positive b) = monadicIO $ do\n classes <- liftIO $ randomNNInts (c - 1) b\n let forward = forwardPass [unitCorrect classes] multi\n activation <- liftIO $ randomMatrix b c\n let input = ([BatchActivation $ addClasses classes activation], SNil)\n let pass = yield input\n .| forward\n .| await\n result <- testState pass def\n assertRight ((maybe False ((~= (-1)) . trd3)) . fst)\n result\n\nmultiNoulliTest :: TestTree\nmultiNoulliTest = $(testGroupGenerator)\n", "meta": {"hexsha": "8c2e52a620cbdd33211f704507594e8a4338e4bb", "size": 3731, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/School/Unit/Test/MultiNoulli.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/School/Unit/Test/MultiNoulli.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/School/Unit/Test/MultiNoulli.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8645833333, "max_line_length": 83, "alphanum_fraction": 0.6831948539, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5756845805253703}} {"text": "module Lib where\n\nimport Data.Complex\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Storable as S\nimport qualified Data.Vector.Generic as G\nimport Codec.Picture\n\nw :: Int\nw = 500\nh :: Int\nh = 500\nsz :: Float\nsz = fromIntegral st / 2.5\nst :: Int\nst = 30\n\ncolors :: V.Vector PixelRGB8\ncolors = V.fromList [\n PixelRGB8 22 160 133,\n PixelRGB8 192 57 43,\n PixelRGB8 44 62 80,\n PixelRGB8 142 68 173 ]\n\nroots :: [Complex Float]\nroots = [\n 10 :+ 6,\n (-2) :+ 4,\n (-3) :+ (-9),\n 6 :+ (-3) ]\n\nrootsV :: V.Vector (Complex Float)\nrootsV = V.fromList roots\n\ncoefs :: [Complex Float]\ncoefs = coefsFromRoots rootsV\ncoefs' :: [Complex Float]\ncoefs' = deriveCoefs coefs\n\n\npodd :: (Integral a, Num p) => a -> p\npodd n\n | odd n = -1\n | otherwise = 1\n\nbinom :: Int -> Int -> [S.Vector Int]\nbinom n k\n | k < 0 = []\n | k > n = []\n | n <= 0 = [G.empty]\n | k == n = [G.enumFromN 1 n]\n | otherwise = binom (n-1) k ++ ((`G.snoc` n) <$> binom (n-1) (k-1))\n\ncoefsFromRoots :: (Num a, S.Storable a, G.Vector v a) => v a -> [a]\ncoefsFromRoots roots =\n let n = G.length roots\n in [ podd (n-k) * sum [ G.product (G.map (\\i -> roots G.! (i-1)) p) | p <- binom n (n-k) ] | k <- [0..n] ]\n\nderiveCoefs :: Num b => [b] -> [b]\nderiveCoefs coefs = (\\(i, c) -> fromIntegral i * c) <$> zip [1..] (tail coefs)\n\nevalPoly :: Num a => [a] -> a -> a\nevalPoly [] _ = 0\nevalPoly (c0:cs) z = c0 + z * evalPoly cs z\n\nnewton :: (RealFloat a, Num t, Eq t) => t -> [Complex a] -> [Complex a] -> Complex a -> Complex a\nnewton steps coefs coefs' x0 =\n if steps == 0 || magnitude fx < 0.1 then x0\n else newton (steps - 1) coefs coefs' (x0 - fx/fpx)\n where\n fx = evalPoly coefs x0\n fpx = evalPoly coefs' x0\n\nd :: RealFloat a => Complex a -> Complex a -> a\nd c1 c2 = magnitude (c2 - c1)\n\npix :: Int -> Float -> Int -> Int -> PixelRGB8\npix st sz i j =\n let z = realToFrac i / sz :+ realToFrac j / sz\n zr = newton st coefs coefs' z\n (dist, idx) = minimum (zip [d zr r | r <- roots] [0..])\n in colors V.! idx\n", "meta": {"hexsha": "d58186d4f040adc19d4cdcbcac6a54b29c05ce8c", "size": 2049, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "BENICHN/nf", "max_stars_repo_head_hexsha": "fe33dc3d02cd4d7407a86d704e6f3f4191dc728a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "BENICHN/nf", "max_issues_repo_head_hexsha": "fe33dc3d02cd4d7407a86d704e6f3f4191dc728a", "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": "BENICHN/nf", "max_forks_repo_head_hexsha": "fe33dc3d02cd4d7407a86d704e6f3f4191dc728a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.686746988, "max_line_length": 111, "alphanum_fraction": 0.5690580771, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5753569666429574}} {"text": "import Control.Monad.Random\nimport Learning\nimport Data.Set\nimport Numeric.LinearAlgebra\n\nuniformInitializer :: Initializer (Rand StdGen) Double\nuniformInitializer 0 set = pure empty\nuniformInitializer k set = do\n i <- getRandomR (0, Data.Set.size set - 1)\n let a = elemAt i set\n rest <- uniformInitializer (k - 1) (deleteAt i set)\n return (singleton a `union` rest)\n\nmain :: IO ()\nmain = do\n stuff <- rand 1000000 100\n [lin] <- toRows <$> rand 1 100\n [noise] <- toRows <$> randn 1 1000000\n let res = stuff #> lin\n putStrLn \"\\nPrinting least squares fit, then real model which was learned with some noise:\\n\"\n print $ (ols stuff (res + noise) - lin)\n\n-- stuff <- (Data.Set.fromList . toRows) <$> randn 1000 3\n-- (centroids, clusters) <- evalRandIO $ kmeans uniformInitializer 3 stuff\n-- print centroids\n", "meta": {"hexsha": "f08b426606548533185db63484e1b6b70a88fb71", "size": 816, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Spec.hs", "max_stars_repo_name": "SamuelSchlesinger/learning", "max_stars_repo_head_hexsha": "c3f2fd2ed6a3699b836338c35814ef9a6cd1e676", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Spec.hs", "max_issues_repo_name": "SamuelSchlesinger/learning", "max_issues_repo_head_hexsha": "c3f2fd2ed6a3699b836338c35814ef9a6cd1e676", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Spec.hs", "max_forks_repo_name": "SamuelSchlesinger/learning", "max_forks_repo_head_hexsha": "c3f2fd2ed6a3699b836338c35814ef9a6cd1e676", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3846153846, "max_line_length": 95, "alphanum_fraction": 0.6985294118, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.574729566834086}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeInType #-}\n{-# LANGUAGE TypeOperators #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n\nmodule AOC.Common.Numeric (\n fft\n , ifft\n , convolve\n , rconvolve\n , zconvolve\n , FFT.FFTWReal\n ) where\n\nimport Data.Complex\nimport GHC.TypeNats\nimport qualified Data.Array.CArray as CA\nimport qualified Data.Array.IArray as IA\nimport qualified Data.Ix as Ix\nimport qualified Data.Vector.Generic as VG\nimport qualified Data.Vector.Generic.Sized as SVG\nimport qualified Foreign.Storable as FS\nimport qualified Math.FFT as FFT\nimport qualified Math.FFT.Base as FFT\n\nfft :: (FFT.FFTWReal a, VG.Vector v (Complex a))\n => SVG.Vector v n (Complex a)\n -> SVG.Vector v n (Complex a)\nfft = SVG.withVectorUnsafe $\n fromCA\n . FFT.dft\n . toCA\n\nifft\n :: (FFT.FFTWReal a, VG.Vector v (Complex a))\n => SVG.Vector v n (Complex a)\n -> SVG.Vector v n (Complex a)\nifft = SVG.withVectorUnsafe $\n fromCA\n . FFT.idft\n . toCA\n\nfromCA\n :: (FS.Storable a, VG.Vector v (Complex a))\n => CA.CArray Int (Complex a)\n -> v (Complex a)\nfromCA v = VG.generate (Ix.rangeSize (IA.bounds v)) (v IA.!)\n\ntoCA\n :: (FS.Storable a, VG.Vector v (Complex a))\n => v (Complex a)\n -> CA.CArray Int (Complex a)\ntoCA v = IA.listArray (0, VG.length v - 1) (VG.toList v)\n\n-- | FFT-based convolution\nconvolve\n :: ( VG.Vector v (Complex a)\n , KnownNat n, 1 <= n\n , KnownNat m, 1 <= m\n , FFT.FFTWReal a\n )\n => SVG.Vector v n (Complex a)\n -> SVG.Vector v m (Complex a)\n -> SVG.Vector v (n + m - 1) (Complex a)\nconvolve x y = ifft $ fft x' * fft y'\n where\n x' = x SVG.++ 0\n y' = y SVG.++ 0\n\n-- | FFT-based real-valued convolution\nrconvolve\n :: ( VG.Vector v (Complex a)\n , VG.Vector v a\n , KnownNat n, 1 <= n\n , KnownNat m, 1 <= m\n , FFT.FFTWReal a\n )\n => SVG.Vector v n a\n -> SVG.Vector v m a\n -> SVG.Vector v (n + m - 1) a\nrconvolve x y = SVG.map realPart $ convolve (SVG.map (:+ 0) x) (SVG.map (:+ 0) y)\n\n-- | FFT-based integral convolution\nzconvolve\n :: ( VG.Vector v (Complex Double)\n , VG.Vector v Double\n , VG.Vector v a\n , KnownNat n, 1 <= n\n , KnownNat m, 1 <= m\n , Integral a\n )\n => SVG.Vector v n a\n -> SVG.Vector v m a\n -> SVG.Vector v (n + m - 1) a\nzconvolve x y = SVG.map (round @Double) $\n rconvolve (SVG.map fromIntegral x) (SVG.map fromIntegral y)\n", "meta": {"hexsha": "39360880725fa54dd6a4a58b68cd10f43eccf133", "size": 2768, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AOC/Common/Numeric.hs", "max_stars_repo_name": "mstksg/advent-of-code-2019", "max_stars_repo_head_hexsha": "6157693f9e46ff954b168827e2cdb3d246d2b381", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2019-11-07T00:26:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T18:46:58.000Z", "max_issues_repo_path": "src/AOC/Common/Numeric.hs", "max_issues_repo_name": "mstksg/advent-of-code-2019", "max_issues_repo_head_hexsha": "6157693f9e46ff954b168827e2cdb3d246d2b381", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-12-04T10:08:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-08T14:51:01.000Z", "max_forks_repo_path": "src/AOC/Common/Numeric.hs", "max_forks_repo_name": "mstksg/advent-of-code-2019", "max_forks_repo_head_hexsha": "6157693f9e46ff954b168827e2cdb3d246d2b381", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-12-02T17:24:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T07:59:16.000Z", "avg_line_length": 27.9595959596, "max_line_length": 81, "alphanum_fraction": 0.5531069364, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5747295470409043}} {"text": "{-# LANGUAGE CPP #-}\nmodule Driver (\n E,\n \n Nat(..),\n Nat2(..),\n Pos(..),\n Pos2(..),\n Index(..),\n Index2(..),\n Assocs(..),\n Assocs2(..),\n BandedAssocs(..),\n \n module Control.Arrow,\n module Control.Monad,\n module Control.Monad.ST,\n \n AEq,\n (===),\n (~==),\n module Data.Function,\n module Data.Ix,\n module Data.List,\n module Data.Ord,\n \n module Debug.Trace,\n \n module Test.QuickCheck,\n \n module Text.Printf,\n\n field,\n\n module Test.Framework,\n module Test.Framework.Providers.QuickCheck2,\n ) where\n\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.AEq( AEq )\nimport qualified Data.AEq as AEq\nimport Data.Complex\nimport Data.Ix\nimport Data.Function\nimport Data.List\nimport Data.Ord\n\nimport Debug.Trace\n\nimport System.IO\nimport System.Random\n\nimport Test.Vector.Dense()\nimport Test.Matrix.Dense()\nimport Test.Matrix.Banded()\n\nimport Test.QuickCheck hiding ( vector )\nimport Test.QuickCheck.BLAS( Nat(..), Nat2(..), Pos(..), Pos2(..), \n Index(..), Index2(..), Assocs(..), Assocs2(..), BandedAssocs(..) )\nimport qualified Test.QuickCheck.BLAS as Test\n\nimport Test.Framework\nimport Test.Framework.Providers.QuickCheck2\n\nimport Text.Printf\nimport Text.Show.Functions\n\n#ifdef COMPLEX\nfield = \"Complex Double\"\ntype E = Complex Double \n#else\nfield = \"Double\"\ntype E = Double\n#endif\n\ninfix 4 ===, ~==\n\nx === y | (AEq.===) x y = True\n | otherwise = trace (printf \"expected `%s', but got `%s'\" (show y) (show x)) False\n\nx ~== y | (AEq.~==) x y = True\n | otherwise = trace (printf \"expected `%s', but got `%s'\" (show y) (show x)) False\n", "meta": {"hexsha": "7072b7380294c5dac27dbbd6aef750f34ec8952c", "size": 1664, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests-old/Driver.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "tests-old/Driver.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests-old/Driver.hs", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 19.3488372093, "max_line_length": 90, "alphanum_fraction": 0.6286057692, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7341195210831258, "lm_q1q2_score": 0.5745678116618009}} {"text": "\nmodule Main (main) where\n\n-- package \u306e import\n-- CSV\u306e\u8aad\u307f\u8fbc\u307f\nimport qualified Text.CSV as CSV\nimport qualified Data.Text as T\nimport Data.Text\nimport Data.Attoparsec.Text as DAT\n\n-- \u53ef\u8996\u5316\nimport Graphics.Rendering.Chart.Easy hiding ( (:<))\nimport Graphics.Rendering.Chart.Backend.Cairo\nimport Graphics.Rendering.Chart.Axis\nimport Graphics.Rendering.Chart.Axis.Int\nimport Graphics.Rendering.Chart.Grid\n\n-- \u91cd\u56de\u5e30\nimport Statistics.Regression\n\n-- \u305d\u306e\u4ed6\nimport qualified Control.Monad as CM\nimport qualified Data.List as L\nimport qualified Data.Vector.Unboxed as VU\n\n-- | Double\u306e\u30d1\u30fc\u30b5\n{-# INLINE parseDouble #-}\nparseDouble :: Text -> Double\nparseDouble tx = case DAT.parseOnly DAT.double tx of\n Right r -> r\n Left l -> error $ \"Error on parseDouble : \" ++ show l\n\n\ntype Title = String\ntype FileName = String\ntype Label = String\n\n-- | \u6298\u308c\u7dda\u30b0\u30e9\u30d5\u306e\u4f5c\u6210\nplotLine :: (PlotValue a, PlotValue b) => [(Label, [(a, b)])] -> FileName -> Title -> IO ()\nplotLine xs file title\n = toFile def (file ++ \".png\") $ do\n layout_title .= title\n CM.forM_ xs $ \\(title,ys) -> plot $ line title [ys]\n\nplotBar :: [(String,[Double])] -> FileName -> Title -> [Label] -> IO ()\nplotBar xs file title labels\n = toFile def (file ++ \".png\") $ do\n layout_title .= title\n layout_title_style . font_size .= 10\n layout_x_axis . laxis_generate .= autoIndexAxis (L.map fst xs)\n plot $ fmap plotBars $ bars labels (addIndexes (L.map snd xs))\n\n\n-- | \u6563\u5e03\u56f3\u306e\u4f5c\u6210\nplotGridPoints :: (PlotValue a, PlotValue b)\n => [[[(Label, [(a, b)])]]] -> FileName -> Title -> IO ()\nplotGridPoints xs file name\n = let ys = aboveN $ (flip L.map) xs\n $ \\ cols -> besideN\n $ (flip L.map) cols -- columns\n $ \\ series -> layoutToGrid\n $ execEC\n $ CM.forM_ series\n $ \\(t,xs) -> plot $ points t xs\n in CM.void $ renderableToFile def (file ++ \".png\")\n $ fillBackground def\n $ gridToRenderable\n $ title `wideAbove` ys\n where\n title = setPickFn nullPickFn $ label ls HTA_Centre VTA_Centre name\n ls = def { _font_size = 15 , _font_weight = FontWeightBold }\n\n\n\nmain = do\n -- CSV\u30d5\u30a1\u30a4\u30eb\u306e\u8aad\u307f\u8fbc\u307f\n -- Data\u30d5\u30a9\u30eb\u30c0\u3092\u4f5c\u6210\u3057,\u305d\u3053\u306b\u30c7\u30fc\u30bf\u3092\u5165\u308c\u3066\u304a\u304d\u307e\u3057\u3087\u3046\n xs <- CSV.parseCSVFromFile \"Data/multiple_regression_test.csv\" >>= \\res\n -> case res of\n Right xs -> return $ L.map (L.map T.pack) xs\n Left xs -> error $ \"error on parseCSVFromFile: \" ++ show xs\n\n -- Header\u306e\u62bd\u51fa Vector\u3078\u306e\u5909\u63db\n let headers = L.map T.unpack\n $ L.head xs\n\n -- \u5024\u306eDouble\u3078\u306e\u5909\u63db Vector\u3078\u306e\u5909\u63db\n let body = L.transpose\n $ L.map (L.map parseDouble)\n $ L.tail xs\n\n let year = body !! 0\n death = body !! 1\n index = body !! 2\n hospital = body !! 3\n\n -- \u30c7\u30fc\u30bf\u3092\u30b0\u30e9\u30d5\u3067\u8868\u793a\n plotLine (L.map (\\(x,y) -> (x, L.zip year y))\n [(\"Number of Death\", death)\n ,(\"Economic Indicators\", index)\n ,(\"Number of Hospitals\", hospital)])\n \"Data/initial_data\"\n \"Data Visualization\"\n\n -- \u6563\u5e03\u56f3\u884c\u5217\u3092\u4f5c\u6210\u3059\u308b\n plotGridPoints [[[(xt ++ \"_\" ++ yt, L.zip xs ys)]\n | (yt,ys) <- L.zip (L.tail headers) (L.tail body)]\n | (xt,xs) <- L.zip (L.tail headers) (L.tail body)]\n \"Data/plot_matrix\"\n \"Plot Matrix\"\n\n -- heatmap \u306e\u4f5c\u6210\u306f\u3061\u3087\u3063\u3068\u96e3\u3057\u3044\u306e\u3067pass\n\n -- \u91cd\u56de\u5e30\n let (coeffs, r2) = olsRegress [ VU.fromList index\n , VU.fromList hospital]\n ( VU.fromList death)\n\n putStrLn $ \"\u56de\u5e30\u4fc2\u6570:\" ++ show (L.init (VU.toList coeffs))\n putStrLn $ \"\u5207\u7247:\" ++ show (L.last (VU.toList coeffs))\n\n -- \u7d50\u679c\u306e\u30d7\u30ed\u30c3\u30c8\n plotBar (L.zipWith (\\x y -> (x,[y]))\n [\"Economic Indicators\", \"Number of Hospitals\"]\n (L.init (VU.toList coeffs)))\n \"Data/bar_result\"\n \"Plot Result\"\n [\"Coeff\"]\n\n\n\n\n\n\n", "meta": {"hexsha": "e2b6b3cb7c1892139018067688c715ade7dcc32e", "size": 4303, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/MultipleRegression.hs", "max_stars_repo_name": "yakagika/stat_hs", "max_stars_repo_head_hexsha": "8cfc9c5a04a00fc2fe0a71a9abf74aea14e05dec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/MultipleRegression.hs", "max_issues_repo_name": "yakagika/stat_hs", "max_issues_repo_head_hexsha": "8cfc9c5a04a00fc2fe0a71a9abf74aea14e05dec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/MultipleRegression.hs", "max_forks_repo_name": "yakagika/stat_hs", "max_forks_repo_head_hexsha": "8cfc9c5a04a00fc2fe0a71a9abf74aea14e05dec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8740740741, "max_line_length": 91, "alphanum_fraction": 0.5163839182, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5745678058811086}} {"text": "{-|\nModule : Qubism.QGate\nDescription : Types and functions for quantum gates\nCopyright : (c) Keith Pearson, 2018\nLicense : MIT\nMaintainer : keith@qubitrot.org\n-}\n\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule Qubism.QGate \n ( QGate\n , (#>)\n , gate\n , ident\n , pauliX\n , pauliY\n , pauliZ\n , hadamard\n , unitary\n , cnot\n , controlled\n , ifBit\n , kronecker\n , onJust\n , onEvery\n , onRange\n ) where\n\n-- For dependent typing\nimport GHC.TypeLits\nimport Data.Singletons\nimport Data.Singletons.TypeLits\nimport Data.Finite\n\nimport Data.Complex\nimport Data.Monoid\nimport Control.Monad.Trans.State.Strict\nimport Numeric.LinearAlgebra ((><))\nimport qualified Numeric.LinearAlgebra as LA\n\nimport Qubism.Algebra\nimport Qubism.StateVec\nimport Qubism.CReg\n\nnewtype QGate (n :: Nat) = \n UnsafeMkQGate (LA.Matrix C) -- must be a (2^n) x (2^n) unitary matrix\n deriving (Show)\n\n-- | \"Close enough\" equality testing\ninstance Eq (QGate n) where\n (UnsafeMkQGate a) == (UnsafeMkQGate b) =\n LA.norm_2 (a - b) < 0.000001\n\ninstance KnownNat n => Semigroup (QGate n) where\n (UnsafeMkQGate a) <> (UnsafeMkQGate b) = UnsafeMkQGate $ a LA.<> b\n\ninstance KnownNat n => Monoid (QGate n) where\n mempty = ident\n\ninstance KnownNat n => VectorSpace (QGate n) where\n zero = UnsafeMkQGate . (l> Algebra (QGate n) where\n (*:) = (<>)\n\ninternalLen :: (KnownNat n, Num a) => Sing n -> a\ninternalLen = (2 ^) . fromIntegral . fromSing \n\n-- | Apply a quantum gate to a quantum register. Note that this\n-- operator conflicts with the one from Numeric.LinearAlgebra.\ninfixr 5 #>\n(#>) :: QGate n -> StateVec n -> StateVec n\n(#>) (UnsafeMkQGate m) (UnsafeMkStateVec v) = UnsafeMkStateVec $ m LA.#> v\n\n-- | Helper function to make state computations nicer\ngate :: Monad m => QGate n -> StateT (StateVec n) m ()\ngate g = state $ \\qr -> ((), g #> qr)\n\nident :: forall n . KnownNat n => QGate n\nident = UnsafeMkQGate . LA.ident $ internalLen (sing :: Sing n)\n\n-- | Also known as a NOT gate\npauliX :: QGate 1\npauliX = UnsafeMkQGate $\n (2><2) [0 :+ 0, 1 :+ 0,\n 1 :+ 0, 0 :+ 0]\n\npauliY :: QGate 1\npauliY = UnsafeMkQGate $\n (2><2) [0 :+ 0, 0 :+ (-1),\n 0 :+ 1, 0 :+ 0]\n\npauliZ :: QGate 1\npauliZ = UnsafeMkQGate $\n (2><2) [1 :+ 0, 0 :+ 0,\n 0 :+ 0, (-1) :+ 0]\n\nhadamard :: QGate 1\nhadamard = UnsafeMkQGate $ 1 / sqrt 2 *\n (2><2) [1 :+ 0, 1 :+ 0,\n 1 :+ 0, (-1) :+ 0]\n\n-- | An arbitrary element of SU(2),\n-- U(theta, phi, lambda)\nunitary :: Double -> Double -> Double -> QGate 1\nunitary theta phi lambda = UnsafeMkQGate $ \n (2><2) [a, b, c, d]\n where a = cis (phi+lambda/2) * ( cos (theta/2) :+ 0 )\n b = -cis (phi-lambda/2) * ( sin (theta/2) :+ 0 )\n c = cis (phi-lambda/2) * ( sin (theta/2) :+ 0 )\n d = cis (phi+lambda/2) * ( cos (theta/2) :+ 0 )\n\n-- | Controlled not between control and target qubits\ncnot :: KnownNat n => Finite n -> Finite n -> QGate n\ncnot c t = controlled c . onJust t $ pauliX\n\n-- | Transform an arbitrary QGate into a controled one depending on qubit i\ncontrolled :: forall n . KnownNat n => Finite n -> QGate n -> QGate n\ncontrolled finite (UnsafeMkQGate m) = \n UnsafeMkQGate $ (m <> projection) + LA.ident (2^n) - projection\n where \n projection = LA.diag $ (2^n) LA.|> fmap f [0..]\n f j = fromIntegral $ j `quot` 2^(n-i-1) `mod` 2\n n = fromIntegral $ fromSing (sing :: Sing n)\n i = fromIntegral $ getFinite finite\n\n-- | If the given Bit is One then apply the gate, otherwise\n-- do nothing\nifBit :: KnownNat n => Bit -> QGate n -> QGate n\nifBit b g = if (b == One) then g else ident\n\n-- | The tensor product of a QGate's A and B is a QGate that acts as A on the \n-- first n qubits and B on the rest. In the computational basis this is simply\n-- the kronecker product of matricies.\nkronecker :: QGate n -> QGate m -> QGate (m+n)\nkronecker (UnsafeMkQGate a) (UnsafeMkQGate b) =\n UnsafeMkQGate $ LA.kronecker a b\n\n-- | Promote a 1-qubit gate to an n-qubit gate with the original gate acting \n-- on qubit i. Other qubits are unaffected.\nonJust :: forall n . KnownNat n => Finite n -> QGate 1 -> QGate n\nonJust i (UnsafeMkQGate m) = UnsafeMkQGate $ -- it should be possible to do\n pre `LA.kronecker` m `LA.kronecker` post -- this with just QGate's \n where pre = LA.ident $ 2^j -- kronecker, but I can't get\n post = LA.ident $ 2^(n-j-1) -- the types to check.\n j = fromIntegral $ getFinite i\n n = fromIntegral $ fromSing (sing :: Sing n)\n\n-- | Promote a 1-qubit gate to an n-qubit gate which acts on every qubit\n-- identically.\nonEvery :: forall n . KnownNat n => QGate 1 -> QGate n\nonEvery (UnsafeMkQGate m) = UnsafeMkQGate $ iterate (LA.kronecker m) m !! (n-1)\n where n = fromIntegral $ fromSing (sing :: Sing n)\n\n-- | Promote a 1-qubit gate to an n-qubit gate which acts on a range of\n-- qubits, leaving others untouched\nonRange :: forall n . KnownNat n => Finite n -> Finite n -> QGate 1 -> QGate n\nonRange f l m = mconcat $ map (\\i -> onJust i m) [f..l]\n", "meta": {"hexsha": "0325fb6b2d30f6bd0714883d01e5e052bdde1ad8", "size": 5414, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Qubism/QGate.hs", "max_stars_repo_name": "qubitrot/qubism", "max_stars_repo_head_hexsha": "41d2fd594d338affdfe1736aec422d75c2cc9401", "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/Qubism/QGate.hs", "max_issues_repo_name": "qubitrot/qubism", "max_issues_repo_head_hexsha": "41d2fd594d338affdfe1736aec422d75c2cc9401", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-09-17T20:07:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T03:29:45.000Z", "max_forks_repo_path": "src/Qubism/QGate.hs", "max_forks_repo_name": "qubitrot/qubism", "max_forks_repo_head_hexsha": "41d2fd594d338affdfe1736aec422d75c2cc9401", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6144578313, "max_line_length": 81, "alphanum_fraction": 0.6268932397, "num_tokens": 1846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5745270572345185}} {"text": "module Main where\n\nimport Embadd\n\nimport qualified Data.Map.Strict as M (fromList, toList, size, lookup)\nimport Numeric.LinearAlgebra as LA\nimport System.Environment\n\nmain :: IO ()\nmain = do\n (vectorFile:args) <- getArgs\n case vectorFile of\n \"--help\" -> putStrLn \"Usage: ./emb.hs FILE\"\n \"NORM\" -> computeNorm (head args)\n _ -> do\n vectorCont <- readFile vectorFile\n let vLine (w:ws) = (w, vector $ map read ws :: Vector Double)\n vectorDict = M.fromList . map (vLine . words) . drop 1 . lines $ vectorCont\n putStrLn \"Embedding vizualization tool\"\n putStrLn \"============================\"\n putStrLn \"\"\n putStrLn \"W1 + W2 - W3 -> nearest neighbours of v(W1) + v(W2) - v(W3); you can use any expression with words, '+' and '-'\"\n putStrLn \"PCA W1 W2 ... Wn -> pca.png will contain {v(W1), ..., v(Wn)} projected to their principal components\"\n readEvalPrintLoop vectorDict\n", "meta": {"hexsha": "b500ee6074c92f983f23d67a1f2bb0e38577329d", "size": 928, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "tomasmcz/embadd", "max_stars_repo_head_hexsha": "59a5412e873fe4d7fc2da1087dd770e9d5fc2644", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "tomasmcz/embadd", "max_issues_repo_head_hexsha": "59a5412e873fe4d7fc2da1087dd770e9d5fc2644", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "tomasmcz/embadd", "max_forks_repo_head_hexsha": "59a5412e873fe4d7fc2da1087dd770e9d5fc2644", "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.12, "max_line_length": 128, "alphanum_fraction": 0.6282327586, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5745098982879084}} {"text": "{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module : Statistics.Distribution.Binomial\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- The binomial distribution. This is the discrete probability\n-- distribution of the number of successes in a sequence of /n/\n-- independent yes\\/no experiments, each of which yields success with\n-- probability /p/.\n\nmodule Statistics.Distribution.Binomial\n (\n BinomialDistribution\n -- * Constructors\n , binomial\n -- * Accessors\n , bdTrials\n , bdProbability\n ) where\n\nimport Data.Aeson (FromJSON, ToJSON)\nimport Data.Binary (Binary)\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport qualified Statistics.Distribution as D\nimport qualified Statistics.Distribution.Poisson.Internal as I\nimport Numeric.SpecFunctions (choose,incompleteBeta)\nimport Numeric.MathFunctions.Constants (m_epsilon)\nimport Data.Binary (put, get)\nimport Control.Applicative ((<$>), (<*>))\n\n\n-- | The binomial distribution.\ndata BinomialDistribution = BD {\n bdTrials :: {-# UNPACK #-} !Int\n -- ^ Number of trials.\n , bdProbability :: {-# UNPACK #-} !Double\n -- ^ Probability.\n } deriving (Eq, Read, Show, Typeable, Data, Generic)\n\ninstance FromJSON BinomialDistribution\ninstance ToJSON BinomialDistribution\n\ninstance Binary BinomialDistribution where\n put (BD x y) = put x >> put y\n get = BD <$> get <*> get\n\ninstance D.Distribution BinomialDistribution where\n cumulative = cumulative\n\ninstance D.DiscreteDistr BinomialDistribution where\n probability = probability\n\ninstance D.Mean BinomialDistribution where\n mean = mean\n\ninstance D.Variance BinomialDistribution where\n variance = variance\n\ninstance D.MaybeMean BinomialDistribution where\n maybeMean = Just . D.mean\n\ninstance D.MaybeVariance BinomialDistribution where\n maybeStdDev = Just . D.stdDev\n maybeVariance = Just . D.variance\n\ninstance D.Entropy BinomialDistribution where\n entropy (BD n p)\n | n == 0 = 0\n | n <= 100 = directEntropy (BD n p)\n | otherwise = I.poissonEntropy (fromIntegral n * p)\n\ninstance D.MaybeEntropy BinomialDistribution where\n maybeEntropy = Just . D.entropy\n\n-- This could be slow for big n\nprobability :: BinomialDistribution -> Int -> Double\nprobability (BD n p) k\n | k < 0 || k > n = 0\n | n == 0 = 1\n | otherwise = choose n k * p^k * (1-p)^(n-k)\n\n-- Summation from different sides required to reduce roundoff errors\ncumulative :: BinomialDistribution -> Double -> Double\ncumulative (BD n p) x\n | isNaN x = error \"Statistics.Distribution.Binomial.cumulative: NaN input\"\n | isInfinite x = if x > 0 then 1 else 0\n | k < 0 = 0\n | k >= n = 1\n | otherwise = incompleteBeta (fromIntegral (n-k)) (fromIntegral (k+1)) (1 - p)\n where\n k = floor x\n\nmean :: BinomialDistribution -> Double\nmean (BD n p) = fromIntegral n * p\n\nvariance :: BinomialDistribution -> Double\nvariance (BD n p) = fromIntegral n * p * (1 - p)\n\ndirectEntropy :: BinomialDistribution -> Double\ndirectEntropy d@(BD n _) =\n negate . sum $\n takeWhile (< negate m_epsilon) $\n dropWhile (not . (< negate m_epsilon)) $\n [ let x = probability d k in x * log x | k <- [0..n]]\n\n-- | Construct binomial distribution. Number of trials must be\n-- non-negative and probability must be in [0,1] range\nbinomial :: Int -- ^ Number of trials.\n -> Double -- ^ Probability.\n -> BinomialDistribution\nbinomial n p\n | n < 0 =\n error $ msg ++ \"number of trials must be non-negative. Got \" ++ show n\n | p < 0 || p > 1 =\n error $ msg++\"probability must be in [0,1] range. Got \" ++ show p\n | otherwise = BD n p\n where msg = \"Statistics.Distribution.Binomial.binomial: \"\n", "meta": {"hexsha": "eab8e9ae11a9c15cedcb6a32adbdb1e9a44f4fab", "size": 3857, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Binomial.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "Statistics/Distribution/Binomial.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Distribution/Binomial.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1048387097, "max_line_length": 83, "alphanum_fraction": 0.6759139227, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915959134569, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5745098842540768}} {"text": "{-# LANGUAGE ViewPatterns, ScopedTypeVariables, TupleSections #-}\n\nimport qualified Text.Printf as TP (printf)\nimport qualified Data.List as L (intercalate)\n\nimport Data.Array.Repa (Z(Z), (:.)((:.)), (!), (-^), (+^), (*^), All(All), Any(Any), extent, size)\nimport qualified Data.Array.Repa as RP (fromFunction, fromListUnboxed, Array, U, D, DIM1, DIM2, DIM4, map)\nimport qualified Data.Array.Repa as RP (sumAllS, slice, delay, computeS, toList)\nimport qualified Data.Array.Repa.Repr.Vector as RP (V, fromListVector)\nimport Data.Complex (Complex((:+)), realPart, imagPart)\nimport Data.Bits (bit)\n\npdim1 :: RP.Array RP.U RP.DIM1 (Complex Double) -> String\npdim1 mat = pt ++ \"\\n\" where\n (Z :. n) = extent mat\n pt = concat [ let (xr :+ xi) = mat ! (Z :. i) in TP.printf \"%14.4f +I %8.4f\" xr xi | i <- [0 .. n - 1] ]\n\npdim2 :: RP.Array RP.U RP.DIM2 (Complex Double) -> String\npdim2 mat = L.intercalate \"\\n\" [ pt i | i <- [0 .. m - 1]] ++ \"\\n\\n\" where\n (Z :. m :. n) = extent mat\n pt i = concat [ let (xr :+ xi) = mat ! (Z :. i :. j) in TP.printf \"%14.4f +I %8.4f\" xr xi | j <- [0 .. n - 1] ]\n\nidentity :: RP.Array RP.U RP.DIM2 (Complex Double)\nidentity = RP.fromListUnboxed (Z :. 2 :. 2) [1, 0, 0, 1]\n\nsigmaX :: RP.Array RP.U RP.DIM2 (Complex Double)\nsigmaX = RP.fromListUnboxed (Z :. 2 :. 2) [0, 1, 1, 0]\n\nsigmaY :: RP.Array RP.U RP.DIM2 (Complex Double)\nsigmaY = RP.fromListUnboxed (Z :. 2 :. 2) [0, 0 :+ (-1), 0 :+ 1, 0]\n\nsigmaZ :: RP.Array RP.U RP.DIM2 (Complex Double)\nsigmaZ = RP.fromListUnboxed (Z :. 2 :. 2) [1, 0, 0, -1]\n\n-- | Tensor product.\nkron :: RP.Array RP.U RP.DIM2 (Complex Double)\n -> RP.Array RP.U RP.DIM2 (Complex Double)\n -> RP.Array RP.U RP.DIM2 (Complex Double)\nkron mata matb = reduceBlock . RP.computeS $ RP.fromFunction (extent mata) iter where\n iter i = RP.computeS $ RP.map (* (mata ! i)) matb :: RP.Array RP.U RP.DIM2 (Complex Double)\n\n-- | Heisenberg Hamiltonian\nhamil :: RP.Array RP.U RP.DIM2 (Complex Double)\nhamil = RP.computeS $ RP.map (* 0.25) (((kron sigmaX identity) `mmult` (kron identity sigmaX))\n +^ ((kron sigmaY identity) `mmult` (kron identity sigmaY))\n +^ ((kron sigmaZ identity) `mmult` (kron identity sigmaZ)))\n\n-- | S^2 Operator\ns2 :: RP.Array RP.U RP.DIM2 (Complex Double)\ns2 = RP.computeS $ RP.map (* 0.25) (\n square (RP.computeS $ kron sigmaX identity +^ kron identity sigmaX)\n +^ square (RP.computeS $ kron sigmaY identity +^ kron identity sigmaY)\n +^ square (RP.computeS $ kron sigmaZ identity +^ kron identity sigmaZ))\n\n-- | Square of a matrix\nsquare :: RP.Array RP.U RP.DIM2 (Complex Double) -> RP.Array RP.U RP.DIM2 (Complex Double)\nsquare mat = mmult mat mat\n\n-- | Matrix Matrix Multiplication\nmmult :: RP.Array RP.U RP.DIM2 (Complex Double)\n -> RP.Array RP.U RP.DIM2 (Complex Double)\n -> RP.Array RP.U RP.DIM2 (Complex Double)\nmmult mata matb = RP.computeS $ RP.fromFunction (Z :. n :. m) iter where\n (Z :. n :. k) = extent mata\n (Z :. kp :. m) = extent matb\n iter :: RP.DIM2 -> Complex Double\n iter (Z :. i :. j) = RP.sumAllS $ RP.slice mata (Any :. i :. All) *^ RP.slice matb (Any :. All :. j)\n\n-- | Matrix Vector Multiplication\nmvmult :: RP.Array RP.U RP.DIM2 (Complex Double)\n -> RP.Array RP.U RP.DIM1 (Complex Double)\n -> RP.Array RP.U RP.DIM1 (Complex Double)\nmvmult mat vec = RP.computeS $ RP.fromFunction (Z :. n) iter where\n (Z :. n :. m) = extent mat\n iter :: RP.DIM1 -> Complex Double\n iter (Z :. i) = RP.sumAllS $ RP.slice mat (Any :. i :. All) *^ vec\n\n-- | Vector Vector Dot Product\ndot :: RP.Array RP.U RP.DIM1 (Complex Double) -> RP.Array RP.U RP.DIM1 (Complex Double) -> Complex Double\ndot veca vecb = RP.sumAllS $ veca *^ vecb\n\n-- | Reduce blocked matrix to regular matrix.\nreduceBlock :: RP.Array RP.V RP.DIM2 (RP.Array RP.U RP.DIM2 (Complex Double)) -- ^ matrix of blocks\n -> RP.Array RP.U RP.DIM2 (Complex Double)\nreduceBlock mat = RP.computeS $ RP.fromFunction (Z :. nl :. nl) iter where\n f :: Int -> RP.Array RP.U RP.DIM2 (Complex Double) -> [(Int, Int)]\n f i block = let (Z :. _ :. n) = extent block in map (i, ) [0..n - 1]\n idx = let l = concat (zipWith f [0..] (RP.toList (RP.slice mat (Any :. (0 :: Int) :. All))))\n in RP.fromListUnboxed (Z :. (length l)) l\n (Z :. nl) = extent idx\n iter (Z :. i :. j) = let (ip, im) = idx ! (Z :. i); (jp, jm) = idx ! (Z :. j)\n in (mat ! (Z :. ip :. jp)) ! (Z :. im :. jm)\n\n-- alpha = 0, beta = 1\n-- |babb> = 1011 = 11\nstateIndex :: String -> Int\nstateIndex x = iter (length x - 1) x where\n iter n (x:xs) = (if n == 0 then 0 else iter (n - 1) xs) + (if x == 'a' then 0 else bit n) \n\n-- | The kth eigenstate represented as n-component vector\neigenState :: Int -> Int -> RP.Array RP.U RP.DIM1 (Complex Double)\neigenState n k = RP.computeS $ RP.fromFunction (Z :. n) (\\(Z :. i) -> if k == i then 1 else 0)\n\nstate_ab = eigenState (bit 2) $ stateIndex \"ab\"\nstate_ba = eigenState (bit 2) $ stateIndex \"ba\"\nstate_aa = eigenState (bit 2) $ stateIndex \"aa\"\nstate_bb = eigenState (bit 2) $ stateIndex \"bb\"\nsinglet = RP.computeS $ RP.map (* (2 ** (-0.5))) (state_ab -^ state_ba)\ntriplet = RP.computeS $ RP.map (* (2 ** (-0.5))) (state_ab +^ state_ba)\n\nmain = do\n putStrLn $ \"[Singlet] (Si . Sj) S^2\"\n print $ let state = singlet in dot state (hamil `mvmult` state)\n print $ let state = singlet in dot state (s2 `mvmult` state)\n putStrLn $ \"[Triplet] (Si . Sj) S^2\"\n print $ let state = triplet in dot state (hamil `mvmult` state)\n print $ let state = triplet in dot state (s2 `mvmult` state)\n putStrLn $ \"[|aa>] (Si . Sj) S^2\"\n print $ let state = state_aa in dot state (hamil `mvmult` state)\n print $ let state = state_aa in dot state (s2 `mvmult` state)\n", "meta": {"hexsha": "4922a44ce63a4b2eaf454cdc67737ea37dc14e75", "size": 5708, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/heisenberg.hs", "max_stars_repo_name": "stczhc/notes", "max_stars_repo_head_hexsha": "638960a1373ec2bbe2116757643075e1a21080cd", "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/heisenberg.hs", "max_issues_repo_name": "stczhc/notes", "max_issues_repo_head_hexsha": "638960a1373ec2bbe2116757643075e1a21080cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/heisenberg.hs", "max_forks_repo_name": "stczhc/notes", "max_forks_repo_head_hexsha": "638960a1373ec2bbe2116757643075e1a21080cd", "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.173553719, "max_line_length": 115, "alphanum_fraction": 0.6154519972, "num_tokens": 1965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5744153074220811}} {"text": "{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeApplications, DataKinds, GADTs #-}\n{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies #-}\n\n\nmodule Lib\n ( someFunc\n ) where\n\n\nimport Data.Maybe ( fromMaybe )\nimport Data.Int (Int32)\nimport Linear.V1\nimport Linear.V3\nimport Linear.V4 hiding (vector)\nimport Linear.Matrix\nimport Linear.Metric (dot, norm)\nimport Graphics.UI.GLUT ( Key(..), SpecialKey(..), MouseButton(..), KeyState(..) )\nimport Vis\nimport Vis.Vis ( vis )\nimport Vis.Camera ( makeCamera, setCamera, cameraMotion, cameraKeyboardMouse, Camera )\nimport Control.Lens\nimport Control.Applicative\nimport Control.Monad (forever)\nimport Numeric.AD\nimport Numeric.LinearAlgebra ((#>), det, fromLists, fromList, toList, pinv, inv, vector, matrix, Vector, Matrix, scale, norm_2)\n--import Debug.Trace\n\n\nrotM33XYZ :: (Floating f) => f -> f -> f -> M33 f\nrotM33XYZ r p y = rotM33Z y !*! rotM33Y p !*! rotM33X r\n\nrotM33X :: (Floating f) => f -> M33 f\nrotM33X a = V3 (V3 1 0 0) (V3 0 ca (-sa)) (V3 0 sa ca) where\n ca = cos a\n sa = sin a\n\nrotM33Y :: (Floating f) => f -> M33 f\nrotM33Y a = V3 (V3 ca 0 sa) (V3 0 1 0) (V3 (-sa) 0 ca) where\n ca = cos a\n sa = sin a\n\nrotM33Z :: (Floating f) => f -> M33 f\nrotM33Z a = V3 (V3 ca (-sa) 0) (V3 sa ca 0) (V3 0 0 1) where\n ca = cos a\n sa = sin a\n\nprintV4 :: (Show f) => V4 f -> IO ()\nprintV4 (V4 v1 v2 v3 v4) = print [v1, v2, v3, v4]\n\nprintV3 :: (Show f) => V3 f -> IO ()\nprintV3 (V3 v1 v2 v3) = print [v1, v2, v3]\n\nprintM33 :: (Show f) => M33 f -> IO ()\nprintM33 (V3 v1 v2 v3) = do\n putStrLn \"\"\n printV3 v1\n printV3 v2\n printV3 v3\n putStrLn \"\"\n\nprintM44 :: (Show f) => M44 f -> IO ()\nprintM44 (V4 v1 v2 v3 v4) = do\n putStrLn \"\"\n printV4 v1\n printV4 v2\n printV4 v3\n printV4 v4\n putStrLn \"\"\n\nrotM44X :: (Floating f) => f -> M44 f\nrotM44X a = identity & _m33 .~ rotM33X a\n\nrotM44Z :: (Floating f) => f -> M44 f\nrotM44Z a = identity & _m33 .~ rotM33Z a\n\ntransM44X :: (Floating f) => f -> M44 f\ntransM44X a = identity & translation .~ V3 a 0 0\n\ntransM44Z :: (Floating f) => f -> M44 f\ntransM44Z a = identity & translation .~ V3 0 0 a\n\ntwistX :: (Floating f) => f -> f -> M44 f\ntwistX d theta = transM44X d !*! rotM44X theta\n\ntwistZ :: (Floating f) => f -> f -> M44 f\ntwistZ d theta = transM44Z d !*! rotM44Z theta\n\nskew :: (Floating f) => V3 f -> M33 f\nskew (V3 x y z) = V3 (V3 0 (-z) y) (V3 z 0 (-x)) (V3 (-y) x 0)\n\ninvSkew :: (Floating f) => M33 f -> V3 f\ninvSkew (V3 (V3 _ _ y) (V3 z _ _) (V3 _ x _)) = V3 x y z\n\nrodrigues :: (Eq f, Floating f) => V3 f -> M33 f\nrodrigues r = identity !!* ct !+! rrt !!* (1 - ct) !+! sr !!* st\n where\n theta = norm r\n ct = cos theta\n st = sin theta\n r' = if theta == 0 then V3 1 0 0 else r / V3 theta theta theta\n sr = skew r'\n mrt = V1 r'\n mr = transpose mrt\n rrt = mr !*! mrt\n\ninvRodrigues :: (Floating f) => M33 f -> V3 f\ninvRodrigues m = V3 x' y' z' * V3 t t t\n where\n V3 x y z = invSkew (m - transpose m) / 2\n st = norm (V3 x y z)\n t = asin st\n V3 x' y' z' = V3 x y z / V3 t t t\n\nframe2xyzaxayaz :: (Floating f) => M44 f -> [f]\nframe2xyzaxayaz m = [x, y, z, ax, ay, az]\n where\n V3 ax ay az = invRodrigues $ m ^. _m33\n V3 x y z = m ^. translation\n\nclass Renderable b f | b -> f where\n renderFC :: Flavour -> Color -> b -> VisObject f\n render :: b -> VisObject f\n render = renderFC Wireframe blue\n\n-- M44 \u3092 render\ninstance (Floating f) => Renderable (M44 f) f where\n renderFC _ _ m = convfrm m $ axes (0.05, 10)\n where\n axes (size, aspectRatio) = VisObjects [ Arrow (size, aspectRatio) (V3 1 0 0) red\n , Arrow (size, aspectRatio) (V3 0 0 1) blue\n ]\n\nclass FrameConvertable b f | b -> f where\n convfrm :: M44 f -> b -> b\n\ninstance (Floating f) => FrameConvertable (VisObject f) f where\n convfrm m v = Trans t $ RotDcm rot v\n where\n rot = transpose $ m ^. _m33 -- NOTE: vis function use row vector??\n t = m ^. translation\n\n---- for rendering and collision detection\ndata LinkShape f = OBB (V3 f) (V3 f) (M33 f) -- center size/2 axis-vector\n deriving Show\n\ninstance (Floating f) => FrameConvertable (LinkShape f) f where\n convfrm m (OBB c a r) = OBB c' a r'\n where\n c' = (m !* point c) ^. _xyz\n r' = m^._m33 !*! r\n\ninstance (Floating f) => Renderable (LinkShape f) f where\n renderFC f color (OBB c b@(V3 bx by bz) m) = Trans c $ RotDcm rot $ Box (2*bx, 2*by, 2*bz) f color\n where\n rot = transpose $ m ^. _m33 -- NOTE: vis function use row vector??\n\nhasIntersection :: (Ord f, Floating f) => LinkShape f -> LinkShape f -> Bool\nhasIntersection (OBB c0 a@(V3 a0 a1 a2) m0) (OBB c1 b@(V3 b0 b1 b2) m1) = not $ easy || i0 || i1 || i2 || i3 || i4 || i5 || i6 || i7 || i8 || i9 || i10 || i11 || i12 || i13 || i14\n where\n\n -- not intersection test using bounding sphere\n easy = norm a + norm b < norm vD\n\n -- not intersection test\n i0 = a0 + (b0*c00' + b1*c01' + b2*c02') < abs sA0D\n i1 = a1 + (b0*c10' + b1*c11' + b2*c12') < abs sA1D\n i2 = a2 + (b0*c20' + b1*c21' + b2*c22') < abs sA2D\n\n i3 = (a0*c00' + a1*c10' + a2*c20') + b0 < abs (vB0 `dot` vD)\n i4 = (a0*c01' + a1*c11' + a2*c21') + b1 < abs (vB1 `dot` vD)\n i5 = (a0*c02' + a1*c12' + a2*c22') + b2 < abs (vB2 `dot` vD)\n\n i6 = (a1*c20' + a2*c10') + (b1*c02' + b2*c01') < abs (c10*sA2D - c20*sA1D)\n i7 = (a1*c21' + a2*c11') + (b0*c02' + b2*c00') < abs (c11*sA2D - c21*sA1D)\n i8 = (a1*c22' + a2*c12') + (b0*c01' + b1*c00') < abs (c12*sA2D - c22*sA1D)\n\n i9 = (a0*c20' + a2*c00') + (b1*c12' + b2*c11') < abs (c20*sA0D - c00*sA2D)\n i10 = (a0*c21' + a2*c01') + (b0*c12' + b2*c10') < abs (c21*sA0D - c01*sA2D)\n i11 = (a0*c22' + a2*c02') + (b0*c11' + b1*c10') < abs (c22*sA0D - c02*sA2D)\n\n i12 = (a0*c10' + a1*c00') + (b1*c22' + b2*c21') < abs (c00*sA1D - c10*sA0D)\n i13 = (a0*c11' + a1*c01') + (b0*c22' + b2*c20') < abs (c01*sA1D - c11*sA0D)\n i14 = (a0*c12' + a1*c02') + (b0*c21' + b1*c20') < abs (c02*sA1D - c12*sA0D)\n\n vD = c1 - c0\n V3 vA0 vA1 vA2 = transpose m0\n V3 vB0 vB1 vB2 = transpose m1\n V3 (V3 c00 c01 c02) (V3 c10 c11 c12) (V3 c20 c21 c22) = transpose m0 !*! m1\n\n ((c00', c01', c02'), (c10', c11', c12'), (c20', c21', c22')) = ((abs c00, abs c01, abs c02), (abs c10, abs c11, abs c12), (abs c20, abs c21, abs c22))\n\n sA0D = vA0 `dot` vD\n sA1D = vA1 `dot` vD\n sA2D = vA2 `dot` vD\n\n-- TODO\nhasCollisions :: (Ord f, Floating f) => [LinkShape f] -> [Bool]\nhasCollisions (x:xs) = any id (hasIntersection x <$> xs) : hasCollisions xs\nhasCollisions [] = []\n\naabb :: (Ord f, Floating f) => (f, f) -> (f, f) -> (f, f) -> LinkShape f\naabb (x0,x1) (y0,y1) (z0,z1) = OBB c b identity\n where\n c = V3 ((x1+x0)/2) ((y1+y0)/2) ((z1+z0)/2)\n b = V3 ((x1-x0)/2) ((y1-y0)/2) ((z1-z0)/2)\n\ntype FrameTrans f = f -> M44 f\n\ndata DH f = DH { __a :: f -- [m]\n , __d :: f -- [m]\n , __alpha :: f -- [rad]\n } deriving Show\n\nmakeLenses ''DH\n\nd1 :: (Floating f) => f\nd1 = 0.089159\n\na2 :: (Floating f) => f\na2 = 0.425\n\na3 :: (Floating f) => f\na3 = 0.39225\n\nd4 :: (Floating f) => f\nd4 = 0.10915\n\nd5 :: (Floating f) => f\nd5 = 0.09465\n\nd6 :: (Floating f) => f\nd6 = 0.0823\n\nur5dh :: (Floating f) => [DH f]\nur5dh =\n [ DH 0 d1 (pi/2) -- J1\n , DH (-a2) 0 0 -- J2\n , DH (-a3) 0 0 -- J3\n , DH 0 d4 (pi/2) -- J4\n , DH 0 d5 (-pi/2)-- J5\n , DH 0 d6 0 -- J6(flange)\n ]\n\ntcpOffsetZ :: (Floating f) => f\ntcpOffsetZ = 0.15\n\n-- how to draw link (from frame{i} to frame{i+1})\nur5link :: (Ord f, Floating f) => [LinkShape f]\nur5link =\n [ aabb (-r/2, r/2) (-d1, r/2) (-r/2, r/2) -- 1,2\n , aabb (-r/2, a2 + r/2) (-r/2, r/2) (delta+r/2, 3*r/2) -- 2,3\n , aabb (-r/2, a3 + r/2) (-r/2, r/2) (-r/2, r/2) -- 3,4\n , aabb (-r/2, r/2) (r/2 + delta-d4, r/2) (-r/2, r/2) -- 4,5\n , aabb (-r/2, r/2) (-r/2, d5 - r/2 - delta) (-r/2, r/2) -- 5,6\n , aabb (-r/2, r/2) (-r/2, r/2) (delta-d6+r, 0) -- 6,frange\n , aabb (-r/2, r/2) (-r/2, r/2) (delta, tcpOffsetZ) -- tool\n ]\n where\n r = 0.05\n delta = 0.01\n\n-- https://en.wikipedia.org/wiki/Denavit%E2%80%93Hartenberg_parameters\ndr2ft :: (Floating f) => DH f -> FrameTrans f\ndr2ft dh theta = twistZ (dh ^. _d) theta !*! twistX (dh^. _a) (dh^. _alpha)\n\nur5fts :: (Floating f) => [FrameTrans f]\nur5fts = dr2ft <$> ur5dh\n\n-- calc each frame in base-coordinate for each joint-angle\nkinematics :: (Floating f) => [FrameTrans f] -> [f] -> [M44 f]\nkinematics (e:es) (a:as) = t : ((t !*! ) <$> kinematics es as)\n where\n t = e a\nkinematics [] [] = []\nkinematics _ _ = error \"invalid args\"\n\njoint2tcp :: (Floating f) => [FrameTrans f] -> [f] -> [f]\njoint2tcp es js = frame2xyzaxayaz $ last ( kinematics es js) !*! transM44Z tcpOffsetZ\n\nposlabel = [\"x\", \"y\", \"z\", \"ax\", \"ay\", \"az\"]\n\n\ndata World = World { _jPos :: [Double]\n , _tcpVel :: [Double]\n , _trajct :: [V3 Double]\n , _camera :: Camera\n }\n\nmakeLenses ''World\n\nworld0 = World [0.1, 0.4, 0.4, 0.1, 0.1, 0.1] [0, 0, 0, 0, 0, 0] [] cameraState0\n where\n defaultCamera = Camera0 { phi0 = 60 , theta0 = 20 , rho0 = 7 }\n cameraState0 = makeCamera $ fromMaybe defaultCamera (optInitialCamera defaultOpts)\n\n\n\nmotionPolicy :: [Double] -> [Double] -> [Double] -> [Double]\nmotionPolicy goal pos vel = toList acc\n where\n alpha = 0.001\n c = 0.01\n beta = 0.5\n acc :: Vector Double\n acc = alpha * s (vector goal - vector pos) - beta * vector vel\n s :: Vector Double -> Vector Double\n s v = scale (1 / h (norm_2 v)) v\n h :: Double -> Double\n h z = z + c * log (1 + exp (-2) * c * z)\n\nmySimulateIO :: IO ()\nmySimulateIO = vis defaultOpts 0.016 world0 simFun drawFun setCameraFun (Just kmCallback) (Just motionCallback) Nothing\n where\n delta = 0.001\n\n simFun (w,t) = return $ w &~ do\n let tcpp = joint2tcp ur5fts $ w ^. jPos\n let tcpv = w ^. tcpVel\n let goal = [0.192428507378705,-0.39791168805212945,-0.43347675593345414,0.7684417340393249,-0.40013839074582813,0.3969016751654795]\n let tcpa = motionPolicy goal tcpp tcpv\n let tcpv' = zipWith (+) tcpv tcpa\n let j = fromLists (jacobian (joint2tcp $ ur5fts) (w ^. jPos) :: [[Double]])\n let jvel = if det j > 0.0001 then toList $ pinv j #> fromList tcpv else [0, 0, 0, 0, 0, 0]\n let jpos' = zipWith (+) (w ^. jPos) jvel\n let pos = joint2tcp ur5fts jpos'\n jPos .= jpos'\n tcpVel .= tcpv'\n trajct %= (:) (V3 (pos !! 0) (pos !! 1) (pos !! 2))\n\n drawFun (w, t) = do\n let jpos = w ^. jPos\n let frames = identity : kinematics ur5fts jpos\n let vframes = render <$> frames\n let ts = tail frames ++ [last frames]\n let links = zipWith convfrm ts ur5link\n let colors = (\\b -> if b then red else blue) <$> hasCollisions links\n let vlinks = zipWith (renderFC Wireframe) colors links\n let pos = joint2tcp ur5fts jpos\n let info = [Text2d (show (l, j)) (0, 110 - i * 20) Fixed8By13 red | (l, i,j) <- zip3 poslabel [0..] pos]\n let infoj = [Text2d (show (\"J\", i, j)) (300, 110 - i * 20) Fixed8By13 red | (i,j) <- zip [0..] jpos]\n let points = Points (w ^. trajct) (Just 1.0) yellow\n print pos\n return (VisObjects $ vlinks ++ vframes ++ info ++ infoj ++ [points], Nothing)\n\n setCameraFun w = setCamera $ w ^. camera\n\n kmCallback w k0 k1 _ _ = case (k0, k1) of \n (Char 'h', Down) -> w & tcpVel .~ [ delta, 0, 0, 0, 0, 0]\n (Char 'l', Down) -> w & tcpVel .~ [-delta, 0, 0, 0, 0, 0]\n (Char 'j', Down) -> w & tcpVel .~ [0, delta, 0, 0, 0, 0]\n (Char 'k', Down) -> w & tcpVel .~ [0, -delta, 0, 0, 0, 0]\n (Char 'n', Down) -> w & tcpVel .~ [0, 0, delta, 0, 0, 0]\n (Char 'p', Down) -> w & tcpVel .~ [0, 0, -delta, 0, 0, 0]\n (SpecialKey KeyLeft, Down) -> w & tcpVel .~ [0, 0, 0, delta, 0, 0]\n (SpecialKey KeyRight, Down) -> w & tcpVel .~ [0, 0, 0, -delta, 0, 0]\n (SpecialKey KeyDown, Down) -> w & tcpVel .~ [0, 0, 0, 0, delta, 0]\n (SpecialKey KeyUp, Down) -> w & tcpVel .~ [0, 0, 0, 0, -delta, 0]\n (Char ',', Down) -> w & tcpVel .~ [0, 0, 0, 0, 0, delta]\n (Char '.', Down) -> w & tcpVel .~ [0, 0, 0, 0, 0, -delta]\n (Char 'a', Down) -> world0 & camera .~ (w ^. camera)\n (Char 's', Down) -> w & tcpVel .~ [0, 0, 0, 0, 0, 0]\n (_, _) -> w & camera %~ (\\x -> cameraKeyboardMouse x k0 k1)\n\n\n motionCallback w pos = w & camera %~ (`cameraMotion` pos)\n\nsomeFunc :: IO ()\nsomeFunc = mySimulateIO\n\nmain = mySimulateIO\n\n", "meta": {"hexsha": "e50c6e31777bd5cf2abf83c933de91c6f0abb829", "size": 13487, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "SuperLazyK/navigation", "max_stars_repo_head_hexsha": "34cddd22e3ffb0e9a77008db9741bb052ca8a1c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "SuperLazyK/navigation", "max_issues_repo_head_hexsha": "34cddd22e3ffb0e9a77008db9741bb052ca8a1c9", "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": "SuperLazyK/navigation", "max_forks_repo_head_hexsha": "34cddd22e3ffb0e9a77008db9741bb052ca8a1c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1581769437, "max_line_length": 180, "alphanum_fraction": 0.5155334767, "num_tokens": 5239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5743804375322799}} {"text": "module Math.IRT.MLE.Truncated\n ( DF (..)\n , MLEResult (..)\n , mleEst\n ) where\n\nimport Data.Default.Class\n\nimport Statistics.Distribution\n\nimport Math.IRT.Internal.Distribution\nimport Math.IRT.Internal.LogLikelihood\nimport Math.IRT.MLE.Internal.Generic\n\n\ndata DF = DF { steps :: !Int\n , thetaEstimate :: !Double\n , lower_bound :: !Double\n , upper_bound :: !Double }\n\ninstance Default DF where\n def = DF 10 0.0 (-3.5) 3.5\n\n\nmleEst :: (Distribution d, ContDistr d, DensityDeriv d, LogLikelihood d) => DF -> [Bool] -> [d] -> MLEResult\nmleEst (DF n th lb ub) rs params =\n let res = generic_mleEst rs params n th\n in res { theta = min ub $ max lb $ theta res }\n", "meta": {"hexsha": "e7606648e226ca328a6b558d8aff2e5266ab33fe", "size": 714, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/IRT/MLE/Truncated.hs", "max_stars_repo_name": "argiopetech/irt", "max_stars_repo_head_hexsha": "ee136da44235bf7ecde4d516adfa8b22899ca0b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-06T08:31:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T08:31:33.000Z", "max_issues_repo_path": "Math/IRT/MLE/Truncated.hs", "max_issues_repo_name": "argiopetech/irt", "max_issues_repo_head_hexsha": "ee136da44235bf7ecde4d516adfa8b22899ca0b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/IRT/MLE/Truncated.hs", "max_forks_repo_name": "argiopetech/irt", "max_forks_repo_head_hexsha": "ee136da44235bf7ecde4d516adfa8b22899ca0b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6206896552, "max_line_length": 108, "alphanum_fraction": 0.6344537815, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5743804268457122}} {"text": "{-# LANGUAGE TypeApplications #-}\nmodule ArrayFire.BLASSpec where\n\nimport ArrayFire hiding (not)\n\nimport Data.Complex\nimport Test.Hspec\n\nspec :: Spec\nspec =\n describe \"BLAS spec\" $ do\n it \"Should matmul two matrices\" $ do\n (matrix @Double (2,2) [[2,2],[2,2]] `matmul` matrix @Double (2,2) [[2,2],[2,2]]) None None\n `shouldBe` matrix @Double (2,2) [[8,8],[8,8]]\n it \"Should dot product two vectors\" $ do\n dot (vector @Double 2 (repeat 2)) (vector @Double 2 (repeat 2)) None None\n `shouldBe`\n scalar @Double 8\n it \"Should produce scalar dot product between two vectors as a Complex number\" $ do\n dotAll (vector @Double 2 (repeat 2)) (vector @Double 2 (repeat 2)) None None\n `shouldBe`\n 8.0 :+ 0.0\n it \"Should take the transpose of a matrix\" $ do\n transpose (matrix @Double (2,2) [[1,1],[2,2]]) False\n `shouldBe`\n matrix @Double (2,2) [[1,2],[1,2]]\n it \"Should take the transpose of a matrix in place\" $ do\n let m = matrix @Double (2,2) [[1,1],[2,2]]\n transposeInPlace m False\n m `shouldBe` matrix @Double (2,2) [[1,2],[1,2]]\n\n\n\n\n\n", "meta": {"hexsha": "40cbbec4615199e2f0c796a5873f11953962760f", "size": 1140, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/ArrayFire/BLASSpec.hs", "max_stars_repo_name": "danielkroeni/arrayfire-haskell", "max_stars_repo_head_hexsha": "510b96cd4121272bdc39ba48aaf9e7e4db297a60", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:54:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:59:15.000Z", "max_issues_repo_path": "test/ArrayFire/BLASSpec.hs", "max_issues_repo_name": "danielkroeni/arrayfire-haskell", "max_issues_repo_head_hexsha": "510b96cd4121272bdc39ba48aaf9e7e4db297a60", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2019-11-04T03:45:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T00:49:36.000Z", "max_forks_repo_path": "test/ArrayFire/BLASSpec.hs", "max_forks_repo_name": "danielkroeni/arrayfire-haskell", "max_forks_repo_head_hexsha": "510b96cd4121272bdc39ba48aaf9e7e4db297a60", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-11-04T03:45:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-17T01:02:23.000Z", "avg_line_length": 31.6666666667, "max_line_length": 96, "alphanum_fraction": 0.5973684211, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5743706374398085}} {"text": "{-# LANGUAGE FlexibleContexts,FlexibleInstances,IncoherentInstances #-}\n{- Assignment 1 Extra Credit\n - Name: TODO add full name\n - Date: TODO add of completion\n -}\nmodule Assign_2_ExtraCredit where\n\nimport Data.Complex\n\nmacid = \"TODO: put your mac id here\"\n\n\ndata GaussianInt a = a :@ a\n deriving Show\n\nclass GaussianIntegral g where\n gaussZero :: Integral a => g a\n gaussReal :: Integral a => g a -> a\n gaussImag :: Integral a => g a -> a\n gaussConj :: Integral a => g a -> g a\n gaussAdd :: Integral a => g a -> g a -> g a\n gaussMult :: Integral a => g a -> g a -> g a\n\n{- TODO\n - implement instances of GaussianIntegral\n - implmenet instances of Eq, Ord\n -}\n\ngaussNorm :: (Integral a, GaussianIntegral g) => g a -> a\ngaussNorm g = error \"TODO: implement gaussNorm\"\n\nmaxGaussNorm :: (Integral a, GaussianIntegral g) => [g a] -> g a\nmaxGaussNorm gs = error \"TODO: implement maxGaussNorm\"\n", "meta": {"hexsha": "98df3582729a5e1001816ef8e4b88544a9dee19f", "size": 900, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Assign_2_ExtraCredit.hs", "max_stars_repo_name": "SaribK/Gaussian-Integers", "max_stars_repo_head_hexsha": "fad3e61f44d2ba02978876a18e54177fcb6d21bf", "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/Assign_2_ExtraCredit.hs", "max_issues_repo_name": "SaribK/Gaussian-Integers", "max_issues_repo_head_hexsha": "fad3e61f44d2ba02978876a18e54177fcb6d21bf", "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/Assign_2_ExtraCredit.hs", "max_forks_repo_name": "SaribK/Gaussian-Integers", "max_forks_repo_head_hexsha": "fad3e61f44d2ba02978876a18e54177fcb6d21bf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4705882353, "max_line_length": 71, "alphanum_fraction": 0.6788888889, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5742608400127476}} {"text": "module D03\n ( Claim (..), mkClaims, claimsIntersectionSize, isolatedClaim\n ) where\n\nimport Data.List\nimport qualified Data.HashMap.Strict as HM\nimport Data.Complex\nimport Text.Regex\n\ndata Claim = Claim { identifier :: Int,\n topLeft :: Complex Int,\n bottomRight :: Complex Int }\n deriving (Show, Eq)\n\ntype World = HM.HashMap (Complex Int) [Claim]\n\nisolatedClaim :: String -> Int\nisolatedClaim input = identifier $ head $ claims \\\\ badClaims\n where\n badClaims = concat $ HM.elems $ HM.filter (\\cs -> (length cs) > 1) $ buildWorld claims\n claims = mkClaims input\n\nclaimsIntersectionSize :: String -> Int\nclaimsIntersectionSize = length . filter (> 1) . map length . HM.elems . buildWorld . mkClaims\n\nbuildWorld :: [Claim] -> World\nbuildWorld = foldl addClaimToWorld HM.empty\n\naddClaimToWorld :: World -> Claim -> World\naddClaimToWorld world claim = foldl addPoint world [x:+y | x<-[(realPart p1)..(realPart p2)], y<-[(imagPart p1)..(imagPart p2)]]\n where\n p1 = topLeft claim\n p2 = bottomRight claim\n addPoint w p = HM.insertWith (++) p [claim] w\n\nmkClaims :: String -> [Claim]\nmkClaims = map mkClaim . lines\n\nmkClaim :: String -> Claim\nmkClaim def = Claim (params !! 0) (left :+ top) ((left+width-1) :+ (top+height-1))\n where\n top = params !! 2\n left = params !! 1\n width = params !! 3\n height = params !! 4\n params = extract $ matchRegexAll (mkRegex \"#([0-9]+) @ ([0-9]+),([0-9]+): ([0-9]+)x([0-9]+)\") def\n extract (Just (_,_,_,subs)) = map read subs\n\n\n", "meta": {"hexsha": "98738295356edbe6e6bf89105ab212a897058764", "size": 1534, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/D03.hs", "max_stars_repo_name": "Oaz/aoc2018", "max_stars_repo_head_hexsha": "7a3dc0a62581aad0bae8d69da80d87fe40592cc7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/D03.hs", "max_issues_repo_name": "Oaz/aoc2018", "max_issues_repo_head_hexsha": "7a3dc0a62581aad0bae8d69da80d87fe40592cc7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/D03.hs", "max_forks_repo_name": "Oaz/aoc2018", "max_forks_repo_head_hexsha": "7a3dc0a62581aad0bae8d69da80d87fe40592cc7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.68, "max_line_length": 128, "alphanum_fraction": 0.6401564537, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5741126121428812}} {"text": "{-# LANGUAGE RankNTypes, BangPatterns, ScopedTypeVariables, FlexibleInstances #-}\n\nmodule Math.Probably.HamMC where\n\nimport Math.Probably.MCMC\nimport qualified Math.Probably.PDF as PDF\nimport Math.Probably.RandIO\nimport Math.Probably.FoldingStats\nimport Math.Probably.Sampler\nimport Control.Applicative\n\nimport Numeric.LinearAlgebra\nimport Numeric.AD\nimport Text.Printf\nimport System.IO\nimport Data.Maybe\n\nimport Statistics.Test.KolmogorovSmirnov\nimport Statistics.Test.MannWhitneyU\nimport qualified Data.Vector.Unboxed as U\nimport qualified Control.Monad.State.Strict as S\n\nimport Debug.Trace\nimport Data.IORef\nimport Control.Spoon\n\n\ndata HMCPar = HMCPar { hpXi :: !(Vector Double),\n hpL :: !Int,\n hpPi :: !Double,\n hpEpsilon :: !Double,\n hpCount :: !Int,\n hpAccept :: !Int,\n hpFreezeEps :: Bool }\n deriving Show\n\nhmc1 :: (Vector Double -> (Double,Vector Double)) \n -> HMCPar\n -> Sampler HMCPar\nhmc1 postGrad (HMCPar current_q l _ epsMean count accept freeze) = do\n let dims = dim current_q\n grad_u = negate . snd . postGrad\n u = negate . fst . postGrad\n current_p <- fmap fromList $ gaussManyUnitD dims\n eps <- uniform (epsMean*0.8) (epsMean*1.2)\n --the initial half momentum step \n\n let p_half_step = current_p - scale (eps/2) (grad_u current_q)\n\n let step :: Int -> Vector Double -> Vector Double -> (Vector Double, Vector Double)\n step n p q -- note that my l is Radford Neal's L+1\n | n == 0 = let qfinal = q + scale eps p -- only q not p update in last loop\n pfinal = p - scale (eps/2) (grad_u qfinal) -- half momentum step at end\n in (negate pfinal, -- negate momentum for symmetric proposal\n qfinal)\n | otherwise =\n let q1 = q + scale eps p\n p1 = p - scale eps (grad_u q1)\n in step (n-1) p1 q1\n\n let (propose_p, propose_q) = step l p_half_step current_q\n current_U = u current_q\n current_K = (current_p `dot` current_p) / 2\n propose_U = u propose_q\n propose_K = (propose_p `dot` propose_p) / 2\n ratio = exp $ current_U - propose_U + current_K - propose_K\n tr = max 1.0 $ realToFrac count\n\n u <- unitSample -- 0 to 1\n return $ if u < ratio\n then HMCPar propose_q l propose_U (if freeze then epsMean else (min 2 $ 1+k_hmc/tr)*epsMean) (count+1) (accept+1) freeze\n else HMCPar current_q l current_U (if freeze then epsMean else (max 0.5 $ 1-k_hmc/tr)**1.8*epsMean) (count+1) (accept) freeze\n\n\ntraceAs s x = trace (s++\" = \"++show x) x\n\n\nrunHMC postgrad nsam hmc0 = go nsam hmc0 [] where\n go 0 hmcp xs = do io $ putStrLn $ \"done with \"++show hmcp\n return (hmcp, xs)\n go n hmcp xs = do hmcnext <- sample $ hmc1 postgrad hmcp\n if isNaN $ hpPi hmcnext\n then return (hmcnext, [])\n else do io $ do putStrLn $ show $ (hpCount hmcnext, \n hpPi hmcnext, \n hpEpsilon hmcnext)\n hFlush stdout\n go (n-1) hmcnext $ hpXi hmcnext : xs\n\n\nk_hmc = 2", "meta": {"hexsha": "1ba1a6a161130ecb5f1ecefc983e1b7146960b17", "size": 3368, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/Probably/HamMC.hs", "max_stars_repo_name": "glutamate/probably", "max_stars_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-28T03:19:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:44.000Z", "max_issues_repo_path": "Math/Probably/HamMC.hs", "max_issues_repo_name": "glutamate/probably", "max_issues_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/Probably/HamMC.hs", "max_forks_repo_name": "glutamate/probably", "max_forks_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.010989011, "max_line_length": 140, "alphanum_fraction": 0.5816508314, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5739108242547099}} {"text": "module MachineLearning.MultiSvmClassifierTest\n(\n tests\n)\n\nwhere\n\nimport Test.Framework (testGroup)\nimport Test.Framework.Providers.HUnit\nimport Test.HUnit\nimport Test.HUnit.Approx\nimport Test.HUnit.Plus\n\nimport MachineLearning.DataSets (dataset2)\n\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified MachineLearning as ML\nimport MachineLearning.Optimization\nimport MachineLearning.Model\nimport MachineLearning.MultiSvmClassifier\n\n(x, y) = ML.splitToXY dataset2\n\nmodel = MultiClass (MultiSvm 1 2)\n\nx1 = ML.addBiasDimension x\nonesTheta :: LA.Vector LA.R\nonesTheta = LA.konst 1 (2 * LA.cols x1)\nzeroTheta :: LA.Vector LA.R\nzeroTheta = LA.konst 0 (2 * LA.cols x1)\n\nprocessX muSigma x = ML.addBiasDimension $ ML.featureNormalization muSigma $ ML.mapFeatures 6 x\n\nmuSigma = ML.meanStddev (ML.mapFeatures 6 x)\nx2 = processX muSigma x\n\n\nxPredict = LA.matrix 2 [ -0.5, 0.5\n , 0.2, -0.2\n , 1, 1\n , 1, 0\n , 0, 0\n , 0, 1]\nxPredict2 = processX muSigma xPredict\nyExpected = LA.vector [1, 1, 0, 0, 1, 0]\n\n\ngradientCheckingEps :: Double\ngradientCheckingEps = 1e-3\n\neps = 0.0001\n\nzeroTheta2 = LA.konst 0 (2 * LA.cols x2)\n(thetaGD, _) = minimize (GradientDescent 0.001) model eps 150 (L2 1) x2 y zeroTheta2\n(thetaCGFR, _) = minimize (ConjugateGradientFR 0.1 0.1) model eps 30 (L2 0.5) x2 y zeroTheta2\n(thetaCGPR, _) = minimize (ConjugateGradientPR 0.1 0.1) model eps 30 (L2 0.5) x2 y zeroTheta2\n(thetaBFGS, _) = minimize (BFGS2 0.1 0.1) model eps 30 (L2 0.5) x2 y zeroTheta2\n\n\ncheckGradientTest lambda theta eps = do\n let diffs = take 5 $ map (\\e -> checkGradient model lambda x1 y theta e) [1e-3, 1.1e-3 ..]\n diff = minimum diffs\n assertApproxEqual \"\" eps 0 diff\n\n\ntests = [ testGroup \"gradient checking\" [\n testCase \"non-zero theta, non-zero lambda\" $ checkGradientTest (L2 2) onesTheta 3e-2\n , testCase \"zero theta, non-zero lambda\" $ checkGradientTest (L2 2) zeroTheta gradientCheckingEps\n , testCase \"non-zero theta, zero lambda\" $ checkGradientTest (L2 0) onesTheta gradientCheckingEps\n , testCase \"zero theta, zero lambda\" $ checkGradientTest (L2 0) zeroTheta gradientCheckingEps\n , testCase \"non-zero theta, no reg\" $ checkGradientTest RegNone onesTheta gradientCheckingEps\n , testCase \"zero theta, no reg\" $ checkGradientTest RegNone zeroTheta gradientCheckingEps\n ]\n , testGroup \"learn\" [\n testCase \"Gradient Descent\" $ assertVector \"\" 0.01 yExpected (hypothesis model xPredict2 thetaGD)\n , testCase \"Conjugate Gradient FR\" $ assertVector \"\" 0.01 yExpected (hypothesis model xPredict2 thetaCGFR)\n , testCase \"Conjugate Gradient PR\" $ assertVector \"\" 0.01 yExpected (hypothesis model xPredict2 thetaCGPR)\n , testCase \"BFGS\" $ assertVector \"\" 0.01 yExpected (hypothesis model xPredict2 thetaBFGS)\n ]\n ]\n\n", "meta": {"hexsha": "f68e380ceb4e10e0d783af275cf90fd0c6324563", "size": 2981, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/MachineLearning/MultiSvmClassifierTest.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "test/MachineLearning/MultiSvmClassifierTest.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "test/MachineLearning/MultiSvmClassifierTest.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 36.3536585366, "max_line_length": 118, "alphanum_fraction": 0.6793022476, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5737441534037272}} {"text": "{-|\nModule : ODMatrix.ElementaryDecomposition\nDescription : This module is responsible for the representation of Elementary operations and the process of elementary decomposition of the path between Origin-Destination matrices.\n\n-}\nmodule ODMatrix.ElementaryDecomposition (\n ElementaryMatrix(..)\n , getChildren\n , applyElementary\n , applyPath\n , applicables\n , elementaryValue\n , opposite\n , isNullElementary\n , ODM\n , Bounds\n ) where\n\n import Numeric.LinearAlgebra\n --import Data.Tree (Tree(..), unfoldTree)\n \n import ODMatrix (ODM)\n\n\n data ElementaryMatrix = \n NullElementary Int |\n Elementary Int (Int, Int) (Int, Int)\n deriving (Show)\n\n -- | Size of the elementary matrix\n emSize :: ElementaryMatrix -> Int\n emSize (NullElementary s) = s\n emSize (Elementary s _ _) = s\n\n\n -- | Bounds of the capacity of the unit (Lower bound, Upper bound).\n type Bounds = (Double, Double) \n\n \n -- Size, visited, s\n type ES = (ElementaryMatrix, ODM)\n\n\n applyElementaries :: ODM -> [ElementaryMatrix] -> [ODM]\n applyElementaries s es = map (applyElementary s) es\n \n\n -- | Apply a elementary operation to the given ODM.\n applyElementary :: ODM -> ElementaryMatrix -> ODM\n applyElementary a e = a + (toMatrix e)\n\n -- | Apply a sequence of elementary operations to the given ODM.\n applyPath :: ODM -> [ElementaryMatrix] -> ODM\n applyPath = foldl applyElementary\n\n\n -- | Given S, such that A + S = B, this function computes the first elementary permutation matrix E such that S' + E = S.\n getChildren :: ODM -- ^ Full path permutation matrix\n -> [ElementaryMatrix] -- ^ All possible elementary matrices\n getChildren odm = es ++ map opposite es\n where al = toAssocList odm\n s = rows odm\n es = [ Elementary s (r1,c1) (r2,c2) | \n ((r1,c1),_) <- al, \n ((r2,c2),_) <- al, \n r1 > r2, c1 < c2 ]\n\n\n opposite :: ElementaryMatrix -> ElementaryMatrix\n opposite (Elementary s (r1,c1) (r2,c2)) = Elementary s (r2,c1) (r1,c2)\n opposite (NullElementary s) = NullElementary s\n\n\n -- getChildren s = foldl (\\acc p -> acc ++ opposites s p pivots) [] pivots\n -- where -- Filtra solo los potenciales pivotes a los que puede agregarse o quitarse un pasajero.\n -- pivots = [ p | p@((i,j),x) <- toAssocList s, i <= j, x /= 0] \n \n\n -- reciprocals :: Pivot -> [Pivot] -> [Pivot]\n -- reciprocals ((i,j),x) pivots = \n -- [ p | p@((h,k),y) <- pivots, h < i, j < k, x/y > 0]\n\n\n -- opposites :: ODM -> Pivot -> [Pivot] -> [ElementaryMatrix]\n -- opposites s p@(i,j) pivots =\n -- [ Elementary (rows s) (i,j) (h,k)\n -- | ((h,k),_) <- reciprocals p pivots, \n -- atIndex s (h,j) / x < 0, -- Opposite signs\n -- atIndex s (i,k) / x < 0 ] \n\n\n\n -- | Filter the elementary matrices that cannot be applied to the odm\n applicables :: Bounds -- ^ Bounds of the values of the target\n -> ODM -- ^ Target Origin-Destination Matrix\n -> [ElementaryMatrix] -- ^ List of potential elementary operations\n -> [ElementaryMatrix] -- ^ List of applicable elementary operations\n applicables b s = filter (applicable b s)\n\n -- | Indicates if an elementary operation is applicable for a given origin destination matrix with the given bounds.\n applicable :: Bounds -- ^ Bounds of the values of the target\n -> ODM -- ^ Target Origin-Destination Matrix\n -> ElementaryMatrix -- ^ Elementary operation to apply\n -> Bool \n applicable _ _ (NullElementary _) = True\n applicable (mn,mx) s (Elementary _ (i,j) (h,k)) = \n p (i,k) > mn && p (h,k) < mx &&\n p (i,j) < mx && p (h,j) > mn\n where p = atIndex s\n\n\n\n -- | Compute the value of a elementary matrix in base of a distance functions between cells.\n elementaryValue :: (Int -> Int -> Double) -- ^ Measure function\n -> ElementaryMatrix -- ^ E \n -> Double -- ^ Value of E\n elementaryValue _ (NullElementary _) = 0\n elementaryValue m (Elementary _ (r1,_ ) (r2,_)) = s * 2 * m r1 r2\n where s = fromIntegral . signum $ (r1 - r2)\n\n\n\n\n \n -- * Convertions\n\n -- | Transform the internal representation of a Elementary Matrix in a Matrix Double\n toMatrix :: ElementaryMatrix -> ODM\n toMatrix (NullElementary n) = assoc (n,n) 0 []\n toMatrix (Elementary n idx1@(r1,c1) idx2@(r2,c2)) = \n assoc (n,n) 0 [(idx1,1), (idx2,1), ((r1,c2),-1), ((r2,c1),-1)]\n \n\n -- | Transform a matrix to an assoc list.\n -- Recovers only the valid, different to 0, elements of the ODM.\n toAssocList :: ODM -> [((Int, Int), Double)]\n toAssocList s = [ c | c@((i,j),v) <- zip idxs elems, i <= j, v /= 0]\n where n = rows s\n idxs = [ (i,j) | i <- [0..(n-1)], j <- [0..(n-1)] ]\n elems = toList . flatten $ s\n\n\n -- | Return True if the elementary matrix is a null elementary matrix.\n isNullElementary :: ElementaryMatrix -> Bool\n isNullElementary (NullElementary s) = True\n isNullElementary _ = False", "meta": {"hexsha": "fb5b3f1b9fd2f3d6d4d32cb25070b2d9ec4414b1", "size": 5117, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ODMatrix/ElementaryDecomposition.hs", "max_stars_repo_name": "renecura/odmatrix", "max_stars_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "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/ODMatrix/ElementaryDecomposition.hs", "max_issues_repo_name": "renecura/odmatrix", "max_issues_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "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/ODMatrix/ElementaryDecomposition.hs", "max_forks_repo_name": "renecura/odmatrix", "max_forks_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "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.0479452055, "max_line_length": 181, "alphanum_fraction": 0.5995700606, "num_tokens": 1461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.573314057381994}} {"text": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main\n ( main\n ) where\n\n\n-------------------------------------------------------------------------------\nimport Data.Foldable as FT\nimport Data.Ratio\nimport Data.Sequence as Seq\nimport Test.Tasty\nimport Test.Tasty.HUnit\nimport Test.Tasty.QuickCheck\n-------------------------------------------------------------------------------\nimport Statistics.RollingAverage\n-------------------------------------------------------------------------------\n\n\nmain :: IO ()\nmain = defaultMain tests\n\n\ntests :: TestTree\ntests = testGroup \"rolling-average\"\n [\n testProperty \"window size of 0 always produces 0\" $ \\(samples :: [Int]) ->\n ravg (avgList 0 samples) === (0.0 :: Double)\n , testProperty \"never grows samples larger than the limit\" $ \\(Positive lim) (samples :: [Int]) ->\n Seq.length (ravgSamples (avgList lim samples)) <= lim\n , testCase \"can calculate rolling average as a Ratio\" $ do\n ravg (avgList 3 ([0, 1, 2, 3, 4, 5] :: [Int])) @?= (((3 + 4 + 5) % 3) :: Rational)\n ]\n\n\n-------------------------------------------------------------------------------\navgList :: Num a => Int -> [a] -> RollingAvg a\navgList lim samples = FT.foldl' ravgAdd (mkRavg lim) samples\n", "meta": {"hexsha": "5c48a09474878ff7e4385ce642f461b994e85e3b", "size": 1321, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Main.hs", "max_stars_repo_name": "Soostone/rolling-average", "max_stars_repo_head_hexsha": "939dfdfde84c4cdb4e292458ade43be80240ec18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-07T00:56:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-07T00:56:32.000Z", "max_issues_repo_path": "test/Main.hs", "max_issues_repo_name": "Soostone/rolling-average", "max_issues_repo_head_hexsha": "939dfdfde84c4cdb4e292458ade43be80240ec18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Main.hs", "max_forks_repo_name": "Soostone/rolling-average", "max_forks_repo_head_hexsha": "939dfdfde84c4cdb4e292458ade43be80240ec18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7631578947, "max_line_length": 100, "alphanum_fraction": 0.4526873581, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5729929253807551}} {"text": "-- Modulo destinado a todas as funcoes relativas ao treino da Rede.\n\nmodule Training \n(train) where\n\nimport Execution\nimport InputOutput\nimport Types\nimport Data.List.Split\nimport System.Random\nimport System.Random.Shuffle\nimport Numeric.LinearAlgebra.HMatrix\nimport Numeric.LinearAlgebra.Data\n\ntype Image = [Double]\ntype Sample = (Int, Image)\n\n-- Funcao de treino que executa uma\n-- dada quantidade de epocas de treino\ntrain :: Int -> IO String\ntrain epochAmount = do \n trainingSet <- getTraining\n testSet <- getTest\n network <- readIn\n manageTrainingEpoch epochAmount trainingSet testSet network\n\n-- \nmanageTrainingEpoch :: Int -> [Sample] -> [Sample] -> Data -> IO String\nmanageTrainingEpoch 0 _ _ _ = return \"\"\nmanageTrainingEpoch epochAmount trainingSet testSet network = do\n newNetwork <- trainingEpoch trainingSet network\n let \n correctCnt = testEpoch testSet newNetwork\n totalAmount = length testSet\n do return $ printEpoch epochAmount correctCnt totalAmount\n writeIn newNetwork\n manageTrainingEpoch (epochAmount - 1) trainingSet testSet newNetwork\n\ntrainingEpoch :: [Sample] -> Data -> IO Data\ntrainingEpoch trainingSet network = do\n standardGenerator <- getStdGen\n let trainingSize = length trainingSet\n shuffledTrainingSet = shuffle' trainingSet trainingSize standardGenerator\n minibatchAmount = 20 -- adequar quantidade\n minibatchSize = trainingSize `div` 20 -- adequar quantidade\n minibatches = chunksOf minibatchSize shuffledTrainingSet\n newNetwork = manageMinibatch minibatchAmount 0 network minibatches\n return newNetwork\n\nmanageMinibatch :: Int -> Int -> Data -> [[Sample]] -> Data\nmanageMinibatch amount counter network minibatches = if amount /= (counter + 1) \n then \n let changes = minibatchEvaluation (minibatches !! counter) amount network\n in plus (plus network changes) (manageMinibatch amount (counter + 1) network minibatches)\n else\n generateBasedOf network \n\nminibatchEvaluation :: [Sample] -> Int -> Data -> Data\nminibatchEvaluation minibatch amount network = let sumedDesiredChanges = manageSample minibatch amount network\n averageDesiredChanges = divide sumedDesiredChanges (fromIntegral amount)\n in averageDesiredChanges\n\nmanageSample :: [Sample] -> Int -> Data -> Data\nmanageSample minibatch counter networkModel = if counter > 0\n then\n let representedInt = fst $ minibatch !! counter\n image = snd $ minibatch !! counter\n network = feedforward image networkModel\n expectedOutput = buildExpectedOutput representedInt\n desiredChanges = backpropagation network image expectedOutput\n sumChanges = generateBasedOf networkModel\n in plus (plus sumChanges desiredChanges) (manageSample minibatch counter networkModel)\n else\n generateBasedOf networkModel\n\nbuildExpectedOutput :: Int -> [Double]\nbuildExpectedOutput representedValue = let indexes = [0.0 .. 9.0]\n in [if x == (fromIntegral representedValue) then x else 0.0 | x <- indexes]\n\n-- Recebe as informacoes da rede neural, o resultado \n-- esperado e retorna um Data com as modificacoes necessarias\n-- na rede\n-- N = network, E = expected list, I = image values\nbackpropagation :: Data -> Image -> [Double] -> Data\nbackpropagation n i e\n | isEmpty n = error \"Backpropagation error: Data is empty\"\n | length e /= 10 = error \"Backpropagation error: expectedOutput list is invalid\"\n | otherwise = let outputError = computeOutputError (aOutput n) (fromList e) (zetaOutput n)\n hiddenError = computeHiddenError (wOutput n) outputError (zetaHidden n)\n outputDesiredChanges = computeOutputDesiredChanges outputError (aHidden n)\n hiddenDesiredChanges = computeHiddenDesiredChanges hiddenError i\n wH = fst hiddenDesiredChanges\n bH = snd hiddenDesiredChanges\n wO = fst outputDesiredChanges\n bO = snd outputDesiredChanges\n newNetwork = (Data wH bH (aHidden n) (zetaHidden n) wO bO (aOutput n) (zetaOutput n)) \n in newNetwork\n\n-- Gera o vetor de erro da camada output, recebe\n-- as ativacoes do output atual, as ativacoes esperadas \n-- e a lista zeta do output\ncomputeOutputError :: Vector Double -> Vector Double -> Vector Double -> Vector Double\ncomputeOutputError a e z = fromList $ hadamardV (toList (add a (scale (-1) e))) (sigV' $ toList z)\n\ncomputeHiddenError :: Matrix R -> Vector Double -> Vector Double -> Vector Double\ncomputeHiddenError ow oe hz = fromList $ hadamardV (toList $ (tr' ow) #> oe) (sigV' (toList hz)) \n\ncomputeOutputDesiredChanges :: Vector Double -> Vector Double -> (Matrix R, Vector Double)\ncomputeOutputDesiredChanges oe ah = let owDesired = oe `outer` ah\n ohDesired = oe\n in (owDesired, ohDesired)\n\ncomputeHiddenDesiredChanges :: Vector Double -> Image -> (Matrix R, Vector Double)\ncomputeHiddenDesiredChanges he image = let hwDesired = he `outer` (fromList image)\n hbDesired = he\n in (hwDesired, hbDesired)\n\ntestEpoch :: [Sample] -> Data -> Int\ntestEpoch testSet network = manageEpoch testSet network (length testSet)\n\nmanageEpoch :: [Sample] -> Data -> Int -> Int\nmanageEpoch testSet network counter = if counter > 0\n then\n let newNetwork = feedforward (snd $ testSet !! counter) network\n in if (toList $ aOutput newNetwork) == buildExpectedOutput (fst $ testSet !! counter) \n then\n 1 + manageEpoch testSet network (counter - 1)\n else\n 0 + manageEpoch testSet network (counter - 1)\n else\n 0\n \n", "meta": {"hexsha": "53779a287c5f110f3637fc62743c8b466499089b", "size": 7495, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Haskell/src/Training.hs", "max_stars_repo_name": "Thulio-Carvalho/NedeReural_Haskell", "max_stars_repo_head_hexsha": "6469552ba35358aa0ffb85d36e7fe2bdd8fad477", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Haskell/src/Training.hs", "max_issues_repo_name": "Thulio-Carvalho/NedeReural_Haskell", "max_issues_repo_head_hexsha": "6469552ba35358aa0ffb85d36e7fe2bdd8fad477", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Haskell/src/Training.hs", "max_forks_repo_name": "Thulio-Carvalho/NedeReural_Haskell", "max_forks_repo_head_hexsha": "6469552ba35358aa0ffb85d36e7fe2bdd8fad477", "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": 56.3533834586, "max_line_length": 147, "alphanum_fraction": 0.5319546364, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5727680087405276}} {"text": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE TypeFamilies #-}\n\n-- | Provides spherical harmonic models of scalar-valued functions.\nmodule Math.SphericalHarmonics\n(\n SphericalHarmonicModel\n, sphericalHarmonicModel\n, scaledSphericalHarmonicModel\n, evaluateModel\n, evaluateModelCartesian\n, evaluateModelGradient\n, evaluateModelGradientCartesian\n, evaluateModelGradientInLocalTangentPlane\n)\nwhere\n\nimport Data.Complex\nimport Data.VectorSpace hiding (magnitude)\nimport Math.SphericalHarmonics.AssociatedLegendre\nimport Numeric.AD\n\n-- | Represents a spherical harmonic model of a scalar-valued function.\ndata SphericalHarmonicModel a = SphericalHarmonicModel [[(a, a)]]\n deriving (Functor)\n\n-- | Creates a spherical harmonic model.\n-- Result in an error if the length of the list is not a triangular number.\nsphericalHarmonicModel :: (Fractional a) => [[(a, a)]] -- ^ A list of g and h coefficients for the model\n -> SphericalHarmonicModel a -- ^ The spherical harmonic model\nsphericalHarmonicModel cs | valid = SphericalHarmonicModel cs\n | otherwise = error \"The number of coefficients is not a triangular number.\"\n where\n valid = and $ zipWith (==) (fmap length cs) [1..length cs]\n\n-- | Creates a spherical harmonic model, scaling coefficients for the supplied reference radius.\n-- Result in an error if the length of the list is not a triangular number.\nscaledSphericalHarmonicModel :: (Fractional a) => a -- ^ The reference radius\n -> [[(a, a)]] -- ^ A list of g and h coefficients for the model\n -> SphericalHarmonicModel a -- ^ The spherical harmonic model\nscaledSphericalHarmonicModel r cs = sphericalHarmonicModel cs'\n where\n cs' = normalizeReferenceRadius r cs\n\ninstance(Fractional a, Eq a) => AdditiveGroup (SphericalHarmonicModel a) where\n zeroV = SphericalHarmonicModel [[(0,0)]]\n negateV = fmap negate\n (SphericalHarmonicModel m1) ^+^ (SphericalHarmonicModel m2) = SphericalHarmonicModel (combineCoefficients m1 m2)\n where\n combineCoefficients [] cs = cs\n combineCoefficients cs [] = cs\n combineCoefficients (c1:cs1) (c2:cs2) = zipWith addPairs c1 c2 : combineCoefficients cs1 cs2\n addPairs (g1, h1) (g2, h2) = (g1 + g2, h1 + h2)\n\ninstance (Fractional a, Eq a) => VectorSpace (SphericalHarmonicModel a) where\n type Scalar (SphericalHarmonicModel a) = a\n x *^ m = fmap (* x) m\n\nnormalizeReferenceRadius :: (Fractional a) => a -> [[(a, a)]] -> [[(a, a)]]\nnormalizeReferenceRadius r = zipWith (fmap . mapWholePair . transform) [0 :: Int ..]\n where\n transform n = (* (r ^ (2 + n)))\n\n-- | Computes the scalar value of the spherical harmonic model at a specified spherical position.\nevaluateModel :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model\n -> a -- ^ Spherical radius\n -> a -- ^ Spherical colatitude (radian)\n -> a -- ^ Spherical longitude (radian)\n -> a -- ^ Model value\nevaluateModel m r colat lon = evaluateModel' m r (cos colat) (cis lon)\n\n-- | Computes the scalar value of the spherical harmonic model at a specified Cartesian position.\nevaluateModelCartesian :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model\n -> a -- ^ X position\n -> a -- ^ Y position\n -> a -- ^ Z position\n -> a -- ^ Model value\nevaluateModelCartesian m x y z = evaluateModel' m r cosColat cisLon\n where\n r = sqrt $ (x*x) + (y*y) + (z*z)\n cosColat = z / r\n cisLon = normalize $ mkPolar x y\n\nevaluateModel' :: (RealFloat a, Ord a) => SphericalHarmonicModel a\n -> a -- r\n -> a -- cosColat\n -> Complex a -- cisLon\n -> a\nevaluateModel' (SphericalHarmonicModel cs) r cosColat cisLon = sum $ zipWith (*) (iterate (/ r) (recip r)) (zipWith evaluateDegree [0..] cs)\n where\n sines = 1 : iterate (* cisLon) cisLon\n evaluateDegree n cs' = sum $ zipWith3 evaluateOrder (fmap (schmidtSemiNormalizedAssociatedLegendreFunction n) [0..n]) cs' sines\n evaluateOrder p (g, h) cisMLon = ((g * realPart cisMLon) + (h * imagPart cisMLon)) * (p (cosColat))\n\n-- | Computes the gradient of the scalar value of the spherical harmonic model, in spherical coordinates, at a specified location.\nevaluateModelGradient :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model\n -> a -- ^ Spherical radius\n -> a -- ^ Spherical colatitude (radian)\n -> a -- ^ Spherical longitude (radian)\n -> (a, a, a) -- ^ Radial, colatitudinal, and longitudinal components of gradient\nevaluateModelGradient model r colat lon = makeTuple . fmap negate $ modelGrad [r, colat, lon]\n where\n modelGrad = grad (\\[r', c', l'] -> evaluateModel (fmap auto model) r' c' l')\n\n-- | Computes the gradient of the scalar value of the spherical harmonic model at a specified location, in Cartesian coordinates.\n-- The result is expressed in right-handed coordinates centered at the origin of the sphere, with the positive Z-axis piercing the\n-- north pole and the positive x-axis piercing the reference meridian.\nevaluateModelGradientCartesian :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model\n -> a -- ^ X position\n -> a -- ^ Y position\n -> a -- ^ Z position\n -> (a, a, a) -- X, Y, and Z components of gradient\nevaluateModelGradientCartesian model x y z = makeTuple . fmap negate $ modelGrad [x, y, z]\n where\n modelGrad = grad (\\[x', y', z'] -> evaluateModelCartesian (fmap auto model) x' y' z')\n\n-- | Computes the gradient of the scalar value of the spherical harmonic model at a specified location, in Cartesian coordinates.\n-- The result is expressed in a reference frame locally tangent to the sphere at the specified location.\nevaluateModelGradientInLocalTangentPlane :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model\n -> a -- ^ Spherical radius\n -> a -- ^ Spherical colatitude (radian)\n -> a -- ^ Spherical longitude (radian)\n -> (a, a, a) -- ^ East, North, and up components of gradient\nevaluateModelGradientInLocalTangentPlane model r colat lon = (e, n, u)\n where\n (r', colat', lon') = evaluateModelGradient model r colat lon\n e = lon' / (r * sin colat)\n n = -colat' / r -- negated because the colatitude increase southward\n u = r'\n\nnormalize :: (RealFloat a) => Complex a -> Complex a\nnormalize r@(x :+ y) | isInfinite m' = 0\n | otherwise = (x * m') :+ (y * m')\n where\n m' = recip . magnitude $ r\n\nmapWholePair :: (a -> b) -> (a, a) -> (b, b)\nmapWholePair f (a, b) = (f a, f b)\n\nmakeTuple :: [a] -> (a, a, a)\nmakeTuple [x, y, z] = (x, y, z)\n", "meta": {"hexsha": "1d7a68e0e429e2130f00ad785e98785f11dc0814", "size": 7080, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/SphericalHarmonics.hs", "max_stars_repo_name": "dmcclean/igrf", "max_stars_repo_head_hexsha": "273c1eaa3dce1612ff334e5eed65f55c06bcb93d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Math/SphericalHarmonics.hs", "max_issues_repo_name": "dmcclean/igrf", "max_issues_repo_head_hexsha": "273c1eaa3dce1612ff334e5eed65f55c06bcb93d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-04-13T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T19:30:59.000Z", "max_forks_repo_path": "src/Math/SphericalHarmonics.hs", "max_forks_repo_name": "dmcclean/igrf", "max_forks_repo_head_hexsha": "273c1eaa3dce1612ff334e5eed65f55c06bcb93d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-09T19:05:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T19:05:42.000Z", "avg_line_length": 49.8591549296, "max_line_length": 140, "alphanum_fraction": 0.6367231638, "num_tokens": 1820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5727680070185481}} {"text": "module Main where\n\nimport Data.Monoid\n\nimport Core\nimport Render\nimport Codec.Picture\nimport Codec.Picture.Types\nimport Numeric.LinearAlgebra(vector)\n\nsettings :: RenderSettings\nsettings = RenderSettings {\n background = PixelRGBF 1 1 1,\n width = 800,\n height = 800,\n path = \"out.png\",\n topLeft = vector [1,1,0],\n topRight = vector [1,-1,0],\n bottomRight = vector [-1, -1,0],\n origin = vector [0,0,-1],\n antialiasing = 10}\n\nscene\n = plane (diffuse (scaleColor 0.5)) (Ray (vec3 (-2) 0 0) (vec3 (-2) 0 0))\n <> sphere 0.9 (vec3 0 0 2) (diffuse (scaleColor 0.5))\n <> plane (skylike white blue) (Ray (vec3 10 0 0) (vec3 1 0 0))\n\nmain :: IO ()\nmain = do\n img <- render settings scene\n savePngImage (path settings) img\n \n", "meta": {"hexsha": "f08009ad46369ed0047f33d9233eabb36881fe6f", "size": 758, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "danrocag/raytracer", "max_stars_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "danrocag/raytracer", "max_issues_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "danrocag/raytracer", "max_forks_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9696969697, "max_line_length": 76, "alphanum_fraction": 0.6345646438, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5722244635773396}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE StrictData #-}\nmodule FourierPinwheel.Harmonics where\n\nimport Data.Array.IArray as IA\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List\nimport Data.List as L\nimport Data.Vector.Generic as VG\nimport Data.Vector.Unboxed as VU\nimport Filter.Utils\nimport Math.Gamma\nimport Utils.Parallel\n\ndata FPData vector = FPData\n { getFPDataHarmonics :: [vector]\n , getFPDataHarmonicsOffset :: [vector]\n , getFPDataCoef :: [vector]\n , getFPDataCoefHollow :: [vector]\n }\n\ncreateHarmonics ::\n ( RealFloat e\n , Unbox e\n , NFData e\n , VG.Vector vector (Complex e)\n , NFData (vector (Complex e))\n , Gamma (Complex e)\n )\n => Int\n -> Int\n -> Int\n -> Int\n -> Int\n -> e\n -> e\n -> e\n -> R.Array U DIM4 (Complex e)\n -> IO (FPData (vector (Complex e)))\ncreateHarmonics numR2Freqs phiFreq rhoFreq thetaFreq rFreq alpha periodR2 periodEnv coefficients = do\n let harmonicVecs =\n parMap\n rdeepseq\n (\\radialFreq ->\n createVector\n numR2Freqs\n (2 * phiFreq + 1)\n 1\n (pinwheel periodR2 radialConst alpha radialFreq))\n [-rhoFreq .. rhoFreq]\n harmonicVecsOffset =\n parMap\n rdeepseq\n (\\radialFreq ->\n createVector\n numR2Freqs\n (2 * thetaFreq + 1)\n (-1)\n (logpolarHarmonics periodR2 radialConst radialFreq)) .\n L.reverse $\n [-rFreq .. rFreq]\n phaseShiftedCoefArr <-\n computeUnboxedP .\n R.zipWith (*) coefficients . fromFunction (extent coefficients) $ \\(Z :. r :. theta :. rho :. phi) ->\n phaseShift\n (phi - phiFreq - (theta - thetaFreq))\n (rho - rhoFreq - (r - rFreq))\n radialConst\n alpha\n let phaseShiftedCoefVecs =\n parMap\n rdeepseq\n (\\r ->\n VU.convert . toUnboxed . computeS . R.slice phaseShiftedCoefArr $\n (Z :. r :. All :. All :. All))\n [0 .. 2 * rFreq]\n coefHollowArr <- computeUnboxedP $ sumArr *^ coefficients\n let coefHollowVecs =\n parMap\n rdeepseq\n (\\r ->\n VU.convert . toUnboxed . computeS . R.slice coefHollowArr $\n (Z :. r :. All :. All :. All))\n [0 .. 2 * rFreq]\n return $\n FPData harmonicVecs harmonicVecsOffset phaseShiftedCoefVecs coefHollowVecs\n where\n radialConst = 2 * pi / log periodEnv\n !sumArr1 =\n computePinwheelArray\n numR2Freqs\n phiFreq\n rhoFreq\n thetaFreq\n rFreq\n alpha\n periodR2\n periodEnv\n sumArr =\n fromListUnboxed (extent coefficients) .\n parMap\n rdeepseq\n (\\(r, theta, rho, phi) ->\n let angularFreq = phi - theta\n radialFreq = rho - r\n in sumArr1 IA.! (radialFreq, angularFreq)) $\n [ (r, theta, rho, phi)\n | r <- [-rFreq .. rFreq]\n , theta <- [-thetaFreq .. thetaFreq]\n , rho <- [-rhoFreq .. rhoFreq]\n , phi <- [-phiFreq .. phiFreq]\n ]\n\n{-# INLINE createVector #-}\ncreateVector ::\n (RealFloat e, Unbox e, VG.Vector vector (Complex e))\n => Int\n -> Int\n -> Int\n -> (Int -> e -> e -> Complex e)\n -> vector (Complex e)\ncreateVector numR2Freqs numAngularFreqs sign f =\n let centerR2 = div numR2Freqs 2\n centerAngular = div numAngularFreqs 2\n in VG.convert .\n toUnboxed .\n computeS . \n makeFilter2D . \n fromFunction (Z :. numAngularFreqs :. numR2Freqs :. numR2Freqs) $ \\(Z :. k :. i :. j) ->\n let x = fromIntegral (i - centerR2)\n y = fromIntegral (j - centerR2)\n rho = sqrt $ x ^ 2 + y ^ 2\n phi = atan2 y x\n in if rho == 0\n then 0\n else f (sign * (k - centerAngular)) phi rho\n\n{-# INLINE pinwheel #-}\npinwheel :: (RealFloat e) => e -> e -> e -> Int -> Int -> e -> e -> Complex e\npinwheel periodR2 radialConst alpha radialFreq angularFreq phi rho =\n pi * cis (fromIntegral angularFreq * phi) *\n ((periodR2 / (pi * rho) :+ 0) **\n ((2 + alpha) :+ (radialConst * fromIntegral radialFreq)))\n\n{-# INLINE logpolarHarmonics #-}\nlogpolarHarmonics ::\n (RealFloat e) => e -> e -> Int -> Int -> e -> e -> Complex e\nlogpolarHarmonics periodR2 radialConst radialFreq angularFreq phi rho =\n cis (fromIntegral angularFreq * phi) *\n ((periodR2 / (pi * rho) :+ 0) **\n (0 :+ (radialConst * fromIntegral radialFreq)))\n\n{-# INLINE phaseShift #-}\nphaseShift ::\n (RealFloat e, Gamma (Complex e)) => Int -> Int -> e -> e -> Complex e\nphaseShift angularFreq radialFreq radialConst alpha =\n ((0 :+ (-1)) ^ abs angularFreq) *\n (gamma $\n ((2 + fromIntegral (abs angularFreq) + alpha) :+\n (radialConst * fromIntegral radialFreq)) /\n 2) /\n (gamma $\n ((fromIntegral (abs angularFreq) - alpha) :+\n (radialConst * fromIntegral (-radialFreq))) /\n 2)\n\n{-# INLINE computeIndicesFromRadius #-}\ncomputeIndicesFromRadius :: Double -> [(Int,Int)]\ncomputeIndicesFromRadius radius =\n let rho = round radius\n r2 = rho ^ 2\n in L.filter\n (\\(x, y) ->\n let r = fromIntegral $ x ^ 2 + y ^ 2\n in r < r2)\n [(x, y) | x <- [-rho .. rho], y <- [-rho .. rho]]\n\n{-# INLINE computePinwheelArray #-}\ncomputePinwheelArray ::\n ( Num e\n , RealFloat e\n , Gamma (Complex e)\n , Unbox e\n , NFData e\n )\n => Int\n -> Int\n -> Int\n -> Int\n -> Int\n -> e\n -> e\n -> e\n -> IA.Array (Int, Int) (Complex e)\ncomputePinwheelArray numR2Freqs phiFreq rhoFreq thetaFreq rFreq alpha periodR2 periodEnv =\n let maxAngularFreq = phiFreq + thetaFreq\n maxRadialFreq = rhoFreq + rFreq\n radialConst = 2 * pi / log periodEnv\n centerR2 = div numR2Freqs 2\n idxs =\n [ (radialFreq, angularFreq)\n | radialFreq <- [-maxRadialFreq .. maxRadialFreq]\n , angularFreq <- [-maxAngularFreq .. maxAngularFreq]\n ]\n pinwheels =\n parMap\n rdeepseq\n (\\(radialFreq, angularFreq) ->\n let arr =\n fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i :. j) ->\n let x = fromIntegral $ i - centerR2\n y = fromIntegral $ j - centerR2\n rho = sqrt $ x ^ 2 + y ^ 2\n phi = atan2 y x\n in if rho == 0\n then 0\n else pinwheel\n periodR2\n radialConst\n alpha\n radialFreq\n angularFreq\n phi\n rho *\n phaseShift\n angularFreq\n radialFreq\n radialConst\n alpha\n in sumAllS arr / (fromIntegral numR2Freqs^2))\n idxs\n in listArray\n ((-maxRadialFreq, -maxAngularFreq), (maxRadialFreq, maxAngularFreq))\n pinwheels\n", "meta": {"hexsha": "479c4d8b41995ef40e06a74934e376ca2bbfc2bc", "size": 7345, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FourierPinwheel/Harmonics.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FourierPinwheel/Harmonics.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/FourierPinwheel/Harmonics.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 30.8613445378, "max_line_length": 105, "alphanum_fraction": 0.5180394826, "num_tokens": 1984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5720507589044079}} {"text": "{-# LANGUAGE ViewPatterns #-}\n-- |\n-- Tests for quantile\nmodule Tests.Quantile (tests) where\n\nimport Control.Exception\nimport qualified Data.Vector.Unboxed as U\nimport Test.Framework\nimport Test.Framework.Providers.HUnit\nimport Test.Framework.Providers.QuickCheck2\nimport Test.HUnit (Assertion,assertEqual,assertFailure)\nimport Test.QuickCheck hiding (sample)\nimport Numeric.MathFunctions.Comparison (ulpDelta,ulpDistance)\nimport Statistics.Quantile\n\ntests :: Test\ntests = testGroup \"Quantiles\"\n [ testCase \"R alg. 4\" $ compareWithR cadpw (0.00, 0.50, 2.50, 8.25, 10.00)\n , testCase \"R alg. 5\" $ compareWithR hazen (0.00, 1.00, 5.00, 9.00, 10.00)\n , testCase \"R alg. 6\" $ compareWithR spss (0.00, 0.75, 5.00, 9.25, 10.00)\n , testCase \"R alg. 7\" $ compareWithR s (0.000, 1.375, 5.000, 8.625,10.00)\n , testCase \"R alg. 8\" $ compareWithR medianUnbiased\n (0.0, 0.9166666666666667, 5.000000000000003, 9.083333333333334, 10.0)\n , testCase \"R alg. 9\" $ compareWithR normalUnbiased\n (0.0000, 0.9375, 5.0000, 9.0625, 10.0000)\n , testProperty \"alg 7.\" propWeigtedAverage\n -- Test failures\n , testCase \"weightedAvg should throw errors\" $ do\n let xs = U.fromList [1,2,3]\n xs0 = U.fromList []\n shouldError \"Empty sample\" $ weightedAvg 1 4 xs0\n shouldError \"N=0\" $ weightedAvg 1 0 xs\n shouldError \"N=1\" $ weightedAvg 1 1 xs\n shouldError \"k<0\" $ weightedAvg (-1) 4 xs\n shouldError \"k>N\" $ weightedAvg 5 4 xs\n , testCase \"quantile should throw errors\" $ do\n let xs = U.fromList [1,2,3]\n xs0 = U.fromList []\n shouldError \"Empty xs\" $ quantile s 1 4 xs0\n shouldError \"N=0\" $ quantile s 1 0 xs\n shouldError \"N=1\" $ quantile s 1 1 xs\n shouldError \"k<0\" $ quantile s (-1) 4 xs\n shouldError \"k>N\" $ quantile s 5 4 xs\n --\n , testProperty \"quantiles are OK\" propQuantiles\n , testProperty \"quantilesVec are OK\" propQuantilesVec\n ]\n\nsample :: U.Vector Double\nsample = U.fromList [0, 1, 2.5, 7.5, 9, 10]\n\n-- Compare quantiles implementation with reference R implementation\ncompareWithR :: ContParam -> (Double,Double,Double,Double,Double) -> Assertion\ncompareWithR p (q0,q1,q2,q3,q4) = do\n assertEqual \"Q 0\" q0 $ quantile p 0 4 sample\n assertEqual \"Q 1\" q1 $ quantile p 1 4 sample\n assertEqual \"Q 2\" q2 $ quantile p 2 4 sample\n assertEqual \"Q 3\" q3 $ quantile p 3 4 sample\n assertEqual \"Q 4\" q4 $ quantile p 4 4 sample\n\npropWeigtedAverage :: Positive Int -> Positive Int -> Property\npropWeigtedAverage (Positive k) (Positive q) =\n (q >= 2 && k <= q) ==> let q1 = weightedAvg k q sample\n q2 = quantile s k q sample\n in counterexample (\"weightedAvg = \" ++ show q1)\n $ counterexample (\"quantile = \" ++ show q2)\n $ counterexample (\"delta in ulps = \" ++ show (ulpDelta q1 q2))\n $ ulpDistance q1 q2 <= 16\n\npropQuantiles :: Positive Int -> Int -> Int -> NonEmptyList Double -> Property\npropQuantiles (Positive n)\n ((`mod` n) -> k1)\n ((`mod` n) -> k2)\n (NonEmpty xs)\n = n >= 2\n ==> [x1,x2] == quantiles s [k1,k2] n rndXs\n where\n rndXs = U.fromList xs\n x1 = quantile s k1 n rndXs\n x2 = quantile s k2 n rndXs\n\npropQuantilesVec :: Positive Int -> Int -> Int -> NonEmptyList Double -> Property\npropQuantilesVec (Positive n)\n ((`mod` n) -> k1)\n ((`mod` n) -> k2)\n (NonEmpty xs)\n = n >= 2\n ==> U.fromList [x1,x2] == quantilesVec s (U.fromList [k1,k2]) n rndXs\n where\n rndXs = U.fromList xs\n x1 = quantile s k1 n rndXs\n x2 = quantile s k2 n rndXs\n\n\nshouldError :: String -> a -> Assertion\nshouldError nm x = do\n r <- try (evaluate x)\n case r of\n Left (ErrorCall{}) -> return ()\n Right _ -> assertFailure (\"Should call error: \" ++ nm)\n", "meta": {"hexsha": "12a310f9d5c9409924f25b47d8197fd934bb9cb4", "size": 3898, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Tests/Quantile.hs", "max_stars_repo_name": "intricate/statistics", "max_stars_repo_head_hexsha": "7ac06d597eefb2c42dd3b726c8f5cb17e54f72d7", "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": "tests/Tests/Quantile.hs", "max_issues_repo_name": "intricate/statistics", "max_issues_repo_head_hexsha": "7ac06d597eefb2c42dd3b726c8f5cb17e54f72d7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Tests/Quantile.hs", "max_forks_repo_name": "intricate/statistics", "max_forks_repo_head_hexsha": "7ac06d597eefb2c42dd3b726c8f5cb17e54f72d7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5940594059, "max_line_length": 88, "alphanum_fraction": 0.6164699846, "num_tokens": 1316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5720462322087169}} {"text": "{-# LANGUAGE TemplateHaskell #-}\nmodule AI.NeuralNetwork\n ( Network\n , layerSizes\n , biases\n , weights\n , sigmoid\n , newNetwork\n , feedforward\n , toFile\n , fromFile ) where\n\nimport Control.Lens\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Random.Normal\nimport Numeric.LinearAlgebra\nimport System.IO\nimport System.Random\n\ndata Network = Network { _layerSizes :: [Int]\n , _biases :: [Vector Double]\n , _weights :: [Matrix Double] }\n deriving (Eq, Show)\n\nmakeLenses ''Network\n\nsigmoid :: Floating a => a -> a\nsigmoid z = 1.0 / (1 + exp (negate z))\n\nnewNetwork :: Monad m => [Int] -> StateT StdGen m Network\nnewNetwork sizes = do\n let matrixSizes = zip (init sizes) (tail sizes)\n\n biasesL <- mapM sequence\n [[state normal | _ <- [1..y]] | y <- tail sizes]\n weightsL <- mapM sequence $\n [[state normal | _ <- [1..x], x <- [1..y]] | (x, y) <- matrixSizes]\n\n let randBiases = map fromList biasesL\n let randWeights = map (\\((x, y), l) -> (y> Network -> Vector Double\nfeedforward input nn = foldl (\\a (b, w) -> cmap sigmoid ((w #> a) + b)) input bw\n where bw = zip (nn^.biases) (nn^.weights)\n\ntoFile :: FilePath -> Network -> IO ()\ntoFile filepath nn =\n let headerStr = show (nn^.layerSizes) ++ \"\\n\"\n biasesStr = unlines $ show . toList <$> (nn^.biases)\n weightsStr = unlines $ show . toLists <$> (nn^.weights)\n nnStr = headerStr ++ biasesStr ++ weightsStr\n in writeFile filepath nnStr\n\nfromFile :: FilePath -> IO Network\nfromFile filepath = withFile filepath ReadMode (\\handle -> do\n layerSizes' <- (read :: String -> [Int]) <$> hGetLine handle\n biases' <- forM (tail layerSizes') $ \\_ -> do\n line <- hGetLine handle\n return $ fromList $ (read :: String -> [Double]) line\n weights' <- forM (tail layerSizes') $ \\_ -> do\n line <- hGetLine handle\n return $ fromLists $ (read :: String -> [[Double]]) line\n return $ Network { _layerSizes = layerSizes'\n , _biases = biases'\n , _weights = weights' })\n", "meta": {"hexsha": "31d06568149943362b95f494c329263ab86f75cc", "size": 2433, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/NeuralNetwork.hs", "max_stars_repo_name": "cornelius-sevald/neurocar", "max_stars_repo_head_hexsha": "9a8529ab2007b98ab20b6ce0b7e29ec7cbe085bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AI/NeuralNetwork.hs", "max_issues_repo_name": "cornelius-sevald/neurocar", "max_issues_repo_head_hexsha": "9a8529ab2007b98ab20b6ce0b7e29ec7cbe085bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AI/NeuralNetwork.hs", "max_forks_repo_name": "cornelius-sevald/neurocar", "max_forks_repo_head_hexsha": "9a8529ab2007b98ab20b6ce0b7e29ec7cbe085bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2676056338, "max_line_length": 80, "alphanum_fraction": 0.5626798192, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5720293203683064}} {"text": "module FFTSerialSpec where\n\nimport qualified Clash.Prelude as Clash\nimport Clash.Prelude (Signal, Vec(..), BitVector, Index, Signed, Unsigned, SFixed, Bit, SNat(..),\n simulate, simulate_lazy, listToVecTH, KnownNat, pack, unpack, (++#), mealy, mux, bundle, unbundle, \n HiddenClockResetEnable, System)\nimport Test.Hspec\nimport Test.QuickCheck\n\nimport qualified Numeric.FFT as FFT\nimport qualified Data.Complex as C\nimport Clash.DSP.Complex (Complex, fromComplex, toComplex)\nimport Clash.DSP.FFT.Serial\nimport Clash.DSP.FFT.Example\nimport Clash.DSP.FFT.Twiddle (twiddleFactors)\n\n--serial FFT\nspec = describe \"Serial FFTs\" $ do\n specify \"Decimation in time equals known good implementation\" $ property prop_fftSerialDIT\n specify \"Decimation in frequency equals known good implementation\" $ property prop_fftSerialDIF\n\napproxEqual :: Double -> Double -> Bool\napproxEqual x y = abs (x - y) < 0.0001\n\napproxEqualComplex (a C.:+ b) (c C.:+ d) = approxEqual a c && approxEqual b d\n\ntwiddles4 :: Vec 4 (Complex Double)\ntwiddles4 = $(listToVecTH (twiddleFactors 4))\n\nditInputReorder :: Vec 8 a -> Vec 4 (a, a)\nditInputReorder (a :> b :> c :> d :> e :> f :> g :> h :> Nil) = (a, e) :> (c, g) :> (b, f) :> (d, h) :> Nil\n\nditOutputReorder :: [(a, a)] -> [a]\nditOutputReorder ((a, b) : (c, d) : (e, f) : (g, h) : _) = a : c : e : g : b : d : f : h : []\n\ndifInputReorder :: Vec 8 a -> Vec 4 (a, a)\ndifInputReorder (a :> b :> c :> d :> e :> f :> g :> h :> Nil) = (a, e) :> (b, f) :> (c, g) :> (d, h) :> Nil\n\ndifOutputReorder :: [(a, a)] -> [a]\ndifOutputReorder ((a, b) : (c, d) : (e, f) : (g, h) : _) = a : e : c : g : b : f : d : h : []\n\nprop_fftSerialDIT :: Vec 8 (C.Complex Double) -> Bool\nprop_fftSerialDIT vec = and $ zipWith approxEqualComplex (map toComplex result) (FFT.fft (Clash.toList vec))\n where\n result = ditOutputReorder $ drop 8 $ simulate_lazy @System (fftSerialDIT twiddles4 (pure True)) $ (Clash.toList (ditInputReorder (Clash.map fromComplex vec))) ++ repeat (0, 0)\n\nprop_fftSerialDIF :: Vec 8 (C.Complex Double) -> Bool\nprop_fftSerialDIF vec = and $ zipWith approxEqualComplex (map toComplex result) (FFT.fft (Clash.toList vec))\n where\n result = difOutputReorder $ drop 8 $ simulate_lazy @System (fftSerialDIF twiddles4 (pure True)) $ (Clash.toList (difInputReorder (Clash.map fromComplex vec))) ++ repeat (0, 0)\n\n", "meta": {"hexsha": "e22bea9136af4cd526af0df5439cc83c68deef6b", "size": 2383, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/FFTSerialSpec.hs", "max_stars_repo_name": "adamwalker/clash-utils", "max_stars_repo_head_hexsha": "f122e298b15eadce3fa5ad284a5fe49466eff3a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2017-01-23T06:54:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T08:10:29.000Z", "max_issues_repo_path": "tests/FFTSerialSpec.hs", "max_issues_repo_name": "adamwalker/clash-utils", "max_issues_repo_head_hexsha": "f122e298b15eadce3fa5ad284a5fe49466eff3a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2017-04-05T08:56:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-25T12:05:09.000Z", "max_forks_repo_path": "tests/FFTSerialSpec.hs", "max_forks_repo_name": "adamwalker/clash-utils", "max_forks_repo_head_hexsha": "f122e298b15eadce3fa5ad284a5fe49466eff3a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-04-03T22:25:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-10T07:43:32.000Z", "avg_line_length": 45.8269230769, "max_line_length": 179, "alphanum_fraction": 0.6537977339, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.5720188716676549}} {"text": "module EquivarianceDiagram where\n\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Unboxed as VU\nimport DFT.Plan\nimport Filter.Gaussian\nimport Image.IO\nimport System.Directory\nimport System.Environment\nimport System.FilePath\n\nmain = do\n (inputPath:sigmaStr:_) <- getArgs\n (ImageRepa _ img) <- readImageRepa inputPath True\n let (Z :. channels :. cols :. rows) = extent img\n sigma = read sigmaStr :: Double\n folderPath = \"output/test/EquivarianceDiagram\"\n createDirectoryIfMissing True folderPath\n lock <- getFFTWLock\n (plan1, imgF) <-\n dft1dGPlan lock emptyPlan [channels, cols, rows] [1, 2] .\n VU.convert . VU.map (:+ 0) . toUnboxed $\n img\n (plan2, _) <- idft1dGPlan lock plan1 [channels, cols, rows] [1, 2] imgF\n (plan, gaussianFilterF) <-\n gaussian2DFilter plan2 (Gaussian2DParams sigma rows cols)\n convolvedImg <- convolveGaussian2D plan gaussianFilterF . R.map (:+ 0) $ img\n plotImageRepa (folderPath (takeBaseName inputPath) L.++ \"_out.png\") .\n ImageRepa 8 . computeS . R.map magnitude $\n convolvedImg\n", "meta": {"hexsha": "d3999e25859754bc7183591839efdb267e0a6190", "size": 1203, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/EquivarianceDiagram/EquivarianceDiagram.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/EquivarianceDiagram/EquivarianceDiagram.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/EquivarianceDiagram/EquivarianceDiagram.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 36.4545454545, "max_line_length": 78, "alphanum_fraction": 0.650872818, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.571737378090287}} {"text": "-- A simple example testing arithmetic functions.\n{-# LANGUAGE FlexibleInstances #-}\nimport Control.Monad\nimport Data.Complex\nimport Data.Either\nimport Data.Matrix\nimport Data.Ord\nimport Data.Vector (Vector)\nimport Numeric.Natural\nimport QuickSpec hiding (A)\nimport QuickSpec.Internal hiding (A)\nimport qualified QuickSpec.Internal.Haskell as Haskell\nimport Test.QuickCheck\nimport Test.QuickCheck.Instances\nimport Twee.Pretty\n\ndim = 5\n\ntype A = Rational\ntype T = Matrix A\n\ninstance Ord a => Ord (Matrix a) where\n compare = comparing toLists\n\ninstance (RealFrac a, Ord a) => Ord (Complex a) where\n compare = comparing (\\(x :+ y) -> (truncate (x*1000), truncate (y*1000)))\n\n--instance Ord Cyclotomic where\n-- compare = comparing show\n--\n--instance Arbitrary Cyclotomic where\n-- arbitrary = sized arb\n-- where\n-- arb n =\n-- frequency $\n-- [(5, fromInteger <$> arbitrary),\n-- (5, fromRational <$> arbRat),\n-- (5, gaussianRat <$> arbRat <*> arbRat),\n-- (5, polarRat <$> arbRat <*> arbRat),\n-- (5, e <$> fmap (succ . abs) arbitrary),\n-- (3, sqrtInteger <$> arbitrary),\n-- (3, sqrtRat <$> arbRat),\n-- (2, sinRev <$> arbRat),\n-- (2, cosRev <$> arbRat),\n-- (2, return i)] ++\n-- concat\n-- [ [(5, conj <$> arb (n-1)),\n-- (3, real <$> arb (n-1)),\n-- (3, imag <$> arb (n-1))]\n-- | n > 0 ] ++\n-- concat\n-- [ let arb2 = arb (n `div` 2) in\n-- [(n*5, (+) <$> arb2 <*> arb2),\n-- (n*5, (*) <$> arb2 <*> arb2)]\n-- | n > 0 ]\n-- arbRat = sized $ \\n -> do\n-- x <- choose (-(n `min` 3), n `min` 3)\n-- d <- fmap (succ . abs) (choose (0, n `min` 5))\n-- n <- choose (0, d-1)\n-- return (fromIntegral x + fromIntegral n / fromIntegral d)\n\ninstance Arbitrary T where\n arbitrary =\n makeHermitian <$> frequency [\n--(1, return $ zero dim dim),\n-- (1, return $ identity dim),\n-- (1, return $ negate $ identity dim),\n-- (1, genDiagonal),\n (5, fromList dim dim <$> infiniteListOf genA)]\n\ngenA :: Gen A\ngenA = fromInteger <$> arbitrary\n\ngenDiagonal :: Gen T\ngenDiagonal = diagonalList dim 0 <$> infiniteListOf genA\n\nisDiagonal :: T -> Bool\nisDiagonal m = m == diagonal 0 (getDiag m)\n\nmakeUpperTriangular :: T -> T\nmakeUpperTriangular = mapPos (\\(i, j) x -> if i > j then 0 else x)\n\nisUpperTriangular :: T -> Bool\nisUpperTriangular m = makeUpperTriangular m == m\n\ngenUpperTriangular :: Gen T\ngenUpperTriangular = makeUpperTriangular <$> arbitrary\n\nmakeLowerTriangular :: T -> T\nmakeLowerTriangular = mapPos (\\(i, j) x -> if i > j then 0 else x)\n\nisLowerTriangular :: T -> Bool\nisLowerTriangular m = makeLowerTriangular m == m\n\ngenLowerTriangular :: Gen T\ngenLowerTriangular = makeLowerTriangular <$> arbitrary\n\nmakeHermitian :: T -> T\nmakeHermitian m = m + {-fmap conjugate-} transpose m\n\nisHermitian :: T -> Bool\nisHermitian m = m == {-fmap conjugate-} transpose m\n\ngenHermitian :: Gen T\ngenHermitian = makeHermitian <$> arbitrary\n\ninstance Floating Rational where\n sqrt = error \"sqrt\"\ninstance RealFloat Rational\n\nnewtype RowV = RowV {unRowV :: T} deriving (Eq, Ord)\nnewtype ColV = ColV {unColV :: T} deriving (Eq, Ord)\n\ninstance Arbitrary RowV where\n arbitrary = RowV <$> oneof [return $ zero 1 dim, fromList 1 dim <$> infiniteList]\ninstance Arbitrary ColV where\n arbitrary = (ColV <$> transpose) . unRowV <$> arbitrary\n\ntimes :: T -> T -> T\ntimes x y = scaleMatrix (1/2) (x*y+y*x)\n\npow :: Natural -> T -> T\npow 1 t = t\npow n t | n > 0 = times t (pow (n-1) t)\n\nmain = quickSpec [\n series [\n background\n [withMaxTermSize 7,\n -- Good pruning settings for Hard Maths (TM)\n --withPruningTermSize 9,\n arith (Proxy :: Proxy A),\n arith (Proxy :: Proxy Natural) `without` [\"0\"],\n con \"*\" ((*) :: Natural -> Natural -> Natural),\n monoType (Proxy :: Proxy T),\n con \"0\" (zero dim dim :: T),\n con \"I\" (identity dim :: T),\n con \"+\" ((+) :: T -> T -> T),\n vars [\"A\", \"B\", \"C\"] (Proxy :: Proxy T),\n vars [\"n\", \"m\", \"l\"] (Proxy :: Proxy Natural),\n instFun (arbitrary `suchThat` (\\n -> n > 0 && n < 4) :: Gen Natural)],\n --con \"*\" ((*) :: T -> T -> T),\n --con \"-\" (negate :: T -> T)],\n --[(con \"&&\" (&&))],\n --[predicateGen \"hermitian\" isHermitian (\\() -> liftM2 (,) genHermitian (return ()))],\n con \"\u2218\" times,\n con \"^\" (flip pow)]]\n{- [--con \"perm\" (permMatrix dim :: Int -> Int -> T),\n con \"transpose\" (transpose :: T -> T),\n --con \"inverse\" (either (const Nothing) Just . (inverse :: T -> Either String T)),\n con \"trace\" (trace :: T -> A),\n con \"diagProd\" (diagProd :: T -> A),\n con \"det\" (detLU :: T -> A)],\n {-predicateGen \"isDiagonal\" isDiagonal (\\() -> liftM2 (,) genDiagonal (return ())),\n predicateGen \"isUpperTriangular\" isUpperTriangular (\\() -> liftM2 (,) genUpperTriangular (return ())),\n predicateGen \"isLowerTriangular\" isLowerTriangular (\\() -> liftM2 (,) genLowerTriangular (return ()))],-}\n [monoType (Proxy :: Proxy RowV),\n con \"0R\" (RowV (zero 1 dim)),\n con \"+R\" (\\(RowV x) (RowV y) -> RowV (x+y)),\n con \"*R\" (\\(RowV x) y -> RowV (x*y)),\n con \"-R\" (\\(RowV x) -> RowV (negate x))],\n [con \"transposeR\" (\\(RowV x) -> ColV (transpose x)),\n con \"detR\" (detLU . unRowV)],\n [monoType (Proxy :: Proxy ColV),\n con \"0C\" (ColV (zero dim 1)),\n con \"+C\" (\\(ColV x) (ColV y) -> ColV (x+y)),\n con \"*C\" (\\(ColV x) y -> ColV (x*y)),\n con \"-C\" (\\(ColV x) -> ColV (negate x))],\n [con \"transposeC\" (\\(ColV x) -> RowV (transpose x)),\n con \"detC\" (detLU . unColV)]]]-}\n", "meta": {"hexsha": "8966f1fe6e9b62dfc0aa7fa229207c0e072331c7", "size": 5833, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/Matrix.hs", "max_stars_repo_name": "danwdart/quickspec", "max_stars_repo_head_hexsha": "c31d9191daaca05f5a1a1d30450b710cecfcf974", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Matrix.hs", "max_issues_repo_name": "danwdart/quickspec", "max_issues_repo_head_hexsha": "c31d9191daaca05f5a1a1d30450b710cecfcf974", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Matrix.hs", "max_forks_repo_name": "danwdart/quickspec", "max_forks_repo_head_hexsha": "c31d9191daaca05f5a1a1d30450b710cecfcf974", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1111111111, "max_line_length": 110, "alphanum_fraction": 0.5530601749, "num_tokens": 1779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5717373755734001}} {"text": "module Quantum\n ( QRegister,\n QGate,\n C,\n qbitsNum,\n dimensionsNum,\n qbit,\n qregister,\n qbitL,\n qregisterL,\n makeGateC,\n makeGate,\n (|>),\n (|+>),\n measure,\n )\nwhere\n\nimport Data.Complex\nimport Data.List (sort)\nimport Matrix\nimport System.Random (randomRIO)\nimport Utils\n\ntype C = Complex Double\n\ndata QRegister = QRegister\n { qbitsNum :: Int,\n states :: Matrix C\n }\n\ninstance Show QRegister where\n show (QRegister n xm) = show xm\n\ndata QGate = QGate\n { dimensionsNum :: Int,\n operator :: Matrix C\n }\n\ninstance Show QGate where\n show (QGate n xm) = show xm\n\nclass Entanglable a where\n entangle :: a -> a -> a\n\ninstance Entanglable QRegister where\n entangle (QRegister n1 xm) (QRegister n2 ym) = QRegister n zm\n where\n n = n1 + n2\n zm = kron xm ym\n\ninstance Entanglable QGate where\n entangle (QGate n1 xm) (QGate n2 ym) = QGate n zm\n where\n n = n1 + n2\n zm = kron xm ym\n\nqbitL :: Int -> [C]\nqbitL 0 = [1 :+ 0, 0 :+ 0]\nqbitL 1 = [0 :+ 0, 1 :+ 0]\nqbitL _ = error \"Expecting |0> or |1>\"\n\nqbit :: Int -> QRegister\nqbit = QRegister 1 . vectorV . qbitL\n\napplyGate :: QGate -> QRegister -> QRegister\napplyGate (QGate n1 xm) (QRegister n2 ym)\n | n1 /= n2 = error \"Dimensions of gate and number of qbits in register disagree\"\n | otherwise = QRegister n2 (mult xm ym)\n\nqregister :: [Int] -> QRegister\nqregister = foldl1 entangle . map qbit\n\nqregisterL :: [Int] -> [C]\nqregisterL = concat . toList . states . qregister\n\nmakeGateC :: Matrix C -> QGate\nmakeGateC xm\n | r /= c = error \"Gate matrix must be square\"\n | not . powerOfTwo $ r = error \"Gate matrix dimensions must be power of two\"\n | otherwise = QGate n xm\n where\n r = rowsNum xm\n c = colsNum xm\n n = log2 r\n powerOfTwo n = odd n || (elem n . take (log2 n + 1) . map (2 ^) $ [1 ..])\n log2 = fromIntegral . truncate . logBase 2.0 . fromIntegral\n\nmakeGate :: Matrix Double -> QGate\nmakeGate = makeGateC . fmap (:+ 0.0)\n\ninfixl 7 |>\n\n(|>) :: QRegister -> QGate -> QRegister\n(|>) = flip applyGate\n\ninfixl 8 |+>\n\n(|+>) :: Entanglable a => a -> a -> a\n(|+>) = entangle\n\nmeasure :: QRegister -> IO Int\nmeasure (QRegister n xm) = do\n rnd <- randomRIO (0, 1) :: IO Double\n let state = length . takeWhile (< rnd) $ probs\n return (state - 1)\n where\n probs = sort . (\\xs -> 0.0 : xs ++ [1]) . scanl1 (+) . map ((^ 2) . magnitude) . concat . toList $ xm\n", "meta": {"hexsha": "c3e9a229321ff2a6ab13dd9d00b4cd5d8b761f09", "size": 2396, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Quantum.hs", "max_stars_repo_name": "meownoid/Deutsch-Jozsa", "max_stars_repo_head_hexsha": "d01f173382913e935765aa860bc9c72fefb4b311", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-11T00:35:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T00:35:59.000Z", "max_issues_repo_path": "src/Quantum.hs", "max_issues_repo_name": "meownoid/Deutsch-Jozsa", "max_issues_repo_head_hexsha": "d01f173382913e935765aa860bc9c72fefb4b311", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Quantum.hs", "max_forks_repo_name": "meownoid/Deutsch-Jozsa", "max_forks_repo_head_hexsha": "d01f173382913e935765aa860bc9c72fefb4b311", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9816513761, "max_line_length": 105, "alphanum_fraction": 0.6160267112, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5717165998070656}} {"text": "module Space where\n\nimport Data.Set\nimport qualified Data.Set as S\n\nimport Data.Vector\nimport qualified Data.Vector as V\n\nimport Numeric.LinearAlgebra\nimport qualified Numeric.LinearAlgebra as M\n\n\n\n\n\n-- INITIALISATION ---------------------------------------------------------------------------------\n\n-- The data Space (short for simplicial complex) consist of a set of simplices with\n-- the following property: all the faces of all the simplices in the set must also\n-- belong to the set. A simplex is implemented as a Set for efficiency.\n-- For convenience, the set of simplices is split into a list according to the\n-- dimension. The defining condition is unchecked as, in practice, the helper\n-- function allSimplices (below) is always used to iniatialise the data. The output\n-- of the helper function is always valid.\n\ndata Space t = Space { subsimplices :: [Set (Set t)] } deriving (Show)\n\n\n\n-- This helper function takes a set of simplices as input and returns a valid\n-- simplicial complex. The input consists of all the highest dimensional simplices\n-- which make up the space. The function takes all their boundaries and sorts\n-- them by dimension. The lowest dimension is -1 and it is the dimension of the\n-- empty set. It is considered a simplex.\nallSimplices :: (Ord t) => [[t]] -> [Set (Set t)]\nallSimplices [] = error \"This space has no faces. For empty space input '[[]]'.\"\nallSimplices faces =\n\n let associatedSet = S.fromList (Prelude.map (S.fromList) faces)\n powerFaces = S.map (S.powerSet) associatedSet\n allMixedFaces = S.foldl (S.union) S.empty powerFaces\n lengthFunctions = [ \\xs -> (S.size xs == n) | n <- [0,1..] ]\n\n in sieveAndForget lengthFunctions allMixedFaces\n\n\n\nsieveAndForget :: [t -> Bool] -> Set t -> [Set t]\nsieveAndForget (f:fs) xs \n | (S.size xs == 0) = []\n | otherwise = p1 : (sieveAndForget fs p2)\n where (p1,p2) = S.partition (f) xs\n\n\n\n\n\n-- HOMOLOGY ---------------------------------------------------------------------------------------\n\n-- This function only computes the free rank of the homology groups. It does not give\n-- any information about the torsion subgroups. These require knowledge of the\n-- Smith decomposition of a matrix, an algorithm which has never been developed in\n-- Haskell (over a PID). To compute the free rank, it is enough to know the rank\n-- of the boundary operators (through the package Numeric.LinearALgebra)\n\n-- This function returns the homology numbers of a space from 0 up to its dimension.\n-- All the other homology numbers must be zero.\nhomology :: (Ord t) => Space t -> [Int]\nhomology (Space { subsimplices = xs }) =\n let operators = chainComplex (Space { subsimplices = xs })\n dimensionDomains = Prelude.map (M.cols) operators \n dimensionImages = Prelude.map (M.rank) (Prelude.tail operators)\n dimensionAugmentedImages = 0:dimensionImages\n dimensionShiftedImages = dimensionImages Prelude.++ [0]\n dimensionKernels = Prelude.zipWith (-) dimensionDomains dimensionAugmentedImages\n\n in Prelude.zipWith (-) dimensionKernels dimensionShiftedImages\n\n\n\n-- Very small variation on homology. It is used to understand if a space is connected.\nreducedHomology :: (Ord t) => Space t -> [Int]\nreducedHomology space = reduced\n where reduced = (x-1):xs\n (x:xs) = homology space\n\n\n\n-- Computes all boundary operators in a chain complex\nchainComplex :: (Ord t) => Space t -> [M.Matrix R]\nchainComplex (Space { subsimplices = xs }) = \n\n let listOfSimplices = Prelude.map (S.toList) xs\n domainListOfSimplices = Prelude.tail listOfSimplices\n imageListOfSimplices = Prelude.init listOfSimplices\n domainVectorOfSimplices = Prelude.map (V.fromList) domainListOfSimplices\n imageVectorOfSimplices = Prelude.map (V.fromList) imageListOfSimplices\n domainImage = Prelude.zip domainVectorOfSimplices imageVectorOfSimplices\n\n in Prelude.map (boundaryOperator) domainImage\n \n\n\n-- Computes boundary operator for all simplices of a fixed dimension.\nboundaryOperator :: (Ord t) => (V.Vector (Set t) , V.Vector (Set t))-> M.Matrix R\nboundaryOperator (domain , image) = convertToMatrix vectorMatrix\n where vectorMatrix = V.map (f) domain\n f = \\x -> (piecewiseBoundaryOperator x image)\n\n\n\n-- Computes boundary operator of a single simplex.\npiecewiseBoundaryOperator :: (Ord t) => Set t -> V.Vector (Set t) -> V.Vector Int\npiecewiseBoundaryOperator element image = \n let f imageFace\n | (what == False) = 0\n | odd indicator = 1\n | otherwise = -1\n \n where (s1 , what , s2) = S.splitMember imageFace facesOfElement\n -- Shortcut to compute the sign of a face\n indicator = S.size element + S.size s1\n facesOfElement = S.map (g) element \n g = \\y -> (S.delete y element)\n\n in V.map (f) image \n \n\n\n\n\n-- MATRIX CONVERSION ------------------------------------------------------------------------------\n\n-- These algorithms are necessary to convert from V.Vector to M.Matrix. \n-- Unfortunately these two data lack compatibility. Furthermore\n-- M.Vector cannot store Sets, hence they cannot be used from the beginning.\n-- Ideally, the Smith Normal Form should be called directly on the V.Vector\n-- so to avoid using M.Matrix all together.\n\nconvertToMatrix :: V.Vector (V.Vector Int) -> M.Matrix R\nconvertToMatrix vectorMatrix = M.matrix s doubleFlattenedListMatrix\n where s = V.length vectorMatrix\n doubleFlattenedListMatrix = Prelude.map (fromIntegral) flattenedListMatrix\n flattenedListMatrix = Prelude.foldl (Prelude.++) [] listMatrix\n listMatrix = Prelude.map (V.toList) listVectorMatrix\n listVectorMatrix = V.toList transposedVectorMatrix\n transposedVectorMatrix = transpose vectorMatrix\n \n\ntranspose :: V.Vector (V.Vector Int) -> V.Vector (V.Vector Int)\ntranspose matrix = V.foldr (g) emptyVector matrix\n where emptyVector = V.replicate s V.empty\n s = V.length ((V.!) matrix 0)\n g = \\x y -> V.zipWith (V.cons) x y \n\n\n\n\n\n-- BASIC FUNCTIONS --------------------------------------------------------------------------------\n\n-- These functions are basic as they do not rely on computing homology.\n\n-- The function returns the dimension of the highest dimensional simplices. \n-- 2 is subtracted to account for the simplices of dimension 0 and -1.\ndimension :: (Ord t) => Space t -> Int\ndimension (Space { subsimplices = xs }) = Prelude.length xs - 2\n\n\n\n-- This function returns the number of simplices of a given dimension.\nnumberOfSimplices :: (Ord t) => Space t -> Int -> Int\nnumberOfSimplices (Space { subsimplices = xs }) dim\n | dim < -1 || dim > maxDim = 0\n | otherwise = S.size simplicesDim\n\n where maxDim = dimension (Space { subsimplices = xs })\n simplicesDim = xs !! index\n index = dim + 1\n\n\n\neulerCharacteristic :: (Ord t) => Space t -> Int\neulerCharacteristic (Space { subsimplices = xs }) = \n alternatingSum (Prelude.tail lengths)\n\n where alternatingSum :: (Num t) => [t] -> t\n alternatingSum [] = error \"Not defined.\"\n alternatingSum [x] = x\n alternatingSum (x:xs) = x - alternatingSum xs\n\n lengths = (Prelude.map (S.size) xs)\n\n\n\n\n\n-- ADVANCED FUNCTIONS -----------------------------------------------------------------------------\n\n-- These functions all rely on homology.\n\nisConnected :: (Ord t) => Space t -> Bool\nisConnected space = (zeroHomology == 1)\n where zeroHomology = Prelude.head (homology space)\n\n\n\n-- This function can tell if a space is not homotopic to a topological manifold.\n-- Note that, for the reasons above, it only checks Poincar\u00e9 duality up to torsion.\nrationalPoincareDuality :: (Ord t) => Space t -> Bool\nrationalPoincareDuality space = (homNumbers == revHomNumbers)\n where revHomNumbers = Prelude.reverse homNumbers\n homNumbers = homology space\n\n\n\n-- If this function returns False then the answer is definitely No. If it returns\n-- True, then the algorthm is inconcludent. The function first checks the Euler\n-- characteristic as this is a less expensice invariant to compute, albeit coarser.\n-- If it is the same, homology ranks are computed.\ncouldItBeContractible :: (Ord t) => Space t -> Bool\ncouldItBeContractible space = (euler == 1) && (isZero reduced) \n where euler = eulerCharacteristic space\n reduced = reducedHomology space\n\n\n\n-- Simple helper function to check if all the entries in a list are zero\nisZero :: [Int] -> Bool\nisZero [] = error \"Empty list.\"\nisZero [0] = True\nisZero (x:xs) = (x == 0) && (isZero xs)\n\n\n\n-- Again, if the function returns True, no new information is gained. The\n-- Euler characteristic is computed first. This algorithm only checks\n-- if the homology numbers are the same, however, it is necessary to add\n-- enough zeros to the shorter list to equate the lengths.\ncouldTheyBeHomotopic :: (Ord t) => Space t -> Space t -> Bool\ncouldTheyBeHomotopic space1 space2 = (euler1 == euler2) && (hom1 == hom2)\n where euler1 = eulerCharacteristic space1\n euler2 = eulerCharacteristic space2\n hom1 = tempHom1 Prelude.++ zeroList1\n hom2 = tempHom2 Prelude.++ zeroList2\n tempHom1 = homology space1\n tempHom2 = homology space2\n zeroList1 = [ 0 | x <- [1..s1]]\n zeroList2 = [ 0 | x <- [1..s2]]\n s1 = maxLength - length1\n s2 = maxLength - length2\n length1 = Prelude.length tempHom1\n length2 = Prelude.length tempHom2\n maxLength = Prelude.maximum [length1, length2]", "meta": {"hexsha": "abf3dec118b35de729840de6334d3a20ff0e8a26", "size": 9699, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Space.hs", "max_stars_repo_name": "folidota/simplicial_complexes", "max_stars_repo_head_hexsha": "f7cfbb94b9e72ceee02c50b90c3c6af55a9f26d8", "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": "Space.hs", "max_issues_repo_name": "folidota/simplicial_complexes", "max_issues_repo_head_hexsha": "f7cfbb94b9e72ceee02c50b90c3c6af55a9f26d8", "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": "Space.hs", "max_forks_repo_name": "folidota/simplicial_complexes", "max_forks_repo_head_hexsha": "f7cfbb94b9e72ceee02c50b90c3c6af55a9f26d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1850393701, "max_line_length": 99, "alphanum_fraction": 0.6543973606, "num_tokens": 2323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5716925772712697}} {"text": "\n{-# LANGUAGE FlexibleInstances #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Graphics.Rendering.Chart\nimport Data.Colour\nimport Data.Colour.Names\nimport Data.Default.Class\nimport Graphics.Rendering.Chart.Backend.Cairo\nimport Control.Lens\nimport Data.Complex\n\nsetLinesBlue :: PlotLines a b -> PlotLines a b\nsetLinesBlue = plot_lines_style . line_color .~ opaque blue\n\nchart :: Renderable ()\nchart = toRenderable layout\n where\n sumf = plot_lines_values .~ [[ (x,(s x)) | x <- [1.3,(1.31)..10]]]\n $ plot_lines_style . line_color .~ opaque black\n $ plot_lines_title .~ \"S(a)\"\n $ def\n\n tln = plot_lines_values .~ [[ (x,(taylor1 2.0 x)) | x <- [1.3,(1.4)..3.5]]]\n $ plot_lines_style . line_color .~ opaque red\n $ plot_lines_title .~ \"First taylor\"\n $ def\n\n tln2 = plot_lines_values .~ [[ (x,(taylor2 2.0 x)) | x <- [1.3,(1.4)..4.0]]]\n $ plot_lines_style . line_color .~ opaque orange\n $ plot_lines_title .~ \"Second taylor\"\n $ def\n\n tln3 = plot_lines_values .~ [[ (x,(taylor3 2.0 x)) | x <- [1.3,(1.4)..3.2]]]\n $ plot_lines_style . line_color .~ opaque blue\n $ plot_lines_title .~ \"Third taylor\"\n $ def\n\n layout = layout_title .~ \"Amplitude Modulation\"\n $ layout_plots .~ [toPlot sumf, toPlot tln, toPlot tln2, toPlot tln3]\n $ def\n\nrenderChart :: IO (PickFn ())\nrenderChart = renderableToFile def \"example1_big.png\" chart\n\napproxS :: Int -> Double -> Double\napproxS i a = sum $ map (f.fromIntegral) [1..i]\n where f n = n**(-a)\n\nclass Abs a where\n absoluteValue :: a -> Double\n\ninstance Abs Double where\n absoluteValue = abs\n\ninstance Abs (Complex Double) where\n absoluteValue = magnitude\n\nuntilConverged :: (Abs a, Floating a, Num a) => Double -> [a] -> a\nuntilConverged epsilon (x1:xs) = go x1 xs\n where go last (y:ys) =\n if absoluteValue (last - y) < epsilon\n then y\n else go y ys\n\nsumSeries :: (Abs a, Floating a, Num a) => (Int -> a) -> a\nsumSeries seriesGen = untilConverged 0.000001 $ tail $ scanl1 (+) $ map seriesGen [1..]\n\ns :: Double -> Double\ns a = sumSeries $ \\n-> (fromIntegral n)**(-a)\n\nsDerivative :: (Abs a, Floating a, Num a) => Int -> a -> a\nsDerivative d a = sign * (sumSeries $ \\nInt -> \n let n = fromIntegral nInt in\n (fromIntegral nInt)**(-a) * (realToFrac $ log n)^d)\n where sign = if even d then 1 else (-1)\n\nfact :: Int -> Int\nfact 0 = 1\nfact n = n * fact (n - 1)\n\ntaylorCoeffients :: (Fractional a, Num a) => (Int -> a -> a) -> a -> [a]\ntaylorCoeffients f a0 = map g [0..]\n where g n = (f n a0) / fromIntegral (fact n)\n\ntaylor1 :: Double -> Double -> Double\ntaylor1 a0 a = s a0 + (a - a0) * sDerivative 1 a0\n\ntaylor2 :: Double -> Double -> Double\ntaylor2 a0 a = s a0 + (a - a0) * sDerivative 1 a0 + 0.5 * (a - a0)^2 * sDerivative 2 a0\n\ntaylor3 :: Double -> Double -> Double\ntaylor3 a0 a = s a0 + (a - a0) * sDerivative 1 a0 + 0.5 * (a - a0)^2 * sDerivative 2 a0 + (1.0/6.0) * (a - a0)^3 * sDerivative 3 a0\n\nmain :: IO ()\nmain = void $ renderChart\n\n\n", "meta": {"hexsha": "7b07e8e94cdbcaaea503f3e156a3b2cc417091bb", "size": 3113, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "gcharnock/zeta-function", "max_stars_repo_head_hexsha": "44133f1f6553ebcd5b073d3db1dba05bbf74f28d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "gcharnock/zeta-function", "max_issues_repo_head_hexsha": "44133f1f6553ebcd5b073d3db1dba05bbf74f28d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main.hs", "max_forks_repo_name": "gcharnock/zeta-function", "max_forks_repo_head_hexsha": "44133f1f6553ebcd5b073d3db1dba05bbf74f28d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8217821782, "max_line_length": 131, "alphanum_fraction": 0.5987793126, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5716853667014818}} {"text": "module EKF\n ( KF\n , kf_x\n , kf_p\n , kf_t\n\n , makeFilter\n , predict\n , update\n ) where\n\nimport Prelude hiding ((<>))\n\nimport App (Sensor (..))\n\nimport Numeric.LinearAlgebra\n\n\ndata KF = KF\n { kf_x :: Vector Double\n , kf_p :: Matrix Double\n , kf_t :: Word\n } deriving Show\n\n\nmakeFilter (Laser px py t) =\n KF { kf_x = 4 |> [px,\n py,\n 0,\n 0]\n , kf_p = (4><4) [1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1000, 0,\n 0, 0, 0, 1000]\n , kf_t = t }\n\nmakeFilter (Radar rho phi rho' t) =\n KF { kf_x = 4 |> [rho * cos phi,\n rho * sin phi,\n rho' * cos phi,\n rho' * sin phi]\n , kf_p = (4><4) [1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1000, 0,\n 0, 0, 0, 1000]\n , kf_t = t }\n\n\npredict :: Word -> KF -> KF\npredict t kf =\n KF { kf_x = x\n , kf_p = p\n , kf_t = t }\n where\n -- Time inside the filter.\n filterTime =\n kf_t kf\n\n -- Delta-time. Essentially a timestep.\n dt =\n (fromIntegral (t - filterTime)) / 1000000.0\n dt2 = dt ** 2\n dt3 = dt ** 3\n dt4 = dt ** 4\n\n -- Acceleration noise tuning parameters\n ax = 3\n ay = 3\n\n noiseAx = ax ** 2\n noiseAy = ay ** 2\n\n -- State transition matrix\n f = (4><4) [1, 0, dt, 0,\n 0, 1, 0, dt,\n 0, 0, 1, 0,\n 0, 0, 0, 1]\n\n -- Noise covariance matrix\n q = (4><4) [-- Row 1\n noiseAx * 0.25 * dt4, 0, noiseAx * 0.5 * dt3, 0,\n -- Row 2\n 0, noiseAy * 0.25 * dt4, 0, noiseAy * 0.5 * dt3,\n -- Row 3\n noiseAx *0.5 * dt3, 0, noiseAx * dt2, 0,\n -- Row 4\n 0, noiseAy * 0.5 * dt3, 0, noiseAy * dt2]\n\n -- Noise vector\n v = 4 |> [ax * 0.5 * dt2,\n ay * 0.5 * dt2,\n ax * dt,\n ay * dt]\n\n -- Estimated step based on constant velocity (CV) motion model\n x = f #> kf_x kf + v\n p = f <> kf_p kf <> (tr f) + q\n\n\nupdate (Laser px py t) kf =\n KF { kf_x = x'\n , kf_p = p'\n , kf_t = t }\n where\n kf' = predict t kf\n\n -- Measurment transition matricies\n h = (2><4) [1, 0, 0, 0,\n 0, 1, 0, 0]\n r = (2><2) [0.0225, 0.0000,\n 0.0000, 0.0225]\n y = 2 |> [px, py] - (h #> kf_x kf')\n\n -- Kalman Filter Equations\n i = ident 4\n ht = tr h\n s = h <> kf_p kf' <> ht + r\n si = inv s\n k = kf_p kf' <> ht <> si\n\n -- Estimation based on kalman filter gain\n x' = kf_x kf' + (k #> y)\n p' = (i - k <> h) <> kf_p kf'\n\n\nupdate (Radar rho phi rho' t) kf =\n KF { kf_x = x'\n , kf_p = p'\n , kf_t = t }\n where\n kf' = predict t kf\n\n -- Calculate the Jacobian matrix values \n px = kf_x kf' ! 0\n py = kf_x kf' ! 1\n vx = kf_x kf' ! 2\n vy = kf_x kf' ! 3\n\n c1 = px ** 2 + py ** 2\n c2 = sqrt c1\n c3 = c1 * c2\n\n zRho = c2;\n zPhi = (atan2 py px)\n zRho' = (px*vx + py*vy) / zRho\n\n -- Measurment transition matricies\n h = (3><4) [-- Row 1\n px / c2, py / c2, 0, 0,\n -- Row 2\n -py / c1, px / c1, 0, 0,\n -- Row 3\n py*(vx * py - vy * px)/c3,\n px*(vy * px - vx * py)/c3,\n px/c2,\n py/c2]\n r = (3><3) [0.09, 0.0000, 0.00,\n 0.00, 0.0009, 0.00,\n 0.00, 0.0000, 0.09]\n z = 3 |> [rho, phi, rho'] - 3 |> [zRho, zPhi, zRho']\n y = 3 |> [z ! 0, atan2 (sin (z ! 1)) (cos (z ! 1)), z ! 2]\n\n -- Kalman filter equations\n i = ident 4\n ht = tr h\n s = h <> kf_p kf' <> ht + r\n si = inv s\n k = kf_p kf' <> ht <> si\n\n -- Estimation based on kalman filter gain\n x' = kf_x kf' + (k #> y)\n p' = (i - k <> h) <> kf_p kf'\n", "meta": {"hexsha": "1ccc973e6aa92a67477ba97adc43a0f716422dfe", "size": 3936, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/EKF.hs", "max_stars_repo_name": "steven741/CarND-Extended-Kalman-Filter-Project", "max_stars_repo_head_hexsha": "0c42147e99774919b8ab9472b16987666cb26f21", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-03T23:58:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-03T23:58:53.000Z", "max_issues_repo_path": "lib/EKF.hs", "max_issues_repo_name": "steven741/CarND-Extended-Kalman-Filter-Project", "max_issues_repo_head_hexsha": "0c42147e99774919b8ab9472b16987666cb26f21", "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": "lib/EKF.hs", "max_forks_repo_name": "steven741/CarND-Extended-Kalman-Filter-Project", "max_forks_repo_head_hexsha": "0c42147e99774919b8ab9472b16987666cb26f21", "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": 22.7514450867, "max_line_length": 66, "alphanum_fraction": 0.3965955285, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443252, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5716579751792449}} {"text": "import Criterion.Main\nimport Data.Default.Class\nimport qualified Data.Vector.Unboxed as U\nimport Text.Printf\n\nimport Numeric.SpecFunctions\nimport Numeric.Polynomial\nimport Numeric.RootFinding\n\n\n\n-- Uniformly sample logGamma performance between 10^-6 to 10^6\nbenchmarkLogGamma logG =\n [ bench (printf \"%.3g\" x) $ nf logG x\n | x <- [ m * 10**n | n <- [ -8 .. 8 ]\n , m <- [ 10**(i / tics) | i <- [0 .. tics-1] ]\n ]\n ]\n where tics = 3\n{-# INLINE benchmarkLogGamma #-}\n\n\n-- Power of polynomial to be evaluated (In other words length of coefficients vector)\ncoef_size :: [Int]\ncoef_size = [ 1,2,3,4,5,6,7,8,9\n , 10, 30\n , 100, 300\n , 1000, 3000\n , 10000, 30000\n ]\n{-# INLINE coef_size #-}\n\n-- Precalculated coefficients\ncoef_list :: [U.Vector Double]\ncoef_list = [ U.replicate n 1.2 | n <- coef_size]\n{-# NOINLINE coef_list #-}\n\n\n\nmain :: IO ()\nmain = defaultMain\n [ bgroup \"logGamma\" $\n benchmarkLogGamma logGamma\n , bgroup \"logGammaL\" $\n benchmarkLogGamma logGammaL\n , bgroup \"incompleteGamma\" $\n [ bench (show p) $ nf (incompleteGamma p) p\n | p <- [ 0.1\n , 1, 3\n , 10, 30\n , 100, 300\n , 999, 1000\n ]\n ]\n , bgroup \"factorial\"\n [ bench (show n) $ nf factorial n\n | n <- [ 0, 1, 3, 6, 9, 11, 15\n , 20, 30, 40, 50, 60, 70, 80, 90, 100\n ]\n ]\n , bgroup \"incompleteBeta\"\n [ bench (show (p,q,x)) $ nf (incompleteBeta p q) x\n | (p,q,x) <- [ (10, 10, 0.5)\n , (101, 101, 0.5)\n , (1010, 1010, 0.5)\n , (10100, 10100, 0.5)\n , (100100, 100100, 0.5)\n , (1001000, 1001000, 0.5)\n , (10010000,10010000,0.5)\n ]\n ]\n , bgroup \"log1p\"\n [ bench (show x) $ nf log1p x\n | x <- [ -0.9\n , -0.5\n , -0.1\n , 0.1\n , 0.5\n , 1\n , 10\n , 100\n ] :: [Double]\n ]\n , bgroup \"sinc\" $\n bench \"sin\" (nf sin (0.55 :: Double))\n : [ bench (show x) $ nf sinc x\n | x <- [0, 1e-6, 1e-3, 0.5]\n ]\n , bgroup \"poly\"\n $ [ bench (\"vector_\"++show (U.length coefs)) $ nf (\\x -> evaluatePolynomial x coefs) (1 :: Double)\n | coefs <- coef_list ]\n ++ [ bench (\"unpacked_\"++show n) $ nf (\\x -> evaluatePolynomialL x (map fromIntegral [1..n])) (1 :: Double)\n | n <- coef_size ]\n , bgroup \"RootFinding\"\n [ bench \"ridders sin\" $ nf (ridders def (0,pi/2)) (\\x -> sin x - 0.525)\n , bench \"newton sin\" $ nf (newtonRaphson def (0,1.2,pi/2)) (\\x -> (sin x - 0.525,cos x))\n ]\n ]\n", "meta": {"hexsha": "b3df5759f272bd2b7bd6f87a2e81ef8f0b90ab8d", "size": 2763, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "math-functions-bench/bench/bench.hs", "max_stars_repo_name": "Javran/math-functions", "max_stars_repo_head_hexsha": "11af626bc519c3cb340ce10069906b1b0dd7afaf", "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": "math-functions-bench/bench/bench.hs", "max_issues_repo_name": "Javran/math-functions", "max_issues_repo_head_hexsha": "11af626bc519c3cb340ce10069906b1b0dd7afaf", "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": "math-functions-bench/bench/bench.hs", "max_forks_repo_name": "Javran/math-functions", "max_forks_repo_head_hexsha": "11af626bc519c3cb340ce10069906b1b0dd7afaf", "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": 27.9090909091, "max_line_length": 113, "alphanum_fraction": 0.4730365545, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5716579457589553}} {"text": "module DistanceMatrixRank where\n\nimport Data.List as L\nimport Data.Vector as V\nimport Data.Matrix as M\n\nimport Statistics.Sample\n\ndata DistanceMatrix = DistanceMatrix\n {\n distanceMatrix :: Matrix Double,\n origins :: [String],\n destinations :: [String]\n }\n deriving (Show)\n\nrankDestinations :: DistanceMatrix -> [(String, Double)]\nrankDestinations m = L.zip (destinations m) (L.map stdDev $ columns (distanceMatrix m))\n\ncolumns :: Matrix a -> [Vector a]\ncolumns m = L.map (flip M.getCol m) [1..cols]\n where\n cols = M.ncols m\n", "meta": {"hexsha": "61b21ceb6b60501c786b49a277e710d22f8e41bc", "size": 540, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/DistanceMatrixRank.hs", "max_stars_repo_name": "WilliamDo/optimal-prime", "max_stars_repo_head_hexsha": "14601a1da24d6f9b8219563938ca028bc894ee1c", "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/DistanceMatrixRank.hs", "max_issues_repo_name": "WilliamDo/optimal-prime", "max_issues_repo_head_hexsha": "14601a1da24d6f9b8219563938ca028bc894ee1c", "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/DistanceMatrixRank.hs", "max_forks_repo_name": "WilliamDo/optimal-prime", "max_forks_repo_head_hexsha": "14601a1da24d6f9b8219563938ca028bc894ee1c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5, "max_line_length": 87, "alphanum_fraction": 0.7055555556, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5716185630280497}} {"text": "module Main where\n\nimport Criterion\nimport Criterion.Main.Options\nimport Criterion.Types\nimport Data.Complex\nimport Data.Vector\nimport qualified Numeric.FFT as FFT\n\ntstvec :: Int -> Vector (Complex Double)\ntstvec sz = generate sz (\\i -> let ii = fromIntegral i\n in sin (2*pi*ii/1024) + sin (2*pi*ii/511))\n\nmain :: IO ()\nmain = do\n p <- FFT.plan 256\n benchmarkWith (defaultConfig { resamples = 1000 })\n (nf (FFT.fftWith p) (tstvec 256))\n", "meta": {"hexsha": "2f5414b268584c5cfba66246ce8b1409f97a2a2d", "size": 532, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/profile-256.hs", "max_stars_repo_name": "ian-ross/arb-fft", "max_stars_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-06-15T09:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-08T13:14:27.000Z", "max_issues_repo_path": "test/profile-256.hs", "max_issues_repo_name": "ian-ross/arb-fft", "max_issues_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-03-08T20:31:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T20:32:09.000Z", "max_forks_repo_path": "test/profile-256.hs", "max_forks_repo_name": "ian-ross/arb-fft", "max_forks_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-11-25T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-06T22:54:26.000Z", "avg_line_length": 28.0, "max_line_length": 73, "alphanum_fraction": 0.5883458647, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.571392176547386}} {"text": "module Echo where\n\nimport Data.Complex\nimport Linear.Metric\nimport Linear.V3\n\necho :: (Floating a) => (a -> Complex a) -> V3 a -> V3 a -> a -> Complex a\necho signal carrier obj t = signal (t - 2 * d / c)\n where\n d = distance carrier obj\n c = 299792458", "meta": {"hexsha": "99a672ed9449979d3466b9a3cc1259bfff899a9a", "size": 258, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Echo.hs", "max_stars_repo_name": "nihlete/sar-signal", "max_stars_repo_head_hexsha": "08160f3d2dff08dd201b7a05b0194d2ceb83d42b", "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/Echo.hs", "max_issues_repo_name": "nihlete/sar-signal", "max_issues_repo_head_hexsha": "08160f3d2dff08dd201b7a05b0194d2ceb83d42b", "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/Echo.hs", "max_forks_repo_name": "nihlete/sar-signal", "max_forks_repo_head_hexsha": "08160f3d2dff08dd201b7a05b0194d2ceb83d42b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4545454545, "max_line_length": 74, "alphanum_fraction": 0.6434108527, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5713261351340244}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeOperators #-}\nmodule FokkerPlanck.Interpolation where\n\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List as L\nimport Filter.Utils\nimport Types\n\n{-# INLINE radialCubicInterpolation #-}\nradialCubicInterpolation ::\n (R.Source r1 Double, R.Source r2 (Complex Double), Shape sh)\n => R.Array r1 (sh :. Int) Double\n -> Double\n -> R.Array r2 (sh :. Int :. Int) (Complex Double)\n -> R.Array D (sh :. Int :. Int) (Complex Double)\nradialCubicInterpolation radialArr scaleFactor inputArr =\n let (_ :. n) = extent radialArr\n (_ :. nx :. ny) = extent inputArr\n in if scaleFactor == 0\n then error \"radialCubicInterpolation: scaleFactor = 0\"\n else R.traverse2 inputArr radialArr const $ \\fInput fRadial idx@(sh :. i :. j) ->\n let r =\n (sqrt . fromIntegral $\n (i - center nx) ^ 2 + (j - center ny) ^ 2) /\n scaleFactor\n in if r < 0 || r > (fromIntegral $ n - 1) -- out of boundary. When r = 0, log r makes no sense, and therefore the information at r = 0 should not be used to interpoalte 0 < r <= 1.\n then 0\n else if r <= 1 -- linear interpolation\n then fInput idx *\n ((fRadial (sh :. 1) +\n (r - 1) *\n (fRadial (sh :. 2) - fRadial (sh :. 1))) :+\n 0)\n else if r >= (fromIntegral $ n - 2) -- linear interpolation\n then fInput idx *\n ((fRadial (sh :. n - 2) +\n (r - (fromIntegral $ n - 2)) *\n (fRadial (sh :. n - 1) -\n fRadial (sh :. n - 2))) :+\n 0)\n else let x0 = floor r -- cubic interpolation\n p0 = fRadial (sh :. x0 - 1)\n p1 = fRadial (sh :. x0)\n p2 = fRadial (sh :. x0 + 1)\n p3 = fRadial (sh :. x0 + 2)\n x = r - fromIntegral x0\n in fInput idx *\n (((-0.5 * p0 + 1.5 * p1 - 1.5 * p2 +\n 0.5 * p3) *\n x ^ 3 +\n (p0 - 2.5 * p1 + 2 * p2 - 0.5 * p3) *\n x ^ 2 +\n (-0.5 * p0 + 0.5 * p2) * x +\n p1) :+\n 0)\n\n{-# INLINE cubicInterpolation #-}\ncubicInterpolation ::\n (R.Source s Double)\n => R.Array s DIM5 Double\n -> Double\n -> R.Array D DIM4 Double\ncubicInterpolation arr r =\n let (Z :. _ :. _ :. _ :. _ :. n) = extent arr\n in R.traverse arr (\\(sh :. _) -> sh) $ \\f sh@(Z :. tf :. sf :. t0f :. s0f) ->\n if r < 0 || r > (fromIntegral $ n - 1) -- out of boundary. When r = 0, log r makes no sense, and therefore the information at r = 0 should not be used to interpoalte 0 < r <= 1.\n then 0\n else if r <= 1 -- linear interpolation\n then (f (sh :. 1) + (r - 1) * (f (sh :. 2) - f (sh :. 1)))\n else if r >= (fromIntegral $ n - 2) -- linear interpolation\n then (f (sh :. n - 2) +\n (r - (fromIntegral $ n - 2)) *\n (f (sh :. n - 1) - f (sh :. n - 2)))\n else let x0 = floor r -- cubic interpolation\n p0 = f (sh :. x0 - 1)\n p1 = f (sh :. x0)\n p2 = f (sh :. x0 + 1)\n p3 = f (sh :. x0 + 2)\n x = r - fromIntegral x0\n in ((-0.5 * p0 + 1.5 * p1 - 1.5 * p2 + 0.5 * p3) *\n x ^ 3 +\n (p0 - 2.5 * p1 + 2 * p2 - 0.5 * p3) * x ^ 2 +\n (-0.5 * p0 + 0.5 * p2) * x +\n p1)\n", "meta": {"hexsha": "9ec64ed41d72cfa923967e5f0df4d830f9eb0b07", "size": 4567, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FokkerPlanck/Interpolation.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FokkerPlanck/Interpolation.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/FokkerPlanck/Interpolation.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": 52.4942528736, "max_line_length": 196, "alphanum_fraction": 0.3492445807, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5713261320422789}} {"text": "module Examples where\n\nimport Control.Lens hiding (para)\nimport Prelude hiding (id, (.))\nimport System.Random\nimport Control.Monad\n\nimport Numeric.LinearAlgebra.Array\nimport Numeric.LinearAlgebra.Array.Util\n\nimport CategoricDefinitions\nimport Autodiff.GAD\nimport Autodiff.D\nimport Ops\nimport Para\nimport TrainUtils\nimport TensorUtils\nimport OnesLike\n\n{-\nf (p, q) a = (p + q*a)\n-}\nlinRegFn :: (Additive a, Num a) => DType ((a, a), a) a\nlinRegFn = addC . (id `x` mulC) . assocL\n\n-- returns (inp, out) pair we want to learn\nsampleData :: IO (Double, Double)\nsampleData = do\n x <- randomIO :: IO Double\n return (x, 3 + 7*x)\n\nrun :: IO ()\nrun = do\n initialParams <- randomIO :: IO (Double, Double)\n let initialLearner = Learner initialParams (Para linRegFn) sgd\n sampler = zip3 [0..] (repeat sampleData) (repeat sqDiff)\n\n finalLearner <- foldM trainStepWithCost initialLearner (take 10000 sampler)\n putStrLn $ \"Starting network parameters:\\n\" ++ show initialParams\n putStrLn $ \"Final network parameters:\\n\" ++ show (finalLearner ^. p)\n\n return ()\n\n\nsampleDataTensor :: IO (Tensor, Tensor)\nsampleDataTensor = do\n d <- randomTensor [5, 3] \"bf\"\n return (d, 3 + 7 * d)\n\n-- multiply two arrays you get and sum the \"b\" axis\nl :: _ => ParaDType (Tensor, Tensor) Tensor Tensor\nl = Para $ sumAxes \"b\" . linRegFn\n\nrun1 :: IO _\nrun1 = do\n p1 <- randomTensor [3, 2] \"fo\"\n p2 <- randomTensor [2] \"o\"\n let initialLearner = Learner (p1, p2) l sgd\n sampler = zip3 [0..] (repeat sampleDataTensor) (repeat (sumAxes \"b\" . sqDiff))\n\n\n finalLearner <- foldM trainStepWithCost initialLearner (take 1 sampler)\n putStrLn $ \"Starting network parameters:\\n\" ++ arrShow (p1, p2)\n putStrLn $ \"Final network parameters:\\n\" ++ arrShow (finalLearner ^. p)\n\n return finalLearner\n", "meta": {"hexsha": "7fc59ea1b5ed6706dfeb81745ff3c48aac4a97d4", "size": 1807, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Examples.hs", "max_stars_repo_name": "bgavran/Categorical_Deep_Learning", "max_stars_repo_head_hexsha": "a1c3fce3367a5bddf55287ac8393a729ab815ab9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2018-10-09T03:00:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:59:37.000Z", "max_issues_repo_path": "src/Examples.hs", "max_issues_repo_name": "bgavran/Functional_Deep_Learning", "max_issues_repo_head_hexsha": "a1c3fce3367a5bddf55287ac8393a729ab815ab9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Examples.hs", "max_forks_repo_name": "bgavran/Functional_Deep_Learning", "max_forks_repo_head_hexsha": "a1c3fce3367a5bddf55287ac8393a729ab815ab9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-12-19T06:19:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T02:52:48.000Z", "avg_line_length": 26.9701492537, "max_line_length": 86, "alphanum_fraction": 0.6801328168, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5711653870151658}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n-- |\n-- Module : Graphics.Image.Processing.Complex.Internal\n-- Copyright : (c) Alexey Kuleshevich 2016-2018\n-- License : BSD3\n-- Maintainer : Alexey Kuleshevich \n-- Stability : experimental\n-- Portability : non-portable\n--\nmodule Graphics.Image.Processing.Complex.Internal\n (\n -- * Pixel\n Complex(..)\n -- ** Rectangular form\n , (+:)\n , realPart\n , imagPart\n -- ** Polar form\n , mkPolar\n , cis\n , polar\n , magnitude\n , phase\n -- ** Conjugate\n , conjugate\n -- * Image\n -- ** Rectangular form\n , (+:!)\n , realPartI\n , imagPartI\n -- ** Polar form\n , mkPolarI\n , cisI\n , polarI\n , magnitudeI\n , phaseI\n -- ** Conjugate\n , conjugateI\n -- * Re-export\n ) where\n\nimport Control.Applicative\nimport Data.Complex (Complex(..))\nimport qualified Data.Complex as C\nimport Graphics.Image.Internal\nimport Prelude hiding (map, zipWith)\n\n\ninfix 6 +:!, +:\n\n(+:) :: Applicative (Color cs) => Pixel cs e -> Pixel cs e -> Pixel cs (Complex e)\n(+:) = liftA2 (:+)\n{-# INLINE (+:) #-}\n\nrealPart :: Functor (Color cs) => Pixel cs (Complex e) -> Pixel cs e\nrealPart = fmap C.realPart\n{-# INLINE realPart #-}\n\nimagPart :: Functor (Color cs) => Pixel cs (Complex e) -> Pixel cs e\nimagPart = fmap C.imagPart\n{-# INLINE imagPart #-}\n\n\nmkPolar :: (Applicative (Color cs), Floating e) => Pixel cs e -> Pixel cs e -> Pixel cs (Complex e)\nmkPolar = liftA2 C.mkPolar\n{-# INLINE mkPolar #-}\n\n\ncis :: (Functor (Color cs), Floating e) => Pixel cs e -> Pixel cs (Complex e)\ncis = fmap C.cis\n{-# INLINE cis #-}\n\n\npolar :: (Functor (Color cs), RealFloat e) => Pixel cs (Complex e) -> (Pixel cs e, Pixel cs e)\npolar z = (magnitude z, phase z)\n{-# INLINE polar #-}\n\nmagnitude :: (Functor (Color cs), RealFloat e) => Pixel cs (Complex e) -> Pixel cs e\nmagnitude = fmap C.magnitude\n{-# INLINE magnitude #-}\n\nphase :: (Functor (Color cs), RealFloat e) => Pixel cs (Complex e) -> Pixel cs e\nphase = fmap C.phase\n{-# INLINE phase #-}\n\nconjugate :: (Functor (Color cs), Num e) => Pixel cs (Complex e) -> Pixel cs (Complex e)\nconjugate = fmap C.conjugate\n{-# INLINE conjugate #-}\n\n\n\n-- | Construct a complex image from two images representing real and imaginary parts.\n--\n-- >>> frog <- readImageRGB \"images/frog.jpg\"\n-- >>> frog !+! 0\n-- \n-- >>> frog !+! frog\n-- \n--\n(+:!) :: (ColorModel cs e, ColorModel cs (Complex e)) =>\n Image cs e -> Image cs e -> Image cs (Complex e)\n(+:!) = zipWith (+:)\n{-# INLINE (+:!) #-}\n\n-- | Extracts the real part of a complex image.\nrealPartI :: (RealFloat e, ColorModel cs e, ColorModel cs (Complex e)) =>\n Image cs (Complex e) -> Image cs e\nrealPartI = map realPart\n{-# INLINE realPartI #-}\n\n-- | Extracts the imaginary part of a complex image.\nimagPartI :: (RealFloat e, ColorModel cs e, ColorModel cs (Complex e)) =>\n Image cs (Complex e) -> Image cs e\nimagPartI = map imagPart\n{-# INLINE imagPartI #-}\n\n-- | Form a complex image from polar components of magnitude and phase.\nmkPolarI :: (RealFloat e, ColorModel cs e, ColorModel cs (Complex e)) =>\n Image cs e -> Image cs e -> Image cs (Complex e)\nmkPolarI = zipWith mkPolar\n{-# INLINE mkPolarI #-}\n\n-- | @'cisI' t@ is a complex image with magnitude 1 and phase t (modulo @2*'pi'@).\ncisI :: (RealFloat e, ColorModel cs e, ColorModel cs (Complex e)) =>\n Image cs e -> Image cs (Complex e)\ncisI = map cis\n{-# INLINE cisI #-}\n\n-- | The function @'polar''@ takes a complex image and returns a (magnitude, phase)\n-- pair of images in canonical form: the magnitude is nonnegative, and the phase\n-- in the range @(-'pi', 'pi']@; if the magnitude is zero, then so is the phase.\npolarI :: (RealFloat e, ColorModel cs e, ColorModel cs (Complex e)) =>\n Image cs (Complex e) -> (Image cs e, Image cs e)\npolarI !zImg = (magnitudeI zImg, phaseI zImg)\n{-# INLINE polarI #-}\n\n-- | The nonnegative magnitude of a complex image.\nmagnitudeI :: (RealFloat e, ColorModel cs e, ColorModel cs (Complex e)) =>\n Image cs (Complex e) -> Image cs e\nmagnitudeI = map magnitude\n{-# INLINE magnitudeI #-}\n\n-- | The phase of a complex image, in the range @(-'pi', 'pi']@. If the\n-- magnitude is zero, then so is the phase.\nphaseI :: (RealFloat e, ColorModel cs e, ColorModel cs (Complex e)) =>\n Image cs (Complex e) -> Image cs e\nphaseI = map phase\n{-# INLINE phaseI #-}\n\n-- | The conjugate of a complex image.\nconjugateI :: (RealFloat e, ColorModel cs e, ColorModel cs (Complex e)) =>\n Image cs (Complex e) -> Image cs (Complex e)\nconjugateI = map conjugate\n{-# INLINE conjugateI #-}\n", "meta": {"hexsha": "3b4115f045b3d47031378dc9baac3b49f9b32569", "size": 4722, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Graphics/Image/Processing/Complex/Internal.hs", "max_stars_repo_name": "HanStolpo/hip", "max_stars_repo_head_hexsha": "7f2bd193e07070637eb3935d6c6513e0c5499c65", "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/Graphics/Image/Processing/Complex/Internal.hs", "max_issues_repo_name": "HanStolpo/hip", "max_issues_repo_head_hexsha": "7f2bd193e07070637eb3935d6c6513e0c5499c65", "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/Graphics/Image/Processing/Complex/Internal.hs", "max_forks_repo_name": "HanStolpo/hip", "max_forks_repo_head_hexsha": "7f2bd193e07070637eb3935d6c6513e0c5499c65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.076433121, "max_line_length": 99, "alphanum_fraction": 0.6376535366, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.57093974016416}} {"text": "{-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# OPTIONS_GHC -Wno-orphans #-}\nmodule Utils.Types.Num\n ( NumType(..)\n )\nwhere\n\nimport RIO hiding ( toRational )\nimport Data.Complex ( Complex(..) )\nimport Data.Ratio ( denominator\n , numerator\n , (%)\n )\n\ndata NumType = Complex (Complex Double)\n | Real Double\n | Rational Rational\n | Integer Integer\n deriving(Eq, Ord, Data)\n\ninstance Ord a => Ord (Complex a) where\n compare (ar :+ ai) (br :+ bi) = case compare ar br of\n EQ -> compare ai bi\n other -> other\n\n\ninstance Show NumType where\n show (Integer num ) = show num\n show (Rational num) = show (numerator num) <> \"/\" <> show (denominator num)\n show (Real num ) = show num\n show (Complex (re :+ im)) = show re <> \"+\" <> show im <> \"i\"\n\n\ntoComplex :: NumType -> NumType\ntoComplex ( Integer num) = Complex $ fromInteger num :+ 0\ntoComplex num@(Rational _ ) = toComplex $ toReal num\ntoComplex ( Real num) = Complex $ num :+ 0\ntoComplex num@(Complex _ ) = num\n\ntoReal :: NumType -> NumType\ntoReal (Integer num) = Real $ fromInteger num\ntoReal (Rational num) =\n Real $ fromInteger (numerator num) / fromInteger (denominator num)\ntoReal num@(Real _) = num\ntoReal _ = undefined\n\ntoRational :: NumType -> NumType\ntoRational ( Integer num) = Rational $ fromInteger num\ntoRational num@(Rational _ ) = num\ntoRational _ = undefined\n\ninstance Num NumType where\n (Integer a) + (Integer b) = Integer $ a + b\n a + b = numTypeOp (+) a b\n (Integer a) * (Integer b) = Integer $ a * b\n a * b = numTypeOp (*) a b\n abs = numTypeFun abs\n signum = numTypeFun signum\n negate = numTypeFun negate\n fromInteger = Integer\n\ninstance Fractional NumType where\n (Integer a) / (Integer b) = Rational $ a % b\n a / b = numTypeOp (/) a b\n fromRational = Rational\n\ninstance Floating NumType where\n pi = Real pi\n exp = realOp exp\n log = realOp log\n sin = realOp sin\n cos = realOp cos\n asin = realOp asin\n acos = realOp acos\n atan = realOp atan\n sinh = realOp sinh\n cosh = realOp cosh\n asinh = realOp asinh\n acosh = realOp acosh\n atanh = realOp atanh\n sqrt = realOp sqrt\n\nrealOp :: (Double -> Double) -> NumType -> NumType\nrealOp op (Real a) = Real $ op a\nrealOp op a = realOp op (toReal a)\n\nnumTypeOp\n :: (forall a . (Num a, Fractional a) => a -> a -> a)\n -> NumType\n -> NumType\n -> NumType\nnumTypeOp op ( Real a) (Real b) = Real $ op a b\nnumTypeOp op ( Rational a) (Rational b) = Rational $ op a b\nnumTypeOp op ( Complex a) (Complex b) = Complex $ op a b\nnumTypeOp op a@(Complex _) b = numTypeOp op a (toComplex b)\nnumTypeOp op a b@(Complex _) = numTypeOp op (toComplex a) b\nnumTypeOp op a@(Real _) b = numTypeOp op a (toReal b)\nnumTypeOp op a b@(Real _) = numTypeOp op (toReal a) b\nnumTypeOp op a@(Rational _) b = numTypeOp op a (toRational b)\nnumTypeOp op a b@(Rational _) = numTypeOp op (toRational a) b\nnumTypeOp _ _ _ = undefined\n\nnumTypeFun :: (forall a . Num a => a -> a) -> NumType -> NumType\nnumTypeFun fun (Integer a) = Integer $ fun a\nnumTypeFun fun (Real a) = Real $ fun a\nnumTypeFun fun (Rational a) = Rational $ fun a\nnumTypeFun fun (Complex a) = Complex $ fun a\n\n", "meta": {"hexsha": "cfa3a4969fbf4a200c640622490af1eba37c535a", "size": 3725, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Utils/Types/Num.hs", "max_stars_repo_name": "PKopel/Scheme48", "max_stars_repo_head_hexsha": "fd3578c1ba9c684a4ec76bedc425386e010e792d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Types/Num.hs", "max_issues_repo_name": "PKopel/Scheme48", "max_issues_repo_head_hexsha": "fd3578c1ba9c684a4ec76bedc425386e010e792d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils/Types/Num.hs", "max_forks_repo_name": "PKopel/Scheme48", "max_forks_repo_head_hexsha": "fd3578c1ba9c684a4ec76bedc425386e010e792d", "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.5585585586, "max_line_length": 77, "alphanum_fraction": 0.5608053691, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5708714971950152}} {"text": "module State where\n\nimport Protolude\n\nimport Data.Complex (Complex (..))\nimport qualified Data.Vector as V\n\nimport Instruction (Instruction)\n\ndata MachineState =\n MachineState\n { quantumState :: QuantumState\n , instructions :: [Instruction]\n , pc :: Integer\n , running :: Bool\n }\n\ntype QuantumState = V.Vector (Complex Double)\n\n-- Construct a quantum state given number of qubits\nmakeQuantumState :: Int -> QuantumState\nmakeQuantumState len =\n V.generate\n (2 ^ len)\n (\\i ->\n if i == 0\n then (1 :+ 0)\n else (0 :+ 0))\n", "meta": {"hexsha": "e50f48a2e7a83a8ff4ee466af9e6195d025581f2", "size": 608, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/State.hs", "max_stars_repo_name": "colescott/quantum-interpreter", "max_stars_repo_head_hexsha": "e67bfe3a57080f84333b172c25ae8ade3c7a9e40", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-04T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T14:06:33.000Z", "max_issues_repo_path": "src/State.hs", "max_issues_repo_name": "colescott/quantum-interpreter", "max_issues_repo_head_hexsha": "e67bfe3a57080f84333b172c25ae8ade3c7a9e40", "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/State.hs", "max_forks_repo_name": "colescott/quantum-interpreter", "max_forks_repo_head_hexsha": "e67bfe3a57080f84333b172c25ae8ade3c7a9e40", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9655172414, "max_line_length": 51, "alphanum_fraction": 0.5970394737, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.5706115979388705}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Learning\n ( ols\n , gls\n , kmeans\n , Centroids\n , Clusters\n , Clustering\n , Initializer\n , average\n , invertMap\n ) where\n\nimport Debug.Trace\nimport Data.Set\nimport Data.Map.Strict\nimport Numeric.LinearAlgebra hiding ((!))\n\n--covariance :: (Field n, Ord n, Num (Vector n))\n-- => Set (Vector n)\n-- -> Matrix n\n\n--covariance set = exxt - uut where\n-- exxt = mean $ Prelude.map (\\a -> asColumn a <> asRow a) (Data.Set.elems set)\n-- uut = asColumn mu <> asRow mu\n-- mu = average set\n\n-- | Ordinary least squares\nols :: (Field n, Monoid (Matrix n))\n => Matrix n\n -> Vector n\n -> Vector n\n\nols x y = head $ toColumns $ optimiseMult [l', tr l', tr x, asColumn y] where\n xTx = mTm x\n l = chol xTx\n l' = inv l\n\n-- | Generalized least squares\ngls :: (Eq n, Num (Vector n), Monoid (Matrix n), Field n) \n => Matrix n \n -> Matrix n \n -> Vector n \n -> Vector n\n\ngls c x y = t where\n x' = tr x\n ic = inv c\n r = inv (optimiseMult [x', ic, x])\n s = optimiseMult [r, x, ic]\n t = s #> y\n\ntype Centroids n = Set (Vector n)\n\ntype Clusters n = Map (Vector n) (Set (Vector n))\n\ntype Clustering n = (Centroids n, Clusters n)\n\ntype Initializer m n = Int -> Set (Vector n) -> m (Centroids n)\n\n-- | KMeans clustering algorithm\nkmeans :: (Functor m, Container Vector n, Ord n, Num (Vector n), Normed (Vector n), Field n)\n => Initializer m n\n -> Int\n -> Set (Vector n)\n -> m (Clustering n)\n\n-- KMeans runs by first getting an original clustering, then reclustering\n-- until a fixed point is reached.\nkmeans init k set = (untilEqual fst (recluster k) . (\\centroids -> (centroids, reassign centroids set))) <$> init k set\n\nuntilEqual :: Eq a => (e -> a) -> (e -> e) -> e -> e\nuntilEqual g f e = if g e' == g e then e else untilEqual g f e' where\n e' = f e\n\n-- Reclustering means taking each cluster, computing a new centroid based on\n-- the contents, and then reassigning each vector to the cluster which has a\n-- centroid closest to it.\nrecluster :: (Container Vector n, Ord n, Fractional n, Normed (Vector n), Num (Vector n), Field n)\n => Int \n -> Clustering n \n -> Clustering n\nrecluster k (centroids, clusters) = (centroids', reassign centroids' (Data.Set.unions $ Data.Map.Strict.elems clusters)) where\n centroids' = Data.Set.map (\\centroid -> average (clusters ! centroid)) centroids\n\naverage :: (Container c n, Fractional n, Ord n, Num (c n), Linear n c)\n => Set (c n) -> c n\n\naverage set = scale (1 / (fromInteger . toInteger $ Data.Set.size set)) $ Data.Set.foldr (+) one set' where\n (one, set') = Data.Set.deleteFindMin set\n\n-- Reassignment goes like this: given a set of vectors and a set of centroids,\n-- return a map from centroid to sets of vectors which have been found to be within this\n-- centroid.\nreassign :: (Normed (Vector n), Ord n, Eq n, Num (Vector n), Field n)\n => Set (Vector n)\n -> Set (Vector n)\n -> Clusters n\n\nreassign centroids points = invertMap $ fromSet (getClosest centroids) points\n\n-- | Given a map from x to y, returns a map from y to the preimage of y in the\n-- original map\ninvertMap :: (Ord y, Ord x) => Map x y -> Map y (Set x)\ninvertMap map = st where\n st = fromListWith Data.Set.union [ (e, Data.Set.singleton k) \n | k <- ks, e <- es, map ! k == e ]\n es = Data.Map.Strict.elems map\n ks = keys map\n\ngetClosest :: (Normed (Vector n), Num (Vector n), Field n, Eq n) => Set (Vector n) -> Vector n -> Vector n\ngetClosest points point = if Data.Set.null points then error \"getClosest\" else fst $ Data.Set.foldr \n (\\candidate (c, d) -> let d' = norm_2 (candidate - point)\n in if d > d' then (candidate, d') else (c, d))\n (candidate, norm_2 (candidate - point))\n points' where\n (candidate, points') = Data.Set.deleteFindMin points\n", "meta": {"hexsha": "dc4d1c2b31f9810897c0ac3df8fc2bbf1e480b08", "size": 3919, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Learning.hs", "max_stars_repo_name": "SamuelSchlesinger/learning", "max_stars_repo_head_hexsha": "c3f2fd2ed6a3699b836338c35814ef9a6cd1e676", "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/Learning.hs", "max_issues_repo_name": "SamuelSchlesinger/learning", "max_issues_repo_head_hexsha": "c3f2fd2ed6a3699b836338c35814ef9a6cd1e676", "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/Learning.hs", "max_forks_repo_name": "SamuelSchlesinger/learning", "max_forks_repo_head_hexsha": "c3f2fd2ed6a3699b836338c35814ef9a6cd1e676", "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.9327731092, "max_line_length": 126, "alphanum_fraction": 0.6187803011, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5705787773995545}} {"text": "{-# LANGUAGE BangPatterns #-}\nmodule FourierSeriesOfPinwheels where\n\nimport Control.Monad.Parallel as MP\nimport Data.Array.IArray as IA\nimport Data.Array.Repa as R\nimport Data.Array.Repa.IO.Binary\nimport Data.Array.Repa.Repr.ForeignPtr\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Storable as VS\nimport Data.Vector.Unboxed as VU\nimport FokkerPlanck.GreensFunction\nimport FokkerPlanck.Histogram\nimport Image.IO\nimport Pinwheel.Base\nimport Pinwheel.FourierSeries2D\nimport STC\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Text.Printf\nimport Utils.Parallel\nimport Utils.Time\nimport FourierMethod.FourierSeries2D\n\nmain = do\n args@(gpuIDsStr:lenStr:deltaStr:inverseDeltaStr:numR2FreqsStr:periodStr:phiFreqsStr:rhoFreqsStr:thetaFreqsStr:scaleFreqsStr:coefFilePath:stdStr:batchSizePolarFreqsStr:batchSizeR2FreqsStr:batchSizeR2Str:numThreadStr:_) <-\n getArgs\n let gpuIDs = read gpuIDsStr :: [Int]\n len = read lenStr :: Double\n delta = read deltaStr :: Double\n inverseDelta = read inverseDeltaStr :: Double\n numR2Freqs = read numR2FreqsStr :: Int\n period = read periodStr :: Double\n phiFreq = read phiFreqsStr :: Int\n phiFreqs = L.map fromIntegral [-phiFreq .. phiFreq]\n rhoFreq = read rhoFreqsStr :: Int\n rhoFreqs = L.map fromIntegral [-rhoFreq .. rhoFreq]\n thetaFreq = read thetaFreqsStr :: Int\n thetaFreqs = L.map fromIntegral [-thetaFreq .. thetaFreq]\n scaleFreq = read scaleFreqsStr :: Int\n scaleFreqs = L.map fromIntegral [-scaleFreq .. scaleFreq]\n numThread = read numThreadStr :: Int\n folderPath = \"output/test/FourierSeriesOfPinwheels\"\n std = read stdStr :: Double\n batchSizePolarFreqs = read batchSizePolarFreqsStr :: Int\n batchSizeR2Freqs = read batchSizeR2FreqsStr :: Int\n batchSizeR2 = read batchSizeR2Str :: Int\n removePathForcibly (folderPath \"Recons\")\n createDirectoryIfMissing True folderPath\n let !numAngularFreqs = 2 * (phiFreq + thetaFreq) + 1\n !angularFreqsCenter = div numAngularFreqs 2\n !numRadialFreqs = 2 * (rhoFreq + scaleFreq) + 1\n !numPoints' = round $ len / delta :: Int\n !numPoints =\n if odd numPoints'\n then numPoints'\n else numPoints' + 1\n coefficients <-\n computeFourierCoefficients\n gpuIDs\n numR2Freqs\n numPoints\n period\n delta\n batchSizeR2Freqs\n batchSizePolarFreqs\n numAngularFreqs\n numRadialFreqs\n writeArrayToStorableFile coefFilePath coefficients\n coefficientsArr' <-\n readArrayFromStorableFile\n coefFilePath\n (Z :. numRadialFreqs :. numAngularFreqs :. numR2Freqs :. numR2Freqs) :: IO (R.Array F DIM4 (Complex Double))\n coefficientsArr <- applyGaussian 1 std coefficientsArr'\n let coefficientsVecs =\n L.map\n (\\(!rf, !af) ->\n VU.convert . toUnboxed . computeS . R.slice coefficientsArr $\n (Z :. rf :. af :. All :. All))\n [ (rf, af)\n | rf <- [0 .. numRadialFreqs - 1]\n , af <- [0 .. numAngularFreqs - 1]\n ]\n createDirectoryIfMissing True (folderPath \"Coefficients\")\n MP.mapM_\n (\\(rf, af) ->\n plotImageRepaComplex\n (folderPath \"Coefficients\" \n printf\n \"Coef(%d,%d).png\"\n (rf - div numRadialFreqs 2)\n (af - div numAngularFreqs 2)) .\n ImageRepa 8 .\n computeS . extend (Z :. (1 :: Int) :. All :. All) . R.slice coefficients $\n (Z :. rf :. af :. All :. All)) .\n L.take 10 $\n [ (rf, af)\n | rf <- [0 .. numRadialFreqs - 1]\n , af <- [0 .. numAngularFreqs - 1]\n ]\n recons <-\n computeFourierSeries\n gpuIDs\n numR2Freqs\n (round len)\n period\n inverseDelta\n batchSizePolarFreqs\n batchSizeR2\n numAngularFreqs\n numRadialFreqs\n coefficientsVecs\n createDirectoryIfMissing True (folderPath \"Recons\")\n MP.mapM_\n (\\(!rf, !af) ->\n plotImageRepaComplex\n (folderPath \"Recons\" \n printf\n \"Recon(%d,%d).png\"\n (rf - div numRadialFreqs 2)\n (af - div numAngularFreqs 2)) .\n ImageRepa 8 .\n computeS . extend (Z :. (1 :: Int) :. All :. All) . R.slice recons $\n (Z :. rf :. af :. All :. All)) .\n L.take 10 $\n [ (rf, af)\n | rf <- [0 .. numRadialFreqs - 1]\n , af <- [0 .. numAngularFreqs - 1]\n ]\n", "meta": {"hexsha": "f000624592318fe605e042860ad7b41e3f62ede9", "size": 4691, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/FourierSeriesOfPinwheels/FourierSeriesOfPinwheels.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/FourierSeriesOfPinwheels/FourierSeriesOfPinwheels.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/FourierSeriesOfPinwheels/FourierSeriesOfPinwheels.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 35.5378787879, "max_line_length": 222, "alphanum_fraction": 0.6009379663, "num_tokens": 1329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5705787735294521}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-|\nModule : Grenade.Core.WeightInitialization\nDescription : Defines the Weight Initialization methods of Grenade.\nCopyright : (c) Manuel Schneckenreither, 2018\nLicense : BSD2\nStability : experimental\n\nThis module defines the weight initialization methods.\n\n-}\n\n\nmodule Grenade.Core.WeightInitialization\n ( getRandomVector\n , getRandomVectorV\n , getRandomMatrix\n , getRandomList\n , WeightInitMethod (..)\n ) where\n\nimport Control.DeepSeq\nimport Control.Monad\nimport Control.Monad.Primitive (PrimBase, PrimState)\nimport Data.Proxy\nimport Data.Serialize\nimport Data.Singletons.TypeLits\nimport qualified Data.Vector.Storable as V\nimport GHC.Generics (Generic)\nimport GHC.TypeLits hiding (natVal)\nimport Numeric.LinearAlgebra.Static\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Random.MWC\nimport System.Random.MWC.Distributions\n\nimport Grenade.Types\nimport Grenade.Utils.Vector\n\nimport Debug.Trace\n\n-- ^ Weight initialization method.\ndata WeightInitMethod\n = UniformInit -- ^ W_l,i ~ U(-1/sqrt(n_l),1/sqrt(n_l)) where n_l is the number of nodes in layer l\n | Xavier -- ^ W_l,i ~ U(-sqrt (6/n_l+n_{l+1}),sqrt (6/n_l+n_{l+1})) where n_l is the number of nodes in layer l\n | HeEtAl -- ^ W_l,i ~ N(0,sqrt(2/n_l)) where n_l is the number of nodes in layer l\n deriving (Show, Eq, Ord, Enum, Bounded, NFData, Serialize, Generic)\n\ntype LayerInput = Integer\ntype LayerOutput = Integer\n\ngetRandomList ::\n (PrimBase m)\n => LayerInput\n -> LayerOutput\n -> Int -- ^ Length of list\n -> WeightInitMethod\n -> Gen (PrimState m)\n -> m [RealNum]\ngetRandomList i o n method gen = do\n let unifRands = replicateM n (uniformR (-1, 1) gen)\n gaussRands = replicateM n (realToFrac <$> standard gen)\n case method of\n UniformInit -> map (1 / sqrt (fromIntegral i) *) <$> unifRands\n Xavier -> map ((sqrt 6 / sqrt (fromIntegral i + fromIntegral o)) *) <$> unifRands\n HeEtAl -> map (sqrt (2 / fromIntegral i) *) <$> gaussRands\n\n\ngetRandomVectorV ::\n (PrimBase m)\n => LayerInput\n -> LayerOutput\n -> Int -- ^ Length of list\n -> WeightInitMethod\n -> Gen (PrimState m)\n -> m (V.Vector RealNum)\ngetRandomVectorV i o n method gen = do\n let mkVec :: [RealNum] -> V.Vector RealNum\n mkVec xs = V.imap (\\idx (_ :: RealNum) -> xs' V.! idx) (createVectorUnsafe n)\n where\n xs' = V.fromList xs -- convert first to vector, otherwise this function is quadratic!\n let unifRands = replicateM n (uniformR (-1, 1) gen)\n gaussRands = replicateM n (realToFrac <$> standard gen)\n case method of\n UniformInit -> mkVec . map (1 / sqrt (fromIntegral i) *) <$> unifRands\n Xavier -> mkVec . map ((sqrt 6 / sqrt (fromIntegral i + fromIntegral o)) *) <$> unifRands\n HeEtAl -> mkVec . map (sqrt (2 / fromIntegral i) *) <$> gaussRands\n\n-- test :: IO [Double]\n-- test = withSystemRandom $ asGenIO $ \\gen -> replicateM 10000 (uniformR (-1, 1) gen)\n\n-- test :: Int -> IO (V.Vector Double)\n-- test n = withSystemRandom $ asGenIO $ getRandomVectorV 10 100 n UniformInit\n\n\n-- | Get a random vector initialized according to the specified method.\ngetRandomVector ::\n forall m n. (PrimBase m, KnownNat n)\n => Integer\n -> Integer\n -> WeightInitMethod\n -> Gen (PrimState m)\n -> m (R n)\ngetRandomVector i o method gen = do\n let unifRands = vector <$> replicateM n (uniformR (-1, 1) gen)\n gaussRands = vector <$> replicateM n (realToFrac <$> standard gen)\n case method of\n UniformInit -> ((1 / sqrt (fromIntegral i)) *) <$> unifRands\n Xavier -> ((sqrt 6 / sqrt (fromIntegral i + fromIntegral o)) *) <$> unifRands\n HeEtAl -> (sqrt (2 / fromIntegral i) *) <$> gaussRands\n where\n n = fromIntegral $ natVal (Proxy :: Proxy n)\n\n\n-- | Get a matrix with weights initialized according to the specified method.\ngetRandomMatrix ::\n forall m r n. (PrimBase m, KnownNat r, KnownNat n, KnownNat (n * r))\n => Integer\n -> Integer\n -> WeightInitMethod\n -> Gen (PrimState m)\n -> m (L r n)\ngetRandomMatrix i o method gen = do\n let unifRands = matrix <$> replicateM nr (uniformR (-1, 1) gen)\n gaussRands = matrix <$> replicateM nr (realToFrac <$> standard gen)\n case method of\n UniformInit -> ((1 / sqrt (fromIntegral i)) *) <$> unifRands\n Xavier -> ((sqrt 6 / sqrt (fromIntegral i + fromIntegral o)) *) <$> unifRands\n HeEtAl -> (sqrt (2 / fromIntegral i) *) <$> gaussRands\n where\n nr = fromIntegral $ natVal (Proxy :: Proxy (n * r))\n", "meta": {"hexsha": "c2986fd95234b4c7a28dd475357819c87a8a51e3", "size": 5127, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Core/WeightInitialization.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Core/WeightInitialization.hs", "max_issues_repo_name": "schnecki/grenade", "max_issues_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Core/WeightInitialization.hs", "max_forks_repo_name": "schnecki/grenade", "max_forks_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-02T01:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:08:47.000Z", "avg_line_length": 36.3617021277, "max_line_length": 118, "alphanum_fraction": 0.6210259411, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5705693818457915}} {"text": "{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n\n{-# LANGUAGE DataKinds #-}\n\nmodule HaddockExample ( main ) where\n\nimport Numeric.LinearAlgebra.Static\n ( R, vector, Sym,\n headTail, matrix, sym\n )\nimport Data.Random.Distribution.MultiNormal\nimport Numeric.Kalman\nimport Numeric.LinearAlgebra.Static\n\nimport Graphics.Rendering.Chart hiding ( Vector )\nimport Graphics.Rendering.Chart.Backend.Diagrams\nimport Diagrams.Backend.Cairo.CmdLine\nimport Diagrams.Prelude hiding ( render, Renderable, sample )\nimport Diagrams.Backend.CmdLine\n\nimport Data.Csv\nimport System.IO hiding ( hGetContents )\nimport Data.ByteString.Lazy ( hGetContents )\nimport qualified Data.Vector as V\n\ndeltaT, g :: Double\ndeltaT = 0.01\ng = 9.81\n\nbigQ :: Sym 2\nbigQ = sym $ matrix bigQl\n\nqc1 :: Double\nqc1 = 0.01\n\nbigQl :: [Double]\nbigQl = [ qc1 * deltaT^3 / 3, qc1 * deltaT^2 / 2,\n qc1 * deltaT^2 / 2, qc1 * deltaT\n ]\n\nbigR :: Sym 1\nbigR = sym $ matrix [0.1]\n\nobserve :: R 2 -> R 1\nobserve a = vector [sin x] where x = fst $ headTail a\n\nlinearizedObserve :: R 2 -> L 1 2\nlinearizedObserve a = matrix [cos x, 0.0] where x = fst $ headTail a\n\nstateUpdate :: R 2 -> R 2\nstateUpdate u = vector [x1 + x2 * deltaT, x2 - g * (sin x1) * deltaT]\n where\n (x1, w) = headTail u\n (x2, _) = headTail w\n\nlinearizedStateUpdate :: R 2 -> Sq 2\nlinearizedStateUpdate u = matrix [1.0, deltaT,\n -g * (cos x1) * deltaT, 1.0]\n where\n (x1, _) = headTail u\n\nsingleEKF :: MultiNormal (R 2) -> R 1 -> MultiNormal (R 2)\nsingleEKF = runEKF (const observe) (const linearizedObserve) (const bigR)\n (const stateUpdate) (const linearizedStateUpdate) (const bigQ)\n undefined\n\nsingleUKF :: MultiNormal (R 2) -> R 1 -> MultiNormal (R 2)\nsingleUKF = runUKF (const observe) (const bigR) (const stateUpdate) (const bigQ)\n undefined\n\ninitialDist :: MultiNormal (R 2)\ninitialDist = MultiNormal (vector [1.6, 0.0])\n (sym $ matrix [0.1, 0.0,\n 0.0, 0.1])\n\nmultiEKF :: [\u211d] -> [MultiNormal (R 2)]\nmultiEKF obs = scanl singleEKF initialDist (map (vector . pure) obs)\n\nmultiUKF :: [\u211d] -> [MultiNormal (R 2)]\nmultiUKF obs = scanl singleUKF initialDist (map (vector . pure) obs)\n\ndenv :: IO (DEnv Double)\ndenv = defaultEnv vectorAlignmentFns 600 500\n\ndiagEstimated :: String ->\n [(Double, Double)] ->\n [(Double, Double)] ->\n [(Double, Double)] ->\n IO (Diagram Cairo)\ndiagEstimated t l xs es = do\n env <- denv\n return $ fst $ runBackend env (render (chartEstimated t l xs es) (600, 500))\n\nchartEstimated :: String ->\n [(Double, Double)] ->\n [(Double, Double)] ->\n [(Double, Double)] ->\n Renderable ()\nchartEstimated title acts obs ests = toRenderable layout\n where\n\n actuals = plot_lines_values .~ [acts]\n $ plot_lines_style . line_color .~ opaque red\n $ plot_lines_title .~ \"Actual Trajectory\"\n $ plot_lines_style . line_width .~ 1.0\n $ def\n\n measurements = plot_points_values .~ obs\n $ plot_points_style . point_color .~ opaque blue\n $ plot_points_title .~ \"Measurements\"\n $ def\n\n estimas = plot_lines_values .~ [ests]\n $ plot_lines_style . line_color .~ opaque black\n $ plot_lines_title .~ \"Inferred Trajectory\"\n $ plot_lines_style . line_width .~ 1.0\n $ def\n\n layout = layout_title .~ title\n $ layout_plots .~ [toPlot actuals, toPlot measurements, toPlot estimas]\n $ layout_y_axis . laxis_title .~ \"Angle / Horizontal Displacement\"\n $ layout_y_axis . laxis_override .~ axisGridHide\n $ layout_x_axis . laxis_title .~ \"Time\"\n $ layout_x_axis . laxis_override .~ axisGridHide\n $ def\n\ndisplayHeader :: FilePath -> Diagram B -> IO ()\ndisplayHeader fn =\n mainRender ( DiagramOpts (Just 900) (Just 700) fn\n , DiagramLoopOpts False Nothing 0\n )\n\nmain :: IO ()\nmain = do\n h <- openFile \"matlabRNGs.csv\" ReadMode\n cs <- hGetContents h\n let df = (decode NoHeader cs) :: Either String (V.Vector (Double, Double))\n case df of\n Left _ -> error \"Whatever\"\n Right generatedSamples -> do\n let xs = take 500 (multiEKF $ V.toList $ V.map fst generatedSamples)\n let mus = map (fst . headTail . mu) xs\n let obs = V.toList $ V.map fst generatedSamples\n let acts = V.toList $ V.map snd generatedSamples\n de1 <- diagEstimated \"Fitted Pendulum\"\n (zip [0,1..] acts)\n (zip [0,1..] obs)\n (zip [0,1..] mus)\n displayHeader \"diagrams/PendulumFittedEkf.png\" de1\n let ys = take 500 (multiUKF $ V.toList $ V.map fst generatedSamples)\n let nus = map (fst . headTail . mu) ys\n de2 <- diagEstimated \"Fitted Pendulum\"\n (zip [0,1..] acts)\n (zip [0,1..] obs)\n (zip [0,1..] nus)\n displayHeader \"diagrams/PendulumFittedUkf.png\" de2\n", "meta": {"hexsha": "675f16ff4fc808bfa1519e82c0aa5dfe3ed09a14", "size": 5222, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/HaddockExample.hs", "max_stars_repo_name": "idontgetoutmuch/Kalman", "max_stars_repo_head_hexsha": "619d57e980d53c43bb1675efb17c73127fa924d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2015-03-13T16:16:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T00:33:51.000Z", "max_issues_repo_path": "test/HaddockExample.hs", "max_issues_repo_name": "f-o-a-m/Kalman", "max_issues_repo_head_hexsha": "619d57e980d53c43bb1675efb17c73127fa924d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-31T20:04:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T20:04:27.000Z", "max_forks_repo_path": "test/HaddockExample.hs", "max_forks_repo_name": "f-o-a-m/Kalman", "max_forks_repo_head_hexsha": "619d57e980d53c43bb1675efb17c73127fa924d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-08-23T16:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-02T17:40:49.000Z", "avg_line_length": 33.0506329114, "max_line_length": 82, "alphanum_fraction": 0.5896208349, "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5703543988811792}} {"text": "{-|\nModule: MachineLearning.Classification.OneVsAll\nDescription: One-vs-All Classification.\nCopyright: (c) Alexander Ignatyev, 2016-2017\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n\nOne-vs-All Classification.\n-}\n\nmodule MachineLearning.Classification.OneVsAll\n(\n Opt.MinimizeMethod(..)\n , module Log\n , module Model\n , predict\n , learn\n , MLC.calcAccuracy\n , Regularization(..)\n)\n\nwhere\n\nimport MachineLearning.Types (R, Vector, Matrix)\nimport MachineLearning.Regularization (Regularization(..))\nimport qualified MachineLearning.Optimization as Opt\nimport qualified MachineLearning.LogisticModel as Log\nimport qualified MachineLearning.Model as Model\nimport qualified MachineLearning.Classification.Internal as MLC\nimport qualified Data.Vector.Storable as V\nimport qualified Numeric.LinearAlgebra as LA\n\n\n-- | One-vs-All Classification prediction function.\n-- Takes a matrix of features X and a list of vectors theta,\n-- returns predicted class number assuming that class numbers start at 0.\npredict :: Matrix -> [Vector] -> Vector\npredict x thetas = predictions'\n where predict = Model.hypothesis Log.Logistic x\n predictions = LA.toRows . LA.fromColumns $ map predict thetas\n predictions' = LA.vector $ map (fromIntegral . LA.maxIndex) predictions\n\n\n-- | Learns One-vs-All Classification\nlearn :: Opt.MinimizeMethod -- ^ (e.g. BFGS2 0.1 0.1)\n -> R -- ^ epsilon, desired precision of the solution;\n -> Int -- ^ maximum number of iterations allowed;\n -> Regularization -- ^ regularization parameter lambda;\n -> Int -- ^ number of labels\n -> Matrix -- ^ matrix X;\n -> Vector -- ^ vector y\n -> [Vector] -- ^ initial theta list;\n -> ([Vector], [Matrix]) -- ^ solution vector and optimization path.\nlearn mm eps numIters lambda nLabels x y initialThetaList =\n let ys = MLC.processOutputOneVsAll nLabels y\n minimize = Opt.minimize mm Log.Logistic eps numIters lambda x\n in unzip $ zipWith minimize ys initialThetaList\n", "meta": {"hexsha": "fc303d3dcd27ea16b8666569a42cf248c2939e3d", "size": 2109, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/Classification/OneVsAll.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "src/MachineLearning/Classification/OneVsAll.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "src/MachineLearning/Classification/OneVsAll.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 35.7457627119, "max_line_length": 79, "alphanum_fraction": 0.6932195353, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5703294183639779}} {"text": "module HLearn.Optimization.Amoeba\n where\n\nimport Prelude\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.List\nimport Debug.Trace\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Mutable as VM\nimport qualified Data.Vector.Storable as VS\nimport qualified Data.Vector.Storable.Mutable as VSM\nimport qualified Data.Vector.Generic as VG\nimport qualified Data.Vector.Generic.Mutable as VGM\nimport qualified Data.Vector.Algorithms.Intro as Intro\nimport Numeric.LinearAlgebra hiding ((<>))\nimport qualified Numeric.LinearAlgebra as LA\n\nfindMinAmoeba f x0 = runST $ do\n\n -- initialize simplex\n vec <- VM.new (VG.length x0+1)\n VGM.write vec 0 (f x0,x0)\n forM [1..VGM.length vec-1] $ \\i -> do\n e_i <- VGM.replicate (VG.length x0) 0\n VGM.write e_i (i-1) 1\n e_i' <- VG.freeze e_i\n let x_i = x0 `LA.add` e_i'\n VGM.write vec i (f x_i,x_i)\n\n -- iterate\n vec' <- itrM 1000 (stepAmoeba f) vec\n\n -- return\n (_,ret) <- VGM.read vec 0\n return ret\n\nstepAmoeba f vec = stepAmoebaRaw 1 2 (-1/2) (1/2) f vec\n\nstepAmoebaRaw ::\n ( Fractional b\n , Ord b\n , VGM.MVector vec (b,a)\n-- , a ~ LA.Matrix b\n , a ~ LA.Vector b\n , Field b\n , vec ~ VM.MVector\n , b ~ Double\n ) => b\n -> b\n -> b\n -> b\n -> (a -> b)\n -> vec s (b,a)\n -> ST s (vec s (b,a))\nstepAmoebaRaw alpha gamma ro sigma f vec = do\n\n Intro.sortBy (\\a b -> compare (fst a) (fst b)) vec\n\n (f_1,x_1) <- VGM.read vec 0\n (f_2,x_2) <- VGM.read vec 1\n (f_n1,x_n1) <- VGM.read vec $ VGM.length vec -1\n\n x_0 <- liftM ( scale (1/fromIntegral (VGM.length vec-1))\n . foldl1' (LA.add)\n . init\n . map snd\n . V.toList\n ) $ VG.unsafeFreeze vec\n\n let x_r = x_0 `LA.add` (scale alpha $ x_0 `LA.sub` x_n1)\n f_r = f x_r\n\n x_e = x_0 `LA.add` (scale gamma $ x_0 `LA.sub` x_n1)\n f_e = f x_e\n\n x_c = x_0 `LA.add` (scale ro $ x_0 `LA.sub` x_n1)\n f_c = f x_c\n\n -- check reflection\n if f_1 <= f_r && f_r < f_1\n then VGM.write vec (VGM.length vec-1) (f_r,x_r)\n\n -- check expansion\n else if f_r < f_1\n then if f_e < f_r\n then VGM.write vec (VGM.length vec-1) (f_e,x_e)\n else VGM.write vec (VGM.length vec-1) (f_r,x_r)\n\n -- check contraction\n else if f_c < f_n1\n then VGM.write vec (VGM.length vec-1) (f_c,x_c)\n\n -- reduction\n else forM_ [1..VGM.length vec-1] $ \\i -> do\n (f_i,x_i) <- VGM.read vec i\n let x_i' = x_1 `LA.add` (scale sigma $ x_i `LA.sub` x_1)\n f_i' = f x_i'\n VGM.write vec i (f_i',x_i')\n\n return vec\n-- refMinVal <- newSTRef (-infinity)\n-- refMinIndex <- newSTRef 0\n-- forM [0..VGM.length vec-1] $ \\i -> do\n-- ival <- VGM.read vec i\n-- minVal <- readSTRef refMinVal\n-- if minVal < fst ival\n-- then return ()\n-- else do\n-- writeSTRef refMinVal $ fst ival\n-- writeSTRef refMinIndex i\n-- undefined\n\nitrM :: Monad m => Int -> (a -> m a) -> a -> m a\nitrM 0 f a = return a\nitrM i f a = do\n a' <- f a\n-- if a' == a\n-- then trace (\"no movement\\n a=\"++show a++\"\\n a'=\"++show a') $ return ()\n-- else trace (\"itrM i=\"++show i++\"; f a =\"++show a'++\"; a=\"++show a) $ return ()\n itrM (i-1) f a'\n", "meta": {"hexsha": "c96edea1af66f462c2a651c2dee141ca184b5a79", "size": 3517, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HLearn/Optimization/Amoeba.hs", "max_stars_repo_name": "Heather/HLearn", "max_stars_repo_head_hexsha": "56e0dfedbabea6d4bdeb91bb47b46a578559a092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1427, "max_stars_repo_stars_event_min_datetime": "2015-01-06T05:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T11:18:27.000Z", "max_issues_repo_path": "src/HLearn/Optimization/Amoeba.hs", "max_issues_repo_name": "Heather/HLearn", "max_issues_repo_head_hexsha": "56e0dfedbabea6d4bdeb91bb47b46a578559a092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2015-02-06T22:36:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-21T20:11:59.000Z", "max_forks_repo_path": "src/HLearn/Optimization/Amoeba.hs", "max_forks_repo_name": "Heather/HLearn", "max_forks_repo_head_hexsha": "56e0dfedbabea6d4bdeb91bb47b46a578559a092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 147, "max_forks_repo_forks_event_min_datetime": "2015-01-06T09:07:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T18:54:08.000Z", "avg_line_length": 28.8278688525, "max_line_length": 89, "alphanum_fraction": 0.5317031561, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.57032940746772}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\nimport System.IO\nimport Control.Monad\nimport Data.Complex\nimport Data.List\nimport Data.ByteString (ByteString)\n\ndata Obj2D = Obj2D [String]\ndata Obj3D = Obj3D [String]\n\nclass Render2D a where\n render2d :: a -> [Complex Double]\n\nclass Render3D a where\n render3d :: a -> Obj3D\n\ndata Gear = Gear {\n gAlpha :: Double\n, gTooth :: Double\n, gModule :: Double\n, gWidth :: Double\n} deriving Show\n\ndata Bar = Bar {\n bWidth :: Double\n} deriving Show\n\ninvolute :: Double -> Double -> Complex Double\ninvolute r theta = (r*(cos theta + theta * sin theta)) :+ (r*(sin theta - theta * cos theta))\n\nyrev :: Complex Double -> Complex Double\nyrev (a:+b) = (a:+(-b))\n\nalpha :: Gear -> Double\nalpha Gear{..} = 2 * pi * gAlpha / 360\n\nradius :: Gear -> Double\nradius g@Gear{..} = (cos (alpha g)) * radius' g\n\nradius' :: Gear -> Double\nradius' Gear{..} = gModule * gTooth / 2\n\ninstance Render2D Gear where\n render2d g@Gear{..} =\n let dat :: [Complex Double]\n dat = ((radius g) - 0.5) :+ 0 : map (\\i-> involute (radius g) (i*2.0*pi/100.0)) [0..10]\n dat''' :: [Complex Double]\n dat''' = map (\\i-> mkPolar (radius g) (i*2.0*pi/100.0)) [0..100]\n gear'' = concat $\n flip map [0..(gTooth-1)] $\n \\t -> map (\\i -> i * (cis (t*2*pi/gTooth) )) $\n dat ++\n map (\\t -> t * cis (0.9*pi/gTooth))\n (reverse (map yrev dat))\n in gear''\n\n\ninstance Render3D Gear where\n render3d g@Gear{..} =\n let gear2d = render2d g\n gear2d' = intercalate \",\" $ map (\\(r:+i) -> \"[\" ++ show r ++ \",\" ++ show i ++ \"]\") gear2d\n in Obj3D [\"linear_extrude(height = \" ++ show gWidth ++ \") { polygon( points= [\",\n gear2d',\n \"] );}\"]\n\nwritePlot :: String -> [Complex Double] -> IO ()\nwritePlot file dat = do\n withFile file WriteMode $ \\h -> do\n forM_ dat $ \\(r:+i) -> do\n hPutStrLn h $ show r ++ \" \" ++ show i\n\nwrite3DPlot :: String -> Obj3D -> IO ()\nwrite3DPlot file (Obj3D dat) = do\n withFile file WriteMode $ \\h -> do\n forM_ dat $ \\str -> do\n hPutStr h $ str\n\nmain = do\n writePlot \"involute.dat\" $ render2d $ Gear 20 8 1 6\n write3DPlot \"involute.scad\" $ render3d $ Gear 20 8 1 6\n", "meta": {"hexsha": "21f3a0577478a1913af8f89f1ae336bdb407714b", "size": 2305, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Lego.hs", "max_stars_repo_name": "junjihashimoto/raspberry-pi-box", "max_stars_repo_head_hexsha": "964d841c32336aed388ed56051712805e7ff45de", "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": "Lego.hs", "max_issues_repo_name": "junjihashimoto/raspberry-pi-box", "max_issues_repo_head_hexsha": "964d841c32336aed388ed56051712805e7ff45de", "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": "Lego.hs", "max_forks_repo_name": "junjihashimoto/raspberry-pi-box", "max_forks_repo_head_hexsha": "964d841c32336aed388ed56051712805e7ff45de", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7710843373, "max_line_length": 97, "alphanum_fraction": 0.5652928416, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5702744342178546}} {"text": "module Math.FROG.Tools\n( mkTrace\n, mkSigGate\n, shift\n, mkInitialGuess\n, flatPolar2Complex\n, center\n) where\n\nimport qualified System.Random as R\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Numeric.GSL.Fourier as F\nimport qualified Foreign\n\nimport Math.FROG.Types\n\n\n\nmkTrace :: ComplexSignal -> ComplexSignal -> Trace\nmkTrace field gate = LA.fromColumns $ map atEachDelayApply [upper,upper-1..lower]\n where\n atEachDelayApply = (^2) . (LA.mapVector LA.magnitude) \n . (flip shift upper) \n . F.fft \n . (*field) \n . (shift gate)\n sz = LA.dim field\n upper = (sz `quot` 2)\n lower = (-1) * (sz `quot` 2) + 1\n\n\nmkSigGate :: Nonlinearity -> ComplexSignal -> ComplexSignal -> (ComplexSignal, ComplexSignal)\nmkSigGate PG f g = (id f, LA.mapVector ((^2) . abs) g)\nmkSigGate SHG f g = (id f, id g) \nmkSigGate SD f g = (LA.mapVector (^2) f, LA.mapVector LA.conjugate g)\nmkSigGate THG f g = (LA.mapVector (^2) f, id g)\n\n\n\nshift :: ComplexSignal -> Int -> ComplexSignal\nshift gate delay = LA.buildVector sz (builder delay)\n where\n sz = LA.dim gate\n builder d k = if any (<0) [(sz-1-d-k), (k+d)] then (getElem (k+d-(signum d)*sz)) else (getElem (k+d))\n where\n getElem = (LA.@>) gate\n\n\nmkInitialGuess :: Int -> IO (LA.Vector Double)\nmkInitialGuess sz = do\n stdgen <- R.getStdGen\n let randMags = R.randomRs (0, 1.0) stdgen\n let randAngs = R.randomRs (-pi, pi) stdgen\n return $ LA.buildVector (2*sz) (\\k -> if k < sz then (randMags !! k) else (randAngs !! k))\n\n\nflatPolar2Complex :: LA.Vector Double -> LA.Vector (LA.Complex Double)\nflatPolar2Complex v = LA.buildVector sz (\\k -> LA.mkPolar (mags LA.@> k) (angs LA.@> k))\n where\n sz = (LA.dim v) `quot` 2\n mags = LA.subVector 0 sz v\n angs = LA.subVector sz sz v\n \ncenter :: ComplexSignal -> ComplexSignal\ncenter f = shift f $ getDelay . getMaxInd $ f\n where\n sz = LA.dim f\n getMaxInd = LA.maxIndex . (LA.mapVector LA.magnitude)\n getDelay = (*(-1)) . ((-) (sz `quot` 2))\n\n\n\n", "meta": {"hexsha": "ec24b17219afe1cc50e40d753dee2c9649a3d829", "size": 2105, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/FROG/Tools.hs", "max_stars_repo_name": "leroix/haskell-spsa-frog", "max_stars_repo_head_hexsha": "0ff98b2941840b317a08a0c2a8aa8d101c1503fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-25T19:38:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-25T19:38:00.000Z", "max_issues_repo_path": "src/Math/FROG/Tools.hs", "max_issues_repo_name": "leroix/haskell-spsa-frog", "max_issues_repo_head_hexsha": "0ff98b2941840b317a08a0c2a8aa8d101c1503fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/FROG/Tools.hs", "max_forks_repo_name": "leroix/haskell-spsa-frog", "max_forks_repo_head_hexsha": "0ff98b2941840b317a08a0c2a8aa8d101c1503fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8356164384, "max_line_length": 105, "alphanum_fraction": 0.6147268409, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5702718596934442}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Finance.Hqfl.Pricer.BlackScholes\n-- Copyright : (C) 2016 Mika'il Khan\n-- License : (see the file LICENSE)\n-- Maintainer : Mika'il Khan \n-- Stability : stable\n-- Portability : portable\n--\n---------------------------------------------------------------------------- \n{-# LANGUAGE FlexibleInstances #-}\n\nmodule Finance.Hqfl.Pricer.BlackScholes where\n\nimport Finance.Hqfl.Instrument\nimport Statistics.Distribution.Normal\nimport Data.Random\n\nclass BS a where\n price :: a -> Double -> Double -> Double\n\ninstance BS (Option Equity) where\n price (Option (Equity s q) m European k t) r v =\n case m of\n Call -> s * exp (-q * t) * cdf normal d1 - k * exp (-r * t) * cdf normal d2\n Put -> k * exp (-r * t) * cdf normal (-d2) - s * exp (-q * t) * cdf normal (-d1)\n where d1 = (log (s / k) + (r - q + (v * v) / 2) * t) / (v * sqrt t)\n d2 = d1 - v * sqrt t\n normal = Normal (0 :: Double) 1\n\ninstance BS (Option StockIndex) where\n price (Option (StockIndex s q) m European k t) r v =\n case m of\n Call -> s * exp (-q * t) * cdf normal d1 - k * exp (-r * t) * cdf normal d2\n Put -> k * exp (-r * t) * cdf normal (-d2) - s * exp (-q * t) * cdf normal (-d1)\n where d1 = (log (s / k) + (r - q + (v * v) / 2) * t) / (v * sqrt t)\n d2 = d1 - v * sqrt t\n normal = Normal (0 :: Double) 1\n\n-- Garman & Kohlhagen (1983)\n--instance BS (Option Currency) where\n-- price (Option (Currency s rf) m European k t) r v =\n-- case m of\n-- Call -> s * exp (-rf * t) * cdf normal d1 - k * exp (-r * t) * cdf normal d2\n-- Put -> k * exp (-r * t) * cdf normal (-d2) - s * exp (-rf * t) * cdf normal (-d1)\n-- where d1 = (log (s / k) + (r - rf + (v * v) / 2) * t) / (v * sqrt t)\n-- d2 = d1 - v * sqrt t\n-- normal = Normal (0 :: Double) 1\n\n-- cdi :: Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double\n-- cdi s k r v t q h = s * exp(-q * t) * (h / s)**(2 * lambda) * (cdf normal y)\n-- - k * exp(-r * t) * (h / s)**(2 * lambda - 2) * (cdf normal (y - (v * sqrt t)))\n-- where lambda = ((r - q + (v * v) / 2)) / (v * v)\n-- y = (log ( (h*h) / (s * k)) / v * sqrt t) + (lambda * v * sqrt t)\n-- normal = Normal (0 :: Double) 1\n\n-- cdo :: Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double\n-- cdo s k r v t q h = s * (cdf normal x1) * exp (-q * t) - k * exp(-r * t) * (cdf normal (x1 - v * sqrt t)) -\n-- s * exp(-q * t) * (h / s)**(2 * lambda) * (cdf normal y1) + k * exp(-r * t) * (h/ s)**(2 * lambda - 2) * (cdf normal (y1 - v * sqrt t))\n-- where lambda = ((r - q + (v * v) / 2)) / (v * v)\n-- y1 = (log (h / s) / v * sqrt t) + (lambda * v * sqrt t)\n-- x1 = (log ( s / h ) / (v * sqrt t)) + (lambda * v * sqrt t)\n-- normal = Normal (0 :: Double) 1\n\n-- cui :: Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double\n-- cui s k r v t q h = s * (cdf normal x1) * exp(-q * t) - k * exp(-r * t) * (cdf normal (x1 - v * sqrt t)) -\n-- s * exp(-q *t) * (h / s)**(2 * lambda) * ((cdf normal (-y)) - (cdf normal (-y1))) +\n-- k * exp(-r * t) * (h / s)**(2 * lambda - 2) * ((cdf normal (-y + v * sqrt t)) - (cdf normal (-y1 + v * sqrt t)))\n-- where lambda = ((r - q + (v * v) / 2)) / (v * v)\n-- y1 = (log (h / s) / v * sqrt t) + (lambda * v * sqrt t)\n-- x1 = (log ( s / h ) / (v * sqrt t)) + (lambda * v * sqrt t)\n-- y = (log ( (h*h) / (s * k)) / v * sqrt t) + (lambda * v * sqrt t)\n-- normal = Normal (0 :: Double) 1\n\n-- pui :: Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double\n-- pui s k r v t q h = -s * exp(-q * t) * (h / s)**(2 * lambda) * (cdf normal (-y)) + k * exp(-r * t) * (h / s)**(2 * lambda - 2) * (cdf normal ((-y) + (v * sqrt t)))\n-- where lambda = ((r - q + (v * v) / 2)) / (v * v)\n-- y = (log ( (h*h) / (s * k)) / v * sqrt t) + (lambda * v * sqrt t)\n-- normal = Normal (0 :: Double) 1\n\n-- pdi :: Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double\n-- pdi s k r v t q h = -s * (cdf normal (-x1)) * exp(-q * t)\n-- + k * exp(-r * t) * (cdf normal (-x1 + v * sqrt t))\n-- + s * exp(-q * t) * (h / s)**(2 * lambda) * (cdf normal y - cdf normal y1)\n-- - k * exp(-r * t) * (h / s)**(2 * lambda -2) * (cdf normal (y - v * sqrt t) - cdf normal (y1 - v * sqrt t))\n-- where lambda = ((r - q + (v * v) / 2)) / (v * v)\n-- y1 = (log (h / s) / v * sqrt t) + (lambda * v * sqrt t)\n-- x1 = (log ( s / h ) / (v * sqrt t)) + (lambda * v * sqrt t)\n-- y = (log ( (h*h) / (s * k)) / v * sqrt t) + (lambda * v * sqrt t)\n-- normal = Normal (0 :: Double) 1\n \n-- puo s k r v t q h = -s * (cdf normal (-x1)) * exp(-q * t) + k * exp(-r * t) * (cdf normal (-x1 + v * sqrt t)) +\n-- s * exp(-q * t) * (h / s)**(2 * lambda) * (cdf normal (-y1)) - k * exp(-r * t) * (h / s)**(2 * lambda -2) * (cdf normal ((-y1) + v * sqrt t))\n-- where lambda = ((r - q + (v * v) / 2)) / (v * v)\n-- y1 = (log (h / s) / v * sqrt t) + (lambda * v * sqrt t)\n-- x1 = (log ( s / h ) / (v * sqrt t)) + (lambda * v * sqrt t)\n-- y = (log ( (h*h) / (s * k)) / v * sqrt t) + (lambda * v * sqrt t)\n-- normal = Normal (0 :: Double) 1\n\n\n\n-- instance BS (Option StockIndex) where\n-- blackscholesprice (Option (StockIndex s) Call European k t) r v = call s k r v t q\n-- blackscholesprice (Option (StockIndex s) Put European k t) r v = put s k r v t q\n \n\n-- instance BS (Option Future) where\n-- blackscholesprice (Option (Future f) Call European k t) r v = call f k r v t q\n-- blackscholesprice (Option (Future f) Put European k t) r v = put f k r v t q\n\n-- TODO : factor in rebates\n-- instance BS (BarrierOption Equity) where\n-- blackscholesprice (BarrierOption (Equity s q) x European y h k t) r v =\n-- case (x, y) of\n-- (DownAndIn, Call)\n-- -- | s <= h -> Left \"Contract is converted to a vanilla call\"\n-- | h <= k -> cdi'\n-- | h >= k -> call' - cdo'\n-- (DownAndOut, Call)\n-- -- | s <= h -> Left \"Contract is void\"\n-- | h <= k -> call' - cdi'\n-- | h >= k -> cdo'\n-- (UpAndIn, Call)\n-- -- | h <= s -> Left \"Contract is converted to a vanilla call\"\n-- | h <= k -> call'\n-- | h >= k -> cui'\n-- (UpAndOut, Call)\n-- -- | s <= h -> Left \"Contract is void\"\n-- | h <= k -> call' - cdi'\n-- | h >= k -> cdo'\n-- (DownAndIn, Put)\n-- -- | s <= h -> Left \"Contract is converted to a vanilla call\"\n-- | h < k -> pdi'\n-- | h >= k -> put'\n-- (DownAndOut, Put)\n-- -- | s <= h -> Left \"Contract is void\"\n-- | h < k -> put' - pdi'\n-- | h >= k -> 0\n-- (UpAndIn, Put)\n-- -- | h <= s -> Left \"Contract is converted to a vanilla call\"\n-- | h <= k -> put' - puo'\n-- | h >= k -> pui'\n-- (UpAndOut, Put)\n-- -- | h <= s -> Left \"Contract is void\"\n-- | h <= k -> puo'\n-- | h >= k -> put' - pui'\n-- where\n-- call' = call s k r v t q \n-- cdi' = cdi s k r v t q h\n-- cdo' = cdo s k r v t q h\n-- cui' = cui s k r v t q h\n-- pdi' = pdi s k r v t q h\n-- put' = put s k r v t q\n-- pui' = pui s k r v t q h\n-- puo' = puo s k r v t q h\n", "meta": {"hexsha": "1bca99a261a31e6ad7c4a49539e2670e4f28763d", "size": 7609, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Finance/Hqfl/Pricer/BlackScholes.hs", "max_stars_repo_name": "co-category/hqfl", "max_stars_repo_head_hexsha": "398bd921089522c6c0e6d91893a75615a1f39a2e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-02-19T14:03:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-13T12:44:03.000Z", "max_issues_repo_path": "src/Finance/Hqfl/Pricer/BlackScholes.hs", "max_issues_repo_name": "cokleisli/hqfl", "max_issues_repo_head_hexsha": "398bd921089522c6c0e6d91893a75615a1f39a2e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Finance/Hqfl/Pricer/BlackScholes.hs", "max_forks_repo_name": "cokleisli/hqfl", "max_forks_repo_head_hexsha": "398bd921089522c6c0e6d91893a75615a1f39a2e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-26T18:36:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T09:49:53.000Z", "avg_line_length": 48.7756410256, "max_line_length": 166, "alphanum_fraction": 0.437508214, "num_tokens": 2717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5702409752433696}} {"text": "module Tests.Function ( tests ) where\n\nimport Statistics.Function\nimport Test.Tasty\nimport Test.Tasty.QuickCheck\nimport Test.QuickCheck\nimport Tests.Helpers\nimport qualified Data.Vector.Unboxed as U\n\n\ntests :: TestTree\ntests = testGroup \"S.Function\"\n [ testProperty \"Sort is sort\" p_sort\n , testAssertion \"nextHighestPowerOfTwo is OK\" p_nextHighestPowerOfTwo\n ]\n\n\np_sort :: [Double] -> Property\np_sort xs =\n not (null xs) ==> U.all (uncurry (<=)) (U.zip v $ U.tail v)\n where\n v = sort $ U.fromList xs\n\np_nextHighestPowerOfTwo :: Bool\np_nextHighestPowerOfTwo\n = all (\\(good, is) -> all ((==good) . nextHighestPowerOfTwo) is) lists\n where\n pows = [1 .. 17 :: Int]\n lists = [ (2^m, [2^n+1 .. 2^m]) | (n,m) <- pows `zip` tail pows ]\n", "meta": {"hexsha": "256c3b6b9ecc5fbe935fff7ab0c0b6772ca16db9", "size": 766, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Tests/Function.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:39:40.000Z", "max_issues_repo_path": "tests/Tests/Function.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T14:21:32.000Z", "max_forks_repo_path": "tests/Tests/Function.hs", "max_forks_repo_name": "infinity0/statistics", "max_forks_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2015-02-13T00:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:19:16.000Z", "avg_line_length": 25.5333333333, "max_line_length": 72, "alphanum_fraction": 0.6644908616, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5700549388668487}} {"text": "module Supervised.LinearRegressionSpec where\n\nimport Prelude\nimport Test.Hspec\nimport Supervised.LinearRegression\nimport Datasets.Iris\nimport qualified Data.Vector as V\nimport qualified Numeric.LinearAlgebra as LA\n\nv2la :: V.Vector IrisClass -> LA.Vector Double\nv2la = LA.vector . V.toList . fmap (fromIntegral . fromEnum)\n\nmain :: IO ()\nmain = do\n ((trainX, trainY'), (testX, testY')) <- splitCV 0.6 <$> loadIris\n let\n !trainY = v2la trainY' :: LA.Vector Double\n !testY = v2la testY' :: LA.Vector Double\n\n let\n trainedModel :: Model\n trainedModel = fit mkModel trainX trainY\n\n let\n predicted :: Labels\n predicted = trainedModel `predict` testX\n\n let\n score :: Double\n score = rSquare testY predicted\n\n print $ score\n-- hspec spec\n\nspec :: Spec\nspec =\n describe \"Linear Regression\" $ undefined\n\n\n", "meta": {"hexsha": "551ad65f50bc1972ad263dbefbfab97f49065317", "size": 829, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Supervised/LinearRegressionSpec.hs", "max_stars_repo_name": "stites/hasklearn", "max_stars_repo_head_hexsha": "188464e47d624621c01c7851297b85f9446ffaf4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Supervised/LinearRegressionSpec.hs", "max_issues_repo_name": "stites/hasklearn", "max_issues_repo_head_hexsha": "188464e47d624621c01c7851297b85f9446ffaf4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-08-02T15:05:37.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T16:12:39.000Z", "max_forks_repo_path": "test/Supervised/LinearRegressionSpec.hs", "max_forks_repo_name": "stites/hasklearn", "max_forks_repo_head_hexsha": "188464e47d624621c01c7851297b85f9446ffaf4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.725, "max_line_length": 66, "alphanum_fraction": 0.7044632087, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5700084373348926}} {"text": "import Graphics.Rendering.Plot\nimport Numeric.LinearAlgebra\nimport Numeric.GSL.Statistics\nimport qualified Graphics.Rendering.Cairo as C\nimport Graphics.Rendering.Pango.Enums\nimport Graphics.UI.Gtk hiding(Circle,Cross) \nimport Control.Monad.Trans\n\nln = 25\nts = linspace ln (0,1)\nrs = randomVector 0 Gaussian ln\n\nss = sin (15*2*pi*ts)\nds = 0.25*rs + ss\nes = constant (0.25*(stddev rs)) ln\n\nfs :: Double -> Double\nfs = sin . (15*2*pi*)\n\ntest_graph = do\n withTitle $ setText \"Testing plot package:\"\n withSubTitle $ do\n setText \"with 1 second of a 15Hz sine wave\"\n withPointDefaults $ setPointSize 1.5 -- (A)\n setPlots 1 1\n withPlot (1,1) $ do\n setLegend True SouthWest Inside -- (B)\n addAxis XAxis (Side Lower) $ withAxisLabel $ setText \"time (s)\"\n addAxis YAxis (Side Lower) $ do\n withAxisLabel $ setText \"amplitude\"\n withGridLine Major $ do\n setDashStyle [Dash]\n setLineColour lightgray\n addAxis XAxis (Value 0) $ return ()\n setRange YAxis Lower Linear (-1.25) 1.25\n setDataset (ts,[point (ds,es,\"dat\") (Cross,red),line (fs,\"sin\") blue])\n setRangeFromData XAxis Lower Linear\n\ndisplay :: ((Int,Int) -> C.Render ()) -> IO ()\ndisplay r = do\n initGUI -- is start\n\n window <- windowNew\n set window [ windowTitle := \"Cairo test window\"\n , windowDefaultWidth := 600\n , windowDefaultHeight := 400\n , containerBorderWidth := 1\n ]\n\n-- canvas <- pixbufNew ColorspaceRgb True 8 300 200\n-- containerAdd window canvas\n frame <- frameNew\n containerAdd window frame\n canvas <- drawingAreaNew\n containerAdd frame canvas\n widgetModifyBg canvas StateNormal (Color 65535 65535 65535)\n\n widgetShowAll window \n\n on canvas exposeEvent $ tryEvent $ do s <- liftIO $ widgetGetSize canvas\n drw <- liftIO $ widgetGetDrawWindow canvas\n --dat <- liftIO $ takeMVar d\n --liftIO $ renderWithDrawable drw (circle 50 10)\n liftIO $ renderWithDrawable drw (r s)\n\n onDestroy window mainQuit\n mainGUI\n\n \nmain = display $ render test_graph\n\ntest_render :: (Int,Int) -> C.Render ()\ntest_render = render test_graph\n\n--main = C.withSVGSurface \"out.svg\" 400 400 $ \\surf -> C.renderWith surf $ test_render (400,400)", "meta": {"hexsha": "ecfa00add56ae41af43e1c0ede23db7749f69bcc", "size": 2641, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/Test4.hs", "max_stars_repo_name": "JackTheEngineer/plot", "max_stars_repo_head_hexsha": "547acf1f348c7aad249d87482becd43bbe37a6ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2015-03-03T03:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-04T14:10:10.000Z", "max_issues_repo_path": "examples/Test4.hs", "max_issues_repo_name": "strake/plot.hs", "max_issues_repo_head_hexsha": "eacddea5afcf91b0eb7e4c2bccf640b3558daf1b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2015-01-15T02:11:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-30T07:33:39.000Z", "max_forks_repo_path": "examples/Test4.hs", "max_forks_repo_name": "strake/plot.hs", "max_forks_repo_head_hexsha": "eacddea5afcf91b0eb7e4c2bccf640b3558daf1b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-01-05T02:30:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-23T20:51:16.000Z", "avg_line_length": 35.2133333333, "max_line_length": 96, "alphanum_fraction": 0.5694812571, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5699214940151477}} {"text": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n-- |\n-- Module : Statistics.Transform\n-- Copyright : (c) 2011 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Fourier-related transformations of mathematical functions.\n--\n-- These functions are written for simplicity and correctness, not\n-- speed. If you need a fast FFT implementation for your application,\n-- you should strongly consider using a library of FFTW bindings\n-- instead.\n\nmodule Statistics.Transform\n (\n -- * Type synonyms\n CD\n -- * Discrete cosine transform\n , dct\n , dct_\n , idct\n , idct_\n -- * Fast Fourier transform\n , fft\n , ifft\n ) where\n\nimport Control.Monad (when)\nimport Control.Monad.ST (ST)\nimport Data.Bits (shiftL, shiftR)\nimport Data.Complex (Complex(..), conjugate, realPart)\nimport Numeric.SpecFunctions (log2)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector as V\n\ntype CD = Complex Double\n\n-- | Discrete cosine transform (DCT-II).\ndct :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v Double -> v Double\ndct = dctWorker . G.map (:+0)\n{-# INLINABLE dct #-}\n{-# SPECIAlIZE dct :: U.Vector Double -> U.Vector Double #-}\n{-# SPECIAlIZE dct :: V.Vector Double -> V.Vector Double #-}\n\n-- | Discrete cosine transform (DCT-II). Only real part of vector is\n-- transformed, imaginary part is ignored.\ndct_ :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v CD -> v Double\ndct_ = dctWorker . G.map (\\(i :+ _) -> i :+ 0)\n{-# INLINABLE dct_ #-}\n{-# SPECIAlIZE dct_ :: U.Vector CD -> U.Vector Double #-}\n{-# SPECIAlIZE dct_ :: V.Vector CD -> V.Vector Double#-}\n\ndctWorker :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v CD -> v Double\n{-# INLINE dctWorker #-}\ndctWorker xs\n -- length 1 is special cased because shuffle algorithms fail for it.\n | G.length xs == 1 = G.map ((2*) . realPart) xs\n | vectorOK xs = G.map realPart $ G.zipWith (*) weights (fft interleaved)\n | otherwise = error \"Statistics.Transform.dct: bad vector length\"\n where\n interleaved = G.backpermute xs $ G.enumFromThenTo 0 2 (len-2) G.++\n G.enumFromThenTo (len-1) (len-3) 1\n weights = G.cons 2 . G.generate (len-1) $ \\x ->\n 2 * exp ((0:+(-1))*fi (x+1)*pi/(2*n))\n where n = fi len\n len = G.length xs\n\n\n\n-- | Inverse discrete cosine transform (DCT-III). It's inverse of\n-- 'dct' only up to scale parameter:\n--\n-- > (idct . dct) x = (* length x)\nidct :: (G.Vector v CD, G.Vector v Double) => v Double -> v Double\nidct = idctWorker . G.map (:+0)\n{-# INLINABLE idct #-}\n{-# SPECIAlIZE idct :: U.Vector Double -> U.Vector Double #-}\n{-# SPECIAlIZE idct :: V.Vector Double -> V.Vector Double #-}\n\n-- | Inverse discrete cosine transform (DCT-III). Only real part of vector is\n-- transformed, imaginary part is ignored.\nidct_ :: (G.Vector v CD, G.Vector v Double) => v CD -> v Double\nidct_ = idctWorker . G.map (\\(i :+ _) -> i :+ 0)\n{-# INLINABLE idct_ #-}\n{-# SPECIAlIZE idct_ :: U.Vector CD -> U.Vector Double #-}\n{-# SPECIAlIZE idct_ :: V.Vector CD -> V.Vector Double #-}\n\nidctWorker :: (G.Vector v CD, G.Vector v Double) => v CD -> v Double\n{-# INLINE idctWorker #-}\nidctWorker xs\n | vectorOK xs = G.generate len interleave\n | otherwise = error \"Statistics.Transform.dct: bad vector length\"\n where\n interleave z | even z = vals `G.unsafeIndex` halve z\n | otherwise = vals `G.unsafeIndex` (len - halve z - 1)\n vals = G.map realPart . ifft $ G.zipWith (*) weights xs\n weights\n = G.cons n\n $ G.generate (len - 1) $ \\x -> 2 * n * exp ((0:+1) * fi (x+1) * pi/(2*n))\n where n = fi len\n len = G.length xs\n\n\n\n-- | Inverse fast Fourier transform.\nifft :: G.Vector v CD => v CD -> v CD\nifft xs\n | vectorOK xs = G.map ((/fi (G.length xs)) . conjugate) . fft . G.map conjugate $ xs\n | otherwise = error \"Statistics.Transform.ifft: bad vector length\"\n{-# INLINABLE ifft #-}\n{-# SPECIAlIZE ifft :: U.Vector CD -> U.Vector CD #-}\n{-# SPECIAlIZE ifft :: V.Vector CD -> V.Vector CD #-}\n\n-- | Radix-2 decimation-in-time fast Fourier transform.\nfft :: G.Vector v CD => v CD -> v CD\nfft v | vectorOK v = G.create $ do mv <- G.thaw v\n mfft mv\n return mv\n | otherwise = error \"Statistics.Transform.fft: bad vector length\"\n{-# INLINABLE fft #-}\n{-# SPECIAlIZE fft :: U.Vector CD -> U.Vector CD #-}\n{-# SPECIAlIZE fft :: V.Vector CD -> V.Vector CD #-}\n\n-- Vector length must be power of two. It's not checked\nmfft :: (M.MVector v CD) => v s CD -> ST s ()\n{-# INLINE mfft #-}\nmfft vec = bitReverse 0 0\n where\n bitReverse i j | i == len-1 = stage 0 1\n | otherwise = do\n when (i < j) $ M.swap vec i j\n let inner k l | k <= l = inner (k `shiftR` 1) (l-k)\n | otherwise = bitReverse (i+1) (l+k)\n inner (len `shiftR` 1) j\n stage l !l1 | l == m = return ()\n | otherwise = do\n let !l2 = l1 `shiftL` 1\n !e = -6.283185307179586/fromIntegral l2\n flight j !a | j == l1 = stage (l+1) l2\n | otherwise = do\n let butterfly i | i >= len = flight (j+1) (a+e)\n | otherwise = do\n let i1 = i + l1\n xi1 :+ yi1 <- M.read vec i1\n let !c = cos a\n !s = sin a\n d = (c*xi1 - s*yi1) :+ (s*xi1 + c*yi1)\n ci <- M.read vec i\n M.write vec i1 (ci - d)\n M.write vec i (ci + d)\n butterfly (i+l2)\n butterfly j\n flight 0 0\n len = M.length vec\n m = log2 len\n\n\n----------------------------------------------------------------\n-- Helpers\n----------------------------------------------------------------\n\nfi :: Int -> CD\nfi = fromIntegral\n\nhalve :: Int -> Int\nhalve = (`shiftR` 1)\n\nvectorOK :: G.Vector v a => v a -> Bool\n{-# INLINE vectorOK #-}\nvectorOK v = (1 `shiftL` log2 n) == n where n = G.length v\n", "meta": {"hexsha": "7159bbf9a15daacfdc2a7ad77040151731ee38f1", "size": 6197, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Transform.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:39:40.000Z", "max_issues_repo_path": "Statistics/Transform.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T14:21:32.000Z", "max_forks_repo_path": "Statistics/Transform.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2015-02-13T00:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:19:16.000Z", "avg_line_length": 35.011299435, "max_line_length": 86, "alphanum_fraction": 0.5688236243, "num_tokens": 1777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5696786986275206}} {"text": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n\n-----------------------------------------------------------------------------\n{-|\nModule : Math.Tensor.LinearAlgebra.Equations\nDescription : Linear tensor equations.\nCopyright : (c) Nils Alex, 2020\nLicense : MIT\nMaintainer : nils.alex@fau.de\n\nLinear tensor equations.\n-}\n-----------------------------------------------------------------------------\nmodule Math.Tensor.LinearAlgebra.Equations\n ( Equation\n , tensorToEquations\n , equationFromRational\n , equationsToSparseMat\n , equationsToMat\n , tensorsToSparseMat\n , tensorsToMat\n , systemRank\n , Solution\n , fromRref\n , fromRrefRev\n , fromRow\n , fromRowRev\n , applySolution\n , solveTensor\n , solveSystem\n , redefineIndets\n ) where\n\nimport Math.Tensor\n ( T\n , removeZerosT\n , toListT\n )\nimport Math.Tensor.LinearAlgebra.Scalar\n ( Poly (Const, Affine, NotSupported)\n , Lin (Lin)\n , polyMap\n , normalize\n )\nimport Math.Tensor.LinearAlgebra.Matrix\n ( rref\n , isrref\n , verify\n )\n\nimport qualified Numeric.LinearAlgebra.Data as HM\n ( Matrix\n , R\n , Z\n , fromLists\n , toLists\n )\nimport Numeric.LinearAlgebra (rank)\n\nimport Data.Maybe (mapMaybe)\nimport qualified Data.IntMap.Strict as IM\n ( IntMap\n , foldl'\n , map\n , assocs\n , null\n , findWithDefault\n , lookupMax\n , keys\n , fromList\n , (!)\n , difference\n , intersectionWith\n , mapKeys\n , empty\n )\nimport Data.List (nub, sort)\nimport Data.Ratio (numerator, denominator)\n\n-- |A linear equation is a mapping from variable\n-- indices to coefficients\ntype Equation a = IM.IntMap a\n\n-- |Extract linear equations from tensor components.\n-- The equations are normalized, sorted, and made unique.\ntensorToEquations :: Integral a => T (Poly Rational) -> [Equation a]\ntensorToEquations = nub . sort . filter (not . IM.null) . fmap (equationFromRational . normalize . snd) . toListT\n\n-- |Extract linear equation with integral coefficients from polynomial\n-- tensor component with rational coefficients.\n-- Made made integral by multiplying with the @lcm@ of all denominators.\nequationFromRational :: forall a.Integral a => Poly Rational -> Equation a\nequationFromRational (Affine x (Lin lin))\n | x == 0 = lin'\n | otherwise = error \"affine equation not supported for the moment!\"\n where\n fac :: a\n fac = IM.foldl' (\\acc v -> lcm (fromIntegral (denominator v)) acc) 1 lin\n lin' = IM.map (\\v -> fromIntegral (numerator v) * (fac `div` fromIntegral (denominator v))) lin\nequationFromRational (Const c)\n | c == 0 = IM.empty\nequationFromRational _ = error \"equation can only be extracted from linear scalar!\"\n\n-- |Convert list of equations to sparse matrix representation of the\n-- linear system.\nequationsToSparseMat :: [Equation a] -> [((Int,Int), a)]\nequationsToSparseMat xs = concat $ zipWith (\\i m -> fmap (\\(j,v) -> ((i,j),v)) (IM.assocs m)) [1..] xs\n\n-- |Convert list of equations to dense matrix representation of the\n-- linear system.\nequationsToMat :: Integral a => [Equation a] -> [[a]]\nequationsToMat eqns = mapMaybe (\\m -> if IM.null m\n then Nothing\n else Just $ fmap (\\j -> IM.findWithDefault 0 j m) [1..maxVar]) eqns\n where\n maxVar = maximum $ mapMaybe (fmap fst . IM.lookupMax) eqns\n\n-- |Extract sparse matrix representation for the linear system given\n-- by a list of existentially quantified tensors with polynomial values.\ntensorsToSparseMat :: Integral a => [T (Poly Rational)] -> [((Int,Int), a)]\ntensorsToSparseMat = equationsToSparseMat . concatMap tensorToEquations\n\n-- |Extract dense matrix representation for the linear system given\n-- by a list of existentially quantified tensors with polynomial values.\ntensorsToMat :: Integral a => [T (Poly Rational)] -> [[a]]\ntensorsToMat = equationsToMat . concatMap tensorToEquations\n\n-- |Rank of a linear system. Uses dense svd provided by hmatrix.\nmatRank :: forall a.Integral a => [[a]] -> Int\nmatRank [] = 0\nmatRank mat = rank (hmat :: HM.Matrix HM.R)\n where\n hmat = HM.fromLists $ fmap (fmap (fromIntegral @a @HM.R)) mat\n\n-- |Rank of the linear system given by a list of existentially\n-- quantified tensors with polynomial values.\nsystemRank :: [T (Poly Rational)] -> Int\nsystemRank = matRank . tensorsToMat @Int\n\n-- |The solution to a linear system is represented as a list of\n-- substitution rules, stored as @'IM.IntMap' ('Poly' 'Rational')@.\ntype Solution = IM.IntMap (Poly Rational)\n\n-- |Read substitution rules from reduced row echelon form\n-- of a linear system.\nfromRref :: HM.Matrix HM.Z -> Solution\nfromRref ref = IM.fromList assocs\n where\n rows = HM.toLists ref\n assocs = mapMaybe fromRow rows\n\nfromRrefRev :: HM.Matrix HM.Z -> Solution\nfromRrefRev ref = IM.fromList assocs\n where\n rows = fmap reverse $ HM.toLists ref\n assocs = mapMaybe fromRowRev rows\n\n-- |Read single substitution rule from single\n-- row of reduced row echelon form.\nfromRow :: forall a.Integral a => [a] -> Maybe (Int, Poly Rational)\nfromRow xs = case assocs of\n [] -> Nothing\n [(i,_)] -> Just (i, Const 0)\n (i, v):assocs' -> let assocs'' = fmap (\\(i',v') -> (i', - fromIntegral @a @Rational v' / fromIntegral @a @Rational v)) assocs'\n in Just (i, Affine 0 (Lin (IM.fromList assocs'')))\n where\n assocs = filter ((/=0). snd) $ zip [(1::Int)..] xs\n\nfromRowRev :: forall a.Integral a => [a] -> Maybe (Int, Poly Rational)\nfromRowRev xs = case assocs of\n [] -> Nothing\n [(i,_)] -> Just (i, Const 0)\n (i, v):assocs' -> let assocs'' = fmap (\\(i',v') -> (i', - fromIntegral @a @Rational v' / fromIntegral @a @Rational v)) assocs'\n in Just (i, Affine 0 (Lin (IM.fromList assocs'')))\n where\n assocs = reverse $ filter ((/=0). snd) $ zip [(1::Int)..] xs\n\n-- |Apply substitution rules to tensor component.\napplySolution :: Solution -> Poly Rational -> Poly Rational\napplySolution s (Affine x (Lin lin))\n | x == 0 = case p of\n Affine xFin (Lin linFin) -> if IM.null linFin\n then Const xFin\n else p\n _ -> p\n | otherwise = error \"affine equations not yet supported\"\n where\n s' = IM.intersectionWith (\\row v -> if v == 0\n then error \"value 0 encountered in linear scalar\"\n else polyMap (v*) row) s lin\n lin' = IM.difference lin s\n p0 = if IM.null lin'\n then Const 0\n else Affine 0 (Lin lin')\n\n p = IM.foldl' (+) p0 s'\n\n {-\n lin' = IM.foldlWithKey'\n (\\lin' i sub ->\n case Affine 0 (Lin lin') + sub of\n Affine 0 (Lin lin'') -> IM.delete i lin''\n Const 0 -> IM.empty\n _ -> error \"affine equations not yet supported\")\n lin s'\n -}\napplySolution _ _ = error \"only linear equations supported\"\n\n-- |Apply substitution rules to all components of a tensor.\nsolveTensor :: Solution -> T (Poly Rational) -> T (Poly Rational)\nsolveTensor sol = removeZerosT . fmap (applySolution sol)\n\n-- |Solve a linear system and apply solution to the tensorial\n-- indeterminants.\nsolveSystem ::\n [T (Poly Rational)] -- ^ Tensorial linear system\n -> [T (Poly Rational)] -- ^ List of indeterminant tensors\n -> [T (Poly Rational)] -- ^ Solved indeterminant tensors\nsolveSystem system indets\n | wrongSolution = error \"Wrong solution found. May be an Int64 overflow.\"\n | otherwise = indets'\n where\n mat = HM.fromLists $ tensorsToMat @HM.Z system\n ref = rref mat\n wrongSolution = not (isrref ref && verify mat ref)\n sol = fromRref ref\n indets' = fmap (solveTensor sol) indets\n\n-- |Relabelling of the indeterminants present in a list of tensors.\n-- Redefines the labels of @n@ indeterminants as @[1..n]@, preserving\n-- the previous order.\nredefineIndets :: [T (Poly v)] -> [T (Poly v)]\nredefineIndets indets = fmap (fmap (\\case\n Const c -> Const c\n NotSupported -> NotSupported\n Affine a (Lin lin) ->\n Affine a (Lin (IM.mapKeys (varMap IM.!) lin)))) indets\n where\n comps = snd <$> concatMap toListT indets\n vars = nub $ concat $ mapMaybe (\\case\n Affine _ (Lin lin) -> Just $ IM.keys lin\n _ -> Nothing) comps\n varMap = IM.fromList $ zip vars [(1::Int)..]\n", "meta": {"hexsha": "acca194856b8c9db3ca1f71c1f83b97df6f3c1fa", "size": 8813, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "packages/safe-tensor/src/Math/Tensor/LinearAlgebra/Equations.hs", "max_stars_repo_name": "nilsalex/type-tensor", "max_stars_repo_head_hexsha": "dde3e89c7ceab3a0d0b713523633a3d249702438", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-21T02:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T06:31:57.000Z", "max_issues_repo_path": "packages/safe-tensor/src/Math/Tensor/LinearAlgebra/Equations.hs", "max_issues_repo_name": "nilsalex/type-tensor", "max_issues_repo_head_hexsha": "dde3e89c7ceab3a0d0b713523633a3d249702438", "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": "packages/safe-tensor/src/Math/Tensor/LinearAlgebra/Equations.hs", "max_forks_repo_name": "nilsalex/type-tensor", "max_forks_repo_head_hexsha": "dde3e89c7ceab3a0d0b713523633a3d249702438", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6801619433, "max_line_length": 144, "alphanum_fraction": 0.6043345058, "num_tokens": 2289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5696786894747549}} {"text": "module AoC2021.Day07 where\n\nimport Data.Bifunctor (bimap)\nimport Data.List (sort)\nimport qualified Numeric.LinearAlgebra.Static as N\nimport qualified Parsers as P\nimport Solver (Solver)\n\n\nmean :: (Fractional n, Foldable f) => f n -> n\nmean ns\n | null ns = 0\n | otherwise = uncurry (/) . foldl f (0,0) $ ns\n where f (t,c) n = (t+n,c+1)\n\nmedian :: Ord a => [a] -> a\nmedian as = let m = length as `div` 2\n in sort as!!m\n\nminFuelCost :: [Int] -> Int\nminFuelCost ns = sum . map (abs . (median ns-)) $ ns\n\n\nday07 :: ([Int] -> Int) -> Solver\nday07 algo input = case P.runParser P.parseIntegerList () \"\" input of\n Left e -> show e\n Right positions -> show . algo $ positions\n\nsolve01 :: Solver\nsolve01 = day07 minFuelCost\n", "meta": {"hexsha": "12130f336adee69035360bb458db57543d6ff0ec", "size": 846, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AoC2021/Day07.hs", "max_stars_repo_name": "jroeger23/aoc", "max_stars_repo_head_hexsha": "7f165ff4838a125e61f395cd1e47370dba2e352f", "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/AoC2021/Day07.hs", "max_issues_repo_name": "jroeger23/aoc", "max_issues_repo_head_hexsha": "7f165ff4838a125e61f395cd1e47370dba2e352f", "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/AoC2021/Day07.hs", "max_forks_repo_name": "jroeger23/aoc", "max_forks_repo_head_hexsha": "7f165ff4838a125e61f395cd1e47370dba2e352f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2903225806, "max_line_length": 69, "alphanum_fraction": 0.5567375887, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5694827098765481}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n-- This module uses the test-framework-quickcheck2 package.\nmodule Main where\n\nimport Control.Monad\nimport qualified Data.Vector.Unboxed as V\nimport qualified Data.Vector.Storable as VS\nimport Data.Complex\n\nimport Test.Framework (defaultMain, testGroup)\nimport Test.Framework.Providers.QuickCheck2 (testProperty)\nimport Test.QuickCheck\n\nimport qualified Numeric.FFT.Vector.Invertible as I\nimport qualified Numeric.FFT.Vector.Invertible.Multi as IM\nimport qualified Numeric.FFT.Vector.Unitary as U\nimport qualified Numeric.FFT.Vector.Unitary.Multi as UM\nimport Numeric.FFT.Vector.Plan\n\nmain = defaultMain\n -- NB: There's no explicit tests for the Unnormalized package.\n -- However, its Planners are implicitly used by the other modules,\n -- so it's covered in the below tests.\n [ testGroup \"invertibility\"\n [ testProperty \"I.dft\" $ prop_invert I.dft I.idft\n , testProperty \"I.dftR2C\" $ prop_invert I.dftR2C I.dftC2R\n , testProperty \"I.dct1\" $ prop_invert I.dct1 I.idct1\n , testProperty \"I.dct2\" $ prop_invert I.dct2 I.idct2\n , testProperty \"I.dct3\" $ prop_invert I.dct3 I.idct3\n , testProperty \"I.dct4\" $ prop_invert I.dct4 I.idct4\n , testProperty \"I.dst1\" $ prop_invert I.dst1 I.idst1\n , testProperty \"I.dst2\" $ prop_invert I.dst2 I.idst2\n , testProperty \"I.dst3\" $ prop_invert I.dst3 I.idst3\n , testProperty \"I.dst4\" $ prop_invert I.dst4 I.idst4\n , testProperty \"U.dft\" $ prop_invert U.dft U.idft\n , testProperty \"U.dftR2C\" $ prop_invert U.dftR2C U.dftC2R\n , testProperty \"U.dct2\" $ prop_invert U.dct2 U.idct2\n ]\n , testGroup \"orthogonality\"\n [ testProperty \"U.dft\" $ prop_orthog U.dft\n , testProperty \"U.idft\" $ prop_orthog U.idft\n , testProperty \"U.dftR2C\" $ prop_orthog U.dftR2C\n , testProperty \"U.dftC2R\" $ prop_orthog U.dftR2C\n , testProperty \"U.dct2\" $ prop_orthog U.dct2\n , testProperty \"U.idct2\" $ prop_orthog U.idct2\n , testProperty \"U.dct4\" $ prop_orthog U.dct4\n ]\n , testGroup \"invertibility ND\"\n [ testProperty \"IM.dft\" $ prop_invertND IM.dft IM.idft\n , testProperty \"IM.dftR2C\" $ prop_invertND IM.dftR2C IM.dftC2R\n , testProperty \"UM.dft\" $ prop_invertND UM.dft UM.idft\n , testProperty \"UM.dftR2C\" $ prop_invertND UM.dftR2C UM.dftC2R\n ]\n , testGroup \"orthogonality\"\n [ testProperty \"UM.dft\" $ prop_orthogND UM.dft\n , testProperty \"UM.idft\" $ prop_orthogND UM.idft\n , testProperty \"UM.dftR2C\" $ prop_orthogND UM.dftR2C\n , testProperty \"UM.dftC2R\" $ prop_orthogND UM.dftR2C\n ]\n ]\n\n-------------------\n-- An instance of Arbitrary that probably belongs in another package.\n\ninstance (V.Unbox a, Arbitrary a) => Arbitrary (V.Vector a) where\n arbitrary = V.fromList `fmap` arbitrary\n\n\n-------------------------\n-- Support functions to compare Doubles for (near) equality.\n\nclass Num a => Mag a where\n mag :: a -> Double\n\ninstance Mag Double where\n mag = abs\n\ninstance Mag (Complex Double) where\n mag = magnitude\n\n-- Robustly test whether two Doubles are nearly identical.\nclose :: Mag a => a -> a -> Bool\nclose x y = tol > mag (x-y) / max 1 (mag x + mag y)\n where\n tol = 1e-10\n\nwithinTol :: (Mag a, V.Unbox a) => V.Vector a -> V.Vector a -> Bool\nwithinTol a b\n | V.length a /= V.length b = False\n | otherwise = V.and $ V.zipWith close a b\n\n\n---------------------\n-- The actual properties\n\n-- Test whether the inverse actually inverts the forward transform.\nprop_invert f g a = let\n p1 = plan f (V.length a)\n p2 = plan g (V.length a)\n in (V.length a > 1) ==> withinTol a $ execute p2 $ execute p1 a\n\n-- Test whether the transform preserves the L2 (sum-of-squares) norm.\nprop_orthog f a = let\n p1 = plan f (V.length a)\n in (V.length a > 1) ==> close (norm2 a) (norm2 $ execute p1 a)\n\ndata DimsAndValues a = DimsAndValues (VS.Vector Int) (V.Vector a)\n deriving (Show)\n\ninstance (Arbitrary a, V.Unbox a) => Arbitrary (DimsAndValues a) where\n arbitrary = do\n dims <- liftM (VS.fromList . map getPositive) arbitrary `suchThatMap` maybeReduceSize\n values <- V.replicateM (VS.product dims) arbitrary\n return (DimsAndValues dims values)\n where\n -- We use this to prevent test cases from growing too big\n maybeReduceSize ds =\n if VS.product ds < 1000 then Just ds else maybeReduceSize (VS.init ds)\n\nprop_invertND f g (DimsAndValues ds a) = let\n p1 = planND f ds\n p2 = planND g ds\n in (V.length a > 1) ==> withinTol a $ execute p2 $ execute p1 a\n\nprop_orthogND f (DimsAndValues ds a) = let\n p1 = planND f ds\n in (V.length a > 1) ==> close (norm2 a) (norm2 $ execute p1 a)\n\nnorm2 a = sqrt $ V.sum $ V.map (\\x -> x*x) $ V.map mag a\n", "meta": {"hexsha": "5c9ce1d167c6a5b4f627fb7a50f7d7f9323323ff", "size": 5255, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/FFTProperties.hs", "max_stars_repo_name": "TravisWhitaker/vector-fftw", "max_stars_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-12-02T12:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T17:52:00.000Z", "max_issues_repo_path": "tests/FFTProperties.hs", "max_issues_repo_name": "TravisWhitaker/vector-fftw", "max_issues_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-06-16T18:17:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-14T19:29:13.000Z", "max_forks_repo_path": "tests/FFTProperties.hs", "max_forks_repo_name": "TravisWhitaker/vector-fftw", "max_forks_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-08-29T13:35:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T23:04:18.000Z", "avg_line_length": 40.1145038168, "max_line_length": 89, "alphanum_fraction": 0.6093244529, "num_tokens": 1490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5694655844335033}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}\n\nmodule Math.Regression.Regression where\n\nimport qualified Math.HMatrixUtils as HU\n\nimport qualified Colonnade as C\n\nimport qualified Data.List as List\nimport qualified Data.Text as T\nimport qualified Data.Vector.Storable as V\nimport qualified Lucid as LH\nimport qualified Lucid.Colonnade as LC\nimport qualified Statistics.Distribution as S\nimport qualified Statistics.Distribution.FDistribution\n as S\nimport qualified Statistics.Distribution.StudentT\n as S\nimport qualified Statistics.Types as S\nimport qualified Text.Blaze.Colonnade as BC\nimport qualified Text.Blaze.Html5 as BH\nimport qualified Text.Blaze.Html5.Attributes as BHA\nimport qualified Text.Printf as TP\n\n\nimport Numeric.LinearAlgebra ( (#>)\n , (<.>)\n )\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Data ( Matrix\n , R\n , Vector\n )\nimport qualified Say\n-- NB: for normal errors, we will request the ci and get it. For interval errors, we may request it but we can't produce\n-- what we request, we can only produce what we have. So we make an interface for both. We take CL as input to predict\n-- *and* return it as output, in the prediction.\n\nclass Predictor e a b p where\n predict :: p -> b -> S.Estimate e a -- do we need a predict :: (b, b) -> (a, a) for uncertain inputs?\n\npredictFromEstimateAtConfidence\n :: (RealFrac a, Predictor S.NormalErr a b p)\n => Double\n -> p\n -> S.CL Double\n -> b\n -> (a, a)\npredictFromEstimateAtConfidence dof p cl b =\n let\n S.Estimate pt (S.NormalErr sigma) = predict p b\n prob =\n S.confidenceLevel $ S.mkCLFromSignificance (S.significanceLevel cl / 2)\n predCI =\n 2 * S.quantile (S.studentTUnstandardized dof 0 (realToFrac sigma)) prob\n in\n (pt, realToFrac predCI)\n\ndata RegressionResult a = RegressionResult\n {\n parameterEstimates :: [S.Estimate S.NormalErr a]\n , degreesOfFreedom :: Double -- since N may be an effective N\n , meanSquaredError :: a\n , rSquared :: Double\n , adjRSquared :: Double\n , fStatistic :: Maybe Double -- we can't compute this for fits with one parameter\n , covariances :: Matrix Double\n } deriving (Show)\n\ninstance (LA.Element a, LA.Numeric a, RealFloat a) => Predictor S.NormalErr a (Vector a) (RegressionResult a) where\n predict rr va =\n let mse = meanSquaredError rr\n sigmaPred = sqrt (mse + va <.> (LA.cmap realToFrac (covariances rr) #> va))\n prediction = va LA.<.> V.fromList (S.estPoint <$> parameterEstimates rr)\n in S.estimateNormErr prediction sigmaPred\n\ndata NamedEstimate a = NamedEstimate { regressorName :: T.Text, regressorEstimate :: a, regressorCI :: a, regressorPValue :: a }\n\nnamedEstimates :: [T.Text] -> RegressionResult R -> S.CL R -> [NamedEstimate R]\nnamedEstimates pNames res cl =\n let prob = S.confidenceLevel\n $ S.mkCLFromSignificance (S.significanceLevel cl / 2)\n dof = degreesOfFreedom res\n sigma e = S.normalError $ S.estError e\n dist e = S.studentTUnstandardized dof 0 (sigma e)\n ci e = 2 * S.quantile (dist e) prob\n pValue e = S.complCumulative (dist e) (abs $ S.estPoint e)\n in List.zipWith (\\n e -> NamedEstimate n (S.estPoint e) (ci e) (pValue e))\n pNames\n (parameterEstimates res)\n\nnamedEstimatesColonnade\n :: S.CL R -> C.Colonnade C.Headed (NamedEstimate R) T.Text\nnamedEstimatesColonnade cl =\n C.headed \"parameter\" regressorName\n <> C.headed \"estimate\" (T.pack . TP.printf \"%4.3f\" . regressorEstimate)\n <> C.headed\n ( T.pack (TP.printf \"%.0f\" (100 * S.confidenceLevel cl))\n <> \"% confidence\"\n )\n (T.pack . TP.printf \"%4.3f\" . regressorCI)\n <> C.headed \"p-value\" (T.pack . TP.printf \"%4.3f\" . regressorPValue)\n\nnamedSummaryStats :: RegressionResult R -> [(T.Text, T.Text)]\nnamedSummaryStats r =\n let\n p = List.length (parameterEstimates r)\n effN = degreesOfFreedom r + realToFrac p\n d1 = realToFrac $ p - 1\n d2 = effN - realToFrac p\n pValM = fmap (S.complCumulative (S.fDistributionReal d1 d2)) (fStatistic r)\n printNum = T.pack . TP.printf \"%4.3f\"\n printMaybeNum = maybe \"N/A\" printNum\n in\n [ (\"R-Squared\" , printNum (rSquared r))\n , (\"Adj. R-squared\" , printNum (adjRSquared r))\n , (\"F-stat\" , printMaybeNum (fStatistic r))\n , (\"p-value\" , printMaybeNum pValM)\n , (\"Mean Squared Error\", printNum (meanSquaredError r))\n ]\n\nnamedSummaryStatsColonnade :: C.Colonnade C.Headed (T.Text, T.Text) T.Text\nnamedSummaryStatsColonnade =\n C.headed \"Summary Stat.\" fst <> C.headed \"Value\" snd\n\nprettyPrintRegressionResult\n :: T.Text -> [T.Text] -> RegressionResult R -> S.CL R -> T.Text\nprettyPrintRegressionResult header xNames r cl =\n let nEsts = namedEstimates xNames r cl\n nSS = namedSummaryStats r\n in header\n <> \"\\n\"\n <> T.pack (C.ascii (T.unpack <$> namedEstimatesColonnade cl) nEsts)\n <> T.pack (C.ascii (fmap T.unpack namedSummaryStatsColonnade) nSS)\n\nprettyPrintRegressionResultLucid\n :: T.Text -> [T.Text] -> RegressionResult R -> S.CL R -> LH.Html ()\nprettyPrintRegressionResultLucid header xNames r cl = do\n let nEsts = namedEstimates xNames r cl\n nSS = namedSummaryStats r\n toCell t = LC.Cell [LH.style_ \"border: 1px solid black\"] (LH.toHtmlRaw t)\n LH.div_\n [ LH.style_\n \"display: inline-block; padding: 7px; border-collapse: collapse\"\n ]\n $ do\n LH.span_ (LH.toHtmlRaw header)\n LC.encodeCellTable\n [LH.style_ \"border: 1px solid black; border-collapse: collapse\"]\n (toCell <$> namedEstimatesColonnade cl)\n nEsts\n LC.encodeCellTable\n [LH.style_ \"border: 1px solid black; border-collapse: collapse\"]\n (fmap toCell namedSummaryStatsColonnade)\n nSS\n\nprettyPrintRegressionResultBlaze\n :: T.Text -> [T.Text] -> RegressionResult R -> S.CL R -> BH.Html\nprettyPrintRegressionResultBlaze header xNames r cl = do\n let nEsts = namedEstimates xNames r cl\n nSS = namedSummaryStats r\n toCell t = BC.Cell (BHA.style \"border: 1px solid black\") (BH.toHtml t)\n BH.div\n BH.! BHA.style\n \"display: inline-block; padding: 7px; border-collapse: collapse\"\n $ do\n BH.span (BH.toHtml header)\n BC.encodeCellTable\n (BHA.style \"border: 1px solid black; border-collapse: collapse\")\n (toCell <$> namedEstimatesColonnade cl)\n nEsts\n BC.encodeCellTable\n (BHA.style \"border: 1px solid black; border-collapse: collapse\")\n (fmap toCell namedSummaryStatsColonnade)\n nSS\n\n\ndata FitStatistics a = FitStatistics { fsRSquared :: a, fsAdjRSquared :: a, fsFStatistic :: Maybe a}\n\ngoodnessOfFit\n :: MonadIO m\n => Int\n -> Vector R\n -> Maybe (Vector R)\n -> Vector R\n -> m (FitStatistics R)\ngoodnessOfFit pInt vB vWM vU = do\n let\n n = LA.size vB\n p = realToFrac pInt\n vW = maybe (V.fromList $ List.replicate n (1.0 / realToFrac n))\n (\\v -> LA.scale (1 / realToFrac (LA.sumElements v)) v)\n vWM\n mW = LA.diag vW\n vWB = mW #> vB\n-- vWU = mW #> vU\n meanWB = LA.sumElements vWB\n effN = 1 / (vW <.> vW)\n ssTot = let x = LA.cmap (\\y -> y - meanWB) vB in x <.> (mW #> x)\n ssRes = vU <.> (mW #> vU) -- weighted ssq of residuals\n rSq = 1 - (ssRes / ssTot)\n arSq =\n 1 - (1 - rSq) * realToFrac (effN - 1) / realToFrac (effN - p - 1)\n fStatM = if pInt > 1\n then Just (((ssTot - ssRes) / (p - 1.0)) / (ssRes / (effN - p)))\n else Nothing\n Say.say $ \"n=\" <> show n\n Say.say $ \"p=\" <> show p\n-- Log.log Log.Diagnostic $ \"vW=\" <> show vW\n Say.say $ \"effN=\" <> show effN\n Say.say $ \"ssTot=\" <> show ssTot\n Say.say $ \"ssRes=\" <> show ssRes\n return $ FitStatistics rSq arSq fStatM\n\nestimates :: Matrix R -> Vector R -> [S.Estimate S.NormalErr R]\nestimates cov means =\n let sigmas = LA.cmap sqrt (LA.takeDiag cov)\n in List.zipWith S.estimateNormErr\n (LA.toList means)\n (LA.toList sigmas)\n\neickerHeteroscedasticityEstimator\n :: MonadIO m\n => Matrix R\n -> Vector R\n -> Vector R\n -> m (Matrix R)\neickerHeteroscedasticityEstimator mA vB vB' = do\n HU.checkVectorMatrix \"b\" \"A\" vB mA\n HU.checkVectorMatrix \"b'\" \"A\" vB' mA\n let u = vB - vB'\n diagU = LA.diag $ V.zipWith (*) u u\n mA' = LA.tr mA\n mC = LA.inv (mA' LA.<> mA)\n return $ mC LA.<> (mA' LA.<> diagU LA.<> mA) LA.<> mC\n", "meta": {"hexsha": "920addac19a94eaf02ac395683e934e9e0f9944b", "size": 9686, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Regression/Regression.hs", "max_stars_repo_name": "adamConnerSax/Frames-utils", "max_stars_repo_head_hexsha": "a8b6f9acf35948b98b01e850c847ab4f7cba7dd0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-01-17T21:51:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T08:20:19.000Z", "max_issues_repo_path": "src/Math/Regression/Regression.hs", "max_issues_repo_name": "adamConnerSax/Frames-utils", "max_issues_repo_head_hexsha": "a8b6f9acf35948b98b01e850c847ab4f7cba7dd0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-22T13:50:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T13:50:50.000Z", "max_forks_repo_path": "src/Math/Regression/Regression.hs", "max_forks_repo_name": "adamConnerSax/Frames-utils", "max_forks_repo_head_hexsha": "a8b6f9acf35948b98b01e850c847ab4f7cba7dd0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-04T12:49:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T11:25:11.000Z", "avg_line_length": 39.5346938776, "max_line_length": 128, "alphanum_fraction": 0.585484204, "num_tokens": 2650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.6370307806984445, "lm_q1q2_score": 0.5690655955817316}} {"text": "module Model where\n\nimport Control.Monad.State.Strict\n--import Control.Monad.State\nimport System.Random (StdGen, mkStdGen, randomRs)\nimport Numeric.LinearAlgebra (Matrix(..), (><), toLists)\n\ntype Ising = State IsingState\ntype Spin = Double\ntype Model = Matrix Spin\n\ndata IsingState = IsingState\n { dim :: Int\n , j :: Double\n , h :: Double\n , step :: Int\n , nAccept :: Int\n , propFreq :: Int\n , model :: Model\n , rng :: StdGen\n }\n\ninstance Show IsingState where\n show state =\n \"IsingState { d = \" ++ show (dim state)\n ++ \", j = \" ++ show (j state)\n ++ \", step = \" ++ show (step state)\n ++ \", accept = \" ++ show (nAccept state)\n ++ \", rng = \" ++ show (rng state)\n ++ \" }\"\n ++ showModel (model state)\n\nshowModel :: Model -> String\nshowModel m =\n let rows = toLists m\n showRow r = \"|\" ++ foldl (\\acc s -> acc ++ showSpin s) \"\" r ++ \"|\"\n showSpin s = if s == -1 then \" \" else \"*\"\n stringRows = map showRow rows\n in foldl (\\acc r -> acc ++ \"\\n\" ++ r) \"\" stringRows\n\nnewModel :: Int -> Int -> Double -> [Int] -> IsingState\nnewModel seed n j spins =\n let rng = mkStdGen seed\n model = (n> IsingState -> IsingState\nsetPropertyFreq f model = model { propFreq = f }\n\nsetH :: Double -> IsingState -> IsingState\nsetH h model = model { h = h }\n", "meta": {"hexsha": "b50145c2aae79eab17be251e5b4c5bfe23fc5f04", "size": 1863, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Model.hs", "max_stars_repo_name": "stnma7e/ising", "max_stars_repo_head_hexsha": "f980aefc5674976e212706569050b1fc80bec934", "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/Model.hs", "max_issues_repo_name": "stnma7e/ising", "max_issues_repo_head_hexsha": "f980aefc5674976e212706569050b1fc80bec934", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Model.hs", "max_forks_repo_name": "stnma7e/ising", "max_forks_repo_head_hexsha": "f980aefc5674976e212706569050b1fc80bec934", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 74, "alphanum_fraction": 0.5276435856, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5689977754157204}} {"text": "module Cas.QuickCheckTest where\n\nimport Test.QuickCheck\nimport Test.QuickCheck.Gen\nimport Test.QuickCheck.Random\nimport Control.Monad\nimport Data.Ratio\nimport PreludeCustom\nimport Cas.Interface\nimport Data.Complex.Generic\n\ninstance Arbitrary C where\n arbitrary = oneof [return Pi, return E]\n\ninstance Arbitrary T where\n arbitrary = sized genT\n\nchooseQ :: Gen Rational\nchooseQ = liftM2 (%) (choose (-1,1)) (choose (1,2))\n\n\nmaxTestCnt = 20000\nmaxDepth =13\nscaleFactor = 2 -- maxTestCnt `div` 2^maxDepth + 1\n\ngenT, scaledGenT :: Int -> Gen T\ngenT n = scaledGenT $ n `div` scaleFactor\n\nscaledGenT 0 = oneof [\n liftM f $ liftM2 (:+) chooseQ chooseQ\n , liftM x $ choose (0,1)\n , liftM TC arbitrary\n ]\nscaledGenT n = do\n k <- choose (2,5)\n oneof [\n liftM add $ vectorOf k rec\n , liftM mul $ vectorOf k rec\n , liftM2 pow rec rec\n , liftM ln rec\n ]\n where\n rec = scaledGenT =<< choose (0, n `div` 2)\n\n", "meta": {"hexsha": "6abc6108b713a9c12a0518d406dabac2fe1bee12", "size": 957, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Cas/QuickCheckTest.hs", "max_stars_repo_name": "vcanadi/cas", "max_stars_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-20T22:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-20T22:42:53.000Z", "max_issues_repo_path": "src/Cas/QuickCheckTest.hs", "max_issues_repo_name": "vcanadi/cas", "max_issues_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Cas/QuickCheckTest.hs", "max_forks_repo_name": "vcanadi/cas", "max_forks_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2666666667, "max_line_length": 52, "alphanum_fraction": 0.6645768025, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.568970737984571}} {"text": "{-# LANGUAGE ParallelListComp #-}\nimport Numeric.LinearAlgebra (linearSolve, toDense, (!), flatten)\nimport Data.Monoid ((<>), Sum(..))\n\nrMesh n (ar, ac) (br, bc)\n | n < 2 = Nothing\n | any (\\x -> x < 1 || x > n) [ar, ac, br, bc] = Nothing\n | otherwise = between a b <$> voltage\n where\n a = (ac - 1) + n*(ar - 1)\n b = (bc - 1) + n*(br - 1)\n\n between x y v = abs (v ! a - v ! b)\n\n voltage = flatten <$> linearSolve matrixG current\n\n matrixG = toDense $ concat [ element row col node\n | row <- [1..n], col <- [1..n]\n | node <- [0..] ]\n\n element row col node =\n let (Sum c, elements) =\n (Sum 1, [((node, node-n), -1)]) `when` (row > 1) <>\n (Sum 1, [((node, node+n), -1)]) `when` (row < n) <>\n (Sum 1, [((node, node-1), -1)]) `when` (col > 1) <>\n (Sum 1, [((node, node+1), -1)]) `when` (col < n)\n in [((node, node), c)] <> elements\n\n x `when` p = if p then x else mempty\n\n current = toDense [ ((a, 0), -1) , ((b, 0), 1) , ((n^2-1, 0), 0) ]\n", "meta": {"hexsha": "c60e257400c2bd652e202ff8f0115174f67d0604", "size": 1078, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lang/Haskell/resistor-mesh.hs", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "lang/Haskell/resistor-mesh.hs", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Haskell/resistor-mesh.hs", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 33.6875, "max_line_length": 72, "alphanum_fraction": 0.4471243043, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5689459122991665}} {"text": "{-# LANGUAGE NamedFieldPuns, TemplateHaskell #-}\n\nmodule School.Unit.Test.Affine\n( affineTest ) where\n\nimport Control.Monad.IO.Class (liftIO)\nimport Numeric.LinearAlgebra ((><), (|>), IndexOf, Matrix, R, Vector, accum,\n fromRows, ident, size)\nimport School.TestUtils (CostFunc, diffInput, jTest, matIndexes,\n randomAffineParams, randomMatrix)\nimport School.Types.FloatEq ((~=))\nimport School.Unit.Affine\nimport School.Unit.Unit (Unit(..))\nimport School.Unit.UnitActivation (UnitActivation(..))\nimport School.Unit.UnitGradient (UnitGradient(..))\nimport School.Unit.UnitParams (UnitParams(..))\nimport School.Utils.LinearAlgebra (compareDoubleMatrix, compareDoubleVector,\n oneMatrix, zeroMatrix, zeroVector)\nimport Test.Tasty (TestTree)\nimport Test.Tasty.QuickCheck hiding ((><), scale)\nimport Test.Tasty.TH\nimport Test.QuickCheck.Monadic (assert, monadicIO, pre)\n\neps :: Double\neps = 1e-5\n\nprec :: Double\nprec = 5e-2\n\nprop_trivial_apply :: (Positive Int) -> (Positive Int) -> Property\nprop_trivial_apply (Positive bSize) (Positive fSize) = monadicIO $ do\n let affineBias = zeroVector fSize\n m <- liftIO $ randomMatrix bSize fSize\n let input = BatchActivation m\n let affineWeights = ident fSize\n let params = AffineParams { affineBias\n , affineWeights }\n let result = apply affine params input\n assert $ result ~= input\n\nrandomSetup :: Int\n -> Int\n -> Int\n -> IO (UnitParams R, UnitActivation R)\nrandomSetup bSize fSize oSize = do\n input <- randomMatrix bSize fSize\n affineParams <- randomAffineParams fSize oSize\n return ( affineParams\n , BatchActivation input\n )\n\nprop_overwrite_apply :: (Positive Int) -> (Positive Int) -> Positive Int -> Property\nprop_overwrite_apply (Positive bSize) (Positive fSize) (Positive oSize) = monadicIO $ do\n let affineWeights = zeroMatrix oSize fSize\n (params, input) <- liftIO $ randomSetup bSize fSize oSize\n let params' = params { affineWeights }\n let result = apply affine params' input\n let check = fromRows . (replicate bSize) $ affineBias params\n assert $ result ~= BatchActivation check\n\nprop_deriv_dims :: (Positive Int) -> (Positive Int) -> Positive Int -> Property\nprop_deriv_dims (Positive bSize) (Positive fSize) (Positive oSize) = monadicIO $ do\n (params, input) <- liftIO $ randomSetup bSize fSize oSize\n gradIn <- liftIO $ fmap BatchGradient $ randomMatrix bSize oSize\n let (BatchGradient gradOut, AffineParams{ affineBias, affineWeights }) = deriv affine params gradIn input\n assert $ (size gradOut == (bSize, fSize))\n && (size affineBias == oSize)\n && (size affineWeights == (oSize, fSize))\n\ntype AlterParams a = Double\n -> IndexOf a\n -> UnitParams R\n -> UnitParams R\n \ndiffBias :: UnitParams R\n -> UnitActivation R\n -> CostFunc\n -> IndexOf Vector\n -> Double\ndiffBias params input cost idx =\n (jAdd - jSub) / (2*eps) where\n outAdd = apply affine (alterBias eps idx params) input\n outSub = apply affine (alterBias (-eps) idx params) input\n jAdd = cost outAdd\n jSub = cost outSub\n\ndiffWeights :: UnitParams R\n -> UnitActivation R\n -> CostFunc\n -> IndexOf Matrix\n -> Double\ndiffWeights params input cost idx =\n (jAdd - jSub) / (2*eps) where\n outAdd = apply affine (alterWeights eps idx params) input\n outSub = apply affine (alterWeights (-eps) idx params) input\n jAdd = cost outAdd\n jSub = cost outSub\n\nalterBias :: AlterParams Vector\nalterBias change idx AffineParams{ affineBias, affineWeights } =\n let newBias = accum affineBias (+) [(idx, change)]\n in AffineParams { affineBias = newBias, affineWeights }\nalterBias _ _ _ = EmptyParams\n\nalterWeights :: AlterParams Matrix\nalterWeights change idx AffineParams{ affineBias, affineWeights } =\n let newWeights = accum affineWeights (+) [(idx, change)]\n in AffineParams { affineBias, affineWeights = newWeights }\nalterWeights _ _ _ = EmptyParams\n\nvecIndexes :: Int -> [IndexOf Vector]\nvecIndexes n = [0..n-1]\n\nprop_numerical_gradient :: (Positive Int) -> (Positive Int) -> Positive Int -> Property\nprop_numerical_gradient (Positive bSize) (Positive fSize) (Positive oSize) = monadicIO $ do\n pre $ bSize < 50 && fSize < 50 && oSize < 50\n (params, input) <- liftIO $ randomSetup bSize fSize oSize\n let idxs = matIndexes bSize fSize\n let num = map (\\idx -> diffInput affine params input eps idx)\n idxs\n let numGrad = (bSize >< fSize) num\n let inGrad = BatchGradient $ oneMatrix bSize oSize\n let (BatchGradient result, _) = deriv affine params inGrad input\n assert $ compareDoubleMatrix prec result numGrad\n\nprop_numerical_bias_deriv :: (Positive Int) -> (Positive Int) -> Positive Int -> Property\nprop_numerical_bias_deriv (Positive bSize) (Positive fSize) (Positive oSize) = (mapSize (const 10)) . monadicIO $ do\n pre $ bSize < 50 && fSize < 50 && oSize < 50\n (params, input) <- liftIO $ randomSetup bSize fSize oSize\n let idxs = vecIndexes oSize\n let num = map (\\idx -> diffBias params input jTest idx)\n idxs\n let numDeriv = oSize |> num\n let inGrad = BatchGradient $ oneMatrix bSize oSize\n let (_, AffineParams { affineBias }) = deriv affine params inGrad input\n assert $ compareDoubleVector prec affineBias numDeriv\n\nprop_numerical_weights_deriv :: (Positive Int) -> (Positive Int) -> Positive Int -> Property\nprop_numerical_weights_deriv (Positive bSize) (Positive fSize) (Positive oSize) = (mapSize (const 10)) . monadicIO $ do\n pre $ bSize < 50 && fSize < 50 && oSize < 50\n (params, input) <- liftIO $ randomSetup bSize fSize oSize\n let idxs = matIndexes oSize fSize\n let num = map (\\idx -> diffWeights params input jTest idx)\n idxs\n let numDeriv = (oSize >< fSize) num\n let inGrad = BatchGradient $ oneMatrix bSize oSize\n let (_, AffineParams { affineWeights }) = deriv affine params inGrad input\n assert $ compareDoubleMatrix prec affineWeights numDeriv\n\naffineTest :: TestTree\naffineTest = $(testGroupGenerator)\n", "meta": {"hexsha": "ccce7de212eaa71a12138aa0b32a43c47b50701e", "size": 6139, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/School/Unit/Test/Affine.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/School/Unit/Test/Affine.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/School/Unit/Test/Affine.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3881578947, "max_line_length": 119, "alphanum_fraction": 0.6882228376, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5688936479786778}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n-- |\n-- Orphan instances for common data types\nmodule Tests.Orphanage where\n\nimport Control.Applicative\nimport Statistics.Distribution.Beta (BetaDistribution, betaDistr)\nimport Statistics.Distribution.Binomial (BinomialDistribution, binomial)\nimport Statistics.Distribution.CauchyLorentz\nimport Statistics.Distribution.ChiSquared (ChiSquared, chiSquared)\nimport Statistics.Distribution.Exponential (ExponentialDistribution, exponential)\nimport Statistics.Distribution.FDistribution (FDistribution, fDistribution)\nimport Statistics.Distribution.Gamma (GammaDistribution, gammaDistr)\nimport Statistics.Distribution.Geometric\nimport Statistics.Distribution.Hypergeometric\nimport Statistics.Distribution.Laplace (LaplaceDistribution, laplace)\nimport Statistics.Distribution.Lognormal (LognormalDistribution, lognormalDistr)\nimport Statistics.Distribution.Normal (NormalDistribution, normalDistr)\nimport Statistics.Distribution.Poisson (PoissonDistribution, poisson)\nimport Statistics.Distribution.StudentT\nimport Statistics.Distribution.Transform (LinearTransform, scaleAround)\nimport Statistics.Distribution.Uniform (UniformDistribution, uniformDistr)\nimport Statistics.Distribution.Weibull (WeibullDistribution, weibullDistr)\nimport Statistics.Distribution.DiscreteUniform (DiscreteUniform, discreteUniformAB)\nimport Statistics.Types\n\nimport Test.QuickCheck as QC\n\n\n----------------------------------------------------------------\n-- Arbitrary instances for ditributions\n----------------------------------------------------------------\n\ninstance QC.Arbitrary BinomialDistribution where\n arbitrary = binomial <$> QC.choose (1,100) <*> QC.choose (0,1)\ninstance QC.Arbitrary ExponentialDistribution where\n arbitrary = exponential <$> QC.choose (0,100)\ninstance QC.Arbitrary LaplaceDistribution where\n arbitrary = laplace <$> QC.choose (-10,10) <*> QC.choose (0, 2)\ninstance QC.Arbitrary GammaDistribution where\n arbitrary = gammaDistr <$> QC.choose (0.1,10) <*> QC.choose (0.1,10)\ninstance QC.Arbitrary BetaDistribution where\n arbitrary = betaDistr <$> QC.choose (1e-3,10) <*> QC.choose (1e-3,10)\ninstance QC.Arbitrary GeometricDistribution where\n arbitrary = geometric <$> QC.choose (0,1)\ninstance QC.Arbitrary GeometricDistribution0 where\n arbitrary = geometric0 <$> QC.choose (0,1)\ninstance QC.Arbitrary HypergeometricDistribution where\n arbitrary = do l <- QC.choose (1,20)\n m <- QC.choose (0,l)\n k <- QC.choose (1,l)\n return $ hypergeometric m l k\ninstance QC.Arbitrary LognormalDistribution where\n -- can't choose sigma too big, otherwise goes outside of double-float limit\n arbitrary = lognormalDistr <$> QC.choose (-100,100) <*> QC.choose (1e-10, 20)\ninstance QC.Arbitrary NormalDistribution where\n arbitrary = normalDistr <$> QC.choose (-100,100) <*> QC.choose (1e-3, 1e3)\ninstance QC.Arbitrary PoissonDistribution where\n arbitrary = poisson <$> QC.choose (0,1)\ninstance QC.Arbitrary ChiSquared where\n arbitrary = chiSquared <$> QC.choose (1,100)\ninstance QC.Arbitrary UniformDistribution where\n arbitrary = do a <- QC.arbitrary\n b <- QC.arbitrary `suchThat` (/= a)\n return $ uniformDistr a b\ninstance QC.Arbitrary WeibullDistribution where\n arbitrary = weibullDistr <$> QC.choose (1e-3,1e3) <*> QC.choose (1e-3, 1e3)\ninstance QC.Arbitrary CauchyDistribution where\n arbitrary = cauchyDistribution\n <$> arbitrary\n <*> ((abs <$> arbitrary) `suchThat` (> 0))\ninstance QC.Arbitrary StudentT where\n arbitrary = studentT <$> ((abs <$> arbitrary) `suchThat` (>0))\ninstance QC.Arbitrary d => QC.Arbitrary (LinearTransform d) where\n arbitrary = do\n m <- QC.choose (-10,10)\n s <- QC.choose (1e-1,1e1)\n d <- arbitrary\n return $ scaleAround m s d\ninstance QC.Arbitrary FDistribution where\n arbitrary = fDistribution\n <$> ((abs <$> arbitrary) `suchThat` (>0))\n <*> ((abs <$> arbitrary) `suchThat` (>0))\n\n\ninstance (Arbitrary a, Ord a, RealFrac a) => Arbitrary (PValue a) where\n arbitrary = do\n (_::Int,x) <- properFraction <$> arbitrary\n return $ mkPValue $ abs x\n\ninstance (Arbitrary a, Ord a, RealFrac a) => Arbitrary (CL a) where\n arbitrary = do\n (_::Int,x) <- properFraction <$> arbitrary\n return $ mkCLFromSignificance $ abs x\n\ninstance Arbitrary a => Arbitrary (NormalErr a) where\n arbitrary = NormalErr <$> arbitrary\n\ninstance Arbitrary a => Arbitrary (ConfInt a) where\n arbitrary = liftA3 ConfInt arbitrary arbitrary arbitrary\n\ninstance (Arbitrary (e a), Arbitrary a) => Arbitrary (Estimate e a) where\n arbitrary = liftA2 Estimate arbitrary arbitrary\n\ninstance (Arbitrary a) => Arbitrary (UpperLimit a) where\n arbitrary = liftA2 UpperLimit arbitrary arbitrary\n\ninstance (Arbitrary a) => Arbitrary (LowerLimit a) where\n arbitrary = liftA2 LowerLimit arbitrary arbitrary\n\ninstance QC.Arbitrary DiscreteUniform where\n arbitrary = discreteUniformAB <$> QC.choose (1,1000) <*> QC.choose(1,1000)\n", "meta": {"hexsha": "48d3c04d00836ba110c7cadb68cc6c5883a5e41e", "size": 5183, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Tests/Orphanage.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "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": "tests/Tests/Orphanage.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Tests/Orphanage.hs", "max_forks_repo_name": "infinity0/statistics", "max_forks_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "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": 45.0695652174, "max_line_length": 86, "alphanum_fraction": 0.710978198, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5688936371668228}} {"text": "\nmodule Statistics.Covariance.Shrinkage.Strimmer (\n psmallSVD\n , nsmallSVD\n , posSVD\n , covShrink\n , corShrink\n , corCoef\n , varShrink\n , varCoef\n ) where\n\nimport Numeric.LinearAlgebra hiding ((<>))\nimport Numeric.Sum (kbn, sumVector)\nimport Statistics.Quantile (quantile, s)\nimport qualified Data.Vector.Storable as VS\n\ncovShrink :: Matrix Double -> Herm Double\ncovShrink x = trustSym $ (asColumn sc * unSym c) * asRow sc\n where\n sc = sqrt $ varShrink x\n c = corShrink x\n\npsmallSVD :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double)\npsmallSVD x = (u', d', v')\n where\n b = unSym $ mTm x\n (_, d, v) = svd b\n tol = 1e-6\n positive = find (> tol) d\n u' = (x <> v') * asRow (recip d')\n d' = sqrt . vector $ map (atIndex d) positive\n v' = v \u00bf positive\n\nnsmallSVD :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double)\nnsmallSVD x = (u', d', v')\n where\n b = unSym $ mTm (tr x)\n (u, d, _) = svd b\n tol = 1e-6\n positive = find (> tol) d\n u' = u \u00bf positive\n d' = sqrt . vector $ map (atIndex d) positive\n v' = (tr x <> u') * asRow (recip d')\n\nposSVD :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double)\nposSVD x = (u', d', v')\n where\n (u, d, v) = svd x\n tol = 1e-6\n positive = find (> tol) d\n u' = u \u00bf positive\n d' = vector $ map (atIndex d) positive\n v' = v \u00bf positive\n\nfastSVD :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double)\nfastSVD x\n | n > edgeRatio * p = psmallSVD x\n | edgeRatio * n < p = nsmallSVD x\n | otherwise = posSVD x\n where\n edgeRatio = 2\n n = rows x\n p = cols x\n\nmpower :: Herm Double -> Double -> Herm Double\nmpower x p = trustSym $ (evec * asRow (cmap exp $ scale p (cmap log eval))) <> tr evec\n where (eval, evec) = eigSH x\n\ncorShrink :: Matrix Double -> Herm Double\ncorShrink x\n | lambda == 1 || alpha == 0 = trustSym $ ident p\n | alpha == 1 = unitDiag $ scale (1 - lambda) r0\n | lambda == 0 = unitDiag . trustSym $ svdxsV <> unSym (mpower c2 alpha) <> tr svdxsV\n | otherwise = unitDiag . trustSym . scale (exp (alpha * log lambda)) $ ident p - (svdxsV <> f <> tr svdxsV)\n where\n unitDiag :: Herm Double -> Herm Double\n unitDiag powr = trustSym (diag (1 - takeDiag (unSym powr))) `add` powr\n n = rows x\n p = cols x\n alpha = 1 :: Double\n w2 = recip $ fromIntegral n -- w = 1 / n => sum(w^2) = 1 / n\n h1 = 1 / (1 - w2)\n xs = let (u, v) = meanCov x in (x - asRow u) / asRow (sqrt (takeDiag (unSym v)))\n lambda = corCoef x\n r0 = scale h1 $ mTm (xs / sqrt (fromIntegral n))\n (svdxsU, svdxsS, svdxsV) = fastSVD xs\n m = size svdxsS\n utwu = tr svdxsU <> svdxsU / fromIntegral n\n c0 = utwu * asRow svdxsS * asColumn svdxsS\n c1 = scale ((1 - lambda) * h1) c0\n c2 = sym c1\n f = ident m - unSym (mpower (trustSym $ unSym (scale (recip lambda) c2) + ident m) alpha)\n\ncorCoef :: Matrix Double -> Double\ncorCoef x\n | denominator == 0 = 1\n | otherwise = numerator / denominator * h1w2\n where\n n = rows x\n p = cols x\n xs = let (u, v) = meanCov x in (x - asRow u) / asRow (sqrt (takeDiag (unSym v)))\n w2 = recip $ fromIntegral n\n h1w2 = w2 / (1 - w2)\n sw = sqrt . recip $ fromIntegral n\n xsw = scale sw xs\n (xswsvdU, xswsvdS, xswsvdV) = fastSVD xsw\n colSums = vector . map (sumVector kbn) . toColumns\n -- colCumSums = fromColumns . map (VS.postscanl (+) 0) . toColumns\n rowCumSums = fromRows . map (VS.postscanl (+) 0) . toRows\n sE2R = sumVector kbn (flatten (xsw * ((xswsvdU * asRow (cb xswsvdS)) <> tr xswsvdV)))\n - sumVector kbn (sq (colSums (sq xsw)))\n xs2w = scale sw $ sq xs\n sER2 = 2 * (sumVector kbn . flatten\n $ fliprl (takeColumns (p - 1) xs2w) * (rowCumSums . fliprl $ dropColumns 1 xs2w))\n denominator = sE2R\n numerator = sER2 - sE2R\n\nvarShrink :: Matrix Double -> Vector Double\nvarShrink x = scalar (lambda * target) + scale (1 - lambda) v\n where\n lambda = varCoef x\n v = takeDiag . unSym . snd $ meanCov x\n target = quantile s 1 2 v\n\nvarCoef :: Matrix Double -> Double\nvarCoef x\n | denominator == 0 = 1\n | otherwise = max 0 . min 1 $ numerator / denominator * h1w2\n where\n n = rows x\n w2 = recip (fromIntegral n)\n h1 = 1 / (1 - w2)\n h1w2 = w2 / (1 - w2)\n xc = x - asRow (fst (meanCov x))\n v = scale h1 q1\n target = quantile s 1 2 v\n zz = xc * xc\n q1 = fst $ meanCov zz\n q2 = fst (meanCov (zz * zz) ) - q1 * q1\n numerator = sumVector kbn q2\n denominator = sumVector kbn . sq $ q1 - scalar (target / h1)\n\nsq, cb :: Num a => a -> a\nsq a = a * a\ncb a = a * sq a\n", "meta": {"hexsha": "6b7046838e503d45ffd10bd96664d6715c5f0c5f", "size": 4582, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Covariance/Shrinkage/Strimmer.hs", "max_stars_repo_name": "tsbattman/coviest", "max_stars_repo_head_hexsha": "20dd81ca77567dd146a3cb17be7b87e24d9f10b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/Covariance/Shrinkage/Strimmer.hs", "max_issues_repo_name": "tsbattman/coviest", "max_issues_repo_head_hexsha": "20dd81ca77567dd146a3cb17be7b87e24d9f10b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Covariance/Shrinkage/Strimmer.hs", "max_forks_repo_name": "tsbattman/coviest", "max_forks_repo_head_hexsha": "20dd81ca77567dd146a3cb17be7b87e24d9f10b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1700680272, "max_line_length": 109, "alphanum_fraction": 0.596464426, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5688717606743061}} {"text": "import Criterion.Main\nimport qualified Data.Vector.Unboxed as U\nimport Numeric.SpecFunctions\nimport Numeric.Polynomial\nimport Text.Printf\n\n-- Uniformly sample logGamma performance between 10^-6 to 10^6\nbenchmarkLogGamma logG =\n [ bench (printf \"%.3g\" x) $ nf logG x\n | x <- [ m * 10**n | n <- [ -8 .. 8 ]\n , m <- [ 10**(i / tics) | i <- [0 .. tics-1] ]\n ]\n ]\n where tics = 3\n{-# INLINE benchmarkLogGamma #-}\n\n\n-- Power of polynomial to be evaluated (In other words length of coefficients vector)\ncoef_size :: [Int]\ncoef_size = [ 1,2,3,4,5,6,7,8,9\n , 10, 30\n , 100, 300\n , 1000, 3000\n , 10000, 30000\n ]\n{-# INLINE coef_size #-}\n\n-- Precalculated coefficients\ncoef_list :: [U.Vector Double]\ncoef_list = [ U.replicate n 1.2 | n <- coef_size]\n{-# NOINLINE coef_list #-}\n\n\n\nmain :: IO ()\nmain = defaultMain\n [ bgroup \"logGamma\" $\n benchmarkLogGamma logGamma\n , bgroup \"logGammaL\" $\n benchmarkLogGamma logGammaL\n , bgroup \"incompleteGamma\" $\n [ bench (show p) $ nf (incompleteGamma p) p\n | p <- [ 0.1\n , 1, 3\n , 10, 30\n , 100, 300\n , 999, 1000\n ]\n ]\n , bgroup \"factorial\"\n [ bench (show n) $ nf factorial n\n | n <- [ 0, 1, 3, 6, 9, 11, 15\n , 20, 30, 40, 50, 60, 70, 80, 90, 100\n ]\n ]\n , bgroup \"incompleteBeta\"\n [ bench (show (p,q,x)) $ nf (incompleteBeta p q) x\n | (p,q,x) <- [ (10, 10, 0.5)\n , (101, 101, 0.5)\n , (1010, 1010, 0.5)\n , (10100, 10100, 0.5)\n , (100100, 100100, 0.5)\n , (1001000, 1001000, 0.5)\n , (10010000,10010000,0.5)\n ]\n ]\n , bgroup \"log1p\"\n [ bench (show x) $ nf log1p x\n | x <- [ -0.9\n , -0.5\n , -0.1\n , 0.1\n , 0.5\n , 1\n , 10\n , 100\n ]\n ]\n , bgroup \"poly\"\n $ [ bench (\"vector_\"++show (U.length coefs)) $ nf (\\x -> evaluatePolynomial x coefs) (1 :: Double)\n | coefs <- coef_list ]\n ++ [ bench (\"unpacked_\"++show n) $ nf (\\x -> evaluatePolynomialL x (map fromIntegral [1..n])) (1 :: Double)\n | n <- coef_size ]\n ]\n", "meta": {"hexsha": "7960dcd81f955bd8f74a4692a6b3819ace2f0668", "size": 2334, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmark/bench.hs", "max_stars_repo_name": "chris-taylor/math-functions", "max_stars_repo_head_hexsha": "5e29b31604985fef29024983909b9fca7b220e1f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-10T04:21:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-10T04:21:02.000Z", "max_issues_repo_path": "benchmark/bench.hs", "max_issues_repo_name": "chris-taylor/math-functions", "max_issues_repo_head_hexsha": "5e29b31604985fef29024983909b9fca7b220e1f", "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": "benchmark/bench.hs", "max_forks_repo_name": "chris-taylor/math-functions", "max_forks_repo_head_hexsha": "5e29b31604985fef29024983909b9fca7b220e1f", "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": 27.4588235294, "max_line_length": 113, "alphanum_fraction": 0.4661525278, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5687539188948048}} {"text": "module SongId\n( chunkIdentifier\n, findMaxFreq\n, mapChunk2Freqs\n, ft\n) where\n\nimport Debug.Trace\n\nimport Data.Array.Unboxed (elems, assocs, UArray)\nimport Data.Array.IArray (Array(..), listArray, array)\nimport Data.Array.CArray (CArray)\n\nimport Data.Complex (Complex(..), magnitude)\nimport Data.Int (Int64, Int32, Int16, Int8)\nimport Math.FFT (dft)\n\nimport Data.List (sort)\n\nimport Common (importantFrequencies, breakChunks, slice)\n\nchunkIdentifier :: [(Int, Int)] -> ([Float], [Complex Float]) -> [Float]\nchunkIdentifier freqRanges (freqs, amps) =\n let breakFreqs chunk = map (flip slice chunk) freqRanges\n unzippedChunksInFrequencyRanges = map unzip $ breakFreqs $ zip freqs amps\n maxFreqsInRanges = map findMaxFreq $ unzippedChunksInFrequencyRanges\n in map fst maxFreqsInRanges\n\nfindMaxFreq :: ([Float], [Complex Float]) -> (Float, Complex Float)\nfindMaxFreq (xs, ys) = foldl (\\max@(_, maxamp) new@(_, amp) ->\n if (magnitude amp) > (magnitude maxamp)\n then new\n else max)\n (0,0) $ zip xs ys\n\nmapChunk2Freqs :: (Fractional a, Fractional b) => [a] -> ([b], [a])\nmapChunk2Freqs chunk =\n let l = length chunk\n halfOfChunk = slice (0, l `quot` 2) chunk\n amps = map (/ fromIntegral l) halfOfChunk\n\n xs1 = map fromIntegral $ [0,1..l]\n xs2 = replicate l (44100 / fromIntegral l)\n freqs = map (\\(x1,x2) -> x1 * x2) $ zip xs1 xs2\n in (freqs, amps)\n\nft :: Int -> UArray Int Int32 -> [CArray Int (Complex Float)]\nft chunkSize samples = map dft chunks\n where chunks = map (listArray (0, chunkSize - 1)) $ breakChunks chunkSize elements -- enumerate the samples in each chunk\n elements = map convertToComplex $ elems samples\n convertToComplex v = (fromIntegral v) :+ 0\n", "meta": {"hexsha": "05cfb2fd3228eee13647eeebac02f7c1e5129025", "size": 1763, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SongId.hs", "max_stars_repo_name": "stnma7e/msk", "max_stars_repo_head_hexsha": "3f0c8a5c0090da79e743ea3c1f451e1eb7fcdd8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SongId.hs", "max_issues_repo_name": "stnma7e/msk", "max_issues_repo_head_hexsha": "3f0c8a5c0090da79e743ea3c1f451e1eb7fcdd8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SongId.hs", "max_forks_repo_name": "stnma7e/msk", "max_forks_repo_head_hexsha": "3f0c8a5c0090da79e743ea3c1f451e1eb7fcdd8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9038461538, "max_line_length": 125, "alphanum_fraction": 0.6704480998, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5684721470031016}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n\nmodule Numeric.Optimization.TwoPhase.Tableau.Pivot\n ( index\n , allCells\n , pivot\n ) where\n\nimport Data.Finite (Finite)\nimport GHC.TypeLits (KnownNat)\nimport Numeric.LinearAlgebra ((!))\nimport qualified Numeric.LinearAlgebra as LA (atIndex)\nimport Numeric.LinearAlgebra.Static (L)\nimport qualified Numeric.LinearAlgebra.Static as LS\n\n\ntype Index rows cols = (Finite rows, Finite cols)\n\n\nindex :: (KnownNat rows, KnownNat cols)\n => Index rows cols\n -> L rows cols\n -> Double\nindex (i, j) x =\n LA.atIndex (LS.unwrap x) ix\n where\n ix = (fromIntegral i, fromIntegral j)\n\n\nallCells :: (KnownNat rows, KnownNat cols)\n => (Double -> Bool)\n -> [Index rows cols]\n -> L rows cols\n -> Bool\nallCells f is x =\n all f $ fmap (`index` x) is\n\n\npivot :: (KnownNat rows, KnownNat cols)\n => (Finite rows, Finite cols) -> L rows cols -> L rows cols\npivot (x', y') table =\n LS.build (newValue $ LS.unwrap table)\n where\n (x, y) = (fromIntegral x', fromIntegral y')\n\n newValue mat i' j'\n | i == x = mat!i!j / mat!x!y\n | j == y = 0\n | otherwise = mat!x!y * mat!i!j - mat!x!j * mat!i!y\n where\n (i, j) = (round i', round j')\n\n", "meta": {"hexsha": "c45f28cdb4c214c0497ba8ade793bf5bb3c44b63", "size": 1475, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Optimization/TwoPhase/Tableau/Pivot.hs", "max_stars_repo_name": "alex-mckenna/optimum", "max_stars_repo_head_hexsha": "4137cf3aa4d96b86f74eed804a0eb582c6b28501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-01-09T22:43:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T17:34:44.000Z", "max_issues_repo_path": "src/Numeric/Optimization/TwoPhase/Tableau/Pivot.hs", "max_issues_repo_name": "alex-mckenna/optimum", "max_issues_repo_head_hexsha": "4137cf3aa4d96b86f74eed804a0eb582c6b28501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Optimization/TwoPhase/Tableau/Pivot.hs", "max_forks_repo_name": "alex-mckenna/optimum", "max_forks_repo_head_hexsha": "4137cf3aa4d96b86f74eed804a0eb582c6b28501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3392857143, "max_line_length": 63, "alphanum_fraction": 0.5559322034, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5682077018519966}} {"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule Network (initNet, feedForward, sgd, forwardPass, backprop, updateMiniBatch) where\n\nimport Control.Monad\nimport Data.List.Split\nimport Numeric.LinearAlgebra as L\n\nimport MnistLoader\nimport Aux\n\nfeedForward :: Network -> Matrix Float -> Matrix Float\nfeedForward n a = foldl f a $ zip (weights n) (biases n)\n where\n f a' (w, b) = sigmoid ((w L.<> a') + b)\n\nsgd :: Network\n -> [(Matrix Float, Matrix Float)] -- traning data\n -> [(Matrix Float, Matrix Float)] -- Evaluation data\n -> Int -- Number of epochs\n -> Int -- Current Epoc\n -> Int -- Mini batch size\n -> Float -- Eta\n -> IO Network\nsgd n exemplars testData maxEpoch epoch batchSize eta = do\n exemplars' <- shuffle exemplars\n\n let batches = chunksOf batchSize exemplars'\n let newNet = foldl (\\accNet batch -> updateMiniBatch accNet batch eta) n batches\n let correct = evaluate newNet testData\n putStrLn $ \"Epoch \" ++ (show (epoch + 1)) ++ \" Eval: \" ++ (show correct) ++ \" / \" ++ (show $ length testData)\n\n if epoch == maxEpoch\n then return newNet\n else sgd newNet exemplars' testData maxEpoch (epoch + 1) batchSize eta\n\nupdateMiniBatch :: Network -> [(Matrix Float, Matrix Float)] -> Float -> Network\nupdateMiniBatch n l@((x, y) : rest) eta = let \n initAcc = backprop n x y \n nablaSums = foldl f initAcc rest\n nabla_b = map fst nablaSums\n nabla_w = map snd nablaSums\n in\n Network {\n sizes = sizes n\n , weights = zipWith wavg (weights n) nabla_w\n , biases = zipWith wavg (biases n) nabla_b\n }\n where\n f nablaSum (x, y) = let\n bp = backprop n x y\n in\n zipWith add nablaSum bp\n add (nb, nw) (nb', nw') = (nb+nb', nw+nw')\n wavg :: Matrix Float -> Matrix Float -> Matrix Float\n wavg m1 m2 = let \n nt = (1><1) [fromIntegral $ length l]\n eta' = (1><1) [eta]\n in m1 - (eta' / nt) * m2\n\n\n-- Network -> x -> y -> (nabla_b, nabla_w)\nbackprop :: Network -> Matrix Float -> Matrix Float -> [(Matrix Float, Matrix Float)]\nbackprop n x y = let\n -- Reversed list of forward passes\n ((a:a':as), (z:zs)) = forwardPass n x\n revW = foldl (\\acc w -> w:acc) [] (weights n)\n fp = zip as zs\n zippedFp = zip fp revW\n \n -- Handle last layer manually\n delta = (cost_derivative a y) * (sigmoid' z)\n nabla_b = delta\n nabla_w = delta L.<> (tr' a')\n res = foldl f [(nabla_b, nabla_w)] zippedFp\n in\n res\n where\n f (acc@((delta, _):_)) ((a, z), w) = let\n sp = sigmoid' z\n delta' = ((tr' w) L.<> delta) * sp\n nabla_b = delta'\n nabla_w = delta' L.<> (tr' a)\n in\n (nabla_b, nabla_w) : acc\n\n-- Network -> activation -> (activations, z vectors)\nforwardPass :: Network -> Matrix Float -> ([Matrix Float], [Matrix Float])\nforwardPass n a = let\n pairs = zip (weights n) (biases n)\n fp = foldl f [(a, a)] pairs\n in\n (map fst fp, init $ map snd fp)\n where\n f (l@((a, _):_)) (w, b) = let\n z = (w L.<> a) + b\n activation = sigmoid z\n in (activation, z):l\n\nevaluate :: Network -> [(Matrix Float, Matrix Float)] -> Int\nevaluate net exemplars = sum $ map f exemplars\n where\n f (x, y) = let\n approx = argMax $ feedForward net x\n actual = argMax y \n in\n if approx == actual\n then 1\n else 0\n\ncost_derivative output_activations y = output_activations - y\n\n-- Miscellaneous\nsigmoid z = 1.0 / (1.0 + (exp $ -z))\n\nsigmoid' :: Matrix Float -> Matrix Float\nsigmoid' z = (sigmoid z) * (1 - (sigmoid z))\n\nargMax :: Matrix Float -> Int\nargMax m = L.maxIndex $ L.flatten m\n\n-- assuming row-major order\ndata Network = Network { sizes :: [Int]\n , weights :: [Matrix Float]\n , biases :: [Matrix Float]\n } deriving (Show)\n\ninitNet :: [Int] -> IO (Network)\ninitNet sizes = do\n ws <- genWeights sizes\n bs <- genBiases sizes\n return Network { sizes = sizes\n , weights = ws\n , biases = bs\n }\n where\n genWeights [s, s'] =\n do\n m <- L.randn s' s\n return [L.cmap realToFrac m]\n genWeights (s:s':ss) = \n do\n rest <- genWeights (s' : ss)\n m <- L.randn s' s\n return (L.cmap realToFrac m : rest)\n genWeights _ = error \"Not enough layers\"\n genBiases [s, s'] =\n do\n m <- L.randn s' 1\n return $ [L.cmap realToFrac m]\n genBiases (s:s':ss) = \n do\n rest <- genBiases (s' : ss)\n m <- L.randn s' 1\n return (L.cmap realToFrac m : rest)\n genBiases _ = error \"Not enough layers\"", "meta": {"hexsha": "90531f762663656aba367e76ca6ab9296d54ef12", "size": 4591, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Network.hs", "max_stars_repo_name": "madsbuch/haskell-nn", "max_stars_repo_head_hexsha": "756c30da245b8f0f7e860d5624033c022d844e42", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Network.hs", "max_issues_repo_name": "madsbuch/haskell-nn", "max_issues_repo_head_hexsha": "756c30da245b8f0f7e860d5624033c022d844e42", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Network.hs", "max_forks_repo_name": "madsbuch/haskell-nn", "max_forks_repo_head_hexsha": "756c30da245b8f0f7e860d5624033c022d844e42", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6193548387, "max_line_length": 111, "alphanum_fraction": 0.5750381181, "num_tokens": 1397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5680067399713139}} {"text": "module Statistics.Information.Mixed.Entropy where\n\nimport Data.Matrix\nimport qualified Statistics.Information.Continuous.Entropy as CE\nimport qualified Statistics.Information.Discrete.Entropy as DE\nimport Statistics.Information.Mixed.MutualInfo\nimport Statistics.Information.Utils.Random\nimport System.Random\n\ncentropydc :: (RandomGen g, Eq a) => g -> Int -> Int -> Matrix a ->\n Matrix Double -> Double\ncentropydc g k base xs ys = DE.entropy base xs - midc g k base xs ys\n\ncentropycd :: (RandomGen g, Eq a) => g -> Int -> Int -> Matrix Double ->\n Matrix a -> Double\ncentropycd g k base xs ys = CE.entropy g1 k base xs - micd g2 k base xs ys where\n (g1, g2) = split g\n\nentropy :: (RandomGen g, Eq a) => g -> Int -> Int -> Matrix a ->\n Matrix Double -> Double\nentropy g k base xs ys = hx + hy - ixy\n where\n (g1, g2) = split g\n hx = DE.entropy base xs\n hy = CE.entropy g1 k base ys\n ixy = midc g2 k base xs ys", "meta": {"hexsha": "a1a1c1b1de597ea130b053303595dc6c6a4d1cd9", "size": 956, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Information/Mixed/Entropy.hs", "max_stars_repo_name": "eligottlieb/Shannon", "max_stars_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/Information/Mixed/Entropy.hs", "max_issues_repo_name": "eligottlieb/Shannon", "max_issues_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Information/Mixed/Entropy.hs", "max_forks_repo_name": "eligottlieb/Shannon", "max_forks_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7692307692, "max_line_length": 80, "alphanum_fraction": 0.6725941423, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5679544022148649}} {"text": "{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -fno-warn-name-shadowing #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}\n{-# OPTIONS_GHC -fno-warn-missing-methods #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TypeFamilies #-}\n\n-- | An extended Kalman filter. Note that this could be generalized\n-- further. If you need a Kalman filter and have a state update matrix\n-- \\(A\\) then you can just use @const bigA@ as the function which\n-- returns the Jacobian.\n\nmodule Kalman (\n extKalman\n )where\n\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra.Static hiding ( create )\nimport Data.Maybe ( fromJust )\n\n-- | The model for the extended Kalman filter is given by\n--\n-- \\[\n-- \\begin{aligned}\n-- \\boldsymbol{x}_i &= \\boldsymbol{a}(\\boldsymbol{x}_{i-1}) + \\boldsymbol{\\psi}_{i-1} \\\\\n-- \\boldsymbol{y}_i &= {H}\\boldsymbol{x}_i + \\boldsymbol{\\upsilon}_i\n-- \\end{aligned}\n-- \\]\n--\n-- where\n--\n-- * \\(\\boldsymbol{a}\\)\\ is some non-linear vector-valued state update\n-- function.\n--\n-- * \\(\\boldsymbol{\\psi}_{i}\\) are independent identically normally\n-- distributed random variables with mean 0 representing the fact that\n-- the state update is noisy: \\(\\boldsymbol{\\psi}_{i} \\sim {\\cal{N}}(0,Q)\\).\n--\n-- * \\({H}\\) is a matrix which represents how we observe the\n-- hidden state process.\n--\n-- * \\(\\boldsymbol{\\upsilon}_i\\) are independent identically normally\n-- distributed random variables with mean 0 represent the fact that\n-- the observations are noisy: \\(\\boldsymbol{\\upsilon}_{i} \\sim {\\cal{N}}(0,R)\\).\n--\n-- We assume the whole process starts at 0 with our belief of the state (aka the\n-- prior state) being given by\n-- \\(\\boldsymbol{x}_0 \\sim {\\cal{N}}(\\boldsymbol{\\mu}_0, \\Sigma_0)\\)\nextKalman :: forall m n .\n (KnownNat m, KnownNat n, (1 <=? n) ~ 'True, (1 <=? m) ~ 'True) =>\n R n -- ^ Prior mean \\(\\boldsymbol{\\mu}_0\\)\n -> Sq n -- ^ Prior variance \\(\\Sigma_0\\)\n -> L m n -- ^ Observation map \\(H\\)\n -> Sq m -- ^ Observation noise \\(R\\)\n -> (R n -> R n) -- ^ State update function \\(\\boldsymbol{a}\\)\n -> (R n -> Sq n) -- ^ A function which returns the\n -- Jacobian of the state update\n -- function at a given point\n -- \\(\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{x}}\\)\n -> Sq n -- ^ State noise \\(Q\\)\n -> [R m] -- ^ List of observations \\(\\boldsymbol{y}_i\\)\n -> [(R n, Sq n)] -- ^ List of posterior means and variances \\((\\hat{\\boldsymbol{x}}_i, \\hat{\\Sigma}_i)\\)\nextKalman muPrior sigmaPrior bigH bigSigmaY\n littleA bigABuilder bigSigmaX ys = result\n where\n result = scanl update (muPrior, sigmaPrior) ys\n\n update :: (R n, Sq n) -> R m -> (R n, Sq n)\n update (xHatFlat, bigSigmaHatFlat) y =\n (xHatFlatNew, bigSigmaHatFlatNew)\n where\n\n v :: R m\n v = y - (bigH #> xHatFlat)\n\n bigS :: Sq m\n bigS = bigH <> bigSigmaHatFlat <> (tr bigH) + bigSigmaY\n\n bigK :: L n m\n bigK = bigSigmaHatFlat <> (tr bigH) <> (inv bigS)\n\n xHat :: R n\n xHat = xHatFlat + bigK #> v\n\n bigSigmaHat :: Sq n\n bigSigmaHat = bigSigmaHatFlat - bigK <> bigS <> (tr bigK)\n\n bigA :: Sq n\n bigA = bigABuilder xHat\n\n xHatFlatNew :: R n\n xHatFlatNew = littleA xHat\n\n bigSigmaHatFlatNew :: Sq n\n bigSigmaHatFlatNew = bigA <> bigSigmaHat <> (tr bigA) + bigSigmaX\n\ninv :: (KnownNat n, (1 <=? n) ~ 'True) => Sq n -> Sq n\ninv m = fromJust $ linSolve m eye\n", "meta": {"hexsha": "d5c91e68b925dd1ebdb1c9466ab0fbf70dd58b59", "size": 3867, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Kalman.hs", "max_stars_repo_name": "idontgetoutmuch/Kalman", "max_stars_repo_head_hexsha": "619d57e980d53c43bb1675efb17c73127fa924d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2015-03-13T16:16:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T00:33:51.000Z", "max_issues_repo_path": "src/Kalman.hs", "max_issues_repo_name": "f-o-a-m/Kalman", "max_issues_repo_head_hexsha": "619d57e980d53c43bb1675efb17c73127fa924d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-31T20:04:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T20:04:27.000Z", "max_forks_repo_path": "src/Kalman.hs", "max_forks_repo_name": "f-o-a-m/Kalman", "max_forks_repo_head_hexsha": "619d57e980d53c43bb1675efb17c73127fa924d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-08-23T16:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-02T17:40:49.000Z", "avg_line_length": 37.1826923077, "max_line_length": 118, "alphanum_fraction": 0.5660718904, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5678171593255557}} {"text": "{-# LANGUAGE DataKinds #-}\n\nmodule Rotation\n ( Rotation\n , rotationMatrix\n , rotate\n , mkRotation\n , mkXYRotation\n , mkXYRotationCamera\n , rotateV\n ) where\n\nimport qualified Numeric.LinearAlgebra as L\nimport Numeric.LinearAlgebra.Static\n\nimport Matrix\n\ntype Quaternion = R 4\n\ntype Rotation = Quaternion\n\nrotate :: Quaternion -> Quaternion -> Quaternion\nq1 `rotate` q2 =\n vec4\n (r1 * r2 - i1 * i2 - j1 * j2 - k1 * k2)\n (r1 * i2 + i1 * r2 + j1 * k2 - k1 * j2)\n (r1 * j2 + j1 * r2 + k1 * i2 - i1 * k2)\n (r1 * k2 + k1 * r2 + i1 * j2 - j1 * i2)\n where\n [r1, i1, j1, k1] = L.toList . unwrap $ q1\n [r2, i2, j2, k2] = L.toList . unwrap $ q2\n\nmkRotation :: Double -> Vector3 -> Quaternion\nmkRotation angle axis =\n normalize $\n vec4\n (cos (angle / 2))\n (x * sin (angle / 2))\n (y * sin (angle / 2))\n (z * sin (angle / 2))\n where\n [x, y, z] = L.toList . unwrap $ axis\n\nrotationMatrix :: Quaternion -> Matrix4\nrotationMatrix q = eye + 2 * m\n where\n [r, i, j, k] = L.toList . unwrap $ q\n m =\n row (vec4 (-j * j - k * k) (i * j - k * r) (i * k + j * r) 0) ===\n row (vec4 (i * j + k * r) (-i * i - k * k) (j * k - i * r) 0) ===\n row (vec4 (i * k - j * r) (j * k + i * r) (-i * i - j * j) 0) ===\n row (vec4 0 0 0 0)\n\nmkXYRotationCamera x y = q2 `rotate` q1\n where\n q1 = mkRotation x yHat\n q2 = mkRotation y xHat\n\nmkXYRotation x y = q2 `rotate` q1\n where\n q1 = mkRotation y xHat\n q2 = mkRotation x yHat\n\nconj :: Quaternion -> Quaternion\nconj q = q * vec4 1 (-1) (-1) (-1)\n\nqmult = rotate\n\nrotateV :: Vector3 -> Quaternion -> Vector3\nrotateV v q = v'\n where\n (_, v') = split $ q `qmult` p `qmult` conj q\n p = vector [0] # v\n", "meta": {"hexsha": "fc22f7e884faa98924e17e3b3463b51c816acfd6", "size": 1726, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Rotation.hs", "max_stars_repo_name": "aelg/haskell-render", "max_stars_repo_head_hexsha": "c55fd2e3cfde1899b03910545b835935fef62759", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Rotation.hs", "max_issues_repo_name": "aelg/haskell-render", "max_issues_repo_head_hexsha": "c55fd2e3cfde1899b03910545b835935fef62759", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Rotation.hs", "max_forks_repo_name": "aelg/haskell-render", "max_forks_repo_head_hexsha": "c55fd2e3cfde1899b03910545b835935fef62759", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3243243243, "max_line_length": 71, "alphanum_fraction": 0.5393974508, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5678171480752717}} {"text": "{-# LANGUAGE RecordWildCards #-}\n\nmodule Data.Matrix.CSC where\n\nimport Control.Arrow (second)\nimport Control.Exception\nimport Data.Maybe\nimport qualified Data.Vector.Storable as VS\nimport qualified Data.Vector as VB\nimport Foreign.C.Types\nimport Numeric.LinearAlgebra\n\ndata CSC a = CSC\n { cscVals :: VS.Vector a\n , cscCols :: VS.Vector CInt\n , cscRows :: VS.Vector CInt\n , cscNRows :: CInt\n , cscNCols :: CInt\n } deriving (Eq, Show)\n\nfromMatrix :: (Element a, VS.Storable a, Eq a, Num a) => Matrix a -> CSC a\nfromMatrix mat = CSC{..}\n where\n cscNRows = fromIntegral $ rows mat\n cscNCols = fromIntegral $ cols mat\n cscRows = VS.fromList $ concat irs\n cscVals = VS.fromList $ concat vals\n cscCols = VS.fromList $ scanl (\\a b -> a + fromIntegral (length b)) 0 vals\n (irs, vals) = unzip $ map (go . VS.toList) (toColumns mat)\n go col = unzip $ catMaybes $ zipWith (\\idx val -> if val == 0 then Nothing else Just (fromIntegral idx, val)) [0..] col\n\ntoMatrix :: (Element a, Num a, VS.Storable a) => CSC a -> Matrix a\ntoMatrix CSC {..} = fromColumns cols\n where\n cols = zipWith go rows vals\n go rs vs = VS.replicate (fromIntegral cscNRows) 0 VS.//\n (zipWith (\\r v -> (fromIntegral r, v)) (VS.toList rs) (VS.toList vs))\n rows = split cscRows cscCols\n vals = split cscVals cscCols\n split v = snd . VS.foldr splitter (v, []) . VS.init\n where\n splitter idx (v, xs) = second (:xs) $ VS.splitAt (fromIntegral idx) v \n\n(===) :: (VS.Storable a) => CSC a -> CSC a -> CSC a\na === b = assert (cscNCols a == cscNCols b) $ CSC\n { cscNCols = cscNCols a\n , cscNRows = cscNRows a + cscNRows b\n , cscRows = rows\n , cscVals = vals\n , cscCols = cols\n }\n where\n cols = VS.zipWith (+) (cscCols a) (cscCols b)\n rows = VS.concat $ concat $\n zipWith (\\a b -> [a, b]) (split (cscRows a) (cscCols a))\n (split (VS.map (+ cscNRows a) $ cscRows b) (cscCols b))\n vals = VS.concat $ concat $\n zipWith (\\a b -> [a, b]) (split (cscVals a) (cscCols a))\n (split (cscVals b) (cscCols b))\n split v = snd . VS.foldr splitter (v, [])\n where\n splitter idx (v, xs) = second (:xs) $ VS.splitAt (fromIntegral idx) v\n\n(|||) :: (VS.Storable a) => CSC a -> CSC a -> CSC a\na ||| b = assert (cscNRows a == cscNRows b) $ CSC\n { cscNCols = cscNCols a + cscNCols b\n , cscNRows = cscNRows a\n , cscRows = cscRows a VS.++ cscRows b\n , cscVals = cscVals a VS.++ cscVals b\n , cscCols = cscCols a VS.++ (VS.map (+ VS.last (cscCols a)) $ VS.tail (cscCols b))\n }\n\ndiagBlock :: (VS.Storable a) => CSC a -> CSC a -> CSC a\ndiagBlock a b = CSC\n { cscNCols = cscNCols a + cscNCols b\n , cscNRows = cscNRows a + cscNRows b\n , cscRows = cscRows a VS.++ VS.map (+ cscNRows a) (cscRows b)\n , cscVals = cscVals a VS.++ cscVals b\n , cscCols = cscCols a VS.++ (VS.map (+ VS.last (cscCols a)) $ VS.tail (cscCols b))\n }\n\nzero :: (Integral a, VS.Storable b) => a -> a -> CSC b\nzero rows cols = CSC\n { cscNCols = fromIntegral cols\n , cscNRows = fromIntegral rows\n , cscRows = VS.empty\n , cscVals = VS.empty\n , cscCols = VS.replicate (fromIntegral cols + 1) 0\n }\n\nfromBlocks :: (VS.Storable a) => [[CSC a]] -> CSC a\nfromBlocks = foldr1 (===) . map (foldr1 (|||))\n\nscale :: (VS.Storable a, Num a) => a -> CSC a -> CSC a\nscale mult csc = csc { cscVals = VS.map (* mult) (cscVals csc) }\n", "meta": {"hexsha": "c6e3f513bea8cf5ad367ee9f18775cb990b91051", "size": 3403, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Matrix/CSC.hs", "max_stars_repo_name": "alang9/qp", "max_stars_repo_head_hexsha": "feb1705bcb47c31dabc88c69fd7897b55215cd1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/Matrix/CSC.hs", "max_issues_repo_name": "alang9/qp", "max_issues_repo_head_hexsha": "feb1705bcb47c31dabc88c69fd7897b55215cd1a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/Matrix/CSC.hs", "max_forks_repo_name": "alang9/qp", "max_forks_repo_head_hexsha": "feb1705bcb47c31dabc88c69fd7897b55215cd1a", "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.4479166667, "max_line_length": 123, "alphanum_fraction": 0.6027034969, "num_tokens": 1183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5678156845487173}} {"text": "module Newton.Render where\n\n-- this module comes from JuicyPixels package\nimport qualified Codec.Picture as J\nimport Codec.Picture.ColorQuant (defaultPaletteOptions)\nimport Data.Complex\nimport Newton.Utils (root)\n\n-- | Add brightness to an RGB8 Image\nbrightnessRGB8 :: Int -> J.Palette -> J.Palette\nbrightnessRGB8 add = J.pixelMap brightFunction\n where\n up v = fromIntegral (fromIntegral v + add)\n brightFunction (J.PixelRGB8 r g b) = J.PixelRGB8 (up r) (up g) (up b)\n\n-- | Save an PNG image as a file\nsaveBasinsPic ::\n FilePath -- ^ Where to write the image file.\n -> J.Palette\n -> IO ()\nsaveBasinsPic = J.writePng\n\nsaveBasinsAnim ::\n FilePath -- ^ Filename of an image\n -> J.GifDelay -- ^ Delay between frames\n -> [J.Palette] -- ^ List of pictures to store within the GIF\n -> IO ()\nsaveBasinsAnim path delay images =\n case J.writeGifImages path J.LoopingForever finalImgs of\n Left msg -> error msg\n Right ans -> ans\n where\n palettized = map (J.palettize defaultPaletteOptions) images\n finalImgs = map (\\(img, plt) -> (plt, delay, img)) palettized\n\n-- | Render attraction basins for zeros (roots) of a complex function\n-- as a PNG image.\nrenderBasins ::\n (Fractional a, RealFloat a)\n => Int -- ^ Size of the square image in pixels\n -> (Complex a -> Complex a) -- ^ A function f to find zero for.\n -> (Complex a -> Complex a) -- ^ A derivative of function f.\n -> (Complex a -> J.PixelRGB8) -- ^ How to color roots.\n -> J.Palette\nrenderBasins commonSize f f' color = image\n where\n image = J.generateImage render width height\n width = commonSize -- width in pixels\n height = commonSize -- height in pixels\n (xfrom, xto) = (-2, 2) -- range for the real axis\n (yfrom, yto) = (-2, 2) -- range for the imaginary axis\n -- | Convert pixel coordinates to a complex number.\n pixelToComplex (i, j) = re :+ im\n where\n re = xfrom + (xto - xfrom) * fromIntegral i / fromIntegral width\n im = yfrom + (yto - yfrom) * fromIntegral j / fromIntegral height\n n = 100 -- maximum number of iterations\n p e = magnitude e < 1e-7 -- precision tolerance\n -- | Convert actual number of interations into\n -- into a grey pixel using logarithmic scale\n -- (this helps bring out more details in the image).\n logscale :: Integral a => Int -> a -> a\n logscale k c = floor (fromIntegral c * (1 - logBase n' k'))\n where\n n' = fromIntegral n + 1\n k' = fromIntegral k + 1\n -- | Render one pixel.\n render :: Int -> Int -> J.PixelRGB8\n render i j =\n case root n p f f' (pixelToComplex (i, j)) of\n Nothing -> J.PixelRGB8 0 0 0 -- black\n Just (k, xr) ->\n let J.PixelRGB8 r g b = color xr\n in J.PixelRGB8 (logscale k r) (logscale k g) (logscale k b)\n\n-- | Simple (unstructured) complex number coloring.\nsimpleColoring :: Complex Double -> J.PixelRGB8\nsimpleColoring z = J.PixelRGB8 r g b\n where\n r = floor ((2 ^ 8 - 1) * r')\n g = floor ((2 ^ 8 - 1) * g')\n b = floor ((2 ^ 8 - 1) * b')\n (r', g', b') = hsl (phase z) 1 (1 - 0.5 ** magnitude z)\n\n-- | Convert HSL color to RGB.\n-- This function is copied with slight changes\n-- from http://hackage.haskell.org/package/colour-2.3.4\nhsl :: (RealFrac a, Floating a, Ord a) => a -> a -> a -> (a, a, a)\nhsl h s l = (component tr, component tg, component tb)\n where\n hk = h / (2 * pi)\n (tr, tg, tb) = (mod1 (hk + 1 / 3), mod1 hk, mod1 (hk - 1 / 3))\n q\n | l < 0.5 = l * (1 + s)\n | otherwise = l + s - l * s\n p = 2 * l - q\n component t\n | t < 1 / 6 = p + ((q - p) * 6 * t)\n | t < 1 / 2 = q\n | t < 2 / 3 = p + ((q - p) * 6 * (2 / 3 - t))\n | otherwise = p\n mod1 x =\n if pf < 0\n then pf + 1\n else pf\n where\n (_, pf) = properFraction x\n", "meta": {"hexsha": "93f1308b779892ca64447c46a87387d21e5adba4", "size": 3846, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Newton/Render.hs", "max_stars_repo_name": "unaimillan/NewtonFractals", "max_stars_repo_head_hexsha": "d0118677332500f299addfb3eafaf6467cdffff8", "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/Newton/Render.hs", "max_issues_repo_name": "unaimillan/NewtonFractals", "max_issues_repo_head_hexsha": "d0118677332500f299addfb3eafaf6467cdffff8", "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/Newton/Render.hs", "max_forks_repo_name": "unaimillan/NewtonFractals", "max_forks_repo_head_hexsha": "d0118677332500f299addfb3eafaf6467cdffff8", "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.6111111111, "max_line_length": 73, "alphanum_fraction": 0.5930837233, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.567815665053417}} {"text": "-- {-# DeriveDataTypeable #-}\nmodule Main where\n\n import System.Environment\n import System.Random\n import Numeric.LinearAlgebra (Matrix, assoc, Z, toLists)\n import Control.Monad (join)\n import Data.Char (toLower)\n\n import System.Console.CmdArgs.Implicit\n \n import ODMatrix.Sim.BusState\n\n\n\n data SimParams = Params {\n size :: Int,\n capacity :: Int,\n seed :: Int,\n cases :: Int,\n lambdas :: Bool\n } deriving (Show, Data, Typeable)\n\n params = Params {\n size = 10 &= help \"Size of the route\",\n capacity = 50 &= help \"Capacity of the unit\",\n seed = 0 &= help \"Seed for the simulation\",\n cases = 10 &= help \"Number of cases to simulate\",\n lambdas = False &= help \"Indicates if the lists of lambdas will be provided manually\"\n }\n\n\n getLambdas :: RandomGen g => Bool -> g -> Int -> Int -> IO ([Double],[Double])\n getLambdas False g n k = do -- Random genetated\n let (bg,ag) = split g\n bs = take n $ randomRs (0,fromIntegral k) bg\n as = take n $ randomRs (0,fromIntegral k) ag\n return (bs, as) \n getLambdas True _ n _ = do -- Manually provided\n input <- getContents\n let ls = lines input\n bs = take n ls\n as = take n $ drop n ls\n return (map read bs, map read as)\n\n\n\n\n main :: IO ()\n main = do\n -- ODMatrix Simulation\n putStrLn \"{\"\n\n args <- cmdArgs params\n \n let (Params n k seed cases manual_lambdas) = args\n (g1, g2) = split $ mkStdGen seed\n\n putStrLn \"\\\"params\\\": {\"\n putStrLn $ \"\\\"size\\\":\" ++ (show n) ++ \",\" \n putStrLn $ \"\\\"capacity\\\":\" ++ (show k) ++ \",\" \n putStrLn $ \"\\\"seed\\\":\" ++ (show seed) ++ \",\" \n putStrLn $ \"\\\"cases\\\":\" ++ (show cases) ++ \",\" \n putStrLn $ \"\\\"manual_lambdas\\\":\" ++ (map toLower $ show manual_lambdas)\n putStrLn \"},\"\n\n -- putStrLn $ if manual_lambdas \n -- then \"# Reading lambdas...\"\n -- else \"# Generating randoms lambdas...\"\n\n (bs,as) <- getLambdas manual_lambdas g1 n k\n\n putStrLn \"\\\"lambdas\\\" : {\"\n \n -- Boarding lambdas\n putStr \"\\\"boards\\\": \" \n putStr . show $ bs\n putStrLn \",\"\n \n -- Alighting lambdas\n putStr \"\\\"alights\\\": \" \n putStrLn . show $ as\n\n putStrLn \"},\"\n\n\n -- Generating origin destination matrices\n \n putStrLn \"\\\"odms\\\": {\"\n let ms = map (assoc (n,n) 0) (busSims k bs as g2) :: [Matrix Z]\n ms' = map (\\(i,m) -> \"\\\"\" ++ (show i) ++ \"\\\": \" ++ (show m) ++ \",\\n\") .\n zip [0..] .\n take cases . map (join . toLists) $ ms\n\n\n putStrLn . init . init . join $ ms'\n putStrLn \"}\"\n \n putStrLn \"}\"", "meta": {"hexsha": "5c83b5074e2cbbc71fa8b67754c9fa934e288a4f", "size": 2598, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "renecura/odmatrix-sim", "max_stars_repo_head_hexsha": "4e307c846faabe965a3ffc48f93ef06cbc40651f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "renecura/odmatrix-sim", "max_issues_repo_head_hexsha": "4e307c846faabe965a3ffc48f93ef06cbc40651f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "renecura/odmatrix-sim", "max_forks_repo_head_hexsha": "4e307c846faabe965a3ffc48f93ef06cbc40651f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2424242424, "max_line_length": 89, "alphanum_fraction": 0.5511932256, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5676915239380376}} {"text": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\n\nmodule CNVectorSpec where\n\nimport Data.Complex\nimport Data.Proxy\n\nimport Test.QuickCheck\nimport Test.QuickCheck.Poly\n\nimport CNVector\nimport Category\nimport Comonad\nimport Functor\nimport Unboxed\n-- import Vec\n\n\n\ntype N = 10\n\nprop_CNVector_Functor_id :: FnProp (CNVector N A)\nprop_CNVector_Functor_id = checkFnEqual law_Functor_id\n\nprop_CNVector_Functor_comp :: Fun B C -> Fun A B -> FnProp (CNVector N A)\nprop_CNVector_Functor_comp f g = checkFnEqual (law_Functor_comp f g)\n\nprop_CNVector_Semicomonad_comm ::\n Fun (CNVector N B) C -> Fun (CNVector N A) B -> FnProp (CNVector N A)\nprop_CNVector_Semicomonad_comm f g = checkFnEqual (law_Semicomonad_comm f g)\n\nprop_CNVector_Comonad_id :: FnProp (CNVector N A)\nprop_CNVector_Comonad_id = checkFnEqual (law_Comonad_id (Proxy @(->)))\n\nprop_CNVector_Comonad_apply :: Fun (CNVector N A) B -> FnProp (CNVector N A)\nprop_CNVector_Comonad_apply f = checkFnEqual (law_Comonad_apply f)\n\nprop_CNVector_Semicomonad1_comm ::\n Fun (CNVector N B) C -> Fun (CNVector N A) B -> FnProp (CNVector N A)\nprop_CNVector_Semicomonad1_comm f g = checkFnEqual (law_Semicomonad1_comm f g)\n\nprop_CNVector_Semicomonad1_comm' ::\n Fun (CNVector N B) C -> Fun (CNVector N A) B -> FnProp (CNVector N A)\nprop_CNVector_Semicomonad1_comm' (Fn f) (Fn g) =\n checkFnEqual (law_Semicomonad1_comm' f g)\n\nprop_CNVector_Comonad1_id :: FnProp (CNVector N A)\nprop_CNVector_Comonad1_id = checkFnEqual (law_Comonad1_id (Proxy @(->)))\n\nprop_CNVector_Comonad1_id' :: FnProp (CNVector N A)\nprop_CNVector_Comonad1_id' = checkFnEqual law_Comonad1_id'\n\nprop_CNVector_Comonad1_apply ::\n Fun (CNVector N A) B -> FnProp (CNVector N A)\nprop_CNVector_Comonad1_apply f = checkFnEqual (law_Comonad1_apply f)\n\nprop_CNVector_Comonad1_apply' ::\n Fun (CNVector N A) B -> FnProp (CNVector N A)\nprop_CNVector_Comonad1_apply' (Fn f) = checkFnEqual (law_Comonad1_apply' f)\n\n\n\ntype UA = Int\ntype UB = Double\ntype UC = Complex Double\n\nprop_CNUVector_Functor_id :: FnProp (CNUVector N UA)\nprop_CNUVector_Functor_id = checkFnEqual law_Functor_id\n\nprop_CNUVector_Functor_comp ::\n (UB -#> UC) -> (UA -#> UB) -> FnProp (CNUVector N UA)\nprop_CNUVector_Functor_comp f g = checkFnEqual (law_Functor_comp f g)\n\n-- prop_CNUVector_NatAdjunction_restrict ::\n-- Proxy (CNUVector N) -> (UVec3 N) UA -> Property\n-- prop_CNUVector_NatAdjunction_restrict = law_NatAdjunction_restrict\n\nprop_CNUVector_Semicomonad1_comm' ::\n Fun (CNUVector N UB) UC -> Fun (CNUVector N UA) UB ->\n FnProp (CNUVector N UA)\nprop_CNUVector_Semicomonad1_comm' (Fn f) (Fn g) =\n checkFnEqual (law_Semicomonad1_comm'\n (f :: CNUVector N UB -> UC)\n (g :: CNUVector N UA -> UB))\n\nprop_CNUVector_Comonad1_id' :: FnProp (CNUVector N UA)\nprop_CNUVector_Comonad1_id' = checkFnEqual law_Comonad1_id'\n\nprop_CNUVector_Comonad1_apply' ::\n Fun (CNVector N UA) UB -> FnProp (CNVector N UA)\nprop_CNUVector_Comonad1_apply' (Fn f) = checkFnEqual (law_Comonad1_apply' f)\n", "meta": {"hexsha": "232976a6a6ae121e697e4b42ef61dda275f1798e", "size": 3011, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/CNVectorSpec.hs", "max_stars_repo_name": "eschnett/wavetoy6", "max_stars_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/CNVectorSpec.hs", "max_issues_repo_name": "eschnett/wavetoy6", "max_issues_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/CNVectorSpec.hs", "max_forks_repo_name": "eschnett/wavetoy6", "max_forks_repo_head_hexsha": "53a77a10543aed973458c8f27b5a60cb1c78839a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7282608696, "max_line_length": 78, "alphanum_fraction": 0.7529060113, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.567407023863596}} {"text": "{-# LANGUAGE BangPatterns #-}\n{- |\n Description : Functions to work with transition probability matrices on rooted trees\n Copyright : (c) Dominik Schrempf 2017\n License : GPLv3\n\n Maintainer : dominik.schrempf@gmail.com\n Stability : unstable\n Portability : non-portable (not tested)\n\nCalculate transition probability matrices, map rate matrices on trees, populate\na tree with states according to a stationary distribution, etc.\n\nThe implementation of the Markov process is more than basic and can be improved in a lot of ways.\n\nTODO: Try https://hackage.haskell.org/package/Dist-0.4.1.0/docs/Numeric-Probability-Distribution.html\n\n* Changelog\n\n-}\n\nmodule Transition where\nimport Control.Monad.Random.Strict hiding (fromList)\nimport Data.Distribution hiding (toList)\nimport Numeric.LinearAlgebra hiding (fromList)\nimport RateMatrix\nimport RTree\n\n-- | This may be moved to a different module ProbMatrix or alike.\ntype ProbMatrix = Matrix R\n\n-- | The important matrix that gives the probabilities to move from one state to\n-- another in a specific time (branch length).\nprobMatrix :: RateMatrix -> BranchLn -> ProbMatrix\nprobMatrix m t = exponential\n where !exponential = expm $ scale t m\n\n-- | Convert a tree with branch lengths into a tree that has transition\n-- probability matrices assigned to each of its branches.\nbranchLengthsToTransitionProbs :: RateMatrix -> RTree a Double -> RTree a ProbMatrix\nbranchLengthsToTransitionProbs m = fmap (probMatrix m)\n\n-- | Move from a given state to a new one according to a transition probability\n-- matrix (for performance reasons this probability matrix needs to be given as\n-- a list of generators, see\n-- https://hackage.haskell.org/package/distribution-1.1.0.0/docs/Data-Distribution-Sample.html).\n-- This function is the bottleneck of the simulator and takes up most of the\n-- computation time. However, I was not able to find a faster implementation\n-- than the one from Data.Distribution.\njump :: (MonadRandom m) => State -> [Generator State] -> m State\njump (State s) p = target\n where !target = getSample $ p !! s\n\n-- | Perform N jumps from a given state and according to a transition\n-- probability matrix transformed to a list of generators. This implementation\n-- uses 'foldM' and I am not sure how to access or store the actual chain. This\n-- could be done by an equivalent of 'scanl' for general monads, which I was\n-- unable to find. This function is neat, but will most likely not be needed.\n-- However, it is instructive and is left in place.\njumpN :: (MonadRandom m) => State -> [Generator State] -> Int -> m State\njumpN s p n = foldM jump s (replicate n p)\n\n-- | This is the heart of the simulation. Take a tree (most probably with node\n-- labels of type a, but this could be anything) and a root state. If there is a\n-- split (i.e., if we have a node and not a leaf), jump down the left branch and\n-- populate and flatten the tree and jump down the right branch and populate and\n-- flatten the tree and append the two results. This is what 'liftM2' is doing,\n-- it lifts the append function of lists (++) to the 'Rand g' monad. If we\n-- encounter a leaf, just return the node label (or whatever the type a is) and\n-- the state that we ended up at.\npopulateAndFlattenTree :: (MonadRandom m) => RTree a [Generator State] -> State -> m [(a, State)]\npopulateAndFlattenTree (Leaf a) s = return [(a, s)]\npopulateAndFlattenTree (Node _ lp lc rp rc) s = liftM2 (++) (jumpDownBranch lp lc) (jumpDownBranch rp rc)\n where jumpDownBranch p t = jump s p >>= populateAndFlattenTree t\n\n-- | Convert a stationary distribution to a generator which speeds up random\n-- picks. Cf. 'jump'.\nstationaryDistToGenerator :: StationaryDist -> Generator State\nstationaryDistToGenerator f = fG\n -- This is a little complicated. I need to convert the vector to a list to be\n -- able to create a distribution.\n where !fL = toList f\n !fD = fromList $ zip (map State [0..]) fL\n !fG = fromDistribution fD\n\n-- | See 'jump'.\ntreeProbMatrixToTreeGenerator :: RTree a ProbMatrix -> RTree a [Generator State]\ntreeProbMatrixToTreeGenerator t = tG\n where\n -- Create a tree with the probability matrices as list of row vectors.\n !tL = fmap toLists t\n -- A complicated double map. We need to create generators for each branch on\n -- the tree (fmap) and for each target state on each branch (map).\n !tG = (fmap . map) (fromDistribution . fromList . zip (map State [0..])) tL\n\n-- | Simulate data (states at the leaves) for a tree with transition\n-- probabilities on its branches and with the stationary distribution of states\n-- at the root. The state at the root is randomly chosen from the stationary\n-- distribution and the states at the nodes and leaves are randomly chosen\n-- according to the transition probabilities.\nsimulateSite :: (MonadRandom m) =>\n Generator State\n -> RTree a [Generator State]\n -> m [(a, State)]\nsimulateSite f t = do\n !rootState <- getSample f\n populateAndFlattenTree t rootState\n\n-- | Randomly draw an index according to a given generator. Use the stationary\n-- distribution and rooted tree at the drawn index to simulate a site. This is\n-- useful for simulation, e.g., Gamma rate heterogeneity models.\nsimulateSiteGen :: (MonadRandom m) =>\n Generator Int\n -> [Generator State]\n -> [RTree a [Generator State]]\n -> m [(a, State)]\nsimulateSiteGen gen fs trs = do\n !i <- getSample gen\n let !f = fs !! i\n !t = trs !! i\n simulateSite f t\n", "meta": {"hexsha": "c7c09786879e6564b404788e60e8da5a31eb16c5", "size": 5625, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Transition.hs", "max_stars_repo_name": "dschrempf/bmm-simulate", "max_stars_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-14T15:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T15:53:08.000Z", "max_issues_repo_path": "src/Transition.hs", "max_issues_repo_name": "pomo-dev/bmm-simulate", "max_issues_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Transition.hs", "max_forks_repo_name": "pomo-dev/bmm-simulate", "max_forks_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.106557377, "max_line_length": 105, "alphanum_fraction": 0.7100444444, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5673774284909637}} {"text": "{-# LANGUAGE GADTs #-}\nmodule Math.IRT.Internal.LogLikelihood where\n\nimport Numeric.AD (Mode, Scalar)\nimport Statistics.Distribution (Distribution)\n\nclass (Distribution d) => LogLikelihood d where\n logLikelihood :: (Mode a, Floating a, Scalar a ~ Double) => Bool -> d -> a -> a\n\nlogLikeFunc :: (Distribution d, Mode a, Floating a, Scalar a ~ Double) => (d -> a -> a) -> Bool -> d -> a -> a\nlogLikeFunc f True = (log .) . f\nlogLikeFunc f False = ((log . (1-)) .) . f\n", "meta": {"hexsha": "232ab28c8a3723a137ff65204f213a2f7ee2dcf6", "size": 470, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/IRT/Internal/LogLikelihood.hs", "max_stars_repo_name": "argiopetech/irt", "max_stars_repo_head_hexsha": "ee136da44235bf7ecde4d516adfa8b22899ca0b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-06T08:31:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T08:31:33.000Z", "max_issues_repo_path": "Math/IRT/Internal/LogLikelihood.hs", "max_issues_repo_name": "argiopetech/irt", "max_issues_repo_head_hexsha": "ee136da44235bf7ecde4d516adfa8b22899ca0b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/IRT/Internal/LogLikelihood.hs", "max_forks_repo_name": "argiopetech/irt", "max_forks_repo_head_hexsha": "ee136da44235bf7ecde4d516adfa8b22899ca0b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1538461538, "max_line_length": 110, "alphanum_fraction": 0.6468085106, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5671888889555525}} {"text": "{-# Language DerivingVia #-}\n{-# Language FlexibleInstances #-}\n{-# Language GeneralizedNewtypeDeriving #-}\n{-# Language MultiParamTypeClasses #-}\n{-# Language UndecidableInstances #-}\n\nmodule Geometry.Testing (\n DInt (..)\n , Parameter (..)\n , Position (..)\n , AnyPoint (..)\n , AnyCircle (..)\n , AnyAngle (..)\n , AnyLine (..)\n , AnyRay (..)\n , AnySegment (..)\n , Motion (..), appMotion \n , Nontrivial (..)\n , NonDegenerate (..)\n , (<==>)\n) where\n\nimport Data.Complex\nimport Data.Foldable\nimport Data.Monoid\nimport Test.QuickCheck hiding (scale)\nimport Test.QuickCheck.Modifiers\nimport Data.Tuple.Extra (second)\n\nimport Geometry\nimport Geometry.Circle (mkCircle)\nimport Geometry.Base (roundUp)\n\ninfix 0 <==>\na <==> b = (a ==> b) .&&. (b ==> a)\n\n------------------------------------------------------------\n\n{- | A type for an interger double number.\n\n>>> sample (arbitrary :: Gen DInt)\nDInt 0.0\nDInt 2.0\nDInt 0.0\nDInt (-1.0)\nDInt 7.0\n...\n-}\nnewtype DInt = DInt Double deriving Show\n\ninstance Arbitrary DInt where\n arbitrary = DInt . fromIntegral <$> (arbitrary :: Gen Int)\n shrink (DInt l) = DInt <$> shrink l\n\n{- | A type for a double number parameterizing the `Manifold`.\n\n>>> sample (arbitrary :: Gen Parameter)\nParameter 0.6977012699848539\nParameter 0.5321234247634057\nParameter 9.832672492232597e-2\nParameter 0.9510866292762408\n...\n-}\nnewtype Parameter = Parameter { getParameter :: Double} deriving Show\n\ninstance Arbitrary Parameter where\n arbitrary = Parameter <$> choose (0, 1)\n shrink (Parameter l) = Parameter <$> shrink l\n\n------------------------------------------------------------\n\n{- | A type for an affine position (`XY`, `Cmp`, `Point` etc).\n\n>>> sample (arbitrary :: Gen (Position XY))\nPosition (0.0,0.0)\nPosition (-1.0,2.0)\nPosition (-3.0,3.0)\nPosition (6.0,4.0)\nPosition (-1.0,-1.0\n...\n-}\nnewtype Position a = Position a\n deriving (Show, Affine, Trans, Metric, Eq)\n\n\ninstance (Eq a, Pnt a, Arbitrary a) =>\n Arbitrary (Position a) where\n arbitrary = Position . roundUp 1 <$> arbitrary \n shrink = shrinkPos 0.5\n\n\nshrinkPos :: (Eq a, Affine a, Metric a) => Double -> a -> [a]\nshrinkPos d x = res\n where res = filter (/= x) $\n map (roundUp d) $\n takeWhile (\\p -> distance x p >= d/2) $\n map (\\s -> asCmp $ (1 - s) * cmp x) $\n iterate (/2) 1\n\n------------------------------------------------------------\n\ninstance Arbitrary Direction where\n arbitrary = oneof [asDeg <$> arbitrary, asCmp <$> arbitrary]\n shrink = shrinkPos 1\n\n------------------------------------------------------------\ninstance Arbitrary Point where\n arbitrary = Point <$> arbitrary\n shrink = shrinkPos 1\n\n{- | A wrapper for a `Point`. -}\nnewtype AnyPoint = AnyPoint Point\n deriving (Show, Arbitrary)\n\n------------------------------------------------------------\n\ninstance Arbitrary Circle where\n arbitrary = do (Position c) <- arbitrary\n (Position r) <- arbitrary :: Gen (Position Cmp)\n return (mkCircle (norm r) c # rotateAt' c (angle r))\n \n shrink cir =\n do Position c <- shrink (Position (center cir))\n r <- shrink (radius cir)\n return $ mkCircle r c\n\n{- | A wrapper for nondegenative `Circle`. -}\nnewtype AnyCircle = AnyCircle Circle\n deriving Show\n deriving Arbitrary via Nontrivial Circle\n\n------------------------------------------------------------\n\ninstance Arbitrary Angle where\n arbitrary = do (Position p) <- arbitrary\n Angle p <$> arbitrary <*> arbitrary\n \n shrink an =\n do Position p <- shrink (Position (refPoint an))\n s <- shrink (angleStart an)\n e <- shrink (angleEnd an)\n return $ Angle p s e\n\n{- | A wrapper for nontrivial `Angle`. -}\nnewtype AnyAngle = AnyAngle Angle\n deriving Show\n deriving Arbitrary via Nontrivial Angle\n\n------------------------------------------------------------\n\ninstance Arbitrary Segment where\n arbitrary =\n do Position p1 <- arbitrary\n Position p2 <- arbitrary\n return $ Segment (p1, p2)\n \n shrink l = let (p1, p2) = refPoints l\n in do Position p1' <- shrink (Position p1)\n Position p2' <- shrink (Position p2)\n return $ Segment (p1', p2')\n\ninstance Arbitrary Line where\n arbitrary = asLine <$> (arbitrary :: Gen Segment) \n shrink l = asLine <$> shrink (asSegment l)\n\ninstance Arbitrary Ray where\n arbitrary = asRay <$> (arbitrary :: Gen Segment) \n shrink l = asRay <$> shrink (asSegment l)\n\n{- | A wrapper for nontrivial `Line`. -}\nnewtype AnyLine = AnyLine Line\n deriving Show\n deriving Arbitrary via Nontrivial Line\n\n{- | A wrapper for nontrivial `Ray`. -}\nnewtype AnyRay = AnyRay Ray\n deriving Show\n deriving Arbitrary via Nontrivial Ray\n\n{- | A wrapper for nontrivial `Segment`. -}\nnewtype AnySegment = AnySegment Segment\n deriving Show\n deriving Arbitrary via Nontrivial Segment\n\n------------------------------------------------------------\n\n{- | A wrapper for a motion `translate`, `rotate` or `reflect`. -} \nnewtype Motion a = Motion (String, Endo a)\n\nappMotion :: Motion a -> a -> a\nappMotion (Motion (_, m)) = appEndo m\n\ninstance Show (Motion a) where\n show (Motion (s, _)) = s\n\ninstance Trans a => Arbitrary (Motion a) where\n arbitrary = Motion . fold <$> listOf (oneof motions)\n where\n motions = [ label \"Tr \" translate <$> (arbitrary :: Gen XY)\n , label \"Rot \" rotate <$> arbitrary\n , label \"Ref \" reflect <$> arbitrary ]\n label l t x = (l <> show x <> \" \", Endo $ t x) \n\n------------------------------------------------------------\n\n{- | A wrapper for a nontrivial `Figure`. -} \nnewtype Nontrivial a = Nontrivial a deriving\n ( Eq\n , Show\n , Figure\n , Affine\n , Trans\n , Curve\n , ClosedCurve\n , Manifold\n , PiecewiseLinear\n , Polygonal\n , APoint\n , Linear\n , Circular\n , Angular\n )\n\n\ninstance (Arbitrary a, Figure a) => Arbitrary (Nontrivial a) where\n arbitrary = Nontrivial <$> arbitrary `suchThat` isNontrivial\n shrink (Nontrivial l) = Nontrivial <$> filter isNontrivial (shrink l)\n\n--------------------------------------------------------------------------------\n\n{- | A wrapper for a nondegenerate `Figure`. -} \nnewtype NonDegenerate a = NonDegenerate a deriving\n ( Eq\n , Show\n , Figure\n , Affine\n , Trans\n , Curve\n , ClosedCurve\n , Manifold\n , PiecewiseLinear\n , Polygonal\n , APoint\n , Linear\n , Circular\n , Angular\n )\n\ninstance (Arbitrary a, PiecewiseLinear a) => Arbitrary (NonDegenerate a) where\n arbitrary = NonDegenerate <$> arbitrary `suchThat` isNondegenerate\n shrink (NonDegenerate l) = NonDegenerate <$> filter isNondegenerate (shrink l)\n\n--------------------------------------------------------------------------------\n\ninstance Arbitrary Triangle where\n arbitrary = (`suchThat` isNontrivial) $ do\n Position p1 <- arbitrary\n Position p2 <- arbitrary\n Position p3 <- arbitrary\n pure $ Triangle [p1, p2, p3]\n\n shrink (Triangle [p1, p2, p3]) = filter isNontrivial $ do\n p1' <- shrink p1\n p2' <- shrink p2\n p3' <- shrink p3\n pure $ Triangle [p1', p2', p3']\n\ninstance Arbitrary RightTriangle where\n arbitrary = (`suchThat` isNondegenerate) $ do\n Positive a <- arbitrary\n Positive b <- arbitrary\n m <- arbitrary\n pure $ aRightTriangle # scaleX a # scaleY b # appMotion m\n shrink (RightTriangle t) = RightTriangle <$> shrink t\n", "meta": {"hexsha": "6dbc8963ff6dae5aac8498490814032d12853b22", "size": 7437, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Geometry/Testing.hs", "max_stars_repo_name": "MethaHardworker/geometry", "max_stars_repo_head_hexsha": "77c987e0704722636d7d00afa54e22295df3e428", "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": "Geometry/Testing.hs", "max_issues_repo_name": "MethaHardworker/geometry", "max_issues_repo_head_hexsha": "77c987e0704722636d7d00afa54e22295df3e428", "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": "Geometry/Testing.hs", "max_forks_repo_name": "MethaHardworker/geometry", "max_forks_repo_head_hexsha": "77c987e0704722636d7d00afa54e22295df3e428", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0436363636, "max_line_length": 80, "alphanum_fraction": 0.5773833535, "num_tokens": 1939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5670825051413227}} {"text": "module Lib.Practice.P3_1 (\n f3_1\n) where\n\nimport Lib.Practice.P3 (Input( Fire, NotFire ), input2Int, inputs)\nimport Numeric.LinearAlgebra\n\nf3_1 = showOutput (\"XOR\", gXor)\n\ngAnd = Single (SNeuron (vector [0.5, 0.5]) (-0.7))\ngNand = Single (SNeuron (vector [-0.5, -0.5]) 0.7)\ngOr = Single (SNeuron (vector [0.5, 0.5]) (-0.2))\ngXor = Multi MNeuron { inputLayer = [gNand, gOr], intermediateLayer = gAnd }\n\nshowOutput (name, gate) = do\n putStrLn $ name ++ \"\u30b2\u30fc\u30c8\"\n mapM_ (showOutput' gate) inputs\n putStrLn \"\"\n where\n showOutput' gate input = do\n let result = input --> gate\n putStrLn $ show input ++ \" -> \" ++ show result\n\ndata SNeuron = SNeuron {\n weight :: Vector R,\n bias :: R\n} deriving Show\n\ndata MNeuron = MNeuron {\n inputLayer :: [Neuron],\n intermediateLayer :: Neuron\n} deriving Show\n\ndata Neuron = Single SNeuron | Multi MNeuron deriving Show\n(-->) :: [Input] -> Neuron -> Input\ninputs --> Single SNeuron { weight = w, bias = b } = result\n where inputV = fromList $ map input2Int inputs\n sum' = sumElements $ inputV * w\n result' = b + sum'\n result = case () of\n _ | result' >= 0 -> Fire \n _ -> NotFire\ninputs --> Multi MNeuron { inputLayer = inpLs, intermediateLayer = intL } = result\n where inputs' = map (inputs -->) inpLs\n result = inputs' --> intL", "meta": {"hexsha": "e6535895797489b3cee5fc60a0797e1dd103233c", "size": 1407, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib/Practice/P3_1.hs", "max_stars_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_stars_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-01-04T12:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T06:16:37.000Z", "max_issues_repo_path": "src/Lib/Practice/P3_1.hs", "max_issues_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_issues_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-01-04T02:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-09T12:39:40.000Z", "max_forks_repo_path": "src/Lib/Practice/P3_1.hs", "max_forks_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_forks_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-20T03:39:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T03:39:47.000Z", "avg_line_length": 31.2666666667, "max_line_length": 82, "alphanum_fraction": 0.5870646766, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5670677666113774}} {"text": "{-\n - *Main Data.Complex> h = concat [[1..5], replicate 11 0]\n - *Main Data.Complex> x = concat [[1..10], replicate 6 0]\n - *Main Data.Complex> convFft h x\n - [1.0,4.000000000000007,10.0,20.0,35.0,49.99999999999999,65.0,80.0,95.0,110.0,114.0,106.0,85.0,50.00000000000001,7.105427357601002e-15,7.105427357601002e-15]\n - *Main Data.Complex>\n -}\nimport Data.Complex\n\nconvOne :: (Num a) => [a] -> [a] -> Int -> a\nconvOne h x n = sum (zipWith (*) kernel input)\n where kernel = drop (-begin) (reverse h)\n input = drop begin x\n begin = n - length h + 1\n\nconv :: (Num a) => [a] -> [a] -> [a]\nconv h x = [convOne h x n | n <- [0..(length x + length h - 2)]]\n\nisPowerOfTwo :: Int -> Bool\nisPowerOfTwo 1 = True\nisPowerOfTwo x\n | mod x 2 == 0 = isPowerOfTwo (div x 2)\n | otherwise = False\n\nfftRaw :: (RealFloat a) => [a] -> Int -> Int -> [Complex a]\nfftRaw _ 0 _ = []\nfftRaw [] _ _ = []\nfftRaw (x0:_) 1 _ = [x0 :+ 0]\nfftRaw x n s = zipWith (+) x1 x2 ++ (zipWith (-) x1 x2)\n where x1 = fftRaw x (div n 2) (2 * s)\n x2 = zipWith (*) [exp (0 :+ (-2 * pi * fromIntegral k / (fromIntegral n))) | k <- [0..((div n 2) - 1)]] (fftRaw (drop s x) (div n 2) (2 * s))\n\nfft :: (RealFloat a) => [a] -> [Complex a]\nfft x\n | isPowerOfTwo n = fftRaw x n 1\n | otherwise = error \"FFT works only for powers of two\"\n where n = length x\n\nifftRaw :: (RealFloat a) => [Complex a] -> Int -> Int -> [Complex a]\nifftRaw _ 0 _ = []\nifftRaw [] _ _ = []\nifftRaw (x0:_) 1 _ = [x0]\nifftRaw x n s = zipWith (+) x1 x2 ++ (zipWith (-) x1 x2)\n where x1 = ifftRaw x (div n 2) (2 * s)\n x2 = zipWith (*) [exp (0 :+ (2 * pi * fromIntegral k / (fromIntegral n))) | k <- [0..((div n 2) - 1)]] (ifftRaw (drop s x) (div n 2) (2 * s))\n\nifft :: (RealFloat a) => [Complex a] -> [a]\nifft x\n | isPowerOfTwo n = [realPart v / (fromIntegral n) | v <- ifftRaw x n 1]\n | otherwise = error \"IFFT works only for powers of two\"\n where n = length x\n\nconvFft :: (RealFloat a) => [a] -> [a] -> [a]\nconvFft h x\n | length x == length h = ifft (zipWith (*) (fft h) (fft x))\n | otherwise = error \"Kernel and input data must have the same length\"\n", "meta": {"hexsha": "1699b652790e185c716469074979e4906dc4a27c", "size": 2152, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "conv.hs", "max_stars_repo_name": "sjappig/convhs", "max_stars_repo_head_hexsha": "2f14e3cfa469d9d236a75891ed439c49d75a8c0f", "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": "conv.hs", "max_issues_repo_name": "sjappig/convhs", "max_issues_repo_head_hexsha": "2f14e3cfa469d9d236a75891ed439c49d75a8c0f", "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": "conv.hs", "max_forks_repo_name": "sjappig/convhs", "max_forks_repo_head_hexsha": "2f14e3cfa469d9d236a75891ed439c49d75a8c0f", "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.7543859649, "max_line_length": 159, "alphanum_fraction": 0.5608736059, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5663254062283445}} {"text": "module Statistics.Information.Utils.Random where\n\nimport Data.Matrix\nimport Statistics.Information.Utils.List\nimport System.Random\n\nsplitN :: RandomGen g => Int -> g -> [g]\nsplitN 0 _ = []\nsplitN 1 g = [g]\nsplitN n g = let (g', g'') = split g in\n g' : splitN (n-1) g''\n\nrands :: (RandomGen g, Random a) => g -> Int -> (a, a) -> [a]\nrands g n (a, b) = take n $ randomRs (a, b) g\n\nnoisy :: RandomGen g => g -> Matrix Double -> Matrix Double\nnoisy g xs =\n let noise = [repeatN d (intens * r) | r <- rands g n (0.0, fromIntegral n)] in\n elementwise (+) xs (fromLists noise)\n where\n intens = 1e-10\n n = nrows xs\n d = ncols xs\n", "meta": {"hexsha": "84592b6fd61cfb38dce3503b0712220361dc2afe", "size": 636, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Information/Utils/Random.hs", "max_stars_repo_name": "eligottlieb/Shannon", "max_stars_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/Information/Utils/Random.hs", "max_issues_repo_name": "eligottlieb/Shannon", "max_issues_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Information/Utils/Random.hs", "max_forks_repo_name": "eligottlieb/Shannon", "max_forks_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5, "max_line_length": 80, "alphanum_fraction": 0.6132075472, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5660339312843458}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE DefaultSignatures #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE Trustworthy #-}\n---------------------------------------------------------------------------\n-- |\n-- Copyright : (C) 2012-2015 Edward Kmett\n-- License : BSD-style (see the file LICENSE)\n--\n-- Maintainer : Edward Kmett \n-- Stability : experimental\n-- Portability : non-portable\n--\n-- Simple matrix operation for low-dimensional primitives.\n---------------------------------------------------------------------------\nmodule Linear.Trace\n ( Trace(..)\n , frobenius\n ) where\n\nimport Control.Monad as Monad\nimport Linear.V0\nimport Linear.V1\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport Linear.Plucker\nimport Linear.Quaternion\nimport Linear.V\nimport Linear.Vector\nimport Data.Complex\nimport Data.Distributive\nimport Data.Foldable as Foldable\nimport Data.Functor.Bind as Bind\nimport Data.Functor.Compose\nimport Data.Functor.Product\nimport Data.Hashable\nimport Data.HashMap.Lazy\nimport Data.IntMap (IntMap)\nimport Data.Map (Map)\n\n-- $setup\n-- >>> import Data.Complex\n-- >>> import Debug.SimpleReflect.Vars\n-- >>> import Linear.V2\n\nclass Functor m => Trace m where\n -- | Compute the trace of a matrix\n --\n -- >>> trace (V2 (V2 a b) (V2 c d))\n -- a + d\n trace :: Num a => m (m a) -> a\n#ifndef HLINT\n default trace :: (Foldable m, Num a) => m (m a) -> a\n trace = Foldable.sum . diagonal\n {-# INLINE trace #-}\n#endif\n\n -- | Compute the diagonal of a matrix\n --\n -- >>> diagonal (V2 (V2 a b) (V2 c d))\n -- V2 a d\n diagonal :: m (m a) -> m a\n#ifndef HLINT\n default diagonal :: Monad m => m (m a) -> m a\n diagonal = Monad.join\n {-# INLINE diagonal #-}\n#endif\n\ninstance Trace IntMap where\n diagonal = Bind.join\n {-# INLINE diagonal #-}\n\ninstance Ord k => Trace (Map k) where\n diagonal = Bind.join\n {-# INLINE diagonal #-}\n\ninstance (Eq k, Hashable k) => Trace (HashMap k) where\n diagonal = Bind.join\n {-# INLINE diagonal #-}\n\ninstance Dim n => Trace (V n)\ninstance Trace V0\ninstance Trace V1\ninstance Trace V2\ninstance Trace V3\ninstance Trace V4\ninstance Trace Plucker\ninstance Trace Quaternion\n\ninstance Trace Complex where\n trace ((a :+ _) :+ (_ :+ b)) = a + b\n {-# INLINE trace #-}\n diagonal ((a :+ _) :+ (_ :+ b)) = a :+ b\n {-# INLINE diagonal #-}\n\ninstance (Trace f, Trace g) => Trace (Product f g) where\n trace (Pair xx yy) = trace (pfst <$> xx) + trace (psnd <$> yy) where\n pfst (Pair x _) = x\n psnd (Pair _ y) = y\n {-# INLINE trace #-}\n diagonal (Pair xx yy) = diagonal (pfst <$> xx) `Pair` diagonal (psnd <$> yy) where\n pfst (Pair x _) = x\n psnd (Pair _ y) = y\n {-# INLINE diagonal #-}\n\ninstance (Distributive g, Trace g, Trace f) => Trace (Compose g f) where\n trace = trace . fmap (fmap trace . distribute) . getCompose . fmap getCompose\n {-# INLINE trace #-}\n diagonal = Compose . fmap diagonal . diagonal . fmap distribute . getCompose . fmap getCompose\n {-# INLINE diagonal #-}\n\n-- | Compute the of a matrix.\nfrobenius :: (Num a, Foldable f, Additive f, Additive g, Distributive g, Trace g) => f (g a) -> a\nfrobenius m = trace $ fmap (\\ f' -> Foldable.foldl' (^+^) zero $ liftI2 (*^) f' m) (distribute m)\n", "meta": {"hexsha": "51806d28f4da4bc0d8f85bd0599d5e490ca402a9", "size": 3286, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Linear/Trace.hs", "max_stars_repo_name": "ekmett/linear", "max_stars_repo_head_hexsha": "d05577d0a60f6090a343e2adfa0e70a59b9c995c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 162, "max_stars_repo_stars_event_min_datetime": "2015-01-31T10:50:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T19:48:43.000Z", "max_issues_repo_path": "src/Linear/Trace.hs", "max_issues_repo_name": "ekmett/linear", "max_issues_repo_head_hexsha": "d05577d0a60f6090a343e2adfa0e70a59b9c995c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 94, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T12:52:34.000Z", "max_forks_repo_path": "src/Linear/Trace.hs", "max_forks_repo_name": "ekmett/linear", "max_forks_repo_head_hexsha": "d05577d0a60f6090a343e2adfa0e70a59b9c995c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2015-01-02T10:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T23:59:32.000Z", "avg_line_length": 28.0854700855, "max_line_length": 97, "alphanum_fraction": 0.6232501522, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.566017652172189}} {"text": "--\n-- FullConnLayer : fully connected layer\n--\n\nmodule CNN.FullConnLayer (\n initFilterF\n, zeroFilterF\n, connect\n, deconnect\n, reverseFullConnFilter\n, updateFullConnFilter\n) where\n\nimport Control.Monad hiding (msum)\n--import Data.List\nimport Data.Maybe\nimport Debug.Trace\nimport Numeric.LinearAlgebra\nimport System.Random.Mersenne as MT\n\nimport CNN.Algebra\nimport CNN.Image\nimport CNN.LayerType\n\n{- |\ninitFilterF\n\n IN : #kernel\n #channel\n\n OUT: filter of fully connected layer\n\n OUT: filter of fully connected layer\n\n>>> f <- initFilterF 3 20\n>>> rows f\n3\n>>> cols f\n21\n\n-}\n\ninitFilterF :: Int -> Int -> IO FilterF\ninitFilterF k c = do\n rs <- forM [1..k] $ \\i -> do\n w <- forM [1..c] $ \\j -> do\n r <- MT.randomIO :: IO Double\n return ((r * 2.0 - 1.0) * a)\n return (0.0:w)\n return $ fromLists rs\n where\n --a = 1.0 / fromIntegral c\n a = 4.0 * sqrt (6.0 / fromIntegral (c + k))\n --a = sqrt (6.0 / fromIntegral (c + k))\n\nzeroFilterF :: Int -> Int -> IO FilterF\nzeroFilterF k c = return $ (k><(c+1)) $ repeat 0.0\n\n--\n\n{- |\nconnect\n\n IN : filter of fully connected layer\n image\n\n OUT: updated image\n\n>>> let fs = fromLists [[0.5,1.0,2.0,3.0],[0.1,4.0,5.0,6.0]]\n>>> let im = [fromLists [[9.0,8.0,7.0]]]\n>>> connect fs im\n[(1><2)\n [ 46.5, 118.1 ]]\n>>> connect fs []\n*** Exception: invalid Image\nCallStack (from HasCallStack):\n error, called at CNN/FullConnLayer.hs:82:16 in main:CNN.FullConnLayer\n\n-}\n\nconnect :: FilterF -> Image -> Image\nconnect _ [] = error \"invalid Image\"\nconnect fs [im] = [reshape (rows fs) $ fs #> v]\n where\n v = vjoin [konst 1.0 1, flatten im]\n\n-- back prop\n\n{- |\ndeconnect\n\n IN : filter of fully connected layer\n image\n difference from previous layer\n\n OUT: difference and updated layer\n\n>>> let im = [fromLists [[1.0, 2.0, 3.0]]]\n>>> let delta = [fromLists [[1.0, 2.0]]]\n>>> let fs = fromLists [[1.0, 2.0],[3.0,4.0],[5.0,6.0]]\n>>> let (d,l) = deconnect fs im delta\n>>> d\n[(1><2)\n [ 11.0, 17.0 ]]\n>>> l\nJust FullConnLayer:(2><4)\n [ 1.0, 1.0, 2.0, 3.0\n , 2.0, 2.0, 4.0, 6.0 ]\n\n-}\n\ndeconnect :: FilterF -> Image -> Delta -> (Delta, Maybe Layer)\ndeconnect fs im delta = ([reshape (rows fs') $ fs' #> dl]\n , Just (FullConnLayer $ outer dl im'))\n where\n dl = flatten $ head delta -- to Vector\n fs' = dropRows 1 fs\n im' = vjoin [konst 1.0 1, flatten $ head im]\n\n-- reverse\n\nreverseFullConnFilter :: FilterF -> Layer\nreverseFullConnFilter fs = FullConnLayer $ tr' fs\n\n-- update filter\n\nupdateFullConnFilter :: FilterF -> Double -> [Maybe Layer] -> Layer\nupdateFullConnFilter fs lr dl\n | dl' == [] = FullConnLayer fs\n | otherwise = FullConnLayer fs'\n where\n dl' = catMaybes dl\n delta = mscale (lr / fromIntegral (length dl')) (msum $ strip dl')\n fs' = msub fs delta\n\nstrip :: [Layer] -> [FilterF]\nstrip [] = []\nstrip (FullConnLayer fs:ds) = fs:strip ds\nstrip (_:ds) = strip ds\n", "meta": {"hexsha": "7f477903cc9f2200e93b1258a6cc08edbf72bd21", "size": 2899, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "CNN/FullConnLayer.hs", "max_stars_repo_name": "eijian/deeplearning", "max_stars_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-30T01:28:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T18:58:17.000Z", "max_issues_repo_path": "CNN/FullConnLayer.hs", "max_issues_repo_name": "eijian/deeplearning", "max_issues_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CNN/FullConnLayer.hs", "max_forks_repo_name": "eijian/deeplearning", "max_forks_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7071428571, "max_line_length": 71, "alphanum_fraction": 0.6126250431, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5659860682112196}} {"text": "module STCR2S1 where\n\nimport Control.Monad as M\nimport Control.Monad.Parallel as MP\nimport Data.Array.Repa as R\nimport Data.Binary (decodeFile)\nimport Data.Complex\nimport Data.List as L\nimport DFT.Plan\nimport Filter.Utils\nimport FokkerPlanck.MonteCarlo\nimport Image.IO\nimport STC.CompletionFieldR2S1\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Types\nimport Utils.Array\nimport Utils.Time\nimport STC.Utils\nimport Text.Printf\nimport FokkerPlanck.FourierSeries\nimport FokkerPlanck.GreensFunction\n\nmain = do\n args@(numPointStr:numOrientationStr:sigmaStr:taoStr:thresholdStr:numTrailStr:maxTrailStr:initDistStr:initOriStr:initSpeedStr:rStr:locationStr:deltaStr:cornerWeightStr:numThreadStr:_) <-\n getArgs\n print args\n let numPoint = read numPointStr :: Int\n numOrientation = read numOrientationStr :: Int\n sigma = read sigmaStr :: Double\n tao = read taoStr :: Double\n threshold = read thresholdStr :: Double\n numTrail = read numTrailStr :: Int\n maxTrail = read maxTrailStr :: Int\n initDist = read initDistStr :: [R2S1RPPoint]\n initOri = read initOriStr :: Double\n initSpeed = read initSpeedStr :: Double\n r = read rStr :: Double\n location = read locationStr :: (Int, Int)\n delta = read deltaStr :: Double\n cornerWeight = read cornerWeightStr :: Double\n numThread = read numThreadStr :: Int\n sourceDist =\n computeInitialDistribution numPoint numPoint numOrientation delta . L.take 1 $\n initDist\n sinkDist =\n computeInitialDistribution numPoint numPoint numOrientation delta . L.drop 1 $\n initDist\n dist =\n computeInitialDistribution numPoint numPoint numOrientation delta initDist\n folderPath = \"output/test/STCR2S1\"\n createDirectoryIfMissing True folderPath\n -- Compute the Green's function\n -- arrG <-\n -- solveMonteCarloR2S1\n -- numThread\n -- numTrail\n -- maxTrail\n -- numPoint\n -- numPoint\n -- numOrientation\n -- sigma\n -- tao\n -- r\n -- initSpeed\n -- \"\"\n let deltaTheta = 2 * pi / fromIntegral numOrientation\n -- arrG <-\n -- sampleR2S1\n -- numPoint\n -- numPoint\n -- delta\n -- deltaTheta\n -- initSpeed\n -- sigma\n -- tao\n -- [0 .. numOrientation - 1]\n arrG <-\n sampleR2S1Corner\n numPoint\n numPoint\n delta\n deltaTheta\n initSpeed\n sigma\n tao\n threshold\n [0 .. numOrientation - 1]\n cornerWeight\n printCurrentTime \"Done.\"\n plan <- makeR2S1Plan emptyPlan arrG\n -- Source Field\n source <- shareWeightST plan sourceDist arrG\n plotImageRepa\n (folderPath \"Source.png\")\n (ImageRepa 8 .\n computeS .\n R.extend (Z :. (1 :: Int) :. All :. All) .\n reduceContrast 100 . R.sumS . rotate3D $\n source)\n plotThetaDimension folderPath \"R2S1_\" location .\n R.backpermute\n (extent source)\n (\\(Z :. k :. i :. j) ->\n (Z :.\n (mod (k + numOrientation - (div numOrientation 2)) numOrientation :: Int) :.\n i :.\n j)) $\n source\n -- MP.mapM_\n -- (\\i ->\n -- plotImageRepa\n -- (folderPath printf \"Source_%d.png\" i)\n -- (ImageRepa 8 .\n -- computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.slice source $\n -- (Z :. i :. All :. All)))\n -- [0 .. numOrientation - 1]\n -- Sink Field\n sink <- shareWeightST plan sinkDist arrG -- . rotateST arrG $ div numOrientation 2\n plotImageRepa\n (folderPath \"Sink.png\")\n (ImageRepa 8 .\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) . reduceContrast 100 . R.sumS . rotate3D $\n sink)\n -- MP.mapM_\n -- (\\i ->\n -- plotImageRepa\n -- (folderPath printf \"Sink_%d.png\" i)\n -- (ImageRepa 8 .\n -- computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.slice sink $\n -- (Z :. i :. All :. All)))\n -- [0 .. numOrientation - 1]\n -- Completion Field\n let completion = R.zipWith (*) source . timeReversal $ sink\n plotImageRepa\n (folderPath \"Completion.png\")\n (ImageRepa 8 .\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.sumS . rotate3D $\n completion)\n", "meta": {"hexsha": "8e0d0a4cea77fd042502b9b39707bf9a0be81d1c", "size": 4440, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2S1/STCR2S1.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/STCR2S1/STCR2S1.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/STCR2S1/STCR2S1.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.4893617021, "max_line_length": 187, "alphanum_fraction": 0.5849099099, "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5659860624932743}} {"text": "-- |\n-- This module defines the @Density@ type, which is the result of\n-- doing a kernel density estimate on a sample of data. The idea\n-- is that the distribution of metrics can be recorded using the @kde@\n-- function, and then sampled in the model using @sampleDensity@.\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DeriveAnyClass #-}\nmodule Hypersphere.Density where\n\nimport Control.DeepSeq\nimport Control.Monad.Bayes.Class\nimport Data.Aeson (ToJSON, FromJSON)\nimport Data.Foldable\nimport Data.List.NonEmpty (NonEmpty)\nimport qualified Data.List.NonEmpty as NonEmpty\nimport qualified Data.Vector.Unboxed as UV\nimport Data.Monoid (Any)\nimport qualified Diagrams.Core as D\nimport GHC.Generics\nimport Graphics.Rendering.Chart.Backend.Diagrams\nimport Graphics.Rendering.Chart.Easy\nimport Linear.V2 (V2)\nimport qualified Linear.V2 as V2\nimport qualified Statistics.Sample.KernelDensity as S\n\n-- | Represents a Kernel Density Estimate.\n--\n-- TODO: Should we store the cummulutive density to prevent recalculating\n-- it all the time when sampling?\ndata Density = Density\n { dMesh :: !(UV.Vector Double)\n , dDensity :: !(UV.Vector Double)\n } deriving (Eq, Ord, Show, Generic, NFData)\n\ninstance ToJSON Density\ninstance FromJSON Density\n\n-- | Find the area under the curve of the probability density. Should\n-- be pretty close to 1.\n--\n-- Useful for debug.\nintegrate :: Density -> Double\nintegrate d@Density{..} =\n let\n spacing = UV.foldl1 subtract $ UV.take 2 dMesh\n zoids = getTrapezoids d\n in UV.sum $ UV.map (uncurry $ trapezoidalArea spacing) zoids\n\n-- | The area of a trapezoid.\n-- `trapezoid width height1 height2`\ntrapezoidalArea :: Double -> Double -> Double -> Double\ntrapezoidalArea w h1 h2 = (h1 + h2) * 0.5 * w\n\n-- | Get the trapezoids that make up the area under the density curve.\ngetTrapezoids :: Density -> UV.Vector (Double,Double)\ngetTrapezoids Density{..} = UV.zip dDensity $ UV.tail dDensity\n\n-- | Cumulative area under the density curve.\nscanIntegral :: Density -> UV.Vector Double\nscanIntegral d@Density{..} =\n let\n spacing = UV.foldl1 subtract $ UV.take 2 dMesh\n zoids = getTrapezoids d\n in \n UV.scanl (\\area trap -> area + uncurry (trapezoidalArea spacing) trap) 0 zoids\n\n-- | Create a density from a series of observations. There must be at least\n-- one observation.\nkde :: NonEmpty Double -> Density\nkde = uncurry Density . S.kde 512 . UV.fromList . toList\n\n-- | Plot the @Density@ to a file with the given name and title.\nplotDensity :: FilePath -> String -> Density -> IO ()\nplotDensity file title Density{..} = toFile def file $ do\n let\n maxDensity = 1.1 * UV.maximum dDensity\n layout_title .= title\n layout_y_axis . laxis_generate .= scaledAxis def (0,maxDensity)\n plot $ line \"\" [UV.toList $ UV.zip dMesh dDensity]\n\n-- | Sample a value from the @Density@.\nsampleDensity :: MonadSample m => Density -> m Double\nsampleDensity d@Density{..} = do\n s <- random\n let\n mi = UV.findIndex (>=s) $ scanIntegral d\n o = maybe UV.last (\\i -> (UV.! i)) mi dMesh\n return o\n\n", "meta": {"hexsha": "111579bb61a01847cc60bd25605c8db316bd15f8", "size": 3124, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Hypersphere/Density.hs", "max_stars_repo_name": "luke-clifton/hypersphere", "max_stars_repo_head_hexsha": "2c7ba5e5f0ce887249cbf0d1625c1104be34c167", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-03-20T10:17:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T01:02:34.000Z", "max_issues_repo_path": "lib/Hypersphere/Density.hs", "max_issues_repo_name": "luke-clifton/hypersphere", "max_issues_repo_head_hexsha": "2c7ba5e5f0ce887249cbf0d1625c1104be34c167", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-10-30T05:17:49.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-11T22:23:57.000Z", "max_forks_repo_path": "lib/Hypersphere/Density.hs", "max_forks_repo_name": "luke-clifton/hypersphere", "max_forks_repo_head_hexsha": "2c7ba5e5f0ce887249cbf0d1625c1104be34c167", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-10-27T04:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-12T05:57:44.000Z", "avg_line_length": 34.3296703297, "max_line_length": 86, "alphanum_fraction": 0.7061459667, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5659145391624577}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n\n-- |\n-- Module : Test.Convolution\n-- Copyright : (c) 2020 Drexel University\n-- License : BSD-style\n-- Maintainer : mainland@drexel.edu\n\nmodule Test.Convolution (\n convolutionTests,\n linearConvolutionTests,\n cyclicConvolutionTests\n ) where\n\nimport Data.Complex\nimport Test.HUnit ((@?=))\nimport Test.Hspec\n\nimport Spiral.Convolution\nimport Spiral.Exp\nimport Spiral.SPL\n\nconvolutionTests :: Spec\nconvolutionTests = describe \"Convolution\" $ do\n linearConvolutionTests\n cyclicConvolutionTests\n\nlinearConvolutionTests :: Spec\nlinearConvolutionTests = describe \"Linear Convolution\" $ do\n sequence_ [linearConvolutionTest (Standard i) i | i <- [1..16::Int]]\n sequence_ [linearConvolutionTest (ToomCook i) i | i <- [1..16::Int]]\n linearConvolutionTest (Tensor [2,2] [Standard 2, ToomCook 2]) 4\n linearConvolutionTest (Tensor [3,5] [Standard 3, ToomCook 5]) 15\n linearConvolutionTest (Tensor [2,2,2,2] [ToomCook 2, ToomCook 2, ToomCook 2, ToomCook 2]) 16\n sequence_ [linearConvolutionTest (Lift 5 i (Standard i)) 5 | i <- [6..10::Int]]\n sequence_ [linearConvolutionTest (FromCyclic i (ConvolutionTheorem (2*i - 2))) i | i <- [2..8::Int]]\n\nlinearConvolutionTest :: LinearConvolution (Exp (Complex Double)) -> Int -> Spec\nlinearConvolutionTest lin n =\n it (show lin) $ toMatrix (convolve lin vector) @?= expected_result\n where\n l :: Int\n l = 2 * n - 1\n\n vector :: [Exp (Complex Double)]\n vector = [fromIntegral i | i <- [1..n]]\n\n -- expected_result :: Matrix M (Exp (Complex Double))\n expected_result = toMatrix $ transpose $ fromLists\n [replicate i 0 ++ vector ++ replicate (l - n - i) 0 | i <- [0..n-1]]\n\ncyclicConvolutionTests :: Spec\ncyclicConvolutionTests = describe \"Cyclic Convolution\" $ do\n sequence_ [cyclicConvolutionTest (ConvolutionTheorem i) | i <- [3..8::Int]]\n cyclicConvolutionTest (Winograd 2 [Standard 1, Standard 1])\n cyclicConvolutionTest (Winograd 3 [Standard 1, Standard 2])\n cyclicConvolutionTest (Winograd 3 [Standard 1, Lift 2 4 (Standard 4)])\n cyclicConvolutionTest (Winograd 3 [Standard 1, Lift 2 3 (Standard 3)])\n cyclicConvolutionTest (AgarwalCooley 2 3 (ConvolutionTheorem 2) (Winograd 3 [Standard 1, Standard 2]))\n cyclicConvolutionTest (AgarwalCooley 4 3 (ConvolutionTheorem 4) (Winograd 3 [Standard 1, Standard 2]))\n cyclicConvolutionTest (SplitNesting [2, 3] [(Winograd 2 [Standard 1, Standard 1]), (Winograd 3 [Standard 1, Standard 2])])\n cyclicConvolutionTest (SplitNesting [3, 2] [(Winograd 3 [Standard 1, Standard 2]), (Winograd 2 [Standard 1, Standard 1])])\n\ncyclicConvolutionTest :: CyclicConvolution (Exp (Complex Double)) -> Spec\ncyclicConvolutionTest cyc = it (show cyc) $\n toMatrix (convolve cyc vector) @?= toMatrix (circ vector)\n where\n n :: Int\n n = getSize cyc\n\n vector :: [Exp (Complex Double)]\n vector = [fromIntegral i | i <- [1..n]]\n", "meta": {"hexsha": "e077766bd00e6804e70d4a282139b053a418670b", "size": 3077, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/test/Test/Convolution.hs", "max_stars_repo_name": "mainland/hspiral", "max_stars_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-05-21T21:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T04:48:25.000Z", "max_issues_repo_path": "src/test/Test/Convolution.hs", "max_issues_repo_name": "mainland/hspiral", "max_issues_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/Test/Convolution.hs", "max_forks_repo_name": "mainland/hspiral", "max_forks_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4487179487, "max_line_length": 124, "alphanum_fraction": 0.6987325317, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5657217643765768}} {"text": "{-# LANGUAGE ViewPatterns #-}\nmodule AsteriskGaussian where\n\nimport Control.Parallel.Strategies\nimport Data.Array.Repa as R\nimport Data.Complex as C\nimport Data.List as L\nimport Data.Vector.Storable as VS\nimport Data.Vector.Unboxed as VU\nimport Graphics.Rendering.Chart.Backend.Cairo\nimport Graphics.Rendering.Chart.Easy\nimport Math.Gamma\nimport Pinwheel.FourierSeries2D\n-- import Pinwheel.Gaussian\nimport qualified FourierPinwheel.Filtering as FP\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Text.Printf\nimport Utils.BLAS\nimport Utils.List\nimport Utils.Distribution\n\nmain = do\n args@(numR2FreqStr:numThetaFreqStr:numRFreqStr:numPointStr:numThetaStr:numRStr:xStr:yStr:periodStr:std1Str:std2Str:stdR2Str:_) <-\n getArgs\n let numR2Freq = read numR2FreqStr :: Int\n numThetaFreq = read numThetaFreqStr :: Int\n numRFreq = read numRFreqStr :: Int\n numPoint = read numPointStr :: Int\n numTheta = read numThetaStr :: Int\n numR = read numRStr :: Int\n x = read xStr :: Double\n y = read yStr :: Double\n period = read periodStr :: Double\n std1 = read std1Str :: Double\n std2 = read std2Str :: Double\n stdR2 = read stdR2Str :: Double\n folderPath = \"output/test/AsteriskGaussian\"\n let centerR2Freq = div numR2Freq 2\n centerThetaFreq = div numThetaFreq 2\n periodEnv = period ^ 2 / 4\n a = std1\n b = std2\n asteriskGaussianFreqTheta =\n VS.concat .\n parMap\n rdeepseq\n (\\tFreq' ->\n let tFreq = tFreq' - centerThetaFreq\n arr =\n R.map (* (gaussian1DFreq (fromIntegral tFreq) b :+ 0)) $\n analyticalFourierCoefficients1\n numR2Freq\n 1\n tFreq\n 0\n a\n period\n periodEnv\n in VS.convert . toUnboxed . computeS $\n centerHollowArray numR2Freq arr) $\n [0 .. numThetaFreq - 1]\n deltaTheta = 2 * pi / Prelude.fromIntegral numTheta\n harmonicsThetaD =\n fromFunction (Z :. numTheta :. numThetaFreq :. numR2Freq :. numR2Freq) $ \\(Z :. theta' :. tFreq' :. xFreq' :. yFreq') ->\n let tFreq = fromIntegral $ tFreq' - centerThetaFreq\n xFreq = fromIntegral $ xFreq' - centerR2Freq\n yFreq = fromIntegral $ yFreq' - centerR2Freq\n theta = fromIntegral theta' * deltaTheta\n in (1 / (2 * pi) :+ 0) *\n cis (2 * pi / period * (x * xFreq + y * yFreq) + tFreq * theta)\n harmonicsTheta <- computeUnboxedP harmonicsThetaD\n xs <-\n VS.toList . VS.map magnitude <$>\n gemmBLAS\n numTheta\n 1\n (numThetaFreq * numR2Freq ^ 2)\n (VS.convert . toUnboxed $ harmonicsTheta)\n asteriskGaussianFreqTheta\n toFile def (folderPath \"theta.png\") $ do\n layout_title .=\n printf \"(%d , %d)\" (Prelude.round x :: Int) (Prelude.round y :: Int)\n plot\n (line\n \"\"\n [ L.zip\n [fromIntegral i * deltaTheta / pi | i <- [0 .. numTheta - 1]]\n xs\n ])\n let centerRFreq = div numRFreq 2\n centerR2Freq = div numR2Freq 2\n gaussian2D =\n computeUnboxedS . fromFunction (Z :. numR2Freq :. numR2Freq) $ \\(Z :. i' :. j') ->\n let i = i' - centerR2Freq\n j = j' - centerR2Freq\n in exp\n (pi * fromIntegral (i ^ 2 + j ^ 2) /\n ((-1) * period ^ 2 * stdR2 ^ 2)) /\n (2 * pi * stdR2 ^ 2) :+\n 0\n asteriskGaussianFreqR =\n VS.concat .\n parMap\n rdeepseq\n (\\rFreq' ->\n let rFreq = rFreq' - centerRFreq\n arr =\n R.map\n (* ((gaussian1DFourierCoefficients\n (fromIntegral rFreq)\n (log periodEnv)\n b :+\n 0) -- *\n -- cis\n -- ((-2) * pi / log periodEnv * fromIntegral rFreq *\n -- log 0.25)\n )) . centerHollowArray numR2Freq $\n analyticalFourierCoefficients1\n numR2Freq\n 1\n 0\n rFreq\n a\n period\n periodEnv\n in VS.convert . toUnboxed . computeS . centerHollowArray numR2Freq $\n arr -- *^ gaussian2D\n ) $\n [0 .. numRFreq - 1]\n deltaR = log periodEnv / Prelude.fromIntegral numR\n harmonicsRD =\n fromFunction (Z :. numR :. numRFreq :. numR2Freq :. numR2Freq) $ \\(Z :. r' :. rFreq' :. xFreq' :. yFreq') ->\n let rFreq = fromIntegral $ rFreq' - centerRFreq\n xFreq = fromIntegral $ xFreq' - centerR2Freq\n yFreq = fromIntegral $ yFreq' - centerR2Freq\n r = fromIntegral r' * deltaR - log periodEnv / 2\n in (1 / log periodEnv :+ 0) *\n cis\n (2 * pi / period * (x * xFreq + y * yFreq) +\n 2 * pi / log periodEnv * rFreq * r)\n harmonicsR <- computeUnboxedP harmonicsRD\n ys <-\n VS.toList . VS.map magnitude <$>\n gemmBLAS\n numR\n 1\n (numRFreq * numR2Freq ^ 2)\n (VS.convert . toUnboxed $ harmonicsR)\n asteriskGaussianFreqR\n toFile def (folderPath \"R.png\") $ do\n layout_title .= printf \"(%.3f , %.3f)\" x y\n plot\n (line\n \"\"\n [ L.zip\n [ fromIntegral i * deltaR - log periodEnv / 2\n | i <- [0 .. numR - 1]\n ]\n ys\n ])\n", "meta": {"hexsha": "e2904d98ddf970ac2f88f107fa11ad35ea3dcd4d", "size": 6012, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/AsteriskGaussian/AsteriskGaussian.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/AsteriskGaussian/AsteriskGaussian.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/AsteriskGaussian/AsteriskGaussian.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 36.8834355828, "max_line_length": 131, "alphanum_fraction": 0.494677312, "num_tokens": 1590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5655743419675588}} {"text": "--stolen from kmeans!\n\nmodule Math.Probably.KMeans (kmeansOn, kmeans', kmeansLargestCentroids)\n where\nimport Data.List (transpose, sort, groupBy, minimumBy, sortBy)\nimport Data.Function (on)\nimport Data.Ord (comparing)\n--import Numeric.LinearAlgebra\n--import qualified Data.Vector.Storable as VS\n\ntype Vector a = [a]\n\n\ndist :: (Floating b) => Vector b -> Vector b -> b\ndist a b = sqrt . sum $ zipWith (\\x y-> (x-y) ^ 2) a b\n\n\ncentroid :: (Fractional b) => (a -> Vector b) -> [a] -> Vector b\ncentroid f points = map (flip (/) l . sum) $ transpose $ map f points\n where l = fromIntegral $ length points\n\nclosest :: (Ord b, Floating b) => [Vector b] -> Vector b -> Vector b\nclosest points point = minimumBy (comparing $ dist point) points\n\nrecluster'\n :: (Ord b, Ord a, Floating b) =>\n (a -> Vector b) -> [Vector b] -> [a] -> [[a]]\nrecluster' f centroids points = map (map snd) $ groupBy ((==) `on` fst) reclustered\n where reclustered = sort [(closest centroids $ f a, a) | a <- points]\n\nrecluster :: (Floating a, Ord a, Ord b) => (b->Vector a) -> [[b]] -> [[b]]\nrecluster f clusters = recluster' f centroids $ concat clusters\n where centroids = map (centroid f) clusters\n\npart :: (Eq a) => Int -> [a] -> [[a]]\npart x ys\n | zs' == [] = [zs]\n | otherwise = zs : part x zs'\n where (zs, zs') = splitAt x ys\n-- | Recluster points\nkmeans' :: (Floating a, Ord a, Eq b, Ord b) => (b->Vector a) -> [[b]] -> [[b]]\nkmeans' f clusters\n | clusters == clusters' = clusters\n | otherwise = kmeans' f clusters'\n where clusters' = recluster f clusters\n-- | Cluster points into k clusters.\n-- |\n-- | The initial clusters are chosen arbitrarily\nkmeansOn :: (Floating a, Ord a, Eq b, Ord b) => (b->Vector a) -> Int -> [b] -> [[b]]\nkmeansOn f k points = kmeans' f $ part l points\n where l = (length points + k - 1) `div` k\n\nkmeansLargestCentroids :: Int -> [Vector Double] -> [Vector Double]\nkmeansLargestCentroids k data0 =\n let clusters = reverse $ sortBy (comparing length) $ kmeansOn id k data0\n in map (centroid id) clusters\n", "meta": {"hexsha": "bb5fa45b3fa1fb326dc74c797e235357d18a2eee", "size": 2060, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Probably/KMeans.hs", "max_stars_repo_name": "glutamate/probably-baysig", "max_stars_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-02-12T05:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:37.000Z", "max_issues_repo_path": "src/Math/Probably/KMeans.hs", "max_issues_repo_name": "silky/probably-baysig", "max_issues_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/Probably/KMeans.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 36.1403508772, "max_line_length": 84, "alphanum_fraction": 0.6281553398, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5651164269881654}} {"text": "module HVX.Internal.Matrix\n ( Mat\n , allMat\n , anyMat\n , diagMat\n , ei\n , fpequalsMat\n , lpnorm\n , matrixPow\n , reduceMat\n , scalarMat\n , zeroMat\n , zeroVec\n ) where\n\nimport Numeric.LinearAlgebra hiding (i)\nimport Numeric.LinearAlgebra.Util\n\nimport HVX.Internal.Util\n\ntype Mat = Matrix Double\n\nallMat :: (Double -> Bool) -> Mat -> Bool\nallMat f x = all f (toList . flatten $ x)\n\nanyMat :: (Double -> Bool) -> Mat -> Bool\nanyMat f x = any f (toList . flatten $ x)\n\ndiagMat :: Mat -> Mat\ndiagMat = diag . flatten\n\nei :: Int -> Int -> Mat\nei n i = buildMatrix n 1 (\\(j, _) -> if i == j then 1 else 0)\n\nfpequalsMat :: Mat -> Mat -> Bool\nfpequalsMat a b\n | ra == rb && ca == cb = all (uncurry fpequals) $ zip alist blist\n | otherwise = error \"Two matrices with different dimensions cannot possibley be equal!\"\n where\n ra = rows a\n rb = rows b\n ca = cols a\n cb = cols b\n alist = toList . flatten $ a\n blist = toList . flatten $ b\n\nlpnorm :: Double -> Mat -> Double\nlpnorm p x = sumElements y ** (1/p)\n where pMat = (1><1) [p]\n y = abs x ** pMat\n\nmatrixPow :: Double -> Mat -> Mat\nmatrixPow p = mapMatrix (** p)\n\nreduceMat :: ([Double] -> Double) -> Mat -> Mat\nreduceMat f = (1><1) . (:[]) . f . toList . flatten\n\nscalarMat :: Double -> Mat\nscalarMat x = (1><1) [x]\n\nzeroMat :: Int -> Mat\nzeroMat n = zeros n n\n\nzeroVec :: Int -> Mat\nzeroVec n = zeros n 1\n", "meta": {"hexsha": "6f8ffc54f17211f9fff0b07f0c4d604ea59c24f5", "size": 1391, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HVX/Internal/Matrix.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/Internal/Matrix.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/Internal/Matrix.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": 21.0757575758, "max_line_length": 89, "alphanum_fraction": 0.6074766355, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.5651164269881653}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Strict #-} \nmodule FokkerPlanck.GreensFunction where\n\nimport Control.DeepSeq\nimport Control.Monad as M\nimport Data.Array.Accelerate.LLVM.PTX\nimport Data.Array.IArray as IA\nimport Data.Array.Repa as R\nimport Data.Binary\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Storable as VS\nimport Data.Vector.Unboxed as VU\nimport FokkerPlanck.Analytic\nimport FokkerPlanck.FourierSeriesGPU\nimport FokkerPlanck.Histogram\nimport Foreign.CUDA.Driver as CUDA\nimport FourierMethod.FourierSeries2D\nimport Image.IO\nimport Pinwheel.FourierSeries2D\nimport Pinwheel.Transform\nimport Sparse.Vector\nimport STC.Utils\nimport System.FilePath\nimport Utils.Array\nimport Utils.List\nimport Utils.Parallel\nimport Utils.SimpsonRule\nimport Utils.Time\nimport Text.Printf\nimport Utils.Distribution\n\nsampleCartesian ::\n FilePath\n -> FilePath\n -> [PTX]\n -> Int\n -> Double\n -> Double\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> Int\n -> Int\n -> Int\n -> Int -> Double\n -> IO (Histogram (Complex Double))\nsampleCartesian filePath folderPath ptxs numPoints period delta oris gamma thetaSigma tau threshold r2Sigma maxPhiFreqs maxRhoFreqs maxThetaFreqs maxRFreqs stdR2 = do\n let center = div numPoints 2\n deltaTheta = 2 * pi / fromIntegral oris\n origin = R2S1RP 0 0 0 gamma\n idx =\n L.filter\n (\\(R2S1RP c r _ g) -> (sqrt (c ^ 2 + r ^ 2) > 0) && g > 0)\n [ R2S1RP\n ((fromIntegral $ c - center) * delta)\n ((fromIntegral $ r - center) * delta)\n 0\n gamma\n | c <- [0 .. numPoints - 1]\n , r <- [0 .. numPoints - 1]\n ]\n logGamma = 0 -- log gamma\n -- simpsonWeights = weightsSimpsonRule oris\n xs =\n L.concat -- .\n -- L.zipWith\n -- (\\w -> L.map (\\(a, b, c, d, v) -> (a, b, c, d, v * w)))\n -- simpsonWeights\n $\n parMap\n rdeepseq\n (\\o ->\n let ori = fromIntegral o * deltaTheta\n in L.filter (\\(_, _, _, _, v) -> v > threshold) .\n L.map\n (\\point@(R2S1RP x y _ g) ->\n let v =\n computePji thetaSigma tau origin (R2S1RP x y ori g)\n phi = atan2 y x\n rho = sqrt $ (x ^ 2 + y ^ 2)\n in ( phi\n , log rho\n , ori\n , logGamma\n , v * (1 - gaussian2DPolar rho stdR2)\n )) $\n idx)\n [0 .. oris - 1]\n -- arr <-\n -- computeUnboxedP . fromFunction (Z :. oris :. numPoints :. numPoints) $ \\(Z :. o :. i :. j) ->\n -- let x = (fromIntegral $ i - center) * delta\n -- y = (fromIntegral $ j - center) * delta\n -- phi = atan2 y x\n -- rho = sqrt $ (x ^ 2 + y ^ 2)\n -- theta = fromIntegral o * deltaTheta\n -- v = computePji thetaSigma tau origin (R2S1RP x y theta gamma)\n -- in if rho <= 1.5\n -- then (1, 1, 1, 1, 0)\n -- else (phi, log rho, theta, logGamma, v)\n -- plotImageRepa (folderPath \"GreensFunction.png\") .\n -- ImageRepa 8 .\n -- computeS .\n -- -- reduceContrast 20 .\n -- extend (Z :. (1 :: Int) :. All :. All) .\n -- sumS . rotate3D . R.map (\\(_, _, _, _, v) -> v) $\n -- arr\n -- simpsonWeights =\n -- computeWeightArrFromListOfShape [numPoints, numPoints, oris]\n -- xs =\n -- L.filter (\\(_, _, _, _, v) -> v > threshold) .\n -- R.toList -- .\n -- -- R.zipWith (\\w (a, b, c, d, v) -> (a, b, c, d, w * v)) simpsonWeights\n -- $\n -- arr\n let\n printCurrentTime $\n printf\n \"Sparsity: %f%%\\n\"\n (100 * (fromIntegral . L.length $ xs) /\n (fromIntegral $ oris * numPoints ^ 2) :: Double)\n let phiFreqs = L.map fromIntegral [-maxPhiFreqs .. maxPhiFreqs]\n rhoFreqs = L.map fromIntegral [-maxRhoFreqs .. maxRhoFreqs]\n thetaFreqs = L.map fromIntegral [-maxThetaFreqs .. maxThetaFreqs]\n rFreqs = L.map fromIntegral [-maxRFreqs .. maxRFreqs]\n hist =\n L.foldl1' (addHistogram) .\n parZipWith\n rdeepseq\n (\\ptx ys ->\n computeFourierCoefficientsGPU'\n r2Sigma\n period\n phiFreqs\n rhoFreqs\n thetaFreqs\n rFreqs\n ptx\n ys)\n ptxs .\n divideListN (L.length ptxs) $\n xs\n encodeFile filePath hist\n return hist\n \n\nsampleCartesianCorner ::\n FilePath\n -> FilePath\n -> [PTX]\n -> Int\n -> Double\n -> Double\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> Int\n -> Int\n -> Int\n -> Int\n -> Double\n -> Double\n -> IO (Histogram (Complex Double))\nsampleCartesianCorner filePath folderPath ptxs numPoints period delta oris gamma thetaSigma tau threshold r2Sigma maxPhiFreqs maxRhoFreqs maxThetaFreqs maxRFreqs stdR2 weight = do\n let center = div numPoints 2\n deltaTheta = 2 * pi / fromIntegral oris\n -- origin = R2S1RP 0 0 0 gamma\n logGamma = 0\n idxFunc c r o =\n ( fromIntegral o * deltaTheta\n , fromIntegral (c - center) * delta\n , fromIntegral (r - center) * delta)\n -- arr1 =\n -- fromFunction (Z :. oris :. numPoints :. numPoints) $ \\(Z :. o :. c :. r) ->\n -- if c == center && r == center\n -- then 0\n -- else let (ori, x, y) = idxFunc c r o\n -- in computePji thetaSigma tau origin (R2S1RP x y ori gamma)\n -- orientations = [fromIntegral i * deltaTheta | i <- [0 .. oris - 1]]\n -- arr2 =\n -- fromFunction (Z :. oris :. numPoints :. numPoints) $ \\(Z :. o :. c :. r) ->\n -- if c == center && r == center\n -- then 0\n -- else let (ori, x, y) = idxFunc c r o\n -- in computePjiCorner'\n -- thetaSigma\n -- tau\n -- threshold\n -- orientations\n -- (R2S1RP x y ori gamma)\n -- arr <- computeUnboxedP $ arr1 +^ (R.map (* weight) arr2)\n arr <- sampleR2S1Corner numPoints numPoints delta deltaTheta gamma thetaSigma tau threshold [0 .. oris - 1] weight\n let idx =\n [ idxFunc c r o\n | o <- [0 .. oris - 1]\n , c <- [0 .. numPoints - 1]\n , r <- [0 .. numPoints - 1]\n ]\n xs =\n L.map\n (\\((ori, x, y), v) ->\n let phi = atan2 y x\n rho = sqrt (x ^ 2 + y ^ 2)\n in ( phi\n , log rho\n , ori\n , logGamma\n , v * (1 - gaussian2DPolar rho stdR2))) .\n L.filter (\\((_, x, y), v) -> v > threshold && (x /= 0 || y /= 0)) .\n L.zip idx . R.toList $\n arr\n printCurrentTime $\n printf\n \"Sparsity: %f%%\\n\"\n (100 * (fromIntegral . L.length $ xs) /\n (fromIntegral $ oris * numPoints ^ 2) :: Double)\n let phiFreqs = L.map fromIntegral [-maxPhiFreqs .. maxPhiFreqs]\n rhoFreqs = L.map fromIntegral [-maxRhoFreqs .. maxRhoFreqs]\n thetaFreqs = L.map fromIntegral [-maxThetaFreqs .. maxThetaFreqs]\n rFreqs = L.map fromIntegral [-maxRFreqs .. maxRFreqs]\n hist =\n L.foldl1' (addHistogram) .\n parZipWith\n rdeepseq\n (\\ptx ys ->\n computeFourierCoefficientsGPU'\n r2Sigma\n period\n phiFreqs\n rhoFreqs\n thetaFreqs\n rFreqs\n ptx\n ys)\n ptxs .\n divideListN (L.length ptxs) $\n xs\n encodeFile filePath hist\n return hist\n\n\n-- sampleLogpolar ::\n-- FilePath\n-- -> [PTX]\n-- -> Int\n-- -> Int\n-- -> Int\n-- -> Double\n-- -> Double\n-- -> Double\n-- -> Double\n-- -> Double\n-- -> Double\n-- -> Int\n-- -> Int\n-- -> Int\n-- -> Int\n-- -> IO (Histogram (Complex Double))\n-- sampleLogpolar filePath ptxs phis rhos oris maxScale gamma sigma tau threshold r2Sigma maxPhiFreqs maxRhoFreqs maxThetaFreqs maxRFreqs = do\n-- let deltaPhi = 2 * pi / fromIntegral phis\n-- deltaTheta = 2 * pi / fromIntegral oris\n-- logMaxScale = log maxScale\n-- deltaLogRho = logMaxScale / fromIntegral rhos\n-- logGamma = 0 -- log gamma\n-- origin = R2S1RP 0 0 0 gamma\n-- -- xs =\n-- -- parMap\n-- -- rdeepseq\n-- -- (\\(phi, logRho, theta) ->\n-- -- let x = (exp logRho) * cos phi\n-- -- y = (exp logRho) * sin phi\n-- -- v = computePji sigma tau origin (R2S1RP x y theta gamma)\n-- -- in (phi, logRho, theta, 0, v))\n-- -- [ ( deltaTheta * fromIntegral iPhi\n-- -- , deltaLogRho * fromIntegral iLogRho - logMaxScale\n-- -- , deltaTheta * fromIntegral iTheta)\n-- -- | iPhi <- [0 .. oris - 1]\n-- -- , iLogRho <- [0 .. rhos - 1]\n-- -- , iTheta <- [0 .. oris - 1]\n-- -- ]\n-- arr <-\n-- computeUnboxedP . R.fromFunction (Z :. oris :. rhos :. phis) $ \\(Z :. iTheta :. iLogRho :. iPhi) ->\n-- let theta = deltaTheta * fromIntegral iTheta\n-- phi = deltaPhi * fromIntegral iPhi\n-- logRho = deltaLogRho * fromIntegral iLogRho -- logMaxScale\n-- x = (exp logRho) * cos phi\n-- y = (exp logRho) * sin phi\n-- v = computePji sigma tau origin (R2S1RP x y theta gamma)\n-- in (phi, logRho, theta, logGamma, v)\n-- let simpsonWeights = computeWeightArrFromListOfShape [phis, rhos, oris]\n-- xs =\n-- L.filter (\\(_, _, _, _, v) -> v > threshold) .\n-- R.toList .\n-- R.zipWith (\\w (a, b, c, d, v) -> (a, b, c, d, w * v)) simpsonWeights $\n-- arr\n-- printCurrentTime $\n-- printf\n-- \"Sparsity: %f%%\\n\"\n-- (100 * (fromIntegral . L.length $ xs) / (fromIntegral $ oris * phis * rhos) :: Double)\n-- let phiFreqs = L.map fromIntegral [-maxPhiFreqs .. maxPhiFreqs]\n-- rhoFreqs = L.map fromIntegral [-maxRhoFreqs .. maxRhoFreqs]\n-- thetaFreqs = L.map fromIntegral [-maxThetaFreqs .. maxThetaFreqs]\n-- rFreqs = L.map fromIntegral [-maxRFreqs .. maxRFreqs]\n-- hist =\n-- L.foldl1' (addHistogram) .\n-- parZipWith\n-- rdeepseq\n-- (\\ptx ys ->\n-- computeFourierCoefficientsGPU'\n-- r2Sigma\n-- phiFreqs\n-- rhoFreqs\n-- thetaFreqs\n-- rFreqs\n-- ptx\n-- ys)\n-- ptxs .\n-- divideListN (L.length ptxs) $\n-- xs\n-- encodeFile filePath hist\n-- return hist\n\n{-# INLINE sampleR2S1 #-}\nsampleR2S1 ::\n Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> [Int]\n -> IO (R.Array U DIM3 Double)\nsampleR2S1 rows cols delta deltaTheta gamma sigma tau oris = do\n let centerRow = div rows 2\n centerCol = div cols 2\n origin = R2S1RP 0 0 0 gamma\n computeUnboxedP .\n R.traverse\n (fromListUnboxed (Z :. (L.length oris)) oris)\n (\\(Z :. o) -> (Z :. o :. cols :. rows)) $ \\f (Z :. o :. c :. r) ->\n if (c == centerCol) && (r == centerRow)\n then 0\n else computePji\n sigma\n tau\n origin\n (R2S1RP\n (delta * fromIntegral (c - centerCol))\n (delta * fromIntegral (r - centerRow))\n (fromIntegral (f (Z :. o)) * deltaTheta)\n gamma)\n\n{-# INLINE sampleR2S1' #-}\nsampleR2S1' ::\n Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> R.Array U DIM2 (Int, Double)\nsampleR2S1' rows cols delta gamma sigma tau ori =\n let centerRow = div rows 2\n centerCol = div cols 2\n origin = R2S1RP 0 0 0 gamma\n in computeUnboxedS . R.fromFunction (Z :. cols :. rows) $ \\(Z :. c :. r) ->\n let x = c - centerCol\n y = r - centerRow\n in if x == 0 && y == 0\n then (0, 0)\n else ( getVectorIndex2D rows c r\n , computePji\n sigma\n tau\n origin\n (R2S1RP\n (delta * fromIntegral (c - centerCol))\n (delta * fromIntegral (r - centerRow))\n ori\n gamma))\n \n\n{-# INLINE sampleR2S1Corner #-}\nsampleR2S1Corner ::\n Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> [Int]\n -> Double\n -> IO (R.Array U DIM3 Double)\nsampleR2S1Corner rows cols delta deltaTheta gamma sigma tau threshold oris weight = do\n let centerRow = div rows 2\n centerCol = div cols 2\n origin = R2S1RP 0 0 0 gamma\n orientations = L.map (\\o -> deltaTheta * fromIntegral o) oris\n arr1 <-\n computeUnboxedP .\n R.traverse\n (fromListUnboxed (Z :. (L.length oris)) oris)\n (\\(Z :. o) -> (Z :. o :. cols :. rows)) $ \\f (Z :. o :. c :. r) ->\n if (c == centerCol) && (r == centerRow)\n then 0\n else computePji\n sigma\n tau\n origin\n (R2S1RP\n (delta * fromIntegral (c - centerCol))\n (delta * fromIntegral (r - centerRow))\n (fromIntegral (f (Z :. o)) * deltaTheta)\n gamma)\n arr2 <-\n computeUnboxedP .\n R.traverse\n (fromListUnboxed (Z :. (L.length oris)) oris)\n (\\(Z :. o) -> (Z :. o :. cols :. rows)) $ \\f (Z :. o :. c :. r) ->\n if (c == centerCol) && (r == centerRow)\n then 0\n else computePjiCorner'\n delta\n sigma\n tau\n threshold\n orientations\n (R2S1RP\n (delta * fromIntegral (c - centerCol))\n (delta * fromIntegral (r - centerRow))\n (fromIntegral (f (Z :. o)) * deltaTheta)\n gamma)\n computeUnboxedP $ (arr1 +^ (R.map (* weight) arr2))\n \n\ncornerDistribution ::\n Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> [Double]\n -> Double\n -> (Double, Double)\n -> [Double]\ncornerDistribution delta gamma sigma tau threshold oris weight (x, y) =\n let origin = R2S1RP 0 0 0 gamma\n in L.map\n (\\ori ->\n computePji sigma tau origin (R2S1RP x y ori gamma) +\n weight *\n computePjiCorner'\n delta\n sigma\n tau\n threshold\n oris\n (R2S1RP x y ori gamma))\n oris\n \n{-# INLINE cornerDistribution' #-}\ncornerDistribution' ::\n Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> [Double]\n -> Double\n -> (Double, Double)\n -> Double\n -> IO (Double, Double, Double)\ncornerDistribution' delta gamma sigma tau threshold oris weight (x, y) ori = do\n let origin = R2S1RP 0 0 0 gamma\n a = computePji sigma tau origin (R2S1RP x y ori gamma)\n b = computePjiCorner' delta sigma tau threshold oris (R2S1RP x y ori gamma)\n printf \"sigma = %f\\ntau = %f\\nthreshold = %f\\noris = %s\\n(R2S1RP %f %f %f %f)\\n\" sigma tau threshold (show oris) x y ori gamma\n return (a, b, a + weight * b)\n\n\n\ncomputeFourierCoefficients ::\n FilePath\n -> [Int]\n -> [PTX]\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> Int\n -> Double\n -> Double\n -> Int\n -> Int\n -> Int\n -> Int\n -> Int\n -> Int\n -> IO (Histogram (Complex Double))\ncomputeFourierCoefficients histFilePath deviceIDs ptxs numPoints oris delta deltaFreq gamma sigma tau numR2Freqs period std numBatchR2Freqs numBatchOri maxPhiFreq maxRhoFreq maxThetaFreq maxRFreq = do\n when\n (even oris)\n (error \"computeFourierCoefficients: the number of orientations is not odd.\")\n let deltaTheta = 2 * pi / fromIntegral oris\n simpsonWeights =\n computeUnboxedS $\n (computeWeightArrFromListOfShape [numPoints, numPoints] :: R.Array D DIM2 (Complex Double))\n oriIdxs = divideListN numBatchOri [0 .. oris - 1]\n xs <-\n M.mapM\n (sampleR2S1 numPoints numPoints delta deltaTheta gamma sigma tau)\n oriIdxs\n let weightedVecs =\n parMap\n rdeepseq\n (\\arr ->\n let (Z :. n :. m :. c) = extent arr\n in CuMat (n * m) c .\n CuVecHost .\n VU.convert .\n toUnboxed . computeS . R.traverse2 arr simpsonWeights const $ \\f fW idx@(Z :. i :. j :. _) ->\n (f idx :+ 0) * fW (Z :. i :. j))\n xs\n coefficients <-\n computeFourierCoefficientsR2Stream\n deviceIDs\n ptxs\n numR2Freqs\n numPoints\n period\n delta\n deltaFreq\n numBatchR2Freqs\n weightedVecs\n print \"coefficients done\"\n let centerR2Freq = div numR2Freqs 2\n centerPoints = div numPoints 2\n logGamma = log gamma\n gaussianWeightedCoef =\n computeUnboxedS $ applyGaussian deltaFreq std coefficients\n -- gaussianWeightedCoef = coefficients\n simpsonWeightsOri =\n computeUnboxedS $\n (computeWeightArrFromListOfShape [oris] :: R.Array D DIM1 (Complex Double))\n weightedCoef =\n R.traverse2 gaussianWeightedCoef simpsonWeightsOri const $ \\fG fS idx@(Z :. o :. _ :. _) ->\n fG idx * fS (Z :. o)\n folderPath = \"output/test/STCPinwheel\"\n -- print . extent $ gaussianWeightedCoef\n -- inverseR2Harmonics <-\n -- createInverseHarmonicMatriesGPU ptxs 1 numPoints numR2Freqs period delta\n -- sourceR2 <-\n -- computeFourierSeriesR2\n -- deviceIDs\n -- numR2Freqs\n -- numPoints\n -- period\n -- inverseR2Harmonics\n -- [ CuMat oris (numR2Freqs ^ 2) . CuVecHost . VU.convert . toUnboxed $\n -- gaussianWeightedCoef\n -- ]\n plotImageRepa (folderPath \"Green.png\") .\n ImageRepa 8 .\n fromUnboxed (Z :. (1 :: Int) :. numPoints :. numPoints) .\n VU.map sqrt . toUnboxed . sumS . R.map (\\x -> (x) ** 2) . L.head $\n xs\n plotImageRepa (folderPath \"Coefficients.png\") .\n ImageRepa 8 .\n fromUnboxed (Z :. (1 :: Int) :. numR2Freqs :. numR2Freqs) .\n VU.map sqrt . toUnboxed . sumS . R.map (\\x -> (magnitude x) ** 2) . rotate3D $\n gaussianWeightedCoef\n -- plotImageRepa (folderPath \"GreenRecon.png\") .\n -- ImageRepa 8 .\n -- fromUnboxed (Z :. (1 :: Int) :. numPoints :. numPoints) .\n -- VU.map sqrt . toUnboxed . sumS . R.map (\\x -> (magnitude x) ** 2) . rotate3D $\n -- sourceR2\n ys <-\n (computeUnboxedP . R.traverse weightedCoef id $ \\f idx@(Z :. o :. i :. j) ->\n if i == centerR2Freq && j == centerR2Freq\n then (0, 0, 0, 0, 0)\n else let x = deltaFreq * (fromIntegral $ i - centerR2Freq)\n y = deltaFreq * (fromIntegral $ j - centerR2Freq)\n phi = atan2 y x\n logRho = log . sqrt $ (x ^ 2 + y ^ 2)\n in (phi, logRho, fromIntegral o * deltaTheta, logGamma, f idx))\n -- ys <-\n -- (computeUnboxedP .\n -- R.traverse\n -- (R.traverse2 (L.head xs) simpsonWeightsOri const $ \\fG fS idx@(Z :. _ :. _ :. o) ->\n -- (fG idx :+ 0) * fS (Z :. o))\n -- id $ \\f idx@(Z :. i :. j :. o) ->\n -- if i == centerPoints && j == centerPoints\n -- then (0, 0, 0, 0, 0)\n -- else let x = delta * (fromIntegral $ i - centerPoints)\n -- y = delta * (fromIntegral $ j - centerPoints)\n -- phi = atan2 x y\n -- logRho = log . sqrt $ (x ^ 2 + y ^ 2)\n -- in ( phi\n -- , logRho\n -- , fromIntegral o * deltaTheta\n -- , logGamma\n -- , f idx))\n let hist =\n L.foldl1' (addHistogram) .\n parZipWith\n rdeepseq\n (\\ptx ->\n computePinwheelCoefficients\n maxPhiFreq\n maxRhoFreq\n maxThetaFreq\n maxRFreq\n ptx)\n ptxs .\n divideListN (L.length ptxs) . R.toList $\n ys\n encodeFile histFilePath hist\n return hist\n\n\n\ncomputePinwheelTransformCoefficients ::\n Int\n -> FilePath\n -> [Int]\n -> [PTX]\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> Int\n -> Double\n -> Double\n -> Int\n -> Int\n -> Int\n -> Int\n -> Int\n -> Int\n -> Int\n -> Double\n -> IO (Histogram (Complex Double))\ncomputePinwheelTransformCoefficients numThread histFilePath deviceIDs ptxs numPoints oris delta threshold gamma sigma tau numR2Freqs periodR2 std numBatchR2 numBatchPinwheelFreqs maxPhiFreq maxRhoFreq maxThetaFreq maxRFreq batchSize s = do\n printCurrentTime \"compute pinwheelArr\"\n pinwheelArr <-\n pinwheelFourierSeries\n deviceIDs\n ptxs\n numPoints -- numR2Freqs\n numPoints\n delta\n periodR2\n maxPhiFreq\n maxRhoFreq\n maxThetaFreq\n maxRFreq\n s\n numBatchR2\n numBatchPinwheelFreqs :: IO (IA.Array (Int, Int) (VU.Vector (Complex Double)))\n printCurrentTime \"pinwheelArr done\"\n let folderPath = \"output/test/STCPinwheel\"\n let deltaTheta = 2 * pi / (fromIntegral oris)\n greensFunc =\n parMap\n rdeepseq\n (\\o ->\n let theta = fromIntegral o * deltaTheta\n vec =\n toUnboxed $\n sampleR2S1' numPoints numPoints delta gamma sigma tau theta\n in PinwheelTransformData (log gamma) theta .\n uncurry SparseVector .\n VU.unzip .\n VU.map (\\(i, v) -> (i, v :+ 0)) .\n VU.filter (\\(_, v) -> v > threshold) $\n vec)\n [0 .. oris - 1]\n len =\n L.foldl'\n (\\s (PinwheelTransformData _ _ (SparseVector vec _)) ->\n s + VU.length vec)\n 0\n greensFunc\n printCurrentTime $\n printf\n \"Sparsity: %f%%\\n\"\n (100 * (fromIntegral len) / (fromIntegral $ oris * numPoints ^ 2) :: Double)\n let hist =\n pinwheelTransform\n numThread\n maxPhiFreq\n maxRhoFreq\n maxThetaFreq\n maxRFreq\n s\n pinwheelArr\n greensFunc\n encodeFile histFilePath hist\n return hist\n", "meta": {"hexsha": "508aac21c1dd40838fac70446f095c6a9d04a2c6", "size": 22574, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FokkerPlanck/GreensFunction.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FokkerPlanck/GreensFunction.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/FokkerPlanck/GreensFunction.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.4839609484, "max_line_length": 239, "alphanum_fraction": 0.511916364, "num_tokens": 6698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5651050823152096}} {"text": "{-|\nModule : Qubism.StateVec\nDescription : Types and functions for quantum state vectors\nCopyright : (c) Keith Pearson, 2018\nLicense : MIT\nMaintainer : keith@qubitrot.org\n-}\n\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule Qubism.StateVec\n ( StateVec (UnsafeMkStateVec)\n , mkStateVec\n , mkStateVec'\n , mkQubit\n , normalize\n , tensor\n , collapse\n , measureQubit\n , measure\n , dimension\n ) where\n\n-- For dependent typing\nimport GHC.TypeLits\nimport Data.Singletons\nimport Data.Singletons.TypeLits\nimport Data.Finite\n\nimport Control.Monad.Random\nimport Control.Monad.Trans.State.Strict\nimport Data.Complex\nimport Numeric.LinearAlgebra ((|>))\nimport qualified Numeric.LinearAlgebra as LA\nimport Text.Printf\n\nimport Qubism.Algebra\nimport Qubism.CReg\n\nnewtype StateVec (n :: Nat) =\n UnsafeMkStateVec (LA.Vector C)\n\n-- | To provide \"close enough\" equality testing.\ninstance Eq (StateVec n) where\n UnsafeMkStateVec zs == UnsafeMkStateVec ws = \n LA.norm_2 (zs - ws) < 0.000001\n\ninstance KnownNat n => VectorSpace (StateVec n) where\n zero = UnsafeMkStateVec $ internalLen (sing :: Sing n) |> repeat 0\n z .: (UnsafeMkStateVec a) = UnsafeMkStateVec $ LA.scalar z * a\n (UnsafeMkStateVec a) +: (UnsafeMkStateVec b) = UnsafeMkStateVec $ a + b\n neg (UnsafeMkStateVec a) = UnsafeMkStateVec $ -a\n\ninstance KnownNat n => HilbertSpace (StateVec n) where\n (UnsafeMkStateVec zs) <.> (UnsafeMkStateVec ws) = zs LA.<.> ws\n\ninstance KnownNat n => Show (StateVec n) where\n show (UnsafeMkStateVec zs) = foldl show' \"\" $ zip [0..] (LA.toList zs)\n where show' str (i,z) = str ++ pf z ++ \" \" ++ basis i ++ \"\\n\"\n pf z = printf \"% 6.4f\" (realPart z) ++ \" + \" \n ++ printf \"% 6.4f\" (imagPart z) ++ \"i\"\n basis i = let bit j = if i `quot` 2^(n-j-1) `mod` 2 == 0\n then '0' else '1'\n in \"|\" ++ fmap bit (take n [0..]) ++ \">\"\n n = fromIntegral $ fromSing (sing :: Sing n)\n\ninternalLen :: (KnownNat n, Num a) => Sing n -> a\ninternalLen = (2 ^) . fromIntegral . fromSing \n\n-- | Number of qubits in the StateVec\ndimension :: forall (n :: Nat) a. (KnownNat n, Num a) => StateVec n -> a\ndimension _ = fromIntegral $ fromSing (sing :: SNat n)\n\n-- | StateVec's are intialized to |0>\nmkStateVec :: forall n . KnownNat n => StateVec n\nmkStateVec = UnsafeMkStateVec $ internalLen (sing :: Sing n) |> (1 : repeat 0) \n\n-- | Make a statevector with an explicity specified size.\n-- StateVec's are intialized to |0>\nmkStateVec' :: Sing n -> StateVec n\nmkStateVec' sn = UnsafeMkStateVec $ l |> (1 : repeat 0) \n where l = (2^) . fromIntegral $ fromSing sn\n\n-- | A qubit is just a StateVec 1, initalized to |0>\nmkQubit :: StateVec 1\nmkQubit = UnsafeMkStateVec $ LA.fromList [1, 0]\n\nnormalize :: StateVec n -> StateVec n\nnormalize (UnsafeMkStateVec zs) = UnsafeMkStateVec $ LA.normalize zs\n\nadjoint :: KnownNat n => StateVec n -> (StateVec n -> C)\nadjoint qr = (qr <.>)\n\n-- | The tensor product on elements of our Hilbert space\ntensor :: StateVec n -> StateVec m -> StateVec (n + m)\ntensor (UnsafeMkStateVec zs) (UnsafeMkStateVec ws) =\n UnsafeMkStateVec $ LA.flatten (zs `LA.outer` ws)\n\n-- | Collapse a StateVec to a state compatable with qubit being measured .\n-- Only occurs physically with measurement, so internal use only.\ncollapse \n :: forall n . KnownNat n \n => Finite n -> Bit -> StateVec n -> StateVec n\ncollapse i b (UnsafeMkStateVec zs) = normalize . UnsafeMkStateVec $ zs * mask\n where\n mask = l |> altseq\n altseq = replicate m ifZero ++ replicate m ifOne ++ altseq\n ifZero = if b == Zero then 1 else 0\n ifOne = if b == One then 1 else 0\n l = internalLen (sing :: Sing n)\n m = l `quot` (2 ^ (getFinite i + 1))\n\n-- | Preforms a measurement of an induvidual qubit (indexed Finite n) \n-- in a quantum register.\nmeasureQubit \n :: (MonadRandom m, KnownNat n) \n => Finite n -> StateT (StateVec n) m Bit\nmeasureQubit i = do\n qr <- get\n r <- getRandomR (0, 1)\n let qrZero = collapse i Zero qr\n qrOne = collapse i One qr\n pOne = realPart $ qrOne <.> qr -- guaranteed to be real, so this\n if r < pOne -- is just a type-cast.\n then put qrOne >> pure One\n else put qrZero >> pure Zero\n\n-- | Preform a measurement on all qubits in a quantum register, returning a \n-- computational basis state.\nmeasure\n :: forall m n . (MonadRandom m, KnownNat n) \n => StateT (StateVec n) m CReg\nmeasure = mkCReg <$> traverse measureQubit (take n [0 ..])\n where n = fromIntegral $ fromSing (sing :: Sing n)\n", "meta": {"hexsha": "7b4a2d2d174ffbb0139e2232cb8d85712d433d9a", "size": 4728, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Qubism/StateVec.hs", "max_stars_repo_name": "qubitrot/qubism", "max_stars_repo_head_hexsha": "41d2fd594d338affdfe1736aec422d75c2cc9401", "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/Qubism/StateVec.hs", "max_issues_repo_name": "qubitrot/qubism", "max_issues_repo_head_hexsha": "41d2fd594d338affdfe1736aec422d75c2cc9401", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-09-17T20:07:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T03:29:45.000Z", "max_forks_repo_path": "src/Qubism/StateVec.hs", "max_forks_repo_name": "qubitrot/qubism", "max_forks_repo_head_hexsha": "41d2fd594d338affdfe1736aec422d75c2cc9401", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2608695652, "max_line_length": 83, "alphanum_fraction": 0.6417089679, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.5648822756131155}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Control.Monad (forever)\nimport Control.Monad.IO.Class (MonadIO (liftIO))\nimport Control.Monad.State.Strict\n ( MonadState (get, put),\n execStateT,\n forever,\n lift,\n runStateT,\n )\nimport Data.Complex (Complex (..), magnitude)\nimport Data.List (foldl')\nimport qualified Data.Text as T\nimport System.Random (Random (randomR), newStdGen)\nimport UI.NCurses\n ( Color (..),\n CursorMode (..),\n defaultWindow,\n drawText,\n moveCursor,\n render,\n runCurses,\n setColor,\n setCursorMode,\n setEcho,\n updateWindow,\n )\nimport UI.NCurses.HalfHeight\n ( Buffer,\n colorId,\n drawBuffer,\n initHexColors,\n mkBuffer,\n setXY,\n )\n\n-- Set up a 15-color greyscale pallette\ngreyScale :: [String]\ngreyScale =\n [ \"000000\",\n \"111111\",\n \"222222\",\n \"333333\",\n \"444444\",\n \"666666\",\n \"777777\",\n \"888888\",\n \"999999\",\n \"aaaaaa\",\n \"bbbbbb\",\n \"cccccc\",\n \"dddddd\",\n \"eeeeee\",\n \"ffffff\"\n ]\n\n-- Calculate the Mandelbrot steps-to-divergence and plot as Color 1 to Color 15\nmandelbrot :: (Fractional a, RealFloat a) => a -> a -> Color\nmandelbrot x y = Color (16 - ((+) 1 $ steps (0 :+ 0) (x' :+ y') 0))\n where\n x' = (x - 100) * 0.025\n y' = (y - 50) * 0.025\n steps z c i\n | i > 13 || magnitude z' > 2 = i\n | otherwise = steps z' c (i + 1)\n where\n z' = z * z + c\n\n-- Draw the Mandelbrot set to the buffer point by point\ndrawMandelbrot :: Buffer -> Buffer\ndrawMandelbrot buffer =\n foldl'\n (\\b (x, y) -> setXY x y (mandelbrot (fromIntegral x) (fromIntegral y)) b)\n buffer\n [(x, y) | x <- [0 .. 149], y <- [0 .. 99]]\n\nmandelbrotMain :: IO ()\nmandelbrotMain = do\n -- Register the 15 greyscale hex colors as Color 1 through Color 15.\n -- Every combination of these colors (fg and bg) is registered with Curses\n -- with a unique ID, which we return in the colorMap.\n colorMap <- runCurses $ initHexColors nord\n\n -- Creates a new buffer and draws the Mandelbrot set in each cell using the\n -- greyscale colors 1 through 15\n let buffer = drawMandelbrot $ mkBuffer 150 100 (Color 1)\n\n runCurses $ do\n -- Hide the cursor\n setEcho False\n setCursorMode CursorInvisible\n\n -- Enter an infinite drawing loop displaying the buffer.\n forever $ do\n let drawOp = do\n -- First draw the buffer to the screen.\n drawBuffer colorMap 0 0 buffer\n -- Now draw some text in the centre.\n -- We set the color to curses ID corresponding to fg 15 (white) and bg 1 (black)\n let (Just c) = colorId colorMap (Color 15) (Color 1)\n setColor c\n moveCursor 25 50\n drawText \"| Text demonstrating that each cell is half the row height |\"\n w <- defaultWindow\n updateWindow w drawOp\n render\n\nnord :: [String]\nnord =\n [ \"3b4252\",\n \"bf616a\",\n \"a3be8c\",\n --\"ebcb8b\",\n \"81a1c1\",\n \"b48ead\",\n \"88c0d0\",\n \"e5e9f0\",\n \"4c566a\",\n \"bf616a\",\n \"a3be8c\",\n \"ebcb8b\",\n \"81a1c1\",\n \"b48ead\",\n \"8fbcbb\",\n \"eceff4\"\n ]\n\nperformanceMain :: IO ()\nperformanceMain = do\n colorMap <- runCurses $ initHexColors greyScale\n -- Precompute the buffers\n let buffer = mkBuffer 100 100 (Color 1)\n col x y t =\n let x' = fromIntegral (x - 50)\n y' = fromIntegral (y - 50)\n t' = fromIntegral t\n in abs $ round $ (14 * ((sin $ 0.1 * x') * (cos $ 0.1 * y')) / (sin $ 0.1 * t')) + 1\n nextBuf b t = foldl' (\\b (x, y) -> setXY x y (Color $ col x y t) b) b [(x, y) | x <- [0 .. 99], y <- [0 .. 99]]\n bufs = cycle $ scanl nextBuf buffer [0 .. 63]\n runCurses $ do\n _ <- (flip runStateT) (bufs, 0) $ do\n lift $ setEcho False\n lift $ setCursorMode CursorInvisible\n forever $ do\n (bufs, t) <- get\n let b = head bufs\n drawOp = do\n drawBuffer colorMap 0 0 b\n let (Just c) = colorId colorMap (Color 15) (Color 1)\n setColor c\n moveCursor 0 0\n drawText $ T.pack $ show t\n w <- lift defaultWindow\n lift $ updateWindow w drawOp\n lift render\n put (tail bufs, t + 1)\n return ()\n\nmain :: IO ()\nmain = do\n --mandelbrotMain\n performanceMain\n", "meta": {"hexsha": "5b80ed6ef127f7ccbdef5d40677a125cd69bb2a7", "size": 4273, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "harryaskham/halfheight", "max_stars_repo_head_hexsha": "0025348cc033be3db340ae53f00164db69dfd771", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "harryaskham/halfheight", "max_issues_repo_head_hexsha": "0025348cc033be3db340ae53f00164db69dfd771", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "harryaskham/halfheight", "max_forks_repo_head_hexsha": "0025348cc033be3db340ae53f00164db69dfd771", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7409638554, "max_line_length": 117, "alphanum_fraction": 0.5789843201, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5647695307877248}} {"text": "module Problem215 where\n{-\n Task description:\n Consider the problem of building a wall out of 2\u00d71 and 3\u00d71 bricks (horizontal\u00d7vertical dimensions) such that,\n for extra strength, the gaps between horizontally-adjacent bricks never line up in consecutive layers, i.e. never form a \"running crack\".\n\n For example, the following 9\u00d73 wall is not acceptable due to the running crack shown in red:\n\n There are eight ways of forming a crack-free 9\u00d73 wall, written W(9,3) = 8.\n\n Calculate W(32,10).\n-}\n\nimport Control.Monad\nimport Data.Function (on)\nimport Data.Graph (Graph, Vertex)\nimport Data.Maybe (fromJust)\nimport Numeric.LinearAlgebra (Matrix, (<>))\nimport qualified GHC.Arr as Arr\nimport qualified Data.Graph as Graph\nimport qualified Data.HashSet as HashSet\nimport qualified Data.List as List\nimport qualified Data.Map as Map\nimport qualified Data.Tree as Tree\nimport qualified Numeric.LinearAlgebra as LA\n\n{-\nA row may only ever depend on the preceding row.\nWe may have cycles of rows that are allowed to follow each other.\nAn interesting question will be wether collapsing such cycles will be easier than simply 'exploring them'.\nIn both ways memoization may come in handy here.\n-}\n\ntype Brick = Int\ntype Line = [Brick]\ntype Width = Int\ntype Height = Int\ntype Wall = [Line]\n\nbricks :: [Brick]\nbricks = [2, 3]\n\nbuildLines :: Width -> [Line]\nbuildLines 0 = [[]]\nbuildLines w = do\n brick <- bricks\n guard $ brick <= w\n lineRest <- buildLines $ w - brick\n return $ brick:lineRest\n\nmatchingLines :: Line -> Line -> Bool\nmatchingLines l1 l2 = not $ (matchingCracks `on` crackPositions) l1 l2\n where\n crackPositions :: Line -> [Int]\n crackPositions = fmap sum . init . tail . List.inits\n\n matchingCracks :: [Int] -> [Int] -> Bool\n matchingCracks [] _ = False\n matchingCracks _ [] = False\n matchingCracks xss@(x:xs) yss@(y:ys)\n | x == y = True\n | x < y = matchingCracks xs yss\n | x > y = matchingCracks xss ys\n\n{-\nWith the matchingLines predicate I can generate a graph out of the possible lines.\nWe're searching for all routes of a given length that traverse this graph\nand that start in any of it's nodes.\n-}\n\nmkLineEdges :: [Line] -> [(Line, Line)]\nmkLineEdges [] = []\nmkLineEdges (l:ls) = findMatchingLines l ls `mappend` mkLineEdges ls\n where\n findMatchingLines :: Line -> [Line] -> [(Line, Line)]\n findMatchingLines l lines = concat $ do\n l' <- lines\n guard $ matchingLines l l'\n return [(l,l'), (l',l)]\n\nmkLineToVertex :: [Line] -> (Line -> Vertex)\nmkLineToVertex lines = let lvMap = Map.fromList $ zip lines [0..]\n in fromJust . (`Map.lookup` lvMap)\n\ngraphForWidth :: Width -> Graph\ngraphForWidth w = let lines = buildLines w\n lEdges = mkLineEdges lines\n bounds = (0, length lines - 1)\n toVertex = mkLineToVertex lines\n edges = [(toVertex a, toVertex b)|(a,b) <- lEdges]\n in Graph.buildG bounds edges\n\ngraphToDenseMatrix :: Graph -> Matrix Double\ngraphToDenseMatrix = LA.toDense . graphToAssocMatrix\n where\n graphToAssocMatrix :: Graph -> LA.AssocMatrix\n graphToAssocMatrix g = do\n (v, targets) <- Arr.assocs g\n [((v, t), 1)| t <- targets]\n\ndissect :: Graph -> [Graph]\ndissect g = do\n tree <- Graph.components g\n let vertices = Tree.flatten tree\n (renumber, bounds) = mkRenumber vertices\n return . Graph.buildG bounds $ do\n v <- vertices\n w <- Arr.unsafeAt g v\n return (renumber v, renumber w)\n where\n mkRenumber ls = let mapping = Map.fromList $ zip ls [0..]\n \u03bb = fromJust . (`Map.lookup` mapping)\n in (\u03bb, (0, Map.size mapping))\n\nmPow :: Matrix Double -> Int -> Matrix Double\nmPow m 0 = LA.ident $ LA.rows m\nmPow m 1 = m\nmPow m n\n | even n = mPow (m <> m) (n `div` 2)\n | otherwise = m <> mPow m (n - 1)\n\ncountWalls :: Width -> Height -> Int\ncountWalls w h\n | h < 1 = 0\n | h == 1 = length $ buildLines w\n-- Using dissect reduced computation time from ~140s to ~9s.\n | otherwise = let g = graphForWidth w\n ms = graphToDenseMatrix <$> dissect g\n ms' = fmap (mPow `flip` (h - 1)) ms\n calcSum = sum . concat . LA.toLists\n in round . sum $ fmap calcSum ms'\n\nexample = countWalls 9 3\n\n-- 806844323190414\nsolution = countWalls 32 10\n\nmain = print solution\n", "meta": {"hexsha": "a11fcbb6fcc3a74fc531e013ccf7cc582cab2fb3", "size": 4398, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Problem215.hs", "max_stars_repo_name": "runjak/projectEuler", "max_stars_repo_head_hexsha": "10a3dc0be87b101f81e6b5bdd026adcb22cc792d", "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/Problem215.hs", "max_issues_repo_name": "runjak/projectEuler", "max_issues_repo_head_hexsha": "10a3dc0be87b101f81e6b5bdd026adcb22cc792d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Problem215.hs", "max_forks_repo_name": "runjak/projectEuler", "max_forks_repo_head_hexsha": "10a3dc0be87b101f81e6b5bdd026adcb22cc792d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6402877698, "max_line_length": 139, "alphanum_fraction": 0.6482492042, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5647695307877248}} {"text": "-- comment\nmodule Main where\n\nimport qualified Graphics.Rendering.OpenGL as GL\nimport Numeric.LinearAlgebra.HMatrix as H hiding (reshape)\nimport Prelude hiding (init)\nimport GLCode\nimport Points\n\nimport Sketch\n\nrrand :: Int -> IO (Matrix Double)\nrrand n = randn n n\n\ncrand :: Int -> IO (Matrix (Complex Double))\ncrand n = curry toComplex <$> randn n n <*> randn n n\n\nunit :: Floating a => Int -> [a]\nunit n = [fromIntegral j/fromIntegral n | j <- [0..n-1]]\n\ninitialPoints :: Int -> Vector (Complex Double)\ninitialPoints num = fromList (n ++ s) where\n n = [(-12.5+25*j) :+ (-20) | j <- unit num]\n s = [(-12.5+25*j) :+ 20 | j <- unit num]\n\nfinalPoints :: Int -> Vector (Complex Double)\nfinalPoints num = fromList (e ++ w) where\n e = [(-20) :+ (-12.5+25*j) | j <- unit num]\n w = [20 :+ (-12.5+25*j) | j <- unit num]\n\nmain :: IO ()\nmain = do\n let num = 20\n\n u' <- crand (num * 2)\n let u = scale 1.5 u'\n\n let d = initialPoints num\n let d' = finalPoints num\n\n let p = diag d\n let p' = u `mul` diag d' `mul` inv u\n\n mainGifLoop \"xxx\" 12.0 512 512 1 0 100 $ \\time -> do\n let t = time/200\n \n let eigs = H.toList $ eigenvalues $ scale (1-realToFrac t) p + scale (realToFrac t) p'\n\n GL.clearColor GL.$= GL.Color4 0.0 0.0 0.0 1\n io $ GL.clear [GL.ColorBuffer]\n\n let points = [GL.Vertex2 (0.04*realToFrac x) (0.04*realToFrac y) |\n x :+ y <- eigs] :: [GL.Vertex2 Float]\n setUniform \"shader\" \"pointSize\" (8.0 :: Float)\n drawPoint \"shader\" \"vPosition\" points\n\n io GL.flush\n", "meta": {"hexsha": "c1871972beeaf6e4c6863356be98dfb5647a1bed", "size": 1579, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/ex2/Main.hs", "max_stars_repo_name": "dpiponi/SketchBox", "max_stars_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-23T01:58:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-23T01:58:44.000Z", "max_issues_repo_path": "examples/ex2/Main.hs", "max_issues_repo_name": "dpiponi/SketchBox", "max_issues_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ex2/Main.hs", "max_forks_repo_name": "dpiponi/SketchBox", "max_forks_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.224137931, "max_line_length": 94, "alphanum_fraction": 0.5826472451, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5647695259997887}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE NamedFieldPuns #-}\n{-# LANGUAGE RecordWildCards #-}\nmodule Network\n ( NeuralNet (..),\n train,\n initWB,\n loadData,\n loadTestData,\n ) where\n\nimport Codec.Compression.GZip (decompress)\nimport Control.Monad\nimport qualified Data.Array.IO as A\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Lazy as BL\nimport Data.Int (Int64)\nimport Data.List\nimport GHC.Base (build)\nimport Numeric.LinearAlgebra hiding (build, normalize)\nimport Prelude hiding ((<>))\nimport System.Directory (getCurrentDirectory)\nimport qualified System.Random as R\nimport Text.Printf\nimport Util\n\ntype Image = Vector Double\ntype Label = Vector Double\ntype Bias = Vector Double\ntype Weight = Matrix Double\ntype Activation = Matrix Double\ntype Nabla = Matrix Double\ntype ImagesMat = Matrix Double\ntype LabelsMat = Matrix Double\n\ndata NeuralNet = NN\n { weights :: ![Weight] -- ^ List of all weights\n , biases :: ![Bias] -- ^ List of all biases\n , eta :: !Double -- ^ Learning rate\n , epochs :: !Int -- ^ No. of epochs\n , layers :: !Int -- ^ No. of layers\n , layerSize :: !Int -- ^ Size of hidden layers\n , batchSize :: !Int -- ^ Size of mini-batch\n , trainData :: ![(Image, Label)]\n , testData :: ![(ImagesMat, Int)]\n } deriving (Show, Eq)\n\ntest :: NeuralNet -> IO ()\ntest NN{..} = do\n let (imgs, labels) = unzip testData\n let guesses = [guess img (zip weights $ toMatrix <$> biases) | img <- imgs]\n let correct = sum $ (\\(a,b) -> if a == b then 1 else 0) <$> zip guesses labels\n printf \"Epoch %d: %.2f%%\\n\" (30-epochs :: Int) (correct/100 :: Float)\n where\n guess :: ImagesMat -> [(Weight, Matrix Double)] -> Int\n guess i wb = maxIndex . flatten . head $ feedforward i wb\n\ntrain :: NeuralNet -> IO NeuralNet\ntrain net@NN{..} = do\n shuffledData <- shuffle trainData\n let miniBatches = getMiniBatch <$> chunkList batchSize shuffledData\n let newNet = foldl trainBatch net miniBatches\n test newNet\n case epochs of\n 0 -> return newNet\n _ -> train newNet { epochs=epochs-1 }\n\ntrainBatch :: NeuralNet -> (ImagesMat, LabelsMat) -> NeuralNet\ntrainBatch net@NN{weights=ws, biases=bs, ..} (mX, mY) = newNet\n where newNet = let activations = feedforward mX (zip ws $ bTm bs batchSize)\n in updateMiniBatch net $\n backprop mX mY net activations\n\n-- | Make biases suitable for full-matrix backprop.\nbTm :: [Bias] -> Int -> [Matrix Double]\nbTm biases batchSize = fmap (fromColumns . replicate batchSize) biases\n\n-- | Turn mini-batch matrices into one matrix.\ngetMiniBatch :: [(Image, Label)] -> (ImagesMat, LabelsMat)\ngetMiniBatch mBatchData = (fromColumns imgs, fromColumns labels)\n where\n (imgs, labels) = unzip mBatchData\n\nfeedforward :: ImagesMat -> [(Weight, Matrix Double)] -> [Activation]\nfeedforward = scanr (\\(w, b) a -> sigmoid $ w <> a + b)\n\n-- | Stochastic gradient descent\nsgd = id\n\n-- | Updates mini-batch\n-- NOTE: use 'seq' or 'deepseq' for full evaluation,\n-- instead of just reducing to WHNF\nupdateMiniBatch :: NeuralNet -> ([Vector Double], [Matrix Double]) -> NeuralNet\nupdateMiniBatch net@NN{..} (nablaB, nablaW) = net {weights=wnew, biases=bnew}\n where\n wnew :: [Weight]\n !wnew = [ w - scale (eta/fromIntegral batchSize) nw |\n (w, nw) <- zip weights nablaW ]\n bnew :: [Bias]\n !bnew = [ b - scale (eta/fromIntegral batchSize) nb |\n (b, nb) <- zip biases nablaB ]\n\n-- | Returns nablaW and nablaB\nbackprop :: ImagesMat -> LabelsMat -> NeuralNet -> [Activation] -> ([Vector Double], [Matrix Double])\nbackprop x y NN{..} (aL:as) = (nablaB, nablaW)\n where\n nablaW :: [Matrix Double]\n nablaW = zipWithSafe (<>) delta (tr <$> as) -- THIS IS WHERE THE MEMORY LEAK IS IF I DO JUST zipWith\n nablaB :: [Vector Double]\n nablaB = sumRows <$> delta\n delta :: [Matrix Double]\n delta = init $ deltas [crossEntropy y aL] y as weights\n\ndeltas :: [Matrix Double] -> LabelsMat -> [Activation] -> [Weight] -> [Matrix Double]\ndeltas deltal _ [] [] = deltal\ndeltas deltal y (a:as) (wlp1:ws) = deltas (deltal++[(tr wlp1 <> last deltal) * sigmoid' a]) y as ws\n\nquadraticLoss :: LabelsMat -> Activation -> Matrix Double\nquadraticLoss y aL = (aL - y) * sigmoid' aL\n\ncrossEntropy :: LabelsMat -> Activation -> Matrix Double\ncrossEntropy y aL = (aL - y)\n\n{-- Arithmetic Functions --}\ncost :: Matrix Double -> Matrix Double -> Matrix Double\ncost a y = ((a-y)**2) / 2\n\nsigmoid :: Floating a => a -> a\nsigmoid x = 1 / (1 + (exp (-x)))\n\nsigmoid' :: Floating a => a -> a\nsigmoid' x = x * (1 - x)\n\nnormalize :: (Integral a, Floating b) => a -> b\nnormalize x = (fromIntegral x) / 255\n\n{-- Data Processing Functions --}\ninitWB :: NeuralNet -> IO NeuralNet\ninitWB net@NN{batchSize = bs, layerSize = ls, layers = n} = do\n headW <- randn ls 784\n midW <- replicateM (n-2) (randn ls ls)\n lastW <- randn 10 ls\n\n initB <- replicateM (n-1) (randn ls 1)\n lastB <- randn 10 1\n\n let weights = reverse $ headW : midW ++ [lastW]\n let biases = reverse . fmap flatten $ initB ++ [lastB]\n\n return net { weights = weights\n , biases = biases }\n\nloadData :: IO [(Vector Double, Vector Double)]\nloadData = do\n trainImgs <- getData \"train-images-idx3-ubyte.gz\"\n trainLabels <- getData \"train-labels-idx1-ubyte.gz\"\n let !labels = BL.toStrict trainLabels\n let !imgs = BL.toStrict trainImgs\n let !l = [vectorizeLabel $ getLabel n labels | n <- [0..49999]] :: [Label]\n let !i = [getImage n imgs | n <- [0..49999]] :: [Image]\n return $ zip i l\n\nloadTestData :: IO [(Matrix Double, Int)]\nloadTestData = do\n testImgs <- getData \"t10k-images-idx3-ubyte.gz\"\n testLabels <- getData \"t10k-labels-idx1-ubyte.gz\"\n let !labels = BL.toStrict testLabels\n let !imgs = BL.toStrict testImgs\n let !l = [getLabel n labels | n <- [0..9999]] :: [Int]\n let !i = asColumn <$> [getImage n imgs | n <- [0..9999]] :: [Matrix Double]\n return $ zip i l\n\ngetData :: FilePath -> IO BL.ByteString\ngetData path = do\n currentDir <- getCurrentDirectory\n fileData <- decompress <$> BL.readFile (currentDir ++ \"/data/mnist_dataset/\" ++ path)\n return fileData\n\ngetImage :: Int -> BS.ByteString -> Image\ngetImage n imgs = fromList [normalize $ BS.index imgs (16 + n*784 + s) | s <- [0..783]]\n\n-- | `getImage` but lazy\ngetImage' :: Int64 -> BL.ByteString -> Image\ngetImage' n imgs = fromList [normalize $ BL.index imgs (16 + n*784 + s) | s <- [0..783]]\n\ngetLabel :: Num a => Int -> BS.ByteString -> a\ngetLabel n labels = fromIntegral $ BS.index labels (n+8)\n\ngetGuess :: [Activation] -> Int\ngetGuess = maxIndex . flatten . head\n\nvectorizeLabel :: Int -> Vector Double\nvectorizeLabel l = fromList $ x ++ 1 : y\n where (x,y) = splitAt l $ replicate 9 0\n\n{-- HELPER FUNCTIONS --}\ntoMatrix :: Vector Double -> Matrix Double\ntoMatrix = reshape 1\n\n-- | Means of rows in matrix as a column vector\nmeanRows :: Matrix Double -> Vector Double\nmeanRows = fst . meanCov . tr\n\nsumRows :: (Num a, Element a) => Matrix a -> Vector a\nsumRows m = fromList $ sum <$> toLists m\n\n-- | zipWith, but throws error if lengths don't match\nzipWithSafe :: (a -> b -> c) -> [a] -> [b] -> [c]\nzipWithSafe f as bs\n | length as == length bs = zipWith f as bs\n | otherwise = error $ \"zipWith: lengths don't match (\" ++ (show $ length as) ++ \" \" ++ (show $ length bs) ++ \")\"\n\n-- | Randomly shuffle a list\n-- /O(N)/\nshuffle :: [a] -> IO [a]\nshuffle xs = do\n ar <- newArray n xs\n forM [1..n] $ \\i -> do\n j <- R.randomRIO (i,n)\n vi <- A.readArray ar i\n vj <- A.readArray ar j\n A.writeArray ar j vi\n return vj\n where\n n = length xs\n newArray :: Int -> [a] -> IO (A.IOArray Int a)\n newArray n xs = A.newListArray (1,n) xs\n", "meta": {"hexsha": "8bcbbd67801e40fbd1dcb1526cb849afa50c192b", "size": 8136, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Network.hs", "max_stars_repo_name": "ttesmer/haskell-mnist", "max_stars_repo_head_hexsha": "a4d993c5745a7f049d998aa5a2f0616b0808ab93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-13T14:41:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:41:32.000Z", "max_issues_repo_path": "src/Network.hs", "max_issues_repo_name": "ttesmer/haskell-mnist", "max_issues_repo_head_hexsha": "a4d993c5745a7f049d998aa5a2f0616b0808ab93", "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/Network.hs", "max_forks_repo_name": "ttesmer/haskell-mnist", "max_forks_repo_head_hexsha": "a4d993c5745a7f049d998aa5a2f0616b0808ab93", "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.6842105263, "max_line_length": 116, "alphanum_fraction": 0.607300885, "num_tokens": 2314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5647649569393465}} {"text": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Neural.Matrix(\n initNet, updateNet, feedLayer, forwardPass, propagate,\n backPropagate, relu, softmax, categoricalCrossEntropy\n) where\n\nimport Control.Monad (zipWithM)\nimport Data.List (foldl', scanl', transpose)\nimport Control.Arrow ((&&&))\nimport Numeric.AD (grad)\nimport Numeric.AD.Mode (auto)\nimport Numeric.AD.Internal.Reverse (Reverse, Tape)\nimport Data.Reflection (Reifies)\nimport Numeric.LinearAlgebra\n\ntype Biases = Vector R\ntype Weights = Matrix R\ntype Activation = [R] -> [R]\ntype Layer = (Activation, Biases, Weights)\n\nparameters :: Layer -> (Biases, Weights)\nparameters (_, bs, ws) = (bs, ws)\n\nweights :: Layer -> Weights\nweights (_, _, ws) = ws\n\ninitNet :: R -> [Int] -> [Activation] -> IO [Layer]\ninitNet b szs@(_:lns) acts = layer <$> zipWithM randn szs lns\n where layer = zip3 acts $ vector . flip replicate b <$> lns\n\nrelu :: Activation\nrelu = map $ max 0\n\nrelu' :: Activation\nrelu' = map f\n where f x | x < 0 = 0\n | otherwise = 1\n\ncategoricalCrossEntropy :: RealFloat a => [a] -> [a] -> a\ncategoricalCrossEntropy ys = negate . sum . zipWith (*) ys . map log . softmax\n\nsoftmax :: RealFloat a => [a] -> [a]\nsoftmax ts = let exps = exp <$> ts in map (/ sum exps) exps\n\nfeedLayer :: (Vector R, Vector R) -> Layer -> (Vector R, Vector R)\nfeedLayer (_, an) (aF, bs, ws) = (id &&& fromList . aF . toList) $ bs + an <# ws\n\nforwardPass :: Vector R -> [Layer] -> [(Vector R, Vector R)]\nforwardPass = scanl' feedLayer . (id &&& id)\n\npropagate :: (Vector R, Matrix R) -> Vector R -> Vector R\npropagate (zn, wn) dldn = wn #> dldn * dadz\n where dadz = fromList . relu' . toList $ zn\n\nbackPropagate :: Vector R -> [Vector R] -> [Matrix R] -> [Vector R]\nbackPropagate dldL tls lws = tail $ scanr propagate dldL $ zip tls lws\n\nupdateLayer :: R -> (Vector R, Vector R, Layer) -> Layer\nupdateLayer s (a, e, (aF, bs, ws)) = (aF, newBs, newWs)\n where newWs = ws - scalar s * outer a e\n newBs = bs - scalar s * e\n\nupdateNet :: (forall a. Reifies a Tape => [Reverse a R]\n -> [Reverse a R]\n -> Reverse a R) ->\n R -> Vector R -> Vector R -> [Layer] -> [Layer]\nupdateNet c s xs ys ls = map (updateLayer s) $ zip3 (init ans) dls ls\n where fps = forwardPass xs ls\n ans = snd <$> fps\n yhat = auto <$> (toList . last) ans\n dldL = fromList $ grad (c (auto <$> (toList ys))) yhat\n dls = backPropagate dldL (fst <$> init fps) (weights <$> ls)\n", "meta": {"hexsha": "f18dd859fa3581db09851580bbfb1ec85271cf71", "size": 2551, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Neural/Matrix.hs", "max_stars_repo_name": "Ultramann/hnet", "max_stars_repo_head_hexsha": "1105c44b7a138707e284e2e1694a8dd24141d4ef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-03-27T05:57:49.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-27T05:57:49.000Z", "max_issues_repo_path": "src/Neural/Matrix.hs", "max_issues_repo_name": "Ultramann/hnet", "max_issues_repo_head_hexsha": "1105c44b7a138707e284e2e1694a8dd24141d4ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Neural/Matrix.hs", "max_forks_repo_name": "Ultramann/hnet", "max_forks_repo_head_hexsha": "1105c44b7a138707e284e2e1694a8dd24141d4ef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0133333333, "max_line_length": 80, "alphanum_fraction": 0.6111328891, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.564714328932743}} {"text": "module Lib\n( Ising\n, randModel\n, runBatch\n, runMC\n, totalEnergy\n, totalMagnetization\n, flipRandSpin\n, flipSpin\n) where\n\nimport Model\n\nimport Data.Maybe\nimport Control.Monad.State\nimport System.Random (Random, random, randomR)\nimport Numeric.LinearAlgebra (accum, atIndex, toLists)\n\nrunBatch :: Show a => Int -> [Ising a] -> Ising ([Maybe [a]], IsingState)\nrunBatch steps prop = do\n props <- replicateM steps $ runMC prop\n state <- get\n return (props, state)\n\nrunMC :: [Ising a] -> Ising (Maybe [a])\nrunMC properties = do\n incrementStep\n state_i <- get\n dE <- flipRandSpin >>= getSpinEnergy >>= return . negate\n state_f <- get\n\n if dE <= 0\n then put $ state_f { nAccept = nAccept state_f + 1 }\n else do\n r <- randR (0,1)\n\n if r <= exp (-beta * dE)\n then put $ state_f { nAccept = nAccept state_f + 1 }\n else do\n put state_i -- reset the state to before the spin flip\n r <- rand :: Ising Int -- increment RNG\n return ()\n\n state <- get\n if step state `mod` propFreq state == 0\n then liftM Just $ sequence properties\n else return Nothing\n\ntotalEnergy :: Ising Double\ntotalEnergy = do\n state <- get\n let n = dim state\n let indices = [(row, col) | row <- [0..n-1], col <- [0..n-1]]\n spinE <- liftM sum $ mapM getSpinEnergy indices\n let fieldE = sum $ map (* h state) (spins state)\n normalize $ spinE - fieldE\n\ntotalMagnetization :: Ising Double\ntotalMagnetization = do\n state <- get\n normalize $ sum (spins state)\n\ngetSpinEnergy :: (Int, Int) -> Ising Double\ngetSpinEnergy (row, col) = do\n state <- get\n neighbors <- getNeighbors (row, col)\n let spin = model state `atIndex` (row,col)\n return $ 2 * j state * spin * (sum neighbors)\n\ngetNeighbors :: (Int, Int) -> Ising [Spin]\ngetNeighbors (row, col) = do\n state <- get\n let n = dim state\n let m = model state\n let ns = map (atIndex m) [ ((row - 1) `mod` n, col)\n , ((row + 1) `mod` n, col)\n , (row, (col - 1) `mod` n)\n , (row, (col + 1) `mod` n)\n ]\n return ns \nflipRandSpin :: Ising (Int, Int)\nflipRandSpin = do\n state <- get\n let n = dim state\n row <- randR (0,n-1)\n col <- randR (0,n-1)\n flipSpin (row, col)\n return (row, col)\n\nflipSpin :: (Int, Int) -> Ising ()\nflipSpin (row, col) = do\n state <- get\n let spin = (model state) `atIndex` (row, col)\n let model' = accum (model state) (\\a b -> a) [((row,col), -spin)]\n put $ state { model = model' }\n\n-----\n--\n-- Helper functions\n--\n-----\n\nbeta = 1.0\n\nnormalize :: Fractional a => a -> Ising a\nnormalize x = do\n state <- get\n return $ x / (fromIntegral $ dim state)^2\n\nspins :: IsingState -> [Spin]\nspins state = concat . toLists $ model state\n\nrandR :: (Random a) => (a,a) -> Ising a\nrandR (a,b) = do \n state <- get\n let (r, rng') = randomR (a,b) $ rng state\n put $ state { rng = rng' }\n return r\n\nrand :: (Random a) => Ising a\nrand = do \n state <- get\n let (r, rng') = random $ rng state\n put $ state { rng = rng' }\n return r\n\nincrementStep :: Ising Int\nincrementStep = do\n state <- get\n let step' = step state + 1\n put $ state { step = step' }\n return step'\n", "meta": {"hexsha": "5233a2dac6bc671dfef43e477f6b9245bd4bd11c", "size": 3328, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "stnma7e/ising", "max_stars_repo_head_hexsha": "f980aefc5674976e212706569050b1fc80bec934", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "stnma7e/ising", "max_issues_repo_head_hexsha": "f980aefc5674976e212706569050b1fc80bec934", "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": "stnma7e/ising", "max_forks_repo_head_hexsha": "f980aefc5674976e212706569050b1fc80bec934", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.022556391, "max_line_length": 77, "alphanum_fraction": 0.5646033654, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5645902101006441}} {"text": "module Main where\n\n\nimport Control.Monad.Par\nimport Data.Complex\nimport qualified Data.Vector as V\n\nimport Graphics.Gloss.Data.Display\nimport Graphics.Gloss.Data.Color\nimport Graphics.Gloss.Data.Picture\nimport Graphics.Gloss.Interface.Pure.Display\n\nwindowSpec :: Display\nwindowSpec = InWindow \"hello\" (800,800) (0,0)\n\n\nblackColor :: Color\nblackColor = makeColor 0.0 0.0 0.0 1.0\n\n\nwhiteColor :: Color\nwhiteColor = makeColor 1.0 1.0 1.0 1.0\n\n\npseudoPixel :: Picture\npseudoPixel = rectangleSolid 1.0 1.0\n\n\nblockf :: ((Float, Float), Int) -> Picture\nblockf ((x,y),t) = let b = ((fromIntegral t) / 25) :: Float\n c = makeColor b b b 1.0\n in color c (translate x y pseudoPixel)\n\n\nfractalRadius :: Float\nfractalRadius = 2.0 \n\n\nfractalCalc :: (Complex Float, Complex Float) -> ((Float,Float),Int)\nfractalCalc n = let a1 = V.iterateN 50 (\\(start,c) -> (start*start + c,c)) (fmap (*0.005) n) :: V.Vector (Complex Float, Complex Float)\n b = V.length . V.filter (> fractalRadius) . V.map (realPart . abs . fst) $ a1 :: Int\n c = snd n\n d = (realPart c, imagPart c) :: (Float, Float)\n in (d, b) \n\n\ncomplexBlock :: V.Vector (Complex Float, Complex Float)\ncomplexBlock = let x = [-400.0..400.0]\n xv = V.fromList x\n c = 0 :+ 0\n in V.concatMap (\\x -> V.map (\\z -> (c, x :+ z)) xv) xv\n\nfractalP :: V.Vector (Par ((Float, Float), Int))\nfractalP = V.map (\\x -> (spawnP . fractalCalc $ x) >>= get) complexBlock \n\nfractal :: Picture\nfractal = mconcat . V.toList . V.map blockf . runPar . sequence $ fractalP\n\n\nmain :: IO ()\nmain = display windowSpec whiteColor fractal\n", "meta": {"hexsha": "aaa1b5a76ca2532c8236a4ea16f9687b2f8dab08", "size": 1710, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "metric-space/project", "max_stars_repo_head_hexsha": "ab36bb3a6804cb01b23fcc7018b71b878ab86285", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "metric-space/project", "max_issues_repo_head_hexsha": "ab36bb3a6804cb01b23fcc7018b71b878ab86285", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main.hs", "max_forks_repo_name": "metric-space/project", "max_forks_repo_head_hexsha": "ab36bb3a6804cb01b23fcc7018b71b878ab86285", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5806451613, "max_line_length": 135, "alphanum_fraction": 0.6093567251, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5645797544371582}} {"text": "-- |\n-- Module : Statistics.Test.MannWhitneyU\n-- Copyright : (c) 2010 Neil Brown\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Mann-Whitney U test (also know as Mann-Whitney-Wilcoxon and\n-- Wilcoxon rank sum test) is a non-parametric test for assessing\n-- whether two samples of independent observations have different\n-- mean.\nmodule Statistics.Test.MannWhitneyU (\n -- * Mann-Whitney U test\n mannWhitneyUtest\n , mannWhitneyU\n , mannWhitneyUCriticalValue\n , mannWhitneyUSignificant\n -- ** Wilcoxon rank sum test\n , wilcoxonRankSums\n , module Statistics.Test.Types\n -- * References\n -- $references\n ) where\n\nimport Control.Applicative ((<$>))\nimport Data.List (findIndex)\nimport Data.Ord (comparing)\nimport Numeric.SpecFunctions (choose)\nimport Prelude hiding (sum)\nimport Statistics.Distribution (quantile)\nimport Statistics.Distribution.Normal (standard)\nimport Statistics.Function (sortBy)\nimport Statistics.Sample.Internal (sum)\nimport Statistics.Test.Internal (rank, splitByTags)\nimport Statistics.Test.Types (TestResult(..), PositionTest(..), significant)\nimport Statistics.Types (PValue,pValue)\nimport qualified Data.Vector.Unboxed as U\n\n-- | The Wilcoxon Rank Sums Test.\n--\n-- This test calculates the sum of ranks for the given two samples.\n-- The samples are ordered, and assigned ranks (ties are given their\n-- average rank), then these ranks are summed for each sample.\n--\n-- The return value is (W\u2081, W\u2082) where W\u2081 is the sum of ranks of the first sample\n-- and W\u2082 is the sum of ranks of the second sample. This test is trivially transformed\n-- into the Mann-Whitney U test. You will probably want to use 'mannWhitneyU'\n-- and the related functions for testing significance, but this function is exposed\n-- for completeness.\nwilcoxonRankSums :: (Ord a, U.Unbox a) => U.Vector a -> U.Vector a -> (Double, Double)\nwilcoxonRankSums xs1 xs2 = (sum ranks1, sum ranks2)\n where\n -- Ranks for each sample\n (ranks1,ranks2) = splitByTags $ U.zip tags (rank (==) joinSample)\n -- Sorted and tagged sample\n (tags,joinSample) = U.unzip\n $ sortBy (comparing snd)\n $ tagSample True xs1 U.++ tagSample False xs2\n -- Add tag to a sample\n tagSample t = U.map (\\x -> (t,x))\n\n\n\n-- | The Mann-Whitney U Test.\n--\n-- This is sometimes known as the Mann-Whitney-Wilcoxon U test, and\n-- confusingly many sources state that the Mann-Whitney U test is the same as\n-- the Wilcoxon's rank sum test (which is provided as 'wilcoxonRankSums').\n-- The Mann-Whitney U is a simple transform of Wilcoxon's rank sum test.\n--\n-- Again confusingly, different sources state reversed definitions for U\u2081\n-- and U\u2082, so it is worth being explicit about what this function returns.\n-- Given two samples, the first, xs\u2081, of size n\u2081 and the second, xs\u2082,\n-- of size n\u2082, this function returns (U\u2081, U\u2082)\n-- where U\u2081 = W\u2081 - (n\u2081(n\u2081+1))\\/2\n-- and U\u2082 = W\u2082 - (n\u2082(n\u2082+1))\\/2,\n-- where (W\u2081, W\u2082) is the return value of @wilcoxonRankSums xs1 xs2@.\n--\n-- Some sources instead state that U\u2081 and U\u2082 should be the other way round, often\n-- expressing this using U\u2081' = n\u2081n\u2082 - U\u2081 (since U\u2081 + U\u2082 = n\u2081n\u2082).\n--\n-- All of which you probably don't care about if you just feed this into 'mannWhitneyUSignificant'.\nmannWhitneyU :: (Ord a, U.Unbox a) => U.Vector a -> U.Vector a -> (Double, Double)\nmannWhitneyU xs1 xs2\n = (fst summedRanks - (n1*(n1 + 1))/2\n ,snd summedRanks - (n2*(n2 + 1))/2)\n where\n n1 = fromIntegral $ U.length xs1\n n2 = fromIntegral $ U.length xs2\n\n summedRanks = wilcoxonRankSums xs1 xs2\n\n-- | Calculates the critical value of Mann-Whitney U for the given sample\n-- sizes and significance level.\n--\n-- This function returns the exact calculated value of U for all sample sizes;\n-- it does not use the normal approximation at all. Above sample size 20 it is\n-- generally recommended to use the normal approximation instead, but this function\n-- will calculate the higher critical values if you need them.\n--\n-- The algorithm to generate these values is a faster, memoised version of the\n-- simple unoptimised generating function given in section 2 of \\\"The Mann Whitney\n-- Wilcoxon Distribution Using Linked Lists\\\"\nmannWhitneyUCriticalValue\n :: (Int, Int) -- ^ The sample size\n -> PValue Double -- ^ The p-value (e.g. 0.05) for which you want the critical value.\n -> Maybe Int -- ^ The critical value (of U).\nmannWhitneyUCriticalValue (m, n) p\n | m < 1 || n < 1 = Nothing -- Sample must be nonempty\n | p' <= 1 = Nothing -- p-value is too small. Null hypothesis couldn't be disproved\n | otherwise = findIndex (>= p')\n $ take (m*n)\n $ tail\n $ alookup !! (m+n-2) !! (min m n - 1)\n where\n mnCn = (m+n) `choose` n\n p' = mnCn * pValue p\n\n\n{-\n-- Original function, without memoisation, from Cheung and Klotz:\n-- Double is needed to avoid integer overflows.\na :: Int -> Int -> Int -> Double\na u bigN m\n | u < 0 = 0\n | u >= m * n = bigN `choose` m\n | m == 1 || n == 1 = fromIntegral (u + 1)\n | otherwise = a u (bigN - 1) m\n + a (u - n) (bigN - 1) (m-1)\n where\n n = bigN - m\n-}\n\n-- Memoised version of the original a function, above.\n--\n-- Doubles are stored to avoid integer overflow. 32-bit Ints begin to\n-- overflow for bigN as small as 33 (64-bit one at 66) while Double to\n-- go to infinity till bigN=1029\n--\n--\n-- outer list is indexed by big N - 2\n-- inner list by (m-1) (we know m < bigN)\n-- innermost list by u\n--\n-- So: (alookup !! (bigN - 2) !! (m - 1) ! u) == a u bigN m\nalookup :: [[[Double]]]\nalookup = gen 2 [1 : repeat 2]\n where\n gen bigN predBigNList\n = let bigNlist = [ [ amemoed u m\n | u <- [0 .. m*(bigN-m)]\n ] ++ repeat (bigN `choose` m)\n | m <- [1 .. (bigN-1)]] -- has bigN-1 elements\n in bigNlist : gen (bigN+1) bigNlist\n where\n amemoed :: Int -> Int -> Double\n amemoed u m\n | m == 1 || n == 1 = fromIntegral (u + 1)\n | otherwise = mList !! u\n + if u < n then 0 else predmList !! (u-n)\n where\n n = bigN - m\n (predmList : mList : _) = drop (m-2) predBigNList\n -- Lists for m-1 and m respectively. i-th list correspond to m=i+1\n --\n -- We know that predBigNList has bigN - 2 elements\n -- (and we know that n > 1 therefore bigN > m + 1)\n -- So bigN - 2 >= m, i.e. predBigNList must have at least m elements\n -- elements, so dropping (m-2) must leave at least 2\n\n\n-- | Calculates whether the Mann Whitney U test is significant.\n--\n-- If both sample sizes are less than or equal to 20, the exact U critical value\n-- (as calculated by 'mannWhitneyUCriticalValue') is used. If either sample is\n-- larger than 20, the normal approximation is used instead.\n--\n-- If you use a one-tailed test, the test indicates whether the first sample is\n-- significantly larger than the second. If you want the opposite, simply reverse\n-- the order in both the sample size and the (U\u2081, U\u2082) pairs.\nmannWhitneyUSignificant\n :: PositionTest -- ^ Perform one-tailed test (see description above).\n -> (Int, Int) -- ^ The samples' size from which the (U\u2081,U\u2082) values were derived.\n -> PValue Double -- ^ The p-value at which to test (e.g. 0.05)\n -> (Double, Double) -- ^ The (U\u2081, U\u2082) values from 'mannWhitneyU'.\n -> Maybe TestResult -- ^ Return 'Nothing' if the sample was too\n -- small to make a decision.\nmannWhitneyUSignificant test (in1, in2) pVal (u1, u2)\n -- Use normal approximation\n | in1 > 20 || in2 > 20 =\n let mean = n1 * n2 / 2 -- (u1+u2) / 2\n sigma = sqrt $ n1*n2*(n1 + n2 + 1) / 12\n z = (mean - u1) / sigma\n in Just $ case test of\n AGreater -> significant $ z < quantile standard p\n BGreater -> significant $ (-z) < quantile standard p\n SamplesDiffer -> significant $ abs z > abs (quantile standard (p/2))\n -- Use exact critical value\n | otherwise = do crit <- fromIntegral <$> mannWhitneyUCriticalValue (in1, in2) pVal\n return $ case test of\n AGreater -> significant $ u2 <= crit\n BGreater -> significant $ u1 <= crit\n SamplesDiffer -> significant $ min u1 u2 <= crit\n where\n n1 = fromIntegral in1\n n2 = fromIntegral in2\n p = pValue pVal\n\n\n-- | Perform Mann-Whitney U Test for two samples and required\n-- significance. For additional information check documentation of\n-- 'mannWhitneyU' and 'mannWhitneyUSignificant'. This is just a helper\n-- function.\n--\n-- One-tailed test checks whether first sample is significantly larger\n-- than second. Two-tailed whether they are significantly different.\nmannWhitneyUtest\n :: (Ord a, U.Unbox a)\n => PositionTest -- ^ Perform one-tailed test (see description above).\n -> PValue Double -- ^ The p-value at which to test (e.g. 0.05)\n -> U.Vector a -- ^ First sample\n -> U.Vector a -- ^ Second sample\n -> Maybe TestResult -- ^ Return 'Nothing' if the sample was too small to\n -- make a decision.\nmannWhitneyUtest ontTail p smp1 smp2 =\n mannWhitneyUSignificant ontTail (n1,n2) p $ mannWhitneyU smp1 smp2\n where\n n1 = U.length smp1\n n2 = U.length smp2\n\n-- $references\n--\n-- * Cheung, Y.K.; Klotz, J.H. (1997) The Mann Whitney Wilcoxon\n-- distribution using linked lists. /Statistica Sinica/\n-- 7:805–813.\n-- .\n", "meta": {"hexsha": "3732251194d7f90df8bf99fd4d8137e1aa85b2d3", "size": 9801, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Test/MannWhitneyU.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-11T23:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T22:33:10.000Z", "max_issues_repo_path": "Statistics/Test/MannWhitneyU.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-02-26T06:10:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:27:01.000Z", "max_forks_repo_path": "Statistics/Test/MannWhitneyU.hs", "max_forks_repo_name": "infinity0/statistics", "max_forks_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-12-14T09:59:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T23:04:37.000Z", "avg_line_length": 41.0083682008, "max_line_length": 99, "alphanum_fraction": 0.634016937, "num_tokens": 2832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5642537382552149}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TypeFamilies #-}\n\nmodule Song.Grenade (\n SongSD\n, song2SD\n, song2Rn\n, song2TupleRn\n) where\n\nimport Song (Song(Song, _genre, _loudness, _tempo, _timeSignature, _key, _mode, _duration, _avgTimbre, _varTimbre))\nimport Grenade (S(S1D), Shape(D1))\nimport Numeric.LinearAlgebra.Static (R, konst, vector, (#), (&))\nimport Control.Arrow ((***), first)\n\ntype SongSD = (S ('D1 30), S ('D1 1))\n\nsong2SD :: (String -> Double) -> Song -> SongSD\nsong2SD tag = (S1D *** S1D) . song2Rn tag\n\nsong2Rn :: (String -> Double) -> Song -> (R 30, R 1)\nsong2Rn tag song = first (uncurry (#)) $ song2TupleRn tag song\n\nsong2TupleRn :: (String -> Double) -> Song -> ((R 3, R 27), R 1)\nsong2TupleRn tag Song{..} = ((discreteFeats, floatFeats), konst $ tag _genre)\n where\n discreteFeats = konst (fromIntegral _timeSignature)\n & fromIntegral _key\n & fromIntegral _mode\n\n floatFeats = (konst _loudness & _tempo & _duration)\n # (vector _avgTimbre::R 12)\n # (vector _varTimbre::R 12)\n", "meta": {"hexsha": "fdcaeb72d79e4fabab760f93cfc3b2e55f6d9834", "size": 1093, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Song/Grenade.hs", "max_stars_repo_name": "helq/haskell-binary-classification", "max_stars_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-10-02T06:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T11:49:35.000Z", "max_issues_repo_path": "src/Song/Grenade.hs", "max_issues_repo_name": "helq/haskell-binary-classification", "max_issues_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Song/Grenade.hs", "max_forks_repo_name": "helq/haskell-binary-classification", "max_forks_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T14:57:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T14:57:00.000Z", "avg_line_length": 31.2285714286, "max_line_length": 115, "alphanum_fraction": 0.6340347667, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.564203972130957}} {"text": "module STCR2Z1T0Edge where\n\nimport Data.Array.Repa as R\nimport Data.Binary (decodeFile)\nimport Data.Complex\nimport Data.List as L\nimport DFT.Plan\nimport Filter.Utils\nimport FokkerPlanck.MonteCarlo\nimport FokkerPlanck.Pinwheel\nimport Image.Edge\nimport Image.IO\nimport STC\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Types\n\n\nmain = do\n args@(numPointStr:numOrientationStr:sigmaStr:taoStr:lenStr:initialScaleStr:numTrailStr:maxTrailStr:theta0FreqsStr:thetaFreqsStr:histFilePath:pinwheelFlagStr:numIterationStr:writeSourceFlagStr:edgeFilePath:numThreadStr:_) <-\n getArgs\n print args\n let numPoint = read numPointStr :: Int\n numOrientation = read numOrientationStr :: Int\n sigma = read sigmaStr :: Double\n tao = read taoStr :: Double\n len = read lenStr :: Int\n initialScale = read initialScaleStr :: Double\n numTrail = read numTrailStr :: Int\n maxTrail = read maxTrailStr :: Int\n theta0Freq = read theta0FreqsStr :: Double\n theta0Freqs = [-theta0Freq .. theta0Freq]\n thetaFreq = read thetaFreqsStr :: Double\n thetaFreqs = [-thetaFreq .. thetaFreq]\n pinwheelFlag = read pinwheelFlagStr :: Bool\n numIteration = read numIterationStr :: Int\n writeSourceFlag = read writeSourceFlagStr :: Bool\n numThread = read numThreadStr :: Int\n folderPath = \"output/test/STCR2Z1T0Edge\"\n createDirectoryIfMissing True folderPath\n flag <- doesFileExist histFilePath\n radialArr <-\n if flag\n then R.map magnitude . getNormalizedHistogramArr <$>\n decodeFile histFilePath\n else do\n putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n solveMonteCarloR2Z1T0Radial\n numThread\n numTrail\n maxTrail\n numPoint\n numPoint\n sigma\n tao\n 1\n theta0Freqs\n thetaFreqs\n histFilePath\n (emptyHistogram\n [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n , L.length theta0Freqs\n , L.length thetaFreqs\n ]\n 0)\n arrR2Z1T0 <-\n computeUnboxedP $\n computeR2Z1T0ArrayRadial\n radialArr\n numPoint\n numPoint\n 1.5\n thetaFreqs\n theta0Freqs\n plan <- makeR2Z1T0Plan emptyPlan arrR2Z1T0\n xs <- parseEdgeFile edgeFilePath\n randomPonintSet <- generateRandomPointSet 40 numPoint numPoint\n let ys =\n L.map\n (\\(R2S1RPPoint (a, b, c, d)) -> (R2S1RPPoint (a - 150, b - 150, c, d)))\n xs\n zs =\n L.map\n (\\(R2S1RPPoint (a, b, c, d)) ->\n (R2S1RPPoint (a - center numPoint, b - center numPoint, c, d)))\n randomPonintSet\n points = ys L.++ zs\n let bias = computeBiasR2T0 numPoint numPoint theta0Freqs points\n eigenVec =\n computeInitialEigenVectorR2T0\n numPoint\n numPoint\n theta0Freqs\n thetaFreqs\n points\n powerMethod1\n plan\n folderPath\n numPoint\n numPoint\n numOrientation\n thetaFreqs\n theta0Freqs\n arrR2Z1T0\n numIteration\n writeSourceFlag\n \"\"\n 0.5\n bias\n eigenVec\n\n", "meta": {"hexsha": "6b4f999a79cfa817acd4cf831bd5e6f7c62bf7d8", "size": 3343, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2Z1T0Edge/STCR2Z1T0Edge.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/STCR2Z1T0Edge/STCR2Z1T0Edge.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/STCR2Z1T0Edge/STCR2Z1T0Edge.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": 29.5840707965, "max_line_length": 225, "alphanum_fraction": 0.6126233922, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5639713487593115}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n-- |\n-- Monoids for calculating various statistics in constant space\nmodule Statistics.Monoid.Numeric (\n -- * Mean & Variance\n -- ** Number of elements\n CountG(..)\n , Count\n , asCount\n -- ** Mean\n , Mean\n , asMean\n , MeanKBN(..)\n , asMeanKBN\n -- ** Variance\n , Variance(..)\n , asVariance\n -- * Maximum and minimum\n , Max(..)\n , Min(..)\n , MaxD(..)\n , MinD(..)\n -- * Binomial trials\n , BinomAcc(..)\n , asBinomAcc\n -- * Accessors\n , CalcCount(..)\n , CalcMean(..)\n , CalcVariance(..)\n , calcStddev\n , calcStddevML\n -- * References\n -- $references\n ) where\n\nimport Data.Semigroup (Semigroup(..))\nimport Data.Monoid (Monoid(..))\nimport Data.Data (Typeable,Data)\nimport Data.Vector.Unboxed (Unbox)\nimport Data.Vector.Unboxed.Deriving (derivingUnbox)\nimport Numeric.Sum\nimport GHC.Generics (Generic)\n\nimport Statistics.Monoid.Class\n-- COMPAT\nimport qualified Data.Vector.Generic -- Needed for GHC7.4\nimport qualified Data.Vector.Generic.Mutable -- Needed for GHC7.4\n\n\n----------------------------------------------------------------\n-- Statistical monoids\n----------------------------------------------------------------\n\n-- | Calculate number of elements in the sample.\nnewtype CountG a = CountG { calcCountN :: a }\n deriving (Show,Eq,Ord,Typeable)\n\ntype Count = CountG Int\n\n-- | Type restricted 'id'\nasCount :: CountG a -> CountG a\nasCount = id\n\ninstance Integral a => Semigroup (CountG a) where\n (<>) = mappend\n {-# INLINE (<>) #-}\n\ninstance Integral a => Monoid (CountG a) where\n mempty = CountG 0\n CountG i `mappend` CountG j = CountG (i + j)\n {-# INLINE mempty #-}\n {-# INLINE mappend #-}\n\ninstance (Integral a) => StatMonoid (CountG a) b where\n singletonMonoid _ = CountG 1\n addValue (CountG n) _ = CountG (n + 1)\n {-# INLINE singletonMonoid #-}\n {-# INLINE addValue #-}\n\ninstance CalcCount (CountG Int) where\n calcCount = calcCountN\n {-# INLINE calcCount #-}\n\n\n\n----------------------------------------------------------------\n\n-- | Type alias for currently recommended algorithms for calculation\n-- of mean. It should be default choice\ntype Mean = MeanKBN\n\nasMean :: Mean -> Mean\nasMean = id\n\n-- | Incremental calculation of mean. Sum of elements is calculated\n-- using Kahan-Babu\u0161ka-Neumaier summation.\ndata MeanKBN = MeanKBN !Int !KBNSum\n deriving (Show,Eq,Typeable,Data,Generic)\n\nasMeanKBN :: MeanKBN -> MeanKBN\nasMeanKBN = id\n\n\ninstance Semigroup MeanKBN where\n (<>) = mappend\n {-# INLINE (<>) #-}\n\ninstance Monoid MeanKBN where\n mempty = MeanKBN 0 mempty\n MeanKBN 0 _ `mappend` m = m\n m `mappend` MeanKBN 0 _ = m\n MeanKBN n1 s1 `mappend` MeanKBN n2 s2 = MeanKBN (n1+n2) (s1 `mappend` s2)\n\ninstance Real a => StatMonoid MeanKBN a where\n addValue (MeanKBN n m) x = MeanKBN (n+1) (addValue m x)\n\ninstance CalcCount MeanKBN where\n calcCount (MeanKBN n _) = n\ninstance CalcMean MeanKBN where\n calcMean (MeanKBN 0 _) = Nothing\n calcMean (MeanKBN n s) = Just (kbn s / fromIntegral n)\n\n\n\n\n\n\n----------------------------------------------------------------\n\n-- | This is algorithm for estimation of mean and variance of sample\n-- which uses modified Welford algorithm. It uses KBN summation and\n-- provides approximately 2 additional decimal digits\ndata VarWelfordKBN = VarWelfordKBN\n {-# UNPACK #-} !Int -- Number of elements in the sample\n {-# UNPACK #-} !KBNSum -- Current sum of elements of sample\n {-# UNPACK #-} !KBNSum -- Current sum of squares of deviations from current mean\n\nasVarWelfordKBN :: VarWelfordKBN -> VarWelfordKBN\nasVarWelfordKBN = id\n\n \n-- | Incremental algorithms for calculation the standard deviation.\ndata Variance = Variance {-# UNPACK #-} !Int -- Number of elements in the sample\n {-# UNPACK #-} !Double -- Current sum of elements of sample\n {-# UNPACK #-} !Double -- Current sum of squares of deviations from current mean\n deriving (Show,Eq,Typeable)\n\n-- | Type restricted 'id '\nasVariance :: Variance -> Variance\nasVariance = id\n{-# INLINE asVariance #-}\n\ninstance Semigroup Variance where\n (<>) = mappend\n {-# INLINE (<>) #-}\n\n-- | Iterative algorithm for calculation of variance [Chan1979]\ninstance Monoid Variance where\n mempty = Variance 0 0 0\n mappend (Variance n1 ta sa) (Variance n2 tb sb)\n = Variance (n1+n2) (ta+tb) sumsq\n where\n na = fromIntegral n1\n nb = fromIntegral n2\n nom = sqr (ta * nb - tb * na)\n sumsq | n1 == 0 = sb\n | n2 == 0 = sa\n | otherwise = sa + sb + nom / ((na + nb) * na * nb)\n {-# INLINE mempty #-}\n {-# INLINE mappend #-}\n\ninstance Real a => StatMonoid Variance a where\n addValue (Variance 0 _ _) x = singletonMonoid x\n addValue (Variance n t s) (realToFrac -> x)\n = Variance (n + 1) (t + x) (s + sqr (t - n' * x) / (n' * (n'+1)))\n where\n n' = fromIntegral n\n singletonMonoid x = Variance 1 (realToFrac x) 0\n {-# INLINE singletonMonoid #-}\n\ninstance CalcCount Variance where\n calcCount (Variance n _ _) = n\n\ninstance CalcMean Variance where\n calcMean (Variance 0 _ _) = Nothing\n calcMean (Variance n s _) = Just (s / fromIntegral n)\n\ninstance CalcVariance Variance where\n calcVariance (Variance n _ s)\n | n < 2 = Nothing\n | otherwise = Just $! s / fromIntegral (n - 1)\n calcVarianceML (Variance n _ s)\n | n < 1 = Nothing\n | otherwise = Just $! s / fromIntegral n\n\n\n\n\n----------------------------------------------------------------\n\n-- | Calculate minimum of sample\nnewtype Min a = Min { calcMin :: Maybe a }\n deriving (Show,Eq,Ord,Typeable,Data,Generic)\n\ninstance Ord a => Semigroup (Min a) where\n (<>) = mappend\n {-# INLINE (<>) #-}\n\ninstance Ord a => Monoid (Min a) where\n mempty = Min Nothing\n Min (Just a) `mappend` Min (Just b) = Min (Just $! min a b)\n Min a `mappend` Min Nothing = Min a\n Min Nothing `mappend` Min b = Min b\n\ninstance (Ord a, a ~ a') => StatMonoid (Min a) a' where\n singletonMonoid a = Min (Just a)\n\n----------------------------------------------------------------\n\n-- | Calculate maximum of sample\nnewtype Max a = Max { calcMax :: Maybe a }\n deriving (Show,Eq,Ord,Typeable,Data,Generic)\n\ninstance Ord a => Semigroup (Max a) where\n (<>) = mappend\n {-# INLINE (<>) #-}\n\ninstance Ord a => Monoid (Max a) where\n mempty = Max Nothing\n Max (Just a) `mappend` Max (Just b) = Max (Just $! min a b)\n Max a `mappend` Max Nothing = Max a\n Max Nothing `mappend` Max b = Max b\n\ninstance (Ord a, a ~ a') => StatMonoid (Max a) a' where\n singletonMonoid a = Max (Just a)\n\n\n----------------------------------------------------------------\n\n-- | Calculate minimum of sample of Doubles. For empty sample returns NaN. Any\n-- NaN encountered will be ignored.\nnewtype MinD = MinD { calcMinD :: Double }\n deriving (Show,Typeable,Data,Generic)\n\ninstance Eq MinD where\n MinD a == MinD b\n | isNaN a && isNaN b = True\n | otherwise = a == b\n\ninstance Semigroup MinD where\n (<>) = mappend\n {-# INLINE (<>) #-}\n\n-- N.B. forall (x :: Double) (x <= NaN) == False\ninstance Monoid MinD where\n mempty = MinD (0/0)\n mappend (MinD x) (MinD y)\n | isNaN x = MinD y\n | isNaN y = MinD x\n | otherwise = MinD (min x y)\n {-# INLINE mempty #-}\n {-# INLINE mappend #-}\n\ninstance a ~ Double => StatMonoid MinD a where\n singletonMonoid = MinD\n\n\n\n-- | Calculate maximum of sample. For empty sample returns NaN. Any\n-- NaN encountered will be ignored.\nnewtype MaxD = MaxD { calcMaxD :: Double }\n deriving (Show,Typeable,Data,Generic)\n\ninstance Eq MaxD where\n MaxD a == MaxD b\n | isNaN a && isNaN b = True\n | otherwise = a == b\n\ninstance Semigroup MaxD where\n (<>) = mappend\n {-# INLINE (<>) #-}\n\ninstance Monoid MaxD where\n mempty = MaxD (0/0)\n mappend (MaxD x) (MaxD y)\n | isNaN x = MaxD y\n | isNaN y = MaxD x\n | otherwise = MaxD (max x y)\n {-# INLINE mempty #-}\n {-# INLINE mappend #-}\n\ninstance a ~ Double => StatMonoid MaxD a where\n singletonMonoid = MaxD\n\n\n----------------------------------------------------------------\n\n-- | Accumulator for binomial trials.\ndata BinomAcc = BinomAcc { binomAccSuccess :: !Int\n , binomAccTotal :: !Int\n }\n deriving (Show,Eq,Ord,Typeable,Data,Generic)\n\n-- | Type restricted 'id'\nasBinomAcc :: BinomAcc -> BinomAcc\nasBinomAcc = id\n\ninstance Semigroup BinomAcc where\n (<>) = mappend\n {-# INLINE (<>) #-}\n\ninstance Monoid BinomAcc where\n mempty = BinomAcc 0 0\n mappend (BinomAcc n1 m1) (BinomAcc n2 m2) = BinomAcc (n1+n2) (m1+m2)\n\ninstance StatMonoid BinomAcc Bool where\n addValue (BinomAcc nS nT) True = BinomAcc (nS+1) (nT+1)\n addValue (BinomAcc nS nT) False = BinomAcc nS (nT+1)\n\n\n\n----------------------------------------------------------------\n-- Helpers\n----------------------------------------------------------------\n\nsqr :: Double -> Double\nsqr x = x * x\n{-# INLINE sqr #-}\n\n\n----------------------------------------------------------------\n-- Unboxed instances\n----------------------------------------------------------------\n\nderivingUnbox \"CountG\"\n [t| forall a. Unbox a => CountG a -> a |]\n [| calcCountN |]\n [| CountG |]\n\nderivingUnbox \"MeanKBN\"\n [t| MeanKBN -> (Int,Double,Double) |]\n [| \\(MeanKBN a (KBNSum b c)) -> (a,b,c) |]\n [| \\(a,b,c) -> MeanKBN a (KBNSum b c) |]\n\nderivingUnbox \"Variance\"\n [t| Variance -> (Int,Double,Double) |]\n [| \\(Variance a b c) -> (a,b,c) |]\n [| \\(a,b,c) -> Variance a b c |]\n\nderivingUnbox \"MinD\"\n [t| MinD -> Double |]\n [| calcMinD |]\n [| MinD |]\n\nderivingUnbox \"MaxD\"\n [t| MaxD -> Double |]\n [| calcMaxD |]\n [| MaxD |]\n\n-- $references\n--\n-- * [Welford1962] Welford, B.P. (1962) Note on a method for\n-- calculating corrected sums of squares and\n-- products. /Technometrics/\n-- 4(3):419-420. \n--\n-- * [Chan1979] Chan, Tony F.; Golub, Gene H.; LeVeque, Randall\n-- J. (1979), Updating Formulae and a Pairwise Algorithm for\n-- Computing Sample Variances., Technical Report STAN-CS-79-773,\n-- Department of Computer Science, Stanford University. Page 4.\n", "meta": {"hexsha": "19f09b47f69715bbefb86264be7e29f503fe9b42", "size": 10716, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Monoid/Numeric.hs", "max_stars_repo_name": "o1lo01ol1o/monoid-statistics", "max_stars_repo_head_hexsha": "1ba6f20e7a88afacb3c8f0fa6c4d4eeb3d626c35", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistics/Monoid/Numeric.hs", "max_issues_repo_name": "o1lo01ol1o/monoid-statistics", "max_issues_repo_head_hexsha": "1ba6f20e7a88afacb3c8f0fa6c4d4eeb3d626c35", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Monoid/Numeric.hs", "max_forks_repo_name": "o1lo01ol1o/monoid-statistics", "max_forks_repo_head_hexsha": "1ba6f20e7a88afacb3c8f0fa6c4d4eeb3d626c35", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2, "max_line_length": 105, "alphanum_fraction": 0.5724150803, "num_tokens": 3080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5639270437910627}} {"text": "{-# LANGUAGE FlexibleContexts, Rank2Types, NoMonomorphismRestriction,\n StandaloneDeriving #-}\n\nmodule Numeric.MaxEnt.Linear where\n\nimport Control.Applicative\n\nimport Data.List (transpose)\nimport qualified Data.Vector.Storable as S\n\nimport Numeric.MaxEnt.ConjugateGradient (minimize, dot)\nimport Numeric.Optimization.Algorithms.HagerZhang05 (Result, Statistics)\nimport Numeric.AD\n \nmultMV :: (Num a) => [[a]] -> [a] -> [a]\nmultMV mat vec = map (\\row -> dot row vec) mat\n \nprobs :: (Floating a) => [[a]] -> [a] -> [a]\nprobs matrix ls = result where\n norm = partitionFunc matrix ls\n result = map (\\x -> exp x / norm ) $ (transpose matrix) `multMV` ls\n\npartitionFunc :: (Floating a) => [[a]] -> [a] -> a\npartitionFunc matrix ws = sum . map exp . multMV (transpose matrix) $ ws\n\n-- This is almost the sam as the objectiveFunc \n\nobjectiveFunc :: (Floating a) => [[a]] -> [a] -> [a] -> a\nobjectiveFunc as moments ls = log $ partitionFunc as ls - dot ls moments\n\ndata LinearConstraints = LC\n { unLC :: forall a. (Floating a) => ([[a]], [a]) }\n\n-- These instances default the underlying numeric type of `LC` to `Double`,\n-- which may be problematic for some usages.\nderiving instance Eq LinearConstraints\nderiving instance Show LinearConstraints\n\n-- | This is for the linear case Ax = b \n-- @x@ in this situation is the vector of probablities.\n-- \n-- Consider the 1 dimensional circular convolution using hmatrix.\n-- \n-- >>> import Numeric.LinearAlgebra\n-- >>> fromLists [[0.68, 0.22, 0.1], [0.1, 0.68, 0.22], [0.22, 0.1, 0.68]] <> fromLists [[0.2], [0.5], [0.3]]\n-- (3><1) [0.276, 0.426, 0.298] \n-- \n-- Now if we were given just the convolution and the output, we can use 'linear' to infer the input.\n-- \n-- >>> linear 3.0e-17 $ LC ([[0.68, 0.22, 0.1], [0.1, 0.68, 0.22], [0.22, 0.1, 0.68]], [0.276, 0.426, 0.298])\n-- Right (fromList [0.2000000000000001,0.49999999999999983,0.30000000000000004])\n--\n-- I fell compelled to point out that we could also just invert the original\n-- convolution matrix. Supposedly using maxent can reduce errors from noise if\n-- the convolution matrix is not properly estimated.\nlinear :: Double \n -- ^ Tolerance for the numerical solver\n -> LinearConstraints\n -- ^ The matrix A and column vector b\n -> Either (Result, Statistics) (S.Vector Double)\n -- ^ Either a description of what went wrong or the probability\n -- distribution \nlinear tolerance constraints =\n let (matrix, output) = unLC constraints\n obj = objectiveFunc matrix output \n n = length output\n in (S.fromList . probs matrix . S.toList) <$> minimize tolerance n obj\n\n--------------------------------------------------------------------------------\n-- I updated everything below to work with the new types, but it's not clear to \n-- me what it's for. -- EP\n--------------------------------------------------------------------------------\n\nlinear' :: (Floating a, Ord a)\n => LinearConstraints\n -- ^ The matrix A and column vector b\n -> [[a]]\n -- ^ Either a description of what went wrong or the probability\n -- distribution\nlinear' constraints =\n let (matrix, output) = unLC constraints\n obj = objectiveFunc matrix output\n guess = 1 : replicate (length output - 1) 0\n in map (probs matrix) . gradientDescent obj $ guess\n \nlinear'' :: (Floating a, Ord a)\n => LinearConstraints\n -- ^ The matrix A and column vector b\n -> [[a]]\n -- ^ Either a description of what went wrong or the probability\n -- distribution\nlinear'' constraints =\n let (matrix, output) = unLC constraints\n obj = objectiveFunc matrix output \n guess = 1 : replicate (length output - 1) 0\n in map (probs matrix) . conjugateGradientDescent obj $ guess\n\n--test1 = LC ( [ [0.892532,0.003851,0.063870,0.001593,0.038155]\n-- , [0.237713,0.111149,0.326964,0.271535,0.052639]\n-- , [0.133708,0.788233,0.051543,0.003976,0.022539]\n-- , [0.238064,0.263171,0.112279,0.270452,0.116034]\n-- , [0.844155,0.011312,0.001470,0.001826,0.141237]\n-- ]\n-- ,\n-- [0.246323,0.235600,0.071699,0.211339,0.238439]\n-- )\n", "meta": {"hexsha": "550a29f180633cf806417c2753e343c882bf4561", "size": 4287, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/MaxEnt/Linear.hs", "max_stars_repo_name": "jfischoff/maxent", "max_stars_repo_head_hexsha": "35120673d916e1537497c4853d337365c0e04701", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-10-06T11:28:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T04:49:36.000Z", "max_issues_repo_path": "src/Numeric/MaxEnt/Linear.hs", "max_issues_repo_name": "jfischoff/maxent", "max_issues_repo_head_hexsha": "35120673d916e1537497c4853d337365c0e04701", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/MaxEnt/Linear.hs", "max_forks_repo_name": "jfischoff/maxent", "max_forks_repo_head_hexsha": "35120673d916e1537497c4853d337365c0e04701", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-10-06T11:28:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:37:48.000Z", "avg_line_length": 40.0654205607, "max_line_length": 111, "alphanum_fraction": 0.6053184045, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5635073681974102}} {"text": "{-# LANGUAGE RecordWildCards #-}\nmodule Statistics.BBVI.StepSize\n ( KucP(..)\n , rhoKuc\n , defaultKucP\n , Rho\n )\nwhere\n\nimport qualified Data.Vector as V\nimport Statistics.BBVI.Propagator ( DistCell(..)\n , Gradient\n , Memory\n )\n\n-- | step size is a vector the same length as n parameters in\n-- the distribution\ntype Rho = V.Vector Double\n\n-- | calculates a step size following Kucukelbir et al 2017\nrhoKuc\n :: KucP -- ^ parameters\n -> Gradient -- ^ gradient at time t\n -> DistCell a -- ^ distribution cell (needed for memory data\n -- e.g. \\( s_{t-1} \\) in Kucukelbir et al 2017)\n -> (Memory, Rho) -- ^ change in memory, stepsize\nrhoKuc KucP {..} gra (Node time memory _dist) =\n ( deltaM\n , V.zipWith\n (\\ds s ->\n eta\n * (fromIntegral time)\n ** (negate 0.5 + eps)\n * (1.0 / (tau + sqrt (s + ds)))\n )\n deltaM\n memory\n )\n where\n deltaM = V.zipWith (\\g s -> alpha * g ^ (2 :: Int) - alpha * s) gra memory\nrhoKuc _kp _gra (U{}) = error \"called step size cell on an update cell!\"\n\n-- | parameters for 'rhoKuc'\ndata KucP = KucP\n { alpha :: Double\n , eta :: Double\n , tau :: Double\n , eps :: Double\n } deriving (Show, Eq, Ord, Read)\n\n-- | default parameters for 'rhoKuc.' eta is what you probably want to\n-- tune: kucukelbir et al try 0.01 0.1 1 10 100\ndefaultKucP :: KucP\ndefaultKucP = KucP { alpha = 0.1, eta = 0.1, tau = 1.0, eps = 1e-16 }\n", "meta": {"hexsha": "66e1b2fced481963d8b9413c22b963bfa7afec3a", "size": 1579, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/BBVI/StepSize.hs", "max_stars_repo_name": "massma/propagator-bbvi", "max_stars_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/BBVI/StepSize.hs", "max_issues_repo_name": "massma/propagator-bbvi", "max_issues_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/BBVI/StepSize.hs", "max_forks_repo_name": "massma/propagator-bbvi", "max_forks_repo_head_hexsha": "7a29a1e28a401d7c5e6a41b7ed3eebcf166b113a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7090909091, "max_line_length": 76, "alphanum_fraction": 0.5433818873, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.563348272206492}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Foreign.LAPACK\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Types with a Linear Algebra PACKage.\n--\nmodule Foreign.LAPACK (\n -- * LAPACK typeclass\n LAPACK(..),\n -- * Enums\n module Foreign.LAPACK.Types,\n ) where\n\nimport Control.Monad( forM_, when )\nimport Control.Exception( assert )\nimport Data.Complex( Complex )\nimport Foreign\nimport Foreign.BLAS\nimport Foreign.LAPACK.Types\nimport Foreign.LAPACK.Double\nimport Foreign.LAPACK.Zomplex\n\n\n-- | Types with LAPACK operations.\nclass (BLAS3 e) => LAPACK e where\n geqrf :: Int -> Int -> Ptr e -> Int -> Ptr e -> IO ()\n gelqf :: Int -> Int -> Ptr e -> Int -> Ptr e -> IO ()\n \n heevr :: EigJob -> EigRange -> Uplo -> Int -> Ptr e -> Int -> Double\n -> Ptr Double -> Ptr e -> Int -> Ptr Int -> IO Int\n \n larfg :: Int -> Ptr e -> Ptr e -> Int -> IO e\n potrf :: Uplo -> Int -> Ptr e -> Int -> IO Int\n potrs :: Uplo -> Int -> Int -> Ptr e -> Int -> Ptr e -> Int -> IO ()\n pptrf :: Uplo -> Int -> Ptr e -> IO Int\n pptrs :: Uplo -> Int -> Int -> Ptr e -> Ptr e -> Int -> IO ()\n \n unmqr :: Side -> Trans -> Int -> Int -> Int -> Ptr e -> Int -> Ptr e -> Ptr e -> Int -> IO ()\n unmlq :: Side -> Trans -> Int -> Int -> Int -> Ptr e -> Int -> Ptr e -> Ptr e -> Int -> IO ()\n\n\ncallWithWork :: (Storable e) => (Ptr e -> Ptr LAInt -> Ptr LAInt -> IO ()) -> IO LAInt\ncallWithWork call =\n alloca $ \\pquery ->\n with (-1) $ \\pnone ->\n alloca $ \\pinfo -> do\n call pquery pnone pinfo\n lwork <- (ceiling . max 1) `fmap` (peek (castPtr pquery) :: IO Double)\n allocaArray lwork $ \\pwork ->\n withEnum lwork $ \\plwork -> do\n call pwork plwork pinfo\n peek pinfo\n\ncallWithWorkIWork :: (Storable e)\n => (Ptr e -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> IO ())\n -> IO LAInt\ncallWithWorkIWork call =\n alloca $ \\pquery ->\n alloca $ \\piquery ->\n with (-1) $ \\pnone ->\n alloca $ \\pinfo -> do\n call pquery pnone piquery pnone pinfo\n lwork <- (ceiling . max 1) `fmap` (peek (castPtr pquery) :: IO Double)\n liwork <- max 1 `fmap` peek piquery\n allocaArray lwork $ \\pwork ->\n withEnum lwork $ \\plwork ->\n allocaArray (fromEnum liwork) $ \\piwork ->\n with liwork $ \\pliwork -> do\n call pwork plwork piwork pliwork pinfo\n peek pinfo\n\ncallWithWorkRWorkIWork :: (Storable e)\n => (Ptr e -> Ptr LAInt -> Ptr Double -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> IO ())\n -> IO LAInt\ncallWithWorkRWorkIWork call =\n alloca $ \\pquery ->\n alloca $ \\prquery ->\n alloca $ \\piquery ->\n with (-1) $ \\pnone ->\n alloca $ \\pinfo -> do\n call pquery pnone prquery pnone piquery pnone pinfo\n lwork <- (ceiling . max 1) `fmap` (peek (castPtr pquery) :: IO Double)\n lrwork <- (ceiling . max 1) `fmap` peek prquery\n liwork <- max 1 `fmap` peek piquery\n allocaArray lwork $ \\pwork ->\n withEnum lwork $ \\plwork ->\n allocaArray lrwork $ \\prwork ->\n withEnum lrwork $ \\plrwork ->\n allocaArray (fromEnum liwork) $ \\piwork ->\n with liwork $ \\pliwork -> do\n call pwork plwork prwork plrwork piwork pliwork pinfo\n peek pinfo\n\n\ncheckInfo :: (Num info) => info -> IO ()\ncheckInfo info = assert (info == 0) $ return ()\n\nwithEnum :: (Enum a, Storable a) => Int -> (Ptr a -> IO b) -> IO b\nwithEnum = with . toEnum\n{-# INLINE withEnum #-}\n \n\ninstance LAPACK Double where\n geqrf m n pa lda ptau =\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n checkInfo =<< callWithWork (dgeqrf pm pn pa plda ptau)\n\n gelqf m n pa lda ptau =\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n checkInfo =<< callWithWork (dgelqf pm pn pa plda ptau)\n\n heevr jobz range uplo n pa lda abstol pw pz ldz psuppz =\n withEigJob jobz $ \\pjobz ->\n withEigRange range $ \\prange pvl pvu pil piu ->\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n with abstol $ \\pabstol ->\n alloca $ \\pm ->\n withEnum ldz $ \\pldz -> \n allocaArray nsuppz $ \\psuppz' -> do\n checkInfo =<<\n (callWithWorkIWork $\n dsyevr pjobz prange puplo pn pa plda pvl pvu pil piu\n pabstol pm pw pz pldz psuppz')\n m <- fromEnum `fmap` peek pm\n when (psuppz /= nullPtr) $\n forM_ [ 0..2*m - 1 ] $ \\i -> do\n s <- peekElemOff psuppz' i\n pokeElemOff psuppz i (fromEnum s)\n return m\n where\n nsuppz = if psuppz == nullPtr then 0 else 2 * max 1 n\n\n unmqr side trans m n k pa lda ptau pc ldc =\n withSide side $ \\pside ->\n withTrans trans $ \\ptrans ->\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n withEnum k $ \\pk ->\n withEnum lda $ \\plda ->\n withEnum ldc $ \\pldc ->\n checkInfo =<< callWithWork (dormqr pside ptrans pm pn pk pa plda ptau pc pldc)\n\n unmlq side trans m n k pa lda ptau pc ldc =\n withSide side $ \\pside ->\n withTrans trans $ \\ptrans ->\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n withEnum k $ \\pk ->\n withEnum lda $ \\plda ->\n withEnum ldc $ \\pldc ->\n checkInfo =<< callWithWork (dormlq pside ptrans pm pn pk pa plda ptau pc pldc)\n\n larfg n palpha px incx = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n alloca $ \\ptau -> do\n dlarfg pn palpha px pincx ptau\n peek ptau\n\n potrf uplo n pa lda =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n alloca $ \\pinfo -> do\n dpotrf puplo pn pa plda pinfo\n info <- fromEnum `fmap` peek pinfo\n assert (info >= 0) $ return info \n\n potrs uplo n nrhs pa lda pb ldb =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n withEnum nrhs $ \\pnrhs ->\n withEnum lda $ \\plda ->\n withEnum ldb $ \\pldb ->\n alloca $ \\pinfo -> do\n dpotrs puplo pn pnrhs pa plda pb pldb pinfo\n checkInfo =<< peek pinfo\n\n pptrf uplo n pa =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n alloca $ \\pinfo -> do\n dpptrf puplo pn pa pinfo\n info <- fromEnum `fmap` peek pinfo\n assert (info >= 0) $ return info \n\n pptrs uplo n nrhs pa pb ldb =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n withEnum nrhs $ \\pnrhs ->\n withEnum ldb $ \\pldb ->\n alloca $ \\pinfo -> do\n dpptrs puplo pn pnrhs pa pb pldb pinfo\n checkInfo =<< peek pinfo\n\n\ninstance LAPACK (Complex Double) where\n geqrf m n pa lda ptau =\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n checkInfo =<< callWithWork (zgeqrf pm pn pa plda ptau)\n\n gelqf m n pa lda ptau =\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n checkInfo =<< callWithWork (zgelqf pm pn pa plda ptau)\n\n heevr jobz range uplo n pa lda abstol pw pz ldz psuppz =\n withEigJob jobz $ \\pjobz ->\n withEigRange range $ \\prange pvl pvu pil piu ->\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n with abstol $ \\pabstol ->\n alloca $ \\pm ->\n withEnum ldz $ \\pldz -> \n allocaArray nsuppz $ \\psuppz' -> do\n checkInfo =<<\n (callWithWorkRWorkIWork $\n zheevr pjobz prange puplo pn pa plda pvl pvu pil piu\n pabstol pm pw pz pldz psuppz')\n m <- fromEnum `fmap` peek pm\n when (psuppz /= nullPtr) $\n forM_ [ 0..2*m - 1 ] $ \\i -> do\n s <- peekElemOff psuppz' i\n pokeElemOff psuppz i (fromEnum s)\n return m\n where\n nsuppz = if psuppz == nullPtr then 0 else 2 * max 1 n\n\n unmqr side trans m n k pa lda ptau pc ldc =\n withSide side $ \\pside ->\n withTrans trans $ \\ptrans ->\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n withEnum k $ \\pk ->\n withEnum lda $ \\plda ->\n withEnum ldc $ \\pldc ->\n checkInfo =<< callWithWork (zunmqr pside ptrans pm pn pk pa plda ptau pc pldc)\n\n unmlq side trans m n k pa lda ptau pc ldc =\n withSide side $ \\pside ->\n withTrans trans $ \\ptrans ->\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n withEnum k $ \\pk ->\n withEnum lda $ \\plda ->\n withEnum ldc $ \\pldc ->\n checkInfo =<< callWithWork (zunmlq pside ptrans pm pn pk pa plda ptau pc pldc)\n\n larfg n palpha px incx = \n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n alloca $ \\ptau -> do\n zlarfg pn palpha px pincx ptau\n peek ptau\n\n potrf uplo n pa lda =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n alloca $ \\pinfo -> do\n zpotrf puplo pn pa plda pinfo\n info <- fromEnum `fmap` peek pinfo\n assert (info >= 0) $ return info\n\n potrs uplo n nrhs pa lda pb ldb =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n withEnum nrhs $ \\pnrhs ->\n withEnum lda $ \\plda ->\n withEnum ldb $ \\pldb ->\n alloca $ \\pinfo -> do\n zpotrs puplo pn pnrhs pa plda pb pldb pinfo\n checkInfo =<< peek pinfo\n\n pptrf uplo n pa =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n alloca $ \\pinfo -> do\n zpptrf puplo pn pa pinfo\n info <- fromEnum `fmap` peek pinfo\n assert (info >= 0) $ return info\n\n pptrs uplo n nrhs pa pb ldb =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n withEnum nrhs $ \\pnrhs ->\n withEnum ldb $ \\pldb ->\n alloca $ \\pinfo -> do\n zpptrs puplo pn pnrhs pa pb pldb pinfo\n checkInfo =<< peek pinfo\n", "meta": {"hexsha": "383e21ed479a7c01abb2abf7af7b0b15f4729308", "size": 10594, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Foreign/LAPACK.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Foreign/LAPACK.hs", "max_issues_repo_name": "patperry/hs-linear-algebra", "max_issues_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "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/Foreign/LAPACK.hs", "max_forks_repo_name": "patperry/hs-linear-algebra", "max_forks_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 34.6209150327, "max_line_length": 102, "alphanum_fraction": 0.516141212, "num_tokens": 3147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5633482703695732}} {"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule Filter.Pinwheel\n ( module Filter.Utils\n , PinwheelParams(..)\n , pinwheel\n , PinwheelType(..)\n , pinwheelFunc\n , pinwheelFilter\n , convolvePinwheel\n , frequencyDomainMultiply\n ) where\n\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List as L (length, reverse)\nimport Data.Vector.Generic as VG (convert)\nimport DFT.Plan\nimport Filter.Utils\nimport Utils.Coordinates\n\ndata PinwheelParams = PinwheelParams\n { pinwheelParamsRows :: !Int\n , pinwheelParamsCols :: !Int\n , pinwheelParamsAlpha :: !Double\n , pinwheelParamsRadialPeriod :: !Double\n , pinwheelParamsAngularFreqs :: ![Double]\n , pinwheelParamsRadialFreqs :: ![Double]\n }\n \ndata PinwheelType\n = Pinwheel\n | PinwheelHollow0 !Double\n | PinwheelHollow1 !Double\n deriving (Read, Show)\n \n{-# INLINE rFunc #-}\nrFunc :: Int -> Int -> Double\nrFunc x y = sqrt . fromIntegral $ x ^ (2 :: Int) + y ^ (2 :: Int)\n\n{-# INLINE thetaFunc #-}\nthetaFunc :: Int -> Int -> Double\nthetaFunc x y = angleFunctionRad (fromIntegral x) (fromIntegral y)\n\n{-# INLINE pinwheel #-}\npinwheel :: Double -> Double -> Double -> Double -> Int -> Int -> Complex Double\npinwheel af rf maxR alpha x y\n | r == 0 && af == 0 && rf == 0 = 1\n | r == 0 = 0\n | otherwise =\n (r :+ 0) ** (alpha :+ rf * 2 * pi / log maxR) *\n exp (0 :+ af * (thetaFunc x y))\n where\n r = rFunc x y\n\n{-# INCLUDE pinwheelFunc #-}\npinwheelFunc ::\n PinwheelType\n -> Double\n -> Double\n -> Double\n -> Double\n -> Int\n -> Int\n -> Complex Double\npinwheelFunc Pinwheel af rf maxR alpha x y\n | r == 0 && af == 0 && rf == 0 = 1\n | r == 0 = 0\n | otherwise =\n (r :+ 0) ** (alpha :+ rf * 2 * pi / logMaxR) *\n exp (0 :+ af * (thetaFunc x y))\n where\n r = rFunc x y\n logMaxR =\n if maxR == 1\n then 1\n else log maxR\npinwheelFunc (PinwheelHollow0 radius) af rf maxR alpha x y\n | r < radius = 0.0\n | otherwise =\n (r :+ 0) ** (alpha :+ rf * 2 * pi / logMaxR) *\n exp (0 :+ af * (thetaFunc x y))\n where\n r = rFunc x y\n logMaxR =\n if maxR == 1\n then 1\n else log maxR\npinwheelFunc (PinwheelHollow1 radius) af rf maxR alpha x y\n | r == 0 && af == 0 && rf == 0 = 1\n | r < radius = 0.0\n | otherwise =\n (r :+ 0) ** (alpha :+ rf * 2 * pi / logMaxR) *\n exp (0 :+ af * (thetaFunc x y))\n where\n r = rFunc x y\n logMaxR =\n if maxR == 1\n then 1\n else log maxR\n\n{-# INLINE pinwheelPI #-}\npinwheelPI :: Double -> Double -> Double -> Double -> Int -> Int -> Complex Double\npinwheelPI af rf maxR alpha x y\n | r == 0 = 0\n | otherwise =\n (((r) :+ 0) ** (alpha :+ (rf * 2 * pi / (log maxR)))) *\n exp (0 :+ ((af) * theta)) \n where\n r = (sqrt . fromIntegral $ x ^ (2 :: Int) + y ^ (2 :: Int))\n theta = pi + angleFunctionRad (fromIntegral x) (fromIntegral y) \n\npinwheelFilter ::\n DFTPlan\n -> PinwheelParams\n -> IO (DFTPlan, Array U DIM4 (Complex Double), Array U DIM4 (Complex Double))\npinwheelFilter plan (PinwheelParams rows cols alpha radialPeriod angularFreqs radialFreqs) = do\n let numAngularFreq = L.length angularFreqs\n numRadialFreq = L.length radialFreqs\n filterVec =\n VG.convert . toUnboxed . computeS . makeFilter2D $\n R.traverse2\n (fromListUnboxed (Z :. L.length angularFreqs) angularFreqs)\n (fromListUnboxed (Z :. L.length radialFreqs) radialFreqs)\n (\\(Z :. numAngularFreq') (Z :. numRadialFreq') ->\n (Z :. numAngularFreq' :. numRadialFreq' :. cols :. rows))\n (\\f1 f2 (Z :. af :. rf :. i :. j) ->\n pinwheel\n (f1 (Z :. af))\n (f2 (Z :. rf))\n radialPeriod\n alpha\n (i - center cols)\n (j - center rows))\n filterPIVec =\n VG.convert . toUnboxed . computeS . makeFilter2D $\n R.traverse2\n (fromListUnboxed (Z :. L.length angularFreqs) angularFreqs)\n (fromListUnboxed (Z :. L.length radialFreqs) radialFreqs)\n (\\(Z :. numAngularFreq') (Z :. numRadialFreq') ->\n (Z :. numAngularFreq' :. numRadialFreq' :. cols :. rows))\n (\\f1 f2 (Z :. af :. rf :. i :. j) ->\n pinwheelPI\n (f1 (Z :. af))\n (f2 (Z :. rf))\n radialPeriod\n alpha\n (i - div cols 2)\n (j - div rows 2))\n forwardPlanID =\n DFTPlanID DFT1DG [numAngularFreq, numRadialFreq, cols, rows] [2, 3]\n backwardPlanID =\n DFTPlanID IDFT1DG [numAngularFreq, numRadialFreq, cols, rows] [2, 3]\n lock <- getFFTWLock\n (plan1, filterVecF) <-\n dft1dGPlan\n lock\n plan\n [numAngularFreq, numRadialFreq, cols, rows]\n [2, 3]\n filterVec\n (newPlan, _) <-\n idft1dGPlan\n lock\n plan1\n [numAngularFreq, numRadialFreq, cols, rows]\n [2, 3]\n filterVecF\n filterPIVecF <-\n dftExecute\n newPlan\n (DFTPlanID DFT1DG [numAngularFreq, numRadialFreq, cols, rows] [2, 3])\n filterPIVec\n return\n ( newPlan\n , fromUnboxed (Z :. numAngularFreq :. numRadialFreq :. cols :. rows) .\n VG.convert $\n filterVecF\n , fromUnboxed (Z :. numAngularFreq :. numRadialFreq :. cols :. rows) .\n VG.convert $\n filterPIVecF)\n\n{-# INLINE frequencyDomainMultiply #-}\nfrequencyDomainMultiply ::\n (Source r (Complex Double))\n => Array U DIM4 (Complex Double)\n -> Array r DIM2 (Complex Double)\n -> Array D DIM4 (Complex Double)\nfrequencyDomainMultiply filterF input =\n R.traverse2\n filterF\n input\n const\n (\\f1 f2 idx@(Z :. af :. rf :. i :. j) -> f1 idx * f2 (Z :. i :. j))\n\n{-# INLINE convolvePinwheel #-}\nconvolvePinwheel ::\n (Source r (Complex Double))\n => DFTPlan\n -> Array U DIM4 (Complex Double)\n -> Array r DIM2 (Complex Double)\n -> IO (Array U DIM4 (Complex Double))\nconvolvePinwheel plan filterF input =\n fmap (fromUnboxed (extent filterF) . VG.convert) .\n dftExecute\n plan\n (DFTPlanID IDFT1DG (L.reverse . listOfShape . extent $ filterF) [2, 3]) .\n VG.convert . toUnboxed . computeUnboxedS $\n frequencyDomainMultiply filterF input\n", "meta": {"hexsha": "0e892b595bec84f0e4b24bb13d603e8b8817d6eb", "size": 6202, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Filter/Pinwheel.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/Filter/Pinwheel.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/Filter/Pinwheel.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": 29.6746411483, "max_line_length": 95, "alphanum_fraction": 0.5720735247, "num_tokens": 1970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5632129369834189}} {"text": "{-# LANGUAGE NamedFieldPuns #-}\n\nmodule ParticleProcessingTests\n ( testParticleHandling\n ) where\n\nimport Control.Applicative (liftA2)\nimport Data.Complex (Complex(..))\nimport Data.List (sort)\nimport qualified Data.Vector as V\nimport HABQTlib.Data\nimport HABQTlib.Data.Particle\nimport HABQTlib.RandomStates\nimport qualified Numeric.LinearAlgebra as LA\nimport StateGenTests (arbPropDensityMatrix)\nimport qualified Streaming.Prelude as S\nimport qualified System.Random.MWC as MWC\nimport qualified Test.QuickCheck as QC\nimport Test.QuickCheck\n ( Args(..)\n , Positive(..)\n , Property\n , (.&&.)\n , arbitrary\n , quickCheckWith\n , stdArgs\n , suchThat\n )\nimport TestHelpers\n\nlik :: Double -> Double\nlik p = p / (1 - p)\n\nloglik :: Double -> Double\nloglik = log . lik\n\nlikProp :: PureStateVector -> DensityMatrix -> Property\nlikProp sv dm =\n let l = pureStateLikelihood sv dm\n in QC.property (l >= 0) .&&. QC.property (l <= 1)\n\ntestLikelihood :: IO ()\ntestLikelihood = do\n putStrLn \"Testing likelihood computation for density matrices:\"\n quickCheckWith stdArgs {maxSuccess = 1000} likProp\n\nexpProp :: QC.Blind Particles -> Property\nexpProp (QC.Blind pts) =\n let dm = snd . getWDM . V.foldl1' (<+>) . ptsParticles $ pts\n dim = LA.rows . getDensityMatrix $ dm\n z = (dim LA.>< dim) $ repeat 0\n scaleDM :: Weight -> DensityMatrix -> LA.Matrix (Complex Double)\n scaleDM w (DensityMatrix dm'') = LA.scale (w :+ 0) dm''\n dm' = DensityMatrix $ foldOverPts id scaleDM (+) z pts\n matchProp = QC.property $ dm <==> dm'\n validProp = arbPropDensityMatrix dm'\n in matchProp .&&. validProp\n\ntestExpectation :: IO ()\ntestExpectation = do\n putStrLn \"Testing particle expectation function:\"\n quickCheckWith stdArgs {maxSuccess = 500} expProp\n\nparticleUpdateFidR :: PureStateVector -> Particles -> Double\nparticleUpdateFidR testState@(PureStateVector sv) particles =\n let testPure = DensityMatrix $ sv LA.<> LA.tr sv\n originalEstimate = snd . getWDM $ reduceParticlesToMean particles\n originalFid = fidelityDM testPure originalEstimate\n updatedParticles = updateParticles testState particles\n updatedEstimate = snd . getWDM $ reduceParticlesToMean updatedParticles\n updatedFid = fidelityDM testPure updatedEstimate\n in loglik updatedFid - loglik originalFid\n\nupdateProp :: Property\nupdateProp =\n let gen = do\n (dim, rank) <- arbDimRank\n Positive num <- arbitrary :: QC.Gen (Positive NumberOfParticles)\n stateVector <- QC.resize dim arbitrary\n particles <- arbParticles dim rank (fromIntegral num)\n return (stateVector, particles)\n prop (sv, pts) =\n let wtsf Particles {ptsParticles} =\n V.foldl1' (+) . V.map (fst . getWDM) $ ptsParticles\n ws = wtsf pts\n pts' = updateParticles sv pts\n ws' = wtsf pts'\n wsProp = abs (ws - 1) < 1e-10\n ws'Prop = abs (ws' - 1) < 1e-10\n in wsProp .&&. ws'Prop\n msg = \"of updates move the estimate closer\"\n in QC.forAll\n gen\n (\\(sv, pts) ->\n QC.classify (particleUpdateFidR sv pts >= 0) msg (prop (sv, pts)))\n\necdfProp :: Particles -> Property\necdfProp Particles {ptsParticles} =\n let cdf = ecdf ptsParticles\n hp = V.head cdf > 0\n tp = abs (V.last cdf - 1) < 1e-10\n cdfSorted = V.fromList . sort . V.toList $ cdf\n sorted = cdf == cdfSorted\n in hp .&&. tp .&&. sorted\n\nicdfProp :: Particles -> Property\nicdfProp Particles {ptsParticles} =\n QC.ioProperty $ do\n gen <- MWC.createSystemRandom\n x <- MWC.uniform gen\n let cdf = ecdf ptsParticles\n idx = icdf cdf x\n Just idx' = V.findIndex (> x) cdf\n return (idx == idx')\n\nhDistProp :: ParticleHierarchy -> PureStateVector -> Double\nhDistProp ph sv =\n let dm = DensityMatrix $ getStateVector sv LA.<> LA.tr (getStateVector sv)\n originalEstimate = getMixedEstimate ph\n updatedEstimate = getMixedEstimate $ updateParticleHierarchy sv ph\n originalFid = fidelityDM dm originalEstimate\n updatedFid = fidelityDM dm updatedEstimate\n in loglik updatedFid - loglik originalFid\n\nhierarchyBatchProp ::\n Int -> Positive Dim -> Positive NumberOfParticles -> IO Property\nhierarchyBatchProp batchSize (Positive dim) (Positive num) = do\n ph <- initialiseParticleHierarchy dim num\n passed <-\n S.length_ . S.filter (>= 0) . S.replicateM batchSize $\n hDistProp ph <$> genPureSV dim\n return . QC.property $\n fromIntegral passed / (fromIntegral batchSize :: Double) >= 0.95\n\nhierarchyUpdateProp :: Int -> Property\nhierarchyUpdateProp batchSize =\n let gen = do\n dim <- suchThat arbitrary (\\x -> x > 1 && x < 20)\n num <- suchThat arbitrary (> 100)\n return (Positive dim, Positive num)\n in QC.forAll\n gen\n (\\(dim, num) -> QC.ioProperty $ hierarchyBatchProp batchSize dim num)\n\neffectiveSampleSizeProp :: Property\neffectiveSampleSizeProp =\n let genP = do\n (dim, rank) <- arbDimRank\n Positive num <- arbitrary :: QC.Gen (Positive NumberOfParticles)\n arbParticles dim rank (fromIntegral num)\n sizeP ps@(Particles _ _ n _) =\n QC.classify\n (es <= fromIntegral n / 2)\n \"of effective sizes are less than half of total particle number\"\n ((es <= fromIntegral n) && (es >= 0))\n where\n es = effectiveSize ps\n in QC.forAll genP sizeP\n\nnudgeProp :: Property\nnudgeProp =\n let gen = do\n (dim, rank) <- arbDimRank\n dm <- arbDM dim rank\n return (dim, rank, dm)\n nudged (dim, rank, dm) =\n truncateRank rank <$> nudgeParticle dim 1e-2 (mkWDM1 dm)\n prop (dim, rank, dm) =\n QC.ioProperty $ do\n WeighedDensityMatrix (w, ndm) <- nudged (dim, rank, dm)\n let validDM = arbPropDensityMatrix ndm\n preservesRank = getRank dm == getRank ndm\n preservesWeight = w == 1\n return $\n QC.classify\n (fidelityDM ndm dm > 0.99)\n \"fidelities exceed 99%\"\n (validDM .&&. preservesRank .&&. preservesWeight)\n in QC.forAll gen prop\n\ntype ResamplingFunIO = MWC.GenIO -> Particles -> IO Particles\n\nresampleProp :: MWC.GenIO -> ResamplingFunIO -> Property\nresampleProp gen resamplingFun =\n let genA = do\n dim <- suchThat (arbitrary :: QC.Gen Dim) (liftA2 (&&) (< 10) (> 1))\n Positive rank <-\n suchThat (arbitrary :: QC.Gen (Positive Rank)) (< Positive dim)\n num <- suchThat arbitrary (> 1000)\n QC.Blind <$> arbParticles dim rank num\n preservesMeanIO :: QC.Blind Particles -> IO Property\n preservesMeanIO (QC.Blind pts) = do\n rpts <- resamplingFun gen pts\n let WeighedDensityMatrix (w1, dm1) = reduceParticlesToMean pts\n WeighedDensityMatrix (w2, dm2) = reduceParticlesToMean rpts\n sumw wacc (WeighedDensityMatrix (w', _)) = wacc + w'\n getpw Particles {ptsParticles = ps} = V.foldl' sumw 0 ps\n w1' = getpw pts\n w2' = getpw rpts\n propWeight = QC.property $ 2 * abs (w1 - w2) / (w1 + w2) < 1e-12\n propWeight' =\n QC.property $ 2 * abs (w1' - w2') / (w1' + w2') < 1e-12\n Particles _ _ num _ = rpts\n propESabs =\n QC.property $ abs (effectiveSize rpts - fromIntegral num) < 1\n propESincrease =\n QC.property $ effectiveSize rpts > effectiveSize pts\n propAll =\n propWeight .&&. propWeight' .&&. propESincrease .&&. propESabs\n return $\n QC.classify\n (fidelityDM dm1 dm2 > 0.99)\n \"fidelities between pre- and post-resampling means exceed 99%\"\n propAll\n in QC.forAll genA (QC.ioProperty . preservesMeanIO)\n\ntestParticleResampling :: IO ()\ntestParticleResampling = do\n gen <- MWC.createSystemRandom\n putStrLn \"Testing multinomial particle resampling without checks:\"\n quickCheckWith stdArgs {maxSuccess = 100} $ resampleProp gen resampleMultinom\n\ntestParticleNudging :: IO ()\ntestParticleNudging = do\n putStrLn \"Testing particle nudging:\"\n quickCheckWith stdArgs {maxSuccess = 1000} nudgeProp\n\ntestEffectiveSampleSize :: IO ()\ntestEffectiveSampleSize = do\n putStrLn \"Testing calculation of effective sample size:\"\n quickCheckWith stdArgs {maxSuccess = 1000} effectiveSampleSizeProp\n\ntestParticleUpdate :: IO ()\ntestParticleUpdate = do\n putStrLn \"Testing update of particles:\"\n quickCheckWith stdArgs {maxSuccess = 1000} updateProp\n\ntestEcdf :: IO ()\ntestEcdf = do\n putStrLn \"Testing ecdf calculation:\"\n quickCheckWith stdArgs {maxSuccess = 10000} ecdfProp\n putStrLn \"Testing iecdf calculation:\"\n quickCheckWith stdArgs {maxSuccess = 10000} icdfProp\n\ntestHierarchyUpdate :: IO ()\ntestHierarchyUpdate = do\n putStrLn \"Testing update of particle hierarchies:\"\n quickCheckWith stdArgs {maxSuccess = 50} (hierarchyUpdateProp 100)\n\ntestParticleHandling :: IO ()\ntestParticleHandling = do\n testLikelihood\n testExpectation\n testParticleUpdate\n testEcdf\n testHierarchyUpdate\n testEffectiveSampleSize\n testParticleNudging\n testParticleResampling\n", "meta": {"hexsha": "bf7b4cbff7f68a99302de6a8352f5d81b8fd7117", "size": 9097, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/ParticleProcessingTests.hs", "max_stars_repo_name": "Belinsky-L-V/HABQT", "max_stars_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-23T03:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T08:45:58.000Z", "max_issues_repo_path": "test/ParticleProcessingTests.hs", "max_issues_repo_name": "Belinsky-L-V/HABQT", "max_issues_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/ParticleProcessingTests.hs", "max_forks_repo_name": "Belinsky-L-V/HABQT", "max_forks_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9884615385, "max_line_length": 79, "alphanum_fraction": 0.6601077278, "num_tokens": 2472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245828938678, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.5631312597201579}} {"text": "{-# LANGUAGE GADTs, Rank2Types, DataKinds, TypeOperators #-}\n\nmodule Lib.Utility.Mnist.IO\n(\n MnistTrainingSize, MnistTestSize, MnistData, TrainingData,\n getMnistData\n) where\n\nimport Network.HTTP as HTTP\nimport Data.ByteString.Lazy as Lazy (ByteString, readFile, writeFile, empty)\nimport Data.ByteString.Lazy.Char8 as Char8 (pack)\nimport Codec.Compression.GZip as GZip\nimport qualified Data.IDX as IDX\nimport Control.Monad.Trans.Maybe\nimport Data.Vector.Unboxed (Vector, toList)\nimport qualified Numeric.LinearAlgebra as HMatrix\nimport qualified Numeric.LinearAlgebra.Static as Static\nimport System.IO.Error\nimport qualified Data.Serialize as Serialize\nimport Control.Arrow\nimport Control.Applicative\nimport GHC.TypeLits\nimport GHC.Generics (Generic)\nimport Data.Proxy\n\ntype TrainingData n = (Static.L n 784, Static.L n 10)\n\ntype MnistTrainingSize = 60000\ntype MnistTestSize = 10000\ntype MnistData = (TrainingData MnistTrainingSize, TrainingData MnistTestSize)\n\ntype SerializedMnistData = ([(Int, [Int])], [(Int, [Int])])\ntype LabeledIntData = [(Int, Vector Int)]\n\ngetMnistData :: MaybeT IO MnistData\ngetMnistData = do\n loadResult <- loadMnistData\n (tr, te) <- case loadResult of\n Just x -> return x\n Nothing -> do\n () <- MaybeT (Just <$> putStrLn \"Try fetch for load fail\")\n x <- fetchMnistData\n () <- saveMnistData x\n MaybeT $ return $ parseMatrix $ fromLabeledIntData2Matrix x\n return (tr, te)\n\nloadMnistData :: MaybeT IO (Maybe MnistData)\nloadMnistData = MaybeT $ do\n putStrLn $ \"Loading from \" ++ fpath\n matrixMaybe <- HMatrix.loadMatrix' fpath -- 70000><785\n let loadResult = matrixMaybe >>= parseMatrix\n return $ Just loadResult\n\n-- toOneHot :: HMatrix.Vector Double -> HMatrix.Matrix Double\ntoOneHot :: forall n. KnownNat n => Static.L n 1 -> Static.L n 10\ntoOneHot label = Static.build f\n where m0 = Static.extract $ (Static.konst 0 :: Static.L 10 10)\n f r c = if c == (atIndex r 0) then 1.0 else 0\n atIndex r c = Static.unwrap label `HMatrix.atIndex` (truncate r, truncate c)\n\nparseMatrix :: HMatrix.Matrix Double -> Maybe MnistData\nparseMatrix matrix = do\n matrix' <- Static.create matrix :: Maybe (Static.L (MnistTrainingSize + MnistTestSize) 785)\n let (label, image) = Static.splitCols matrix'\n let (trL, teL) = Static.splitRows label :: (Static.L MnistTrainingSize 1, Static.L MnistTestSize 1)\n let (trD, teD) = Static.splitRows $ image / 255\n return ((trD, toOneHot trL), (teD, toOneHot teL))\n\nfromLabeledIntData2Matrix :: (LabeledIntData, LabeledIntData) -> HMatrix.Matrix Double\nfromLabeledIntData2Matrix (tr, te) = matrix\n where transform = map (second toList)\n tr' = transform tr\n te' = transform te\n join = map (uncurry (:))\n matrix = HMatrix.fromLists $ map (map realToFrac) $ join tr' ++ join te'\n\nsaveMnistData :: (LabeledIntData, LabeledIntData) -> MaybeT IO ()\nsaveMnistData labeledIntData = MaybeT $ do\n putStrLn $ \"Saving to \" ++ fpath\n let matrix = fromLabeledIntData2Matrix labeledIntData\n let saveAction = HMatrix.saveMatrix fpath \"%lf\" matrix\n () <- catchIOError saveAction (\\_ -> do putStrLn \"SaveError\"; return ())\n return $ Just ()\n\nfetchMnistData :: MaybeT IO (LabeledIntData, LabeledIntData)\nfetchMnistData = do\n (Data_ trD) <- fetchIDX trainImagesPath decodeIDXData\n (Labels_ trL) <- fetchIDX trainLabelsPath decodeIDXLabels\n (Data_ teD) <- fetchIDX testImagesPath decodeIDXData\n (Labels_ teL) <- fetchIDX testLabelsPath decodeIDXLabels\n MaybeT $ return $ do\n tr <- IDX.labeledIntData trL trD\n te <- IDX.labeledIntData teL teD\n return (tr, te)\n\ndata IDXW = Data_ IDX.IDXData | Labels_ IDX.IDXLabels\n\ndecodeIDXData :: ByteString -> Maybe IDXW\ndecodeIDXData = fmap Data_ . IDX.decodeIDX\ndecodeIDXLabels :: ByteString -> Maybe IDXW\ndecodeIDXLabels = fmap Labels_ . IDX.decodeIDXLabels\nfetchIDX :: String -> (ByteString -> Maybe IDXW) -> MaybeT IO IDXW\nfetchIDX path decodeF = MaybeT $ do\n let url = toUrl path\n putStrLn $ \"Downloading from \" ++ url\n idxBytes <- getFileFromUrl url\n let idx = decodeF idxBytes\n return idx\n\nbaseUrl = \"http://yann.lecun.com/exdb/mnist/\"\ntrainImagesPath = \"train-images-idx3-ubyte.gz\"\ntrainLabelsPath = \"train-labels-idx1-ubyte.gz\"\ntestImagesPath = \"t10k-images-idx3-ubyte.gz\"\ntestLabelsPath = \"t10k-labels-idx1-ubyte.gz\"\nfpath = \"mnist.pickle\"\ntoUrl path = baseUrl ++ path\n\ngetFileFromUrl :: String -> IO ByteString\ngetFileFromUrl url = do\n response <- simpleHTTP (getRequest url)\n body <- getResponseBody response\n let bytes = Char8.pack body\n return $ GZip.decompress bytes\n", "meta": {"hexsha": "d78d934d7c3006bac3936703f17196f8086fdb82", "size": 4698, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib/Utility/Mnist/IO.hs", "max_stars_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_stars_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-01-04T12:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T06:16:37.000Z", "max_issues_repo_path": "src/Lib/Utility/Mnist/IO.hs", "max_issues_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_issues_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-01-04T02:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-09T12:39:40.000Z", "max_forks_repo_path": "src/Lib/Utility/Mnist/IO.hs", "max_forks_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_forks_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-20T03:39:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T03:39:47.000Z", "avg_line_length": 37.8870967742, "max_line_length": 107, "alphanum_fraction": 0.708599404, "num_tokens": 1312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5631025041278102}} {"text": "module Language.Hakaru.Util.Coda where\n\nimport Statistics.Autocorrelation\nimport qualified Data.Packed.Vector as V\nimport qualified Data.Vector.Generic as G\n\neffectiveSampleSize :: [Double] -> Double\neffectiveSampleSize samples = n / (1 + 2*(G.sum rho))\n where n = fromIntegral (V.dim vec)\n vec = V.fromList samples\n cov = autocovariance vec\n rho = G.map (/ G.head cov) cov\n", "meta": {"hexsha": "cb2f7a86ad51c6abca46e8d86b5ccdef32c5700a", "size": 396, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Language/Hakaru/Util/Coda.hs", "max_stars_repo_name": "zaxtax/hakaru-old", "max_stars_repo_head_hexsha": "edac4bca19a2b7b9257e584529cde5e7242e9695", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-11-12T05:18:12.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-09T14:27:37.000Z", "max_issues_repo_path": "Language/Hakaru/Util/Coda.hs", "max_issues_repo_name": "zaxtax/hakaru-old", "max_issues_repo_head_hexsha": "edac4bca19a2b7b9257e584529cde5e7242e9695", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Language/Hakaru/Util/Coda.hs", "max_forks_repo_name": "zaxtax/hakaru-old", "max_forks_repo_head_hexsha": "edac4bca19a2b7b9257e584529cde5e7242e9695", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4615384615, "max_line_length": 53, "alphanum_fraction": 0.7121212121, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5630260321751013}} {"text": "import Criterion.Main\nimport Numeric.LinearAlgebra\n\nn = 10 :: Int\nmain = defaultMain [\n bench \"eigenvalues\" $ w (\\_ -> eigenvalues sampleDiag),\n bench \"singularValues\" $ w (\\_ -> singularValues sampleDiag),\n\n bench \"svd\" $ w (\\_ -> svd sampleDiag),\n bench \"thin svd\" $ w (\\_ -> thinSVD sampleDiag),\n\n bench \"nullspace\" $ w (\\_ -> nullspace sampleDiag),\n bench \"orthogonal\" $ w (\\_ -> orth sampleDiag),\n\n bench \"determinant\" $ w (\\_ -> det sampleDiag)\n ]\n where\n w f = f `whnf` 0\n sampleList = replicate n $ replicate n 1\n sampleDiag = diagl [1..fromIntegral n]\n", "meta": {"hexsha": "caf40b611ec7ad52ae0cbbe81b925dd16c054518", "size": 633, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/hmatrix-linear-algebra.hs", "max_stars_repo_name": "DataHaskell/numeric-libs-benchmarks", "max_stars_repo_head_hexsha": "68cc634be64b84bf3261045a328ea38ee243e9c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-11-07T14:40:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-04T02:54:12.000Z", "max_issues_repo_path": "app/hmatrix-linear-algebra.hs", "max_issues_repo_name": "mdibaiee/numeric-libs-overview", "max_issues_repo_head_hexsha": "68cc634be64b84bf3261045a328ea38ee243e9c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-10-20T11:21:03.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-20T11:27:56.000Z", "max_forks_repo_path": "app/hmatrix-linear-algebra.hs", "max_forks_repo_name": "DataHaskell/numeric-libs-benchmarks", "max_forks_repo_head_hexsha": "68cc634be64b84bf3261045a328ea38ee243e9c0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1428571429, "max_line_length": 70, "alphanum_fraction": 0.5908372828, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5629892799566144}} {"text": "{-|\nModule: MachineLearning.NeuralNetwork\nDescription: Neural Network\nCopyright: (c) Alexander Ignatyev, 2016\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n\nSimple Neural Networks.\n-}\n\nmodule MachineLearning.NeuralNetwork\n(\n Model(..)\n , NeuralNetworkModel(..)\n , MLC.calcAccuracy\n , T.Topology\n , T.initializeTheta\n , T.initializeThetaIO\n , T.initializeThetaM\n , Regularization(..)\n)\n\nwhere\n\nimport qualified Numeric.LinearAlgebra as LA\nimport MachineLearning.Types (R, Vector, Matrix)\nimport MachineLearning.Utils (reduceByRowsV)\nimport qualified MachineLearning.Classification.Internal as MLC\nimport MachineLearning.Model (Model(..))\nimport qualified MachineLearning.NeuralNetwork.Topology as T\nimport MachineLearning.Regularization (Regularization(..))\n\n\n-- | Neural Network Model.\n-- Takes neural network topology as a constructor argument.\nnewtype NeuralNetworkModel = NeuralNetwork T.Topology\n\n\ninstance Model NeuralNetworkModel where\n hypothesis (NeuralNetwork topology) x theta = predictions\n where thetaList = T.unflatten topology theta\n scores = calcScores topology x thetaList\n predictions = reduceByRowsV (fromIntegral . LA.maxIndex) scores\n\n cost (NeuralNetwork topology) lambda x y theta =\n let (ys, thetaList) = processParams topology y theta\n scores = calcScores topology x thetaList\n in T.loss topology lambda scores thetaList ys\n\n gradient (NeuralNetwork topology) lambda x y theta =\n let (ys, thetaList) = processParams topology y theta\n (scores, cacheList) = T.propagateForward topology x thetaList\n grad = T.flatten $ T.propagateBackward topology lambda scores cacheList ys\n in grad\n\n\n-- | Score function. Takes a topology, X and theta list.\ncalcScores :: T.Topology -> Matrix -> [(Matrix, Matrix)] -> Matrix\ncalcScores topology x thetaList = fst $ T.propagateForward topology x thetaList\n\n\nprocessParams :: T.Topology -> Vector -> Vector -> (Matrix, [(Matrix, Matrix)])\nprocessParams topology y theta =\n let nOutputs = T.numberOutputs topology\n ys = LA.fromColumns $ MLC.processOutputOneVsAll nOutputs y\n thetaList = T.unflatten topology theta\n in (ys, thetaList)\n", "meta": {"hexsha": "c5708d4c6b012edca9973169695540d1ad6f722f", "size": 2178, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/NeuralNetwork.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "src/MachineLearning/NeuralNetwork.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "src/MachineLearning/NeuralNetwork.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 31.5652173913, "max_line_length": 82, "alphanum_fraction": 0.7534435262, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5629892636667629}} {"text": "{-# LANGUAGE GADTs, DataKinds, PolyKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule TensorDAG where\n\nimport Data.Vinyl\nimport Data.Vinyl.Functor\nimport Data.Singletons\nimport Numeric.LinearAlgebra (Numeric)\n\nimport TensorHMatrix\nimport DAGIO\nimport VarArgs\n\nmakeGrad1 :: (a -> b -> a) -> HList '[a] -> Identity b -> HList '[a]\nmakeGrad1 g (Identity a :& RNil) (Identity b) = Identity (g a b) :& RNil\n\nmakeGrad2 :: (a -> b -> c -> (a, b)) -> HList '[a, b] -> Identity c -> HList '[a, b]\nmakeGrad2 g (Identity a :& Identity b :& RNil) (Identity c) = Identity a' :& Identity b' :& RNil\n where (a', b') = g a b c\n\nmakeDot :: Numeric a => Node (Tensor '[n] a) -> Node (Tensor '[n] a) -> IO (Node a)\nmakeDot = makeNode (uncurry2 dot, makeGrad2 gradDot)\n\nmakeMV :: (SingI n, IntegralN n, Usable a) => Node (Tensor '[n, m] a) -> Node (Tensor '[m] a) -> IO (Node (Tensor '[n] a))\nmakeMV = makeNode (uncurry2 mv, makeGrad2 gradMV)\n\nmakeMM :: (SingI n, IntegralN n, SingI k, Usable a) => Node (Tensor '[n, m] a) -> Node (Tensor '[m, k] a) -> IO (Node (Tensor '[n, k] a))\nmakeMM = makeNode (uncurry2 mm, makeGrad2 gradMM)\n\nmakeSelect i = makeNode (uncurry1 $ select i, makeGrad1 $ gradSelect i)\n\n", "meta": {"hexsha": "39efcc62c26bf35947699af4020be72bb39c4260", "size": 1188, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "TensorDAG.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": "TensorDAG.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": "TensorDAG.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": 36.0, "max_line_length": 137, "alphanum_fraction": 0.6422558923, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.562948929431368}} {"text": "module STCR2S1Image where\n\nimport Control.Monad as M\nimport Control.Monad.Parallel as MP\nimport Data.Array.Repa as R\nimport Data.Binary (decodeFile)\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Unboxed as VU\nimport DFT.Plan\nimport Filter.Utils\nimport FokkerPlanck.MonteCarlo\nimport Image.IO\nimport STC.CompletionFieldR2S1\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Text.Printf\nimport Types\nimport Utils.Array\n\nmain = do\n args@(numPointStr:numOrientationStr:sigmaStr:taoStr:numTrailStr:maxTrailStr:initOriStr:initSpeedStr:writeFlagStr:numIterationStr:thresholdStr:histFilePath:cutoffStr:imagePath:numThreadStr:_) <-\n getArgs\n print args\n let numPoint = read numPointStr :: Int\n numOrientation = read numOrientationStr :: Int\n sigma = read sigmaStr :: Double\n tao = read taoStr :: Double\n numTrail = read numTrailStr :: Int\n maxTrail = read maxTrailStr :: Int\n initOri = read initOriStr :: Double\n initSpeed = read initSpeedStr :: Double\n writeFlag = read writeFlagStr :: Bool\n numIteration = read numIterationStr :: Int\n threshold = read thresholdStr :: Double\n cutoff = read cutoffStr :: Int\n numThread = read numThreadStr :: Int\n folderPath = \"output/test/STCR2S1Image\"\n imgRepa@(ImageRepa _ img') <- readImageRepa imagePath False\n let (Z :. _ :. cols :. rows) = extent img'\n img =\n computeS . R.traverse img' id $ \\f idx@(Z :. k :. i :. j) ->\n if (sqrt . fromIntegral $ (i - div cols 2) ^ 2 + (j - div rows 2) ^ 2) >\n 32\n then 0\n else f idx\n createDirectoryIfMissing True folderPath\n plotImageRepa (folderPath \"input.png\") . ImageRepa 8 $ img\n flag <- doesFileExist histFilePath\n arrG <-\n if flag\n then getNormalizedHistogramArr .\n mapHistogram\n (\\x ->\n let y = x :: Int\n in fromIntegral y) <$>\n decodeFile histFilePath\n else do\n putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n computeS . R.map magnitude <$>\n solveMonteCarloR2S1\n numThread\n numTrail\n numPoint\n numPoint\n numOrientation\n sigma\n tao\n cutoff\n histFilePath\n (0, 0, 0, 0, initOri / 180 * pi, initSpeed)\n powerMethod\n emptyPlan\n folderPath\n arrG\n numIteration\n writeFlag\n \"\"\n threshold\n (R.traverse img (const (Z :. numOrientation :. cols :. rows)) $ \\f (Z :. _ :. i :. j) ->\n if f (Z :. (0 :: Int) :. i :. j) > 0\n then 1\n else 0)\n (R.traverse img (const (Z :. numOrientation :. cols :. rows)) $ \\f (Z :. _ :. i :. j) ->\n if f (Z :. (0 :: Int) :. i :. j) > 0\n then 1 / fromIntegral numOrientation\n else 0)\n", "meta": {"hexsha": "a92acfb0e8194753e2756ae02e35cfb72b179c34", "size": 3092, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2S1Image/STCR2S1Image.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/STCR2S1Image/STCR2S1Image.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/STCR2S1Image/STCR2S1Image.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": 34.7415730337, "max_line_length": 195, "alphanum_fraction": 0.5692108668, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5628990376303697}} {"text": "{-# LANGUAGE AllowAmbiguousTypes, ConstraintKinds #-}\n\nmodule GPLVM.GaussianProcess\n ( GaussianProcess (..)\n , GPTrainingData (..)\n , PosteriorSample (..)\n , gpToPosteriorSample\n , kernelGP\n ) where\n\nimport Universum hiding (transpose, Vector)\n\nimport Control.Lens (makeLenses)\n\nimport Data.Array.Repa\nimport Data.Array.Repa.Repr.Unboxed (Unbox)\nimport Numeric.LinearAlgebra.Repa hiding (Matrix, Vector)\nimport System.Random (Random, RandomGen, mkStdGen)\n\nimport GPLVM.Types (InputObservations(..), Matrix, Vector, unInputObs)\nimport GPLVM.Util\n\ndata GaussianProcess a = GaussianProcess\n { -- | we define gaussian process by some kernel function\n _kernelGP :: Vector D a -> Vector D a -> Matrix D a\n }\n\ndata GPTrainingData a = GPTrainingData\n { _inputTrain :: Vector D a -- ^ input training data\n , _outputTrain :: Vector D a -- ^ output training data\n }\n\nmakeLenses ''GaussianProcess\nmakeLenses ''GPTrainingData\n\nnewtype PosteriorSample a = PosteriorSample\n { unSample :: Matrix D a -- ^ posterior sample\n }\n\n-- | Constraint kind required to getting a posterior sample by a given GP\ntype GPConstraint a =\n ( Field a\n , Random a\n , Unbox a\n , Floating a\n , Eq a\n )\n\n-- | Main GP function: get a posterior sample by some kernel function, input observations and training data\n\ngpToPosteriorSample\n :: forall a g.\n GPConstraint a\n => InputObservations a -- ^ input observations\n -> GaussianProcess a -- ^ kernel function\n -> GPTrainingData a -- ^ training data\n -> Int -- ^ number of samples\n -> Maybe (PosteriorSample a) -- ^ posterior functional prior\ngpToPosteriorSample (InputObservations observe@(ADelayed (Z :. len) _)) gP trainingData sampleNumber = do\n -- | kernel applied to input test points (so-called K_ss)\n let covarianceMatrix = kernel observe observe\n\n -- | kernel applied to input training points (so-called K)\n let trainingKernel = kernel inputTrain' inputTrain'\n\n -- | Cholesky decomposition applied to kernel of training points (:), so-called L\n let cholK = cholSH $ trainingKernel +^\n (smap (* 0.00005) . identD . size . extent $ inputTrain')\n\n -- | covariance between test points and input training points (so-called K_s)\n let testPointMean = kernel observe inputTrain'\n\n -- | (roots of L * x = K_s)\n cholKSolve <- delay <$> linearSolveS cholK testPointMean\n\n -- | solve linear system for output training points\n cholKSolveOut <- delay <$> linearSolveS cholK (transposeMatrix $ toMatrix outputTrain' len)\n\n -- | compute mean\n let mean = (transposeMatrix cholKSolveOut) `mulD` cholKSolve\n\n -- | posterior\n let postF' = cholSH $\n covarianceMatrix +^\n ((smap (* 1.0e-6) (identD len)) -^\n (transposeMatrix cholKSolve) `mulD` cholKSolve)\n\n -- | posterior sample\n return $ (PosteriorSample $ mean +^ (functionalPrior postF' (mkStdGen 1) sampleNumber))\n where\n kernel = gP ^. kernelGP\n inputTrain' = trainingData ^. inputTrain\n outputTrain' = trainingData ^. outputTrain\n mulD m n = delay $ m `mulS` n\n functionalPrior matrix@(ADelayed (Z :. rows :. cols) _) gen sampleNumber =\n delay $ matrix `mulS` randomCoeffs\n where\n randomCoeffs = randomMatrixD (mkStdGen (-4)) (rows, sampleNumber)\n", "meta": {"hexsha": "76b143d919ffcb816dc1b4370e817281c51d9fe2", "size": 3380, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/GPLVM/GaussianProcess.hs", "max_stars_repo_name": "serokell/GPLVMHaskell", "max_stars_repo_head_hexsha": "bf6c01b3a9e1812be0da59e39c479f2b5ed47e9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-08-08T23:15:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-27T16:47:52.000Z", "max_issues_repo_path": "src/GPLVM/GaussianProcess.hs", "max_issues_repo_name": "serokell/GPLVMHaskell", "max_issues_repo_head_hexsha": "bf6c01b3a9e1812be0da59e39c479f2b5ed47e9b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GPLVM/GaussianProcess.hs", "max_forks_repo_name": "serokell/GPLVMHaskell", "max_forks_repo_head_hexsha": "bf6c01b3a9e1812be0da59e39c479f2b5ed47e9b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1414141414, "max_line_length": 107, "alphanum_fraction": 0.6689349112, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5628806622147206}} {"text": "module Fuml.Optimisation.SGD where\n\nimport Numeric.LinearAlgebra\nimport Data.Random\n\ndata SGDOpts = SGDOpts\n { learning_rate :: Double\n , batch_size :: Int\n , epochs :: Int\n }\n\nsgdBatch :: SGDOpts -> (Vector Double -> Vector Double) -> Vector Double -> Vector Double\nsgdBatch opts grad p = p - scale (learning_rate opts) (grad p)\n\nsgdEpoch :: SGDOpts -> ([a] -> Vector Double -> Vector Double) -> [a] -> Vector Double -> RVar (Vector Double)\nsgdEpoch opts grad pts' p' = do\n pts <- shuffle pts'\n return $ go p' $ inGroupsOf (batch_size opts) pts\n where go p [] = p\n go p (batch:bs) = go (sgdBatch opts (grad batch) p) bs\n\ninGroupsOf :: Int -> [a] -> [[a]]\ninGroupsOf _ [] = []\ninGroupsOf n xs = let (these,those) = splitAt n xs\n in these : inGroupsOf n those\n", "meta": {"hexsha": "f1b2d1889cc82f4d653605d8a6c83c483932d9f8", "size": 794, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "fuml/lib/Fuml/Optimisation/SGD.hs", "max_stars_repo_name": "ekalosak/open", "max_stars_repo_head_hexsha": "9faadba7614fc9d9448f1d3000c58cc3e93a8a36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 81, "max_stars_repo_stars_event_min_datetime": "2017-05-22T22:42:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T10:41:20.000Z", "max_issues_repo_path": "fuml/lib/Fuml/Optimisation/SGD.hs", "max_issues_repo_name": "ekalosak/open", "max_issues_repo_head_hexsha": "9faadba7614fc9d9448f1d3000c58cc3e93a8a36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2017-05-31T09:06:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-18T12:00:27.000Z", "max_forks_repo_path": "fuml/lib/Fuml/Optimisation/SGD.hs", "max_forks_repo_name": "ekalosak/open", "max_forks_repo_head_hexsha": "9faadba7614fc9d9448f1d3000c58cc3e93a8a36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2017-05-22T15:39:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:26:20.000Z", "avg_line_length": 30.5384615385, "max_line_length": 110, "alphanum_fraction": 0.6410579345, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5628244535719301}} {"text": "module Main where\n\nimport Net\nimport Data.Traversable\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Devel\nimport qualified Data.Vector.Storable as V\nimport System.Random\nimport Data.List\nimport Control.Monad\n\ntestNet :: DoubleNet -> [Vector Double] -> [Vector Double] -> Double\ntestNet n ins ans =\n let outs :: [Vector Double]\n outs = map (runNet n) ins\n in sum (zipWith (\\x y -> norm_1 $ add x (scale (-1) y)) outs ans)\n\nrankNets :: [DoubleNet] -> IO [(Double,DoubleNet)]\nrankNets nets =\n do values <- mapM (\\_ -> do x <- randomRIO (0,10)\n return $ vector [x]) [1..100]\n let answers = map sin values\n scoredNets = map (\\x -> (testNet x values answers,x)) nets\n return $ sortOn fst scoredNets\n\nplotSome :: DoubleNet -> IO ()\nplotSome n =\n do let pts = map (\\x -> (x/1000)*10) $ [1..1000]\n mapM_ (\\x -> putStrLn $ (show $ runNet n (vector [x])) ++ \" \" ++ (show $ (sin x)/2)) pts\n\nsinFunc = DiffFunction sin (\\x y -> y*cos x)\n\nerrFunc :: Double -> DifferentiableFunction (Vector Double) Double\nerrFunc c = DiffFunction (\\v -> ((atIndex v 0) - c)^2) (\\v w -> 2*((atIndex v 0) - c)*(atIndex w 0))\n\niterateNet :: Int -> DoubleNet -> IO DoubleNet\niterateNet 0 net = return net\niterateNet steps net =\n do let n = 10\n xs <- replicateM n $ randomRIO (0,20)\n\n --let x = 0.5\n let loop loopSteps currNet =\n if loopSteps ==0 then\n return currNet\n else\n do grads <- forM xs (\\x -> do let (val,err,grad) = runAndDiffWithError currNet (vector [x]) (errFunc $ (sin x)/2)\n --print (x,val,(sin x)/2,err)\n return grad)\n let grad = foldl1 (zipWith (\\a b -> (add b a))) grads\n let newNet = updateNet net grad (-0.0005)\n loop (loopSteps - 1) newNet\n loop 5 net >>= iterateNet (steps-1)\n\nmain :: IO ()\nmain = do randNet <- randomSimpleNet 1 1 100\n finalNet <- iterateNet 10000 randNet\n plotSome finalNet\n", "meta": {"hexsha": "c7d3a187fc85b5b98139c6fd92e018c022dd80b3", "size": 2056, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "jkelleyy/sinenet", "max_stars_repo_head_hexsha": "367ad0dd2762578c34ef56c8532ce884768fac47", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "jkelleyy/sinenet", "max_issues_repo_head_hexsha": "367ad0dd2762578c34ef56c8532ce884768fac47", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main.hs", "max_forks_repo_name": "jkelleyy/sinenet", "max_forks_repo_head_hexsha": "367ad0dd2762578c34ef56c8532ce884768fac47", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8474576271, "max_line_length": 126, "alphanum_fraction": 0.5802529183, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5628244491714685}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Numeric.LinearAlgebra\n\nmain :: IO ()\nmain = putStrLn $ show $ vector [1,2,3] * vector [3,0,-2]\n", "meta": {"hexsha": "c8e66c284250ae9127037a7173ccbe444923a92a", "size": 157, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "myproject1/Main.hs", "max_stars_repo_name": "tweag/economics", "max_stars_repo_head_hexsha": "f1e6592c492aeb2083037df08605c822c70a3bec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-26T14:33:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T14:33:47.000Z", "max_issues_repo_path": "myproject1/Main.hs", "max_issues_repo_name": "tweag/economics", "max_issues_repo_head_hexsha": "f1e6592c492aeb2083037df08605c822c70a3bec", "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": "myproject1/Main.hs", "max_forks_repo_name": "tweag/economics", "max_forks_repo_head_hexsha": "f1e6592c492aeb2083037df08605c822c70a3bec", "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": 17.4444444444, "max_line_length": 57, "alphanum_fraction": 0.6751592357, "num_tokens": 43, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5626153706494844}} {"text": "-- Kolmogorov-Smirnov tests for distribution\n--\n-- Note that it's not most powerful test for normality.\nmodule KS (\n tests\n ) where\n\nimport qualified Data.Vector.Unboxed as U\n\nimport Statistics.Test.KolmogorovSmirnov\n\nimport Statistics.Distribution\nimport Statistics.Distribution.Binomial\nimport Statistics.Distribution.Exponential\nimport Statistics.Distribution.Gamma\nimport Statistics.Distribution.Normal\nimport Statistics.Distribution.Uniform\nimport Statistics.Distribution.Beta\n\nimport qualified System.Random.MWC as MWC\nimport qualified System.Random.MWC.Distributions as MWC\n\nimport Test.HUnit hiding (Test)\nimport Test.Framework\nimport Test.Framework.Providers.HUnit\n\n\ntests :: MWC.GenIO -> Test\ntests g = testGroup \"Kolmogorov-Smirnov\"\n [ testCase \"standard\" $ testKS standard MWC.standard g\n , testCase \"normal m=1 s=2\" $ testKS (normalDistr 1 2) (MWC.normal 1 2) g\n -- Gamma distribution\n , testCase \"gamma k=1 \u03b8=1\" $ testKS (gammaDistr 1 1 ) (MWC.gamma 1 1 ) g\n , testCase \"gamma k=0.3 \u03b8=0.4\" $ testKS (gammaDistr 0.3 0.4) (MWC.gamma 0.3 0.4) g\n , testCase \"gamma k=0.3 \u03b8=3\" $ testKS (gammaDistr 0.3 3 ) (MWC.gamma 0.3 3 ) g\n , testCase \"gamma k=3 \u03b8=0.4\" $ testKS (gammaDistr 3 0.4) (MWC.gamma 3 0.4) g\n , testCase \"gamma k=3 \u03b8=3\" $ testKS (gammaDistr 3 3 ) (MWC.gamma 3 3 ) g\n -- Uniform\n , testCase \"uniform -2 .. 3\" $ testKS (uniformDistr (-2) 3) (MWC.uniformR (-2,3)) g\n -- Exponential\n , testCase \"exponential l=1\" $ testKS (exponential 1) (MWC.exponential 1) g\n , testCase \"exponential l=3\" $ testKS (exponential 3) (MWC.exponential 3) g\n -- Beta\n , testCase \"beta a=0.3,b=0.5\" $ testKS (betaDistr 0.3 0.5) (MWC.beta 0.3 0.5) g\n , testCase \"beta a=0.1,b=0.8\" $ testKS (betaDistr 0.3 0.5) (MWC.beta 0.3 0.5) g\n , testCase \"beta a=0.8,b=0.1\" $ testKS (betaDistr 0.3 0.5) (MWC.beta 0.3 0.5) g\n ]\n\ntestKS :: (Distribution d) => d -> (MWC.GenIO -> IO Double) -> MWC.GenIO -> IO ()\ntestKS distr generator g = do\n sample <- U.replicateM 1000 (generator g)\n case kolmogorovSmirnovTest distr 0.01 sample of\n Significant -> assertFailure \"KS test failed\"\n NotSignificant -> return ()\n", "meta": {"hexsha": "c91c300849a13ac5cc4790eccd652156daf6c288", "size": 2264, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/KS.hs", "max_stars_repo_name": "OlivierSohn/mwc-random", "max_stars_repo_head_hexsha": "538ea1cd647ed479cb3931778d613b52ea09285d", "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": "test/KS.hs", "max_issues_repo_name": "OlivierSohn/mwc-random", "max_issues_repo_head_hexsha": "538ea1cd647ed479cb3931778d613b52ea09285d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/KS.hs", "max_forks_repo_name": "OlivierSohn/mwc-random", "max_forks_repo_head_hexsha": "538ea1cd647ed479cb3931778d613b52ea09285d", "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.1636363636, "max_line_length": 90, "alphanum_fraction": 0.6590106007, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5625101981883527}} {"text": "-- | Helper for writing tests for numeric code\nmodule Test.QuickCheck.Numeric (\n -- * Approximate equality\n eq\n , eqC\n -- * Function monotonicity\n , Monotonicity(..)\n , monotonicFunction\n , monotonicFunctionIEEE\n -- * Inverse function\n , checkInverse\n , checkInverse2\n ) where\n\nimport Data.Complex\nimport qualified Numeric.IEEE as IEEE\n\n\n\n\n----------------------------------------------------------------\n-- Approximate equality\n----------------------------------------------------------------\n\n-- | Approximate equality for 'Double'. Doesn't work well for numbers\n-- which are almost zero.\neq :: Double -- ^ Relative error\n -> Double -> Double -> Bool\neq eps a b \n | a == 0 && b == 0 = True\n | otherwise = abs (a - b) <= eps * max (abs a) (abs b)\n\n-- | Approximate equality for 'Complex Double'\neqC :: Double -- ^ Relative error\n -> Complex Double\n -> Complex Double\n -> Bool\neqC eps a@(ar :+ ai) b@(br :+ bi)\n | a == 0 && b == 0 = True\n | otherwise = abs (ar - br) <= eps * d\n && abs (ai - bi) <= eps * d\n where\n d = max (realPart $ abs a) (realPart $ abs b)\n\n\n\n----------------------------------------------------------------\n-- Function monotonicity\n----------------------------------------------------------------\n\n-- | Function monotonicity type.\ndata Monotonicity\n = StrictInc -- ^ Strictly increasing function\n | MonotoneInc -- ^ Monotonically increasing function\n | StrictDec -- ^ Strictly decreasing function\n | MonotoneDec -- ^ Monotonically decreasing function\n deriving (Show,Eq,Ord)\n\n\n-- | Check that function is nondecreasing. For floating point number\n-- it may give spurious failures so 'monotonicFunction'\n-- should be used in this case.\nmonotonicFunction :: (Ord a, Ord b) => Monotonicity -> (a -> b) -> a -> a -> Bool\nmonotonicFunction cmp f x1 x2\n = f (min x1 x2) `op` f (max x1 x2)\n where\n op = case cmp of\n StrictInc -> (< )\n MonotoneInc -> (<=)\n StrictDec -> (> )\n MonotoneDec -> (>=)\n\n-- | Check that function is nondecreasing taking rounding errors into\n-- account. This function makes no distinction between strictly\n-- increasing function and monotonically increasing function since\n-- distinction is pointless for floating point.\n--\n-- In fact funstion is allowed to decrease less than one ulp in order\n-- to guard againist problems with excess precision. On x86 FPU works\n-- with 80-bit numbers but doubles are 64-bit so rounding happens\n-- whenever values are moved from registers to memory\nmonotonicFunctionIEEE :: (Ord a, IEEE.IEEE b) => Monotonicity -> (a -> b) -> a -> a -> Bool\nmonotonicFunctionIEEE cmp f x1 x2\n = y1 `op` y2\n || abs (y1 - y2) < abs (y2 * IEEE.epsilon)\n where\n y1 = f (min x1 x2)\n y2 = f (max x1 x2)\n op = case cmp of\n StrictInc -> (<=)\n MonotoneInc -> (<=)\n StrictDec -> (>=)\n MonotoneDec -> (>=)\n\n\n----------------------------------------------------------------\n-- Function and its inverse\n----------------------------------------------------------------\n\n-- | Check that function is inverse. Breaks down near zero.\ncheckInverse\n :: (Double -> Double) -- ^ Function @f(x)@\n -> (Double -> Double) -- ^ Inverse function @g@, @g(f(x)) = x@\n -> (Double -> Double) -- ^ Derivative of function @f(x)@\n -> Double -- ^ Relative error for\n -- @f(x)@. Usually is machine epsilon.\n -> Double -- ^ Relative error for inverse function\n -- @g(x)@. Usually is machine epsilon.\n -> Double -> Bool\ncheckInverse f invF f' eps eps' x\n = x ~= invF y\n where\n (~=) = eq (eps' + abs (y / f' x * eps))\n y = f x\n\n\n-- | Check that function is inverse. Breaks down near zero.\ncheckInverse2\n :: (Double -> Double) -- ^ Function @f(x)@\n -> (Double -> Double) -- ^ Inverse function @g@, @g(f(x)) = x@\n -> (Double -> Double) -- ^ Derivative of function @g(x)@\n -> Double -- ^ Relative error for\n -- @f(x)@. Usually is machine epsilon.\n -> Double -- ^ Relative error for inverse function\n -- @g(x)@. Usually is machine epsilon.\n -> Double -> Bool\ncheckInverse2 f invF invF' eps eps' x\n = x ~= invF y\n where\n (~=) = eq (eps' + abs (y * (invF' y * eps)))\n y = f x\n\n\n", "meta": {"hexsha": "583f5280709d1a37dafe66a7a21535931bf1c027", "size": 4416, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Test/QuickCheck/Numeric.hs", "max_stars_repo_name": "Shimuuar/quickcheck-numeric", "max_stars_repo_head_hexsha": "9cb705966fffbe2a31237ce70da6713f8aef2bc1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-31T04:53:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T04:53:16.000Z", "max_issues_repo_path": "Test/QuickCheck/Numeric.hs", "max_issues_repo_name": "Shimuuar/quickcheck-numeric", "max_issues_repo_head_hexsha": "9cb705966fffbe2a31237ce70da6713f8aef2bc1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test/QuickCheck/Numeric.hs", "max_forks_repo_name": "Shimuuar/quickcheck-numeric", "max_forks_repo_head_hexsha": "9cb705966fffbe2a31237ce70da6713f8aef2bc1", "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.9552238806, "max_line_length": 91, "alphanum_fraction": 0.5307971014, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5625101932015336}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Prelude hiding (readFile, drop)\nimport Control.Monad\nimport Control.Monad.IO.Class\nimport Control.Exception\nimport Foreign.C.Types\nimport System.Random\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Data\nimport SDL\nimport Debug.Trace\nimport qualified Linear\nimport Data.List.Split (chunksOf)\n\nimport Neural\nimport MNIST\n\n-- Generates a layer with a given number of neurons with inputCount weights.\n-- Weights are randomised between 0 and 1.\ngenLayer :: Int -> Int -> IO Layer\ngenLayer neurons inputCount = do\n weights <- replicateM (neurons * inputCount) (randomRIO (-0.2, 0.2) :: IO R)\n biases <- replicateM (neurons) (randomRIO (-0.2, 0.2) :: IO R)\n return $ Layer (matrix inputCount weights) (vector biases)\n\n-- Generates a network with the specified number of neurons in each layer,\n-- and the number of inputs to the network.\n-- Initialised with random weights and biases as in genLayer.\ngenNetwork :: [Int] -> Int -> IO Network\ngenNetwork layers inputCount = sequence . map (uncurry genLayer) $ layerDefs\n where\n -- Layer definitions in the form (neuronCount, inputCount)\n layerDefs = zip layers (inputCount:layers)\n\n-- A test network\ntestNetwork :: IO Network\ntestNetwork = do\n l1 <- genLayer 5 3\n l2 <- genLayer 5 5\n l3 <- genLayer 1 5\n return [l1, l2, l3]\n\n-- Another test network\ntestNetwork2 :: Network\ntestNetwork2 = [hiddenLayer, outputLayer]\n where\n hiddenLayer = Layer (matrix 2 [0.15, 0.2, 0.25, 0.3]) (vector [0.35, 0.35])\n outputLayer = Layer (matrix 2 [0.4, 0.45, 0.5, 0.55]) (vector [0.6, 0.6])\n\n-- Test inputs for testNetwork2\ntestInputs = vector [0.05, 0.1]\n\n-- Training data for testInputs\ntrainingData = vector [0.01, 0.99]\n\n-- Train neural network\ntrainNet = do\n (imageCount, width, height, imageData) <- readMNISTImages \"train-images-idx3-ubyte\"\n (labelCount, labels) <- readMNISTLabels \"train-labels-idx1-ubyte\"\n\n let image = head imageData\n let input = vector (map fromIntegral image)\n let correctNumber = fromIntegral . head $ labels\n let training = vector $ map (\\i -> if i == correctNumber then 1.0 else 0.0) [1..10]\n\n hiddenLayer <- genLayer 20 (width * height)\n outputLayer <- genLayer 10 20\n\n let initialNetwork = [hiddenLayer, outputLayer]\n\n let loop net i err =\n case i > 1000 || err < 0.1 of\n True -> net\n False -> trace (show $ sumElements (last error)) $ loop nextNet (i+1) (sumElements (last error))\n where\n output = evalNetwork net input\n error = evalNetworkError net output input training\n nextNet = gradientDescent net input (map fst output) error 0.1\n\n let trainedNet = loop initialNetwork 0 1000\n\n return (input, initialNetwork, trainedNet, training)\n\n-- Train neural network\ntrainNetM = do\n (imageCount, width, height, imageData) <- readMNISTImages \"train-images-idx3-ubyte\"\n (labelCount, labels) <- readMNISTLabels \"train-labels-idx1-ubyte\"\n\n let image = head imageData\n let input = fromRows [vector (map fromIntegral image)]\n let correctNumber = fromIntegral . head $ labels\n let training = fromRows [vector $ map (\\i -> if i == correctNumber then 1.0 else 0.0) [1..10]]\n\n hiddenLayer <- genLayer 20 (width * height)\n outputLayer <- genLayer 10 20\n\n let initialNetwork = [hiddenLayer, outputLayer]\n\n let loop net i err =\n case i > 100000 || err < 0.1 of\n True -> net\n False -> trace (show $ sumElements (last error)) $ loop nextNet (i+1) (sumElements (last error))\n where\n output = evalNetworkM net input\n error = evalNetworkErrorM net output input training\n nextNet = gradientDescentM net input (map fst output) error 0.1\n\n let trainedNet = loop initialNetwork 0 1000\n\n return (input, initialNetwork, trainedNet, training)\n\n-- Make a window and show MNIST image\nwindow image width height = do\n initializeAll\n\n window <- createWindow \"SDL Application\" defaultWindow\n renderer <- createRenderer window (-1) defaultRenderer\n\n -- Convert to sdl texture\n texture <- loadTextureMNIST renderer width height image\n\n SDL.rendererDrawColor renderer $= Linear.V4 255 255 255 255\n SDL.clear renderer\n\n copy renderer texture Nothing Nothing\n\n present renderer\n\n let loop = do\n pollEvents\n \n keyState <- getKeyboardState\n\n case keyState ScancodeEscape of\n True -> (return ()) :: IO ()\n False -> loop\n\n loop\n\n destroyTexture texture\n destroyRenderer renderer\n destroyWindow window\n\n-- Train a network using a given set of inputs and training values for the given\n-- number of epochs using the given learning rate.\ntrainNetwork :: Network -> [Vector R] -> [Vector R] -> Int -> Int -> R -> Network\ntrainNetwork initialNet input trainingValues epochs batchSize learnRate =\n train initialNet 0\n where\n train net epoch = case epoch >= epochs of\n True -> net\n False -> train nextNet (epoch + 1)\n where\n --inputBatch = fromRows input\n --trainingBatch = fromRows trainingValues\n inputBatches = map fromRows . chunksOf batchSize $ input\n trainingBatches = map fromRows . chunksOf batchSize $ trainingValues\n nextNet = foldl runBatch net (zip inputBatches trainingBatches)\n --nextNet = net\n runBatch network (inputBatch, trainingBatch) =\n gradientDescentM net inputBatch (map fst output) error learnRate\n where\n output = evalNetworkM net inputBatch\n error = evalNetworkErrorM net output inputBatch trainingBatch\n\ntoOutput = \\n -> vector . map (\\x -> if n == x then 1.0 else 0.0) $ [0..9]\n\nfromOutput :: Vector R -> Int\nfromOutput v = guess\n where\n list = zip [0..] . toList $ v\n possibles = filter ((>=0.5) . snd) list\n guess = case length possibles of\n 0 -> -1\n 1 -> fst . head $ possibles\n _ -> -2\n\nrunTest :: Network -> ([CUChar], Int) -> Bool\nrunTest network (image, label) = guess == label\n where output = fst . last $ evalNetwork network $ vector . map fromIntegral $ image\n guess = fromOutput output\n\n--runTest :: Network -> ([CUChar], Int) -> IO ()\n--runTest network (image, label) = do\n-- let output = fst . last $ evalNetwork network $ vector . map fromIntegral $ image\n-- let guess = fromOutput output\n-- let expected = label\n-- putStr \"Guess: \"\n-- putStr . show $ guess\n-- putStr \",\\tExpected: \"\n-- putStr . show $ label\n-- putStr $ if guess == expected then \".\\tCorrect! \" else \".\\tINCORRECT!\"\n-- putStrLn \"\"\n\nmain = do\n\n (trainingImageCount, trainingWidth,\n trainingHeight, trainingImageData) <- readMNISTImages \"train-images-idx3-ubyte\"\n (trainingLabelCount, trainingLabels) <- readMNISTLabels \"train-labels-idx1-ubyte\"\n\n (testImageCount, testWidth,\n testHeight, testImageData) <- readMNISTImages \"t10k-images-idx3-ubyte\"\n (testLabelCount, testLabels) <- readMNISTLabels \"t10k-labels-idx1-ubyte\"\n\n assert (trainingWidth == testWidth && trainingHeight == testHeight) (return ())\n\n let input = take 60000 . map (vector . map fromIntegral) $ trainingImageData\n let trainingData = take 60000 . map toOutput $ trainingLabels\n \n initialNetwork <- genNetwork [20,10] (trainingWidth * trainingHeight)\n\n let trainedNetwork = trainNetwork initialNetwork input trainingData 2 10 3.0\n\n let testImage = head testImageData\n let testInput = vector . map fromIntegral $ testImage\n let testOutput = head testLabels --toOutput $ head testLabels\n\n --window testImage testWidth testHeight\n\n --let output = fst . last $ evalNetwork trainedNetwork testInput\n --let filteredOutput = map (>=0.5) . toList $ output\n\n --print $ fromOutput output\n --print $ testOutput\n\n let tests = map (runTest trainedNetwork) $ zip testImageData testLabels\n\n let success = length . filter (==True) $ tests\n let total = length tests\n\n putStr . show $ success\n putStr \"/\"\n putStrLn . show $ total\n\n --flip mapM_ (take 100 $ zip testImageData testLabels) runTest\n -- where\n -- runTest (imageData, label) = output\n -- where\n -- output2 = evalNetwork trainedNetwork\n -- output = putStrLn \"test\"\n -- --let output = evalNetwork trainedNetwork (vector . map fromIntegral $ imageData)\n -- --in do\n -- -- putStr \"Guess: \"\n -- -- putStr . show . fromOutput $ output\n", "meta": {"hexsha": "35fd0d8d48079ac4785156f457c89c0f9c5c30e1", "size": 8402, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "Catchouli/neuron", "max_stars_repo_head_hexsha": "7c3e641d583b9b15992f89bef7a38061f083a72a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-08T21:09:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-08T21:09:05.000Z", "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "Catchouli/neuron", "max_issues_repo_head_hexsha": "7c3e641d583b9b15992f89bef7a38061f083a72a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main.hs", "max_forks_repo_name": "Catchouli/neuron", "max_forks_repo_head_hexsha": "7c3e641d583b9b15992f89bef7a38061f083a72a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-08T21:09:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-08T21:09:09.000Z", "avg_line_length": 33.8790322581, "max_line_length": 106, "alphanum_fraction": 0.6766246132, "num_tokens": 2256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.562374335690722}} {"text": "import Test.HUnit\nimport FFT.FFTControl\nimport FFT.Orig\nimport FFT.Samples\nimport System.Environment\nimport Data.Complex\n\ntestFFTbflySPipeline = TestCase (assertEqual \"FFT-bflyS-Pipline\" expected actual)\n where\n expected = (sum $ fftbflySPipeline samples512)\n actual = (sum $ fft samples512)\n samples512 = samples 1 512\n\ntestFFTDc = TestCase (assertEqual \"DFTDc\" expected actual)\n where\n expected = (sum $ fftdc samples512)\n actual = (sum $ fft samples512)\n samples512 = samples 1 512\n\ntests = TestList [TestLabel \"testFFTbFlysPipeline\" testFFTbflySPipeline,\n\t\tTestLabel \"testFFTDc\" testFFTDc\n ]\n \nmain = runTestTT tests\n", "meta": {"hexsha": "dc44e4d5597ebb51e4405af566541446384c3947", "size": 707, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/test/FFTControlTest.hs", "max_stars_repo_name": "BNJHope/parallel-fourier-transforms", "max_stars_repo_head_hexsha": "274ec189ed99715c4a912659683c0f93c0628a72", "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/test/FFTControlTest.hs", "max_issues_repo_name": "BNJHope/parallel-fourier-transforms", "max_issues_repo_head_hexsha": "274ec189ed99715c4a912659683c0f93c0628a72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/FFTControlTest.hs", "max_forks_repo_name": "BNJHope/parallel-fourier-transforms", "max_forks_repo_head_hexsha": "274ec189ed99715c4a912659683c0f93c0628a72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.28, "max_line_length": 81, "alphanum_fraction": 0.684582744, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5623272896319123}} {"text": "\nimport qualified Numeric.BMML.RVMR as RVM\nimport qualified Numeric.LinearAlgebra.HMatrix as H\nimport System.Random.MWC (asGenIO, uniformVector,\n withSystemRandom)\n\nf :: Double -> Double\nf x = 2.0 * x\n\n\ngenerateX :: IO (H.Vector Double)\ngenerateX =\n withSystemRandom . asGenIO $\n \\gen ->\n uniformVector gen 12500\n\ngenerateT :: H.Vector Double -> H.Vector Double\ngenerateT = H.cmap f\n\nmain :: IO ()\nmain = do\n x <- generateX\n noiseX <- H.rand 12500 2\n let trainT = generateT x\n trainX = (H.fromColumns [x]) H.||| noiseX\n print (f 0.5)\n print (RVM.predict (RVM.fit trainX trainT) (H.fromList [0.5, 10.0, 10000.0]))\n", "meta": {"hexsha": "ea57081b6428e729af0c74e667f7adc0dbb56e81", "size": 718, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "demo/Regression.hs", "max_stars_repo_name": "DbIHbKA/BMML", "max_stars_repo_head_hexsha": "1ed44258bacf91a1319a34f50d0ebcc6e5bbaef9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demo/Regression.hs", "max_issues_repo_name": "DbIHbKA/BMML", "max_issues_repo_head_hexsha": "1ed44258bacf91a1319a34f50d0ebcc6e5bbaef9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/Regression.hs", "max_forks_repo_name": "DbIHbKA/BMML", "max_forks_repo_head_hexsha": "1ed44258bacf91a1319a34f50d0ebcc6e5bbaef9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6428571429, "max_line_length": 79, "alphanum_fraction": 0.5988857939, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.5622349888839608}} {"text": "module GPLVM.PPCA\r\n ( PPCA (..)\r\n , makePPCA\r\n ) where\r\n\r\nimport Prelude (isNaN, log)\r\n\r\nimport Universum hiding (All, Any, Vector, map, toList, transpose, (++))\r\n\r\nimport qualified Universum as U\r\n\r\nimport GPLVM.Types\r\nimport GPLVM.Util\r\n\r\nimport Data.Array.Repa\r\nimport Data.Array.Repa.Repr.ForeignPtr\r\nimport Data.List ((\\\\))\r\nimport Numeric.LinearAlgebra.Repa hiding (Matrix, Vector, diag)\r\nimport System.Random\r\n\r\ndata PPCA = PPCA\r\n { _noMissedData :: Bool\r\n , _learningData :: Matrix D Double\r\n , desiredDimension :: Int\r\n , stopParameter :: Either Int Double\r\n , _variance :: Double\r\n , _W :: Matrix D Double\r\n , _finalExpLikelihood :: Double\r\n , _restoredMatrix :: Maybe (Matrix D Double)\r\n }\r\n\r\nmakePPCA\r\n :: (HasCallStack) => RandomGen gen\r\n => Matrix D Double -- ^ learning vectors\r\n -> Int -- ^ desired dimention\r\n -> Either Int Double -- ^ number of iterations or\r\n -- the value of stop difference of the likelihood expectation between interations of EM.\r\n -> gen\r\n -> PPCA\r\nmakePPCA leaningVectors desiredDimension stopParameter generator =\r\n let _learningData@(ADelayed (Z :. n :. _) _) = leaningVectors\r\n initMatrix = randomMatrixD generator (n, desiredDimension)\r\n initDispersion = fromIntegral $ fst . next $ generator\r\n _noMissedData = not $ isNaN $ runIdentity $ sumAllP _learningData\r\n (_W, _variance, _finalExpLikelihood, _restoredMatrix) =\r\n if _noMissedData\r\n then emStepsFast _learningData initMatrix initDispersion stopParameter\r\n else emStepsMissed _learningData initMatrix initDispersion stopParameter\r\n in PPCA{..}\r\n\r\n-- TODO: add comments to the most of following local binds\r\n-- Most of them does not have informative names because they are just intermediate calculations.\r\n\r\nemStepsFast\r\n :: (HasCallStack) => Matrix D Double\r\n -> Matrix D Double\r\n -> Double\r\n -> Either Int Double\r\n -> (Matrix D Double, Double, Double, Maybe (Matrix D Double))\r\nemStepsFast learnMatrix@(ADelayed (Z :. _ :. n) _) initMatrix@(ADelayed (Z :. d :. _) _) initVariance stopParam =\r\n let learnMatrixCentered = transpose $ substractMean (transpose learnMatrix)\r\n\r\n stepOne :: (HasCallStack) => Array D DIM2 Double -> Double -> Int -> (Matrix D Double, Double, Double, Maybe (Matrix D Double))\r\n stepOne (!oldW) oldVariance iteration =\r\n let m = delay $ mapDiagonal (oldVariance +) $ (transpose oldW) `mulS` oldW\r\n invM = invS m\r\n expEznZ = delay $ invM `mul` (transpose oldW `mulS` learnMatrixCentered)\r\n expXnEZnZ = learnMatrixCentered `mulS` (transpose expEznZ)\r\n expZtrZ = computeS $ (map (*((fromIntegral n)*oldVariance)) $ delay invM) +^ (expEznZ `mulS` (transpose $ expEznZ)) :: Matrix F Double\r\n in stepTwo (expEznZ, expZtrZ, expXnEZnZ) oldW oldVariance iteration\r\n\r\n stepTwo :: (HasCallStack) => (Matrix D Double, Matrix F Double, Matrix F Double) -> Matrix D Double -> Double -> Int -> (Matrix D Double, Double, Double, Maybe (Matrix D Double))\r\n stepTwo (expEznZ, expZtrZ, expXnEZnZ) oldW oldVariance iteration =\r\n let newW = delay $ expXnEZnZ `mul` (inv expZtrZ)\r\n u = chol $ trustSym expZtrZ\r\n wr = newW `mulS` (transpose u)\r\n totalSum = sumAllS $ map (^ (2 :: Int)) learnMatrixCentered\r\n secondDenominatorInVariance = (*2) $ sumAllS $ expEznZ *^ (delay $ (transpose newW) `mulS` learnMatrixCentered)\r\n thirdDenominatorInVariance = sumAllS $ map (^(2 :: Int)) wr\r\n newVariance = (totalSum - secondDenominatorInVariance + thirdDenominatorInVariance)/(fromIntegral $ n*d)\r\n maxDiffNewOldW = foldAllS max 0.0 $ map abs $ oldW -^ newW\r\n diffVariance = abs $ newVariance - oldVariance\r\n newC = mapDiagonal ((+) newVariance) $ newW `mulS` (transpose newW)\r\n newInvM = delay $ invS $ mapDiagonal (newVariance +) $ (transpose newW) `mulS` newW\r\n newInvC = (mapDiagonal (+(1/newVariance))\r\n (map (\\x -> -x/newVariance) $ (delay $ newW `mulS` newInvM) `mulS` (transpose newW)))\r\n expLogLikelihood = (-1.0)*((fromIntegral n)/2.0)*((fromIntegral d)*(log $ 2*pi)\r\n + (log $ detS newC)\r\n + (trace2S $ computeS $ map (/(fromIntegral $ n-1)) $ newInvC `mulS` (delay $ learnMatrixCentered `mulS` (transpose learnMatrixCentered))))\r\n in case stopParam of\r\n Left maxIteration -> if maxIteration > iteration then stepOne newW newVariance (iteration + 1) else (newW,newVariance, expLogLikelihood, Nothing)\r\n Right stopDiffBetweenIterations -> if (max diffVariance maxDiffNewOldW) > stopDiffBetweenIterations then stepOne newW newVariance (iteration + 1) else (newW,newVariance, expLogLikelihood, Nothing)\r\n\r\n in stepOne initMatrix initVariance 0\r\n\r\nemStepsMissed\r\n :: (HasCallStack) => Matrix D Double\r\n -> Matrix D Double\r\n -> Double\r\n -> Either Int Double\r\n -> (Matrix D Double, Double, Double, Maybe (Matrix D Double))\r\nemStepsMissed learnMatrix@(ADelayed (Z :. _ :. n) _) initMatrix@(ADelayed (Z :. d :. _) _) initVariance stopParam =\r\n let initMu = delay $ fromListUnboxed (Z:.d:.1) $ replicate d 0.0 -- extend (Any :. (1 :: Int)) $ meanColumnWithNan learnMatrix\r\n\r\n stepOne :: (HasCallStack) => Array D DIM2 Double -> Array D DIM2 Double -> Double -> Int -> (Matrix D Double, Double, Double, Maybe (Matrix D Double))\r\n stepOne oldMu (!oldW) oldVariance iteration =\r\n let yi i = extend (Any :. (1 :: Int)) $ slice learnMatrix (Any :. (i :: Int))\r\n yList i = toList (yi i)\r\n unknownIndices i =\r\n let zipped = zip [0..] (yList i)\r\n in U.map fst $ filter (isNaN . snd) zipped\r\n yPi i = deleteRows (unknownIndices i) (yi i)\r\n muP i = deleteRows (unknownIndices i) oldMu\r\n oldWP i = deleteRows (unknownIndices i) oldW\r\n mP i = mapDiagonal (+ oldVariance) $ (transpose (oldWP i)) `mulS` (oldWP i)\r\n invMP i = delay $ invS $ mP i\r\n expXi i = delay $ (delay $ (delay $ invMP i) `mulS` (transpose (oldWP i))) `mulS` (yPi i -^ muP i)\r\n in stepTwo ([yPi, expXi, invMP], unknownIndices, oldW) oldVariance iteration\r\n\r\n stepTwo :: (HasCallStack) => ([Int -> Matrix D Double], Int -> [Int], Matrix D Double) -> Double -> Int -> (Matrix D Double, Double, Double, Maybe (Matrix D Double))\r\n stepTwo ([yP, expXi, invMP], unknownIndices, oldW) oldVariance iteration =\r\n let expX = foldl1 (\\acc i -> acc ++ i) $ U.map expXi [0..(n-1)]\r\n newMu = extend (Any :. (1 :: Int)) $ meanColumnWithNan $ (learnMatrix -^ (oldW `mulS` expX))\r\n\r\n newW =\r\n let yj j = extend (Any :. (1 :: Int) :. All) $ slice learnMatrix (Any :. (j :: Int) :. All)\r\n yJList j = toList (yj j)\r\n unknownColumns j =\r\n let zipped = zip [0..] (yJList j)\r\n in U.map fst $ filter (isNaN . snd) zipped\r\n knownColumns j = [0..(n-1)] \\\\ (unknownColumns j)\r\n expXPj j = deleteColumns (unknownColumns j) expX\r\n sumInvMP j = sumListMatrices $ U.map invMP (knownColumns j)\r\n gj j = ((expXPj j) `mulS` (transpose $ expXPj j)) +^ (map (*oldVariance) (sumInvMP j))\r\n yPj j = deleteColumns (unknownColumns j) (yj j)\r\n expXtrXj j = (expXPj j) `mulS` (transpose (map (\\x -> x - (newMu ! (Z:.j:.0))) (yPj j)))\r\n newWj j = (gj j) `solveS` (delay $ expXtrXj j)\r\n in transpose $ foldl1 (\\acc j -> acc ++ j) $ U.map (\\x -> delay $ newWj x) [0..(d-1)]\r\n\r\n newVariance =\r\n let newWPi i = deleteRows (unknownIndices i) newW\r\n newMuP i = deleteRows (unknownIndices i) newMu\r\n varianceStep i = sumAllS $\r\n (map (^(2 :: Int)) (yP i -^ ((newWPi i) `mulS` (expXi i)) -^ (newMuP i)))\r\n +^ (map (*oldVariance) $ diag $ delay $ (delay $ (delay $ newWPi i) `mulS` (invMP i)) `mulS` (transpose $ newWPi i))\r\n knownVars = foldAllS (\\acc x -> if isNaN x then acc else acc + 1.0) 0.0 learnMatrix\r\n in (sum $ U.map varianceStep [0..(n-1)])/knownVars\r\n\r\n expLogLikelihood =\r\n let newMuP i = deleteRows (unknownIndices i) newMu\r\n newWPi i = deleteRows (unknownIndices i) newW\r\n yCenteredP i = (yP i) -^ (newMuP i)\r\n yCenteredProd i = delay $ (yCenteredP i) `mulS` (transpose $ yCenteredP i)\r\n invMY i = mapDiagonal (+newVariance) $ (newWPi i) `mulS` (transpose $ newWPi i)\r\n knownIndices i = [0..(d-1)] \\\\ (unknownIndices i)\r\n expLogLikelihoodStep i = (fromIntegral $ length $ knownIndices i)*(log $ 2*pi) + (log $ detS $ invMY i) +\r\n (trace2S $ computeS $ delay $ (invMY i) `solveS` (yCenteredProd i))\r\n\r\n in (-1.0)*(sum $ U.map expLogLikelihoodStep [0..(n-1)])/2.0\r\n\r\n restoredData =\r\n let muX = extend (Any :. (1 :: Int)) $ meanColumn (transpose expX)\r\n finalMu = slice (newMu +^ (newW `mulS` muX)) (Any :. (0 :: Int))\r\n wtrw = (transpose newW) `mulS` newW\r\n factor1 = newW `mulS` (delay $ inv wtrw)\r\n factor2 = computeS $ mapDiagonal (+newVariance) wtrw\r\n restoredCentered = factor1 `mul` factor2 `mul` (computeS $ expX)\r\n in (delay restoredCentered) +^ (extend (Any :. (n :: Int)) finalMu)\r\n\r\n diffVariance = abs $ newVariance - oldVariance\r\n maxDiffNewOldW = foldAllS max 0.0 $ map abs $ oldW -^ newW\r\n\r\n in case stopParam of\r\n Left maxIteration ->\r\n if maxIteration > iteration\r\n then stepOne newMu newW newVariance (iteration + 1)\r\n else (newW,newVariance, expLogLikelihood, Just restoredData)\r\n Right stopDiffBetweenIterations ->\r\n if (max diffVariance maxDiffNewOldW) > stopDiffBetweenIterations\r\n then stepOne newMu newW newVariance (iteration + 1)\r\n else (newW,newVariance, expLogLikelihood, Just restoredData)\r\n in stepOne initMu initMatrix initVariance 0\r\n", "meta": {"hexsha": "98053518e86b6ba8e9dd6e59f6724526f8be263f", "size": 10430, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/GPLVM/PPCA.hs", "max_stars_repo_name": "serokell/GPLVMHaskell", "max_stars_repo_head_hexsha": "bf6c01b3a9e1812be0da59e39c479f2b5ed47e9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-08-08T23:15:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-27T16:47:52.000Z", "max_issues_repo_path": "src/GPLVM/PPCA.hs", "max_issues_repo_name": "serokell/GPLVMHaskell", "max_issues_repo_head_hexsha": "bf6c01b3a9e1812be0da59e39c479f2b5ed47e9b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GPLVM/PPCA.hs", "max_forks_repo_name": "serokell/GPLVMHaskell", "max_forks_repo_head_hexsha": "bf6c01b3a9e1812be0da59e39c479f2b5ed47e9b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.9945355191, "max_line_length": 211, "alphanum_fraction": 0.5896452541, "num_tokens": 2964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.5622311004962071}} {"text": "{-# LANGUAGE LambdaCase #-}\n-- |\n-- Module: Analysis.PerfModel\n--\n-- An experimental approach to obtaining strengths, which takes Elo (or\n-- Elo-like) ratings as derived from a performance model. With a performance\n-- model in hand, we can use https://stats.stackexchange.com/a/44142 to\n-- obtain the victory probability of a 1500-rated racer given a field of\n-- racers, and use that as a measure of strength.\n--\n-- According to the model, player performances follow a gamma distribution,\n-- with the outcome 0 corresponding to an ideal performance. The shape\n-- parameter of the distribution is fixed, while the rate parameter varies\n-- across players. A higher rate parameter amounts to results that are both\n-- more consistent and closer to the ideal. (Pinning both mean and standard\n-- deviation of player performance to a single parameter is the main\n-- simplifying assumption of the model.)\n--\n-- Note that the performance model winning probabilities for pairs of players\n-- agree exactly with the conventional Elo formula if the shape parameter of\n-- the gamma distribution is taken to be 1.\nmodule Analysis.PerfModel\n ( perfModelStrength\n , perfModelTopStrength\n , example\n ) where\n\nimport Orbital (orbitalDistr, initialRating)\nimport qualified Util.Combinations as Util\n\nimport qualified Numeric.Integration.TanhSinh as Integration\nimport Statistics.Distribution\n\nimport Data.Profunctor\nimport qualified Control.Foldl as L\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntMap.Strict (IntMap, (!))\nimport qualified Data.IntSet as IntSet\nimport Data.IntSet (IntSet)\nimport qualified Control.Foldl as L\n\n-- | PDF for a race victory against a field of racers.\nraceWinPDF\n :: Int -- ^ Gamma shape.\n -> [Double] -- ^ Ratings of the field of opponents.\n -> Double -- ^ Rating of the racer.\n -> Double -- ^ Performance.\n -> Double\nraceWinPDF gsh rs r t = density (orbitalDistr gsh r) t\n * L.fold (lmap winVersus L.product) rs\n where\n winVersus r' = 1 - cumulative (orbitalDistr gsh r') t\n\n-- | Integrating the race win PDF gives the likelihood of victory, whose\n-- reciprocal we use as a strength metric.\nperfModelStrength\n :: Int -- ^ Gamma shape.\n -> [Double] -- ^ Ratings of the field of opponents.\n -> Double\nperfModelStrength gsh rs = 1 / integ\n where\n integ = Integration.result . Integration.absolute 1e-6 $\n Integration.nonNegative Integration.trap (raceWinPDF gsh rs initialRating)\n\n-- TODO: positionPDF and positionPDFPre are still the same as in\n-- Analysis.PerfModel.Reference.Precompute . Conside redefining them so that\n-- topPDF can share code with them.\n\n-- | Like 'raceWinPDF', but for an arbitrary position on the scoreboard.\npositionPDF\n :: Int -- ^ Gamma shape.\n -> Int -- ^ Target position.\n -> [Double] -- ^ Ratings of the field of opponents.\n -> Double -- ^ Rating of the racer.\n -> Double -- ^ Performance.\n -> Double\npositionPDF gsh pos rs r t = density (orbitalDistr gsh r) t\n * L.fold L.sum (L.fold L.product . toFactors <$> combos)\n where\n n = length rs\n combos = Util.combinations n (pos-1) [1..n]\n loseVersus r' = cumulative (orbitalDistr gsh r') t\n -- winVersus r' = 1 - loseVersus r'\n lvs = IntMap.fromList (zip [1..n] (loseVersus <$> rs))\n wvs = (1 -) <$> lvs\n toFactors (above, below) = map (lvs !) above ++ map (wvs !) below\n\n-- | A variant of 'positionPDF' that takes precomputed probabilities.\npositionPDFPre :: Int -- ^ Target position.\n -> (IntMap Double, IntMap Double) -- ^ Win and loss probabilities\n -- (given a probe laptime) for\n -- for each racer on the\n -- scoreboard.\n -> Double -- ^ Probability density of the\n -- probe laptime.\n -> Double\npositionPDFPre pos (lvs, wvs) p =\n p * L.fold L.sum (L.fold L.product . toFactors <$> combos)\n where\n n = IntMap.size lvs\n combos = Util.combinations n (pos-1) [1..n]\n toFactors (above, below) = map (lvs !) above ++ map (wvs !) below\n\n-- | Like 'positionPDF', but for a top-N finish.\ntopPDF\n :: Int -- ^ Gamma shape.\n -> Int -- ^ Target position.\n -> [Double] -- ^ Ratings of the field of opponents.\n -> Double -- ^ Rating of the racer.\n -> Double -- ^ Performance.\n -> Double\ntopPDF gsh pos rs r t = (probeDensity *) . L.fold L.sum $\n L.fold L.sum . partials <$> validPositions\n where\n validPositions = zipWith const [1..pos] (r : rs)\n loseVersus r' = cumulative (orbitalDistr gsh r') t\n lvs = IntMap.fromList (zip [1..] (loseVersus <$> rs))\n wvs = (1 -) <$> lvs\n probeDensity = density (orbitalDistr gsh r) t\n partials = Util.processCombsInt alg (length rs) . subtract 1\n alg = \\case\n Util.LeafF Nothing -> 0\n Util.LeafF (Just rest) ->\n L.fold L.product ((wvs !) <$> IntSet.toList rest)\n Util.FlowerF a rest -> (lvs ! a)\n * L.fold L.product ((wvs !) <$> IntSet.toList rest)\n Util.BranchF a bs -> (lvs ! a) * L.fold L.sum bs\n\n-- | Like 'perfModelStrength', but for a top-N finish. Note that the\n-- computational cost grows quickly with the length of the list of ratings.\nperfModelTopStrength\n :: Int -- ^ Gamma shape.\n -> Int -- ^ Target position.\n -> [Double] -- ^ Ratings of the field of racers.\n -> Double\nperfModelTopStrength gsh pos rs = 1 / integ\n where\n integ = Integration.result . Integration.absolute 1e-6 $\n Integration.nonNegative Integration.trap (topPDF gsh pos rs initialRating)\n\n\nexample :: [Double]\nexample = [2200,2100,1900,1870,1850,1600]\n--example = [2200,2100,1900,1870,1850,1600,1590,1570,1510,1420,1370,1350,1225]\n\n-- >$> perfModelStrength [2200,2100,1900,1870,1850]\n--\n-- >$> :set +s\n--\n\n-- >$> perfModelTopStrength 5 example\n\n", "meta": {"hexsha": "abed3b81175a4cdbdf3c34984d2084d048a3fdff", "size": 6048, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Analysis/PerfModel.hs", "max_stars_repo_name": "duplode/elo-zs", "max_stars_repo_head_hexsha": "1496a6a46f9aa62dc3bf16d14e3ae8bb497c4a9f", "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": "Analysis/PerfModel.hs", "max_issues_repo_name": "duplode/elo-zs", "max_issues_repo_head_hexsha": "1496a6a46f9aa62dc3bf16d14e3ae8bb497c4a9f", "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": "Analysis/PerfModel.hs", "max_forks_repo_name": "duplode/elo-zs", "max_forks_repo_head_hexsha": "1496a6a46f9aa62dc3bf16d14e3ae8bb497c4a9f", "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.5294117647, "max_line_length": 82, "alphanum_fraction": 0.6398809524, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5620687193176281}} {"text": "{-# LANGUAGE GADTs #-}\nmodule Distrib (\n -- * Data Constructors\n Distrib(..)\n -- * Operations\n , compNormalDistr\n , pdf\n ) where\n\n------------------------------------------------------------------\n\nimport Classifier\nimport qualified Data.Vector.Unboxed as VU\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal\nimport qualified Statistics.Sample as Statistics\n\n------------------------------------------------------------------\n\ndata Distrib where\n Distrib :: ContDistr d => d -> Distrib\n\n-- | We don't know much about our numeric variable\n-- so we will assume normallity to simplify the implementation.\ncompNormalDistr :: [Double] -> Distrib\ncompNormalDistr xs =\n Distrib (normalDistr mean' stdDev')\n where\n v = VU.fromList xs\n mean' = Statistics.mean v\n stdDev' = max 0.1 (Statistics.stdDev v) -- stdDev must be > 0\n\n-- | Probability Density Function\npdf :: Distrib -> Double -> Probability\npdf (Distrib d) = Probability . density d\n", "meta": {"hexsha": "ca95b3ff1fd4d3d6f8074fe3f0ad2ae97aa5b4a5", "size": 1039, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Distrib.hs", "max_stars_repo_name": "monadplus/naive-bayes-classifier", "max_stars_repo_head_hexsha": "bb6ee4ba8eba2ff43d9e042906af78b789225760", "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/Distrib.hs", "max_issues_repo_name": "monadplus/naive-bayes-classifier", "max_issues_repo_head_hexsha": "bb6ee4ba8eba2ff43d9e042906af78b789225760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Distrib.hs", "max_forks_repo_name": "monadplus/naive-bayes-classifier", "max_forks_repo_head_hexsha": "bb6ee4ba8eba2ff43d9e042906af78b789225760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8611111111, "max_line_length": 68, "alphanum_fraction": 0.5794032724, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5619880705657435}} {"text": "module Statistics.ANOVA (anova, fisherLSD) where\nimport Data.List\nimport Statistics.Distribution hiding (mean, variance)\nimport Statistics.Distribution.FDistribution\nimport Statistics.Distribution.StudentT\nimport Statistics.Sample\nimport qualified Data.Vector as V\n\n{-# INLINE treatments #-}\ntreatments :: (Ord a,Eq a) => V.Vector (a, Double) -> V.Vector a\ntreatments input = V.fromList $! nub $! V.toList $! V.map fst input --not good\n\ntreatmentMeans :: (Ord a, Eq a) => V.Vector a -> V.Vector (a, Double) -> V.Vector (a,Double) \ntreatmentMeans treatments input = V.map (\\x -> x input) meanFuncs \n where meanFuncs = V.map treatmentMean $! treatments \n\ntreatmentMean :: (Ord a, Eq a) => a -> V.Vector (a,Double) -> (a,Double)\ntreatmentMean treatment input = (treatment, avg) \n where avg = mean $! V.map snd $! filterTreatment treatment $! input\n \ntreatmentSize treatment input = V.length $! filterTreatment treatment $! input \n \n{-# INLINE filterTreatment #-}\nfilterTreatment :: (Ord a, Eq a) => a -> V.Vector (a, Double) -> V.Vector (a, Double)\nfilterTreatment treatment = V.filter (\\(x,y) -> x == treatment)\n\nsampleMean input = mean $! V.map snd input \n\nssTreatment :: (Ord a, Eq a) => V.Vector a -> V.Vector (a, Double) -> Double\nssTreatment treatments input = V.sum $! V.zipWith (\\size mean -> size*(mean-sMean)*(mean-sMean)) tSizes tMeans \n where sMean = sampleMean input\n tMeans = V.map snd $! treatmentMeans treatments input\n tSizes = V.map (\\x -> fromIntegral $! x input) $! V.map treatmentSize $! treatments --input\n\nssError :: (Ord a, Eq a) => V.Vector (a, Double) -> Double\nssError input = V.sum $! V.map (\\x -> x input) $! V.map treatmentError $! treatments input\n\ntreatmentError treatment input = V.sum $! V.map (\\x -> (x-tMean)*(x-tMean)) filteredInput\n where filteredInput = V.map snd $! filterTreatment treatment input \n tMean = snd $! treatmentMean treatment input\n\nfValue :: (Ord a, Eq a) => V.Vector a -> V.Vector (a, Double) -> Double\nfValue treatments input = ((ssTreatment treatments input)/(ssError input)) * ((sampleSize - numberOfTreatments)/(numberOfTreatments -1))\n where numberOfTreatments = fromIntegral $! V.length $! treatments \n sampleSize = fromIntegral $! V.length input\n \nfDist treatments input = fDistribution (numberOfTreatments-1) (sampleSize-numberOfTreatments) \n where numberOfTreatments = fromIntegral $! V.length treatments \n sampleSize = fromIntegral $! V.length input\n \npValue input = 1 - cumulative (fDist t input) (fValue t input)\n where t = treatments input\n\nanova pvalue input\n | pValue input < pvalue = True\n | otherwise = False \n\ntTest :: (Ord a, Eq a) => Double -> a -> a -> V.Vector (a, Double) -> Bool\ntTest pvalue treatment1 treatment2 inputs = abs (tTestT treatment1 treatment2 inputs) > critical\n where critical = quantile (studentT (degreesOfFreedom treatment1 treatment2 inputs)) (1 - pvalue/2)\n\ntTestT :: (Ord a, Eq a) => a -> a -> V.Vector (a, Double) -> Double\ntTestT treatment1 treatment2 inputs = (mean1-mean2)/sqrt(var1/size1+var2/size2)\n where mean1 = snd $! treatmentMean treatment1 inputs\n mean2 = snd $! treatmentMean treatment2 inputs\n size1 = fromIntegral $! V.length $! filterTreatment treatment1 inputs\n size2 = fromIntegral $! V.length $! filterTreatment treatment2 inputs\n var1 = variance $! V.map snd $! filterTreatment treatment1 inputs\n var2 = variance $! V.map snd $! filterTreatment treatment2 inputs\n \ndegreesOfFreedom\n :: (Ord a, Eq a) => a -> a -> V.Vector (a, Double) -> Double\ndegreesOfFreedom treatment1 treatment2 inputs = numerator / denominator\n where size1 = fromIntegral $! V.length $! filterTreatment treatment1 inputs\n size2 = fromIntegral $! V.length $! filterTreatment treatment2 inputs\n var1 = variance $! V.map snd $! filterTreatment treatment1 inputs\n var2 = variance $! V.map snd $! filterTreatment treatment2 inputs\n numerator = (var1/size1+var2/size2)^2\n denominator = (((var1/size1)^2)/(size1-1)) + (((var2/size2)^2)/(size2-1))\n\nnoDifferenceInMean pvalue treatment input = (:) treatment $!\n map fst $!\n filter (\\(x,y) -> not y) $! \n map (\\x -> (x, tTest pvalue treatment x input)) othertreatments\n where othertreatments = delete treatment $! V.toList $! treatments input\n \nequivalenceList pvalue input = nub $! V.toList $! V.map (\\x -> sort $! noDifferenceInMean pvalue x input) $! treatments input\n\nfisherLSD :: (Eq a, Ord a) => Double -> V.Vector (a, Double) -> [[a]]\nfisherLSD pvalue input = case (anova pvalue input) of\n False -> [V.toList $! treatments input]\n True -> equivalenceList pvalue input\n", "meta": {"hexsha": "3839bd9c89821e6ed6a977f10e8b3b66f98d6fea", "size": 4841, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/ANOVA.hs", "max_stars_repo_name": "richardfergie/statistics-anova", "max_stars_repo_head_hexsha": "6b2bab997951c54bfa82520fe0a2de7a816c0901", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-03T03:11:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-06T07:45:10.000Z", "max_issues_repo_path": "Statistics/ANOVA.hs", "max_issues_repo_name": "richardfergie/statistics-anova", "max_issues_repo_head_hexsha": "6b2bab997951c54bfa82520fe0a2de7a816c0901", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/ANOVA.hs", "max_forks_repo_name": "richardfergie/statistics-anova", "max_forks_repo_head_hexsha": "6b2bab997951c54bfa82520fe0a2de7a816c0901", "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": 52.0537634409, "max_line_length": 136, "alphanum_fraction": 0.6624664326, "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5619644833633659}} {"text": "module European (\n European(European),\n PutCall(PUT, CALL),\n black76Call,\n black76Put) where\n\nimport Dates\nimport Market\nimport Instrument\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal\n\n-- |Enum defining a put (option to sell) or call (option to buy)\ndata PutCall = PUT | CALL deriving (Eq, Show, Read)\n\n-- |The 1976 formulation of the Black-Scholes formula for pricing a European\n-- |call option. Parameters discount d, forward f, variance v, strike k, \nblack76Call :: Double -> Double -> Double -> Double -> Double\nblack76Call d f v k = d * ((n d1) * f - (n d2) * k) where\n d1 = (log (f/k) + 0.5 * v) / sqrt v\n d2 = d1 - v\n n = cumulative standard\n\n-- |Put call parity says that C - P = S - K, or that here\n-- |P = C + d (k - f)\nblack76Put :: Double -> Double -> Double -> Double -> Double\nblack76Put d f v k = (black76Call d f v k) + d * (k - f)\n\n-- |European option\ndata European = European {\n putOrCall :: PutCall,\n expiry :: Date,\n creditEntity :: String, -- e.g. Currency for a risk-free option\n underlying :: String,\n underlyingEntity :: String, -- e.g. Currency of the underlying asset\n strike :: Double } deriving (Eq, Show, Read)\n\n-- |Price a European given a discount, forward and vol surface\npriceGivenCurves :: European -> Date -> Discount -> Forward -> VolSurface -> Double\npriceGivenCurves e valueDate d f v = \n let\n k = (strike e)\n date = (expiry e)\n dates = [date] -- only one date of interest (ignoring settlement)\n discount = head (d dates)\n forward = head (f dates)\n vol = v f date k\n t = act365 valueDate date\n variance = vol^2 * t\n in\n case putOrCall e of\n PUT -> black76Put discount forward variance k\n CALL -> black76Call discount forward variance k\n\n-- |Generic pricer for European, where it finds the data it needs in the market\ninstance Priceable European where\n price e m = do\n let ul = (underlying e)\n let valDate = valueDate m\n discount <- findDiscount m (creditEntity e)\n forward <- findEquityForward m ul (underlyingEntity e)\n volSurface <- findVol m ul\n return $ priceGivenCurves e valDate discount forward volSurface\n", "meta": {"hexsha": "5bdfa7ff9c2d6f4f3942318cd9c445d52a8b7455", "size": 2258, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/European.hs", "max_stars_repo_name": "MarcusRainbow/Ffinar", "max_stars_repo_head_hexsha": "9205856a13e959ba4b871895f87eaa3e6dc64fc3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-22T16:17:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T16:17:28.000Z", "max_issues_repo_path": "src/European.hs", "max_issues_repo_name": "MarcusRainbow/Ffinar", "max_issues_repo_head_hexsha": "9205856a13e959ba4b871895f87eaa3e6dc64fc3", "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/European.hs", "max_forks_repo_name": "MarcusRainbow/Ffinar", "max_forks_repo_head_hexsha": "9205856a13e959ba4b871895f87eaa3e6dc64fc3", "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.28125, "max_line_length": 83, "alphanum_fraction": 0.645704163, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5617220771306608}} {"text": "{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module : Statistics.Distribution.FDistribution\n-- Copyright : (c) 2011 Aleksey Khudyakov\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Fisher F distribution\nmodule Statistics.Distribution.FDistribution (\n FDistribution\n , fDistribution\n , fDistributionNDF1\n , fDistributionNDF2\n ) where\n\nimport Data.Aeson (FromJSON, ToJSON)\nimport Data.Binary (Binary)\nimport Data.Data (Data, Typeable)\nimport Numeric.MathFunctions.Constants (m_neg_inf)\nimport GHC.Generics (Generic)\nimport qualified Statistics.Distribution as D\nimport Statistics.Function (square)\nimport Numeric.SpecFunctions (\n logBeta, incompleteBeta, invIncompleteBeta, digamma)\nimport Data.Binary (put, get)\nimport Control.Applicative ((<$>), (<*>))\n\n-- | F distribution\ndata FDistribution = F { fDistributionNDF1 :: {-# UNPACK #-} !Double\n , fDistributionNDF2 :: {-# UNPACK #-} !Double\n , _pdfFactor :: {-# UNPACK #-} !Double\n }\n deriving (Eq, Show, Read, Typeable, Data, Generic)\n\ninstance FromJSON FDistribution\ninstance ToJSON FDistribution\n\ninstance Binary FDistribution where\n get = F <$> get <*> get <*> get\n put (F x y z) = put x >> put y >> put z\n\nfDistribution :: Int -> Int -> FDistribution\nfDistribution n m\n | n > 0 && m > 0 =\n let n' = fromIntegral n\n m' = fromIntegral m\n f' = 0.5 * (log m' * m' + log n' * n') - logBeta (0.5*n') (0.5*m')\n in F n' m' f'\n | otherwise =\n error \"Statistics.Distribution.FDistribution.fDistribution: non-positive number of degrees of freedom\"\n\ninstance D.Distribution FDistribution where\n cumulative = cumulative\n\ninstance D.ContDistr FDistribution where\n density d x\n | x <= 0 = 0\n | otherwise = exp $ logDensity d x\n logDensity d x\n | x <= 0 = m_neg_inf\n | otherwise = logDensity d x\n quantile = quantile\n\ncumulative :: FDistribution -> Double -> Double\ncumulative (F n m _) x\n | x <= 0 = 0\n | isInfinite x = 1 -- Only matches +\u221e\n | otherwise = let y = n*x in incompleteBeta (0.5 * n) (0.5 * m) (y / (m + y))\n\nlogDensity :: FDistribution -> Double -> Double\nlogDensity (F n m fac) x\n = fac + log x * (0.5 * n - 1) - log(m + n*x) * 0.5 * (n + m)\n\nquantile :: FDistribution -> Double -> Double\nquantile (F n m _) p\n | p >= 0 && p <= 1 =\n let x = invIncompleteBeta (0.5 * n) (0.5 * m) p\n in m * x / (n * (1 - x))\n | otherwise =\n error $ \"Statistics.Distribution.Uniform.quantile: p must be in [0,1] range. Got: \"++show p\n\n\ninstance D.MaybeMean FDistribution where\n maybeMean (F _ m _) | m > 2 = Just $ m / (m - 2)\n | otherwise = Nothing\n\ninstance D.MaybeVariance FDistribution where\n maybeStdDev (F n m _)\n | m > 4 = Just $ 2 * square m * (m + n - 2) / (n * square (m - 2) * (m - 4))\n | otherwise = Nothing\n\ninstance D.Entropy FDistribution where\n entropy (F n m _) =\n let nHalf = 0.5 * n\n mHalf = 0.5 * m in\n log (n/m)\n + logBeta nHalf mHalf\n + (1 - nHalf) * digamma nHalf\n - (1 + mHalf) * digamma mHalf\n + (nHalf + mHalf) * digamma (nHalf + mHalf)\n\ninstance D.MaybeEntropy FDistribution where\n maybeEntropy = Just . D.entropy\n\ninstance D.ContGen FDistribution where\n genContVar = D.genContinous\n", "meta": {"hexsha": "56ef912c5043e4620d98cc22e5ba4e75408f9b50", "size": 3387, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/FDistribution.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "Statistics/Distribution/FDistribution.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Distribution/FDistribution.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7909090909, "max_line_length": 106, "alphanum_fraction": 0.6220844405, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.561722077107816}} {"text": "{-# OPTIONS_GHC -Wall #-}\n\n-- | A magma heirarchy for addition. The basic magma structure is repeated and prefixed with 'Additive-'.\nmodule Plankton.Additive\n ( AdditiveMagma(..)\n , AdditiveUnital(..)\n , AdditiveAssociative\n , AdditiveCommutative\n , AdditiveInvertible(..)\n , AdditiveIdempotent\n , sum\n , Additive(..)\n , AdditiveRightCancellative(..)\n , AdditiveLeftCancellative(..)\n , AdditiveGroup(..)\n ) where\n\nimport Data.Complex (Complex(..))\nimport qualified Protolude as P\nimport Protolude (Bool(..), Double, Float, Int, Integer)\n\n-- | 'plus' is used as the operator for the additive magma to distinguish from '+' which, by convention, implies commutativity\n--\n-- > \u2200 a,b \u2208 A: a `plus` b \u2208 A\n--\n-- law is true by construction in Haskell\nclass AdditiveMagma a where\n plus :: a -> a -> a\n\ninstance AdditiveMagma Double where\n plus = (P.+)\n\ninstance AdditiveMagma Float where\n plus = (P.+)\n\ninstance AdditiveMagma Int where\n plus = (P.+)\n\ninstance AdditiveMagma Integer where\n plus = (P.+)\n\ninstance AdditiveMagma Bool where\n plus = (P.||)\n\ninstance (AdditiveMagma a) => AdditiveMagma (Complex a) where\n (rx :+ ix) `plus` (ry :+ iy) = (rx `plus` ry) :+ (ix `plus` iy)\n\n-- | Unital magma for addition.\n--\n-- > zero `plus` a == a\n-- > a `plus` zero == a\nclass AdditiveMagma a =>\n AdditiveUnital a where\n zero :: a\n\ninstance AdditiveUnital Double where\n zero = 0\n\ninstance AdditiveUnital Float where\n zero = 0\n\ninstance AdditiveUnital Int where\n zero = 0\n\ninstance AdditiveUnital Integer where\n zero = 0\n\ninstance AdditiveUnital Bool where\n zero = False\n\ninstance (AdditiveUnital a) => AdditiveUnital (Complex a) where\n zero = zero :+ zero\n\n-- | Associative magma for addition.\n--\n-- > (a `plus` b) `plus` c == a `plus` (b `plus` c)\nclass AdditiveMagma a =>\n AdditiveAssociative a\n\ninstance AdditiveAssociative Double\n\ninstance AdditiveAssociative Float\n\ninstance AdditiveAssociative Int\n\ninstance AdditiveAssociative Integer\n\ninstance AdditiveAssociative Bool\n\ninstance (AdditiveAssociative a) => AdditiveAssociative (Complex a)\n\n-- | Commutative magma for addition.\n--\n-- > a `plus` b == b `plus` a\nclass AdditiveMagma a =>\n AdditiveCommutative a\n\ninstance AdditiveCommutative Double\n\ninstance AdditiveCommutative Float\n\ninstance AdditiveCommutative Int\n\ninstance AdditiveCommutative Integer\n\ninstance AdditiveCommutative Bool\n\ninstance (AdditiveCommutative a) => AdditiveCommutative (Complex a)\n\n-- | Invertible magma for addition.\n--\n-- > \u2200 a \u2208 A: negate a \u2208 A\n--\n-- law is true by construction in Haskell\nclass AdditiveMagma a =>\n AdditiveInvertible a where\n negate :: a -> a\n\ninstance AdditiveInvertible Double where\n negate = P.negate\n\ninstance AdditiveInvertible Float where\n negate = P.negate\n\ninstance AdditiveInvertible Int where\n negate = P.negate\n\ninstance AdditiveInvertible Integer where\n negate = P.negate\n\ninstance AdditiveInvertible Bool where\n negate = P.not\n\ninstance (AdditiveInvertible a) => AdditiveInvertible (Complex a) where\n negate (rx :+ ix) = negate rx :+ negate ix\n\n-- | Idempotent magma for addition.\n--\n-- > a `plus` a == a\nclass AdditiveMagma a =>\n AdditiveIdempotent a\n\ninstance AdditiveIdempotent Bool\n\n-- | sum definition avoiding a clash with the Sum monoid in base\n--\nsum :: (Additive a, P.Foldable f) => f a -> a\nsum = P.foldr (+) zero\n\n-- | Additive is commutative, unital and associative under addition\n--\n-- > zero + a == a\n-- > a + zero == a\n-- > (a + b) + c == a + (b + c)\n-- > a + b == b + a\nclass (AdditiveCommutative a, AdditiveUnital a, AdditiveAssociative a) =>\n Additive a where\n infixl 6 +\n (+) :: a -> a -> a\n a + b = plus a b\n\ninstance Additive Double\n\ninstance Additive Float\n\ninstance Additive Int\n\ninstance Additive Integer\n\ninstance Additive Bool\n\ninstance (Additive a) => Additive (Complex a)\n\n-- | Non-commutative left minus\n--\n-- > negate a `plus` a = zero\nclass (AdditiveUnital a, AdditiveAssociative a, AdditiveInvertible a) =>\n AdditiveLeftCancellative a where\n infixl 6 ~-\n (~-) :: a -> a -> a\n (~-) a b = negate b `plus` a\n\n-- | Non-commutative right minus\n--\n-- > a `plus` negate a = zero\nclass (AdditiveUnital a, AdditiveAssociative a, AdditiveInvertible a) =>\n AdditiveRightCancellative a where\n infixl 6 -~\n (-~) :: a -> a -> a\n (-~) a b = a `plus` negate b\n\n-- | Minus ('-') is reserved for where both the left and right cancellative laws hold. This then implies that the AdditiveGroup is also Abelian.\n--\n-- Syntactic unary negation - substituting \"negate a\" for \"-a\" in code - is hard-coded in the language to assume a Num instance. So, for example, using ''-a = zero - a' for the second rule below doesn't work.\n--\n-- > a - a = zero\n-- > negate a = zero - a\n-- > negate a + a = zero\n-- > a + negate a = zero\nclass (Additive a, AdditiveInvertible a) =>\n AdditiveGroup a where\n infixl 6 -\n (-) :: a -> a -> a\n (-) a b = a `plus` negate b\n\ninstance AdditiveGroup Double\n\ninstance AdditiveGroup Float\n\ninstance AdditiveGroup Int\n\ninstance AdditiveGroup Integer\n\ninstance (AdditiveGroup a) => AdditiveGroup (Complex a)\n", "meta": {"hexsha": "b10a63880b5e3ca5ed7cbd459e1f5e13e5852bec", "size": 5080, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Plankton/Additive.hs", "max_stars_repo_name": "chessai/plankton", "max_stars_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T05:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T05:38:15.000Z", "max_issues_repo_path": "src/Plankton/Additive.hs", "max_issues_repo_name": "chessai/plankton", "max_issues_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "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/Plankton/Additive.hs", "max_forks_repo_name": "chessai/plankton", "max_forks_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6279069767, "max_line_length": 209, "alphanum_fraction": 0.6921259843, "num_tokens": 1497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021788, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5616228310911962}} {"text": "import ActivationFunction\nimport Numeric.LinearAlgebra\n\nmain = do\n let x = (1><2) [1.0, 0.5] :: Matrix R\n y = forward x\n print y\n\nforward x =\n let w1 = (2><3) [0.1, 0.3, 0.5, 0.2, 0.4, 0.6] :: Matrix R\n w2 = (3><2) [0.1, 0.4, 0.2, 0.5, 0.3, 0.6] :: Matrix R\n w3 = (2><2) [0.1, 0.3, 0.2, 0.4] :: Matrix R\n b1 = (1><3) [0.1, 0.2, 0.3] :: Matrix R\n b2 = (1><2) [0.1, 0.2] :: Matrix R\n b3 = (1><2) [0.1, 0,2] :: Matrix R\n a1 = (x <> w1) + b1\n z1 = sigmoid a1\n a2 = (z1 <> w2) + b2\n z2 = sigmoid a2\n a3 = (z2 <> w3) + b3\n in id a3\n", "meta": {"hexsha": "118141b2dad968d2fb51541d435923e3d2beb1a9", "size": 615, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ThreeLayersNeuralNetwork.hs", "max_stars_repo_name": "ku00/deep-learning-practice", "max_stars_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-03T05:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T05:32:58.000Z", "max_issues_repo_path": "src/ThreeLayersNeuralNetwork.hs", "max_issues_repo_name": "ku00/deep-learning-practice", "max_issues_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ThreeLayersNeuralNetwork.hs", "max_forks_repo_name": "ku00/deep-learning-practice", "max_forks_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9545454545, "max_line_length": 62, "alphanum_fraction": 0.4260162602, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.5614270481486303}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Berp.Base.StdTypes.Complex\n-- Copyright : (c) 2010 Bernie Pope\n-- License : BSD-style\n-- Maintainer : florbitous@gmail.com\n-- Stability : experimental\n-- Portability : ghc\n--\n-- The standard floating point type.\n--\n-----------------------------------------------------------------------------\n\nmodule Berp.Base.StdTypes.Complex (complex, complexClass) where\n\nimport Data.Complex (Complex (..), realPart, imagPart)\nimport Berp.Base.Monad (constantIO)\nimport Berp.Base.Prims (primitive, raise)\nimport Berp.Base.SemanticTypes (Object (..), Eval)\nimport Berp.Base.Identity (newIdentity)\nimport Berp.Base.Attributes (mkAttributesList)\nimport Berp.Base.StdNames\nimport Berp.Base.Builtins (notImplementedError)\nimport Berp.Base.Operators\n ( addComplexComplexComplex\n , addComplexIntComplex\n , addComplexFloatComplex\n , subComplexComplexComplex\n , subComplexIntComplex\n , subComplexFloatComplex\n , mulComplexComplexComplex\n , mulComplexIntComplex\n , mulComplexFloatComplex\n , divComplexComplexComplex\n , divComplexIntComplex\n , divComplexFloatComplex\n , eqComplexComplexBool\n , eqComplexIntBool\n , eqComplexFloatBool )\nimport {-# SOURCE #-} Berp.Base.StdTypes.Type (newType)\nimport Berp.Base.StdTypes.ObjectBase (objectBase)\nimport Berp.Base.StdTypes.String (string)\n\n{-# NOINLINE complex #-}\ncomplex :: Complex Double -> Object\ncomplex c = constantIO $ do\n identity <- newIdentity\n return $ Complex { object_identity = identity, object_complex = c }\n\n{-# NOINLINE complexClass #-}\ncomplexClass :: Object\ncomplexClass = constantIO $ do\n dict <- attributes\n newType [string \"complex\", objectBase, dict]\n\nattributes :: IO Object\nattributes = mkAttributesList\n [ (specialAddName, add)\n , (specialSubName, sub)\n , (specialMulName, mul)\n , (specialDivName, divide)\n , (specialEqName, eq)\n , (specialStrName, str)\n ]\n\nmkOp :: (Object -> Object -> Eval Object) ->\n (Object -> Object -> Eval Object) ->\n (Object -> Object -> Eval Object) ->\n Object\nmkOp opComplex opFloat opInt = primitive 2 fun\n where\n fun (x:y:_) =\n case y of\n Complex {} -> opComplex x y\n Float {} -> opFloat x y\n Integer {} -> opInt x y\n _other -> raise notImplementedError\n fun _other = error \"operator on Complex applied to wrong number of arguments\"\n\nadd :: Object\nadd = mkOp addComplexComplexComplex addComplexFloatComplex addComplexIntComplex\n\nsub :: Object\nsub = mkOp subComplexComplexComplex subComplexFloatComplex subComplexIntComplex\n\nmul :: Object\nmul = mkOp mulComplexComplexComplex mulComplexFloatComplex mulComplexIntComplex\n\ndivide :: Object\ndivide = mkOp divComplexComplexComplex divComplexFloatComplex divComplexIntComplex\n\neq :: Object\neq = mkOp eqComplexComplexBool eqComplexFloatBool eqComplexIntBool\n\nstr :: Object\nstr = primitive 1 fun\n where\n fun (x:_) = return $ string $ showComplex x\n fun _other = error \"str method on Complex applied to wrong number of arguments\"\n\nshowComplex :: Object -> String\nshowComplex obj\n | r == 0 = if i < 0 then \"-\" ++ showImg else showImg\n | i < 0 = \"(\" ++ showR ++ \"-\" ++ showImg ++ \")\"\n | otherwise = \"(\" ++ showR ++ \"+\" ++ showImg ++ \")\"\n where\n showImg = showI ++ \"j\"\n showI = showNum $ abs i\n showR = showNum r\n c = object_complex obj\n i = imagPart c\n r = realPart c\n showNum :: Double -> String\n showNum n\n | fracPart == 0 = show intPart\n | otherwise = show n\n where\n (intPart, fracPart) = properFraction n :: (Integer, Double)\n", "meta": {"hexsha": "13efd30326fc1c65487d7fad7b9b7c56b67db7bb", "size": 3618, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "libs/src/Berp/Base/StdTypes/Complex.hs", "max_stars_repo_name": "ppelleti/berp", "max_stars_repo_head_hexsha": "30925288376a6464695341445688be64ac6b2600", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 90, "max_stars_repo_stars_event_min_datetime": "2015-02-03T23:56:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T03:55:32.000Z", "max_issues_repo_path": "libs/src/Berp/Base/StdTypes/Complex.hs", "max_issues_repo_name": "ppelleti/berp", "max_issues_repo_head_hexsha": "30925288376a6464695341445688be64ac6b2600", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-04-01T13:49:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-09T19:28:56.000Z", "max_forks_repo_path": "libs/src/Berp/Base/StdTypes/Complex.hs", "max_forks_repo_name": "bjpop/berp", "max_forks_repo_head_hexsha": "30925288376a6464695341445688be64ac6b2600", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-04-25T03:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-27T06:33:56.000Z", "avg_line_length": 30.4033613445, "max_line_length": 82, "alphanum_fraction": 0.6686014373, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5613717261310216}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule Lib where\n\nimport Control.Monad.Random\nimport Data.Binary as B\nimport Data.Singletons\nimport Data.Singletons.Prelude\nimport Data.Singletons.TypeLits\nimport GHC.Generics (Generic)\nimport GHC.Natural\nimport Numeric.LinearAlgebra.Static\nimport Prelude\n\n{-# ANN module (\"HLint: ignore Eta reduce\" :: Prelude.String) #-}\n{-# ANN module (\"HLint: ignore Redundant lambda\" :: Prelude.String) #-}\n\n------------------------------------------------------------------------------\n--import Test.Hspec\n------------------------------------------------------------------------------\n{-\nhttps://blog.jle.im/entry/practical-dependent-types-in-haskell-2.html\n\nPractical Dependent Types in Haskell 2: Existential Neural Networks and Types at Runtime\nby Justin Le \u2666 Thursday June 30, 2016\n\nusing dependent types to write type-safe neural networks!\n\nPart 1 dealt with types that are fixed at compile-time.\n\nPart 2 types that depend runtime info\n-}\nrandomWeights\n :: (MonadRandom m, KnownNat i, KnownNat o)\n => m (Weights i o)\nrandomWeights = do\n s1 :: Int <- getRandom\n s2 :: Int <- getRandom\n let wB = randomVector s1 Uniform * 2 - 1\n wN = uniformSample s2 (-1) 1\n return $ W wB wN\n\nrunLayer\n :: (KnownNat i, KnownNat o)\n => Weights i o\n -> R i\n -> R o\nrunLayer (W wB wN) v = wB + wN #> v\n\n-- * Network\n--\n\ndata Network :: Nat -> [Nat] -> Nat -> * where\n O :: !(Weights i o)\n -> Network i '[] o\n (:&~) :: KnownNat h\n => !(Weights i h)\n -> !(Network h hs o)\n -> Network i (h ': hs) o\ninfixr 5 :&~\n\nderiving instance (KnownNat i, KnownNat o) => Show (Network i hs o)\n\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n\nrunNet\n :: (KnownNat i, KnownNat o)\n => Network i hs o\n -> R i\n -> R o\nrunNet (O w) !v = logistic (runLayer w v)\nrunNet (w :&~ n') !v = let v' = logistic (runLayer w v)\n in runNet n' v'\n{-\n------------------------------------------------------------------------------\nTypes at Runtime\n\ntype for neural networks:\n\n:k Network\nNetwork :: Nat -> [Nat] -> Nat -> *\n ^ ^ ^\n | | size of the output vector\n | list of hidden layer sizes\n size of input vector\n\nabove requires knowing entire structure of the network at compile-time\n\n------------------------------------------------------------------------------\nAn Existential Crisis\n\ntwo main ways to solve this issue : actually just two styles of doing the same thing.\n\n------------------------------------------------------------------------------\nTypes hiding behind constructors\n\na user only needs to know input and output vectors, so Neural Network is R i -> R o\n\ndownside of having the structure in the type\n- can\u2019t store them in the same list or data structure\n Network 10 '[5,3] 1 and Network 10 '[5,2] 1\n\nIf written without the internal structure in the type then could:\n\ndata OpaqueNet i o\n\nOpaqueNet a useful type for users\n- only exposes types relevant to usage/API\n- can store in list or MVar : [OpaqueNet 10 3] and MVar (OpaqueNet 10 3)\n- serialize/deserialize\n\nOpaqueNet as an \"existential\" wrapper over Network ('hs' is existential)\n-}\ndata OpaqueNet :: Nat -> Nat -> * where\n ONet :: Network i hs o -> OpaqueNet i o\n{-\nGiven Network 6 '[10,6,3] 2\ncan create OpaqueNet 6 2\nWhen using ONet constructor, the structure of the hidden layers disappears from the type.\n\nUse the Network inside by pattern matching on ONet:\n-}\nrunOpaqueNet\n :: (KnownNat i, KnownNat o)\n => OpaqueNet i o\n -> R i\n -> R o\nrunOpaqueNet (ONet n) x = runNet n x\n\nnumHiddens :: OpaqueNet i o -> Int\nnumHiddens (ONet n) = go n\n where\n go :: Network i hs o -> Int\n go = \\case\n O _ -> 0\n _ :&~ n' -> 1 + go n'\n{-\nScopedTypeVariables\n- enables bringing hs back into scope:\n\ncase oN of\n ONet (n :: Network i hs o) -> ...\n\nAbove pattern is sometimes called dependent pair:\n- pattern matching on ONet yields the hidden existentially quantified type : hs\n and also a value whose type is based on it (Network i hs o)\n- like hs \u201cpaired\u201d with Network i hs o\n\nPattern match on the results to give both the type 'hs' and the data structure.\n\n(could have implemented it as ONet :: Sing hs -> Network i hs o -> OpaqueNet i o)\n\nkey to making this work\n- after pattern matching on ONet, must handle 'hs' in a completely polymorphic way\n- cannot assume anything about 'hs'\n\ne.g., not ok:\n\nbad :: OpaqueNet i o -> Network i hs o\nbad (ONet n) = n\n\nbecause the type signature means the caller can decide what 'hs' can be.\nbut the function has a specific 'hs' : the network that ONet hides.\nThe caller must accommodate whatever is inside ONet.\n\n------------------------------------------------------------------------------\nThe Universal and the Existential\n\ncentral to using existential types\n- who has the power to decide what the types will be instantiated as\n\nMost polymorphic functions in Haskell are \"universally qualified\", e.g.,\n\n map :: (a -> b) -> [a] -> [b]\n\nthe caller of map decides what a and b are\n\nmap is defined such that it will work for any a and b that the caller chooses\n\nBut for\n\nfoo :: [Int] -> OpaqueNet i o\n\ncaller of 'foo' chooses i and o\n'foo' implementation chooses 'hs'\nTo use what 'foo' returns, must being able to handle anything 'foo'returns.\n\nsummary:\n\nuniversal : caller chooses\n function\u2019s implementation must accommodate any choice\n\nexistential : function\u2019s implementation chooses\n caller must accommodate any choice\n\nearlier showed to Network i hs o inside the OpaqueNet i o\nmust deal with it in a parametrically polymorphic way (i.e., handle any 'hs')\n\n------------------------------------------------------------------------------\nA familiar friend\n\nOpaqueNet i o is a \"dependent pair\"\n- pairs 'hs' with 'Network i hs o'\n\nanother common term : DEPENDENT SUM\n\n\"sum types\" are Either-like types that can be one thing or another.\n\nDependent pairs/existential types actually are similar to Either/sum types\n\nworking with existential types is no different than working with Either\n\nGiven:\n\nfoo :: String -> Either Int Bool\n\nthen must handle the result for both cases.\n- the function gets to pick which\n\n(can view OpaqueNet i o as being an infinite Either over '[], '[1], '[1,2], ...)\n\nhandle Either via pattern matching\nOpaqueNet i o is the same\n- do not know the type of Network i hs o until pattern matching (a \"dependent pattern match\")\n\n------------------------------------------------------------------------------\nREIFICATION\n\nre-write randomNet with explicit singleton input style\n-}\nrandomNet'\n :: forall m i hs o. (MonadRandom m, KnownNat i, KnownNat o)\n => Sing hs -> m (Network i hs o)\nrandomNet' = \\case\n SNil -> O <$> randomWeights\n SNat `SCons` ss -> (:&~) <$> randomWeights <*> randomNet' ss\n\nrandomNet\n :: forall m i hs o. (MonadRandom m, KnownNat i, SingI hs, KnownNat o)\n => m (Network i hs o)\nrandomNet = randomNet' sing\n{-\nuse sing :: SingI hs => Sing hs to call the Sing hs ->-style function\nfrom the SingI hs => one\n\nstill need to get the list of integers to the type level\n- to create a Network i hs o\n- to put into ONet\n\nUse 'SomeSing' (a lot like OpaqueNet)\n- wrapping the Sing a inside an existential data constructor\n- toSing\n - takes term-level value (here [Integer])\n - returns 'SomeSing' wrapping the type-level value (here [Nat])\n- pattern match on SomeSing constructor brings 'a' into scope\n\nSomeSing implementation:\n\ndata SomeSing :: * -> * where\n SomeSing :: Sing (a :: k) -> SomeSing k\n\nso,\n\nfoo :: SomeSing Bool\nfoo = SomeSing STrue\n\nbar :: SomeSing Nat\nbar = SomeSing (SNat :: Sing 10)\n-}\n\nmSing :: IO ()\nmSing = do\n putStrLn \"How many cats do you own?\"\n c <- readLn :: IO Natural\n case toSing c of SomeSing sc -> print (fromSing sc + 2)\n\nxIn :: Int -> SomeSing Nat\nxIn = toSing . intToNatural\n\nxOut :: SomeSing Nat -> Int\nxOut = \\case SomeSing n -> naturalToInt (fromSing n)\n\nxio :: Int -> Int\nxio = xOut . xIn\n{-\ninside the case statement branch the type n :: Nat is in scope.\npattern matching on the SNat constructor gives a KnownNat n instance\n\ntoSing can convert value x of type a to a singleton representing type x with kind a\n\nCan use this to write randomONet:\n-}\nrandomONet\n :: (MonadRandom m, KnownNat i, KnownNat o)\n => [Natural]\n -> m (OpaqueNet i o)\nrandomONet hs = case toSing hs of\n SomeSing ss -> ONet <$> randomNet' ss\n{-\nconverting term-level value to type level type known as reification\n\noriginal goal is now within reach:\n-}\nmain :: IO ()\nmain = do\n putStrLn \"What hidden layer structure do you want?\"\n hs <- readLn\n n <- randomONet hs\n case n of\n ONet (net :: Network 10 hs 3) ->\n print net\n -- more stuff with dynamically generated net\n{-\n------------------------------------------------------------------------------\nThe Boundary\n\nexistentially quantified types (e.g., SomeSing),\nenables ability to work with types that depend on runtime results\n\ntoSing and SomeSing is a BOUNDARY between untyped world and typed world\nreification : cleanly separates the two\n\nReification boundary similar to boundary between pure code and impure (IO, etc.) code.\n\nworking with typed/untyped worlds as the same thing\n- write as as possible in typed world\n- write only what absolutely must be in untyped world\n (e.g., values from runtime environment)\n\n------------------------------------------------------------------------------\nContinuation-Based Existentials\n\nanother way to work with existentials that can be more natural to use\n\nwhen pattern matching on existential, must work with ANY values in constructor\n\noNetToFoo :: OpaqueNet i o -> Foo\noNetToFoo (ONet n) = f n\n\nf take 'Network i hs o' and work for all 'hs'\n\ncould skip the constructor and represent an existential type\nas something taking the continuation f and giving it what it needs\n-}\n\ntype OpaqueNet' i o r = (forall hs. Network i hs o -> r) -> r\n\n{-\n\"Tell me how you would make an r\n- given a 'Network i hs o' that works for any 'hs'\n- then I will make it for you\u201d\n\nUses Rank-N types\n\nUsing above is similar to using constructor-style:\n-}\nrunOpaqueNet'\n :: (KnownNat i, KnownNat o)\n => OpaqueNet' i o (R o)\n -> R i\n -> R o\nrunOpaqueNet' oN x = oN (`runNet` x)\n-- :: ((forall hs. Network i hs o -> R o) -> R o)\n-- -> R i\n-- -> R o\n\nnumHiddens' :: OpaqueNet' i o Int -> Int\nnumHiddens' oN = oN go\n where\n go :: Network i hs o -> Int\n go = \\case\n O _ -> 0\n _ :&~ n' -> 1 + go n'\n-- :: ((forall hs. Network i hs o -> Int) -> Int)\n-- -> Int\n{-\nAbove \"continuation transformation\" formally known as skolemization\n\nwrap\n-}\n\noNet' :: Network i hs o -> OpaqueNet' i o r\noNet' n = \\f -> f n\n\n-- randomONet that returns a continuation-style existential:\n\nwithRandomONet'0\n :: (MonadRandom m, KnownNat i, KnownNat o)\n => [Natural]\n -> (forall hs. Network i hs o -> m r)\n -> m r\n-- aka\n-- => [Integer]\n-- -> OpaqueNet' i o (m r)\nwithRandomONet'0 hs f = case toSing hs of\n SomeSing ss -> do\n net <- randomNet' ss\n f net\n{-\n-- version of `toSing` that returns a skolemized `SomeSing`\nwithSomeSing :: [Integer]\n -> (forall (hs :: [Nat]). Sing hs -> r)\n -> r\n-}\n\nwithRandomONet'\n :: (MonadRandom m, KnownNat i, KnownNat o)\n => [Natural]\n -> (forall hs. Network i hs o -> m r)\n -> m r\n--aka,\n-- => [Integer]\n-- -> OpaqueNet' i o (m r)\nwithRandomONet' hs f = withSomeSing hs $ \\ss -> do\n net <- randomNet' ss\n f net\n\nmain' :: IO ()\nmain' = do\n putStrLn \"What hidden layer structure do you want?\"\n hs <- readLn\n withRandomONet' hs $ \\(net :: Network 10 hs 3) ->\n print net\n -- blah blah stuff with our dynamically generated net\n{-\nJust like the case statement pattern match represented the lexical boundary\nbetween the untyped and typed world when using constructor-style existentials,\nthe ... $ \\net -> ... is also a BOUNDARY for continuation-style existentials.\n\n------------------------------------------------------------------------------\nA Tale of Two Styles\n\ntwo equivalent ways representing/working with existential types\ncan always convert between them\n\nwhich one to use or offer can make a difference in code clarity\n\nPROS/CONS\n\ncontinuation-style\n- does not require a data type/constructor\n - can use newtypes, but they force users to learn those types/constructors\n for each existential type returned\n - if there are many existentials, then that means a lot of un/wrapping\n- easier to use when functions return existentials\n - especially if intended to immediately use them\n - saves an extraneous pattern match\n- when using several existentials at once, continuation-style is better\n because each nested existential doesn\u2019t force another level of indentation:\n\nfoo = withSomeSing x $ \\sx ->\n withSomeSing y $ \\sy ->\n withSomeSing z $ \\sz ->\n -- ...\nvs.\n\nfoo = case toSing x of\n SomeSing sx ->\n case toSing y of\n SomeSing sy ->\n case toSing z of\n SomeSing sz ->\n -- ...\nIn monadic context, use do notation and ScopedTypeVariables for a non-nested style\n\nmain = do\n ONet n1 <- randomONet [7,5,3] :: IO (OpaqueNet 10 1)\n ONet n2 <- randomONet [5,5,5] :: IO (OpaqueNet 10 1)\n ONet n3 <- randomONet [5,4,3] :: IO (OpaqueNet 10 1)\n hs <- readLn\n ONet (n4 :: Network 10 hs 1) <- randomONet hs\n -- ...\n\nnicer than\n\nmain = withRandomONet' [7,5,3] $ \\n1 ->\n withRandomONet' [5,5,5] $ \\n2 ->\n withRandomONet' [5,4,3] $ \\n3 -> do\n hs <- readLn\n withRandomONet' hs $ \\(n4 :: Network 10 hs 1) -> do\n -- ...\ntrick less useful for functions like toSing where things are not returned in a monad\nYou could wrap it in Identity, but that\u2019s kind of silly:\n\nfoo = runIdentity $ do\n SomeSing sx <- Identity $ toSing x\n SomeSing sy <- Identity $ toSing y\n SomeSing sz <- Identity $ toSing z\n return $ -- ...\n\nConstructor-style\n- necessary for writing typeclass instances\n - i.e., cannowrite a Show instance for (forall hs. Network i hs o -> r) -> r\n but can write one for OpaqueNet i o\n - i.e., Binary de/serialization instances\n\nHaskell does not support using Rank-N types as arguments to type constructors,\nso [OpaqueNet i o] is possible,\nbut not [OpaqueNet' i o r] or [(forall hs. Network i hs o -> r) -> r]\n\nMVar (OpaqueNet i o) is OK\nbut not MVar ((forall hs. Network i hs o -> r) -> r)\n\n(latter are known as impredicative types)\n\nIf the type constructor is a Monad, you can use ContT-style skolemization,\nlike (forall hs. Network i hs o -> [r]) -> [r] and (forall hs. Network i hs o -> IO r) -> IO r.\nBut doesn\u2019t work for MVar and other useful type constructors.\n\nWhen writing functions that take existentials as inputs,\nthe constructor-style is arguably more natural. But barely.\n\nFor example, we wrote a function to find the number of hidden layers in a network earlier:\n\nnumHiddens :: OpaqueNet i o -> Int\n\nBut the continuation-style version has a slightly messier type:\n\nnumHiddens' :: ((forall hs. Network i hs o -> Int) -> Int)\n -> Int\n\nEven with with the type synonym, it\u2019s still a little awkward:\n\nnumHiddens' :: OpaqueNet' i o Int -> Int\n\nThis is why you\u2019ll encounter many more functions returning continuation-style existentials\nin libraries than taking them, for the most part.\n\n------------------------------------------------------------------------------\nSerializing Networks\n\napply existential types and reification to serialization\n\n------------------------------------------------------------------------------\nRecap on the Binary Library\n\nSerializing networks whose sizes are statically in\ntheir types \u2014 is straightforward --- an advantages of having sizes in types\n\nbinary library : typeclass-based de/serializing\n\nmonads (Get, Put) for describing serialization schemes and also a\ntypeclass used to provide serialization instructions for different\ntypes.\n\nusually do not write instances\nuse GHC generics:\n-}\ndata Weights i o = W\n { wBiases :: !(R o)\n , wNodes :: !(L o i)\n } deriving (Show, Generic)\n\ninstance (KnownNat i, KnownNat o) => Binary (Weights i o)\n{-\ngives get and put:\n\nget :: (KnownNat i, KnownNat o) => Get (Weights i o)\nput :: (KnownNat i, KnownNat o) => Weights i o -> Put\nHowever, for GADTs like Network, we have to things manually.\n\n------------------------------------------------------------------------------\nSerializing Network\n-}\nputNet :: (KnownNat i, KnownNat o) => Network i hs o -> Put\nputNet = \\case\n O w -> put w\n w :&~ n -> put w *> putNet n\n{-\nUsually a flag is needed to tell what constructor is being serialized,\nso the deserializer can know what constructor to deserialize.\nBut need needed for Network because it is known know how many :&~ layers to expect\nvia the type: deserializing Network 5 '[10,6,3] 2 means three (:&~)\u2019s and one O.\n-}\ngetNet :: forall i hs o. (KnownNat i, KnownNat o) => Sing hs -> Get (Network i hs o)\ngetNet = \\case\n SNil -> O <$> get\n SNat `SCons` ss -> (:&~) <$> get <*> getNet ss\n{-\ngetNet similar to randomNet': pattern match on 'hs' to get constructors\nand ollow what the singleton\u2019s structure says.\n\na Network Binary instance : cannot have get take a Sing hs input\n- change the arity/type of the function\n- switch to SingI-style and have their Binary instances require a SingI hs constraint.\n-}\ninstance (KnownNat i, SingI hs, KnownNat o) => Binary (Network i hs o) where\n put = putNet\n get = getNet sing\n{-\n------------------------------------------------------------------------------\nSerializating OpaqueNet\n\nto de/serialize, must know complete structure\n\nthe complete structure is not in the type\n- need to encode it as a flag so deserializer will which constructors\n-}\nhiddenStruct :: Network i hs o -> [Natural]\nhiddenStruct = \\case\n O _ -> []\n _ :&~ (n' :: Network h hs' o) -> natVal (Proxy @h) : hiddenStruct n'\n\n{-\nnatVal :: KnownNat n => Proxy n -> Natural\nreturns the value-level Natural corresponding to type-level n :: Nat\n\nnatVal and hiddenStruct : turn type-level infor ('n', 'hs') into term-level values\n\ninverse of reification functions (like toSing)\n\nREFECTION: type level to the value level\n-}\nputONet :: (KnownNat i, KnownNat o) => OpaqueNet i o -> Put\nputONet (ONet net) = do\n put (hiddenStruct net) -- put the structure (as a binary flag)\n putNet net -- then put the network itself\n\n-- deserialize: load the list of Integers and reify it\ngetONet :: (KnownNat i, KnownNat o) => Get (OpaqueNet i o)\ngetONet = do\n hs <- get -- load flag\n withSomeSing hs -- reify it\n (fmap ONet . getNet) -- create it\n\ninstance (KnownNat i, KnownNat o) => Binary (OpaqueNet i o) where\n put = putONet\n get = getONet\n{-\nused constructor-style existential (instead of continuation-style)\nbecause typeclass instances for the latter are not possible\n\n------------------------------------------------------------------------------\nAn Existence For All\n\nlearned\n- reification : untyped world to typed world to create tyypes depend on runtime values\n- reflection : de/serialization shows type safety in dynamic context\n\n------------------------------------------------------------------------------\nExercises\n\n1. Implement putONet' and getONet' using continuation-style existentials\nhttps://github.com/mstksg/inCode/tree/master/code-samples/dependent-haskell/NetworkTyped2.hs#L188-L193\nhttps://github.com/mstksg/inCode/tree/master/code-samples/dependent-haskell/NetworkTyped2.hs#L195-L203\n\n2. Work with an existential wrapper over the entire network structure (inputs and outputs, too):\n\ndata SomeNet where\n SNet :: (KnownNat i, KnownNat o)\n => Network i hs o\n -> SomeNet\n\n(Need KnownNat because of type erasure, to recover original input/output dimensions\nback on pattern matching)\n\nAnd write:\n\n- A function to convert SomeNets to OpaqueNets.\n Return OpaqueNet with existentially quantified i and o in continuation-style.\n (Also try a data type to return it in constructor-style)\nhttps://github.com/mstksg/inCode/tree/master/code-samples/dependent-haskell/NetworkTyped2.hs#L231-L234\n\n- randomSNet, returning m SomeNet.\nhttps://github.com/mstksg/inCode/tree/master/code-samples/dependent-haskell/NetworkTyped2.hs#L236-L245\n\nWhile you\u2019re at it, write it to return a random continuation-style SomeNet, too! (See the type of withRandomONet' for reference on how to write the type)\n\nThe binary instance for SomeNet.\n\nHint: Remember natVal :: KnownNat n => Proxy n -> Integer!\n\nHint: Remember that toSomeSing also works for Integers, to get Sings for Nats, too!\n\nA bit of a stretch, because the set of all [Nat]s is non-enumerable and uncountable, but hopefully you get the picture!\u21a9\ufe0e\n\nRecall that I recommend (personally, and subjectively) a style where your external API functions and typeclass instances are implemented in SingI a => style, and your internal ones in Sing a -> style. This lets all of your internal functions fit together more nicely (Sing a -> style tends to be easier to write in, especially if you stay in it the entire time, because Sings are normal first-class values, unlike those global and magical typeclasses) while at the same time removing the burden of calling with explicit singletons from people using the functionality externally.\u21a9\ufe0e\n\nIn older versions of singletons, before GHC 8 and TypeInType, we had to implement it using \u201ckind proxies\u201d. Don\u2019t worry if you\u2019re following along in 7.10; the basic usage of SomeSing is essentially identical either way.\u21a9\ufe0e\n\nSkolemization is probably one of the coolest words you\u2019ll encounter when learning/using Haskell, and sometimes just knowing that you\u2019re \u201cskolemizing\u201d something makes you feel cooler. Thank you Thoralf Skolem. If you ever see a \u201crigid, skolem\u201d error in GHC, you can thank him for that too! He is also the inspiration behind my decision to name my first-born son Thoralf. (My second son\u2019s name will be Curry)\u21a9\ufe0e\n\nIt even lets you write Storable instances!\u21a9\ufe0e\n-}\n", "meta": {"hexsha": "319de36a972304bf6fb3fee7d2e8806f7a62de4b", "size": 22551, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/topic/existentials/2016-06-justin-le-practical-dependent-types-in-haskell-existential-neural-networks-and-types-at-runtime/src/Lib.hs", "max_stars_repo_name": "haroldcarr/learn-haskell-coq-ml-etc", "max_stars_repo_head_hexsha": "3dc7abca7ad868316bb08f31c77fbba0d3910225", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2015-01-29T14:37:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-30T06:55:03.000Z", "max_issues_repo_path": "haskell/topic/existentials/2016-06-justin-le-practical-dependent-types-in-haskell-existential-neural-networks-and-types-at-runtime/src/Lib.hs", "max_issues_repo_name": "haroldcarr/learn-haskell-coq-ml-etc", "max_issues_repo_head_hexsha": "3dc7abca7ad868316bb08f31c77fbba0d3910225", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "haskell/topic/existentials/2016-06-justin-le-practical-dependent-types-in-haskell-existential-neural-networks-and-types-at-runtime/src/Lib.hs", "max_forks_repo_name": "haroldcarr/learn-haskell-coq-ml-etc", "max_forks_repo_head_hexsha": "3dc7abca7ad868316bb08f31c77fbba0d3910225", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-04-13T21:40:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:58:10.000Z", "avg_line_length": 32.3543758967, "max_line_length": 580, "alphanum_fraction": 0.6472440247, "num_tokens": 5737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5612892572535234}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n{-|\nModule : Math\nDescription : Auxiliary math functions\nCopyright : (c) Julian Kopka Larsen, 2015\nStability : experimental\n\nDefinition of math functions like 'scatterMatrix' and the multivariate log Gamma function 'mlgamma'\n-}\n{-# LANGUAGE TypeSynonymInstances #-}\nmodule Math (\n X,\n dimension,\n Sstat,\n add_means,\n sub_means,\n add_scatter,\n sub_scatter,\n fromX,\n AbelianGroup((<+>), (<->)),\n mlgamma,\n scatterMatrix,\n scatterMatrixAlt,\n mean,\n meanv,\n lnDeterminant\n) where\n\nimport Numeric.LinearAlgebra (Matrix, Vector, trans, (<>), fromRows, dim, meanCov, invlndet, outer, konst, scale)\nimport Numeric.LinearAlgebra.Data (size)\nimport Debug.Trace\nimport Data.List ((\\\\))\nimport Partition (group)\n\nqtr x = trace (\"value: \" ++ show x) x\n\n-- | Class for the\nclass AbelianGroup a where\n (<+>) :: a -> a -> a\n (<->) :: a -> a -> a\n\n-- | Type synonym for data objects that can be anything as long as it is compatible with the likelihood\n-- could be extended to a type class with sufficient statistics member functions.\ntype X = [Vector Double]\n\n-- | Computes the scatter matrix defined as:\nscatterMatrixAlt :: X -> Matrix Double\nscatterMatrixAlt x = sum $ map (\\v -> outer (v-xm) (v-xm)) x\n where xm = meanv x\n\nscatterMatrix :: X -> Matrix Double\nscatterMatrix x = sum (map (\\ v -> outer v v) x) - scale n (outer xm xm)\n where xm = meanv x\n n = fromIntegral $ length x\n\n-- | Mean of a dataset\nmean :: [Vector Double] -> Matrix Double\nmean x = fromRows [meanv x]\n\nmeanv :: [Vector Double] -> Vector Double\nmeanv x = scale (1/(fromIntegral $ length x))(sum x)\n\ndimension :: [Vector Double] -> Int\ndimension = dim . head\n\ntype Sstat = (Int, Matrix Double, Vector Double)\n\nfromX :: X -> Sstat\nfromX x = (length x, scatterMatrix x, meanv x)\n\ninstance AbelianGroup Sstat where\n s <+> (0,_,_) = s\n (n1, s1, m1) <+> (n2, s2, m2) = (n1+n2, add_scatter n1 s1 m1 n2 s2 m2 , add_means n1 m1 n2 m2)\n s <-> (0,_,_) = s\n (n1, s1, m1) <-> (n2, s2, m2) = (n1-n2, sub_scatter n1 s1 m1 n2 s2 m2, sub_means n1 m1 n2 m2)\n\ninstance (AbelianGroup a) => AbelianGroup [a] where\n x <+> y = map (\\(a,b) -> a <+> b) $ zip x y\n x <-> y = map (\\(a,b) -> a <-> b) $ zip x y\n\nadd_means :: Int -> Vector Double -> Int -> Vector Double -> Vector Double\nadd_means _ m1 0 _ = m1\nadd_means 0 _ _ m2 = m2\nadd_means i1 m1 i2 m2 = scale w1 m1 + scale w2 m2\n where n1 = fromIntegral i1\n n2 = fromIntegral i2\n w1 = (n1/(n1+n2))\n w2 = (n2/(n1+n2))\n\nsub_means :: Int -> Vector Double -> Int -> Vector Double -> Vector Double\nsub_means _ m1 0 _ = m1\nsub_means i1 _ i2 _ | i1==i2 = meanv []\nsub_means i1 m1 i2 m2 = scale w1 m1 - scale w2 m2\n where n1 = fromIntegral i1\n n2 = fromIntegral i2\n w1 = (n1/(n1-n2))\n w2 = (n2/(n1-n2))\n\nadd_scatter :: Int -> Matrix Double -> Vector Double -> Int -> Matrix Double -> Vector Double -> Matrix Double\nadd_scatter _ sa _ 0 _ _ = sa\nadd_scatter 0 _ _ _ sb _ = sb\nadd_scatter ia sa ma ib sb mb = sa + sb + (scale na xaa) + (scale nb xbb) - (scale n xx)\n where na = fromIntegral ia\n nb = fromIntegral ib\n xaa = outer ma ma\n xbb = outer mb mb\n mx = add_means ia ma ib mb\n xx = outer mx mx\n n = na + nb\n\nsub_scatter :: Int -> Matrix Double -> Vector Double -> Int -> Matrix Double -> Vector Double -> Matrix Double\nsub_scatter 0 _ _ n _ _ = error \"Nothing to subtract from.\"\nsub_scatter _ sa _ 0 _ _ = sa\nsub_scatter ia sa ma ib sb mb | ia==ib = scatterMatrix [ma]\nsub_scatter ia sa ma ib sb mb | ia-ib==1 = konst 0 (size sa)\nsub_scatter ia sa ma ib sb mb = sa - sb + (scale na xaa) - (scale nb xbb) - (scale n xx)\n where na = fromIntegral ia\n nb = fromIntegral ib\n xaa = outer ma ma\n xbb = outer mb mb\n mx = sub_means ia ma ib mb\n xx = outer mx mx\n n = na - nb\n\n\nlnDeterminant :: Matrix Double -> Double\nlnDeterminant x = absLnDet * signDet\n where (_,(absLnDet,signDet)) = invlndet x\n\n\ncofG :: [Double]\ncofG = [76.18009172947146,-86.50532032941677,24.01409824083091,-1.231739572450155,0.001208650973866179,-0.000005395239384953]\n\nserG :: Double\nserG = 1.000000000190015\n\nlgamma :: Double -> Double\nlgamma xx = let tmp' = (xx+5.5) - (xx+0.5)*log(xx+5.5)\n ser' = serG + (sum $ zipWith (/) cofG [xx+1..])\n in -tmp' + log(2.5066282746310005 * ser' / xx)\n\nmlgamma :: Double -> Double -> Double\nmlgamma p a = (log pi)*(p*(p-1)/4) + sum (map (\\j -> lgamma (a + ((1-j)/2))) [1..p])\n\n", "meta": {"hexsha": "08b0e75aa053197b9270a188633a26ca3312d4f7", "size": 4731, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "GMM/src/Math.hs", "max_stars_repo_name": "juliankopkalarsen/FpStats", "max_stars_repo_head_hexsha": "2a9d1cdec7cc9621da2cc7c9972fbf85a1d2f683", "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": "GMM/src/Math.hs", "max_issues_repo_name": "juliankopkalarsen/FpStats", "max_issues_repo_head_hexsha": "2a9d1cdec7cc9621da2cc7c9972fbf85a1d2f683", "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": "GMM/src/Math.hs", "max_forks_repo_name": "juliankopkalarsen/FpStats", "max_forks_repo_head_hexsha": "2a9d1cdec7cc9621da2cc7c9972fbf85a1d2f683", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6275862069, "max_line_length": 125, "alphanum_fraction": 0.5994504333, "num_tokens": 1500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095497, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5612892527361704}} {"text": "{-# LANGUAGE Strict #-}\nmodule Pinwheel.Asterisk where\n\nimport Data.Complex\n\n{-# INLINE asteriskGaussianFunc #-}\nasteriskGaussianFunc ::\n (RealFloat e) => e -> e -> Int -> e -> e -> e -> Complex e\nasteriskGaussianFunc phi rho n a b period =\n (0 :+ (-1)) ^ n *\n exp\n ((-1) *\n (((fromIntegral n ^ 2) / (4 * b) + (pi * rho) ^ 2 / (a * period ^ 2)) :+\n (fromIntegral n * phi)))\n\n", "meta": {"hexsha": "8de8c444420ca6266fc065a7d71526f3c84fd52f", "size": 393, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Pinwheel/Asterisk.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Pinwheel/Asterisk.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/Pinwheel/Asterisk.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": 24.5625, "max_line_length": 77, "alphanum_fraction": 0.5547073791, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5612284056368299}} {"text": "module Raycast (intersect, findHits, raycast) where\n\nimport Control.Monad (guard)\nimport Data.Maybe (isJust, fromJust, listToMaybe)\nimport Types\nimport Ray (createHit)\nimport Numeric.Vector\nimport Numeric.Scalar\n\n-- https://courses.cs.washington.edu/courses/csep557/10au/lectures/triangle_intersection.pdf\nintersect :: Ray -> Object -> Tri -> Maybe RayHit\nintersect ray@(Ray pos dir) obj tri = do\n let a = v_getPos $ t_getP0 tri\n b = v_getPos $ t_getP1 tri\n c = v_getPos $ t_getP2 tri\n n = normalized $ (b - a) \u00d7 (c - a)\n d = n \u00b7 a\n t = (d - n \u00b7 pos) / (n \u00b7 dir)\n q = pos + dir * (fromScalar t)\n\n areaQAB = ((b - a) \u00d7 (q - a)) \u00b7 n\n areaQBC = ((c - b) \u00d7 (q - b)) \u00b7 n\n areaQCA = ((a - c) \u00d7 (q - c)) \u00b7 n\n areaABC = ((b - a) \u00d7 (c - a)) \u00b7 n\n \n guard $ areaQAB >= 0\n guard $ areaQBC >= 0\n guard $ areaQCA >= 0\n guard $ t > 0\n -- Only counts as a hit if the ray is traveling towards the front of the triangle\n -- (when direction and normal are closer to antiparallel)\n guard $ (dir \u00b7 n) < 0\n\n let alpha = unScalar $ areaQBC / areaABC\n beta = unScalar $ areaQCA / areaABC\n gamma = unScalar $ areaQAB / areaABC\n\n let hitPos = pos + dir * (fromScalar t)\n\n return $ createHit obj tri ray (unScalar t) (alpha, beta, gamma) hitPos\n \nfindHits :: Scene -> Ray -> [RayHit]\nfindHits s ray = let objs = s_getObjects s\n intersections = concatMap (\\o -> map (intersect ray o) $ o_getTris o) objs\n -- It's safe to use `fromJust` here because the filter guarantees all values are `Just`\n in map fromJust $ filter isJust intersections\n\nminimumBy :: (Ord b) => (a -> b) -> [a] -> a\nminimumBy f xs = foldr1 (\\m x -> if f x < f m then x else m) xs\n\nraycast :: Scene -> Ray -> Maybe RayHit\nraycast s ray@(Ray origin _) = let hs = findHits s ray\n in if length hs == 0 then Nothing\n else Just $ minimumBy rh_getDistance hs\n", "meta": {"hexsha": "63ad6de5dfac595f088fdd327055c2333d001aaf", "size": 2054, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Raycast.hs", "max_stars_repo_name": "craigmc08/haskell-raytracer", "max_stars_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Raycast.hs", "max_issues_repo_name": "craigmc08/haskell-raytracer", "max_issues_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Raycast.hs", "max_forks_repo_name": "craigmc08/haskell-raytracer", "max_forks_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3454545455, "max_line_length": 104, "alphanum_fraction": 0.5730282376, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5611671189019427}} {"text": "module Square where\n\nimport Genetics\nimport qualified Neural\nimport Utilities\nimport qualified Numeric.LinearAlgebra\n ( cmap )\nimport Numeric.LinearAlgebra\n ( (<>)\n , (><)\n )\nimport System.Random\n\nnewtype Phenotype = Network Double\n\ntrainingSet :: TrainingSet\ntrainingSet = [ ((1><3)[1, 1, 1], (6><1)[1, 1, 1, 0, 1, 1])\n , ((1><3)[0, 0, 1], (6><1)[0, 0, 0, 0, 0, 1])\n , ((1><3)[0, 1, 0], (6><1)[0, 0, 0, 1, 0, 0])\n , ((1><3)[0, 1, 1], (6><1)[0, 0, 1, 0, 0, 1])\n , ((1><3)[1, 0, 0], (6><1)[0, 1, 0, 0, 0, 0])\n ]\n\nrandompopulation :: IO [Genotype]\nrandompopulation = do\n g <- getStdGen\n return $ map Neural.flatten $ take 10 $ randomNetworks g [3, 6]\n\nmorphogenesis :: Genotype -> Phenotype\nmorphogenesis g = Neural.fromList [3, 6]\n\nfit :: Genotype -> Double\nfit = (fitness trainingSet) . morphogenesis\n\n-- Iterates fitness and selection on a population, where the\n-- selection function uses randomness.\niterations :: RandomGen g => g -> Population -> [Population]\niterations g population = \n map fst $ iterate (mySelection fit) (population, g)\n\nmaximums :: [Population] -> [Double]\nmaximums populations = map maximum $ (map.map) fit $ populations\n\n-- example to see how well we are doing\nexample :: IO [Double]\nexample = do\n g <- newStdGen\n population <- randompopulation\n return $ maximums (iterations g population)\n\nfitness :: Neural.TrainingSet -> Neural.Network -> Double\nfitness training network =\n let xs = map fst training\n ys = concat (map (Neural.toList . Neural.flatten . snd) training)\n actual = concat (map (Neural.toList . Neural.flatten . (Neural.forward network)) xs)\n differences = zipWith (-) ys actual\n in (-1) * sqrt (sum (map (^2) differences))\n", "meta": {"hexsha": "b265bd617c505c45ed008189614ebf1543a58f99", "size": 1786, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Square.hs", "max_stars_repo_name": "dbeecham/NeuralFourInARow", "max_stars_repo_head_hexsha": "3dd9d2979eaf5a2494cf128beff9e1dc6f405688", "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/Square.hs", "max_issues_repo_name": "dbeecham/NeuralFourInARow", "max_issues_repo_head_hexsha": "3dd9d2979eaf5a2494cf128beff9e1dc6f405688", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Square.hs", "max_forks_repo_name": "dbeecham/NeuralFourInARow", "max_forks_repo_head_hexsha": "3dd9d2979eaf5a2494cf128beff9e1dc6f405688", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7931034483, "max_line_length": 92, "alphanum_fraction": 0.6198208287, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5611671142706498}} {"text": "module Main where\n\nimport Control.Monad.Par\nimport Data.Monoid ( (<>) )\nimport Types\nimport qualified Text.Printf as Printf\nimport Graphics.Gloss\nimport Graphics.Gloss.Data.Color\nimport Graphics.Gloss.Data.ViewPort\nimport qualified Numeric.LinearAlgebra as LinAlg\n\n\nwindowSize :: (Int, Int)\nwindowSize = (1200, 800)\n\nfps :: Int\nfps = 10\n\ndata Model = Model\n { earth :: Point\n , earthSpeed :: LinAlg.Vector Float\n , jupiter :: Point\n , jupiterSpeed :: LinAlg.Vector Float\n } deriving (Show, Eq)\n\nearthPosString :: Model -> String\nearthPosString m =\n Printf.printf \"earth (%.1f, %.1f)\" (fst . earth $ m) (snd . earth $ m)\n\njupiterPosString :: Model -> String\njupiterPosString m =\n Printf.printf \"jupiter (%.1f, %.1f)\" (fst . jupiter $ m) (snd . jupiter $ m)\n\ninitialModel = Model\n { earth = (-200, 0)\n , earthSpeed = LinAlg.fromList [0, 20]\n , jupiter = (0, 0)\n , jupiterSpeed = LinAlg.fromList [0, 0]\n }\n\nmain :: IO ()\nmain = simulate (InWindow \"Newtons Planets\" windowSize (200, 500))\n black\n fps\n initialModel\n drawModel\n stepFunction\n\nradiusScaleFactor :: Integer -> Float\nradiusScaleFactor diameter = fromIntegral diameter / distanceScale\n\nearthRadius :: Float\nearthRadius = radiusScaleFactor . diameter $ Earth\n\njupiterRadius :: Float\njupiterRadius = radiusScaleFactor . diameter $ Jupiter\n\ndrawModel :: Model -> Picture\ndrawModel model =\n let earth' = color blue (circle earthRadius)\n jupiter' = color cyan (circle jupiterRadius)\n (earthX , earthY ) = earth model\n (jupiterX, jupiterY) = jupiter model\n earthPos = translate earthX earthY earth'\n jupiterPos = translate jupiterX jupiterY jupiter'\n in earthPos <> jupiterPos <> modelInfo (earthPosString model) (-580) (-350) <>\n modelInfo (jupiterPosString model) (-580) (-300)\n\nmodelInfo :: String -> Integer -> Integer -> Picture\nmodelInfo text a b =\n let text' = Text text\n scaled = scale 0.1 0.1 text'\n moved = translate (fromIntegral a) (fromIntegral b) scaled\n in color red moved\n\nstepFunction :: ViewPort -> Float -> Model -> Model\nstepFunction vp secs model =\n let earthPoint = earth model\n jupiterPoint = jupiter model\n earthSpeed' = earthSpeed model\n jupiterSpeed' = jupiterSpeed model\n (earthPulled, jupiterPulled) = runPar $ do\n p1 <- spawnP $ pullOn Earth earthPoint Jupiter jupiterPoint\n p2 <- spawnP $ pullOn Jupiter jupiterPoint Earth earthPoint\n p1' <- get p1\n p2' <- get p2\n return (p1', p2')\n\n in Model\n { earth = newPoint earthPoint earthSpeed'\n , earthSpeed = alterSpeed earthSpeed' earthPulled\n , jupiter = newPoint jupiterPoint jupiterSpeed'\n , jupiterSpeed = alterSpeed jupiterSpeed' jupiterPulled\n }\n\n", "meta": {"hexsha": "287a2e499e6bf67492f6de886a3a6db33446052e", "size": 3009, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "mariatsji/planets", "max_stars_repo_head_hexsha": "6ca1272ef18817359c4e30495e61c30599adaa45", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "mariatsji/planets", "max_issues_repo_head_hexsha": "6ca1272ef18817359c4e30495e61c30599adaa45", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "mariatsji/planets", "max_forks_repo_head_hexsha": "6ca1272ef18817359c4e30495e61c30599adaa45", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.34375, "max_line_length": 81, "alphanum_fraction": 0.6224659355, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.561167110838834}} {"text": "module Isumi.Math.FFT.Internal.Utils\n ( realToComplex\n , virtToComplex\n , vecFromValues\n , compI\n , findM\n , isSorted\n ) where\n\nimport Data.Complex\nimport Data.Foldable (traverse_)\nimport qualified Data.Vector.Generic as GV\nimport qualified Data.Vector.Generic.Mutable as MGV\n\nrealToComplex :: (Real a, Fractional b) => a -> Complex b\nrealToComplex x = realToFrac x :+ 0\n\nvirtToComplex :: (Real a, Fractional b) => a -> Complex b\nvirtToComplex y = 0 :+ realToFrac y\n\nvecFromValues :: (Traversable t, GV.Vector v a)\n => t (Int, a) -> v a\nvecFromValues xs = GV.create $ do\n v <- MGV.new ((1+) . maximum . fmap fst $ xs)\n traverse_ (uncurry (MGV.write v)) xs\n pure v\n\ncompI :: Fractional b => Complex b\ncompI = virtToComplex (1 :: Int)\n\nfindM :: Monad m => (a -> m Bool) -> [a] -> m (Maybe a)\nfindM _ [] = pure Nothing\nfindM p (x:xs) = do\n b <- p x\n if b then pure $ Just x\n else findM p xs\n\n-- |Determine whether a list is sorted strictly.\nisSorted :: Ord a\n => Bool -- ^ ascending if True, descending if False\n -> [a]\n -> Bool\nisSorted _ [] = True\nisSorted _ [_] = True\nisSorted asc (x:y:zs) =\n (if asc then x < y else x > y) && isSorted asc zs\n\n", "meta": {"hexsha": "dc55a8fd26e3750d36fba5b04f321fa9e5b425f7", "size": 1243, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/lib/Isumi/Math/FFT/Internal/Utils.hs", "max_stars_repo_name": "IsumiF/fft-bruun", "max_stars_repo_head_hexsha": "93920f47a67f091d0451edcf32fd6032aceb2845", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-18T06:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-18T06:45:22.000Z", "max_issues_repo_path": "src/lib/Isumi/Math/FFT/Internal/Utils.hs", "max_issues_repo_name": "IsumiF/fft-bruun", "max_issues_repo_head_hexsha": "93920f47a67f091d0451edcf32fd6032aceb2845", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/Isumi/Math/FFT/Internal/Utils.hs", "max_forks_repo_name": "IsumiF/fft-bruun", "max_forks_repo_head_hexsha": "93920f47a67f091d0451edcf32fd6032aceb2845", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8958333333, "max_line_length": 60, "alphanum_fraction": 0.6114239743, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5611059128254184}} {"text": "{-# LANGUAGE TemplateHaskell #-}\n\nmodule School.Unit.Test.WeightDecay\n( weightDecayTest ) where\n\nimport Conduit(Identity, liftIO)\nimport Numeric.LinearAlgebra ((><))\nimport School.TestUtils (diffCost, randomMatrix)\nimport School.Types.FloatEq ((~=))\nimport School.Types.Slinky (Slinky(..))\nimport School.Unit.CostFunction (CostFunction(..))\nimport School.Unit.UnitActivation (UnitActivation(..))\nimport School.Unit.UnitGradient (UnitGradient(..))\nimport School.Unit.WeightDecay\nimport School.Utils.LinearAlgebra (compareDoubleMatrix)\nimport Test.Tasty (TestTree)\nimport Test.Tasty.QuickCheck hiding ((><))\nimport Test.Tasty.TH\nimport Test.QuickCheck.Monadic (monadicIO, assert, pre)\n\neps :: Double\neps = 1e-5\n\nprec :: Double\nprec = 5e-2\n\nweight :: Double -> CostFunction Double Identity\nweight coeff = weightDecay coeff\n\nprop_coeff_zero :: (Positive Int) -> (Positive Int) -> Property\nprop_coeff_zero (Positive bSize) (Positive fSize) = monadicIO $ do\n inputMat <- liftIO $ randomMatrix bSize fSize\n let input = BatchActivation inputMat\n let cost = computeCost (weight 0) input SNil\n either (const (assert False))\n (\\result -> assert $ result ~= 0)\n cost\n\nprop_numerical_deriv :: (Positive Int) -> (Positive Int) -> Double -> Property\nprop_numerical_deriv (Positive bSize) (Positive fSize) coeff = monadicIO $ do\n pre $ bSize < 23 && fSize < 23\n inputMat <- liftIO $ randomMatrix bSize fSize\n let input = BatchActivation inputMat\n let costFunc = weight coeff\n let deriv = derivCost costFunc input SNil\n let check = (bSize >< fSize) [ diffCost costFunc\n input\n eps\n (j, k)\n SNil\n | j <- [0..bSize-1], k <- [0..fSize-1] ]\n either (const (assert False))\n (\\(BatchGradient g) -> assert $ compareDoubleMatrix prec g check)\n deriv\n\nweightDecayTest :: TestTree\nweightDecayTest = $(testGroupGenerator)\n", "meta": {"hexsha": "a9350b89544b600fbcc3a40e7cf6190dea09fd74", "size": 2031, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/School/Unit/Test/WeightDecay.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/School/Unit/Test/WeightDecay.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/School/Unit/Test/WeightDecay.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0172413793, "max_line_length": 78, "alphanum_fraction": 0.655342196, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.5610286592665108}} {"text": "module Types\n(Data (..),\n plus,\n divide,\n multiply,\n generateBasedOf,\n isEmpty,\n hadamardV,\n hadamardM,\n sigV,\n sigV'\n) where\n\nimport Numeric.LinearAlgebra.HMatrix\n\n-- Construtor do Data\ndata Data = Data {\n wHidden :: Matrix R,\n bHidden :: Vector Double,\n aHidden :: Vector Double,\n zetaHidden :: Vector Double,\n wOutput :: Matrix R,\n bOutput :: Vector Double,\n aOutput :: Vector Double,\n zetaOutput :: Vector Double\n } deriving (Eq, Show)\n\n-- Efetua soma entre os respectivos vetores e matrizes de ambos os Datas\nplus :: Data -> Data -> Data\nplus (Data wH1 bH1 aH1 zH1 wO1 bO1 aO1 zO1) (Data wH2 bH2 aH2 zH2 wO2 bO2 a02 z02) = \n (Data (add wH1 wH2) (add bH1 bH2) aH1 zH1 (add wO1 wO2) (add bO1 bO2) aO1 zO1)\n\n-- Efetua divisao por esacalar entre os respectivos vetores e matrizes do Data\ndivide :: Data -> Double -> Data\ndivide (Data wH bH aH zH wO bO aO zO) constant = (Data (scale (1/constant) wH) (scale (1/constant) bH) aH zH (scale (1/constant) wO) (scale (1/constant) bO) aO zO)\n\n-- Efetua multiplicacao por scalar entre os respectivos vetores e matrizes do Data\nmultiply :: Data -> Double -> Data\nmultiply (Data wH bH aH zH wO bO aO zO) constant = (Data (scale constant wH) (scale constant bH) aH zH (scale constant wO) (scale constant bO) aO zO)\n\n-- Efetua hadamard entre dois vetores\nhadamardV :: (Num a) => [a] -> [a] -> [a]\nhadamardV list1 list2 = zipWith (*) list1 list2\n\n-- Efetua hadamard entre duas matrizes\nhadamardM :: (Num a) => [[a]] -> [[a]] -> [[a]]\nhadamardM matrix1 matrix2 = zipWith hadamardV matrix1 matrix2\n\n-- Computa a funcao sigmoid daquele valor\nsig :: Double -> Double\nsig x = 1.0 - (1.0 + exp(-x))\n\n-- Computa a derivada da funcao sigmoid daquele valor\nsig' :: Double -> Double\nsig' x = sig x * (1 - sig x) \n\n-- Computa a funcao sigmoid para cada elemento de uma lista\nsigV :: [Double] -> [Double]\nsigV l = [sig x | x <- l]\n\n-- Computa a derivada da funcao sigmoid para cada elemento de uma lista\nsigV' :: [Double] -> [Double]\nsigV' l = [sig' x | x <- l]\n\n-- Cria um data repleto de valores 0.0 com as mesmas dimensoes do modelo passado por parametro\ngenerateBasedOf :: Data -> Data\ngenerateBasedOf (Data wH bH aH zH wO bO aO zO) = let whRows = fst $ size wH\n whColumns = snd $ size wH\n bhLen = size bH\n ahLen = size aH\n zhLen = size zH\n woRows = fst $ size wO\n woColumns = snd $ size wO\n boLen = size bO\n aoLen = size aH\n zoLen = size zH\n \n newWH = (whRows> Bool\nisEmpty (Data wH bH aH zH wO bO aO zO) = \n (null (toList $ flatten wH)) || (null $ toList bH) || (null (toList $ flatten wO)) || (null $ toList bO)", "meta": {"hexsha": "0785acd737a3bdfc320d4d64c9d88a5340b068d1", "size": 4168, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Haskell/src/Types.hs", "max_stars_repo_name": "Thulio-Carvalho/NedeReural_Haskell", "max_stars_repo_head_hexsha": "6469552ba35358aa0ffb85d36e7fe2bdd8fad477", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Haskell/src/Types.hs", "max_issues_repo_name": "Thulio-Carvalho/NedeReural_Haskell", "max_issues_repo_head_hexsha": "6469552ba35358aa0ffb85d36e7fe2bdd8fad477", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Haskell/src/Types.hs", "max_forks_repo_name": "Thulio-Carvalho/NedeReural_Haskell", "max_forks_repo_head_hexsha": "6469552ba35358aa0ffb85d36e7fe2bdd8fad477", "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": 45.8021978022, "max_line_length": 163, "alphanum_fraction": 0.5011996161, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5609680691766329}} {"text": "{-# LANGUAGE NoMonomorphismRestriction,\n ScopedTypeVariables\n #-}\n\n\nmodule PFP where\n\nimport Debug.Trace\n\nimport Data.Traversable\nimport Control.Applicative\nimport Control.Monad\n\nimport Control.Monad.Random\nimport Control.Monad.State\nimport Control.Monad.Fix\n\nimport Numeric.SpecFunctions -- From cabal install spec-functions\n\n--import Rec\nimport SplitEval\nimport Mem\n\nbernoulli :: (Functor m, MonadRandom m) => Double -> m Bool\nbernoulli p = (< p) <$> getRandom\n\n-- From Alexey Radul's HSVenture\nbeta :: (MonadRandom m) => Double -> Double -> m Double\nbeta alpha beta = do\n -- Adapted from Statistics.Distribution.Beta; not reused because of\n -- funny randomness management convention.\n x <- getRandomR (0.0,1.0)\n return $ quantile x\n where\n quantile x | x == 0 = 0\n | x == 1 = 1\n | 0 < x && x < 1 = invIncompleteBeta alpha beta x\n | otherwise = error $ \"x must be in the range [0,1], got: \" ++ show x\n\n-- Makes a CRP sampler given the concentration parameter alpha via stick breaking.\nmakeCRP ::\n (RandomGen g, Functor m, MonadSplit g m, Functor f, MonadRandom f) =>\n Double -> m (f Int)\nmakeCRP alpha = do\n -- This is probably our only choice for this type\n -- without adding Proxy arguments. Oh well.\n let breakStick :: (RandomGen g) => Rand g Double\n breakStick = beta 1 alpha\n \n sticks <- repeatS breakStick\n \n let choose (p:ps) = do\n b <- bernoulli p\n if b\n then return 0\n else (1 +) <$> choose ps\n \n return $ choose sticks\n\n-- This type was inferred by ghc, so should be the most general.\ndpmem ::\n (MonadEval g n, MonadRandom f, MonadSplit g m, RandomGen g,\n Applicative n, Functor f, Functor m) =>\n Double -> n a -> m (f a)\ndpmem alpha sampler = do\n crp <- makeCRP alpha\n tables <- memIntS (const sampler)\n return $ tables <$> crp\n\ndpMemInt :: forall a g n m f.\n (MonadEval g n, MonadRandom f, MonadSplit g m, RandomGen g,\n Applicative n, Functor f, Functor m) =>\n Double -> (Int -> n a) -> m (Int -> f a)\ndpMemInt alpha f = memIntS f'\n where -- This type needs to have both (MonadSplit g m) for dpmem\n -- and (MonadEval g n) for memIntS\n f' :: Int -> Rand g (f a)\n f' = (dpmem alpha) . f\n\n\ndpBernoulli = dpmem 1.0 $ (bernoulli 0.5 :: (RandomGen g) => Rand g Bool)\n\nrandomWalkRec ::\n (Functor m, MonadRandom m) => Double -> (Int -> m Int) -> Int -> m Int\nrandomWalkRec _ _ 0 = return 0\nrandomWalkRec p f n = do\n x <- f (n-1)\n b <- bernoulli p\n let dx = if b then 1 else -1\n return $ x + dx\n\nrandomWalk\n :: (MonadSplit g m, RandomGen g, MonadFix m, Functor m) =>\n Double -> m (Int -> Int)\nrandomWalk p = mfix $ memIntS . f\n where f :: RandomGen g => (Int -> Int) -> (Int -> Rand g Int)\n f = (randomWalkRec p) . (return .)\n\ndpRandomWalk :: forall g n m f.\n (MonadEval g n, MonadRandom n, MonadSplit g m, RandomGen g,\n Applicative n, MonadFix m, Functor m) =>\n Double -> Double -> m (Int -> n Int)\ndpRandomWalk alpha p = mfix $ (dpMemInt alpha) . (randomWalkRec p)\n\ndpRandomWalkIO alpha p = (evalRandIO .) <$> dpRandomWalk alpha p\n\n\n", "meta": {"hexsha": "8ebe4a2bab994cc6efedbbd05a4c6bc7cf61cf7a", "size": 3135, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "PFP/PFP.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": "PFP/PFP.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": "PFP/PFP.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": 29.0277777778, "max_line_length": 86, "alphanum_fraction": 0.6341307815, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.560455575304477}} {"text": "{-# LANGUAGE TemplateHaskell #-}\n\nimport Test.QuickCheck\nimport System.Exit\nimport Data.Complex as C\nimport FFT\n\n-- Helpers\n\nallClose :: (Ord a, Fractional a) => [a] -> [a] -> Bool\nallClose xs ys = and $ fmap (\\diff -> diff < 1e-4) diffs\n where\n diffs = [abs $ x - y | (x,y) <- zip xs ys]\n\nallCloseComplex :: (RealFloat a) => [Complex a] -> [Complex a] -> Bool\nallCloseComplex xs ys = and $ fmap (\\diff -> diff < 1e-4) diffs\n where\n diffs = [C.magnitude $ x - y | (x,y) <- zip xs ys]\n\n-- Properties\n\nprop_dftInverse :: [Complex Double] -> Bool\nprop_dftInverse xs = allCloseComplex xs $ idft (dft xs)\n\nprop_rdftInverse :: [Double] -> Bool\nprop_rdftInverse xs = allClose xs $ irdft (rdft xs)\n\nprop_fftInverse :: [Complex Double] -> Bool\nprop_fftInverse xs = allCloseComplex xs $ ifft (fft xs)\n\nprop_rfftInverse :: [Double] -> Bool\nprop_rfftInverse xs = allClose xs $ irfft (rfft xs)\n\nprop_fft :: [Complex Double] -> Bool\nprop_fft xs = allCloseComplex (fft xs) (dft xs)\n\nprop_rfft :: [Double] -> Bool\nprop_rfft xs = allCloseComplex (rfft xs) (rdft xs)\n\n-- https://hackage.haskell.org/package/QuickCheck-2.13.2/docs/Test-QuickCheck-All.html\nreturn []\nrunTests :: IO Bool\nrunTests = $quickCheckAll\n\nmain :: IO ()\nmain = do\n success <- and <$> sequence [runTests]\n if success then exitSuccess else exitFailure\n", "meta": {"hexsha": "b62a38fc7843ea26d3f50e9c96eefed6a0c71ebb", "size": 1314, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Spec.hs", "max_stars_repo_name": "viswanathgs/haskell-fft", "max_stars_repo_head_hexsha": "a62272da68db2c8c3174fb2db966fba47d1e7bfb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Spec.hs", "max_issues_repo_name": "viswanathgs/haskell-fft", "max_issues_repo_head_hexsha": "a62272da68db2c8c3174fb2db966fba47d1e7bfb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Spec.hs", "max_forks_repo_name": "viswanathgs/haskell-fft", "max_forks_repo_head_hexsha": "a62272da68db2c8c3174fb2db966fba47d1e7bfb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8163265306, "max_line_length": 86, "alphanum_fraction": 0.6803652968, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5602055325474466}} {"text": "{-|\nModule: MachineLearning.Optimization.MinibatchGradientDescent\nDescription: Gradient Descent\nCopyright: (c) Alexander Ignatyev, 2017\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n\nMinibatch Gradient Descent\n-}\n\nmodule MachineLearning.Optimization.MinibatchGradientDescent\n(\n minibatchGradientDescent\n)\n\nwhere\n\nimport MachineLearning.Types (R, Vector, Matrix)\nimport MachineLearning.Regularization (Regularization)\nimport qualified Data.Vector.Storable as V\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra ((?))\nimport qualified Control.Monad.Random as RndM\n\nimport qualified MachineLearning.Model as Model\n\n-- | Minibatch Gradient Descent method implementation. See \"MachineLearning.Regression\" for usage details.\nminibatchGradientDescent :: Model.Model a\n => Int -- ^ seed\n -> Int -- ^ batch size\n -> R -- ^ learning rate, alpha\n -> a -- ^ model to learn\n -> R -- ^ epsilon\n -> Int -- ^ max number of iters\n -> Regularization -- ^ regularization parameter, lambda\n -> Matrix -- ^ matrix of features, X\n -> Vector -- ^ output vector, y\n -> Vector -- ^ vector of initial weights, theta or w\n -> (Vector, Matrix) -- ^ vector of weights and learning path \nminibatchGradientDescent seed batchSize alpha model eps maxIters lambda x y theta =\n RndM.evalRand (minibatchGradientDescentM batchSize alpha model eps maxIters lambda x y theta) gen\n where gen = RndM.mkStdGen seed\n\n\n-- | Minibatch Gradient Descent method implementation. See \"MachineLearning.Regression\" for usage details.\nminibatchGradientDescentM :: (Model.Model a, RndM.RandomGen g)\n => Int -- ^ batch size\n -> R -- ^ learning rate, alpha\n -> a -- ^ model to learn\n -> R -- ^ epsilon\n -> Int -- ^ max number of iters\n -> Regularization -- ^ regularization parameter, lambda\n -> Matrix -- ^ matrix of features, X\n -> Vector -- ^ output vector, y\n -> Vector -- ^ vector of initial weights, theta or w\n -> RndM.Rand g (Vector, Matrix) -- ^ vector of weights and learning path \nminibatchGradientDescentM batchSize alpha model eps maxIters lambda x y theta = do\n idxList <- RndM.getRandomRs (0, (LA.rows x) - 1)\n let gradient = Model.gradient model lambda\n cost = Model.cost model lambda\n helper theta nIters optPath =\n let idx = take batchSize idxList\n x' = x ? idx\n y' = LA.flatten $ (LA.asColumn y) ? idx\n theta' = theta - (LA.scale alpha (gradient x' y' theta))\n j = cost x' y' theta'\n gradientTest = LA.norm_2 (theta' - theta) < eps\n optPathRow = V.concat [LA.vector [(fromIntegral $ maxIters - nIters), j], theta']\n optPath' = optPathRow : optPath\n in if gradientTest || nIters <= 1\n then (theta, LA.fromRows $ reverse optPath')\n else helper theta' (nIters - 1) optPath'\n return $ helper theta maxIters []\n\n", "meta": {"hexsha": "8c32a36ad3df6d75bafeedfda674bbf23590b839", "size": 3651, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/Optimization/MinibatchGradientDescent.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "src/MachineLearning/Optimization/MinibatchGradientDescent.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "src/MachineLearning/Optimization/MinibatchGradientDescent.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 48.0394736842, "max_line_length": 106, "alphanum_fraction": 0.5403998904, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5601674922487648}} {"text": "module KAB where\n\nimport Control.Applicative\nimport Control.Monad\nimport Statistics.Distribution (genContVar)\nimport Statistics.Distribution.Normal (normalDistr)\nimport Statistics.Distribution.Uniform (uniformDistr)\nimport System.Random.MWC (withSystemRandom, GenIO)\n\ntestComp = \".\"\n\nnormalDist = normalDistr 0 1\nuniformDist = uniformDistr 0 1\n\nnumActions = 10\n\nrunLength = 10000\n\nalpha = 0.1\nepsilon = 0.1\n\nvalueBias = 0.0\n\ntype ActionMeans = [Double]\n\nsampleNormal :: IO Double\nsampleNormal = withSystemRandom (genContVar normalDist :: (GenIO -> IO Double))\n\nactionMeans :: IO ActionMeans\nactionMeans = replicateM numActions sampleNormal\n\nsampleValue :: Double -> IO Double\nsampleValue v = fmap (+ v) sampleNormal\n\nsampleNonstationaryStep :: IO Double\nsampleNonstationaryStep = fmap (/ 100) sampleNormal\n\nstepValues :: [Double] -> IO [Double]\nstepValues values = sequenceA $ fmap takeStep values\n where\n takeStep val = do\n step <- sampleNonstationaryStep\n return $ val + step\n\n\n--progress :: [Double] -> Int -> IO (Double, [Double])\n--progress values move = (,) <$> (sampleValue $ values !! move) <*> (stepActions values <$> (replicateM numActions sampleNonstationaryStep))\n\ntype SampleAverageStats = [(Double, Int)]\n\ntype AlphaValEstimates = [Double]\n\ngetReward :: ActionMeans -> Int -> IO Double\ngetReward means actionNum = \n if (length means <= actionNum)\n then error $ \"getReward: index \" ++ (show actionNum) ++\" is too large for list of length \" ++ (show $ length means)\n else ((+) (means !! actionNum)) <$> sampleNormal\n\nobserveSA :: SampleAverageStats -> Int -> Double -> SampleAverageStats\nobserveSA oldStats actionNum latestSample =\n if (length oldStats <= actionNum)\n then error $ \"action number \" ++ (show actionNum) ++ \" does not exist in the list \" ++ (show oldStats)\n else let (avg, count) = (oldStats !! actionNum) in take actionNum oldStats ++ ((avg + ((latestSample - avg) / (fromIntegral $ count + 1)), count + 1) : (drop (actionNum + 1) oldStats))\n\nobserveAlp :: AlphaValEstimates -> Int -> Double -> AlphaValEstimates\nobserveAlp oldStats actionNum latestSample =\n if (length oldStats <= actionNum)\n then error $ \"observeAlp does not contain index \" ++ (show actionNum)\n else let oldAvg = (oldStats !! actionNum) in take actionNum oldStats ++ (oldAvg + (alpha * (latestSample - oldAvg)) : (drop (actionNum + 1) oldStats))\n\nargmax :: Ord b => (a -> b) -> [a] -> a\nargmax f (a:as) = go a (f a) as\n where\n go amx _ [] = amx\n go amx maxSoFar (b:bs) = if (f b > maxSoFar)\n then go b (f b) bs\n else go amx maxSoFar bs\n\nactGreedySA :: SampleAverageStats -> Int\nactGreedySA stats = argmax (saValue stats) [0 .. (length stats - 1)]\n\nactGreedyAlpha :: AlphaValEstimates -> Int\nactGreedyAlpha stats = argmax ((!!) stats) [0 .. (length stats - 1)]\n\nactEpsilonGreedy :: Int -> IO Int\nactEpsilonGreedy greedyChoice = do\n randomSample <- withSystemRandom (genContVar uniformDist :: (GenIO -> IO Double))\n if (randomSample <= epsilon)\n then randomAction\n else return greedyChoice\n\nrandomAction :: IO Int\nrandomAction = do\n randomSample <- withSystemRandom (genContVar uniformDist :: (GenIO -> IO Double))\n return $ floor $ randomSample * (fromIntegral numActions)\n\n\nsaValue :: SampleAverageStats -> Int -> Double\nsaValue stats actionNum =\n if (length stats <= actionNum)\n then error \"saValue index too large\"\n else fst $ stats !! actionNum\n\ninitialValsAlp :: AlphaValEstimates\ninitialValsAlp = take numActions $ repeat valueBias\n\ninitialValsSA :: SampleAverageStats\ninitialValsSA = take numActions $ repeat (valueBias, 0)\n\ninitializeScenario :: IO (AlphaValEstimates, SampleAverageStats, ActionMeans)\ninitializeScenario = (,,) initialValsAlp initialValsSA <$> actionMeans\n\nrunScenario :: IO [[Double]]\nrunScenario = go runLength initialValsAlp initialValsSA =<< actionMeans\n where\n go :: Int -> AlphaValEstimates -> SampleAverageStats -> ActionMeans -> IO [[Double]]\n go 0 _ _ _ = return []\n go n alphaEsts averageEsts means = do\n --putStrLn $ \"Time Remaining: \" ++ (show n)\n\n alphaAction <- actEpsilonGreedy $ actGreedyAlpha alphaEsts\n alphaReward <- getReward means alphaAction\n\n saAction <- actEpsilonGreedy $ actGreedySA averageEsts\n saReward <- getReward means saAction\n\n newMeans <- stepValues means\n\n ((:) [alphaReward, saReward]) <$> (go (n - 1) (observeAlp alphaEsts alphaAction alphaReward) (observeSA averageEsts saAction saReward) newMeans)\n\naverage :: [[Double]] -> [Double]\naverage nums = fmap (flip (/) (fromIntegral $ length nums)) $ foldr (zipWith (+)) (head nums) (tail nums)\n\nreportPerformance :: IO [Double]\nreportPerformance = fmap average runScenario\n\nf 0 = 0\nf n = nextDown + alpha * (1 - nextDown)\n where\n nextDown = f (n - 1)", "meta": {"hexsha": "e5a7591b509174d6e7484ef9cabf7c50d85a01b1", "size": 4773, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/KAB.hs", "max_stars_repo_name": "Daedalus359/k-arm-bandits", "max_stars_repo_head_hexsha": "268d78acde27a8dce289b961125b198b4b7df920", "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/KAB.hs", "max_issues_repo_name": "Daedalus359/k-arm-bandits", "max_issues_repo_head_hexsha": "268d78acde27a8dce289b961125b198b4b7df920", "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/KAB.hs", "max_forks_repo_name": "Daedalus359/k-arm-bandits", "max_forks_repo_head_hexsha": "268d78acde27a8dce289b961125b198b4b7df920", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0928571429, "max_line_length": 188, "alphanum_fraction": 0.7062644039, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256353465629, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5601596552120363}} {"text": "{-# LANGUAGE ViewPatterns, NoMonomorphismRestriction, FlexibleInstances #-}\nmodule Math.Probably.LinearPDF where\n\nimport qualified Math.Probably.Student as S\nimport Numeric.LinearAlgebra\n\ntype PDF a = a->Double\n\ninstance Show (a->Double) where\n show f = error \"Math.Prob.PDF: showing function\" \n\ninstance Eq (a->Double) where\n f == g = error \"Math.Prob.PDF: comparing functions!\"\n\ninstance Num a => Num (a->Double) where\n f + g = \\x-> f x + g x\n f * g = \\x-> f x * g x\n f - g = \\x-> f x - g x\n abs f = \\x -> abs (f x)\n signum f = \\x-> signum $ f x\n fromInteger = error $ \"Math.Prob.PDF: frominteger on function\"\n\nuniform :: (Real a, Fractional a) => a-> a-> PDF a\nuniform from to = \\x-> if x>=from && x <=to\n then realToFrac $ 1/(to-from )\n else 0\n\n--http://en.wikipedia.org/wiki/Normal_distribution\ngauss :: (Real a, Floating a) => a-> a-> PDF a\ngauss mean sd = \\x->realToFrac $ recip(sd*sqrt(2*pi))*exp(-(x-mean)**2/(2*sd*sd))\n\ngaussD :: Double -> Double-> PDF Double\ngaussD mean sd = \\x->recip(sd*sqrt(2*pi))*exp(-(x-mean)**2/(2*sd*sd))\n\ngammafun = exp . S.gammaln\n\n--http://en.wikipedia.org/wiki/Gamma_distribution\ngammaD :: Double -> Double -> PDF Double\ngammaD k theta x = x**(k-1)*(exp(-x/theta)/(theta**k*(exp (S.gammaln k))))\n\ninvGammaD :: Double -> Double -> PDF Double\ninvGammaD a b x =(b**a/gammafun a)*(1/x)**(a+1)*exp(-b/x)\n\nlogNormal m sd x = recip (x*sd*sqrt(2*pi)) * exp (negate $ square (log x - m) / (2*square sd))\n where square x = x*x\n\nbeta a b x = (recip $ S.beta a b) * x ** (a-1) * (1-x) ** (b-1)\n{-# SPECIALIZE gauss :: Double -> Double-> PDF Double #-}\n\n--this is a Prob. Mass function, not density.\nbinomial :: Int -> Double -> PDF Int\nbinomial n p k = realToFrac (choose (toInteger n) (toInteger k)) * p^^k * (1-p)^^(n-k)\n\n\nzipPdfs :: Num a => PDF a -> PDF b -> PDF (a,b)\nzipPdfs fx fy (x,y) = fx x * fy y\n\nmulPdf :: Num a => PDF a -> PDF a -> PDF a\nmulPdf d1 d2 = \\x -> (d1 x * d2 x)\n\n--instance Num a => Num (PDF a) where\n \n--http://blog.plover.com/math/choose.html\nchoose :: Integer -> Integer -> Integer\nchoose n 0 = 1\nchoose 0 k = 0\nchoose (n) (k) | k > n `div` 2 = choose n (n-k)\n | otherwise = (choose (n-1) (k-1)) * (n) `div` (k)\n\n\n\nmultiNormal :: Vector Double -> Matrix Double -> PDF (Vector Double)\nmultiNormal mu sigma = \n let k = realToFrac $ dim mu\n invSigma = inv sigma\n mat1 = head . head . toLists\n in \\x-> recip ((2*pi)**(k/2) * sqrt(det sigma)) * exp (mat1 $ negate $ 0.5*(asRow $ x-mu) `multiply` invSigma `multiply` (asColumn $ x-mu) ) \n\nmu1 = 2 |> [0, 0::Double]\nsig1 = (2><2)[1::Double, 0,\n 0, 1]\n\ntst = multiNormal mu1 sig1 mu1\ntsta = inv sig1\ntstb = det sig1\ntstc = let mu = mu1\n sigma = sig1 \n x = mu1\n invSigma = inv sigma\n in (asRow $ x-mu) `multiply` invSigma `multiply` (asColumn $ x-mu) ", "meta": {"hexsha": "2f94e6635c3328967072e81290a7c0a1ff34ee8b", "size": 2914, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/Probably/LinearPDF.hs", "max_stars_repo_name": "glutamate/probably", "max_stars_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-28T03:19:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:44.000Z", "max_issues_repo_path": "Math/Probably/LinearPDF.hs", "max_issues_repo_name": "glutamate/probably", "max_issues_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/Probably/LinearPDF.hs", "max_forks_repo_name": "glutamate/probably", "max_forks_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3777777778, "max_line_length": 143, "alphanum_fraction": 0.5840768703, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5599652065459111}} {"text": "-- \n-- \n-- \n\n-- \n-- Indexless linear algebra algorithms\n-- \n-- \n-- \n--
    \n--
    \n--

    \n-- ***\n--

    \n--

    \n-- Indexless linear algebra algorithms\n--

    \n-- \n--
    \n-- Orthogonalization, linear equations, eigenvalues and eigenvectors\n--
    \n-- Literate Haskell module Orthogonals.lhs\n--
    \n--

    \n-- Jan Skibinski, \n-- Numeric Quest Inc., Huntsville, Ontario, Canada\n--

    \n-- 1998.09.19, last modified 1998.12.28\n--

    \n--
    \n--

    \n-- It has been argued that the functional paradigm offers more\n-- support for scientific computing than the traditional imperative\n-- programming, such as greater similarity of functional implementation\n-- to mathematical specification of a problem. However, efficiency\n-- of scientific algorithms implemented in Haskell is very low compared\n-- to efficiencies of C or Fortran implementations - notwithstanding\n-- the exceptional descriptive power of Haskell.\n--

    \n-- It has been also argued that tradition and inertia are partially\n-- responsible for this sore state and that many functional algorithms\n-- are direct translations of their imperative counterparts.\n--
    \n-- Arrays - with their indexing schemes and destructive updating\n-- are basic tools of imperative programming. But pure functional\n-- languages, which prohibit variable reassignments, cannot compete\n-- with imperative languages by using the same tools and following\n-- similar reasoning and patterns - unless the functional arrays\n-- themselves are designed with performance in mind. This is\n-- a case with Clean, where efficiency of one kind of their arrays\n-- -- strict unboxed array, approaches efficiency of C.\n--
    \n-- But this has not been done for Haskell arrays yet. They are\n-- lazy, boxed and use auxiliary association lists (index, value)\n-- for initialization -- the latter being mostly responsible for\n-- low efficiency of those algorithms that create many interim\n-- arrays.\n--
    \n-- It appears, that -- as long as indexing scheme is not used\n-- for lookups and updates -- Haskell lists are more efficient\n-- than arrays -- at least at the currents state of Haskell.\n--

    \n-- With this in mind, we are attempting to demonstrate here\n-- that the indexing traps can be successfully avoided.\n-- This module implements afresh several typical problems from linear\n-- algebra. Standard Haskell lists are employed instead of arrays\n-- and not a single algorithm ever uses indices for lookups\n-- or updates.\n--

    \n-- We do not claim high efficiency of these algorithms; consider\n-- them exploratory. However, we do claim that the clarity of\n-- these algorithms is significantly better than of those functionally\n-- similar algorithms that employ indexing schemes.\n--

    \n-- Two major algorithms have been invented and implemented in Haskell:\n-- one for solving systems of linear equations and one for finding\n-- eigenvalues and eigenvectors of almost any type of a square matrix.\n-- This includes symmetric, hermitian, general complex or nonsymmetric\n-- matrices with real eigenvalues.\n--

    \n-- Amazingly, both methods are based on the same factorization, akin\n-- to QR method, but not exactly the same as the standard QR one.\n-- A simple trick allows to extend this method to nonsymmetric real\n-- matrices with complex eigenvalues and thus one method applies to\n-- all types of matrices.\n-- It follows that the eigenvalue/eigenvector problem can be consistently\n-- treated all across the board. In addition, no administrative\n-- (housekeeping) boring trivia is required here and that helps to\n-- clearly explain the mechanisms employed.\n\n-- \n--

    \n--


    \n--

    \n-- \n-- Contents\n-- \n--

    \n--

      \n--

    • \n-- Notation\n--

    • \n-- Scalar products and vector normalization\n--
        \n--
      • \n-- bra_ket, scalar product\n--
      • \n-- sum_product, a cousin of bra_ket\n--
      • \n-- norm, vector norm\n--
      • \n-- normalized, vector normalized to one\n--
      \n--

    • \n-- Transposition and adjoining of matrices\n--
        \n--
      • \n-- transposed, transposed matrix\n--
      • \n-- adjoint, transposed and conjugated matrix\n--
      \n--

    • \n-- Products involving matrices\n--
        \n--
      • \n-- matrix_matrix, product of two matrices as list of rows\n--
      • \n-- matrix_matrix', product of two matrices as list of columns\n--
      • \n-- triangle_matrix', upper triangular matrix times square matrix\n--
      • \n-- matrix_ket, matrix times ket vector\n--
      • \n-- bra_matrix, bra vector times matrix\n--
      • \n-- bra_matrix_ket, matrix multiplied on both sides by vectors\n--
      • \n-- scalar_matrix, scalar times matrix\n--
      \n--

    • \n-- Orthogonalization process\n--
        \n--
      • \n-- orthogonals, set of orthogonal vectors\n--
      • \n-- gram_schmidt, vector perpendicular to a hyperplane\n--
      \n\n--

    • \n-- Solutions of linear equations by orthogonalization\n--
        \n--
      • \n-- one_ket_triangle, triangularization of one vector equation\n--
      • \n-- one_ket_solution, solution for one unknown vector\n--
      • \n-- many_kets_triangle, triangularization of several vector equations\n--
      • \n-- many_kets_solution, solution for several unknown vectors\n--
      \n--

    • \n-- Matrix inversion\n--
        \n--
      • \n-- inverse, inverse of a matrix\n--
      \n--

    • \n-- QR factorization of matrices provided by \"many_kets_triangle\"\n--
        \n--
      • \n-- factors_QR, QR alike factorization of matrices\n--
      • \n-- determinant, computation of the determinant based on the QR factorization\n--
      \n--

    • \n-- Similarity transformations and eigenvalues\n--
        \n--
      • \n-- similar_to, matrix obtained by similarity transformation\n--
      • \n-- iterated_eigenvalues, list of approximations of eigenvalues\n--
      • \n-- eigenvalues, final approximation of eigenvalues\n--
      \n--

    • \n-- Preconditioning of real nonsymmetric matrices\n--
        \n--
      • \n-- add_to_diagonal, simple preconditioning method\n--
      \n--

    • \n-- Examples of iterated eigenvalues\n--
        \n--
      • \n-- Symmetric real matrix\n--
      • \n-- Hermitian complex matrix\n--
      • \n-- General complex matrix\n--
      • \n-- Nonsymmetric real matrix with real eigenvalues\n--
      • \n-- Nonsymmetric real matrix with complex eigenvalues\n--
      \n--

    • \n-- Eigenvectors for distinct eigenvalues\n--
        \n--
      • \n-- eigenkets, eigenvectors for distinct eigenvalues\n--
      \n--

    • \n-- Eigenvectors for degenerated eigenvalues\n--
        \n--
      • \n-- eigenket', eigenvector based on a trial vector\n--
      \n\n--

    • \n-- Auxiliary functions\n--
        \n--
      • \n-- unit_matrix, a unit matrix with 1's on a diagonal\n--
      • \n-- unit_vector, a vector with one non-zero component\n--
      • \n-- diagonals, vector made of a matrix diagonal\n--
      \n--
    \n\n--

    \n--


    \n--

    \n-- \n-- Notation\n-- \n--

    \n-- What follows is written in Dirac's notation, as used\n-- in Quantum Mechanics. Matrices are represented by capital\n-- letters, while vectors come in two varieties:\n--

      \n--

    • \n-- Bra vector x, written < x |, is represented by one-row matrix\n--

    • Ket vector y, written | y >, is represented by one-column matrix\n--
    \n--

    \n-- Bra vectors can be obtained from ket vectors by transposition\n-- and conjugation of their components. Conjugation is only\n-- important for complex vectors.\n--

    \n-- Scalar product of two vectors | x > and | y > is written\n-- as\n--

    \n--         < x | y >\n-- 
    \n-- which looks like a bracket and is sometimes called a \"bra_ket\".\n-- This justifies \"bra\" and \"ket\" names introduced by Dirac. There\n-- is a good reason for conjugating the components of \"bra-vector\":\n-- the scalar product of\n--
    \n--         < x | x >\n-- 
    \n-- should be a square of the norm of the vector \"x\", and that\n-- means that it should be represented by a real number, or complex\n-- number but with its imaginary part equal to zero.\n--

    \n--


    \n--

    \n--

    \n\n module Orthogonals where\n import Data.Complex\n import Data.Ratio\n import qualified Data.List as List\n\n-- 
    \n-- \n-- Scalar product and vector normalization\n-- \n--

    \n-- The scalar product \"bra_ket\" is a basis of many algorithms\n-- presented here.\n\n\n--

    \n\n bra_ket :: (Scalar a, Num a) => [a] -> [a] -> a\n bra_ket u v =\n       --\n       -- Scalar product of two vectors u and v,\n       -- or < u | v > in Dirac's notation.\n       -- This is equally valid for both: real and complex vectors.\n       --\n       sum_product u (map coupled v)\n\n-- 
    \n\n-- Notice the call to function \"coupled\" in the above implementation\n-- of scalar product. This function conjugates its argument\n-- if it is complex, otherwise does not change it. It is defined\n-- in the class Scalar - specifically designed for this purpose\n-- mainly.\n--
    \n-- This class also defines a norm of a vector that might be used\n-- by some algorithms. So far we have been able to avoid this.\n--
    \n\n class Eq a => Scalar a where\n     coupled    :: a->a\n     norm       :: [a] -> a\n     almostZero :: a -> Bool\n     scaled     :: [a] -> [a]\n\n instance Scalar Double where\n     coupled x    = x\n     norm u       = sqrt (bra_ket u u)\n     almostZero x = (abs x) < 1.0e-8\n     scaled       = scaled'\n\n instance Scalar Float where\n     coupled x    = x\n     norm u       = sqrt (bra_ket u u)\n     almostZero x = (abs x) < 1.0e-8\n     scaled       = scaled'\n\n instance (Integral a) => Scalar (Ratio a) where\n     coupled x    = x\n     -- norm u    = fromDouble ((sqrt (bra_ket u u))::Double)\n     -- Intended hack to silently convert to and from Double.\n     -- But I do not know how to declare it properly.\n     --\n     -- Our type Fraction, when used instead of Ratio a, has its own\n     -- definition of sqrt. No hack would be needed here.\n     almostZero x = abs x < 1e-8\n     scaled       = scaled'\n\n instance (RealFloat a) => Scalar (Complex a) where\n     coupled (x:+y) = x:+(-y)\n     norm u         = sqrt (realPart (bra_ket u u)) :+ 0\n     almostZero z   = (realPart (abs z)) < 1.0e-8\n     scaled u       = [(x/m):+(y/m) | x:+y <- u]\n        where m = maximum [max (abs x) (abs y) | x:+y <- u]\n\n norm1 :: (Num a) => [a] -> a\n norm1 = sum . map abs\n\n norminf :: (Num a, Ord a) => [a] -> a\n norminf = maximum . map abs\n\n matnorm1 :: (Num a, Ord a) => [[a]] -> a\n matnorm1 = matnorminf . transposed\n\n matnorminf :: (Num a, Ord a) => [[a]] -> a\n matnorminf = maximum . map norm1\n\n\n-- 
    \n\n-- But we also need a slightly different definition of\n-- scalar product that will appear in multiplication of matrices\n-- by vectors (or vice versa): a straightforward accumulated product\n-- of two lists, where no complex conjugation takes place.\n-- We will call it a 'sum_product\".\n--
    \n\n sum_product :: Num a => [a] -> [a] -> a\n sum_product u v =\n       --\n       -- Similar to scalar product but without\n       -- conjugations of | u > components\n       -- Used in matrix-vector or vector-matrix products\n       --\n       sum (zipWith (*) u v)\n\n-- 
    \n-- Some algorithms might need vectors normalized to one, although\n-- we'll try to avoid the normalizations due to its high cost\n-- or its inapplicability to rational numbers. Instead, we wiil\n-- scale vectors by their maximal components.\n--
    \n\n normalized :: (Scalar a, Fractional a) => [a] -> [a]\n normalized u =\n       map (/norm u) u\n\n scaled' :: (Fractional t, Ord t) => [t] -> [t]\n scaled' u =\n       map (/norminf u) u\n\n-- 
    \n--
    \n--

    \n-- \n-- Transposition and adjoining of matrices\n-- \n--

    \n-- Matrices are represented here by lists of lists.\n-- Function \"transposed\" converts from row-wise to column-wise\n-- representation, or vice versa.\n--

    \n-- When transposition is combined with complex conjugation\n-- the resulting matrix is called \"adjoint\".\n--

    \n-- A square matrix is called symmetric if it is equal to its transpose\n--

    \n--         A = AT\n-- 
    \n-- It is called Hermitian, or self-adjoint, if it equals to\n-- its adjoint\n--
    \n--         A = A+\n\n transposed :: [[a]] -> [[a]]\n transposed a\n     | null (head a) = []\n     | otherwise = ([head mi| mi <- a])\n                   :transposed ([tail mi| mi <- a])\n\n adjoint :: Scalar a => [[a]] -> [[a]]\n adjoint a\n     | null (head a) = []\n     | otherwise = ([coupled (head mi)| mi <- a])\n                   :adjoint ([tail mi| mi <- a])\n\n-- 
    \n--

    \n--


    \n--

    \n-- \n-- Linear combination and sum of two matrices\n-- \n--

    \n-- One can form a linear combination of two matrices, such\n-- as\n--

    \n--         C = alpha A + beta B\n--         where\n--             alpha and beta are scalars\n-- 
    \n-- The most generic form of any combination, not necessary\n-- linear, of components of two matrices is given by \"matrix_zipWith\"\n-- function below, which accepts a function \"f\" describing such\n-- combination. For the linear combination with two scalars\n-- the function \"f\" could be defined as:\n--
    \n--         f alpha beta a b = alpha*a + beta*b\n-- 
    \n-- For a straightforward addition of two matrices this auxiliary\n-- function is simply \"(+)\".\n--
    \n\n matrix_zipWith :: (a -> b -> c) -> [[a]] -> [[b]] -> [[c]]\n matrix_zipWith f a b =\n     --\n     -- Matrix made of a combination\n     -- of matrices a and b - as specified by f\n     --\n     [zipWith f ak bk | (ak,bk) <- zip a b]\n\n add_matrices :: (Num a) => t -> t1 -> [[a]] -> [[a]] -> [[a]]\n add_matrices _ _ = matrix_zipWith (+)\n\n-- 
    \n\n--

    \n--


    \n--

    \n-- \n-- Products involving matrices\n-- \n--

    \n-- Variety of products involving matrices can be defined.\n-- Our Haskell implementation is based on lists of lists\n-- and therefore is open to interpretation: sublists\n-- can either represent the rows or the columns of a matrix.\n--

    \n-- The following definitions are somehow arbitrary, since\n-- one can choose alternative interpretations of lists\n-- representing matrices.\n--

    \n-- \n-- C = A B\n-- \n--

    \n-- Inner product of two matrices A B can be expressed quite simply,\n-- providing that matrix A is represented by a list of rows\n-- and B - by a list of columns. Function \"matrix_matrix\"\n-- answers list of rows, while \"matrix_matrix'\" - list\n-- of columns.\n--

    \n-- Major algorithms of this module make use of \"triangle_matrix'\",\n-- which calculates a product of upper triangular matrix\n-- with square matrix and returns a rectangular list of columns.\n\n--
    \n\n matrix_matrix :: Num a => [[a]] -> [[a]] -> [[a]]\n matrix_matrix a b\n --\n -- A matrix being an inner product\n -- of matrices A and B, where\n --     A is represented by a list of rows a\n --     B is represented by a list of columns b\n --     result is represented by list of rows\n -- Require: length of a is equal of length of b\n -- Require: all sublists are of equal length\n\n       | null a = []\n       | otherwise = ([sum_product (head a) bi | bi <- b])\n                  : matrix_matrix (tail a) b\n\n matrix_matrix' :: (Num a) => [[a]] -> [[a]] -> [[a]]\n matrix_matrix' a b\n       --\n       -- Similar to \"matrix_matrix\"\n       -- but the result is represented by\n       -- a list of columns\n       --\n       | null b = []\n       | otherwise = ([sum_product ai (head b) | ai <- a])\n                    : matrix_matrix' a (tail b)\n\n\n triangle_matrix' :: Num a => [[a]] -> [[a]] -> [[a]]\n triangle_matrix' r q =\n       --\n       -- List of columns of of a product of\n       -- upper triangular matrix R and square\n       -- matrix Q\n       -- where\n       --     r is a list of rows of R\n       --     q is a list of columns of A\n       --\n       [f r qk | qk <- q]\n       where\n           f t u\n               | null t = []\n               | otherwise = (sum_product (head t) u)\n                             : (f (tail t) (tail u))\n\n\n\n-- 
    \n-- \n-- | u > = A | v >\n-- \n--

    \n-- Product of a matrix and a ket-vector is another\n-- ket vector. The following implementation assumes\n-- that list \"a\" represents rows of matrix A.\n--

    \n\n matrix_ket :: Num a => [[a]] -> [a] -> [a]\n matrix_ket a v = [sum_product ai v| ai <- a]\n\n-- 
    \n-- \n-- < u | = < v | A\n-- \n--

    \n-- Bra-vector multiplied by a matrix produces\n-- another bra-vector. The implementation below\n-- assumes that list \"a\" represents columns\n-- of matrix A. It is also assumed that vector\n-- \"v\" is given in its standard \"ket\" representation,\n-- therefore the definition below uses \"bra_ket\"\n-- instead of \"sum_product\".\n--

    \n\n bra_matrix :: (Scalar a, Num a) => [a] -> [[a]] -> [a]\n bra_matrix v a = [bra_ket v ai | ai <- a]\n\n-- 
    \n-- \n-- alpha = < u | A | v >\n-- \n--

    \n-- This kind of product results in a scalar and is often\n-- used to define elements of a new matrix, such as\n--

    \n--         B[i,j] = < ei | A | ej >\n-- 
    \n-- The implementation below assumes that list \"a\" represents\n-- rows of matrix A.\n--
    \n\n bra_matrix_ket :: (Scalar a, Num a) => [a] -> [[a]] -> [a] -> a\n bra_matrix_ket u a v =\n     bra_ket u (matrix_ket a v)\n\n-- 
    \n-- \n-- B = alpha A\n-- \n--

    \n-- Below is a function which multiplies matrix by a scalar:\n--

    \n\n scalar_matrix :: Num a => a -> [[a]] -> [[a]]\n scalar_matrix alpha a =\n       [[alpha*aij| aij <- ai] | ai<-a]\n\n-- 
    \n--

    \n--


    \n--

    \n-- \n-- Orthogonalization process\n-- \n--

    \n\n-- Gram-Schmidt orthogonalization procedure is used here\n-- for calculation of sets of mutually orthogonal vectors.\n--

    \n-- Function \"orthogonals\" computes a set of mutually orthogonal\n-- vectors - all orthogonal to a given vector. Such set plus\n-- the input vector form a basis of the vector space. Another\n-- words, they are the base vectors, although we cannot call them\n-- unit vectors since we do not normalize them for two reasons:\n--
      \n--
    • \n-- None of the algorithms presented here needs this -- quite\n-- costly -- normalization.\n--
    • \n-- Some algorithms can be used either with doubles or with\n-- rationals. The neat output of the latter is sometimes desirable\n-- for pedagogical or accuracy reasons. But normalization requires \"sqrt\"\n-- function, which is not defined for rational numbers. We could\n-- use our module Fraction instead, where \"sqrt\" is defined,\n-- but we'll leave it for a future revision of this module.\n--
    \n--

    \n-- Function \"gram_schmidt\" computes one vector - orthogonal\n-- to an incomplete set of orthogonal vectors, which form a hyperplane\n-- in the vector space. Another words, \"gram_schmidt\" vector is\n-- perpendicular to such a hyperlane.\n\n\n--

    \n\n orthogonals :: (Scalar a, Fractional a) => [a] -> [[a]]\n orthogonals x =\n       --\n       -- List of (n-1) linearly independent vectors,\n       -- (mutually orthogonal) and orthogonal to the\n       -- vector x, but not normalized,\n       -- where\n       --     n is a length of x.\n       --\n       orth [x] size (next (-1))\n       where\n           orth a n m\n               | n == 1        = drop 1 (reverse a)\n               | otherwise     = orth ((gram_schmidt a u ):a) (n-1) (next m)\n               where\n                   u = unit_vector m size\n           size = length x\n           next i = if (i+1) == k then (i+2) else (i+1)\n           k = length (takeWhile (== 0) x) -- first non-zero component of x\n\n gram_schmidt :: (Scalar a, Fractional a) => [[a]] -> [a] -> [a]\n gram_schmidt a u =\n       --\n       -- Projection of vector | u > on some direction\n       -- orthogonal to the hyperplane spanned by the list 'a'\n       -- of mutually orthogonal (linearly independent)\n       -- vectors.\n       --\n       gram_schmidt' a u u\n       where\n           gram_schmidt' [] _ w = w\n           gram_schmidt' (b:bs) v w\n               | all (== 0) b = gram_schmidt' bs v w\n               | otherwise    = gram_schmidt' bs v w'\n               where\n                   w' = vectorCombination w (-(bra_ket b v)/(bra_ket b b)) b\n           vectorCombination x c y\n               | null x = []\n               | null y = []\n               | otherwise = (head x + c * (head y))\n                             : (vectorCombination (tail x) c (tail y))\n\n-- 
    \n--

    \n--


    \n--

    \n-- \n-- Solutions of linear equations by orthogonalization\n-- \n--

    \n-- A matrix equation for unknown vector | x >\n--

    \n--         A | x > = | b >\n-- 
    \n-- can be rewritten as\n--
    \n--         x1 | 1 > + x2 | 2 > + x3 | 3 > + ... + xn | n > = | b >     (7.1)\n--         where\n--                 | 1 >, | 2 >... represent columns of the matrix A\n-- 
    \n-- For any n-dimensional vector, such as \"1\", there exist\n-- n-1 linearly independent vectors \"ck\" that are orthogonal to \"1\";\n-- that is, each satisfies the relation:\n--
    \n--         < ck | 1 > = 0, for k = 1...m, where m = n - 1\n-- 
    \n-- If we could find all such vectors, then we could multiply\n-- the equation (7.1) by each of them, and end up with m = n-1\n-- following equations\n--
    \n--         < c1 | 2 > x2 + < c1 | 3 > x3 + ... < c1 | n > xn = < c1 | b >\n--         < c2 | 2 > x2 + < c2 | 3 > x3 + ... < c2 | n > xn = < c2 | b >\n--         .......\n--         < cm | 2 > x2 + < cm | 3 > x3 + ... < cm | n > xn = < cm | b >\n-- 
    \n-- But the above is nothing more than a new matrix equation\n--
    \n--         A' | x' > = | b' >\n--         or\n\n--         x2 | 2'> + x3 | 3'> .... + xn | n'> = | b'>\n--         where\n--             primed vectors | 2' >, etc. are the columns of the new\n--             matrix A'.\n-- 
    \n-- with the problem dimension reduced by one.\n\n--
    \n-- Taking as an example a four-dimensional problem and writing\n-- down the successive transformations of the original equation\n-- we will end up with the following triangular pattern made of\n-- four vector equations:\n\n--
    \n--         x1 | 1 > + x2 | 2 > + x3 | 3 >  + x4 | 4 >   = | b >\n--                    x2 | 2'> + x3 | 3'>  + x4 | 4'>   = | b'>\n--                               x3 | 3''> + x4 | 4''>  = | b''>\n--                                           x4 | 4'''> = | b'''>\n-- 
    \n-- But if we premultiply each vector equation by a non-zero vector\n-- of our choice, say < 1 | , < 2' |, < 3'' |, and < 4''' | - chosen\n-- correspondingly for equations 1, 2, 3 and 4, then the above\n-- system of vector equations will be converted to much simpler\n-- system of scalar equations. The result is\n-- shown below in matrix representation:\n\n--
    \n--         | p11  p12   p13   p14 | | x1 | = | q1 |\n--         | 0    p22   p23   p24 | | x2 | = | q2 |\n--         | 0    0     p33   p34 | | x3 | = | q3 |\n--         | 0    0     0     p44 | | x4 | = | q4 |\n-- 
    \n-- In effect, we have triangularized our original matrix A.\n-- Below is a function that does that for any problem size:\n--
    \n\n one_ket_triangle :: (Scalar a, Fractional a) => [[a]] -> [a] -> [([a],a)]\n one_ket_triangle a b\n     --\n     -- List of pairs: (p, q) representing\n     -- rows of triangular matrix P and of vector | q >\n     -- in the equation P | x > = | q >, which\n     -- has been obtained by linear transformation\n     -- of the original equation A | x > = | b >\n     --\n     | null a = []\n     | otherwise = (p,q):(one_ket_triangle a' b')\n     where\n         p    = [bra_ket u ak | ak <- a]\n         q    = bra_ket u b\n         a'   = [[bra_ket ck ai | ck <- orth] | ai <- v]\n         b'   = [ bra_ket ck b  | ck <- orth]\n         orth = orthogonals u\n         u    = head a\n         v    = tail a\n\n-- 
    \n-- The triangular system of equations can be easily solved by\n-- successive substitutions - starting with the last equation.\n\n--
    \n\n one_ket_solution :: (Scalar a, Fractional a) => [[a]] -> [a] -> [a]\n one_ket_solution a b =\n     --\n     -- List representing vector |x>, which is\n     -- a solution of the matrix equation\n     --     A |x> = |b>\n     -- where\n     --     a is a list of columns of matrix A\n     --     b is a list representing vector |b>\n     --\n     solve' (unzip (reverse (one_ket_triangle a b))) []\n     where\n         solve' (d, c) xs\n             | null d  = xs\n             | otherwise = solve' ((tail d), (tail c)) (x:xs)\n             where\n                 x = (head c - (sum_product (tail u) xs))/(head u)\n                 u = head d\n\n-- 
    \n-- The triangularization procedure can be easily extended\n-- to a list of several ket-vectors | b > on the right hand\n-- side of the original equation A | x > = | b > -- instead\n-- of just one:\n--
    \n\n many_kets_triangle :: (Scalar a, Fractional a) => [[a]] -> [[a]] -> [([a],[a])]\n many_kets_triangle a b\n     --\n     -- List of pairs: (p, q) representing\n     -- rows of triangular matrix P and of rectangular matrix Q\n     -- in the equation P X = Q, which\n     -- has been obtained by linear transformation\n     -- of the original equation A X = B\n     -- where\n     --     a is a list of columns of matrix A\n     --     b is a list of columns of matrix B\n     --\n     | null a = []\n     | otherwise = (p,q):(many_kets_triangle a' b')\n     where\n         p    = [bra_ket u ak   | ak <- a]\n         q    = [bra_ket u bk   | bk <- b]\n         a'   = [[bra_ket ck ai | ck <- orth] | ai <- v]\n         b'   = [[bra_ket ck bi | ck <- orth] | bi <- b]\n         orth = orthogonals u\n         u    = head a\n         v    = tail a\n\n-- 
    \n-- Similarly, function 'one_ket_solution' can be generalized\n-- to function 'many_kets_solution' that handles cases with\n-- several ket-vectors on the right hand side.\n--
    \n\n many_kets_solution :: (Scalar a, Fractional a) => [[a]] -> [[a]] -> [[a]]\n many_kets_solution a b =\n     --\n     -- List of columns of matrix X, which is\n     -- a solution of the matrix equation\n     --     A X = B\n     -- where\n     --     a is a list of columns of matrix A\n     --     b is a list of columns of matrix B\n     --\n     solve' p q emptyLists\n     where\n         (p, q) = unzip (reverse (many_kets_triangle a b))\n         emptyLists = [[] | _ <- [1..(length (head q))]]\n         solve' a' b' x\n             | null a'  = x\n             | otherwise = solve' (tail a') (tail b')\n                                 [(f vk xk):xk  | (xk, vk) <- (zip x v)]\n             where\n                 f vk xk = (vk - (sum_product (tail u) xk))/(head u)\n                 u = head a'\n                 v = head b'\n\n\n-- 
    \n--

    \n--


    \n--

    \n-- \n-- Matrix inversion\n-- \n--

    \n-- Function 'many_kets_solution' can be used to compute\n-- inverse of matrix A by specializing matrix B to a unit\n-- matrix I:\n--

    \n\n--         A X = I\n-- 
    \n-- It follows that matrix X is an inverse of A; that is X = A-1.\n--
    \n\n inverse :: (Scalar a, Fractional a) => [[a]] -> [[a]]\n inverse a = many_kets_solution a (unit_matrix (length a))\n       --\n       -- List of columns of inverse of matrix A\n       -- where\n       --     a is list of columns of A\n\n-- 
    \n--

    \n--


    \n--

    \n-- \n-- QR factorization of matrices\n-- \n--

    \n-- The process described above and implemented by\n-- 'many_kets_triangle' function transforms the equation\n--

    \n--         A X = B\n-- 
    \n-- into another equation for the same matrix X\n--
    \n--         R X = S\n-- 
    \n-- where R is an upper triangular matrix. All operations\n-- performed on matrices A and B during this process are linear,\n-- and therefore we should be able to find a square matrix Q\n-- that describes the entire process in one step. Indeed, assuming\n-- that matrix A can be decomposed as a product of unknown matrix Q\n-- and triangular matrix R and that Q-1 is an inverse of matrix Q\n-- we can reach the last equation by following these steps:\n--
    \n--         A X       = B\n--         (Q R) X   = B\n--         Q-1 Q R X = Q-1 B\n--         R X       = S\n-- 
    \n-- It follows that during this process a given matrix B\n-- transforms to matrix S, as delivered by 'many_kets_triangle':\n--
    \n--         S = Q-1 B\n-- 
    \n-- from which the inverse of Q can be found:\n--
    \n--         Q-1 = S B-1\n-- 
    \n-- Having a freedom of choice of the right hand side matrix B\n-- we can choose the unit matrix I in place of B, and therefore\n-- simplify the definition of Q-1:\n--
    \n--         Q-1 = S,  if B is unit matrix\n-- 
    \n-- It follows that any non-singular matrix A can be decomposed\n-- as a product of a matrix Q and a triangular matrix R\n\n--
    \n--         A = Q R\n-- 
    \n-- where matrices Q-1 and R are delivered by \"many_kets_triangle\"\n-- as a result of triangularization process of equation:\n--
    \n--         A X = I\n-- 
    \n-- The function below extracts a pair of matrices Q and R\n-- from the answer provided by \"many_kets_triangle\".\n-- During this process it inverts matrix Q-1 to Q.\n-- This factorization will be used by a sequence of similarity\n-- transformations to be defined in the next section.\n\n--
    \n\n factors_QR :: (Scalar a, Fractional a) => [[a]] -> ([[a]],[[a]])\n factors_QR a =\n       --\n       -- A pair of matrices (Q, R), such that\n       -- A = Q R\n       -- where\n       --     R is upper triangular matrix in row representation\n       --     (without redundant zeros)\n       --     Q is a transformation matrix in column representation\n       --     A is square matrix given as columns\n       --\n       (inverse (transposed q1),r)\n       where\n           (r, q1) = unzip (many_kets_triangle a (unit_matrix (length a)))\n\n-- 
    \n\n--

    \n--


    \n--

    \n-- \n-- Computation of the determinant\n-- \n\n-- \n\n--

    \n\n determinant :: (Scalar a, Fractional a) => [[a]] -> a\n determinant a =\n    let (q,r) = factors_QR a\n    -- matrix Q is not normed so we have to respect the norms of its rows\n    in  product (map norm q) * product (map head r)\n\n-- 
    \n\n-- Naive division-free computation of the determinant by expanding the first column.\n-- It consumes n! multiplications.\n\n--
    \n\n determinantNaive :: (Num a) => [[a]] -> a\n determinantNaive [] = 1\n determinantNaive m  =\n    sum (alternate\n       (zipWith (*) (map head m)\n           (map determinantNaive (removeEach (map tail m)))))\n\n-- 
    \n\n-- Compute the determinant with about n^4 multiplications\n-- without division according to the clow decomposition algorithm\n-- of Mahajan and Vinay, and Berkowitz\n-- as presented by G\u00fcnter Rote:\n-- \n-- Division-Free Algorithms for the Determinant and the Pfaffian:\n-- Algebraic and Combinatorial Approaches.\n\n--
    \n\n determinantClow :: (Num a) => [[a]] -> a\n determinantClow [] = 1\n determinantClow m =\n    let lm = length m\n    in  parityFlip lm (last (newClow m\n           (nest (lm-1) (longerClow m)\n               (take lm (iterate (0:) [1])))))\n\n-- 
    \n\n-- Compute the weights of all clow sequences\n-- where the last clow is closed and a new one is started.\n\n--
    \n\n newClow :: (Num a) => [[a]] -> [[a]] -> [a]\n newClow a c =\n    scanl (-) 0\n          (sumVec (zipWith (zipWith (*)) (List.transpose a) c))\n\n-- 
    \n\n-- Compute the weights of all clow sequences\n-- where the last (open) clow is extended by a new arc.\n\n--
    \n\n extendClow :: (Num a) => [[a]] -> [[a]] -> [[a]]\n extendClow a c =\n    map (\\ai -> sumVec (zipWith scaleVec ai c)) a\n\n-- 
    \n\n-- Given the matrix of all weights of clows of length l\n-- compute the weight matrix for all clows of length (l+1).\n-- Take the result of 'newClow' as diagonal\n-- and the result of 'extendClow' as lower triangle\n-- of the weight matrix.\n\n--
    \n\n longerClow :: (Num a) => [[a]] -> [[a]] -> [[a]]\n longerClow a c =\n    let diagonal = newClow a c\n        triangle = extendClow a c\n    in  zipWith3 (\\i t d -> take i t ++ [d]) [0 ..] triangle diagonal\n\n-- 
    \n\n-- Auxiliary functions for the clow determinant.\n\n--
    \n\n {- | Compositional power of a function,\n      i.e. apply the function n times to a value. -}\n nest :: Int -> (a -> a) -> a -> a\n nest 0 _ x = x\n nest n f x = f (nest (n-1) f x)\n\n {- successively select elements from xs and remove one in each result list -}\n removeEach :: [a] -> [[a]]\n removeEach xs =\n    zipWith (++) (List.inits xs) (tail (List.tails xs))\n\n alternate :: (Num a) => [a] -> [a]\n alternate = zipWith id (cycle [id, negate])\n\n parityFlip :: Num a => Int -> a -> a\n parityFlip n x = if even n then x else -x\n\n {-| Weight a list of numbers by a scalar. -}\n scaleVec :: (Num a) => a -> [a] -> [a]\n scaleVec k = map (k*)\n\n {-| Add corresponding numbers of two lists. -}\n {- don't use zipWith because it clips to the shorter list -}\n addVec :: (Num a) => [a] -> [a] -> [a]\n addVec x [] = x\n addVec [] y = y\n addVec (x:xs) (y:ys) = x+y : addVec xs ys\n\n {-| Add some lists. -}\n sumVec :: (Num a) => [[a]] -> [a]\n sumVec = foldl addVec []\n\n-- 
    \n\n\n\n--

    \n--


    \n--

    \n-- \n-- Similarity transformations and eigenvalues\n-- \n--

    \n-- Two n-square matrices A and B are called similar if there\n-- exists a non-singular matrix S such that:\n--

    \n--         B = S-1 A S\n-- 
    \n\n-- It can be proven that:\n--
      \n--
    • \n-- Any two similar matrices have the same eigenvalues\n--
    • \n-- Every n-square matrix A is similar to a triangular matrix\n-- whose diagonal elements are the eigenvalues of A.\n--
    \n--

    \n-- If matrix A can be transformed to a triangular or a diagonal\n-- matrix Ak by a sequence of similarity transformations then\n-- the eigenvalues of matrix A are the diagonal elements of Ak.\n\n--

    \n\n-- Let's construct the sequence of matrices similar to A\n--

    \n--         A, A1, A2, A3...\n-- 
    \n-- by the following iterations - each of which factorizes a matrix\n-- by applying the function 'factors_QR' and then forms a product\n-- of the factors taken in the reverse order:\n--
    \n--         A = Q R          = Q (R Q) Q-1    = Q A1 Q-1        =\n--           = Q (Q1 R1) Q-1 = Q Q1 (R1 Q1) Q1-1 Q-1 = Q Q1 A2 Q1-1 Q-1 =\n--           = Q Q1 (Q2 R2) Q1-1 Q-1 = ...\n\n-- 
    \n-- We are hoping that after some number of iterations some matrix\n-- Ak would become triangular and therefore its diagonal\n-- elements could serve as eigenvalues of matrix A. As long as\n-- a matrix has real eigenvalues only, this method should work well.\n-- This applies to symmetric and hermitian matrices. It appears\n-- that general complex matrices -- hermitian or not -- can also\n-- be handled this way. Even more, this method also works for some\n-- nonsymmetric real matrices, which have real eigenvalues only.\n--
    \n-- The only type of matrices that cannot be treated by this algorithm\n-- are real nonsymmetric matrices, whose some eigenvalues are complex.\n-- There is no operation in the process that converts real elements\n-- to complex ones, which could find their way into diagonal\n-- positions of a triangular matrix. But a simple preconditioning\n-- of a matrix -- described in the next section -- replaces\n-- a real matrix by a complex one, whose eigenvalues are related\n-- to the eigenvalues of the matrix being replaced. And this allows\n-- us to apply the same method all across the board.\n--
    \n-- It is worth noting that a process known in literature as QR\n-- factorization is not uniquely defined and different algorithms\n-- are employed for this. The algorithms using QR factorization\n-- apply only to symmetric or hermitian matrices, and Q matrix\n-- must be either orthogonal or unitary.\n--
    \n-- But our transformation matrix Q is not orthogonal nor unitary,\n-- although its first row is orthogonal to all other rows. In fact,\n-- this factorization is only similar to QR factorization. We just\n-- keep the same name to help identify a category of the methods\n-- to which it belongs.\n--
    \n-- The same factorization is used for tackling two major problems:\n-- solving the systems of linear equations and finding the eigenvalues\n-- of matrices.\n--
    \n-- Below is the function 'similar_to', which makes a new matrix that is\n-- similar to a given matrix by applying our similarity transformation.\n--
    \n-- Function 'iterated_eigenvalues' applies this transformation n\n-- times - storing diagonals of each new matrix as approximations of\n-- eigenvalues.\n--
    \n-- Function 'eigenvalues' follows the same process but reports the last\n-- approximation only.\n--
    \n\n\n similar_to :: (Scalar a, Fractional a) => [[a]] -> [[a]]\n similar_to a =\n       --\n       -- List of columns of matrix A1 similar to A\n       -- obtained by factoring A as Q R and then\n       -- forming the product A1 = R Q = (inverse Q) A Q\n       -- where\n       --     a is list of columns of A\n       --\n       triangle_matrix' r q\n       where\n           (q,r) = factors_QR a\n\n iterated_eigenvalues :: (Scalar a1, Fractional a1, Eq a, Num a) => [[a1]] -> a -> [[a1]]\n iterated_eigenvalues a n\n       --\n       -- List of vectors representing\n       -- successive approximations of\n       -- eigenvalues of matrix A\n       -- where\n       --     a is a list of columns of A\n       --     n is a number of requested iterations\n       --\n       | n == 0 = []\n       | otherwise = (diagonals a)\n                     : iterated_eigenvalues (similar_to a) (n-1)\n\n eigenvalues :: (Scalar a1, Fractional a1, Eq a, Num a) => [[a1]] -> a -> [a1]\n eigenvalues a n\n       --\n       -- Eigenvalues of matrix A\n       -- obtained by n similarity iterations\n       -- where\n       --     a are the columns of A\n       --\n       | n == 0    = diagonals a\n       | otherwise = eigenvalues (similar_to a) (n-1)\n\n-- 
    \n--

    \n--


    \n--

    \n-- \n-- Preconditioning of real nonsymmetric matrices\n-- \n--

    \n-- As mentioned above, our QR-like factorization method works\n-- well with almost all kind of matrices, but with the exception\n-- of a class of real nonsymmetric matrices that have\n-- complex eigenvalues.\n--

    \n-- There is no mechanism in that method that would be able to\n-- produce complex eigenvalues out of the real components of\n-- this type of nonsymmetric matrices. Simple trivial replacement\n-- of real components of a matrix by its complex counterparts\n-- does not work because zero-valued imaginary components do\n-- not contribute in any way to production of nontrivial\n-- imaginary components during the factorization process.\n--
    \n-- What we need is a trick that replaces real nonsymmetric matrix\n-- by a nontrivial complex matrix in such a way that the results\n-- of such replacements could be undone when the series of\n-- similarity transformations finally produced the expected\n-- effect in a form of a triangular matrix.\n--
    \n-- The practical solution is surprisingly simple:\n-- it's suffice to add any complex number, such as \"i\", to the\n-- main diagonal of a matrix, and when triangularization is done\n-- -- subtract it back from computed eigenvalues.\n-- The explanation follows.\n--

    \n-- Consider the eigenproblem for real and nonsymmetric matrix A.\n--

    \n--         A | x > = a | x >\n-- 
    \n-- Let us now define a new complex matrix B, such that:\n--
    \n--         B = A + alpha I\n--         where\n--             I is a unit matrix and alpha is a complex scalar\n-- 
    \n-- It is obvious that matrices A and B commute; that is:\n--
    \n--         A B = B A\n-- 
    \n-- It can be proven that if two matrices commute then they\n-- have the same eigenvectors. Therefore we can use vector\n-- | x > of matrix A as an eigenvector of B:\n--
    \n--         B | x > = b | x >\n--         B | x > = A | x > + alpha I | x >\n--                 = a | x > + alpha | x >\n--                 = (a + alpha) | x >\n-- 
    \n-- It follows that eigenvalues of B are related to the eigenvalues\n-- of A by:\n--
    \n--         b = a + alpha\n-- 
    \n-- After eigenvalues of complex matrix B have been succesfully\n-- computed, all what remains is to subtract \"alpha\" from them\n-- all to obtain eigenvalues of A. And nothing has to be done\n-- to eigenvectors of B - they are the same for A as well.\n-- Simple and elegant!\n--

    \n-- Below is an auxiliary function that adds a scalar to the\n-- diagonal of a matrix:\n\n--

    \n\n add_to_diagonal :: Num a => a -> [[a]] -> [[a]]\n add_to_diagonal alpha a =\n       --\n       -- Add constant alpha to diagonal of matrix A\n       --\n       [f ai ni | (ai,ni) <- zip a [0..(length a -1)]]\n       where\n           f b k = p++[head q + alpha]++(tail q)\n               where\n                   (p,q) = splitAt k b\n\n\n\n-- 
    \n--

    \n--


    \n--

    \n-- \n-- Examples of iterated eigenvalues\n-- \n--

    \n\n\n-- Here is an example of a symmetric real matrix with results\n-- of application of function 'iterated_eigenvalues'.\n--

    \n--         | 7  -2  1 |\n--         |-2  10 -2 |\n--         | 1  -2  7 |\n\n--          [[7.0,     10.0,    7.0],\n--           [8.66667, 9.05752, 6.27582],\n--           [10.7928, 7.11006, 6.09718],\n--           [11.5513, 6.40499, 6.04367],\n--           [11.7889, 6.18968, 6.02142],\n--           [11.8943, 6.09506, 6.01068],\n--           [11.9468, 6.04788, 6.00534],\n--           [11.9733, 6.02405, 6.00267],\n--           [11.9866, 6.01206, 6.00134],\n--           [11.9933, 6.00604, 6.00067],\n--           [11.9966, 6.00302, 6.00034],\n--           [11.9983, 6.00151, 6.00017],\n--           [11.9992, 6.00076, 6.00008],\n--           [11.9996, 6.00038, 6.00004],\n--           [11.9998, 6.00019, 6.00002],\n--           [11.9999, 6.00010, 6.00001],\n--           [11.9999, 6.00005, 6.00001]]\n\n--           The true eigenvalues are:\n--           12, 6, 6\n\n-- 
    \n-- Here is an example of a hermitian matrix. (Eigenvalues of hermitian\n-- matrices are real.) The algorithm works well and converges fast.\n--
    \n--         | 2   0     i|\n--         [ 0   1   0  |\n--         [ -i  0   2  |\n\n--         [[2.8     :+ 0.0, 1.0 :+ 0.0, 1.2     :+ 0.0],\n--          [2.93979 :+ 0.0, 1.0 :+ 0.0, 1.06021 :+ 0.0],\n--          [2.97972 :+ 0.0, 1.0 :+ 0.0, 1.02028 :+ 0.0],\n--          [2.9932  :+ 0.0, 1.0 :+ 0.0, 1.0068  :+ 0.0],\n--          [2.99773 :+ 0.0, 1.0 :+ 0.0, 1.00227 :+ 0.0],\n--          [2.99924 :+ 0.0, 1.0 :+ 0.0, 1.00076 :+ 0.0],\n--          [2.99975 :+ 0.0, 1.0 :+ 0.0, 1.00025 :+ 0.0],\n--          [2.99992 :+ 0.0, 1.0 :+ 0.0, 1.00008 :+ 0.0],\n--          [2.99997 :+ 0.0, 1.0 :+ 0.0, 1.00003 :+ 0.0],\n--          [2.99999 :+ 0.0, 1.0 :+ 0.0, 1.00001 :+ 0.0],\n--          [3.0     :+ 0.0, 1.0 :+ 0.0, 1.0     :+ 0.0],\n--          [3.0     :+ 0.0, 1.0 :+ 0.0, 1.0     :+ 0.0],\n--          [3.0     :+ 0.0, 1.0 :+ 0.0, 1.0     :+ 0.0]]\n\n-- 
    \n-- Here is another example: this is a complex matrix and it is not\n-- even hermitian. Yet, the algorithm still works, although its\n-- fluctuates around true values.\n--
    \n--         | 2-i   0      i |\n--         | 0     1+i  0   |\n--         |   i   0    2-i |\n\n--         [[2.0     :+ (-1.33333), 1.0 :+ 1.0, 2.0     :+ (-0.666667)],\n--          [1.89245 :+ (-1.57849), 1.0 :+ 1.0, 2.10755 :+ (-0.421509)],\n--          [1.81892 :+ (-1.80271), 1.0 :+ 1.0, 2.18108 :+ (-0.197289)],\n--          [1.84565 :+ (-1.99036), 1.0 :+ 1.0, 2.15435 :+ (-0.00964242)],\n--          [1.93958 :+ (-2.07773), 1.0 :+ 1.0, 2.06042 :+ 0.0777281],\n--          [2.0173  :+ (-2.06818), 1.0 :+ 1.0, 1.9827  :+ 0.0681793],\n--          [2.04357 :+ (-2.02437), 1.0 :+ 1.0, 1.95643 :+ 0.0243654],\n--          [2.03375 :+ (-1.99072), 1.0 :+ 1.0, 1.96625 :+ (-0.00928429)],\n--          [2.01245 :+ (-1.97875), 1.0 :+ 1.0, 1.98755 :+ (-0.0212528)],\n--          [1.99575 :+ (-1.98307), 1.0 :+ 1.0, 2.00425 :+ (-0.0169263)],\n--          [1.98938 :+ (-1.99359), 1.0 :+ 1.0, 2.01062 :+ (-0.00640583)],\n--          [1.99145 :+ (-2.00213), 1.0 :+ 1.0, 2.00855 :+ 0.00212504],\n--          [1.9968  :+ (-2.00535), 1.0 :+ 1.0, 2.0032  :+ 0.00535265],\n--          [2.00108 :+ (-2.00427), 1.0 :+ 1.0, 1.99892 :+ 0.0042723],\n--          [2.00268 :+ (-2.00159), 1.0 :+ 1.0, 1.99732 :+ 0.00158978],\n--          [2.00213 :+ (-1.99946), 1.0 :+ 1.0, 1.99787 :+ (-0.000541867)],\n--          [2.00079 :+ (-1.99866), 1.0 :+ 1.0, 1.9992  :+ (-0.00133514)],\n--          [1.99973 :+ (-1.99893), 1.0 :+ 1.0, 2.00027 :+ (-0.00106525)],\n--          [1.99933 :+ (-1.9996) , 1.0 :+ 1.0, 2.00067 :+ (-0.000397997)],\n--          [1.99947 :+ (-2.00013), 1.0 :+ 1.0, 2.00053 :+ 0.000134972]]\n\n--          The true eigenvalues are\n--          2 - 2i, 1 + i, 2\n-- 
    \n-- Some nonsymmetric real matrices have all real eigenvalues and\n-- our algorithm still works for such cases. Here is one\n-- such an example, which traditionally would have to be treated\n-- by one of the Lanczos-like algorithms, specifically designed\n-- for nonsymmetric real matrices. Evaluation of\n--
    \n-- \n-- iterated_eigenvalues [[2,1,1],[-2,1,3],[3,1,-1::Double]] 20\n-- \n--
    \n-- gives the following results\n--
    \n--         [[3.0,     -0.70818,-0.291815],\n--          [3.06743, -3.41538, 2.34795],\n--          [3.02238, -1.60013, 0.577753],\n--          [3.00746, -2.25793, 1.25047],\n--          [3.00248, -1.88764, 0.885154],\n--          [3.00083, -2.06025, 1.05943],\n--          [3.00028, -1.97098, 0.970702],\n--          [3.00009, -2.0148,  1.01471],\n--          [3.00003, -1.99268, 0.992648],\n--          [3.00001, -2.00368, 1.00367],\n--          [3.0,     -1.99817, 0.998161],\n--          [3.0,     -2.00092, 1.00092],\n--          [3.0,     -1.99954, 0.99954],\n--          [3.0,     -2.00023, 1.00023],\n--          [3.0,     -1.99989, 0.999885],\n--          [3.0,     -2.00006, 1.00006],\n--          [3.0,     -1.99997, 0.999971],\n--          [3.0,     -2.00001, 1.00001],\n--          [3.0,     -1.99999, 0.999993],\n--          [3.0,     -2.0,     1.0]]\n\n--          The true eigenvalues are:\n--          3, -2, 1\n-- 
    \n-- Finally, here is a case of a nonsymmetric real matrix with\n-- complex eigenvalues:\n--
    \n--         | 2 -3 |\n--         | 1  0 |\n-- 
    \n-- The direct application of \"iterated_eigenvalues\" would\n-- fail to produce expected eigenvalues:\n--
    \n--         1 + i sqrt(2) and 1 - i sqrt (2)\n-- 
    \n-- But if we first precondition the matrix by adding \"i\" to its diagonal:\n--
    \n--         | 2+i  -3|\n--         | 1     i|\n-- 
    \n-- and then compute its iterated eigenvalues:\n--
    \n-- \n-- iterated_eigenvalues [[2:+1,1],[-3,0:+1]] 20\n-- \n--
    \n-- then the method will succeed. Here are the results:\n--
    \n\n--         [[1.0     :+ 1.66667, 1.0     :+   0.333333 ],\n--         [0.600936 :+ 2.34977, 1.39906 :+ (-0.349766)],\n--         [0.998528 :+ 2.59355, 1.00147 :+ (-0.593555)],\n--         [1.06991  :+ 2.413,   0.93009 :+ (-0.412998)],\n--         [1.00021  :+ 2.38554, 0.99979 :+ (-0.385543)],\n--         [0.988004 :+ 2.41407, 1.012   :+ (-0.414074)],\n--         [0.999963 :+ 2.41919, 1.00004 :+ (-0.419191)],\n--         [1.00206  :+ 2.41423, 0.99794 :+ (-0.414227)],\n--         [1.00001  :+ 2.41336, 0.99999 :+ (-0.413361)],\n--         [0.999647 :+ 2.41421, 1.00035 :+ (-0.414211)],\n--         [0.999999 :+ 2.41436, 1.0     :+ (-0.41436) ],\n--         [1.00006  :+ 2.41421, 0.99993 :+ (-0.414214)],\n--         [1.0      :+ 2.41419, 1.0     :+ (-0.414188)],\n--         [0.99999  :+ 2.41421, 1.00001 :+ (-0.414213)],\n--         [1.0      :+ 2.41422, 1.0     :+ (-0.414218)],\n--         [1.0      :+ 2.41421, 0.99999 :+ (-0.414213)],\n--         [1.0      :+ 2.41421, 1.0     :+ (-0.414212)],\n--         [1.0      :+ 2.41421, 1.0     :+ (-0.414213)],\n--         [1.0      :+ 2.41421, 1.0     :+ (-0.414213)],\n--         [1.0      :+ 2.41421, 1.0     :+ (-0.414213)]]\n-- 
    \n-- After subtracting \"i\" from the last result, we will get\n-- what is expected.\n\n--

    \n--


    \n--

    \n-- \n-- Eigenvectors for distinct eigenvalues\n-- \n--

    \n-- Assuming that eigenvalues of matrix A are already found\n-- we may now attempt to find the corresponding aigenvectors\n-- by solving the following homogeneous equation\n--

    \n--         (A - a I) | x > = 0\n-- 
    \n-- for each eigenvalue \"a\". The matrix\n--
    \n--         B = A - a I\n-- 
    \n-- is by definition singular, but in most cases it can be\n-- triangularized by the familiar \"factors_QR\" procedure.\n--
    \n--         B | x > = Q R | x > = 0\n-- 
    \n-- It follows that the unknown eigenvector | x > is one of\n-- the solutions of the homogeneous equation:\n\n--
    \n--         R | x > = 0\n-- 
    \n-- where R is a singular, upper triangular matrix with at least one\n-- zero on its diagonal.\n--
    \n-- If | x > is a solution we seek, so is its scaled version\n-- alpha | x >. Therefore we have some freedom of scaling choice.\n-- Since this is a homogeneous equation, one of the components\n-- of | x > can be freely chosen, while the remaining components\n-- will depend on that choice.\n-- \n-- To solve the above, we will be working from the bottom up of\n-- the matrix equation, as illustrated in the example below:\n--
    \n--         | 0     1     1     3     | | x1 |\n--         | 0     1     1     2     | | x2 |      /\\\n--         | 0     0     2     4     | | x3 | = 0  ||\n--         | 0     0     0     0     | | x4 |      ||\n-- 
    \n-- Recall that the diagonal elements of any triangular matrix\n-- are its eigenvalues.\n-- Our example matrix has three distinct eigenvalues:\n-- 0, 1, 2. The eigenvalue 0 has degree of degeneration two.\n-- Presence of degenerated eigenvalues complicates\n-- the solution process. The complication arises when we have to\n-- make our decision about how to solve the trivial scalar equations\n-- with zero coefficients, such as\n--
    \n--         0 * x4 = 0\n-- 
    \n-- resulting from multiplication of the bottom row by vector | x >.\n-- Here we have two choices: \"x4\" could be set to 0, or to any\n-- nonzero number 1, say. By always choosing the \"0\" option\n-- we might end up with the all-zero trivial vector -- which is\n-- obviously not what we want. Persistent choice of the \"1\" option,\n-- might lead to a conflict between some of the equations, such as\n-- the equations one and four in our example.\n--

    \n-- So the strategy is as follows.\n--

    \n-- If there is at least one zero on the diagonal, find the topmost\n-- row with zero on the diagonal and choose for it the solution \"1\".\n-- Diagonal zeros in other rows would force the solution \"0\".\n-- If the diagonal element is not zero than simply solve\n-- an arithmetic equation that arises from the substitutions of\n-- previously computed components of the eigenvector. Since certain\n-- inaccuracies acumulate during QR factorization, set to zero all\n-- very small elements of matrix R.\n--

    \n-- By applying this strategy to our example we'll end up with the\n-- eigenvector\n--

    \n--         < x | = [1, 0, 0, 0]\n-- 
    \n\n--

    \n-- If the degree of degeneration of an eigenvalue of A is 1 then the\n-- corresponding eigenvector is unique -- subject to scaling.\n-- Otherwise an eigenvector found by this method is one of many\n-- possible solutions, and any linear combination of such solutions\n-- is also an eigenvector. This method is not able to find more than one\n-- solution for degenerated eigenvalues. An alternative method, which\n-- handles degenerated cases, will be described in the next section.\n--

    \n-- The function below calculates eigenvectors corresponding to\n-- distinct selected eigenvalues of any square matrix A, provided\n-- that the singular matrix B = A - a I can still be factorized as Q R,\n-- where R is an upper triangular matrix.\n\n--

    \n\n eigenkets :: (Scalar a, Fractional a) => [[a]] -> [a] -> [[a]]\n eigenkets a u\n       --\n       -- List of eigenkets of a square matrix A\n       -- where\n       --     a is a list of columns of A\n       --     u is a list of eigenvalues of A\n       --     (This list does not need to be complete)\n       --\n       | null u        = []\n       | not (null x') = x':(eigenkets a (tail u))\n       | otherwise     = (eigenket_UT (reverse b) d []):(eigenkets a (tail u))\n       where\n           a'  = add_to_diagonal (-(head u)) a\n           x'  = unit_ket a' 0 (length a')\n           b   = snd (factors_QR a')\n           d   = discriminant [head bk | bk <- b] 1\n           discriminant v n\n               | null v    = []\n               | otherwise = x : (discriminant (tail v) m)\n               where\n                   (x, m)\n                       | (head u) == 0     = (n, 0)\n                       | otherwise         = (n, n)\n           eigenket_UT c e xs\n               | null c    = xs\n               | otherwise = eigenket_UT (tail c) (tail e) (x:xs)\n               where\n                   x = solve_row (head c) (head e) xs\n\n           solve_row (v:vs) n x\n               | almostZero v = n\n               | otherwise    = q/v\n               where\n                   q\n                       | null x = 0\n                       | otherwise = -(sum_product vs x)\n\n           unit_ket b' m n\n               | null b'              = []\n               | all (== 0) (head b') = unit_vector m n\n               | otherwise            = unit_ket (tail b') (m+1) n\n\n-- 
    \n--

    \n--


    \n--

    \n-- \n-- Eigenvectors for degenerated eigenvalues\n-- \n--

    \n-- Few facts:\n--

      \n--
    • \n-- Eigenvectors of a general matrix A, which does not have any\n-- special symmetry, are not generally orthogonal. However, they\n-- are orthogonal, or can be made orthogonal, to another set of\n-- vectors that are eigenvectors of adjoint matrix A+;\n-- that is the matrix obtained by complex conjugation and transposition\n-- of matrix A.\n--
    • \n-- Eigenvectors corresponding to nondegenerated eigenvalues of\n-- hermitian or symmetric matrix are orthogonal.\n--
    • \n-- Eigenvectors corresponding to degenerated eigenvalues are - in\n-- general - neither orthogonal among themselves, nor orthogonal\n-- to the remaining eigenvectors corresponding to other\n-- eigenvalues. But since any linear combination of such degenerated\n-- eigenvectors is also an eigenvector, we can orthogonalize\n-- them by Gram-Schmidt orthogonalization procedure.\n--
    \n-- Many practical applications deal solely with hermitian\n-- or symmetric matrices, and for such cases the orthogonalization\n-- is not only possible, but also desired for variety of reasons.\n--
    \n-- But the method presented in the previous section is not able\n-- to find more than one eigenvector corresponding to a degenerated\n-- eigenvalue. For example, the symmetric matrix\n--
    \n--             |  7  -2   1 |\n--         A = | -2  10  -2 |\n--             |  1  -2   7 |\n-- 
    \n-- has two distinct eigenvalues: 12 and 6 -- the latter\n-- being degenerated with degree of two. Two corresponding\n-- eigenvectors are:\n--
    \n--         < x1 | = [1, -2, 1] -- for 12\n--         < x2 | = [1,  1, 1] -- for 6\n-- 
    \n-- It happens that those vectors are orthogonal, but this is\n-- just an accidental result. However, we are missing a third\n-- distinct eigenvector. To find it we need another method.\n-- One possibility is presented below and the explanation\n-- follows.\n--
    \n\n eigenket' :: (Scalar a, Fractional a) => [[a]] -> a -> a -> [a] -> [a]\n eigenket' a alpha eps x' =\n       --\n       -- Eigenket of matrix A corresponding to eigenvalue alpha\n       -- where\n       --     a is a list of columns of matrix A\n       --     eps is a trial inaccuracy factor\n       --         artificially introduced to cope\n       --         with singularities of A - alpha I.\n       --         One might try eps = 0, 0.00001, 0.001, etc.\n       --     x' is a trial eigenvector\n       --\n       scaled [xk' - dk | (xk', dk) <- zip x' d]\n       where\n           b = add_to_diagonal (-alpha*(1+eps)) a\n           d = one_ket_solution b y\n           y = matrix_ket (transposed b) x'\n\n-- 
    \n-- Let us assume a trial vector | x' >, such that\n--
    \n--         | x' > = | x > + | d >\n--         where\n--             | x > is an eigenvector we seek\n--             | d > is an error of our estimation of | x >\n-- 
    \n-- We first form a matrix B, such that:\n--
    \n--         B = A - alpha I\n-- 
    \n-- and multiply it by the trial vector | x' >, which\n-- results in a vector | y >\n--
    \n--         B | x' > = |y >\n-- 
    \n-- On another hand:\n--
    \n--         B | x' > = B | x > + B | d > = B | d >\n--         because\n--             B | x > = A | x > - alpha | x > = 0\n-- 
    \n-- Comparing both equations we end up with:\n--
    \n--         B | d > = | y >\n-- 
    \n-- that is: with the system of linear equations for unknown error | d >.\n-- Finally, we subtract error | d > from our trial vector | x' >\n-- to obtain the true eigenvector | x >.\n--

    \n-- But there is some problem with this approach: matrix B is\n-- by definition singular, and as such, it might be difficult\n-- to handle. One of the two processes might fail, and their failures\n-- relate to division by zero that might happen during either the\n-- QR factorization, or the solution of the triangular system of equations.\n--

    \n-- But if we do not insist that matrix B should be exactly singular,\n-- but almost singular:\n--

    \n--         B = A - alpha (1 + eps) I\n-- 
    \n-- then this method might succeed. However, the resulting eigenvector\n-- will be the approximation only, and we would have to experiment\n-- a bit with different values of \"eps\" to extrapolate the true\n-- eigenvector.\n--

    \n-- The trial vector | x' > can be chosen randomly, although some\n-- choices would still lead to singularity problems. Aside from\n-- this, this method is quite versatile, because:\n--

      \n--
    • \n-- Any random vector | x' > leads to the same eigenvector\n-- for nondegenerated eigenvalues,\n--
    • \n-- Different random vectors | x' >, chosen for degenerated\n-- eigenvalues, produce -- in most cases -- distinct eigenvectors.\n-- And this is what we want. If we need it, we can the always\n-- orthogonalize those eigenvectors either internally (always\n-- possible) or externally as well (possible only for hermitian\n-- or symmetric matrices).\n--
    \n-- It might be instructive to compute the eigenvectors for\n-- the examples used in demonstration of computation of eigenvalues.\n-- We'll leave to the reader, since this module is already too obese.\n--

    \n--


    \n--

    \n-- \n-- Auxiliary functions\n-- \n--

    \n-- The functions below are used in the main algorithms of\n-- this module. But they can be also used for testing. For example,\n-- the easiest way to test the usage of resources is to use easily\n-- definable unit matrices and unit vectors, as in:\n\n--

    \n--         one_ket_solution (unit_matrix n::[[Double]])\n--                          (unit_vector 0 n::[Double])\n--         where n = 20, etc.\n\n\n unit_matrix :: Num a => Int -> [[a]]\n unit_matrix m =\n       --\n       -- Unit square matrix of with dimensions m x m\n       --\n       [ [ if j==k then 1 else 0 | j <- [0 .. m-1] ] | k <- [0 .. m-1]]\n\n unit_vector :: Num a => Int -> Int -> [a]\n unit_vector i m =\n       --\n       -- Unit vector of length m\n       -- with 1 at position i, zero otherwise\n       map (\\k -> if k==i then 1 else 0) [0 .. m-1]\n\n diagonals :: [[a]] -> [a]\n diagonals a =\n       --\n       -- Vector made of diagonal components\n       -- of square matrix a\n       --\n       diagonals' a 0\n       where\n           diagonals' b n\n               | null b = []\n               | otherwise =\n                   (head $ drop n $ head b) : (diagonals' (tail b) (n+1))\n\n\n-- 
    \n\n--
    \n-- -----------------------------------------------------------------------------\n-- --\n-- -- Copyright:\n-- --\n-- --      (C) 1998 Numeric Quest Inc., All rights reserved\n-- --\n-- -- Email:\n-- --\n-- --      jans@numeric-quest.com\n-- --\n-- -- License:\n-- --\n-- --      GNU General Public License, GPL\n-- --\n-- -----------------------------------------------------------------------------\n-- 
    \n--
\n-- \n\n-- \n-- \n", "meta": {"hexsha": "a54d8b00f0d433b414de1bfd766b5ffd6e12f7fe", "size": 65137, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Orthogonals.hs", "max_stars_repo_name": "rzil/wLPAs", "max_stars_repo_head_hexsha": "d8cde11e4ff40c802d1f79d423f0e676ccd49d59", "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/Orthogonals.hs", "max_issues_repo_name": "rzil/wLPAs", "max_issues_repo_head_hexsha": "d8cde11e4ff40c802d1f79d423f0e676ccd49d59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Orthogonals.hs", "max_forks_repo_name": "rzil/wLPAs", "max_forks_repo_head_hexsha": "d8cde11e4ff40c802d1f79d423f0e676ccd49d59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9634997316, "max_line_length": 128, "alphanum_fraction": 0.5438076669, "num_tokens": 18609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5598874290232695}} {"text": "import Data.Complex\nimport Data.Ratio\nimport Data.List\n-- | We need to import \"list\" for intercalate, it will be needed later\n\n-- | A regular mathematical integer (real whole number)\nn0 :: Int\nn0 = 5\n\n-- | Decimal Number\nn1 :: Double\nn1 = 5\n\n-- | Decimal complex number x + yi\nn2 :: Complex Double\nn2 = 2 :+ 3\n\n-- | A simple ratio of two arbitrary-precision rational numbers\nn3 :: Ratio Int\nn3 = 2 % 3\n\n-- | A standard char.. char uses single quotes\nchar0 :: Char\nchar0 = 'X'\n\n-- | A decimal unicode char\nchar1 :: Char\nchar1 = '\\0088'\n\n-- | A hexidecimal unicode char\nchar2 :: Char\nchar2 = '\\x0058'\n\n-- | A octal unicode char\nchar3 :: Char\nchar3 = '\\o0130'\n\n-- | A standard string\nstring0 :: String\nstring0 = \"This is a string\"\n\n-- | A combination of char representations forming a string.. strings require double quotes\nstring1 :: String\nstring1 = \"\\088\\x0058\\o00130\"\n\n-- | Lists are declared by placing [ ] around the type\nintList :: [Int]\nintList = [1,2,3,4,5]\n\nstringList :: [String]\nstringList = [\"abc\",\"r\",\"c\"] -- | This is not legal => [\"abc\", 'a', \"c\"] because the a is a Char\n\n-- | A list of chars can just be a string\ncharList :: [Char]\ncharList = \"abcd\"\n-- | It can also be a standard list of chars => charList = ['a', 'b', 'c', 'd']\n\n-- | Another interesting list is an infinite list\ninfiniteList :: [Int]\ninfiniteList = [1..]\n\nboundedList :: [Int]\nboundedList = [1..10]\n\n-- | Count by steps list .. provide the first two values, and then it will \"step\" the difference to the limit you set as the third\n-- | The following will step by fours(5-1) till <=100.. so this will end at 97\nsteppedList :: [Int]\nsteppedList = [1,5..97]\n\n-- | Tuples don't have to be the same types, they can combine any of the types to create a pair,triplet, or nested tuples in tuples\ncoolTuple :: (([Int], String), ([Float], [Char]))\ncoolTuple = (([1,2,3], \"This is the tuple\"), ([11.0,2.455], \"Remember the charlist trick?\")) -- | This might be the `trouble with tuples`\n\n-- | Functions can be created with types as well\ngetStringLength :: String -> Int -- | Takes a string, gives an int\ngetStringLength = length\n\ngetStringAndLength :: String -> (String, Int) -- | Takes a string, gives the string and an int\ngetStringAndLength arg = (arg, length arg)\n\ngetStringsAndLengths :: [String] -> [(String, Int)] -- | Takes a string, gives the string and an int\ngetStringsAndLengths = map getStringAndLength\n\n-- | You know what we need is more arrows.. lets get some\n-- |listFormatter :: String -> String -> String -> [String] -> String\nlistFormatter :: String -> (String -> (String -> ([String] -> String))) -- | Can fully paranthsise and its still valid\nlistFormatter start end joiner stringList = start ++ (intercalate joiner (map show stringList)) ++ end -- | need to know more about \"show\"\n\n-- | Polymorphism\nmapping :: (a -> b) -> [a] -> [b]\nmapping _ [] = []\nmapping f (a:as) = f a : mapping f as -- | : constricting list\n-- | The above function is polymorphic because it behaves thee same, no matter which types you provide\n-- | I believe this is called parametric polymorphism.. alternatively there is \"bounded\" or \"ad hoc\" polymorphism in which you can overload the function for different argument types\n\n-- | A little more about constraints\nfolder :: (a -> b -> b) -> b -> [a] -> b\nfolder _ b [] = b\nfolder f b (a:as) = folder f (f a b) as\n\n-- | we can call folder likee this => print $ folder (+) 0 [1,2,3]\n-- | but thanks to referential transparency, we can also create a \"variable\" for `folder (+) 0` and make it a little simpler\nsummer = folder (+) 0\ncallFolder = summer [1,2,3]\n-- | Then we can just call `print $ callFolder`... ru-ru-ru-REFERENTIAL TRANSPARENCY!!!\n-- | We didn't define a type for summer, since the use of the (+) constrains it, this is a little complicated and I don't fully understand it\n-- | However a cool trick to figure out a suitable type signature would be to use the typed hole\n-- | summer :: _\n-- | On compile this will throw an error, but will also suggest a suitable type sig... Something like \"Found type wildcard `_` standing for `[Integer] -> Integer`\n-- | probably better not to be lazy though.. since this is at best a \"guess\"\n-- | using this for summer will allow the program to compile correctly... TYPED HOLE!\n-- | Further reading => https://wiki.haskell.org/Data_declaration_with_constraint\n\n\n\nmain :: IO ()\nmain = do\n print n0\n print n1\n print n2\n print n3\n print char0\n print char1\n print char2\n print char3\n print string0\n print string1\n print intList\n print stringList\n print charList\n-- | print infiniteList -- | probably shouldnt try to print this :p .. actually I did, nothing that a little CTRL+c won't fix\n print (take 20 infiniteList) -- | Cool trick to print only the first 20 of the infinite list\n print boundedList\n print steppedList\n print coolTuple\n -- | This syntax \"applies\" these functions to \"arguments\" and prints the results, since these functions don't have a \"show\"\n print $ getStringLength \"How long is this thing anyway?\"\n print $ getStringAndLength \"How long is this thing anyway?\"\n print $ getStringsAndLengths [\"How\", \"long\", \"are\", \"these\", \"things\", \"anyway\"]\n putStrLn $ listFormatter \"\" \"\" \"|\" [\"First element\", \"Second element\", \"Third element\"]\n print $ mapping show [\"This is 1\", \"This is 2\", \"3\"]\n -- | This will break by mixing datatypes => print $ mapping show ['1', \"string\"] \n print $ callFolder\n", "meta": {"hexsha": "82b75a3d7616050a1f75994ebe8e1f6c7c562ab9", "size": 5412, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Datatypes.hs", "max_stars_repo_name": "csawtelle/functional-haskell", "max_stars_repo_head_hexsha": "ec96edac669ad898f38454777d91709661210b85", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Datatypes.hs", "max_issues_repo_name": "csawtelle/functional-haskell", "max_issues_repo_head_hexsha": "ec96edac669ad898f38454777d91709661210b85", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Datatypes.hs", "max_forks_repo_name": "csawtelle/functional-haskell", "max_forks_repo_head_hexsha": "ec96edac669ad898f38454777d91709661210b85", "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.5833333333, "max_line_length": 181, "alphanum_fraction": 0.6851441242, "num_tokens": 1507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.5597623156504934}} {"text": "{-# LANGUAGE TemplateHaskell, OverloadedLists, DeriveGeneric, DeriveAnyClass, Strict #-}\n\nmodule Data.PhysicsData where\n\nimport Control.Lens hiding (indices)\nimport Number.Quaternion (T)\nimport Numeric.LinearAlgebra (Matrix, Vector,(><), scale)\n\nimport Utils.Quaternions\nimport Control.DeepSeq\nimport GHC.Generics\nimport Control.Arrow\n\nimport Physics.Collision\n\ndata PhysicsData = PhysicsData {\n _acc :: Vector Float,\n _speed :: Vector Float,\n _inertiaD :: Matrix Float,\n _massInv :: Float,\n _inertiaInv :: Matrix Float,\n _angularS :: Vector Float,\n _torque :: Vector Float } deriving Show\n\nmakeLenses ''PhysicsData\n\ndefaultInertiaDiag :: Float -> Matrix Float\ndefaultInertiaDiag m =\n (3><3)[ m, 0, 0\n , 0, m, 0\n , 0, 0, m ]\n\n\nsetRectInertia x y z m = set inertiaD . scale (m/12) $\n (3><3) [(x^2+z^2), 0, 0\n , 0, (x^2+z^2), 0\n , 0, 0, (x^2+y^2)]\n\ncarPhysics =\n setRectInertia 1 1 10 &&& startPhysics >>> uncurry (.)\n\nstartPhysics :: Float -> T Float -> PhysicsData\nstartPhysics mInv quat =\n PhysicsData { _acc = [0,0,0]\n , _speed = [0,0,0]\n , _inertiaD = defaultInertiaDiag (1/mInv)\n , _massInv = mInv\n , _inertiaInv = quatToLInv (defaultInertiaDiag (1/mInv)) quat\n , _angularS = [0,0,0]\n , _torque = [0,0,0] }\n", "meta": {"hexsha": "397071e1447e81aa8141c9ab54ec204026cffa0d", "size": 1455, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/PhysicsData.hs", "max_stars_repo_name": "Antystenes/CPG", "max_stars_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/PhysicsData.hs", "max_issues_repo_name": "Antystenes/CPG", "max_issues_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/PhysicsData.hs", "max_forks_repo_name": "Antystenes/CPG", "max_forks_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5294117647, "max_line_length": 88, "alphanum_fraction": 0.5766323024, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5597200252579668}} {"text": "module Scene.Object.Plane where\n \nimport Scene.Base\nimport Math.Color\nimport Math.Ray\nimport Numeric.LinearAlgebra\n\n-- Sphere\nplane' :: Material -> Ray -> Object\nplane' mat r = Object (plane_intercept r) mat\n\nplane mat ray = [plane' mat ray]\n\nplane_intercept :: Ray -> Ray -> Maybe (Double,Ray)\nplane_intercept (Ray p normal) incidence@(Ray q v) =\n let\n v_orth = v <.> normal\n pq_orth = (p-q) <.> normal\n lambda = pq_orth / v_orth\n in if lambda > 0\n then Just (lambda, Ray (parametric incidence lambda) (scale (-signum (v_orth)) normal))\n else Nothing", "meta": {"hexsha": "33a255bfcf1950698314e1fd7fe17f11aaf836b0", "size": 595, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Scene/Object/Plane.hs", "max_stars_repo_name": "danrocag/raytracer", "max_stars_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Scene/Object/Plane.hs", "max_issues_repo_name": "danrocag/raytracer", "max_issues_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Scene/Object/Plane.hs", "max_forks_repo_name": "danrocag/raytracer", "max_forks_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0454545455, "max_line_length": 95, "alphanum_fraction": 0.6571428571, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5597177239601364}} {"text": "module Network.Mux.DeltaQ.TraceStatsSupport where\n\n-- This module is making use of hackage statisitical libraries. They\n-- are not the most efficicient approches for this particlular use\n-- case, and they may increase the package dependencies for the final\n-- binaries (they have a lot of dependencies).\n--\n-- It may well be worthwhile constructing specialsed version for the\n-- specific use case, but building those and creating the associated\n-- test suite was not deemed a good use of time (at the time of\n-- creation).\n--\n-- Definite space/time optimisation task here.\n\nimport Network.Mux.DeltaQ.TraceTypes\n\nimport qualified Data.Vector.Unboxed as V\nimport Statistics.LinearRegression\n\nestimateGS :: [(Int, SISec)] -> (Double, Double, Double)\nestimateGS xys\n = let (xs', ys') = unzip xys\n xs = V.fromList $ map fromIntegral xs'\n ys = V.fromList $ map (\\(S x) -> fromRational . toRational $ x) ys'\n in linearRegressionRSqr xs ys\n", "meta": {"hexsha": "0bb6a678b04958209a31905963541a917072576e", "size": 970, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "network-mux/src/Network/Mux/DeltaQ/TraceStatsSupport.hs", "max_stars_repo_name": "RyanGlScott/ouroboros-network", "max_stars_repo_head_hexsha": "85b06a74c7b895c5412ba2ac8a43b9c264ad7957", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-26T15:04:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T15:04:41.000Z", "max_issues_repo_path": "network-mux/src/Network/Mux/DeltaQ/TraceStatsSupport.hs", "max_issues_repo_name": "RyanGlScott/ouroboros-network", "max_issues_repo_head_hexsha": "85b06a74c7b895c5412ba2ac8a43b9c264ad7957", "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": "network-mux/src/Network/Mux/DeltaQ/TraceStatsSupport.hs", "max_forks_repo_name": "RyanGlScott/ouroboros-network", "max_forks_repo_head_hexsha": "85b06a74c7b895c5412ba2ac8a43b9c264ad7957", "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": 37.3076923077, "max_line_length": 75, "alphanum_fraction": 0.7237113402, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5596358781250581}} {"text": "module FFT.DFTControl (\n dcdft,\n nesteddcdft,\n tfdft,\n nestedtfdft\n) where\nimport Data.Complex\nimport FFT.Samples\nimport System.Environment\nimport Control.Parallel\nimport Strategies\nimport Criterion.Main\nimport FFT.Orig\n\n-- twiddle factors\ntw :: Int -> Int -> Complex Float\ntw n k = cis (-2 * pi * fromIntegral k / fromIntegral n)\n\ndcdft [] = []\ndcdft xs = dc split threshold combine worker [0..n']\n where\n n = length xs\n n' = n-1\n worker = map workerInner\n where workerInner k = [sum (map (\\j -> xs!!j * tw n (j*k)) [0..n'])]\n combine = concat\n threshold = (\\x -> length x < (floor $ sqrt $ fromIntegral n'))\n split l = [front, back]\n where\n front = take p l\n back = drop p l\n p = length l `div` 2\n\nnesteddcdft [] = []\nnesteddcdft xs = dc split threshold combine worker [0..n']\n where\n n = length xs\n n' = n-1\n worker = map workerInner\n where workerInner k = [sum (dc split threshold combine (jWorker k) [0..n'])]\n where jWorker k = map (\\j -> [xs!!j * tw n (j*k)])\n combine = concat\n threshold = (\\x -> length x < (floor $ sqrt $ fromIntegral n'))\n split l = [front, back]\n where\n front = take p l\n back = drop p l\n p = length l `div` 2\n\ntfdft [] = []\ntfdft xs = taskfarm worker numWorkers [0..n']\n where\n n = length xs\n n' = n-1\n numWorkers = (floor $ sqrt $ fromIntegral n')\n worker k = [sum [ xs!!j * tw n (j*k) | j <- [0..n']]]\n\nnestedtfdft [] = []\nnestedtfdft xs = taskfarm worker numWorkers [0..n']\n where\n n = length xs\n n' = n-1\n numWorkers = (floor $ sqrt $ fromIntegral n')\n worker k = [foldr (+) (0 :+ 0) (concat (taskfarm (innerWorker k) numWorkers [0..n']))]\n where\n innerWorker k j = [xs!!j * tw n (j*k)]\n", "meta": {"hexsha": "c23a161a00118df72c8ccf8f0fec983ed53a4fd7", "size": 1824, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FFT/DFTControl.hs", "max_stars_repo_name": "BNJHope/parallel-fourier-transforms", "max_stars_repo_head_hexsha": "274ec189ed99715c4a912659683c0f93c0628a72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FFT/DFTControl.hs", "max_issues_repo_name": "BNJHope/parallel-fourier-transforms", "max_issues_repo_head_hexsha": "274ec189ed99715c4a912659683c0f93c0628a72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FFT/DFTControl.hs", "max_forks_repo_name": "BNJHope/parallel-fourier-transforms", "max_forks_repo_head_hexsha": "274ec189ed99715c4a912659683c0f93c0628a72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.223880597, "max_line_length": 90, "alphanum_fraction": 0.5646929825, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5593220362736168}} {"text": "module Cas.Internal.Def.Interface\n ( module Cas.Internal.Def.Interface\n , module ReEx\n ) where\n\nimport Data.List\nimport Cas.Misc\nimport PreludeCustom\nimport Cas.Internal.Def as ReEx\nimport Data.Complex.Generic\n\ncPi, cE :: T\ncPi = TC Pi\ncE = TC E\n\nf :: F -> T\nf = TF\n\ni = TF (imag 1) :: T\n\nzeroF, oneF, aInvOneF :: F\n(zeroF, oneF, aInvOneF ) = (0, 1, (-1))\n\nzero, one, aInvOne :: T\n(zero, one, aInvOne) = (f 0, f 1, f (-1))\n\nx :: Int -> T\nx = TX . X\n\n_x :: Int -> X\n_x = X\n\nadd, mul :: [T] -> T\nadd ts' = case length ts of\n 0 -> zero\n 1 -> head ts\n _ -> TAdd $ Add ts\n where\n ts = filter (not . isZero) ts'\n\nmul ts'' = case length ts of\n 0 -> one\n 1 -> head ts\n _ -> TMul $ Mul ts\n where\n ts' = filter (not . isOne) ts''\n ts = if elem zero ts'' then [zero] else ts'\n\naddBin, mulBin,sub, pow :: T -> T -> T\naddBin x y = add [x,y]\nmulBin x y = mul [x,y]\nsub x y = addBin x (aInv y)\npow = TPow\n\naddRaw = TAdd . Add\nmulRaw = TMul . Mul\nln :: T -> T\nln = TLn\n\naInv :: T -> T\naInv = mul . (:[aInvOne])\n\nmInv :: T -> T\nmInv = flip pow aInvOne\n\ntAddTs, tMulTs :: T -> [T]\n\ntXI = xI . tX\ntAddTs = addTs . tAdd\ntMulTs = mulTs . tMul\n\n\nisZeroF, isOneF :: F -> Bool\nisZero, isOne, isC, isF, isX, isAdd, isMul, isLeaf, isFlat :: T -> Bool\nisThisX :: X -> T -> Bool\n\nisZero = (==zero)\nisZeroF = (==zeroF)\nisOne = (==one)\nisOneF = (==oneF)\nisC = \\case (TC _) -> True; _ -> False\nisF = \\case (TF _) -> True; _ -> False\nisX = \\case (TX _) -> True; _ -> False\nisThisX x = \\case (TX y) -> x==y; _ -> False\nisAdd = \\case (TAdd _) -> True; _ -> False\nisMul = \\case (TMul _) -> True; _ -> False\nisPow = \\case (TPow _ _) -> True; _ -> False\nisLn = \\case (TLn _) -> True; _ -> False\n\n\n\nisLeaf = or . ([isF, isC, isX,isLn] <*>) . return\nisNonFLeaf = or . ([isX, isC, isLn] <*>) . return\nisOper = or . ([isAdd, isMul, isPow] <*>) . return\n\nisFlat = isAdd ?>>> all (not . isAdd) . tAddTs\n ||> isMul ?>>- all (not . isMul) . tMulTs\n ||> True\n\n\nsimpleShow :: T -> String\nsimpleShow TC {..} = show $ tC\nsimpleShow t@TF {..} = wrap $ showF tF\nsimpleShow t@TX {..} = \"x\" <> show ( tXI t)\nsimpleShow t@TAdd {..} = wrap $ intercalate \"+\" $ fmap simpleShow (tAddTs t)\nsimpleShow t@TMul {..} = wrap $ intercalate \"*\" $ fmap simpleShow (tMulTs t)\nsimpleShow t@TPow {..} = wrap $ simpleShow tPowB <> \"^\" <> simpleShow tPowE\nsimpleShow t@TLn {..} = wrap $ \"ln \" <> simpleShow tLnT\n\n(+:+) z w = TF $ z :+ w\n\neqType :: T -> T -> Bool\neqType (TF _) (TF _) = True\neqType (TX _) (TX _) = True\neqType (TC _) (TC _) = True\neqType (TAdd _) (TAdd _) = True\neqType (TMul _) (TMul _) = True\neqType (TPow _ _) (TPow _ _) = True\neqType (TLn _) (TLn _) = True\neqType t r = False\n\n", "meta": {"hexsha": "a9526f7b889cf9e5d3fe6d44ee084bc1c9dc6941", "size": 2873, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Cas/Internal/Def/Interface.hs", "max_stars_repo_name": "vcanadi/cas", "max_stars_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-20T22:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-20T22:42:53.000Z", "max_issues_repo_path": "src/Cas/Internal/Def/Interface.hs", "max_issues_repo_name": "vcanadi/cas", "max_issues_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Cas/Internal/Def/Interface.hs", "max_forks_repo_name": "vcanadi/cas", "max_forks_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5491803279, "max_line_length": 77, "alphanum_fraction": 0.5280194918, "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5593035554440704}} {"text": "{-# LANGUAGE RecordWildCards #-}\n\nmodule Numeric.Solver where\n\nimport Control.Exception\nimport Data.Function\nimport Data.List\nimport qualified Data.Vector.Storable as Storable\nimport Numeric.GSL.ODE\nimport Numeric.LinearAlgebra.Data\nimport Numeric.SSystem\nimport Text.Parse.ODEBench\n\ntype Objective = SSystem Double -> Double\n\nlogLikelihood :: Matrix Double -- ^ Observed values\n -> Matrix Double -- ^ Standard deviations\n -> Matrix Double -- ^ Simulated values\n -> Double\nlogLikelihood o d s =\n (-0.5) * Storable.sum\n (Storable.zipWith3 ll\n (flatten o)\n (flatten d)\n (flatten s))\n where ll obs stddev sim = ((sim - obs) / stddev) ** 2\n\ndata Experiment = Experiment\n { times :: Storable.Vector Double\n , initalVals :: [Double]\n , observedVals :: Matrix Double\n , observedStddevs :: Matrix Double }\n\nexperiments :: Problem -> [Experiment]\nexperiments = map toExpr . groupBy ((==) `on` experimentNum) . samples where\n toExpr = Experiment <$> Storable.fromList . map time\n <*> Storable.toList . values . head\n <*> fromRows . map values\n <*> fromRows . map stdDevs\n\nsolve :: SSystem Double -> [Double] -> Storable.Vector Double -> Matrix Double\nsolve = odeSolve . const . toEqns'\n\nlikelihood :: [Experiment] -> Objective\nlikelihood exprs syst = foldl' (+) 0 (map f exprs) where\n f Experiment {..} =\n logLikelihood\n observedVals\n observedStddevs\n (solve syst initalVals times)\n\ntype SafeObjective = SSystem Double -> IO (Either SomeException Double)\n\nsafeLikelihood :: [Experiment] -> SafeObjective\nsafeLikelihood expr syst = (try . evaluate) (likelihood expr syst)\n\n-- | >>> testSolve exampleSystem [0.7,0.12,0.14,0.16,0.18] 6 (0,0.25)\n-- (6><5)\n-- [ 0.7, 0.12, 0.14, 0.16, 0.18\n-- , 1.1167718442535226, 0.5288004914151249, 0.9744853978475282, 1.0888238837276851, 0.40157122204470663\n-- , 0.9667747407434063, 0.827179819885076, 0.9938518679839954, 1.0925434854072784, 0.8240710601831301\n-- , 0.8394130067100113, 0.8627637078683361, 0.9980826732970266, 0.9920051282448126, 0.9522071825140638\n-- , 0.7765858895457368, 0.8274811279700081, 0.999411143907833, 0.943541476235036, 0.9572057285536645\n-- , 0.7499481576778694, 0.7905920430606405, 0.9998291350909083, 0.9281457408781921, 0.9424146353794791 ]\ntestSolve :: SSystem Double -> [Double] -> Int -> (Double,Double) -> Matrix Double\ntestSolve s t n i = solve s t (linspace n i)\n", "meta": {"hexsha": "c4bd661a75d359b39b8f8aeae662398c23f2fa06", "size": 2637, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Solver.hs", "max_stars_repo_name": "oisdk/SSystemOpt", "max_stars_repo_head_hexsha": "f95c6e5bf692da82d61ec53653770612246dd2db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/Solver.hs", "max_issues_repo_name": "oisdk/SSystemOpt", "max_issues_repo_head_hexsha": "f95c6e5bf692da82d61ec53653770612246dd2db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Solver.hs", "max_forks_repo_name": "oisdk/SSystemOpt", "max_forks_repo_head_hexsha": "f95c6e5bf692da82d61ec53653770612246dd2db", "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.3582089552, "max_line_length": 107, "alphanum_fraction": 0.6454304133, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.55922297402563}} {"text": "{-# LANGUAGE DataKinds #-}\nmodule Data.Array.RankedS.MatMul(matMul) where\nimport Prelude hiding ((<>))\nimport GHC.Stack\nimport Data.Array.RankedS\nimport Numeric.LinearAlgebra as N\n\nmatMul :: (HasCallStack, N.Numeric a) => Array 2 a -> Array 2 a -> Array 2 a\nmatMul x y =\n case (shapeL x, shapeL y) of\n ([m, n], [n', o]) | n == n' ->\n let x' = N.reshape n $ toVector x\n y' = N.reshape o $ toVector y\n xy' = x' N.<> y'\n xy = fromVector [m, o] $ N.flatten xy'\n in xy\n sz -> error $ \"matMul: expected two conforming two-dimensional arrays, got shape \" ++ show sz\n", "meta": {"hexsha": "c722dd341abd9271053a76a7775dd7dd03694e48", "size": 604, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Array/RankedS/MatMul.hs", "max_stars_repo_name": "augustss/orthotope-hmatrix", "max_stars_repo_head_hexsha": "4806a67ac5228ffc1dab317b3df2cda36d4679d6", "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": "Data/Array/RankedS/MatMul.hs", "max_issues_repo_name": "augustss/orthotope-hmatrix", "max_issues_repo_head_hexsha": "4806a67ac5228ffc1dab317b3df2cda36d4679d6", "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": "Data/Array/RankedS/MatMul.hs", "max_forks_repo_name": "augustss/orthotope-hmatrix", "max_forks_repo_head_hexsha": "4806a67ac5228ffc1dab317b3df2cda36d4679d6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5555555556, "max_line_length": 97, "alphanum_fraction": 0.6026490066, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985637, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5592229536657906}} {"text": "{-|\nModule : SmithDecomposition\nDescription : Descomposici\u00f3n de matrices para la resoluciones de sistemas de ecuaciones diof\u00e1nticas. Espec\u00edfico a la forma del sistema de ecuaciones asociado a la matriz de viajes.\n\nEste m\u00f3dulo no provee funciones generales para encontrar la Forma Normal de Smith, sino que genera los resultados basado en el patron regular del sistema.\n-}\nmodule ODMatrix.SmithDecomposition (\n computeODM\n --\n , systemMatrix\n , snfR\n --\n , vectorToODM\n , odmToVector\n --\n , tVectorSize\n -- Publish from Dimensions\n , srows\n , scols\n , nFromN\n , nFromM\n --\n , generalSolution\n ) where\n\n import Prelude hiding ((<>))\n \n import Numeric.LinearAlgebra as L \n\n import ODMatrix (ODM, FeatVec, toFlatList, fromFlatList)\n import Control.Monad (join)\n \n import ODMatrix.SmithDecomposition.SparseMat (SparseMat(SparseMat), denseSparseMat, makeAssoc)\n import ODMatrix.SmithDecomposition.Dimensions\n\n\n \n -- * Solution computation\n\n\n -- | Given a input vector and a t vector, computes a unique solution of the system.\n computeODM :: FeatVec -- ^ Input Vector\n -> FeatVec -- ^ t Vector\n -> ODM -- ^ Solution Matrix\n computeODM b t = vectorToODM $ r1b + r2 <> asColumn t\n where (r1b, r2) = generalSolution b\n\n\n -- | Given and input vector, computes the general solution of the system.\n -- This is a partial solution. The aplicaction of a t vector is needed to find a particular one.\n generalSolution :: FeatVec -- ^ Input Vector\n -> (ODM, ODM) -- ^ Solution Matrix\n generalSolution b = (r1 <> asColumn b, r2)\n where (r1, r2) = splitR $ snfR n\n n = nFromN $ size b\n\n\n -- * Smith's Decomposition\n \n -- | Given the size of the route, computes the system matrix.\n systemMatrix :: Int -> Matrix Double\n systemMatrix n = denseSparseMat $ SparseMat r c ab\n where r = srows n\n c = scols n\n a = zip (join $ map (\\x -> [x..n]) [1..n]) [1..c]\n b = zip (join $ map (\\x -> replicate (n-x) (n+x)) [1..n-1]) [n+1..c]\n ab = zip (a++b) $ repeat 1.0\n\n -- | Given the size of the route, computes the R matrix.\n snfR :: Int -> Matrix Double\n snfR n = stepA n <> stepB n <> stepC n\n\n \n stepA :: Int -> Matrix Double\n stepA n = accum (ident m) (+) as\n where as = makeAssoc (-1.0) $ zip sr [n+1..] \n m = scols n\n sr = join [[k..n] | k <- [2..n]]\n\n \n stepB :: Int -> Matrix Double\n stepB n = accum (ident m) (+) $ as\n where m = scols n\n as = makeAssoc (-1.0) $ sbs\n sbs = join . map (\\(p,k) -> zip [k,k..] [k+1..k+p]) . zip [n-2,n-3..1] $ ser n\n\n\n stepC :: Int -> Matrix Double\n stepC n = accum (ident m) (+) $ as ++ bs\n where m = scols n\n as = makeAssoc (-1.0) . join . map (\\(a,b) -> [(a,a),(b,b)]) $ swp\n bs = makeAssoc ( 1.0) . join . map (\\(a,b) -> [(a,b),(b,a)]) $ swp\n swp = tail . zip [n+1..] $ ser n\n\n \n ser :: Int -> [Int]\n ser n = foldl (\\(a:ac) x -> (a-x):a:ac) [scols n] [2..n-1]\n\n\n -- * Computation of the t-vector\n\n -- | The size of the t vector given the size of the route.\n tVectorSize :: Int -> Int\n tVectorSize n = scols n - srows n\n\n\n\n -- * Support Functions\n\n\n -- | Break the right matrix R, for the computation of the solution\n splitR :: Matrix Double -> (Matrix Double, Matrix Double)\n splitR r = (takeColumns n r, dropColumns n r)\n where n = srows . nFromM $ cols r\n\n\n \n -- | Transform a vector in column matrix form to a ODM\n vectorToODM :: Matrix Double -> ODM\n vectorToODM = fromFlatList . toList . flatten\n\n -- | Transform a ODM to vector in column matrix form\n odmToVector :: ODM -> Matrix Double\n odmToVector = matrix 1 . toFlatList\n\n\n\n\n ------------------------------------------------------------------------------------\n ------------------------------------------------------------------------------------\n ------------------------------------------------------------------------------------\n\n \n\n\n -- | Indices fila y columna de la matriz cuadrada triangular superior con la diagonal en cero, a partir del \u00edndice aplanado.\n --\n -- fromFlatIndex :: Int -- ^ Tama\u00f1o de la matriz\n -- -> Int -- ^ \u00cdndice plano\n -- -> (Int,Int) -- ^ (fila, columna)\n -- fromFlatIndex n k = as !! (k-1)\n -- where as = [1..n] >>= (\\x -> [(x,j) | j <- [x+1..n]])\n\n\n -- | Indice aplanado de la matriz cuadrada triangular superior con la diagonal en cero.\n --\n -- toFlatIndex :: Int -- ^ Tama\u00f1o de la matriz\n -- -> (Int, Int) -- ^ (fila, columna)\n -- -> Int -- ^ \u00cdndice plano\n -- toFlatIndex' n (r,c)\n -- | r >= c = 0\n -- | otherwise = fr r - n + c\n -- where fr 0 = 0\n -- fr r = fr (r-1) + n - r\n\n -- toFlatIndex n (r,c)\n -- | r >= c = 0\n -- | otherwise = fr r - n + c\n -- where fr r = (r * n) - (r * (r + 1) `div` 2)\n\n -- * Construcci\u00f3n de matriz del sistema\n\n -- upperCond :: Int -> Int -> Int -> R\n -- upperCond n k c\n -- | (i <= k) && (k < j) = 1\n -- | otherwise = 0\n -- where (i,j) = fromFlatIndex n c\n\n -- lowerCond :: Int -> Int -> Int -> R\n -- lowerCond n k c\n -- | (i == k+1) && (k+1 < j) = 1\n -- | otherwise = 0\n -- where (i,j) = fromFlatIndex n c\n\n\n\n -- partialSystemMatrix :: (Int -> Int -> Int -> R) -> Int -> Matrix R\n -- partialSystemMatrix c n = (rs> Matrix Double\n -- systemMatrix n = um === lm\n -- where um = partialSystemMatrix upperCond n\n -- lm = takeRows (n-2) $ partialSystemMatrix lowerCond n\n --\n --\n\n \n\n\n\n\n -- * System calculation\n\n \n\n -- | Fuck yeah!\n -- calculatorMachine :: Vector R -- ^ Input vector\n -- -> (Matrix R, Matrix R) -- ^ Two part calculator\n -- calculatorMachine b = (sub1, sub2)\n -- where n = nFromInputVector b\n -- (d,l,r) = snf n\n -- b' = asColumn b\n -- (r1,r2) = splitr n r\n -- sub1 = r1 <> l <> b'\n -- sub2 = r2\n\n \n -- calcODMatrix :: InputVector -- ^ Input Vector\n -- -> TVector -- ^ t Vector\n -- -> ODM -- ^ Solution Vector\n -- calcODMatrix b t = s1 + s2 <> asColumn t\n -- where (s1, s2) = calculatorMachine b\n\n\n -- | Validate the solution of the system Ax = b and that all values of the solution are positive integers.\n -- solutionValidation :: Vector R -- ^ Input Vector\n -- -> Vector R -- ^ Solution Vector\n -- -> Bool -- ^ True if validate.\n -- solutionValidation b x = p1 && p2\n -- where p1 = all (>= 0) $ toList x\n -- n = nFromInputVector b\n -- a = systemMatrix n\n -- p2 = a <> asColumn x == asColumn b\n\n\n\n\n\n\n -- tVectors :: Int -- ^ N\n -- -> Int -- ^ K\n -- -> [Vector R] -- ^ All possible t vectors. Not necessarilly for a valid solution.\n -- tVectors n k = tVectors' n k v0\n -- where ss = scols n - srows n\n -- v0 = vector $ replicate ss 0\n\n\n -- tVectors' :: Int -- ^ N\n -- -> Int -- ^ K\n -- -> Vector R -- ^ Initial vector for search.\n -- -> [Vector R] -- ^ All possible t vectors. Not necessarilly for a valid solution.\n -- tVectors' n k v0 = vector <$> list\n -- where list = iterate (nextc k) $ toList v0\n -- nextc k ls =\n -- let (t:ts) = dropWhile (== fromIntegral k) ls\n -- s = length ls - length (t:ts)\n -- h = replicate s 0\n -- in h ++ [t+1] ++ ts\n\n -- tVector :: Vector R -- ^ Input Vector\n -- -> Int -- ^ K\n -- -> Vector R -- ^ t Vector\n -- tVector b k = tVector' b k v0\n -- where n = srows' b\n -- v0 = vector $ replicate (tSize n) 0\n\n -- tVector' :: Vector R -- ^ Input Vector\n -- -> Int -- ^ K\n -- -> Vector R -- ^ Initial vector for search\n -- -> Vector R -- ^ t Vector\n -- tVector' b k v0 = head $ dropWhile cond $ tVectors' n k v0\n -- where n = nFromInputVector b\n -- cond t = validate k . solutionVectorToODMatrix . flatten $ calcODMatrix b t\n\n\n \n\n -- solutionVectorToODMatrix :: Vector R -> ODM\n -- solutionVectorToODMatrix = denseSparseMat . solutionVectorToSparseMat\n\n -- * System decomposition\n\n -- | Smith Normal Form\n -- Dado el tama\u00f1o N de una matriz de viajes A, retorna una tripla (D,L,R) donde D est\u00e1 en la Forma Normal de Smith y LAR = D.\n -- snf :: Int\n -- -> (Matrix R, Matrix R, Matrix R)\n -- snf n = (snfD n, snfL n, snfR n)\n -- --\n -- --\n -- snfD :: Int\n -- -> Matrix R\n -- snfD n = diagRect 0 (fromList $ replicate (srows n) 1) (srows n) (scols n)\n -- --\n -- --\n -- snfL :: Int\n -- -> Matrix R\n -- snfL = toDense . cells . sparseSnfL\n\n -- -- | Componente derecho de la descomposici\u00f3n de Smith.\n -- snfR :: Int\n -- -> Matrix R\n -- snfR = toDense . cells . sparseSnfR\n", "meta": {"hexsha": "8a497c2c1582e57a1df0981de46c6795a45cbc71", "size": 9087, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ODMatrix/SmithDecomposition.hs", "max_stars_repo_name": "renecura/odmatrix", "max_stars_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "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/ODMatrix/SmithDecomposition.hs", "max_issues_repo_name": "renecura/odmatrix", "max_issues_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "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/ODMatrix/SmithDecomposition.hs", "max_forks_repo_name": "renecura/odmatrix", "max_forks_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3913043478, "max_line_length": 180, "alphanum_fraction": 0.5198635413, "num_tokens": 2829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629215, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5592082891644432}} {"text": "module Main (main) where\n\nimport AI.HNN.FF.Network\nimport Data.List (maximumBy)\nimport Data.Ord (comparing)\nimport Data.Word (Word8)\nimport MnistLoader\nimport Numeric.LinearAlgebra\nimport Text.Printf\n\n\nmain :: IO ()\nmain = do\n (samples, validation) <- load_data_wrapper \"../data/\"\n net <- createNetwork 784 [30] 10\n let net' = trainNTimes 30 3.0 sigmoid sigmoid' net samples\n result = map (\\(a, b) -> (output net' sigmoid a, b)) validation\n printf \"%.2f%% correct\\n\" (100 * validate result)\n\n\nvalidate :: [(Vector Double, Word8)] -> Float\nvalidate results =\n correct / (fromIntegral $ length results)\n where\n correct = sum [ 1 | (x, y) <- results, maxListIndex x == y]\n maxListIndex :: Vector Double -> Word8\n maxListIndex = fst . maxPair . toList\n maxPair :: [Double] -> (Word8, Double)\n maxPair = maximumBy (comparing snd) . zip [0..]\n", "meta": {"hexsha": "f8bdb392405244156765c695c567744ea88e84cc", "size": 863, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/src/DigitReader.hs", "max_stars_repo_name": "KaiHa/NNDigitReader", "max_stars_repo_head_hexsha": "789c502b8dfdb6f867d569132b2c5cfe06aea136", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "haskell/src/DigitReader.hs", "max_issues_repo_name": "KaiHa/NNDigitReader", "max_issues_repo_head_hexsha": "789c502b8dfdb6f867d569132b2c5cfe06aea136", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "haskell/src/DigitReader.hs", "max_forks_repo_name": "KaiHa/NNDigitReader", "max_forks_repo_head_hexsha": "789c502b8dfdb6f867d569132b2c5cfe06aea136", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7666666667, "max_line_length": 69, "alphanum_fraction": 0.6732329085, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5589797229743201}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeFamilies #-}\nimport Control.Monad\nimport Control.Monad.Random\nimport Data.List ( foldl' )\n\nimport qualified Data.ByteString as B\nimport Data.Serialize\nimport Data.Semigroup ( (<>) )\n\nimport GHC.TypeLits\n\nimport qualified Numeric.LinearAlgebra.Static as SA\n\nimport Options.Applicative\n\nimport Grenade\n\n\n-- The defininition for our simple feed forward network.\n-- The type level lists represents the layers and the shapes passed through the layers.\n-- One can see that for this demonstration we are using relu, tanh and logit non-linear\n-- units, which can be easily subsituted for each other in and out.\n--\n-- With around 100000 examples, this should show two clear circles which have been learned by the network.\ntype FFNet = Network '[ FullyConnected 2 40, Tanh, FullyConnected 40 10, Relu, FullyConnected 10 1, Logit ]\n '[ 'D1 2, 'D1 40, 'D1 40, 'D1 10, 'D1 10, 'D1 1, 'D1 1]\n\nrandomNet :: MonadRandom m => m FFNet\nrandomNet = randomNetwork\n\nnetTrain :: FFNet -> LearningParameters -> Int -> IO FFNet\nnetTrain net0 rate n = do\n inps <- replicateM n $ do\n s <- getRandom\n return $ S1D $ SA.randomVector s SA.Uniform * 2 - 1\n let outs = flip map inps $ \\(S1D v) ->\n if v `inCircle` (fromRational 0.33, 0.33) || v `inCircle` (fromRational (-0.33), 0.33)\n then S1D $ fromRational 1\n else S1D $ fromRational 0\n\n let trained = foldl' trainEach net0 (zip inps outs)\n return trained\n\n where\n inCircle :: KnownNat n => SA.R n -> (SA.R n, Double) -> Bool\n v `inCircle` (o, r) = SA.norm_2 (v - o) <= r\n trainEach !network (i,o) = train rate network i o\n\nnetLoad :: FilePath -> IO FFNet\nnetLoad modelPath = do\n modelData <- B.readFile modelPath\n either fail return $ runGet (get :: Get FFNet) modelData\n\nnetScore :: FFNet -> IO ()\nnetScore network = do\n let testIns = [ [ (x,y) | x <- [0..50] ]\n | y <- [0..20] ]\n outMat = fmap (fmap (\\(x,y) -> (render . normx) $ runNet network (S1D $ SA.vector [x / 25 - 1,y / 10 - 1]))) testIns\n putStrLn $ unlines outMat\n\n where\n render n' | n' <= 0.2 = ' '\n | n' <= 0.4 = '.'\n | n' <= 0.6 = '-'\n | n' <= 0.8 = '='\n | otherwise = '#'\n\n normx :: S ('D1 1) -> Double\n normx (S1D r) = SA.mean r\n\ndata FeedForwardOpts = FeedForwardOpts Int LearningParameters (Maybe FilePath) (Maybe FilePath)\n\nfeedForward' :: Parser FeedForwardOpts\nfeedForward' =\n FeedForwardOpts <$> option auto (long \"examples\" <> short 'e' <> value 100000)\n <*> (LearningParameters\n <$> option auto (long \"train_rate\" <> short 'r' <> value 0.01)\n <*> option auto (long \"momentum\" <> value 0.9)\n <*> option auto (long \"l2\" <> value 0.0005)\n )\n <*> optional (strOption (long \"load\"))\n <*> optional (strOption (long \"save\"))\n\nmain :: IO ()\nmain = do\n FeedForwardOpts examples rate load save <- execParser (info (feedForward' <**> helper) idm)\n net0 <- case load of\n Just loadFile -> netLoad loadFile\n Nothing -> randomNet\n\n net <- netTrain net0 rate examples\n netScore net\n\n case save of\n Just saveFile -> B.writeFile saveFile $ runPut (put net)\n Nothing -> return ()\n", "meta": {"hexsha": "eb936943fa9fe873f17c12bf5861db2856afca34", "size": 3653, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/feedforward.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": "examples/main/feedforward.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": "examples/main/feedforward.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": 35.8137254902, "max_line_length": 125, "alphanum_fraction": 0.5781549411, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.5589388514375896}} {"text": "module Numeric.LinearAlgebra.Matrix.Mat33 where\n\nimport Numeric.LinearAlgebra.Matrix.Class\n\nimport Data.List ( foldl1' )\n\ndata Mat33 a = Mat33\n { m00 :: !a, m01 :: !a, m02 :: !a\n , m10 :: !a, m11 :: !a, m12 :: !a\n , m20 :: !a, m21 :: !a, m22 :: !a\n }\n deriving (Read, Show, Eq, Ord)\n\ninstance Matrix Mat33 where\n {-# INLINE mDim #-}\n mDim _ = 3\n {-# INLINE mElement #-}\n mElement m 0 0 = m00 m\n mElement m 0 1 = m01 m\n mElement m 0 2 = m02 m\n mElement m 1 0 = m10 m\n mElement m 1 1 = m11 m\n mElement m 1 2 = m12 m\n mElement m 2 0 = m20 m\n mElement m 2 1 = m21 m\n mElement m 2 2 = m22 m\n mElement _ i j = error (\"Index \" ++ show i ++ \", \" ++ show j ++ \": out of range, must be 0,0 to 2,2\")\n {-# INLINE mZip #-}\n mZip f m n = Mat33 (f (m00 m) (m00 n)) (f (m01 m) (m01 n)) (f (m02 m) (m02 n))\n (f (m10 m) (m10 n)) (f (m11 m) (m11 n)) (f (m12 m) (m12 n))\n (f (m20 m) (m20 n)) (f (m21 m) (m21 n)) (f (m22 m) (m22 n))\n {-# INLINE mFold #-}\n mFold f m = foldl1' f [ mElement m i j | i <- [ 0 .. 2 ], j <- [ 0 .. 2 ] ]\n {-# INLINE mIndexOf #-}\n mIndexOf p m = fst (foldl1' p' [ ((i,j), mElement m i j) | j <- [ 2, 1 .. 0 ], i <- [ 2, 1 .. 0 ] ])\n where\n p' x@(_, a) y@(_, a') | a `p` a' = x\n | otherwise = y\n {-# INLINE det #-}\n det (Mat33 a b c d e f g h i) = det33 a b c d e f g h i\n\ninstance Functor Mat33 where\n {-# INLINE fmap #-}\n fmap f m = Mat33 (f (m00 m)) (f (m01 m)) (f (m02 m))\n (f (m10 m)) (f (m11 m)) (f (m12 m))\n (f (m20 m)) (f (m21 m)) (f (m22 m))\n\n{-# SPECIALIZE det33 :: Double -> Double -> Double\n -> Double -> Double -> Double\n -> Double -> Double -> Double\n -> Double #-}\n{-# SPECIALIZE det33 :: Float -> Float -> Float\n -> Float -> Float -> Float\n -> Float -> Float -> Float\n -> Float #-}\ndet33 :: Num a\n => a -> a -> a\n -> a -> a -> a\n -> a -> a -> a\n -> a\ndet33 a b c d e f g h i = a*e*i + d*h*c + g*b*f - g*e*c - d*b*i - a*h*f\n\n{- SPECIALIZE inv33 :: Mat33 Double -> Mat33 Double -}\n{- SPECIALIZE inv33 :: Mat33 Float -> Mat33 Float -}\n{-\ninv33 :: Fractional a => Mat33 a -> Mat33 a\ninv33 m = m'\n where\n d = det m\n m' = Mat33 (m11 * m22 - m21 * m21)\n m' = Mat44 (det3 (m11 m) (m12 m) (m13 m)\n (m21 m) (m22 m) (m23 m)\n (m31 m) (m32 m) (m33 m) / d)\n (-(det3 (m01 m) (m02 m) (m03 m)\n (m21 m) (m22 m) (m23 m)\n (m31 m) (m32 m) (m33 m) / d))\n (det3 (m01 m) (m02 m) (m03 m)\n (m11 m) (m12 m) (m13 m)\n (m31 m) (m32 m) (m33 m) / d)\n (-(det3 (m01 m) (m02 m) (m03 m)\n (m11 m) (m12 m) (m13 m)\n (m21 m) (m22 m) (m23 m) / d))\n \n (-(det3 (m10 m) (m12 m) (m13 m)\n (m20 m) (m22 m) (m23 m)\n (m30 m) (m32 m) (m33 m) / d))\n (det3 (m00 m) (m02 m) (m03 m)\n (m20 m) (m22 m) (m23 m)\n (m30 m) (m32 m) (m33 m) / d)\n (-(det3 (m00 m) (m02 m) (m03 m)\n (m10 m) (m12 m) (m13 m)\n (m30 m) (m32 m) (m33 m) / d))\n (det3 (m00 m) (m02 m) (m03 m)\n (m10 m) (m12 m) (m13 m)\n (m20 m) (m22 m) (m23 m) / d)\n\n (det3 (m10 m) (m11 m) (m13 m)\n (m20 m) (m21 m) (m23 m)\n (m30 m) (m31 m) (m33 m) / d)\n (-(det3 (m00 m) (m01 m) (m03 m)\n (m20 m) (m21 m) (m23 m)\n (m30 m) (m31 m) (m33 m) / d))\n (det3 (m00 m) (m01 m) (m03 m)\n (m10 m) (m11 m) (m13 m)\n (m30 m) (m31 m) (m33 m) / d)\n (-(det3 (m00 m) (m01 m) (m03 m)\n (m10 m) (m11 m) (m13 m)\n (m20 m) (m21 m) (m23 m) / d))\n\n (-(det3 (m10 m) (m11 m) (m12 m)\n (m20 m) (m21 m) (m22 m)\n (m30 m) (m31 m) (m32 m) / d))\n (det3 (m00 m) (m01 m) (m02 m)\n (m20 m) (m21 m) (m22 m)\n (m30 m) (m31 m) (m32 m) / d)\n (-(det3 (m00 m) (m01 m) (m02 m)\n (m10 m) (m11 m) (m12 m)\n (m30 m) (m31 m) (m32 m) / d))\n (det3 (m00 m) (m01 m) (m02 m)\n (m10 m) (m11 m) (m12 m)\n (m20 m) (m21 m) (m22 m) / d)\n-}\n", "meta": {"hexsha": "afa0d8a07d3d055656edf5f28ba5c81c16bb76d2", "size": 4519, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/Matrix/Mat33.hs", "max_stars_repo_name": "dagit/lin-alg", "max_stars_repo_head_hexsha": "b7c189573015871953c41f0b1fed4c8a73c081aa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T07:25:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T07:25:33.000Z", "max_issues_repo_path": "src/Numeric/LinearAlgebra/Matrix/Mat33.hs", "max_issues_repo_name": "dagit/lin-alg", "max_issues_repo_head_hexsha": "b7c189573015871953c41f0b1fed4c8a73c081aa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LinearAlgebra/Matrix/Mat33.hs", "max_forks_repo_name": "dagit/lin-alg", "max_forks_repo_head_hexsha": "b7c189573015871953c41f0b1fed4c8a73c081aa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7398373984, "max_line_length": 103, "alphanum_fraction": 0.3890241204, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5587678430556865}} {"text": "module MachineLearning.LeastSquaresModelTest\n(\n tests\n)\n\nwhere\n\nimport Test.Framework (testGroup)\nimport Test.Framework.Providers.HUnit\nimport Test.HUnit\nimport Test.HUnit.Approx\nimport Test.HUnit.Plus\n\nimport MachineLearning.DataSets (dataset1)\n\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified MachineLearning as ML\nimport MachineLearning.Optimization (checkGradient)\nimport MachineLearning.Model\nimport MachineLearning.LeastSquaresModel\nimport MachineLearning.Regularization (Regularization(..))\n\n(x, y) = ML.splitToXY dataset1\n\nx1 = ML.addBiasDimension x\ninitialTheta :: LA.Vector LA.R\ninitialTheta = LA.konst 1000 (LA.cols x1)\nzeroTheta :: LA.Vector LA.R\nzeroTheta = LA.konst 0 (LA.cols x1)\n\ntests = [ testGroup \"model\" [\n testCase \"cost, no reg\" $ assertApproxEqual \"\" 1e-5 1.6190245331702874e12 (cost LeastSquares RegNone x1 y initialTheta)\n , testCase \"cost, lambda = 0\" $ assertApproxEqual \"\" 1e-5 1.6190245331702874e12 (cost LeastSquares (L2 0) x1 y initialTheta)\n , testCase \"cost, lambda = 1\" $ assertApproxEqual \"\" 1e-5 1.619024554446883e12 (cost LeastSquares (L2 1) x1 y initialTheta)\n , testCase \"cost, lambda = 1000\" $ assertApproxEqual \"\" 1e-5 1.619045809766032e12 (cost LeastSquares (L2 1000) x1 y initialTheta)\n , testCase \"gradient, no reg\" $ assertVector \"\" 1e-5 gradient_l0 (gradient LeastSquares RegNone x1 y initialTheta)\n , testCase \"gradient, lambda = 0\" $ assertVector \"\" 1e-5 gradient_l0 (gradient LeastSquares (L2 0) x1 y initialTheta)\n , testCase \"gradient, lambda = 1\" $ assertVector \"\" 1e-5 gradient_l1 (gradient LeastSquares (L2 1) x1 y initialTheta)\n , testCase \"gradient, lambda = 1000\" $ assertVector \"\" 1e-5 gradient_l1000 (gradient LeastSquares (L2 1000) x1 y initialTheta)\n ]\n , testGroup \"gradient checking\" [\n testCase \"non-zero theta, no reg\" $ assertApproxEqual \"\" 1 0 (checkGradient LeastSquares RegNone x1 y initialTheta 1e-4)\n , testCase \"non-zero theta, non-zero lambda\" $ assertApproxEqual \"\" 1 0 (checkGradient LeastSquares (L2 2) x1 y initialTheta 1e-4)\n , testCase \"zero theta, non-zero lambda\" $ assertApproxEqual \"\" 1 0 (checkGradient LeastSquares (L2 2) x1 y zeroTheta 1e-4) \n , testCase \"non-zero theta, zero lambda\" $ assertApproxEqual \"\" 1 0 (checkGradient LeastSquares (L2 0) x1 y initialTheta 1e-4)\n , testCase \"zero theta, zero lambda\" $ assertApproxEqual \"\" 1 0(checkGradient LeastSquares (L2 0) x1 y zeroTheta 1e-4)\n ]\n ]\n\ngradient_l0 = LA.vector [1664438.4042553192,3.865303999468085e9,5567440.808510638]\ngradient_l1 = LA.vector [1664438.4042553192,3.865304020744681e9,5567462.085106383]\ngradient_l1000 = LA.vector [1664438.4042553192,3.86532527606383e9, 5588717.404255319]\n", "meta": {"hexsha": "96e74a4ec4caf14e20126cca2127be5b2624e9bc", "size": 2863, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/MachineLearning/LeastSquaresModelTest.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "test/MachineLearning/LeastSquaresModelTest.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "test/MachineLearning/LeastSquaresModelTest.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 54.0188679245, "max_line_length": 144, "alphanum_fraction": 0.7121900105, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5585934571755771}} {"text": "{- |\nRaw, unnormalized versions of the transforms in @fftw@.\n\nNote that the forwards and backwards transforms of this module are not actually\ninverses. For example, @run idft (run dft v) /= v@ in general.\n\nFor more information on the individual transforms, see\n.\n-}\nmodule Numeric.FFT.Vector.Unnormalized(\n -- * Creating and executing 'Plan's\n run,\n plan,\n execute,\n -- * Complex-to-complex transforms\n dft,\n idft,\n -- * Real-to-complex transforms\n dftR2C,\n dftC2R,\n -- * Real-to-real transforms\n -- $dct_size\n -- ** Discrete cosine transforms\n dct1,\n dct2,\n dct3,\n dct4,\n -- ** Discrete sine transforms\n dst1,\n dst2,\n dst3,\n dst4,\n ) where\n\nimport Numeric.FFT.Vector.Base\nimport Foreign\nimport Foreign.C\nimport Data.Complex\n\n#include \n\n-- | Whether the complex fft is forwards or backwards.\ntype CDirection = CInt\n\n-- | The type of the cosine or sine transform.\ntype CKind = (#type fftw_r2r_kind)\n\nforeign import ccall unsafe fftw_plan_dft_1d\n :: CInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> CDirection\n -> CFlags -> IO (Ptr CPlan)\n\nforeign import ccall unsafe fftw_plan_dft_r2c_1d\n :: CInt -> Ptr Double -> Ptr (Complex Double) -> CFlags -> IO (Ptr CPlan)\n\nforeign import ccall unsafe fftw_plan_dft_c2r_1d\n :: CInt -> Ptr (Complex Double) -> Ptr Double -> CFlags -> IO (Ptr CPlan)\n\nforeign import ccall unsafe fftw_plan_r2r_1d\n :: CInt -> Ptr Double -> Ptr Double -> CKind -> CFlags -> IO (Ptr CPlan)\n\ndft1D :: CDirection -> Transform (Complex Double) (Complex Double)\ndft1D d = Transform {\n inputSize = id,\n outputSize = id,\n creationSizeFromInput = id,\n makePlan = \\n a b -> withPlanner . fftw_plan_dft_1d n a b d,\n normalization = const id\n }\n\n-- | A forward discrete Fourier transform. The output and input sizes are the same (@n@).\n--\n-- @y_k = sum_(j=0)^(n-1) x_j e^(-2pi i j k/n)@\ndft :: Transform (Complex Double) (Complex Double)\ndft = dft1D (#const FFTW_FORWARD)\n\n-- | A backward discrete Fourier transform. The output and input sizes are the same (@n@).\n--\n-- @y_k = sum_(j=0)^(n-1) x_j e^(2pi i j k/n)@\nidft :: Transform (Complex Double) (Complex Double)\nidft = dft1D (#const FFTW_BACKWARD)\n\n-- | A forward discrete Fourier transform with real data. If the input size is @n@,\n-- the output size will be @n \\`div\\` 2 + 1@.\ndftR2C :: Transform Double (Complex Double)\ndftR2C = Transform {\n inputSize = id,\n outputSize = \\n -> n `div` 2 + 1,\n creationSizeFromInput = id,\n makePlan = \\n a b -> withPlanner . fftw_plan_dft_r2c_1d n a b,\n normalization = const id\n }\n\n-- | A backward discrete Fourier transform which produces real data.\n--\n-- This 'Transform' behaves differently than the others:\n--\n-- - Calling @plan dftC2R n@ creates a 'Plan' whose /output/ size is @n@, and whose\n-- /input/ size is @n \\`div\\` 2 + 1@.\n--\n-- - If @length v == n@, then @length (run dftC2R v) == 2*(n-1)@.\ndftC2R :: Transform (Complex Double) Double\ndftC2R = Transform {\n inputSize = \\n -> n `div` 2 + 1,\n outputSize = id,\n creationSizeFromInput = \\n -> 2 * (n-1),\n makePlan = \\n a b -> withPlanner . fftw_plan_dft_c2r_1d n a b,\n normalization = const id\n }\n\n\nr2rTransform :: CKind -> Transform Double Double\nr2rTransform kind = Transform {\n inputSize = id,\n outputSize = id,\n creationSizeFromInput = id,\n makePlan = \\n a b -> withPlanner . fftw_plan_r2r_1d n a b kind,\n normalization = const id\n }\n\n-- $dct_size\n-- The real-even (DCT) and real-odd (DST) transforms. The input and output sizes\n-- are the same (@n@).\n\n-- | A type-1 discrete cosine transform.\n--\n-- @y_k = x_0 + (-1)^k x_(n-1) + 2 sum_(j=1)^(n-2) x_j cos(pi j k\\/(n-1))@\ndct1 :: Transform Double Double\ndct1 = r2rTransform (#const FFTW_REDFT00)\n\n-- | A type-2 discrete cosine transform.\n--\n-- @y_k = 2 sum_(j=0)^(n-1) x_j cos(pi(j+1\\/2)k\\/n)@\ndct2 :: Transform Double Double\ndct2 = r2rTransform (#const FFTW_REDFT10)\n\n-- | A type-3 discrete cosine transform.\n--\n-- @y_k = x_0 + 2 sum_(j=1)^(n-1) x_j cos(pi j(k+1\\/2)\\/n)@\ndct3 :: Transform Double Double\ndct3 = r2rTransform (#const FFTW_REDFT01)\n\n-- | A type-4 discrete cosine transform.\n--\n-- @y_k = 2 sum_(j=0)^(n-1) x_j cos(pi(j+1\\/2)(k+1\\/2)\\/n)@\ndct4 :: Transform Double Double\ndct4 = r2rTransform (#const FFTW_REDFT11)\n\n-- | A type-1 discrete sine transform.\n--\n-- @y_k = 2 sum_(j=0)^(n-1) x_j sin(pi(j+1)(k+1)\\/(n+1))@\ndst1 :: Transform Double Double\ndst1 = r2rTransform (#const FFTW_RODFT00)\n\n-- | A type-2 discrete sine transform.\n--\n-- @y_k = 2 sum_(j=0)^(n-1) x_j sin(pi(j+1\\/2)(k+1)\\/n)@\ndst2 :: Transform Double Double\ndst2 = r2rTransform (#const FFTW_RODFT10)\n\n-- | A type-3 discrete sine transform.\n--\n-- @y_k = (-1)^k x_(n-1) + 2 sum_(j=0)^(n-2) x_j sin(pi(j+1)(k+1\\/2)/n)@\ndst3 :: Transform Double Double\ndst3 = r2rTransform (#const FFTW_RODFT01)\n\n-- | A type-4 discrete sine transform.\n--\n-- @y_k = sum_(j=0)^(n-1) x_j sin(pi(j+1\\/2)(k+1\\/2)\\/n)@\ndst4 :: Transform Double Double\ndst4 = r2rTransform (#const FFTW_RODFT11)\n", "meta": {"hexsha": "56e7ec7559e36a3b2bcfa493ede63e622c151651", "size": 5703, "ext": "hsc", "lang": "Haskell", "max_stars_repo_path": "Numeric/FFT/Vector/Unnormalized.hsc", "max_stars_repo_name": "TravisWhitaker/vector-fftw", "max_stars_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-12-02T12:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T17:52:00.000Z", "max_issues_repo_path": "Numeric/FFT/Vector/Unnormalized.hsc", "max_issues_repo_name": "TravisWhitaker/vector-fftw", "max_issues_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-08-29T14:18:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T01:29:58.000Z", "max_forks_repo_path": "Numeric/FFT/Vector/Unnormalized.hsc", "max_forks_repo_name": "TravisWhitaker/vector-fftw", "max_forks_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-08-29T13:35:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T23:04:18.000Z", "avg_line_length": 33.350877193, "max_line_length": 91, "alphanum_fraction": 0.5832018236, "num_tokens": 1726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219505, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5584133441440458}} {"text": "{-# LANGUAGE GADTs\n , DataKinds\n , TypeApplications\n , ScopedTypeVariables\n , ExplicitForAll\n , AllowAmbiguousTypes\n , KindSignatures\n , TypeOperators\n , RankNTypes\n , GeneralizedNewtypeDeriving\n , StrictData #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\nmodule Lib where\n\n\nimport Numeric.LinearAlgebra hiding (Vector, Matrix)\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Data.Vector.Storable as VS\nimport GHC.TypeLits\nimport Data.Proxy\nimport System.Random\nimport Control.Monad\nimport Numeric.AD\n\nnewtype Vector (n :: Nat) = Vector { _vec :: VS.Vector Float }\n deriving (Show, Floating)\n\ninstance KnownNat n => Num (Vector n) where\n (Vector v1) + (Vector v2) = Vector $ v1 + v2\n (Vector v1) - (Vector v2) = Vector $ v1 - v2\n (Vector v1) * (Vector v2) = Vector $ v1 * v2\n abs = vectorMap abs\n fromInteger = vecFromList . (:[]) . fromInteger\n negate = vectorMap negate\n signum = vectorMap signum\n\ninstance KnownNat n => Fractional (Vector n) where\n (Vector v1) / (Vector v2) = Vector $ v1 / v2\n fromRational = vecFromList . (:[]) . fromRational\n\n\nnatToInt :: forall n. KnownNat n => Int\nnatToInt = fromIntegral . natVal $ Proxy @n\n\nvecFromList :: forall n. KnownNat n => [Float] -> Vector n\nvecFromList = Vector . VS.fromList . take (natToInt @n) . cycle\n\nvecLength :: forall n. KnownNat n => Vector n -> Int\nvecLength _ = natToInt @n\n\nvecTail :: forall n. KnownNat n => Vector (n+1) -> Vector n\nvecTail (Vector v) = Vector $ VS.tail v\n\nnewtype Matrix (n :: Nat) (m :: Nat) = Matrix { _mat :: LA.Matrix Float }\n deriving Show\n\nmatrixWidth :: forall n m. (KnownNat n, KnownNat m) => Matrix n m -> Int\nmatrixWidth _ = natToInt @n\n\nmatrixHeight :: forall n m. (KnownNat n, KnownNat m) => Matrix n m -> Int\nmatrixHeight _ = natToInt @m\n\nmatFromList :: forall n m. (KnownNat n, KnownNat m) => [Float] -> Matrix n m\nmatFromList = Matrix . (h> IO (Matrix n m)\nrandomMatrix = matFromList <$> replicateM (w*h) (randomRIO (0.001, 0.1))\n where w = natToInt @n\n h = natToInt @m\n\ndata Network :: Nat -> Nat -> * where\n Layer :: forall m n. (KnownNat n, KnownNat m) =>\n Matrix (n+1) m ->\n (forall a. Floating a => a -> a) ->\n Network n m\n Composition :: (KnownNat n, KnownNat m, KnownNat k) =>\n Network m k ->\n Network n m ->\n Network n k\n\n\nconductSignal :: forall n m. (KnownNat n, KnownNat m) =>\n Network n m ->\n Vector n ->\n Vector m\nconductSignal (Layer mat f) = vectorMap f . mvMul mat . vectorCons 1\nconductSignal (Composition network2 network1) = conductSignal network2 . conductSignal network1\n\nvectorMap :: (Float -> Float) -> Vector n -> Vector n\nvectorMap f (Vector v) = Vector $ VS.map f v\n\nmvMul :: Matrix n m -> Vector n -> Vector m\nmvMul (Matrix m) (Vector v) = Vector $ m #> v\n\nvectorCons :: KnownNat n => Float -> Vector n -> Vector (n+1)\nvectorCons n (Vector v) = Vector $ VS.cons n v\n\nrandomLayer :: forall n m. (KnownNat n, KnownNat m) => (forall a. Floating a => a -> a) -> IO (Network n m)\nrandomLayer f = (`Layer` f) <$> randomMatrix\n\nscaleMatrix :: (KnownNat n, KnownNat m) => Float -> Matrix m n -> Matrix m n\nscaleMatrix s (Matrix m) = Matrix $ LA.scale s m\n\ntransposeMat :: (KnownNat n, KnownNat m) => Matrix n m -> Matrix m n\ntransposeMat (Matrix mat) = Matrix $ LA.tr mat\n\nouterProduct :: (KnownNat n, KnownNat m) => Vector n -> Vector m -> Matrix n m\nouterProduct (Vector v1) (Vector v2) = Matrix $ v2 `outer` v1\n\nvvMul :: (KnownNat n) => Vector n -> Vector n -> Vector n\nvvMul (Vector v1) (Vector v2) = Vector $ v1 * v2\n\nmatrixSub :: (KnownNat m, KnownNat n) => Matrix n m -> Matrix n m -> Matrix n m\nmatrixSub (Matrix m1) (Matrix m2) = Matrix $ m1 - m2\n\n\nuseTrainingExample :: forall m n. (KnownNat n, KnownNat m) =>\n Vector m ->\n Network n m ->\n Vector n ->\n (Network n m, Vector n)\nuseTrainingExample diffLoss (Layer weights activation) input = (trainedLayer, inputGradient)\n where\n trainedLayer = Layer newWeights activation\n newWeights :: Matrix (n+1) m\n newWeights = matrixSub weights $ scaleMatrix 0.01 weightGradient\n consedInput = vectorCons 1 input\n preActivationOutput = mvMul weights consedInput\n output = vectorMap activation preActivationOutput\n diffActivation = vectorMap (diff activation) preActivationOutput\n weightGradient = outerProduct consedInput (diffLoss * diffActivation)\n inputGradient = vecTail $ mvMul (transposeMat weights) (diffLoss * diffActivation)\nuseTrainingExample diffLoss (Composition network2 network1) input =\n (Composition trainedNet2 trainedNet1, inputGradient)\n where (trainedNet2,outputGrad1) = useTrainingExample diffLoss network2 input2\n input2 = conductSignal network1 input\n (trainedNet1,inputGradient) = useTrainingExample outputGrad1 network1 input\n\nshowExample :: (KnownNat n, KnownNat m) =>\n (Vector m -> Vector m -> Vector m) ->\n Network n m ->\n (Vector n, Vector m) ->\n Network n m\nshowExample lossGrad network (input,expected) = fst $ useTrainingExample diffLoss network input\n where diffLoss = lossGrad expected output\n output = conductSignal network input\n\n\nsigmoid input = 1/(1+exp(-input))\n -- (1/) . (1+) . exp . negate\n\nepsilon :: Floating a => a\nepsilon = 0.0000001\n\nlogLoss :: Floating a => [a] -> a\nlogLoss [expected, output] = negate $ expected * log (output + epsilon) + (1 - expected) * log (1 - output + epsilon)\n\ngradLogLoss expected output = grad logLoss [expected, output] !! 1\n\n-- \"mnist/train-set\"\n\ngetTrainSet :: IO [(Vector 784, Vector 10)]\ngetTrainSet =\n map (\\(a,b) -> (vecFromList a, toOneHot b)) .\n map (read @([Float],Int)) .\n lines <$> readFile \"mnist/train-set\"\n where\n toOneHot n = vecFromList $ map (\\x -> if x == n then 1 else 0) [0..]\n\neval network (input,expected) = do\n putStrLn \"EXPECTED:\"\n print expected\n putStrLn \"PREDICTED:\"\n print $ conductSignal network input\n\ntrainTest k n = do\n trainSet <- take n <$> getTrainSet\n untrainedLayer1 <- randomLayer sigmoid\n untrainedLayer2 <- randomLayer @50 @10 sigmoid\n let untrainedNetwork = Composition untrainedLayer2 untrainedLayer1\n trainedNetwork = foldl (showExample gradLogLoss) untrainedNetwork . take (k*n) $ cycle trainSet\n evalSet = take 10 trainSet\n mapM_ (eval trainedNetwork) evalSet\n\n{-\n\n diff (loss . activation . mvMul(weights, input))\n\n => diff loss (activation . mvMul (weights,input)) * diff (activation . mvMul (weights,input))\n\n => diff loss (output) * diff activation (mvMul (weights,input)) * diff mvMul(weights,input)\n-}\n", "meta": {"hexsha": "8e0cd7da558129e71f7d83f957f3b46bdd5990d5", "size": 7136, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "Antystenes/MPNN", "max_stars_repo_head_hexsha": "c626f50324ab98b9952da916b875c82c486fa6c3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-06-15T08:42:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-16T23:50:27.000Z", "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "Antystenes/MPNN", "max_issues_repo_head_hexsha": "c626f50324ab98b9952da916b875c82c486fa6c3", "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": "Antystenes/MPNN", "max_forks_repo_head_hexsha": "c626f50324ab98b9952da916b875c82c486fa6c3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4081632653, "max_line_length": 117, "alphanum_fraction": 0.63242713, "num_tokens": 1927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5583844713117757}} {"text": "module STCR2Z1T0 where\n\nimport Control.Monad as M\nimport Control.Monad.Parallel as MP\nimport Data.Array.Repa as R\nimport Data.Binary (decodeFile)\nimport Data.Complex\nimport Data.List as L\nimport DFT.Plan\nimport Filter.Utils\nimport FokkerPlanck.DomainChange\nimport FokkerPlanck.MonteCarlo\nimport FokkerPlanck.Pinwheel\nimport Image.IO\nimport STC\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Types\nimport Utils.Array\n\nmain = do\n args@(numPointStr:numOrientationStr:sigmaStr:taoStr:lenStr:initStr:numTrailStr:maxTrailStr:theta0FreqsStr:thetaFreqsStr:initDistStr:histFilePath:alphaStr:pinwheelFlagStr:numThreadStr:_) <-\n getArgs\n print args\n let numPoint = read numPointStr :: Int\n numOrientation = read numOrientationStr :: Int\n sigma = read sigmaStr :: Double\n tao = read taoStr :: Double\n len = read lenStr :: Int\n init = read initStr :: (Double, Double, Double, Double, Double, Double)\n numTrail = read numTrailStr :: Int\n maxTrail = read maxTrailStr :: Int\n theta0Freq = read theta0FreqsStr :: Double\n theta0Freqs = [-theta0Freq .. theta0Freq]\n thetaFreq = read thetaFreqsStr :: Double\n thetaFreqs = [-thetaFreq .. thetaFreq]\n initDist = read initDistStr :: [R2S1RPPoint]\n alpha = read alphaStr :: Double\n pinwheelFlag = read pinwheelFlagStr :: Bool\n numThread = read numThreadStr :: Int\n sourceDist = L.take 1 initDist\n sinkDist = L.drop 1 initDist\n folderPath = \"output/test/STCR2Z1T0\"\n flag <- doesFileExist histFilePath\n -- arrR2Z1T0 <-\n -- if pinwheelFlag\n -- then computeR2Z1T0Array numPoint numPoint alpha thetaFreqs theta0Freqs\n -- else if flag\n -- then getNormalizedHistogramArr <$> decodeFile histFilePath\n -- else solveMonteCarloR2Z1T0\n -- numThread\n -- numTrail\n -- maxTrail\n -- numPoint\n -- numPoint\n -- sigma\n -- tao\n -- 1\n -- len\n -- theta0Freqs\n -- thetaFreqs\n -- histFilePath\n -- (emptyHistogram\n -- [ numPoint\n -- , numPoint\n -- , L.length theta0Freqs\n -- , L.length thetaFreqs\n -- ]\n -- 0)\n radialArr <-\n if flag\n then R.map magnitude . getNormalizedHistogramArr <$>\n decodeFile histFilePath\n else do\n putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n solveMonteCarloR2Z1T0Radial\n numThread\n numTrail\n maxTrail\n numPoint\n numPoint\n sigma\n tao\n 0\n theta0Freqs\n thetaFreqs\n histFilePath\n (emptyHistogram\n [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n , L.length theta0Freqs\n , L.length thetaFreqs\n ]\n 0)\n arrR2Z1T0 <-\n computeUnboxedP $\n computeR2Z1T0ArrayRadial\n radialArr\n numPoint\n numPoint\n 1\n thetaFreqs\n theta0Freqs\n let arr3d =\n rotate3D . R.slice arrR2Z1T0 $\n (Z :. All :. (L.length theta0Freqs - 1) :. All :. All)\n createDirectoryIfMissing True folderPath\n MP.mapM_\n (\\i ->\n plotImageRepaComplex\n (folderPath \"GreensR2Z1T0_\" L.++ show (i + 1) L.++ \".png\") .\n ImageRepa 8 .\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.slice arr3d $\n (Z :. All :. All :. i))\n [0 .. (L.length thetaFreqs) - 1]\n plan <- makeR2Z1T0Plan emptyPlan arrR2Z1T0\n sourceDistArr <-\n computeInitialDistributionR2T0 plan numPoint numPoint theta0Freqs sourceDist\n sinkDistArr <-\n computeInitialDistributionR2T0 plan numPoint numPoint theta0Freqs sinkDist\n arrR2Z1T0F <- (computeP . makeFilter2D $ arrR2Z1T0) >>= dftR2Z1T0 plan\n arrR2Z1T0TRF <-\n (computeP . makeFilter2D . timeReverseR2Z1T0 thetaFreqs theta0Freqs $\n arrR2Z1T0) >>=\n dftR2Z1T0 plan\n -- Source field\n sourceArr <- convolveR2T0 plan arrR2Z1T0F sourceDistArr\n -- let sourceR2Z1 = R.sumS . rotateR2Z1T0Array $ sourceArr\n -- sourceField =\n -- computeS .\n -- R.extend (Z :. (1 :: Int) :. All :. All) .\n -- R.sumS . rotate3D . r2z1Tor2s1 numOrientation thetaFreqs $\n -- sourceR2Z1\n sourceR2Z1 <- R.sumP . rotateR2Z1T0Array $ sourceArr\n sourceField <-\n fmap (computeS . R.extend (Z :. (1 :: Int) :. All :. All)) .\n R.sumP . rotate3D . r2z1Tor2s1 numOrientation thetaFreqs $\n sourceR2Z1\n plotImageRepaComplex (folderPath \"Source.png\") . ImageRepa 8 $ sourceField\n -- Sink field\n sinkArr' <- convolveR2T0 plan arrR2Z1T0F sinkDistArr\n let sinkArr = computeSinkFromSourceR2Z1T0 thetaFreqs theta0Freqs sinkArr'\n -- let sinkR2Z1 = R.sumS . rotateR2Z1T0Array $ sinkArr\n -- sinkField =\n -- computeS .\n -- R.extend (Z :. (1 :: Int) :. All :. All) .\n -- R.sumS . rotate3D . r2z1Tor2s1 numOrientation thetaFreqs $\n -- sinkR2Z1\n sinkR2Z1 <- R.sumP . rotateR2Z1T0Array $ sinkArr\n sinkField <-\n fmap (computeS . R.extend (Z :. (1 :: Int) :. All :. All)) .\n R.sumP . rotate3D . r2z1Tor2s1 numOrientation thetaFreqs $\n sinkR2Z1\n plotImageRepaComplex (folderPath \"Sink.png\") . ImageRepa 8 $ sinkField\n -- Completion Filed\n completionFiled <-\n convolveR2Z1 plan thetaFreqs sourceR2Z1 sinkR2Z1\n let completionFiledR2 =\n R.sumS . rotate3D . r2z1Tor2s1 numOrientation thetaFreqs $\n completionFiled\n -- completionFiledR2 <-\n -- R.sumP . R.map magnitude . rotate3D . r2z1Tor2s1 numOrientation thetaFreqs $\n -- completionFiled\n plotImageRepa (folderPath \"Completion.png\") .\n ImageRepa 8 .\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.map magnitude $\n completionFiledR2\n", "meta": {"hexsha": "10b89f172443e1d139f80252557a20ce1623a518", "size": 6211, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2Z1T0/STCR2Z1T0.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/STCR2Z1T0/STCR2Z1T0.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/STCR2Z1T0/STCR2Z1T0.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 36.9702380952, "max_line_length": 190, "alphanum_fraction": 0.5889550797, "num_tokens": 1864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5583844659106084}} {"text": "\nmodule Main where\n\nimport Network.Layer\nimport Network.Network\nimport Network.Neuron\nimport Network.Trainer\n\nimport Numeric.LinearAlgebra\nimport System.Random\n\nmain :: IO ()\nmain = do\n\n g <- newStdGen\n let l = LayerDefinition sigmoidNeuron 2 connectFully\n l' = LayerDefinition sigmoidNeuron 2 connectFully\n l'' = LayerDefinition sigmoidNeuron 1 connectFully\n\n let n = createNetwork normals g [l, l', l'']\n\n let t = BackpropTrainer 3 quadraticCost quadraticCost'\n\n let dat = [(fromList [0, 1], fromList [1]),\n (fromList [1, 1], fromList [0]),\n (fromList [1, 0], fromList [1]),\n (fromList [0, 0], fromList [0])]\n\n let n' = trainNTimes n t online dat 10000\n\n putStrLn \"==> XOR predictions: \"\n putStr \"(0,0): \"\n print $ predict (fromList [0, 0]) n'\n putStr \"(1,0): \"\n print $ predict (fromList [1, 0]) n'\n putStr \"(0,1): \"\n print $ predict (fromList [0, 1]) n'\n putStr \"(1,1): \"\n print $ predict (fromList [1, 1]) n'\n\n putStrLn \"\\n==> Trained network: \"\n print $ map layerToShowable $ layers n'\n\n{-\n saveNetwork \"xor.ann\" n'\n\n putStrLn \"==> Network saved and reloaded: \"\n n'' <- loadNetwork \"xor.ann\" [l, l', l'']\n\n print $ predict (fromList [0, 0]) n''\n print $ predict (fromList [1, 0]) n''\n print $ predict (fromList [0, 1]) n''\n print $ predict (fromList [1, 1]) n''\n-}\n\n", "meta": {"hexsha": "2f929dcdb8186c4a6013c550ea8603482fe0d5ca", "size": 1345, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "IMOKURI/nn-sample", "max_stars_repo_head_hexsha": "a9507ec1b7fd2a9ed26e78921f356dad329bf834", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "IMOKURI/nn-sample", "max_issues_repo_head_hexsha": "a9507ec1b7fd2a9ed26e78921f356dad329bf834", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main.hs", "max_forks_repo_name": "IMOKURI/nn-sample", "max_forks_repo_head_hexsha": "a9507ec1b7fd2a9ed26e78921f356dad329bf834", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0178571429, "max_line_length": 56, "alphanum_fraction": 0.6208178439, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5583168335140388}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE IncoherentInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\nmodule Data.Vector.Image.Color.YUV (\n YUV(..)\n) where\n\nimport Prelude hiding(map)\nimport qualified Prelude as P\nimport qualified Data.List as L\nimport Data.Vector.Storable hiding(forM_,map,replicate,fromList,toList,(!?),(!))\nimport Data.Maybe\nimport Numeric.LinearAlgebra.Data hiding (fromList,toList,(!))\nimport Numeric.LinearAlgebra.HMatrix hiding (fromList,toList,(!))\nimport qualified Data.Vector.Storable as V\nimport Foreign\nimport GHC.Real\nimport Foreign.C.String\nimport Foreign.C.Types\nimport qualified Control.Monad as C\nimport Data.Vector.Image.Color.RGB\n\ndata YUV a = YUV {\n yuv_y :: a\n , yuv_u :: a \n , yuv_b :: a\n} deriving (Show,Eq,Ord)\n\ninstance Functor YUV where\n fmap func (YUV r g b) = YUV (func r) (func g) (func b)\n\nrgb2yuv :: (Num a,Integral a) => RGB a -> YUV a\nrgb2yuv (RGB r g b) = YUV ((r+2*g+b)`div`4) (b-g) (r-g)\n\nyuv2rgb :: (Num a,Integral a) => YUV a -> RGB a\nyuv2rgb (YUV y u v) = RGB (v+g) g (u+g)\n where\n g = y - ((u + v)`div`4)\n\ninstance (Num a,Integral a) => ColorSpace YUV a where\n toRGB = yuv2rgb\n fromRGB = rgb2yuv\n toList (YUV r g b) = [r,g,b]\n fromList [r,g,b] = (YUV r g b)\n fromList val = error $ \"List length must be 3 but \" L.++ show (L.length val)\n dim _ = 3\n", "meta": {"hexsha": "9491e7cb8f1694f54d73cff529d120e6f9cceb25", "size": 1651, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Vector/Image/Color/YUV.hs", "max_stars_repo_name": "junjihashimoto/img-vector", "max_stars_repo_head_hexsha": "5331c171337274398a29f6719587893466b4b5d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-29T04:04:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-29T04:04:04.000Z", "max_issues_repo_path": "Data/Vector/Image/Color/YUV.hs", "max_issues_repo_name": "junjihashimoto/img-vector", "max_issues_repo_head_hexsha": "5331c171337274398a29f6719587893466b4b5d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data/Vector/Image/Color/YUV.hs", "max_forks_repo_name": "junjihashimoto/img-vector", "max_forks_repo_head_hexsha": "5331c171337274398a29f6719587893466b4b5d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9649122807, "max_line_length": 80, "alphanum_fraction": 0.682616596, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5581356448814144}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MagicHash #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UnboxedTuples #-}\n{-# LANGUAGE ViewPatterns #-}\nmodule Numeric.Quaternion.Internal\n ( Quaternion (..), Quater(Quater)\n ) where\n\nimport Numeric.DataFrame.Type (KnownBackend)\nimport Numeric.Matrix.Internal (Matrix)\nimport Numeric.PrimBytes (PrimBytes)\nimport Numeric.Vector.Internal (Vector)\nimport Text.Read\n\n-- | @(x,y,z,w)@ of a quaternion\npattern Quater :: Quaternion t => t -> t -> t -> t -> Quater t\npattern Quater a b c d <- (unpackQ# -> (# a, b, c, d #))\n where\n Quater = packQ\n{-# COMPLETE Quater #-}\n\n-- | Quaternion operations\nclass ( Floating (Quater t), Floating t, Ord t, PrimBytes t\n , KnownBackend t '[3], KnownBackend t '[4]\n , KnownBackend t '[3,3], KnownBackend t '[4, 4]\n ) => Quaternion t where\n -- | Quaternion data type. The ordering of coordinates is @(x,y,z,w)@,\n -- where @w@ is the argument, and @x y z@ are the components of a 3D vector\n data Quater t\n -- | Set the quaternion in format @(x,y,z,w)@\n packQ :: t -> t -> t -> t -> Quater t\n -- | Get the values of the quaternion in format @(x,y,z,w)@\n unpackQ# :: Quater t -> (# t, t, t, t #)\n -- | Set the quaternion from 3D axis vector and argument\n fromVecNum :: Vector t 3 -> t -> Quater t\n -- | Set the quaternion from 4D vector in format @(x,y,z,w)@\n fromVec4 :: Vector t 4 -> Quater t\n -- | Transform the quaternion to 4D vector in format @(x,y,z,w)@\n toVec4 :: Quater t -> Vector t 4\n -- | Get scalar square of the quaternion.\n --\n -- >>> realToFrac (square q) == q * conjugate q\n square :: Quater t -> t\n -- | Imaginary part of the quaternion (orientation vector)\n im :: Quater t -> Quater t\n -- | Real part of the quaternion\n re :: Quater t -> Quater t\n -- | Imaginary part of the quaternion as a 3D vector\n imVec :: Quater t -> Vector t 3\n -- | Real part of the quaternion as a scalar\n taker :: Quater t -> t\n -- | i-th component\n takei :: Quater t -> t\n -- | j-th component\n takej :: Quater t -> t\n -- | k-th component\n takek :: Quater t -> t\n -- | Conjugate quaternion (negate imaginary part)\n conjugate :: Quater t -> Quater t\n -- | Rotates and scales vector in 3D using quaternion.\n -- Let \\( q = c (\\cos \\frac{\\alpha}{2}, v \\sin \\frac{\\alpha}{2}) \\)\n -- , \\( c > 0 \\), \\( {|v|}^2 = 1 \\);\n -- then the rotation angle is \\( \\alpha \\), and the axis of rotation is \\(v\\).\n -- Scaling is proportional to \\( c^2 \\).\n --\n -- >>> rotScale q x == q * x * (conjugate q)\n rotScale :: Quater t -> Vector t 3 -> Vector t 3\n -- | Creates a quaternion @q@ from two vectors @a@ and @b@,\n -- such that @rotScale q a == b@.\n getRotScale :: Vector t 3 -> Vector t 3 -> Quater t\n -- | Creates a rotation versor from an axis vector and an angle in radians.\n -- Result is always a unit quaternion (versor).\n -- If the argument vector is zero, then result is a real unit quaternion.\n axisRotation :: Vector t 3 -> t -> Quater t\n -- | Quaternion rotation angle \\( \\alpha \\)\n -- (where \\( q = c (\\cos \\frac{\\alpha}{2}, v \\sin \\frac{\\alpha}{2}) \\)\n -- , \\( c > 0 \\), \\( {|v|}^2 = 1 \\)).\n --\n -- >>> q /= 0 ==> axisRotation (imVec q) (qArg q) == signum q\n qArg :: Quater t -> t\n -- | Create a quaternion from a rotation matrix.\n -- Note, that rotations of \\(q\\) and \\(-q\\) are equivalent, there result of this\n -- function may be ambiguious. Assume the sign of the result to be chosen arbitrarily.\n fromMatrix33 :: Matrix t 3 3 -> Quater t\n -- | Create a quaternion from a homogenious coordinates trasform matrix.\n -- Ignores matrix translation transform.\n -- Note, that rotations of \\(q\\) and \\(-q\\) are equivalent, there result of this\n -- function may be ambiguious. Assume the sign of the result to be chosen arbitrarily.\n fromMatrix44 :: Matrix t 4 4 -> Quater t\n -- | Create a rotation matrix from a quaternion.\n -- Note, that rotations of \\(q\\) and \\(-q\\) are equivalent, so the following property holds:\n --\n -- >>> toMatrix33 q == toMatrix33 (-q)\n toMatrix33 :: Quater t -> Matrix t 3 3\n -- | Create a homogenious coordinates trasform matrix from a quaternion.\n -- Translation of the output matrix is zero.\n -- Note, that rotations of \\(q\\) and \\(-q\\) are equivalent, so the following property holds:\n --\n -- >>> toMatrix44 q == toMatrix44 (-q)\n toMatrix44 :: Quater t -> Matrix t 4 4\n\n\ninstance (Show t, Quaternion t, Ord t, Num t) => Show (Quater t) where\n showsPrec p (Quater x y z w)\n = case finS of\n SEmpty -> showChar '0'\n Simple -> finF\n SParen -> showParen (p > 6) finF\n where\n (finS, finF) = go SEmpty\n [(w, Nothing), (x, Just 'i'), (y, Just 'j'), (z, Just 'k')]\n go :: ShowState -> [(t, Maybe Char)] -> (ShowState, ShowS)\n go s ((v,l):xs)\n | (s0, f0) <- showComponent s v l\n , (s', f') <- go s0 xs\n = (s', f0 . f')\n go s [] = (s, id)\n showLabel Nothing = id\n showLabel (Just c) = showChar c\n showComponent :: ShowState -> t -> Maybe Char -> (ShowState, ShowS)\n showComponent sState val mLabel = case (sState, compare val 0) of\n (_ , EQ) -> ( sState, id )\n (SEmpty, GT) -> ( Simple, shows val . showLabel mLabel )\n (SEmpty, LT) -> ( SParen, shows val . showLabel mLabel )\n (_ , GT) -> ( SParen\n , showString \" + \" . shows val . showLabel mLabel )\n (_ , LT) -> ( SParen\n , showString \" - \" . shows (negate val) . showLabel mLabel )\n\n\ndata ShowState = SEmpty | Simple | SParen\n deriving Eq\n\ninstance (Read t, Quaternion t, Num t) => Read (Quater t) where\n readPrec = parens $ readPrec >>= go id 0 0 0 0\n where\n go :: (t -> t) -> t -> t -> t -> t -> t -> ReadPrec (Quater t)\n go f x y z w new =\n let def = pure (Quater x y z (f new))\n withLabel EOF = def\n withLabel (Ident \"i\")\n = (lexP >>= proceed (f new) y z w) <++ pure (Quater (f new) y z w)\n withLabel (Ident \"j\")\n = (lexP >>= proceed x (f new) z w) <++ pure (Quater x (f new) z w)\n withLabel (Ident \"k\")\n = (lexP >>= proceed x y (f new) w) <++ pure (Quater x y (f new) w)\n withLabel l = proceed x y z (f new) l\n in (lexP >>= withLabel) <++ def\n proceed :: t -> t -> t -> t -> Lexeme -> ReadPrec (Quater t)\n proceed x y z w (Symbol \"+\") = readPrec >>= go id x y z w\n proceed x y z w (Symbol \"-\") = readPrec >>= go negate x y z w\n proceed x y z w EOF = pure (Quater x y z w)\n proceed _ _ _ _ _ = pfail\n\n readListPrec = readListPrecDefault\n readList = readListDefault\n", "meta": {"hexsha": "687a4573c34f7c1dba2b7912c6c27e3365d2c911", "size": 7142, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "easytensor/src/Numeric/Quaternion/Internal.hs", "max_stars_repo_name": "achirkin/fasttensor", "max_stars_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2017-06-30T04:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:46:17.000Z", "max_issues_repo_path": "easytensor/src/Numeric/Quaternion/Internal.hs", "max_issues_repo_name": "achirkin/fasttensor", "max_issues_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-07-17T18:20:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T06:31:42.000Z", "max_forks_repo_path": "easytensor/src/Numeric/Quaternion/Internal.hs", "max_forks_repo_name": "achirkin/fasttensor", "max_forks_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-08T20:44:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T22:08:04.000Z", "avg_line_length": 44.3602484472, "max_line_length": 98, "alphanum_fraction": 0.5540464856, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.557939394478293}} {"text": "{-|\nModule: MachineLearning.Random\nDescription: Random generation utility functions.\nCopyright: (c) Alexander Ignatyev, 2017\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n\nRandon generation uitility functions.\n-}\n\nmodule MachineLearning.Random\n(\n sample\n , sampleM\n , getRandomRListM\n , getRandomRVectorM\n , getRandomRMatrixM\n)\n\nwhere\n\nimport Control.Monad (when)\nimport System.Random (RandomGen, Random)\nimport qualified Control.Monad.ST as ST\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Storable as SV\nimport Numeric.LinearAlgebra ((><))\nimport qualified Data.Vector.Mutable as MV\nimport qualified Control.Monad.Random as RndM\nimport MachineLearning.Types (R, Vector, Matrix)\n\n\n-- | Samples `n` (given as a second parameter) values from `list` (given as a third parameter).\nsample :: RandomGen g => g -> Int -> V.Vector a -> (V.Vector a, g)\nsample gen n xs = RndM.runRand (sampleM n xs) gen\n\n\n-- | Samples `n` (given as a second parameter) values from `list` (given as a third parameter) inside RandomMonad.\nsampleM :: RandomGen g => Int -> V.Vector a -> RndM.Rand g (V.Vector a)\nsampleM n xs = do -- Random Monad starts\n let rangeList = V.fromList $ zip (repeat 0) [n..(length xs)-1]\n rnds <- randomsInRangesM rangeList\n let (pre, post) = V.splitAt n xs\n let ys = ST.runST $ do -- ST Monad starts\n mv <- V.thaw pre\n V.zipWithM_ (\\val r -> when (r < n) $ MV.write mv (mod r n) val) post rnds\n V.unsafeFreeze mv\n return ys\n\n\n-- | Returns a list of random values distributed in a closed interval `range`\ngetRandomRListM :: (RandomGen g, Random a) =>\n Int -- ^ list's lengths\n -> (a, a) -- ^ range\n -> RndM.Rand g [a] -- ^ list of random values inside RandomMonad\ngetRandomRListM size range = mapM (\\_ -> RndM.getRandomR range) [1..size]\n\n\n-- | Returns a vector of random values distributed in a closed interval `range`\ngetRandomRVectorM :: RandomGen g =>\n Int -- ^ vector's length\n -> (R, R) -- ^ range\n -> RndM.Rand g Vector -- vector of randon values inside RandomMonad\ngetRandomRVectorM size range = SV.fromList <$> getRandomRListM size range\n\n\n-- | Returns a matrix of random values distributed in a closed interval `range`\ngetRandomRMatrixM :: RandomGen g =>\n Int -- ^ number of rows\n -> Int -- ^ number of columns\n -> (R, R) -- ^ range\n -> RndM.Rand g Matrix -- vector of randon values inside RandomMonad\ngetRandomRMatrixM r c range = (r> getRandomRListM (r*c) range\n\n\n-- | Takes a list of ranges `(lo, hi)`,\n-- returns a list of random values uniformly distributed in the list of closed intervals [(lo, hi)].\nrandomsInRangesM :: (RndM.RandomGen g, RndM.Random a) => V.Vector (a, a) -> RndM.Rand g (V.Vector a)\nrandomsInRangesM rangeList = mapM RndM.getRandomR rangeList\n", "meta": {"hexsha": "24cc797dc49204bb00cdb60b83710b183cf72c4a", "size": 3051, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/Random.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "src/MachineLearning/Random.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "src/MachineLearning/Random.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 37.6666666667, "max_line_length": 114, "alphanum_fraction": 0.6365126188, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5578429633417109}} {"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule Main where\n\nimport System.Exit\nimport System.Random\nimport System.TimeIt\nimport Control.Monad.State\nimport Numeric.LinearAlgebra\nimport Control.Monad.Trans.Maybe ( runMaybeT )\nimport Control.Monad.Writer ( runWriter )\nimport Criterion.Main\nimport Criterion.Types\n\nimport Neural.Network\nimport Neural.Activation ( sigmoid\n , sigmoid'\n )\nimport Neural.Training\nimport Data.MNIST ( loadData )\n\nshallowShape :: [Int]\nshallowShape = [784, 30, 10]\n\ndeepShape :: [Int]\ndeepShape = [784, 30, 30, 30, 10]\n\n-- HYPER PARAMETERS\n-- learing rate\n\u03bc :: Double\n\u03bc = 0.5\n\n-- Mini batch size\nmbs :: Int\nmbs = 100\n\n-- Amount of training epochs\nepochs :: Int\nepochs = 50\n\nmain :: IO ()\nmain = defaultMain\n [ env setupEnv $ \\ ~(trainEx, testEx) ->\n let trainShallow = timeIt (randomIO >>= trainNetwork trainEx testEx shallowShape)\n trainDeep = timeIt (randomIO >>= trainNetwork trainEx testEx deepShape)\n in bgroup\n \"main\"\n [ bench \"shallow\" $ nfIO trainShallow\n , bench \"deep\" $ nfIO trainDeep\n ]\n ]\n\ntrainNetwork\n :: [TrainingExample Double]\n -> [TestingExample Double]\n -> [Int]\n -> Seed\n -> IO (Network Double)\ntrainNetwork trainEx testEx shape seed = do\n let gen = mkStdGen seed\n let trainFunc = train sigmoid sigmoid' \u03bc trainEx (Just testEx) epochs mbs\n let (randNet, gen') = runState (randomNetwork shape) gen\n let (net, logs) = runWriter $ evalStateT (trainFunc randNet) gen'\n putStrLn \"Training network...\"\n\n mapM_ putStrLn logs\n return net\n\nsetupEnv\n :: IO ([TrainingExample Double], [TestingExample Double])\nsetupEnv = do\n mnistData <- runMaybeT loadData\n case mnistData of\n Nothing -> putStrLn \"Failed to load MNIST data.\" >> exitFailure\n Just (trainEx, testEx) -> return (trainEx, testEx)\n", "meta": {"hexsha": "a4465255fe4094425c6a3b18a82450c73e2f6c97", "size": 2100, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "cornelius-sevald/nnhd", "max_stars_repo_head_hexsha": "b952830829d81f2ec8c4050128abceb1e6c15b48", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "cornelius-sevald/nnhd", "max_issues_repo_head_hexsha": "b952830829d81f2ec8c4050128abceb1e6c15b48", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "cornelius-sevald/nnhd", "max_forks_repo_head_hexsha": "b952830829d81f2ec8c4050128abceb1e6c15b48", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 87, "alphanum_fraction": 0.5971428571, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5573943777492535}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators #-}\n\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n\n{-|\nModule : Numeric.LinearAlgebra.MatrixFree\nDescription : Represent matrices as a pair of functions for forward and adjoint.\nCopyright : (c) Ryan Orendorff, 2020\nLicense : BSD3\nStability : experimental\n-}\nmodule Numeric.LinearAlgebra.MatrixFree\n ( LinearMap(..)\n , (##>)\n , (*#)\n , (+#)\n , (<#>)\n , avgRepeatedFree\n , exactDimsFree\n , eyeFree\n , removeAvg\n , fromL\n , innerDimsFree\n , toL\n , konst\n , diag\n , forward\n , adjoint\n )\nwhere\n\nimport Data.Proxy ( Proxy(..) )\nimport Data.Type.Equality ( (:~:)(Refl) )\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra ( Transposable(..) )\nimport Numeric.LinearAlgebra.Static hiding (konst, diag)\nimport qualified Numeric.LinearAlgebra.Static as LS\nimport qualified Data.Vector.Storable as V\n\n\n-- | A linear operator/map between two vector spaces\ndata LinearMap (m :: Nat) (n :: Nat) where\n LinearMap :: (KnownNat m, KnownNat n) =>\n (R n -> R m) -- ^ Forward Function\n -> (R m -> R n) -- ^ Adjoint FunctionLS\n -> LinearMap m n\n\n-- | Extract the foward function from a `LinearMap`\nforward :: LinearMap m n -> (R n -> R m)\nforward (LinearMap f _) = f\n\n-- | Extract the adjoint function from a `LinearMap`\nadjoint :: LinearMap m n -> (R m -> R n)\nadjoint (LinearMap _ a) = a\n\ninstance Transposable (LinearMap n m) (LinearMap m n) where\n -- We do not have different functions for conjugate transposes in the\n -- LinearMap constructor (yet?)\n tr (LinearMap f a) = LinearMap a f\n tr' = tr\n\n\n---------------------------------------------------------------------\n-- Conversions between matrices and matrix free forms --\n---------------------------------------------------------------------\n\n-- | Convert a static matrix into the matrix free data type. This merely\n-- wraps the matrix in a function (eta abstraction); it does not determine\n-- the function associated with a given matrix.\nfromL :: (KnownNat m, KnownNat n) =>\n L m n -- ^ Static matrix to convert to matrix free data type\n -> LinearMap m n\nfromL a = LinearMap (a #>) (tr a #>)\n\n-- | Convert a matrix free linear map into a static matrix.\n--\n-- This methods is very inefficient as it traverses several components\n-- linearly several times.\ntoL :: (KnownNat m, KnownNat n) => LinearMap m n -> L m n\ntoL (LinearMap f _) =\n matrix $ concatMap (V.toList . extract . f) (toColumns eye)\n\n\n---------------------------------------------------------------------------\n-- Example LinearMaps --\n---------------------------------------------------------------------------\n\n-- | The identity matrix in matrix free form.\neyeFree :: (KnownNat n) => LinearMap n n\neyeFree = LinearMap id id\n\n\n-- | Take the average of a vector.\navg :: forall n. (KnownNat n) => R n -> Double\navg v = v <.> 1 / n' where n' = fromIntegral . natVal $ (Proxy :: Proxy n)\n\n\n-- | mean(v) * 1, where 1 is the ones vector. of length v.\navgRepeatedFree :: (KnownNat n) => LinearMap n n\navgRepeatedFree = LinearMap f f where f v = LS.konst (avg v)\n\n\n-- | Remove the average value of a vector from each element of the vector.\nremoveAvg :: (KnownNat n) => LinearMap n n\nremoveAvg = eyeFree +# ((-1) *# avgRepeatedFree)\n\n\n-- | The constant matrix, which sums the vector and sets every element of\n-- the resulting vector to that sum.\nkonst :: (KnownNat m, KnownNat n) => Double -> LinearMap m n\nkonst k = LinearMap sumAndRepeat sumAndRepeat\n where\n sumAndRepeat :: (KnownNat p, KnownNat q) => R p -> R q\n sumAndRepeat v = LS.konst (v <.> LS.konst k)\n\n-- | Convert a vector into a diagonal matrix.\ndiag :: (KnownNat n) => R n -> LinearMap n n\ndiag r = LinearMap f f\n where\n f v = zipWithVector (*) r v\n\n-- TODO: Define fft in matrix free form using FFT and IFFT\n\n---------------------------------------------------------------------\n-- Operators for composing LinearMaps --\n---------------------------------------------------------------------\n\n-- | Apply matrix free LinearMap to a vector\n(##>) :: LinearMap n m -> R m -> R n\n(##>) (LinearMap f _) = f\n\ninfixr 8 ##>\n\n\n-- | Matrix multiply of two `LinearMap`s\n(<#>) :: LinearMap m n\n -> LinearMap n p\n -> LinearMap m p\n(<#>) (LinearMap f_a a_a) (LinearMap f_b a_b) =\n LinearMap (f_a . f_b) (a_b . a_a)\n\ninfixr 8 <#>\n\n\n-- | Multiply a LinearMap matrix by a constant real number\n(*#) :: (KnownNat m, KnownNat n) => Double -> LinearMap m n -> LinearMap m n\n(*#) s (LinearMap f a) = LinearMap (\\v -> LS.konst s * f v) (\\v -> LS.konst s * a v)\n\ninfixr 8 *#\n\n\n-- | Add two `LinearMap`s together if they have the same shape.\n(+#) :: (KnownNat m, KnownNat n) =>\n LinearMap m n\n -> LinearMap m n\n -> LinearMap m n\n(+#) (LinearMap f_a a_a) (LinearMap f_b a_b) =\n LinearMap (\\v -> f_b v + f_a v) (\\v -> a_b v + a_a v)\n\ninfixr 7 +#\n\n\n-----------------------------------------------------------------------------\n-- Runtime Proofs on LinearMap shape --\n-----------------------------------------------------------------------------\n\n-- | Useful for constraining two dependently typed LinearMap matrices to\n-- match each other in dimensions when they are unknown at compile-time.\nexactDimsFree :: forall m n j k.\n (KnownNat n, KnownNat m, KnownNat j, KnownNat k) =>\n LinearMap m n\n -> Maybe (LinearMap j k)\nexactDimsFree (LinearMap f b) = do\n Refl <- sameNat (Proxy :: Proxy m) (Proxy :: Proxy j)\n Refl <- sameNat (Proxy :: Proxy n) (Proxy :: Proxy k)\n return $ LinearMap f b\n\n-- | Useful for constraining that two dependently typed LinearMap matrices\n-- match in their inner dimensions (enabling matrix multiplication) each\n-- other in dimensions when they are unknown at compile-time.\ninnerDimsFree :: forall m n p q. (KnownNat n, KnownNat p) =>\n LinearMap m n -- ^ The left LinearMap in a matrix multiply\n -> LinearMap p q -- ^ The right LinearMap in a matrix multiply\n -> Maybe (n :~: p) -- ^ Proof that the inner dimensions are equal\ninnerDimsFree (LinearMap _ _) (LinearMap _ _) = do\n Refl <- sameNat (Proxy :: Proxy n) (Proxy :: Proxy p)\n return (Refl)\n", "meta": {"hexsha": "baaf8f2ed36cd625c2fa0468677302351c42b78a", "size": 6738, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/MatrixFree.hs", "max_stars_repo_name": "ryanorendorff/convex", "max_stars_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-06-13T21:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T15:53:28.000Z", "max_issues_repo_path": "src/Numeric/LinearAlgebra/MatrixFree.hs", "max_issues_repo_name": "ryanorendorff/convex", "max_issues_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LinearAlgebra/MatrixFree.hs", "max_forks_repo_name": "ryanorendorff/convex", "max_forks_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5538461538, "max_line_length": 84, "alphanum_fraction": 0.5630750965, "num_tokens": 1699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5573943557104153}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.LinearAlgebra\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Linear algebra types and operations\n--\n\nmodule Numeric.LinearAlgebra (\n -- * Vector types\n Vector,\n RVector,\n STVector,\n IOVector,\n \n -- * Matrix types\n Matrix,\n RMatrix,\n STMatrix,\n IOMatrix,\n \n -- * Packed matrix types\n Packed,\n RPacked,\n STPacked,\n IOPacked,\n \n module Numeric.LinearAlgebra.Types,\n ) where\n\nimport Numeric.LinearAlgebra.Types\nimport Numeric.LinearAlgebra.Vector( Vector, RVector, STVector, IOVector )\nimport Numeric.LinearAlgebra.Matrix( Matrix, RMatrix, STMatrix, IOMatrix )\nimport Numeric.LinearAlgebra.Packed( Packed, RPacked, STPacked, IOPacked )\n", "meta": {"hexsha": "6e69ce68c5a7690a9e1cb4972f23f13081f7c0e8", "size": 930, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Numeric/LinearAlgebra.hs", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 24.4736842105, "max_line_length": 77, "alphanum_fraction": 0.623655914, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.82446190912407, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5571421838419232}} {"text": "module MachineLearning.PCATest\n(\n tests\n)\n\nwhere\n\nimport Test.Framework (testGroup)\nimport Test.Framework.Providers.HUnit\nimport Test.HUnit\nimport Test.HUnit.Approx\n\nimport qualified Numeric.LinearAlgebra as LA\n\nimport MachineLearning.PCA\n\ngetDimReducerSmokeTest =\n let nFeatures = 4\n nExamples = 7\n m = LA.matrix nFeatures [1 .. fromIntegral $ nFeatures*nExamples]\n m10 = m * 10\n (reduceDims, retainedVariance, mReduced) = getDimReducer m 2\n m10Reduced = reduceDims m10\n in do\n assertEqual \"dimension equality (getDimReducer)\" (LA.cols mReduced) 2\n assertEqual \"dimension equality (reduceDims)\" (LA.cols m10Reduced) 2\n assertApproxEqual \"retained variance\" 1e-10 1 retainedVariance\n\ngetDimReducer_rvSmokeTest rv=\n let nFeatures = 4\n nExamples = 7\n m = LA.matrix nFeatures [1 .. fromIntegral $ nFeatures*nExamples]\n m10 = m * 10\n (reduceDims, k, mReduced) = getDimReducer_rv m rv\n m10Reduced = reduceDims m10\n in do\n assertEqual \"dimension equality (getDimReducer_rv)\" (LA.cols mReduced) k\n assertEqual \"dimension equality (reduceDims_rv)\" (LA.cols m10Reduced) k\n assertBool \"reduced number of dimensions\" $ k <= nFeatures\n\ntests = [ testGroup \"smoke test\" [\n testCase \"getDimReducer\" getDimReducerSmokeTest\n , testCase \"getDimReducer_rv, rv = 0\" $ getDimReducer_rvSmokeTest 0\n , testCase \"getDimReducer_rv, rv = 0.5\" $ getDimReducer_rvSmokeTest 0.5\n , testCase \"getDimReducer_rv, rv = 1\" $ getDimReducer_rvSmokeTest 1\n , testCase \"getDimReducer_rv, rv = 2\" $ getDimReducer_rvSmokeTest 2\n ]\n ]\n", "meta": {"hexsha": "55639e7c39e017c94919b144b5447930f86b49de", "size": 1640, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/MachineLearning/PCATest.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "test/MachineLearning/PCATest.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "test/MachineLearning/PCATest.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 33.4693877551, "max_line_length": 83, "alphanum_fraction": 0.7018292683, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.557072813085701}} {"text": "module D03Spec (spec) where\n\nimport Test.Hspec\nimport D03\nimport Data.Complex\n\nspec :: Spec\nspec = do\n\n describe \"utilities\" $ do\n it \"parses into claims\" $ mkClaims \"#1 @ 146,196: 19x14\\n#2 @ 641,817: 27x28\" `shouldBe` [ Claim 1 (146:+196) (164:+209), Claim 2 (641:+817) (667:+844) ]\n\n describe \"intersections size\" $ do\n it \"simple example\" $ claimsIntersectionSize \"#1 @ 1,3: 4x4\\n#2 @ 3,1: 4x4\\n#3 @ 5,5: 2x2\" `shouldBe` 4\n it \"other example\" $ claimsIntersectionSize \"#1 @ 1,2: 3x3\\n#2 @ 2,3: 3x4\\n#3 @ 1,5: 3x3\" `shouldBe` 8\n it \"overlap example\" $ claimsIntersectionSize \"#1 @ 1,2: 3x3\\n#2 @ 2,3: 3x4\\n#3 @ 1,5: 3x3\\n#4 @ 2,5: 2x3\" `shouldBe` 10\n it \"other overlap example\" $ claimsIntersectionSize \"#1 @ 1,2: 3x3\\n#2 @ 2,3: 3x4\\n#3 @ 1,5: 3x3\\n#4 @ 2,5: 2x3\\n#5 @ 2,2: 3x3\" `shouldBe` 14\n it \"submits answer\" $ do input <- readFile \"test/D03.txt\"; claimsIntersectionSize input `shouldBe` 106501\n\n describe \"isolated claim\" $ do\n it \"simple example\" $ isolatedClaim \"#1 @ 1,3: 4x4\\n#2 @ 3,1: 4x4\\n#3 @ 5,5: 2x2\" `shouldBe` 3\n it \"submits answer\" $ do input <- readFile \"test/D03.txt\"; isolatedClaim input `shouldBe` 632\n \n\n\n \n", "meta": {"hexsha": "a0f617285a56bebdacce5a8525a94dc28e7b8421", "size": 1162, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/D03Spec.hs", "max_stars_repo_name": "Oaz/aoc2018", "max_stars_repo_head_hexsha": "7a3dc0a62581aad0bae8d69da80d87fe40592cc7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/D03Spec.hs", "max_issues_repo_name": "Oaz/aoc2018", "max_issues_repo_head_hexsha": "7a3dc0a62581aad0bae8d69da80d87fe40592cc7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/D03Spec.hs", "max_forks_repo_name": "Oaz/aoc2018", "max_forks_repo_head_hexsha": "7a3dc0a62581aad0bae8d69da80d87fe40592cc7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.037037037, "max_line_length": 157, "alphanum_fraction": 0.6376936317, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5570727979342261}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MagicHash #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UnboxedTuples #-}\n{-# LANGUAGE UndecidableInstances #-}\nmodule Numeric.Matrix.Internal\n ( MatrixTranspose (..)\n , SquareMatrix (..)\n , MatrixDeterminant (..)\n , MatrixInverse (..)\n , Matrix\n , HomTransform4 (..)\n , Mat22f, Mat23f, Mat24f\n , Mat32f, Mat33f, Mat34f\n , Mat42f, Mat43f, Mat44f\n , Mat22d, Mat23d, Mat24d\n , Mat32d, Mat33d, Mat34d\n , Mat42d, Mat43d, Mat44d\n , mat22, mat33, mat44\n , (%*)\n ) where\n\nimport GHC.Base\nimport Numeric.DataFrame.Contraction ((%*))\nimport Numeric.DataFrame.Internal.PrimArray\nimport Numeric.DataFrame.Type\nimport Numeric.Dimensions\nimport Numeric.Scalar.Internal\nimport Numeric.Vector.Internal\n\n-- | Alias for DataFrames of rank 2\ntype Matrix (t :: l) (n :: k) (m :: k) = DataFrame t '[n,m]\n\nclass MatrixTranspose t (n :: k) (m :: k) where\n -- | Transpose Mat\n transpose :: Matrix t n m -> Matrix t m n\n\nclass SquareMatrix t (n :: Nat) where\n -- | Mat with 1 on diagonal and 0 elsewhere\n eye :: Matrix t n n\n -- | Put the same value on the Mat diagonal, 0 otherwise\n diag :: Scalar t -> Matrix t n n\n -- | Sum of diagonal elements\n trace :: Matrix t n n -> Scalar t\n\nclass MatrixDeterminant t (n :: Nat) where\n -- | Determinant of Mat\n det :: Matrix t n n -> Scalar t\n\nclass MatrixInverse t (n :: Nat) where\n -- | Matrix inverse\n inverse :: Matrix t n n -> Matrix t n n\n\n\n-- | Operations on 4x4 transformation matrices and vectors in homogeneous coordinates.\n-- All angles are specified in radians.\n--\n-- Note: since version 2 of @easytensor@, DataFrames and matrices are row-major.\n-- A good SIMD implementation may drastically improve performance\n-- of 4D vector-matrix products of the form @v %* m@, but not so much\n-- for products of the form @m %* v@ (due to memory layout).\n-- Thus, all operations here assume the former form to benefit more from\n-- SIMD in future.\nclass HomTransform4 t where\n -- | Create a translation matrix from a vector. The 4th coordinate is ignored.\n --\n -- If @p ! 3 == 1@ and @v ! 3 == 0@, then\n --\n -- > p %* translate4 v == p + v\n --\n translate4 :: Vector t 4 -> Matrix t 4 4\n -- | Create a translation matrix from a vector.\n --\n -- If @p ! 3 == 1@, then\n --\n -- > p %* translate3 v == p + toHomVector v\n --\n translate3 :: Vector t 3 -> Matrix t 4 4\n -- | Rotation matrix for a rotation around the X axis, angle is given in radians.\n -- e.g. @p %* rotateX (pi/2)@ rotates point @p@ around @Ox@ by 90 degrees.\n rotateX :: t -> Matrix t 4 4\n -- | Rotation matrix for a rotation around the Y axis, angle is given in radians.\n -- e.g. @p %* rotateY (pi/2)@ rotates point @p@ around @Oy@ by 90 degrees.\n rotateY :: t -> Matrix t 4 4\n -- | Rotation matrix for a rotation around the Z axis, angle is given in radians.\n -- e.g. @p %* rotateZ (pi/2)@ rotates point @p@ around @Oz@ by 90 degrees.\n rotateZ :: t -> Matrix t 4 4\n -- | Rotation matrix for a rotation around an arbitrary normalized vector\n -- e.g. @p %* rotate (pi/2) v@ rotates point @p@ around @v@ by 90 degrees.\n rotate :: Vector t 3 -> t -> Matrix t 4 4\n -- | Rotation matrix from the Euler angles roll (axis @Z@), yaw (axis @Y'@), and pitch (axis @X''@).\n -- This order is known as Tait-Bryan angles (@Z-Y'-X''@ intrinsic rotations), or nautical angles, or Cardan angles.\n --\n -- > rotateEuler pitch yaw roll == rotateZ roll %* rotateY yaw %* rotateX pitch\n --\n -- https://en.wikipedia.org/wiki/Euler_angles#Conventions_2\n rotateEuler :: t -- ^ pitch (axis @X''@)\n -> t -- ^ yaw (axis @Y'@)\n -> t -- ^ roll (axis @Z@)\n -> Matrix t 4 4\n -- | Create a transform matrix using up direction, camera position and a point to look at.\n -- Just the same as GluLookAt.\n lookAt :: Vector t 3 -- ^ The up direction, not necessary unit length or perpendicular to the view vector\n -> Vector t 3 -- ^ The viewers position\n -> Vector t 3 -- ^ The point to look at\n -> Matrix t 4 4\n -- | A perspective symmetric projection matrix. Right-handed coordinate system. (@x@ - right, @y@ - top)\n -- http://en.wikibooks.org/wiki/GLSL_Programming/Vertex_Transformations\n perspective :: t -- ^ Near plane clipping distance (always positive)\n -> t -- ^ Far plane clipping distance (always positive)\n -> t -- ^ Field of view of the y axis, in radians\n -> t -- ^ Aspect ratio, i.e. screen's width\\/height\n -> Matrix t 4 4\n -- | An orthogonal symmetric projection matrix. Right-handed coordinate system. (@x@ - right, @y@ - top)\n -- http://en.wikibooks.org/wiki/GLSL_Programming/Vertex_Transformations\n orthogonal :: t -- ^ Near plane clipping distance\n -> t -- ^ Far plane clipping distance\n -> t -- ^ width\n -> t -- ^ height\n -> Matrix t 4 4\n -- | Add one more dimension and set it to 1.\n toHomPoint :: Vector t 3 -> Vector t 4\n -- | Add one more dimension and set it to 0.\n toHomVector :: Vector t 3 -> Vector t 4\n -- | Transform a homogenous vector or point into a normal 3D vector.\n -- If the last coordinate is not zero, divide the rest by it.\n fromHom :: Vector t 4 -> Vector t 3\n\n-- Type abbreviations\n\ntype Mat22f = Matrix Float 2 2\ntype Mat32f = Matrix Float 3 2\ntype Mat42f = Matrix Float 4 2\ntype Mat23f = Matrix Float 2 3\ntype Mat33f = Matrix Float 3 3\ntype Mat43f = Matrix Float 4 3\ntype Mat24f = Matrix Float 2 4\ntype Mat34f = Matrix Float 3 4\ntype Mat44f = Matrix Float 4 4\n\ntype Mat22d = Matrix Double 2 2\ntype Mat32d = Matrix Double 3 2\ntype Mat42d = Matrix Double 4 2\ntype Mat23d = Matrix Double 2 3\ntype Mat33d = Matrix Double 3 3\ntype Mat43d = Matrix Double 4 3\ntype Mat24d = Matrix Double 2 4\ntype Mat34d = Matrix Double 3 4\ntype Mat44d = Matrix Double 4 4\n\n\n-- | Compose a 2x2D matrix\nmat22 :: PrimBytes (t :: Type)\n => Vector t 2 -> Vector t 2 -> Matrix t 2 2\nmat22 = packDF @_ @2 @'[2]\n{-# INLINE mat22 #-}\n\n-- | Compose a 3x3D matrix\nmat33 :: PrimBytes (t :: Type)\n => Vector t 3 -> Vector t 3 -> Vector t 3 -> Matrix t 3 3\nmat33 = packDF @_ @3 @'[3]\n{-# INLINE mat33 #-}\n\n-- | Compose a 4x4D matrix\nmat44 :: PrimBytes (t :: Type)\n => Vector t 4\n -> Vector t 4\n -> Vector t 4\n -> Vector t 4\n -> Matrix t 4 4\nmat44 = packDF @_ @4 @'[4]\n{-# INLINE mat44 #-}\n\n\n\ninstance ( KnownDim n, KnownDim m\n , PrimArray t (Matrix t n m)\n , PrimArray t (Matrix t m n)\n ) => MatrixTranspose t (n :: Nat) (m :: Nat) where\n transpose df = case uniqueOrCumulDims df of\n Left a -> broadcast a\n Right _\n | wm <- dimVal' @m\n , wn <- dimVal' @n\n , m <- case wm of W# w -> word2Int# w\n , n <- case wn of W# w -> word2Int# w\n -> let f ( I# i, I# j )\n | isTrue# (i ==# n) = f ( 0, I# (j +# 1#) )\n | otherwise = (# ( I# (i +# 1#), I# j )\n , ix# (i *# m +# j) df\n #)\n in case gen# (CumulDims [wm*wn, wn, 1]) f (0,0) of (# _, r #) -> r\n\ninstance MatrixTranspose (t :: Type) (xn :: XNat) (xm :: XNat) where\n transpose (XFrame (df :: DataFrame t ns))\n | ((D :: Dim n) :* (D :: Dim m) :* U) <- dims @ns\n , Dict <- inferPrimElem df\n = XFrame (transpose df :: Matrix t m n)\n transpose _ = error \"MatrixTranspose/transpose: impossible argument\"\n\ninstance (KnownDim n, PrimArray t (Matrix t n n), Num t)\n => SquareMatrix t n where\n eye\n | n <- dimVal' @n\n = let f 0 = (# n , 1 #)\n f k = (# k - 1, 0 #)\n in case gen# (CumulDims [n*n, n, 1]) f 0 of\n (# _, r #) -> r\n diag se\n | n <- dimVal' @n\n , e <- unScalar se\n = let f 0 = (# n , e #)\n f k = (# k - 1, 0 #)\n in case gen# (CumulDims [n*n, n, 1]) f 0 of\n (# _, r #) -> r\n trace df\n | I# n <- fromIntegral $ dimVal' @n\n , n1 <- n +# 1#\n = let f 0# = ix# 0# df\n f k = ix# k df + f (k -# n1)\n in scalar $ f (n *# n -# 1#)\n", "meta": {"hexsha": "d5d36b34908b28d8cda3effe44045012c17404f5", "size": 8773, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "easytensor/src/Numeric/Matrix/Internal.hs", "max_stars_repo_name": "cjay/easytensor", "max_stars_repo_head_hexsha": "d79f797fa06087a7805667bdcd8916b7977eae8a", "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": "easytensor/src/Numeric/Matrix/Internal.hs", "max_issues_repo_name": "cjay/easytensor", "max_issues_repo_head_hexsha": "d79f797fa06087a7805667bdcd8916b7977eae8a", "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": "easytensor/src/Numeric/Matrix/Internal.hs", "max_forks_repo_name": "cjay/easytensor", "max_forks_repo_head_hexsha": "d79f797fa06087a7805667bdcd8916b7977eae8a", "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.9783549784, "max_line_length": 121, "alphanum_fraction": 0.5686766215, "num_tokens": 2637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236823, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5568886386310482}} {"text": "-- TODO: Avoid recomputing norms and reg const\n\n{-# LANGUAGE BangPatterns, FlexibleContexts, NamedFieldPuns #-}\n\nmodule School.Unit.LogSoftMax\n( logSoftMax ) where\n\nimport Numeric.LinearAlgebra (Container, Matrix, R, Vector, add, atIndex,\n build, cmap, maxElement, size, sumElements)\nimport School.Unit.Unit (Unit(..))\nimport School.Unit.UnitActivation (UnitActivation(..))\nimport School.Unit.UnitParams (UnitParams(..))\nimport School.Unit.UnitGradient (UnitGradient(..))\nimport School.Utils.LinearAlgebra (mapRows, sumCols)\n\nlogSoftMax :: Unit R\nlogSoftMax = Unit\n { apply = lsmApply\n , deriv = lsmDeriv\n }\n\ngetNorm :: (Container Vector a, Floating a)\n => a\n -> Vector a\n -> a\ngetNorm reg = log\n . sumElements\n . cmap (exp . flip (-) reg)\n\nhandleRow :: (Container Vector a, Floating a)\n => Vector a\n -> Vector a\nhandleRow v =\n let !reg = maxElement v\n !norm = getNorm reg v\n in cmap (flip (-) (norm + reg)) v\n\nlsmApply :: UnitParams R\n -> UnitActivation R\n -> UnitActivation R\nlsmApply EmptyParams (BatchActivation inMatrix) =\n BatchActivation $ mapRows handleRow inMatrix\nlsmApply _ (ApplyFail msg) = ApplyFail msg\nlsmApply _ _ = ApplyFail \"Failure when applying log softmax unit\"\n\nfailure :: String\n -> ( UnitGradient R\n , UnitParams R\n )\nfailure msg = (GradientFail msg, EmptyParams)\n\nbuilder :: (Container Vector a, RealFrac a)\n => Matrix a\n -> Vector a\n -> Vector a\n -> (a -> a -> a)\nbuilder exps norms gradCols dj dk =\n let j = round dj :: Int\n k = round dk :: Int\n in (-1) * atIndex exps (j, k)\n * atIndex gradCols j\n / atIndex norms j\n\nlsmDeriv :: UnitParams R\n -> UnitGradient R\n -> UnitActivation R\n -> ( UnitGradient R\n , UnitParams R\n )\nlsmDeriv EmptyParams\n (BatchGradient inGrad)\n (BatchActivation input) =\n (outGrad, EmptyParams) where\n !reg = maxElement input\n !exps = cmap (exp . flip (-) reg) input\n !norms = sumCols exps\n !gradCols = sumCols inGrad\n delta = build (size input) (builder exps norms gradCols)\n outGrad = BatchGradient $ add inGrad delta\nlsmDeriv _ (GradientFail msg) _ = failure msg\nlsmDeriv _ _ (ApplyFail msg) = failure msg\nlsmDeriv _ _ _ = failure \"Failure when differentiating log softmax unit\"\n", "meta": {"hexsha": "27d75e0326e06ebc72c000e23b797614aef30cb3", "size": 2385, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/School/Unit/LogSoftMax.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/School/Unit/LogSoftMax.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/School/Unit/LogSoftMax.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.734939759, "max_line_length": 73, "alphanum_fraction": 0.6385744235, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5568540906557925}} {"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Models where\n\nimport Foreign.Storable (Storable)\nimport Numeric.LinearAlgebra ((<.>), (<>), (#>), inv, sumElements, Container)\nimport Numeric.LinearAlgebra.Data (vector, matrix, Matrix, (><), Vector, tr'\n ,cmap, ident, size, fromRows)\n\nclass Trainable m a b where\n train :: m a b -> [(a,b)] -> m a b\n\nclass Predictive m where\n predict :: m a b -> a -> b\n\ntype LBWeights = Matrix Double\ntype LBFuncs a = [a -> Double]\n\ndata LBReg a b = LBReg { lbFuncs :: LBFuncs a\n , lbWeights :: LBWeights\n , lbError :: Double\n , lbReg :: Double\n , lbPredict :: LBWeights\n -> LBFuncs a\n -> a\n -> b\n }\n\ninstance Trainable LBReg [a] (Vector Double) where\n train = trainLBReg\n\ninstance Predictive LBReg where\n predict m = lbPredict m (lbWeights m) (lbFuncs m)\n\nupdateWeights x w e = x { lbWeights = w, lbError = e }\n\ntrainLBReg :: LBReg [a] (Vector Double) -> [([a], Vector Double)] -> LBReg [a] (Vector Double)\ntrainLBReg m d = updateWeights m w e where\n t = fromRows (fmap snd d)\n fs = lbFuncs m\n dps = fmap fst d\n p = lbPredict m\n reg = lbReg m\n iden = ident $ 1 + (length . head) dps :: Matrix Double\n dm = tr' $ (length fs >< length dps) $ fs <*> dps\n w = (inv (cmap (reg*) iden + (tr' dm <> dm)) <> tr' dm) <> t\n e = 2--sosError t pr where pr = vector $ fmap (p w fs) dps\n\nsosError :: Vector Double -> Vector Double -> Double\nsosError t pr = 0--sumElements $ cmap ((/2) . (**2)) $ t - pr\n\nlbEval :: LBWeights -> LBFuncs a -> a -> Vector Double\nlbEval w fs d = tr' w #> vector (zipWith ($) fs $ replicate (length fs) d)\n\nmkLBId :: Int -> LBFuncs [Double]\nmkLBId n = const 1 : [(!!x) | x <- [0 .. n-1]]\n\nmkSLBReg :: Double -> [([Double], Vector Double)] -> LBReg [Double] (Vector Double)\nmkSLBReg reg ds = train LBReg { lbFuncs = mkLBId n\n , lbWeights = (n> Complex Double\n , fpsConfig :: Int\n -- the simulation will play this times faster than real time\n -- mainly to keep time steps small while keeping fps low\n -- the time step in each simulation will be this divided by fps\n , timeFactorConfig :: TimeStep\n }\n\n\n\ntype TimeStep = Double\n\ndata Position = Position { posX :: Int , posY :: Int }\n deriving (Eq, Ord, Show)\n\n\ntype Variance = Double\n\n\ngaussianWave :: Int -> Int -> Variance -> (Position -> Complex Double)\ngaussianWave xCenter yCenter var = \\(Position x y) -> \n ( exp ( (\n - ( ((fromIntegral (x - xCenter))P.^2) P.+ ((fromIntegral (y - yCenter) )P.^2) )\n ) P./ (2 P.* (var P.^ 2))\n )\n ) :+ 0\n\n\n\nsmallBoxConfig :: OscillatorInABoxConfig\nsmallBoxConfig = OscillatorInABoxConfig { plankConstantConfig = 6.62607004e-16 -- scaling length dimension by 10^9 so that 1 corresponds to 1 nm\n , particleMassConfig = 10e-31 -- roughly mass of an electron\n , oscillatorFrequencyConfig = 10000\n , halfWidthConfig = 10\n , halfHeightConfig = 10\n -- tune variance of wave based on mass and frequency (and Plank's constant) to get a nice simulation\n , initialAmplitudeConfig = gaussianWave 0 0 3.8845e-6\n , fpsConfig = 30\n , timeFactorConfig = 1\n }\n\nbigBoxConfig :: OscillatorInABoxConfig\nbigBoxConfig = OscillatorInABoxConfig { plankConstantConfig = 6.62607004e-16 -- scaling length dimension by 10^9 so that 1 corresponds to 1 nm\n , particleMassConfig = 10e-31\n , oscillatorFrequencyConfig = 10000\n , halfWidthConfig = 100\n , halfHeightConfig = 100\n -- tune variance of wave based on mass and frequency (and Plank's constant) to get a nice simulation\n , initialAmplitudeConfig = gaussianWave 0 0 3.8845e-6\n , fpsConfig = 30\n , timeFactorConfig = 1\n } \n\n\n---------------------\n-- Helper functions to generate lattice and translate between two dimensional position and one dimensional array\n-- may not need to modify these\n--------------------\n\npositionRangeConfig :: OscillatorInABoxConfig -> [Position]\npositionRangeConfig config = [Position x y | x <- [-halfWidth .. halfWidth], y <- [-halfHeight .. halfHeight]]\n where halfWidth = halfWidthConfig config\n halfHeight = halfHeightConfig config\n\n\nindexRangeConfig :: OscillatorInABoxConfig -> Int\nindexRangeConfig config = (2 * halfWidth + 1) * (2 * halfHeight + 1)\n where halfWidth = halfWidthConfig config\n halfHeight = halfHeightConfig config\n\n\npositionToIndexConfig :: OscillatorInABoxConfig -> Position -> Int\npositionToIndexConfig config pos = ((posX pos + halfWidth) * (2 * halfHeight + 1)) + (posY pos + halfHeight)\n where halfWidth = halfWidthConfig config\n halfHeight = halfHeightConfig config\n \n\nindexToPositionConfig :: OscillatorInABoxConfig -> Int -> Position\nindexToPositionConfig config index = Position ( (floor ((fromIntegral index) P./ (fromIntegral $! 2 * halfHeight + 1))) - halfWidth )\n ( (index `mod` (2 * halfHeight + 1)) - halfHeight )\n where halfWidth = halfWidthConfig config\n halfHeight = halfHeightConfig config\n \n\n\n\n\n------------------------------------\n-- simulate oscillation using Eigen library's sparse matrices\n------------------------------------\n\n\nsparseMatModelSimulator :: OscillatorInABoxConfig\n -> ( TimeStep -> SparseMatOperator (Complex Double) (CComplex CDouble) Position\n , SparseMatKet (Complex Double) (CComplex CDouble) Position\n , SparseMatKet (Complex Double) (CComplex CDouble) Position -> Picture\n , OscillatorInABoxConfig\n ) \nsparseMatModelSimulator config = (oscillationOperator, initialModel, drawing, config)\n where\n -- shorthands for config params\n positionRange = positionRangeConfig config\n halfWidth = halfWidthConfig config\n halfHeight = halfHeightConfig config\n indexRange = indexRangeConfig config\n\n positionToIndex = positionToIndexConfig config\n indexToPosition = indexToPositionConfig config\n\n plankConstant = plankConstantConfig config\n particleMass = particleMassConfig config\n oscillatorFrequency = oscillatorFrequencyConfig config\n \n initialAmplitude = initialAmplitudeConfig config\n \n \n -- position and momentum operators\n \n posXOp :: SparseMatOperator (Complex Double) (CComplex CDouble) Position\n posXOp = SparseMatOperator $! ES.fromList indexRange indexRange $! map (\\pos@(Position x _) -> (positionToIndex pos, positionToIndex pos, fromIntegral x)) positionRange\n\n posYOp :: SparseMatOperator (Complex Double) (CComplex CDouble) Position\n posYOp = SparseMatOperator $! ES.fromList indexRange indexRange $! map (\\pos@(Position _ y) -> (positionToIndex pos, positionToIndex pos, fromIntegral y)) positionRange\n\n momXOp :: SparseMatOperator (Complex Double) (CComplex CDouble) Position\n -- taking dx as 2\n -- = -ih ( d/dx(a)|_x' ) = - ( a(x'+1) - a(x'-1) ) * ih/2 = - ( - ) * ih / 2\n momXOp = SparseMatOperator $! ES.fromList indexRange indexRange $! ( (map (\\pos@(Position x y) -> ( positionToIndex pos\n , positionToIndex (Position (x P.+ 1) y)\n , 0 :+ (- plankConstant/2)\n )\n )\n -- removing max x from position range to keep operator within lattice\n -- that would give 0 contribution anyway\n [Position i j | i <- [(-halfWidth) .. (halfWidth-1)], j <- [-(halfHeight) .. halfHeight]]\n )\n ++\n (map (\\pos@(Position x y) -> ( positionToIndex pos\n , positionToIndex (Position (x P.- 1) y)\n , 0 :+ ( plankConstant/2)\n )\n )\n -- removing min x from position range to keep operator within lattice\n -- that would give 0 contribution anyway\n [Position i j | i <- [-(halfWidth-1) .. (halfWidth)], j <- [-(halfHeight) .. halfHeight]]\n )\n )\n \n momYOp :: SparseMatOperator (Complex Double) (CComplex CDouble) Position\n -- taking dy as 2\n -- = -ih ( d/dy(a)|_y' ) = - ( a(y'+1) - a(y'-1) ) * ih/2 = - ( - ) * ih / 2\n momYOp = SparseMatOperator $! ES.fromList indexRange indexRange $! ( (map (\\pos@(Position x y) -> ( positionToIndex pos\n , positionToIndex (Position x (y P.+ 1))\n , 0 :+ (- plankConstant/2)\n )\n )\n -- removing max y from position range to keep operator within lattice\n -- that would give 0 contribution anyway\n [Position i j | i <- [(-halfWidth) .. (halfWidth)], j <- [-(halfHeight) .. (halfHeight-1)]]\n )\n ++\n (map (\\pos@(Position x y) -> ( positionToIndex pos\n , positionToIndex (Position x (y P.- 1))\n , 0 :+ ( plankConstant/2)\n )\n )\n -- removing min y from position range to keep operator within lattice\n -- that would give 0 contribution anyway\n [Position i j | i <- [(-halfWidth) .. (halfWidth)], j <- [-(halfHeight-1) .. halfHeight]]\n )\n )\n\n momSquaredOp = (momXOp `pow1p` 2) + (momYOp `pow1p` 2)\n posSquaredOp = (posXOp `pow1p` 2) + (posYOp `pow1p` 2)\n \n\n idOp :: SparseMatOperator (Complex Double) (CComplex CDouble) Position\n idOp = SparseMatOperator $! ES.fromList indexRange indexRange $! map (\\pos@(Position _ _) -> (positionToIndex pos, positionToIndex pos, 1)) positionRange\n\n\n oscillationOperator :: Double -> SparseMatOperator (Complex Double) (CComplex CDouble) Position\n oscillationOperator dt =\n idOp + ( (0 :+ (0 P.- (dt P./ plankConstant))) .*\n (\n ( (((particleMass P./ 2) P.* (oscillatorFrequency P.^ 2)) :+ 0) .* posSquaredOp ) +\n ( ((1 P./ (2 P.* particleMass)) :+ 0) .* momSquaredOp )\n )\n )\n\n \n initialModel :: SparseMatKet (Complex Double) (CComplex CDouble) Position\n initialModel = normalizeVector $! SparseMatKet $! ES.fromList indexRange 1 $! map ( \\pos -> ( positionToIndex pos\n , 0\n , initialAmplitude pos\n )\n ) positionRange\n\n -- bitmap drawing\n drawing :: SparseMatKet (Complex Double) (CComplex CDouble) Position -> Picture\n drawing (SparseMatKet mat) =\n makePicture (2*halfWidth) (2*halfHeight)\n 1 1\n ( \\(x,y) -> let index = positionToIndex $! Position (round $! x P.* (P.fromIntegral halfWidth))\n (round $! y P.* (P.fromIntegral halfHeight))\n amp = mat ES.! (index, 0)\n den = double2Float $! normSquared amp\n in {-trace (show $ (index, amp, den)) $ -} rgb' den 0 0\n )\n where\n normSquared cn = (magnitude cn) P.^ 2\n\n\n {-\n -- drawing with objects\n drawing :: SparseMatKet (Complex Double) (CComplex CDouble) Position -> Picture\n drawing (SparseMatKet mat) = {- trace \"Drawing\" $ -}\n pictures $ catMaybes $ map (\\elem -> case elem of\n (index, 0, amp) -> let pos = indexToPosition index\n in Just $! translate (fromIntegral $! posX pos) (fromIntegral $! posY pos) $!\n color (withAlpha (double2Float $! normSquared amp) red) $!\n circleSolid 1\n _ -> trace \"OutOfBounds: \" Nothing\n ) $! ES.toList $! mat\n where\n normSquared cn = (magnitude cn) P.^ 2\n -}\n\n\n\n\n\n------------------------------------\n-- simulate oscillation using sparse maps\n------------------------------------\n\n\nsparseModelSimulator :: OscillatorInABoxConfig\n -> ( TimeStep -> SparseOperator (Complex Double) Position\n , SparseKet (Complex Double) Position\n , SparseKet (Complex Double) Position -> Picture\n , OscillatorInABoxConfig\n ) \nsparseModelSimulator config = (oscillationOperator, initialModel, drawing, config)\n where\n -- shorthands for config params\n positionRange = positionRangeConfig config\n halfWidth = halfWidthConfig config\n halfHeight = halfHeightConfig config\n\n plankConstant = plankConstantConfig config\n particleMass = particleMassConfig config\n oscillatorFrequency = oscillatorFrequencyConfig config\n \n initialAmplitude = initialAmplitudeConfig config\n \n \n -- position and momentum operators\n \n posXOp :: SparseOperator (Complex Double) Position\n posXOp = SparseOperator $! M.fromList $! map (\\pos@(Position x _) -> ((pos,pos), ((fromIntegral x) :+ 0))) positionRange\n\n posYOp :: SparseOperator (Complex Double) Position\n posYOp = SparseOperator $! M.fromList $! map (\\pos@(Position _ y) -> ((pos,pos), ((fromIntegral y) :+ 0))) positionRange\n\n momXOp :: SparseOperator (Complex Double) Position\n -- taking dx as 2\n -- = -ih ( d/dx(a)|_x' ) = - ( a(x'+1) - a(x'-1) ) * ih/2 = - ( - ) * ih / 2 \n momXOp = SparseOperator $! M.fromList $! ( (map (\\pos@(Position x y) -> ( (pos, Position (x P.+ 1) y), 0 :+ (- plankConstant/2) ))\n -- removing max x from position range to keeo operator within lattice\n -- that would give 0 contribution anyway\n [Position i j | i <- [(-halfWidth) .. (halfWidth-1)], j <- [-(halfHeight) .. halfHeight]]\n )\n ++\n (map (\\pos@(Position x y) -> ( (pos, Position (x P.- 1) y), 0 :+ ( plankConstant/2) ))\n -- removing min x from position range to keeo operator within lattice\n -- that would give 0 contribution anyway\n [Position i j | i <- [-(halfWidth-1) .. (halfWidth)], j <- [-(halfHeight) .. halfHeight]]\n )\n )\n\n momYOp :: SparseOperator (Complex Double) Position\n -- taking dy as 2\n -- = -ih ( d/dy(a)|_y' ) = - ( a(y'+1) - a(y'-1) ) * ih/2 = - ( - ) * ih / 2\n momYOp = SparseOperator $! M.fromList $! ( (map (\\pos@(Position x y) -> ( (pos, Position x (y P.+ 1)), 0 :+ (- plankConstant/2) ))\n -- removing max y from position range to keeo operator within lattice\n -- that would give 0 contribution anyway\n [Position i j | i <- [(-halfWidth) .. (halfWidth)], j <- [-(halfHeight) .. (halfHeight-1)]]\n )\n ++\n (map (\\pos@(Position x y) -> ( (pos, Position x (y P.- 1)), 0 :+ ( plankConstant/2) ))\n -- removing min y from position range to keeo operator within lattice\n -- that would give 0 contribution anyway\n [Position i j | i <- [(-halfWidth) .. (halfWidth)], j <- [-(halfHeight-1) .. halfHeight]]\n )\n \n )\n\n momSquaredOp = (momXOp `pow1p` 2) + (momYOp `pow1p` 2)\n posSquaredOp = (posXOp `pow1p` 2) + (posYOp `pow1p` 2)\n \n\n idOp :: SparseOperator (Complex Double) Position\n idOp = SparseOperator $! M.fromList $! map (\\pos@(Position _ _) -> ((pos,pos), 1)) positionRange\n\n\n oscillationOperator :: Double -> SparseOperator (Complex Double) Position\n oscillationOperator dt =\n idOp + ( (0 :+ (0 P.- (dt P./ plankConstant))) .*\n (\n ( (((particleMass P./ 2) P.* (oscillatorFrequency P.^ 2)) :+ 0) .* posSquaredOp ) +\n ( ((1 P./ (2 P.* particleMass)) :+ 0) .* momSquaredOp )\n )\n )\n\n \n initialModel :: SparseKet (Complex Double) Position\n initialModel = normalizeVector $! SparseKet $! M.fromList $! map ( \\pos -> (pos, initialAmplitude pos) ) positionRange\n\n -- bitmap drawing\n drawing :: SparseKet (Complex Double) Position -> Picture\n drawing (SparseKet coeffMap) =\n makePicture (2*halfWidth) (2*halfHeight)\n 1 1\n ( \\(x,y) -> let pos = Position (round $! x P.* (P.fromIntegral halfWidth))\n (round $! y P.* (P.fromIntegral halfHeight))\n maybeAmp = M.lookup pos coeffMap\n in case maybeAmp of\n Nothing -> rgb' 0 0 0\n Just amp -> let den = double2Float $! normSquared amp\n in {-trace (show $ (index, amp, den)) $ -} rgb' den 0 0\n )\n where\n normSquared cn = (magnitude cn) P.^ 2\n\n {-\n -- drawing with objects\n drawing :: SparseKet (Complex Double) Position -> Picture\n drawing (SparseKet coeffMap) = {- trace \"Drawing\" $ -} \n pictures $ map (\\((Position x y), amp) -> translate (fromIntegral x) (fromIntegral y) $!\n color (withAlpha (double2Float $! normSquared amp) red) $!\n circleSolid 1\n ) $! M.toList $! coeffMap\n where\n normSquared cn = (magnitude cn) P.^ 2\n -}\n\n\n\n------------------------------------\n-- Using repa arrays and matrices\n-- Matrix multiplication turns out to be the bottleneck\n-- Probably because it's not designed for sparse matrices\n-- can work for around halfWidth=2, halfHeight=2\n------------------------------------\n\n\narrayModelSimulator :: OscillatorInABoxConfig\n -> ( TimeStep -> LatticeOperator (Complex Double) Position\n , LatticeKet (Complex Double) Position\n , LatticeKet (Complex Double) Position -> Picture\n , OscillatorInABoxConfig\n )\narrayModelSimulator config = (oscillationOperator, initialModel, drawing, config)\n where\n -- shorthands for config params\n positionRange = positionRangeConfig config\n halfWidth = halfWidthConfig config\n halfHeight = halfHeightConfig config\n\n indexRange = indexRangeConfig config\n positionToIndex = positionToIndexConfig config\n indexToPosition = indexToPositionConfig config\n\n plankConstant = plankConstantConfig config\n particleMass = particleMassConfig config\n oscillatorFrequency = oscillatorFrequencyConfig config\n \n initialAmplitude = initialAmplitudeConfig config\n \n \n -- position and momentum operators\n \n posXOp :: LatticeOperator (Complex Double) Position\n posXOp = LatticeOperator $! R.fromFunction (Z :. indexRange :. indexRange) (\\(Z:.i:.j) -> if i==j\n then (fromIntegral $! posX $! indexToPosition i) :+ 0\n else 0\n )\n\n posYOp :: LatticeOperator (Complex Double) Position\n posYOp = LatticeOperator $! R.fromFunction (Z :. indexRange :. indexRange) (\\(Z:.i:.j) -> if i==j\n then (fromIntegral $! posY $! indexToPosition i) :+ 0\n else 0\n )\n\n momXOp :: LatticeOperator (Complex Double) Position\n -- taking dx as 2\n -- = -ih ( d/dx(a)|_x' ) = - ( a(x'+1) - a(x'-1) ) * ih/2 = - ( - ) * ih / 2 \n momXOp = LatticeOperator $! R.fromFunction (Z :. indexRange :. indexRange) (\\(Z:.i:.j) -> let xo = posX $! indexToPosition j\n yo = posY $! indexToPosition j\n xn = posX $! indexToPosition i\n yn = posY $! indexToPosition i\n in\n case yn==yo of\n False -> 0\n True\n |xn == xo P.+ 1 -> 0 :+ ( plankConstant/2)\n |xn == xo P.- 1 -> 0 :+ (- plankConstant/2)\n |otherwise -> 0\n )\n\n momYOp :: LatticeOperator (Complex Double) Position\n -- taking dy as 2\n -- = -ih ( d/dy(a)|_y' ) = - ( a(y'+1) - a(y'-1) ) * ih/2 = - ( - ) * ih / 2 \n momYOp = LatticeOperator $! R.fromFunction (Z :. indexRange :. indexRange) (\\(Z:.i:.j) -> let xo = posX $! indexToPosition j\n yo = posY $! indexToPosition j\n xn = posX $! indexToPosition i\n yn = posY $! indexToPosition i\n in\n case xn==xo of\n False -> 0\n True\n |yn == yo P.+ 1 -> 0 :+ ( plankConstant/2)\n |yn == yo P.- 1 -> 0 :+ (- plankConstant/2)\n |otherwise -> 0\n )\n\n momSquaredOp = (momXOp `pow1p` 2) + (momYOp `pow1p` 2)\n posSquaredOp = (posXOp `pow1p` 2) + (posYOp `pow1p` 2)\n\n\n -- identity operator\n -- can make operator an instance of Unital, but don't know any one of writing the identity matrix in repa independent of dimensions\n idOp :: LatticeOperator (Complex Double) Position\n idOp = LatticeOperator $! R.fromFunction (Z :. indexRange :. indexRange) (\\(Z:.i:.j) -> case i==j of\n False -> 0\n True -> 1\n )\n\n -- simulation operator\n oscillationOperator :: Double -> LatticeOperator (Complex Double) Position\n oscillationOperator dt =\n idOp + ( (0 :+ (0 P.- (dt P./ plankConstant))) .*\n (\n ( (((particleMass P./ 2) P.* (oscillatorFrequency P.^ 2)) :+ 0) .* posSquaredOp ) +\n ( ((1 P./ (2 P.* particleMass)) :+ 0) .* momSquaredOp )\n )\n )\n\n -- initial ket\n initialModel :: LatticeKet (Complex Double) Position\n initialModel = LatticeKet $! R.fromFunction (Z :. indexRange) $! \\(Z:.i) -> initialAmplitude $! indexToPosition i\n\n -- bitmap drawing\n drawing :: LatticeKet (Complex Double) Position -> Picture\n drawing (LatticeKet vector) =\n makePicture (2*halfWidth) (2*halfHeight)\n 1 1\n ( \\(x,y) -> let pos = Position (round $! x P.* (P.fromIntegral halfWidth))\n (round $! y P.* (P.fromIntegral halfHeight))\n amp = vector R.! ( Z:.(positionToIndex pos) )\n den = double2Float $! normSquared amp\n in {-trace (show $ (pos, amp, den)) $ -} rgb' den 0 0\n )\n where\n normSquared cn = (magnitude cn) P.^ 2\n\n\n \n {-\n -- drawing with objects\n drawing :: LatticeKet (Complex Double) Position -> Picture\n drawing (LatticeKet vector) = {- trace \"Drawing\" $ -}\n pictures $ map (\\(Position x y) -> translate (fromIntegral x) (fromIntegral y) $!\n color (withAlpha (double2Float $ normSquared $! (vector R.! ( Z:.(positionToIndex (Position x y))))) red) $!\n circleSolid 1\n ) $ positionRange\n where normSquared cn = (magnitude cn) P.^ 2\n -}\n \n\n\n\n------------------------------------\n-- simulate oscillation using index functions\n-- doesn't work at the moment\n-- no NormalizeVector instance for InfKet\n------------------------------------\n\nindexFunctionsSimulator :: OscillatorInABoxConfig\n -> ( TimeStep -> InfOperator (Complex Double) Position\n , InfKet (Complex Double) Position\n , InfKet (Complex Double) Position -> Picture\n , OscillatorInABoxConfig\n )\nindexFunctionsSimulator config = (oscillationOperator, initialModel, drawing, config)\n where\n -- shorthands for config params\n positionRange = positionRangeConfig config\n halfWidth = halfWidthConfig config\n halfHeight = halfHeightConfig config\n\n plankConstant = plankConstantConfig config\n particleMass = particleMassConfig config\n oscillatorFrequency = oscillatorFrequencyConfig config\n \n initialAmplitude = initialAmplitudeConfig config\n\n \n -- position and momentum operators\n posXOp :: InfOperator (Complex Double) Position\n posXOp = InfOperator $ \\pos@(Position x _) -> M.fromList [(pos, (fromIntegral x) :+ 0) ]\n\n posYOp :: InfOperator (Complex Double) Position\n posYOp = InfOperator $ \\pos@(Position _ y) -> M.fromList [(pos, (fromIntegral y) :+ 0)]\n\n momXOp :: InfOperator (Complex Double) Position\n -- taking dx as 2\n -- = -ih ( d/dx(a)|_x' ) = - ( a(x'+1) - a(x'-1) ) * ih/2 = - ( - ) * ih / 2 \n momXOp = InfOperator $ \\(Position x y) -> M.fromList [ ( Position (x P.- 1) y, (0 :+ ( plankConstant/2)) ),\n ( Position (x P.+ 1) y, (0 :+ (- plankConstant/2)) )\n ]\n\n momYOp :: InfOperator (Complex Double) Position\n -- taking dy as 2\n -- = -ih ( d/dy(a)|_y' ) = - ( a(y'+1) - a(y'-1) ) * ih/2 = - ( - ) * ih / 2 \n momYOp = InfOperator $ \\(Position x y) -> M.fromList [ ( Position x (y P.- 1), 0 :+ ( plankConstant/2) ),\n ( Position x (y P.+ 1), 0 :+ (- plankConstant/2) )\n ]\n\n momSquaredOp = (momXOp `pow1p` 2) + (momYOp `pow1p` 2)\n posSquaredOp = (posXOp `pow1p` 2) + (posYOp `pow1p` 2)\n\n scOp :: (Complex Double) -> InfOperator (Complex Double) Position\n scOp scalar = InfOperator $! \\pos -> M.fromList [ (pos, scalar) ]\n\n\n oscillationOperator :: Double -> InfOperator (Complex Double) Position\n oscillationOperator dt = (scOp $! 1 :+ 0) + ((scOp $! 0 :+ (0 P.- (dt P./ plankConstant))) *\n (\n ( momSquaredOp * (scOp $ (1 P./ (2 P.* particleMass)) :+ 0) ) +\n ( posSquaredOp * (scOp $ ((particleMass P./ 2) P.* oscillatorFrequency P.^ 2) :+ 0) )\n )\n )\n\n initialModel :: InfKet (Complex Double) Position\n initialModel = InfKet $! initialAmplitude\n\n -- bitmap drawing\n drawing :: InfKet (Complex Double) Position -> Picture\n drawing (InfKet coeffMap) = {- trace \"Drawing\" $ -}\n makePicture (2*halfWidth) (2*halfHeight)\n 1 1\n ( \\(x,y) -> let pos = Position (round $! x P.* (P.fromIntegral halfWidth))\n (round $! y P.* (P.fromIntegral halfHeight))\n amp = coeffMap pos\n den = double2Float $! normSquared amp\n in {-trace (show $ (pos, amp, den)) $ -} rgb' den 0 0\n )\n where\n normSquared cn = (magnitude cn) P.^ 2\n\n {-\n -- drawing with objects \n drawing :: InfKet (Complex Double) Position -> Picture\n drawing (InfKet coeffMap) = {- trace \"Drawing\" $ -}\n pictures $ map (\\(Position x y) -> translate (fromIntegral x) (fromIntegral y) $!\n color (withAlpha (double2Float $! normSquared $! coeffMap (Position x y)) red) $!\n circleSolid 1\n ) $ positionRange\n where normSquared cn = (magnitude cn) P.^ 2\n -}\n\n\n\n\n------------------------------------------\n-- Simulate\n------------------------------------------\n\n\nsimulateOscillation :: (VectorSpace k v, SimpleOperator k v o, NormalizeVector v)\n => (TimeStep -> o)\n -> v\n -> (v -> Picture)\n -> OscillatorInABoxConfig\n -> IO ()\nsimulateOscillation oscillationOperator initialModel drawing config = do\n -- return $! trace \"Start Calculating Operator.\" ()\n -- keeping fps constant to avoid recalculation of operator\n operator <- return $! oscillationOperator $! timeFactor P./ (fromIntegral fps)\n -- return $! trace \"Finish Calculating Operator.\" ()\n simulate (InWindow \"Quantum Oscillation Simulator\" (2*halfWidth, 2*halfHeight) (halfWidth, halfHeight))\n black\n fps\n initialModel\n drawing\n (simulation operator)\n\n where\n fps = fpsConfig config\n halfHeight = halfHeightConfig config\n halfWidth = halfWidthConfig config\n timeFactor = timeFactorConfig config\n \n simulation :: (VectorSpace k v, SimpleOperator k v o, NormalizeVector v)\n => o -> ViewPort -> Float\n -> v -> v\n simulation operator _ _ ket = {- trace \"Simulating\" $! -} normalizeVector $! operator `op` ket\n\n\n \ntextSimulateOscillation :: (VectorSpace k v, Show v, SimpleOperator k v o, NormalizeVector v)\n => (TimeStep -> o)\n -> v\n -> OscillatorInABoxConfig\n -> IO ()\ntextSimulateOscillation oscillationOperator initialModel config = do\n -- return $! trace \"Start Calculating Operator.\" ()\n operator <- return $ oscillationOperator $! timeFactor P./ (fromIntegral fps)\n -- return $! trace \"Finish Calculating Operator.\" ()\n go operator initialModel\n\n where\n fps = fpsConfig config\n timeFactor = timeFactorConfig config\n \n go :: ( VectorSpace k v, SimpleOperator k v o\n , Show v, NormalizeVector v\n )\n => o -> v -> IO ()\n go operator ket = do\n print ket\n threadDelay 1000000\n let nextMap = operator `op` ket \n go operator $! normalizeVector nextMap\n\n\n\n\n\n--------------------------------\n--Class Instances\n--------------------------------\n\n\nclass NormalizeVector a where\n normalizeVector :: a -> a\n\n\ninstance NormalizeVector (SparseMatKet (Complex Double) (CComplex CDouble) Position) where\n normalizeVector ket@(SparseMatKet mat) = (1 / (norm :+ 0)) *^ ket\n where\n norm :: Double\n -- norm = realPart $! ES.norm mat\n -- normalizing with max of norms instead of sum of squares of norm to make the states more visible in simulation\n norm = ESD.maxCoeff $ ESD.convert normSquared $ ES.toMatrix mat\n \n normSquared cn = (magnitude cn) P.^ 2\n\n\ninstance NormalizeVector (SparseKet (Complex Double) Position) where\n normalizeVector ket@(SparseKet ketMap) = (1 / (norm :+ 0)) *^ ket\n where\n -- ketNormSquared = M.foldl' (P.+) 0 $! M.map (\\coeff -> normSquared coeff) ketMap\n -- normalizing with max of norms instead of sum of squares of norm to make the states more visible in simulation\n maxNormSquared = M.foldl' (\\a b -> max a b) 0 $! M.map (\\coeff -> normSquared coeff) ketMap\n normSquared cn = (magnitude cn) P.^ 2\n norm :: Double\n norm = sqrt $! maxNormSquared\n\n \ninstance NormalizeVector (LatticeKet (Complex Double) Position) where\n normalizeVector ket@(LatticeKet array) = (1 / (norm :+ 0)) *^ ket\n where\n -- ketNormSquared = R.foldlAllS (P.+) 0 $! R.map (\\coeff -> normSquared coeff) array\n -- normalizing with max of norms instead of sum of squares of norm to make the states more visible in simulation\n maxNormSquared = R.foldAllS (\\a b -> max a b) 0 $! R.map (\\coeff -> normSquared coeff) array\n normSquared cn = (magnitude cn) P.^ 2\n norm :: Double\n norm = sqrt $! maxNormSquared\n\n{-\n-- Will have to encode positionRange in Position to be able to traverse index map\ninstance NormalizeVector (InfKet (Complex Double) Position) where\n normalizeVector ket@(InfKet coeffMap) = (1 / (norm :+ 0)) *^ ket\n where\n -- ketNormSquared = foldl' (P.+) 0 $! map (normSquared .coeffMap) positionRange\n -- normalizing with max of norms instead of sum of squares of norm to make the states more visible in simulation\n maxNormSquared = foldl' (\\a b -> max a b) 0 $! map (normSquared .coeffMap) positionRange\n normSquared cn = (magnitude cn) P.^ 2\n norm :: Double\n norm = sqrt $! maxNormSquared\n-}\n\n\n \n-- Hermitian Inner Product\ninstance (InnerProductSpace (Complex Double) (SparseKet (Complex Double) Position)) where\n (<.>) (SparseKet coeffA) (SparseKet coeffB) = M.foldl' (+) 0 $! M.intersectionWith (\\ampA ampB -> ampA * (complexConjugate ampB)) coeffA coeffB\n\n\n\n-------------------\n-- For field instance of Complex Double\n\ninstance Euclidean (Complex Double) where degree _ = Just 1\ninstance Division (Complex Double) where (/) = (P./)\ninstance PID (Complex Double)\ninstance UFD (Complex Double)\ninstance GCDDomain (Complex Double)\ninstance IntegralDomain (Complex Double)\ninstance Unital (Complex Double) where one = 1 :+ 0\ninstance DecidableZero (Complex Double) where isZero = ((0 :+ 0) ==)\ninstance ZeroProductSemiring (Complex Double)\ninstance Commutative (Complex Double)\ninstance Multiplicative (Complex Double) where (*) = (P.*)\ninstance DecidableUnits (Complex Double) where recipUnit a = case a of\n (1 :+ 0) -> Just a\n (-1 :+ 0) -> Just a\n _ -> Nothing\ninstance UnitNormalForm (Complex Double)\ninstance Ring (Complex Double)\ninstance Monoidal (Complex Double) where zero = 0 :+ 0\ninstance Semiring (Complex Double)\ninstance Additive (Complex Double) where (+) = (P.+)\ninstance DecidableAssociates (Complex Double) where isAssociate = (==)\ninstance Rig (Complex Double)\ninstance Group (Complex Double) where (-) = (P.-)\ninstance LeftModule Natural (Complex Double) where\n n .* m = (fromIntegral $ toInteger n) P.* m\ninstance RightModule Natural (Complex Double) where\n m *. n = m P.* (fromIntegral n)\ninstance LeftModule Integer (Complex Double) where\n n .* m = (fromIntegral $ toInteger n) P.* m\ninstance RightModule Integer (Complex Double) where\n m *. n = m P.* (fromIntegral n)\ninstance Abelian (Complex Double)\n\n\n\n\n--------------\n-- For field instance of Double\n\ninstance Euclidean Double where degree _ = Just 1\ninstance Division Double where (/) = (P./)\ninstance PID Double\ninstance UFD Double\ninstance GCDDomain Double\ninstance IntegralDomain Double\ninstance Unital Double where one = 1\ninstance DecidableZero Double where isZero = (0 ==)\ninstance ZeroProductSemiring Double\ninstance Commutative Double\ninstance Multiplicative Double where (*) = (P.*)\ninstance DecidableUnits Double where recipUnit a = case a of\n 1 -> Just a\n -1 -> Just a\n _ -> Nothing\ninstance UnitNormalForm Double\ninstance Ring Double\ninstance Monoidal Double where zero = 0\ninstance Semiring Double\ninstance Additive Double where (+) = (P.+)\ninstance DecidableAssociates Double where isAssociate = (==)\ninstance Rig Double\ninstance Group Double where (-) = (P.-)\ninstance LeftModule Natural Double where\n n .* m = (fromIntegral $ toInteger n) P.* m\ninstance RightModule Natural Double where\n m *. n = m P.* (fromIntegral n)\ninstance LeftModule Integer Double where\n n .* m = (fromIntegral $ toInteger n) P.* m\ninstance RightModule Integer Double where\n m *. n = m P.* (fromIntegral n)\ninstance Abelian Double\n\n\n\n---------------\n-- For use by repa\ninstance Elt (Complex Double) where\n touch (a :+ b) = touch a >> touch b \n", "meta": {"hexsha": "65bfea01bea5571b1f570540af32c6c6bd48644f", "size": 46145, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "has-sci-physics-examples/src/Physics/Quantum/Examples/HarmonicOscillator.hs", "max_stars_repo_name": "sarthakbagaria/has-sci", "max_stars_repo_head_hexsha": "f124b0ca7ee5a1337a6c9bafea46b3fb6db96575", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-09-10T00:50:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-15T13:58:57.000Z", "max_issues_repo_path": "has-sci-physics-examples/src/Physics/Quantum/Examples/HarmonicOscillator.hs", "max_issues_repo_name": "sarthakbagaria/has-sci", "max_issues_repo_head_hexsha": "f124b0ca7ee5a1337a6c9bafea46b3fb6db96575", "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": "has-sci-physics-examples/src/Physics/Quantum/Examples/HarmonicOscillator.hs", "max_forks_repo_name": "sarthakbagaria/has-sci", "max_forks_repo_head_hexsha": "f124b0ca7ee5a1337a6c9bafea46b3fb6db96575", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-01-11T09:56:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:30:35.000Z", "avg_line_length": 53.3468208092, "max_line_length": 176, "alphanum_fraction": 0.4495394951, "num_tokens": 9141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5566416527313266}} {"text": "{-# LANGUAGE ScopedTypeVariables #-}\n\n\nmodule Math.Probably.IterLap where\n\nimport Math.Probably.Sampler\nimport Math.Probably.FoldingStats\nimport Math.Probably.MCMC (empiricalMean, empiricalCovariance)\nimport Math.Probably.PDF (posdefify)\nimport Debug.Trace\n\nimport Data.Maybe\n\nimport Numeric.LinearAlgebra hiding (find)\n\nweightedMeanCov :: [(Vector Double, Double)] -> (Vector Double, Matrix Double)\nweightedMeanCov pts = (mu, cov) where\n mu = sum $ flip map pts $ \\(x,w) -> scale w x\n npts = dim $ fst $ head pts\n sumSqrWs = sum $ flip map pts $ \\(x,w) -> w*w\n factor = 1/(1-sumSqrWs) \n xmeans :: [Double]\n xmeans = flip map [0..npts-1] $ \\i -> mean $ flip map pts $ \\(x,w) -> x@>i\n cov = scale factor $ buildMatrix npts npts $ \\(j,k) -> \n sum $ flip map pts $ \\(xi,wi) -> wi*(xi@>j - xmeans!!j)*\n (xi@>k - xmeans!!k)\n\nmean :: [Double] -> Double\nmean xs = sum xs / realToFrac (length xs) \n\nimprove :: Int -> (Vector Double -> Double) \n -> (Vector Double, Matrix Double)\n -> Sampler (Vector Double, Matrix Double)\nimprove n f (mu, cov) = do\n xs <- sequence $ replicate n $ multiNormal mu cov\n let xps = catMaybes $ map (\\x-> let fx = f x in if isNaN fx || isInfinite fx then Nothing else Just (x,fx)) xs\n pmin = runStat (before (minFrom 1e80) snd) xps\n psubmin = map (\\(x,p)-> (x, exp $ p - pmin)) xps\n psum = sum $ map snd psubmin\n ws = map (\\(x,p)-> (x,p/psum)) psubmin\n (mu', cov') = weightedMeanCov $ ws\n return $ (mu', posdefify $ scale 2 cov')\n\niterateM :: Int -> (a -> Sampler a) -> a-> Sampler a\niterateM 0 _ x = return x\niterateM n f x = do\n newx <- f x\n iterateM (n-1) f newx\n\niterLap :: [Int] \n -> (Vector Double -> Double) \n -> (Vector Double, Matrix Double)\n -> Sampler (Vector Double, Matrix Double)\niterLap [] _ x = return x\niterLap (n:ns) f x = do\n newx <- improve n f x\n iterLap (ns) f newx\n", "meta": {"hexsha": "80a1c1597997a66ed6bef5ac11012b2826317fc3", "size": 1940, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/Probably/IterLap.hs", "max_stars_repo_name": "glutamate/probably", "max_stars_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-28T03:19:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:44.000Z", "max_issues_repo_path": "Math/Probably/IterLap.hs", "max_issues_repo_name": "glutamate/probably", "max_issues_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/Probably/IterLap.hs", "max_forks_repo_name": "glutamate/probably", "max_forks_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4482758621, "max_line_length": 112, "alphanum_fraction": 0.6056701031, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5566416213703949}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Geometry where\n\nimport Graphics.Gloss as G\nimport Graphics.Gloss.Data.ViewPort as G\nimport Graphics.Gloss.Data.ViewState as G\nimport Data.Array.Accelerate as A\nimport Data.Array.Accelerate.Data.Complex as A\nimport qualified Prelude as P\nimport qualified GHC.Float as P\nimport qualified Data.Complex as C\n\ntype FractalPoint = Complex Double\n\n-- TODO: phantom types\n\n\nwidth :: Int\nwidth = 400\n\nheight :: Int\nheight = 400\n\n\nblWorldByWidthHeight :: (Int, Int) -> Point\nblWorldByWidthHeight (w, h) = (-P.fromIntegral w P./ 2.0, -P.fromIntegral h P./ 2.0)\n\nurWorldByWidthHeight :: (Int, Int) -> Point\nurWorldByWidthHeight (w, h) = (P.fromIntegral w P./ 2.0, P.fromIntegral h P./ 2.0)\n\nblWorldInit :: Point\nblWorldInit = blWorldByWidthHeight (width, height)\n\nurWorldInit :: Point\nurWorldInit = urWorldByWidthHeight (width, height)\n\nblComplexInit :: FractalPoint\nblComplexInit = (-1) :+ (-1)\n\nurComplexInit :: FractalPoint\nurComplexInit = (1) :+ (1)\n\nconvertWorldToComplex :: Point -> FractalPoint -> Point -> FractalPoint\nconvertWorldToComplex w_ur c_ur (x, y) = xComplex C.:+ yComplex\n where xRel = x P./ P.fst w_ur\n yRel = y P./ P.snd w_ur\n xComplex = P.float2Double xRel P.* C.realPart c_ur\n yComplex = P.float2Double yRel P.* C.imagPart c_ur\n\nmakeComplexGrid :: Int -> Int -> FractalPoint -> FractalPoint -> Acc (A.Matrix FractalPoint)\nmakeComplexGrid w h bl ur = use $ A.fromList (Z:.h :. w) $ do\n imag <- P.reverse $ make1DComplexGrid h (C.imagPart bl) (C.imagPart ur)\n real <- make1DComplexGrid w (C.realPart bl) (C.realPart ur)\n P.return (real :+ imag)\n where \n make1DComplexGrid n l r = (P.+l) . (P./ P.fromIntegral n) . (P.*(r P.- l)) . P.fromIntegral P.<$> [0..n - 1]", "meta": {"hexsha": "8940df6b69db9c05756f5e353f1ee2616ed608ad", "size": 1882, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Geometry.hs", "max_stars_repo_name": "psurkov/Fractal-generator", "max_stars_repo_head_hexsha": "4904154e033821246ed2a6e455400f7162d28a4f", "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/Geometry.hs", "max_issues_repo_name": "psurkov/Fractal-generator", "max_issues_repo_head_hexsha": "4904154e033821246ed2a6e455400f7162d28a4f", "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/Geometry.hs", "max_forks_repo_name": "psurkov/Fractal-generator", "max_forks_repo_head_hexsha": "4904154e033821246ed2a6e455400f7162d28a4f", "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.0175438596, "max_line_length": 120, "alphanum_fraction": 0.6498405951, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5566015969919936}} {"text": "{-# LANGUAGE TypeSynonymInstances, FlexibleInstances#-}\n\nmodule Geometry.Matrix \n(\n -- * Functions\n getIndependent\n)\n\nwhere\n \nimport Numeric.LinearAlgebra.HMatrix\nimport qualified Data.Matrix as M\nimport Data.Function\n-- instance Element Rational\n\n\n-- getIndependent :: [[Rational]] -> [[Rational]] -> Int -> Int -> M.Matrix Rational-> [[Rational]]\n-- getIndependent initial accum currRank maxRank slackMat\n-- | currRank == maxRank = accum\n-- | accum == [] = getIndependent (tail initial) (return $ head initial) 1 maxRank slackMat\n-- | otherwise = if newRank > currRank \n-- then getIndependent (tail initial) (candidate:accum) (currRank+1) maxRank slackMat\n-- else getIndependent (tail initial) accum currRank maxRank slackMat\n-- where\n-- slack = map (map fromRational) $ M.toLists slackMat\n-- candidate = head initial\n-- setVectors = map (1:) $ candidate:accum\n-- matrix = fromLists $ zipRev ((map (map fromRational)) setVectors :: [[Double]]) (slack)\n-- newRank = rank matrix\n\n-- | Get independet rows/columns of a non square matrix\ngetIndependent :: [[Rational]] -> [[Rational]] -> Int -> Int -> M.Matrix Rational-> [[Rational]]\ngetIndependent initial accum currRank maxRank slackMat\n | currRank == maxRank = accum\n | accum == [] = getIndependent (tail initial) (return $ head initial) 1 maxRank slackMat\n | otherwise = if newRank > currRank \n then getIndependent (tail initial) (candidate:accum) (currRank+1) maxRank slackMat\n else getIndependent (tail initial ++ [candidate]) accum currRank maxRank slackMat\n where\n slack = map (map fromRational) $ M.toLists slackMat\n candidate = head initial\n setVectors = map (1:) $ candidate:accum\n matrix = fromLists $ zipRev ((map (map fromRational)) setVectors :: [[Double]]) (slack)\n newRank = rank matrix\n\nzipRev :: [[Double]] -> [[Double]] -> [[Double]]\nzipRev a = (reverse . ((zipWith (++)) `on` reverse) a) ", "meta": {"hexsha": "d39038736d304d28092e1cf0ff43a7a4ea3658cd", "size": 2102, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Geometry/Matrix.hs", "max_stars_repo_name": "matheusvms/facet-enumeration", "max_stars_repo_head_hexsha": "faebf5dc724b5f28fe18f2c0f28c618c76c04c24", "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/Geometry/Matrix.hs", "max_issues_repo_name": "matheusvms/facet-enumeration", "max_issues_repo_head_hexsha": "faebf5dc724b5f28fe18f2c0f28c618c76c04c24", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-04T23:59:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T23:59:44.000Z", "max_forks_repo_path": "src/Geometry/Matrix.hs", "max_forks_repo_name": "matheusvms/facet-enumeration", "max_forks_repo_head_hexsha": "faebf5dc724b5f28fe18f2c0f28c618c76c04c24", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-04T23:38:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T23:38:53.000Z", "avg_line_length": 44.7234042553, "max_line_length": 105, "alphanum_fraction": 0.6284490961, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5564562890711928}} {"text": "{-|\nModule: Numeric.Morpheus.Statistics\nDescription: Statistics Functions\nCopyright: (c) Alexander Ignatyev, 2017\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n-}\n\nmodule Numeric.Morpheus.Statistics\n(\n mean\n , stddev_m\n , stddev\n , columnMean\n , rowMean\n , columnStddev_m\n , rowStddev_m\n)\n\nwhere\n\nimport Numeric.Morpheus.Utils(morpheusLayout)\n\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Devel\nimport System.IO.Unsafe(unsafePerformIO)\nimport Foreign.C.Types\nimport Foreign.Ptr(Ptr)\nimport Foreign.Storable\n\n{- morpheus_mean -}\nforeign import ccall unsafe \"morpheus_mean\"\n c_morpheus_mean :: CInt -> Ptr R -> IO R\n\n-- | Calculates mean (average).\nmean :: Vector R -> R\nmean x = unsafePerformIO $ do\n apply x id c_morpheus_mean\n\n\n{- morpheus_stddev_m -}\nforeign import ccall unsafe \"morpheus_stddev\"\n c_morpheus_stddev_m :: R -> CInt -> Ptr R -> IO R\n\n-- | Calculates sample standard deviation using given mean value.\nstddev_m :: R -> Vector R -> R\nstddev_m m x = unsafePerformIO $ do\n apply x id (c_morpheus_stddev_m m)\n\n\n{- morpheus_stddev -}\nforeign import ccall unsafe \"morpheus_stddev\"\n c_morpheus_stddev :: CInt -> Ptr R -> IO R\n\n-- | Calculates sample standard deviation.\nstddev :: Vector R -> R\nstddev x = unsafePerformIO $ do\n apply x id c_morpheus_stddev\n\n\n{- morpheus_column_mean -}\nforeign import ccall unsafe \"morpheus_column_mean\"\n c_morpheus_column_mean :: CInt -> CInt -> CInt -> Ptr R -> Ptr R -> IO ()\n\n\ncall_morpheus_column_mean :: CInt -> CInt -> CInt -> CInt -> Ptr R\n -> CInt -> Ptr R\n -> IO ()\ncall_morpheus_column_mean rows cols xRow xCol mat _ means = do\n let layout = morpheusLayout xCol cols\n c_morpheus_column_mean layout rows cols mat means\n\n\n-- | Calculates mean (average) for every column.\ncolumnMean :: Matrix R -> Vector R\ncolumnMean m = unsafePerformIO $ do\n v <- createVector (cols m)\n apply m (apply v id) call_morpheus_column_mean\n return v\n\n\n{- morpheus_row_mean -}\nforeign import ccall unsafe \"morpheus_row_mean\"\n c_morpheus_row_mean :: CInt -> CInt -> CInt -> Ptr R -> Ptr R -> IO ()\n\n\ncall_morpheus_row_mean :: CInt -> CInt -> CInt -> CInt -> Ptr R\n -> CInt -> Ptr R\n -> IO ()\ncall_morpheus_row_mean rows cols xRow xCol mat _ means = do\n let layout = morpheusLayout xCol cols\n c_morpheus_row_mean layout rows cols mat means\n\n\n-- | Calculates mean (average) for every row.\nrowMean :: Matrix R -> Vector R\nrowMean m = unsafePerformIO $ do\n v <- createVector (rows m)\n apply m (apply v id) call_morpheus_row_mean\n return v\n\n\n{- morpheus_column_stddev_m -}\nforeign import ccall unsafe \"morpheus_column_stddev_m\"\n c_morpheus_column_stddev_m :: CInt -> CInt -> CInt -> Ptr R -> Ptr R -> Ptr R -> IO ()\n\n\ncall_morpheus_column_stddev_m :: CInt -> Ptr R\n -> CInt -> CInt -> CInt -> CInt -> Ptr R\n -> CInt -> Ptr R\n -> IO ()\ncall_morpheus_column_stddev_m _ means rows cols xRow xCol mat _ stddevs = do\n let layout = morpheusLayout xCol cols\n c_morpheus_column_stddev_m layout rows cols means mat stddevs\n\n\n-- | Calculates sample standard deviation using given mean value for every column.\ncolumnStddev_m :: Vector R -> Matrix R -> Vector R\ncolumnStddev_m means m = unsafePerformIO $ do\n v <- createVector (cols m)\n apply means (apply m (apply v id)) call_morpheus_column_stddev_m\n return v\n\n\n{- morpheus_row_stddev_m -}\nforeign import ccall unsafe \"morpheus_row_stddev_m\"\n c_morpheus_row_stddev_m :: CInt -> CInt -> CInt -> Ptr R -> Ptr R -> Ptr R -> IO ()\n\n\ncall_morpheus_row_stddev_m :: CInt -> Ptr R\n -> CInt -> CInt -> CInt -> CInt -> Ptr R\n -> CInt -> Ptr R\n -> IO ()\ncall_morpheus_row_stddev_m _ means rows cols xRow xCol mat _ stddevs = do\n let layout = morpheusLayout xCol cols\n c_morpheus_row_stddev_m layout rows cols means mat stddevs\n\n\n-- | Calculates sample standard deviation using given mean value for every row.\nrowStddev_m :: Vector R -> Matrix R -> Vector R\nrowStddev_m means m = unsafePerformIO $ do\n v <- createVector (rows m)\n apply means (apply m (apply v id)) call_morpheus_row_stddev_m\n return v\n", "meta": {"hexsha": "ef22de0243f45a3f936ce07cea4432e83ade57e2", "size": 4310, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "hmatrix-morpheus/src/Numeric/Morpheus/Statistics.hs", "max_stars_repo_name": "Alexander-Ignatyev/morpheus", "max_stars_repo_head_hexsha": "ee01b67441cb2e27abff4a025bd0be4a44762108", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-08-04T19:44:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T11:30:47.000Z", "max_issues_repo_path": "hmatrix-morpheus/src/Numeric/Morpheus/Statistics.hs", "max_issues_repo_name": "aligusnet/morpheus", "max_issues_repo_head_hexsha": "ee01b67441cb2e27abff4a025bd0be4a44762108", "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": "hmatrix-morpheus/src/Numeric/Morpheus/Statistics.hs", "max_forks_repo_name": "aligusnet/morpheus", "max_forks_repo_head_hexsha": "ee01b67441cb2e27abff4a025bd0be4a44762108", "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.5205479452, "max_line_length": 88, "alphanum_fraction": 0.6742459397, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5564562863995599}} {"text": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main where\n\nimport Data.Complex\n\nimport Debug.Trace\n\ndata Nav = N Float\n | S Float\n | E Float\n | W Float\n | L Int\n | R Int\n | F Float\n deriving (Show)\n\n\n\ndata Change = Dir (Complex Float)\n | Rot (Complex Float)\n | Move (Complex Float)\n\n deriving (Show)\n\ndegToRot :: Int -> Float\ndegToRot d = fromIntegral (d `div` 90)*pi/2\n\nnavToChange :: Nav -> Change\nnavToChange (N m) = Dir $ 0 :+ m\nnavToChange (S m) = Dir $ 0 :+ (-m)\nnavToChange (E m) = Dir $ m :+ 0\nnavToChange (W m) = Dir $ (-m) :+ 0\nnavToChange (L d) = Rot $ mkPolar 1.0 (degToRot d)\nnavToChange (R d) = Rot $ mkPolar 1.0 (-(degToRot d))\nnavToChange (F m) = Move $ mkPolar m 0\n\n\n\ninstance Read Nav where\n readsPrec _ ('N':r) = [( N $ read r, \"\")]\n readsPrec _ ('S':r) = [( S $ read r, \"\")]\n readsPrec _ ('E':r) = [( E $ read r, \"\")]\n readsPrec _ ('W':r) = [( W $ read r, \"\")]\n readsPrec _ ('L':r) = [( L $ read r, \"\")]\n readsPrec _ ('R':r) = [( R $ read r, \"\")]\n readsPrec _ ('F':r) = [( F $ read r, \"\")]\n\n\ngetInput :: FilePath -> IO [Nav]\ngetInput = fmap (map read . lines) . readFile\n\ndirToComplex :: Nav -> Complex Float\ndirToComplex (N n) = 0 :+ n\ndirToComplex (S s) = 0 :+ (-s)\ndirToComplex (E e) = e :+ 0\ndirToComplex (W w) = (-w) :+ 0\ndirToComplex _ = undefined\n\nsolution :: [Nav] -> Int\nsolution navs = round $ abs (dx + ix) + abs (dy + iy)\n where (dirs, instr) = (filter isDir navs, filter (not . isDir) navs)\n (dx :+ dy) = sum $ map dirToComplex dirs\n (ix :+ iy) = instrsToComplex 0 (0 :+ 0) instr\n\n isDir :: Nav -> Bool\n isDir (N _) = True\n isDir (S _) = True\n isDir (E _) = True\n isDir (W _) = True\n isDir _ = False\n\n instrsToComplex :: Float -> Complex Float -> [Nav] -> Complex Float\n instrsToComplex _ curLoc [] = curLoc\n instrsToComplex curPhase curLoc ((L d):rest)\n = instrsToComplex (curPhase + degToRot d) curLoc rest\n instrsToComplex curPhase curLoc ((R d):rest)\n = instrsToComplex (curPhase - degToRot d) curLoc rest\n instrsToComplex curPhase ship ((F m):rest)\n = instrsToComplex curPhase (ship+rot) rest\n where rot = mkPolar m curPhase\n\n\nsolution2 :: [Nav] -> Int\nsolution2 navs = round $ abs ix + abs iy\n where (ix :+ iy) = run 0 (10 :+ 1) $ map navToChange navs\n run :: Complex Float -> Complex Float -> [Change] -> Complex Float\n run ship _ [] = ship\n run ship wp (Dir d:rest) = run ship (wp + d) rest\n run ship wp (Rot r:rest) = run ship (wp*r) rest\n run ship wp (Move m:rest)= run (ship + m*wp) wp rest\n\n\nmain :: IO ()\nmain = do getInput \"test-input\" >>= print . solution\n getInput \"test-input\" >>= print . solution2\n getInput \"input\" >>= print . solution\n getInput \"input\" >>= print . solution2", "meta": {"hexsha": "6de5d937841b27061e64bc922d81f7c4ff0dddbc", "size": 2904, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Day12/Day12.hs", "max_stars_repo_name": "Tritlo/AdventOfCode2020", "max_stars_repo_head_hexsha": "48d6df6fcbdda8cc4198ea54297475feaf4ab9b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-01T17:24:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T22:00:47.000Z", "max_issues_repo_path": "Day12/Day12.hs", "max_issues_repo_name": "Tritlo/AdventOfCode2020", "max_issues_repo_head_hexsha": "48d6df6fcbdda8cc4198ea54297475feaf4ab9b3", "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": "Day12/Day12.hs", "max_forks_repo_name": "Tritlo/AdventOfCode2020", "max_forks_repo_head_hexsha": "48d6df6fcbdda8cc4198ea54297475feaf4ab9b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9381443299, "max_line_length": 75, "alphanum_fraction": 0.5612947658, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5563007378784017}} {"text": "module STCR2S1PointSet where\n\nimport Control.Monad as M\nimport Control.Monad.Parallel as MP\nimport Data.Array.Repa as R\nimport Data.Binary (decodeFile)\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Unboxed as VU\nimport DFT.Plan\nimport Filter.Utils\nimport FokkerPlanck.MonteCarlo\nimport Image.IO\nimport STC.CompletionFieldR2S1\nimport STC.Shape\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Text.Printf\nimport Types\nimport Utils.Array\nimport FokkerPlanck.Histogram\nimport FokkerPlanck.GreensFunction\n\nmain = do\n args@(numPointStr:numOrientationStr:sigmaStr:taoStr:numTrailStr:maxTrailStr:initOriStr:initSpeedStr:writeFlagStr:numIterationStr:thresholdStr:histFilePath:rStr:deltaStr:stdStr:numThreadStr:_) <-\n getArgs\n print args\n let numPoint = read numPointStr :: Int\n numOrientation = read numOrientationStr :: Int\n sigma = read sigmaStr :: Double\n tao = read taoStr :: Double\n numTrail = read numTrailStr :: Int\n maxTrail = read maxTrailStr :: Int\n initOri = read initOriStr :: Double\n initSpeed = read initSpeedStr :: Double\n writeFlag = read writeFlagStr :: Bool\n numIteration = read numIterationStr :: Int\n threshold = read thresholdStr :: Double\n r = read rStr :: Double\n delta = read deltaStr :: Double\n std = read stdStr :: Double\n numThread = read numThreadStr :: Int\n folderPath = \"output/test/STCR2S1PointSet\"\n createDirectoryIfMissing True folderPath\n flag <- doesFileExist histFilePath\n -- arrG' <-\n -- if flag\n -- then getNormalizedHistogramArr <$> decodeFile histFilePath\n -- else do\n -- putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n -- solveMonteCarloR2S1\n -- numThread\n -- numTrail\n -- maxTrail\n -- numPoint\n -- numPoint\n -- numOrientation\n -- sigma\n -- tao\n -- ((sqrt 2) * fromIntegral numPoint)\n -- initSpeed\n -- histFilePath\n -- -- (0, 0, 0, 0, initOri / 180 * pi, initSpeed)\n arrG' <-\n sampleR2S1\n numPoint\n numPoint\n delta\n (2 * pi / fromIntegral numOrientation)\n initSpeed\n sigma\n tao\n [0 .. numOrientation - 1]\n let -- arrG' =\n -- sampleR2S1\n -- numPoint\n -- numPoint\n -- delta\n -- (2 * pi / fromIntegral numOrientation)\n -- initSpeed\n -- sigma\n -- tao\n -- [0 .. numOrientation - 1]\n -- arrG =\n -- computeS . R.traverse arrG' id $ \\f idx@(Z :. k :. i :. j) ->\n -- let r' =\n -- sqrt . fromIntegral $\n -- (i - div numPoint 2) ^ 2 + (j - div numPoint 2) ^ 2\n -- in -- if r' > 49 -- || r' <= 2\n -- -- then 0\n -- -- else\n -- f idx\n arrG = computeS . rotate3DR $ arrG'\n -- r = 16\n let numTheta = 8\n deltaTheta = (2 * pi) / numTheta\n xs -- [R2S1RPPoint (-i, 0, 0, 1) | i <- [-24,-18 .. 24]]\n =\n ((L.map\n (\\(i, j) -> R2S1RPPoint (round i, round j, 0, 1))\n [ (r * cos (k * deltaTheta) + 0, r * sin (k * deltaTheta) + 0)\n | k <- [0 .. numTheta - 1]\n ]) -- L.++\n -- [R2S1RPPoint (-3, -1, 0, 1)]\n )\n bias = computeBias numPoint numPoint numOrientation xs\n -- initialEigenVec =\n -- computeInitialEigenVec numPoint numPoint numOrientation xs\n circle = Points (0, 0) 2 Circle {circleNum = 8, circleRadius = round r}\n circlePoints = makeShape2D $ circle\n ys = getShape2DIndexListGaussian 5 2 $ circlePoints\n initialEigenVec =\n computeInitialEigenVecGaussian numPoint numPoint numOrientation ys\n print xs\n print circlePoints\n -- powerMethod\n -- emptyPlan\n -- folderPath\n -- arrG\n -- numIteration\n -- writeFlag\n -- \"\"\n -- threshold\n -- bias\n -- initialEigenVec\n computeContourR2S1Analytic\n folderPath\n arrG\n numOrientation\n numPoint\n numPoint\n sigma\n tao\n initSpeed\n std\n delta\n bias\n circlePoints\n -- computeContourR2S1Tangent\n -- folderPath\n -- arrG\n -- numOrientation\n -- numPoint\n -- numPoint\n -- delta\n -- circlePoints\n", "meta": {"hexsha": "26295948504b4ad2284d8371ab145df8ab887039", "size": 4500, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2S1PointSet/STCR2S1PointSet.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/STCR2S1PointSet/STCR2S1PointSet.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/STCR2S1PointSet/STCR2S1PointSet.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 30.4054054054, "max_line_length": 196, "alphanum_fraction": 0.5615555556, "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5562185555078334}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Lib.Utility.MBool where\n\nimport Numeric.LinearAlgebra\n\ninfix 4 .==., ./=., .<., .<=., .>=., .>.\ninfixr 3 .&&.\ninfixr 2 .||.\n\n-- specialized for Int result\ncond'\n :: (Element t, Ord t, Container c I, Container c t)\n => c t -> c t -> c I -> c I -> c I -> c I\ncond' = cond\n\na .<. b = cond' a b 1 0 0\na .<=. b = cond' a b 1 1 0\na .==. b = cond' a b 0 1 0\na ./=. b = cond' a b 1 0 1\na .>=. b = cond' a b 0 1 1\na .>. b = cond' a b 0 0 1\n\na .&&. b = step (a*b)\na .||. b = step (a+b)\nno a = 1-a\nxor a b = a ./=. b\nequiv a b = a .==. b\nimp a b = no a .||. b\n\ntaut x = minElement x == 1\n\nminEvery a b = cond a b a a b\nmaxEvery a b = cond a b b b a\n", "meta": {"hexsha": "2c92e7ada15969e019232ab82953e06605fc3de3", "size": 703, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib/Utility/MBool.hs", "max_stars_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_stars_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-01-04T12:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T06:16:37.000Z", "max_issues_repo_path": "src/Lib/Utility/MBool.hs", "max_issues_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_issues_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-01-04T02:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-09T12:39:40.000Z", "max_forks_repo_path": "src/Lib/Utility/MBool.hs", "max_forks_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_forks_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-20T03:39:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T03:39:47.000Z", "avg_line_length": 20.0857142857, "max_line_length": 55, "alphanum_fraction": 0.4893314367, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5562185491377298}} {"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\nmodule AI.Singularity.Data.Vector where\nimport GHC.TypeLits\nimport qualified Numeric.LinearAlgebra.Data as LD\nimport qualified Numeric.LinearAlgebra.Devel as LDev\nimport qualified Numeric.LinearAlgebra as LA\nimport Control.Lens\nimport Data.Proxy\nimport Control.Monad.ST\nimport System.Random\nimport Control.Monad\nimport Control.Arrow\nimport qualified Data.Vector.Storable as VS\n\nimport AI.Singularity.Utils\nimport AI.Singularity.Data.Matrix\n\ndata GeneralVector :: (* -> *) -> Nat -> * where\n Vec :: vec Float -> GeneralVector vec n\nderiving instance Show (vec Float) => Show (GeneralVector vec n)\n\nvec :: Lens' (GeneralVector vec n) (vec Float)\n{-# INLINE vec #-}\nvec f (Vec v) = Vec <$> f v\n\ntype Vector = GeneralVector LD.Vector\n\ntype MutVector s = GeneralVector (LDev.STVector s)\n\n\nthawV :: Vector n -> ST s (MutVector s n)\nthawV = Vec <$< LDev.thawVector . view vec\n\n\ncmap :: (Float -> Float) -> Vector n -> Vector n\ncmap = over vec . LD.cmap\n\nfoldV :: KnownNat n => (Float -> Float -> Float) -> Float -> Vector n -> Float\nfoldV f z = VS.foldr f z . view vec\n\nlenV :: forall n. KnownNat n => Vector n -> Int\nlenV _ = natToInt @ n\n\nfromListV :: forall n. KnownNat n => [Float] -> Vector n\nfromListV = Vec . LD.fromList . take l . cycle\n where l = natToInt @ n\n\nfromValV :: forall n. KnownNat n => Float -> Vector n\nfromValV = fromListV . repeat\n\ntoListV :: forall n. KnownNat n => Vector n -> [Float]\ntoListV (Vec v) = VS.toList v\n\nconsV :: forall n. (KnownNat n) => Float -> Vector n -> Vector (n+1)\nconsV d = Vec . VS.cons d . view vec\n\ntailV :: forall n. (KnownNat n) => Vector (n+1) -> Vector n\ntailV = Vec . VS.tail . view vec\n\ntakeV :: forall n m. (KnownNat n, KnownNat m, m <= n) => Vector n -> Vector m\ntakeV = Vec . VS.take m . view vec\n where m = natToInt @ n\n\ndropV :: forall n m. (KnownNat n, KnownNat m, m <= n) => Vector n -> Vector (n - m)\ndropV = Vec . VS.drop m . view vec\n where m = natToInt @ m\n\nsplitV :: forall k l n. (KnownNat k, KnownNat l, KnownNat n, (k+l) ~ n) => Vector n -> (Vector k, Vector l)\nsplitV = view vec >>> VS.take k &&& VS.drop k >>> Vec *** Vec\n where k = natToInt @ k\n\nconcatVec :: forall n m. (KnownNat n, KnownNat m) => Vector n -> Vector m -> Vector (n + m)\nconcatVec (Vec v1) (Vec v2) = Vec (v1 VS.++ v2)\n\n(<.>) :: Vector n -> Vector n -> Float\n(<.>) (Vec a) (Vec b) = (LA.<.>) a b\n\n(#>) :: Matrix m n -> Vector m -> Vector n\n(#>) (Mat m) (Vec v) = Vec (m LA.#> v)\n\nouter :: Vector m -> Vector n -> Matrix n m\nouter (Vec a) (Vec b) = Mat (a `LA.outer` b)\n\nappendV :: (KnownNat n, KnownNat m) => Vector n -> Vector m -> Vector (n+m)\nappendV (Vec v1) (Vec v2) = Vec $ v1 VS.++ v2\n\n\ninstance forall n. KnownNat n => Num (Vector n) where\n (+) (Vec v1) (Vec v2) = Vec (v1 + v2)\n (*) (Vec v1) (Vec v2) = Vec (v1 * v2)\n negate (Vec v1) = Vec (LD.cmap negate v1)\n fromInteger i = fromListV [fromIntegral i]\n abs (Vec v1) = Vec (LD.cmap abs v1)\n signum (Vec v1) = Vec (LD.cmap signum v1)\n\ninstance forall n. KnownNat n => Fractional (Vector n) where\n (/) (Vec v1) (Vec v2) = Vec (v1 / v2)\n fromRational = fromValV . fromRational\n\ninstance forall n. KnownNat n => Floating (Vector n) where\n pi = fromValV pi\n exp = cmap exp\n log = cmap log\n sin = cmap sin\n cos = cmap cos\n sinh = cmap sinh\n cosh = cmap cosh\n tanh = cmap tanh\n asinh = cmap asinh\n acosh = cmap acosh\n atanh = cmap atanh\n\nanswer :: Vector n -> Int\nanswer (Vec v) = fst . VS.ifoldr (\\i x b -> if x > snd b then (i,x) else b) (0,0) $ v\n", "meta": {"hexsha": "546bafd536f73cba277774e66236d2bfe35c7e1d", "size": 3863, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Singularity/Data/Vector.hs", "max_stars_repo_name": "Antystenes/Memetic-Predictor", "max_stars_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AI/Singularity/Data/Vector.hs", "max_issues_repo_name": "Antystenes/Memetic-Predictor", "max_issues_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AI/Singularity/Data/Vector.hs", "max_forks_repo_name": "Antystenes/Memetic-Predictor", "max_forks_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1532258065, "max_line_length": 107, "alphanum_fraction": 0.6357753042, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5562002198563131}} {"text": "--stolen from kmeans!\n\nmodule Math.Probably.KMedoids\n where\nimport Data.List (transpose, sort, groupBy, minimumBy, nub)\nimport Data.Ord (comparing)\n--import Numeric.LinearAlgebra\nimport qualified Data.Map.Strict as Map\n\nimport Numeric.LinearAlgebra\nimport Control.Monad\nimport Debug.Trace\nimport Data.Random\n\ntype DistMap = ([Int] , (Int -> Int -> Double))\n\n\nkmedoids :: Int -> Int -> DistMap -> RVar (Map.Map Int [Int])\nkmedoids nclust iters dist = do\n inits <- kmedoidInit nclust dist\n return $ kmedoidIter dist inits iters\n\nkmedoidsMany :: Int -> Int -> Int -> DistMap -> RVar [Int]\nkmedoidsMany nclust iters tries dist = do\n ress <- forM [1..tries] $ \\i -> do\n clusters <- kmedoids nclust iters dist\n let cost = totalCost dist clusters\n return $ trace (\"KMed try = \"++show i++ \" nclus=\"++show nclust++\" cost= \"++show cost) (clusters, cost)\n return $ Map.keys $ fst $ minimumBy (comparing snd) ress\n\n\nkmedoidInit :: Int -> DistMap -> RVar [Int]\nkmedoidInit nclust dist = fmap (sort . take nclust) $ shuffle $ fst dist\n\n\nkmedoidIter :: DistMap -> [Int] -> Int -> Map.Map Int [Int]\nkmedoidIter dists meds 0 = assignToClosestMedoid dists meds\nkmedoidIter dists meds0 iter = next where\n clusters = assignToClosestMedoid dists meds0\n meds1 = sort $ nub $ map (\\(_, pts)-> reassignMedoid dists pts) $ Map.toList clusters\n next = {-trace (show (meds0, totalCost dists clusters))\n $ -} if meds1 == meds0\n then assignToClosestMedoid dists meds1\n else kmedoidIter dists meds1 (iter-1)\n\ntotalCost :: DistMap -> Map.Map Int [Int] -> Double\ntotalCost dists = sum . map ccost . Map.toList where\n ccost (med, pts) = sum $ map (getDist dists med) pts\n\n\ngetDist :: DistMap -> Int -> Int -> Double\ngetDist (_,f) from to\n | from == to = 0\n | otherwise = f from to\n\nassignToClosestMedoid :: DistMap -> [Int] -> Map.Map Int [Int]\nassignToClosestMedoid dists medoids = clusmap where\n assignmap = Map.fromList $ map (\\k -> (k, findNearestMedoid dists medoids k)) $ fst dists\n clusmap = Map.fromList $ map (\\med -> (med, keysWhereValIs assignmap med)) medoids\n\nkeysWhereValIs :: Eq a => Map.Map k a -> a -> [k]\nkeysWhereValIs mp val = Map.keys $ Map.filter (==val) mp\n\n\nfindNearestMedoid :: DistMap -> [Int] -> Int -> Int\nfindNearestMedoid dists meds k\n = fst $ minimumBy (comparing snd) $ map (\\med-> (med, getDist dists k med)) meds\n\ncalcCost :: DistMap -> Int -> [Int] -> Double\ncalcCost dists med = sum . map (getDist dists med)\n\nreassignMedoid :: DistMap -> [Int] -> Int\nreassignMedoid dists points\n = fst $ minimumBy (comparing snd) $ map (\\pt-> (pt, calcCost dists pt points) ) points\n", "meta": {"hexsha": "474390e90729738b930116c56817c4412a23a77a", "size": 2643, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Probably/KMedoids.hs", "max_stars_repo_name": "glutamate/probably-baysig", "max_stars_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-02-12T05:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:37.000Z", "max_issues_repo_path": "src/Math/Probably/KMedoids.hs", "max_issues_repo_name": "silky/probably-baysig", "max_issues_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/Probably/KMedoids.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 35.24, "max_line_length": 107, "alphanum_fraction": 0.6795308362, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5562002043909475}} {"text": "{- | Test of learning\n\nIn this example, two networks are used : 'simple' which is the reference and 'wrong' which is a wrong start.\nThe goal is to use test patterns to learn the right 'simple' network from 'wrong'. Only the values are learnt.\nThe topology of both networks is the same.\n\n@\nsimple :: (['TDV' Bool],'SBN' 'CPT')\nsimple = 'runBN' $ do \n a <- 'variable' \\\"a\\\" ('t' :: Bool)\n b <- 'variable' \\\"b\\\" ('t' :: Bool) \n-- \n 'proba' a '~~' [0.4,0.6]\n 'cpt' b [a] '~~' [0.8,0.2,0.2,0.8]\n--\n return [a,b]\n@\n\nand 'wrong' where the probability for a is wrong.\n\n@\nwrong :: (['TDV' Bool],'SBN' 'CPT')\nwrong = 'runBN' $ do \n a <- 'variable' \\\"a\\\" ('t' :: Bool)\n b <- 'variable' \\\"b\\\" ('t' :: Bool) \n-- \n 'proba' a '~~' [0.2,0.8]\n 'cpt' b [a] '~~' [0.8,0.2,0.2,0.8]\n--\n return [a,b]\n@\n\nSo, the first thing to do is generate test patterns. We are using the 'discreteAncestralSampler' for this. This function is\ngenerating a sequence of graphs. We are just interested in the values. So, we get the values with 'allVertexValues'.\n\n@\ngeneratePatterns :: IO [[DVI]]\ngeneratePatterns = do \n let (vars\\@[a,b],exampleG) = simple\n r <- 'runSampling' 5000 0 ('discreteAncestralSampler' exampleG)\n return (map 'allVertexValues' r)\n@\n\nOnce we have the data, we can try to learn the network:\n\n@\nemTest = do \n samples <- generatePatterns \n let (_,simpleG) = simple \n (_,wrongG) = wrong \n print simpleG \n 'printGraphValues' simpleG\n 'printGraphValues' wrongG\n--\n 'printGraphValues' ('learnEM' samples wrongG)\n@\n\nFirst, we display the topology of the graph and the values for the reference graph and the wrong one.\nThen, we use the 'learnEM' function to learn a new network from the samples. And, we print the new values to check.\n\n-}\nmodule Bayes.Examples.EMTest(\n -- * Test function\n emTest\n ) where\n\n\nimport Bayes.Sampling \nimport System.Random.MWC.CondensedTable\nimport qualified Data.Vector as V\nimport Bayes.Factor\nimport Bayes\nimport Bayes.FactorElimination\nimport Data.Maybe(fromJust)\nimport Bayes.BayesianNetwork\nimport Bayes.Factor.CPT\nimport Statistics.Sample.Histogram\nimport Bayes.EM\n\nsimple :: ([TDV Bool],SBN CPT)\nsimple = runBN $ do \n a <- variable \"a\" (t :: Bool)\n b <- variable \"b\" (t :: Bool) \n \n proba a ~~ [0.4,0.6]\n cpt b [a] ~~ [0.8,0.2,0.2,0.8]\n\n return [a,b]\n\nwrong :: ([TDV Bool],SBN CPT)\nwrong = runBN $ do \n a <- variable \"a\" (t :: Bool)\n b <- variable \"b\" (t :: Bool) \n \n proba a ~~ [0.2,0.8]\n cpt b [a] ~~ [0.8,0.2,0.2,0.8]\n\n return [a,b]\n\nsetJust vertex v = Just v \n\ngeneratePatterns :: IO [[DVI]]\ngeneratePatterns = do \n let (vars@[a,b],exampleG) = simple\n r <- runSampling 5000 0 (discreteAncestralSampler exampleG)\n return (map allVertexValues r)\n\nemTest = do \n samples <- generatePatterns \n let (_,simpleG) = simple \n (_,wrongG) = wrong \n print simpleG \n printGraphValues simpleG\n printGraphValues wrongG\n\n \n printGraphValues (learnEM samples wrongG)\n \n", "meta": {"hexsha": "532a54d340db2cccc5d86783441884c2bcc1e56f", "size": 2988, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Bayes/Examples/EMTest.hs", "max_stars_repo_name": "sid-kap/hbayes", "max_stars_repo_head_hexsha": "94557f9a6277c46c0a4b4b8c386aee7d5d6d00e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2016-05-13T14:48:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-14T14:03:26.000Z", "max_issues_repo_path": "Bayes/Examples/EMTest.hs", "max_issues_repo_name": "sid-kap/hbayes", "max_issues_repo_head_hexsha": "94557f9a6277c46c0a4b4b8c386aee7d5d6d00e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-01-24T15:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-12T20:42:53.000Z", "max_forks_repo_path": "Bayes/Examples/EMTest.hs", "max_forks_repo_name": "sid-kap/hbayes", "max_forks_repo_head_hexsha": "94557f9a6277c46c0a4b4b8c386aee7d5d6d00e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-05-19T23:33:04.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-23T16:11:24.000Z", "avg_line_length": 25.1092436975, "max_line_length": 123, "alphanum_fraction": 0.6422356091, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.55611004085047}} {"text": "module Raytracer.Geometry where\n\nimport Numeric.LinearAlgebra.Data (Vector, (|>), toList, (!), fromList, toList)\nimport Numeric.LinearAlgebra.Data (fromColumns, asColumn, toColumns)\nimport Data.Maybe.HT (toMaybe)\nimport Data.Monoid (First(First), Monoid, getFirst, mempty, mappend, mconcat)\nimport Numeric.LinearAlgebra (luSolve, luPacked, pinv, (<>))\nimport Control.Applicative ((<*>), pure)\nimport Control.Monad (join)\nimport Data.Foldable (find)\nimport Data.List (sort)\nimport Data.Function (on)\nimport Data.Maybe (isJust)\nimport Data.Bool.HT (if')\n\n(|*) = (*).(3|>).repeat\n\nall_of :: [(a -> Bool)] -> a -> Bool\nall_of conditions value = and $ conditions <*> (pure value)\n\ntype Pos = Vector Double\ntype Dir = Vector Double\n\n-- This represents a ray of the form r = ax + b\ndata Ray = Ray Dir Pos deriving (Show)\ncalc_ray (Ray a b) n1 = round_to $ (n1 |* a) + b\n where\n round_to = fromList . map (epsilon_round 6) . toList\n epsilon_round n f = (fromInteger $ round $ f * (10^n)) / (10.0^^n)\n\n-- This computes the ray that goes from the first point to the second\nrayTo :: Pos -> Pos -> Ray\np1 `rayTo` p2 = Ray (p2 - p1) p1\n\n-- This wraps a collision with a ray and an object\n-- The `a` is what the object was holding, and the double is how far down the\n-- ray the collision occured (used to find the \"first\" collision)\ndata Collision a = Collision Double a deriving (Show)\n\ndist (Collision d _) = d\n\ninstance Eq (Collision a) where\n (==) = (==) `on` dist\n\ninstance Ord (Collision a) where\n compare = compare `on` dist\n\nclass Intersectable a where\n\tintersection :: Ray -> a b -> Maybe (Collision b)\n\nray_plane_intersect :: Ray -> Plane a -> (Vector Double)\nray_plane_intersect (Ray r1 r2) (Plane a p1 p2 p3) = head.toColumns.(\\m -> (luSolve.luPacked) m (asColumn (r2 - p3))) $ fromColumns [p1, p2, -1 |* r1]\n\n-- This represents a plane of the form p = ax + by + c\ndata Plane a = Plane a Dir Dir Pos deriving (Show)\ncalc_plane (Plane _ a b c) n1 n2 = (n1 |* a) + (n2 |* b) + c\n\ninstance Intersectable Plane where\n\tintersection ray plane@(Plane a _ _ _) = find (all_of [not.isInfinite, (>0)] . dist) $ Just $ Collision n a\n\t\twhere\n\t\tn = (ray_plane_intersect ray plane) ! 2\n\n-- Each of these Vectors represent a point in 3-space\ndata Triangle a = Triangle a Pos Pos Pos deriving (Show)\n\ninstance Intersectable Triangle where\n\tintersection ray (Triangle a p1 p2 p3) = if' (not $ all_of [all (>0), (1>).sum] [n1,n2]) Nothing $ find (all_of [not.isInfinite, (>0)] . dist) $ Just $ Collision n a\n\t\twhere\n\t\tplane = Plane a (p2 - p1) (p3 - p1) p1\n\t\t(n1:n2:n:_) = toList $ ray_plane_intersect ray plane\n\n-- We'll call a collection of triangles a mesh...\ndata Mesh a = Mesh [Triangle a] deriving (Show)\n\n-- Most of this is just proxying the list of triangles.\ninstance Monoid (Mesh a) where\n\tmempty = Mesh []\n\tmappend (Mesh l1) (Mesh l2) = Mesh $ mappend l1 l2\n\ninstance Intersectable Mesh where\n\t-- We'll return, for the mesh, the first one we hit\n\tintersection ray (Mesh triangles) = join $ find isJust $ sort $ fmap (intersection ray) triangles\n\n-- This function takes a point and two vectors and generates a mesh representing that square\nsquare a v1 v2 p1 = Mesh [Triangle a p1 (p1 + v1) (p1 + v1 + v2), Triangle a (p1 + v1 + v2) (p1 + v2) p1]\n\n-- This function takes a point and three vectors and generates a mesh representing that cube\ncube a v1 v2 v3 p1 = mconcat $ fmap (uncurry3 $ square a) [(v1, v2, p1), (v2, v3, p1), (v3, v1, p1), (neg v1, neg v2, p2), (neg v2, neg v3, p2), (neg v3, neg v1, p2)]\n\twhere\n\tp2 = p1 + v1 + v2 + v3\n\tneg = ((-1) |*)\n\tuncurry3 func (a, b, c) = func a b c\n", "meta": {"hexsha": "ca62c872ccb4ca313172ab1bc1af401d8bbc2f0e", "size": 3588, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Raytracer/Geometry.hs", "max_stars_repo_name": "psycotica0/ray-tracer", "max_stars_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Raytracer/Geometry.hs", "max_issues_repo_name": "psycotica0/ray-tracer", "max_issues_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Raytracer/Geometry.hs", "max_forks_repo_name": "psycotica0/ray-tracer", "max_forks_repo_head_hexsha": "d546b218057061c3c8a3cb15a03c91a29130377b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5806451613, "max_line_length": 166, "alphanum_fraction": 0.6794871795, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5556353154728881}} {"text": "module Main where\n\nimport HopfieldMat as H\nimport Numeric.LinearAlgebra\nimport Codec.Picture\nimport Data.Either\nimport Control.Applicative\n\npixelsAsList :: Image PixelRGB8 -> [Int]\npixelsAsList img@(Image w h _) = go <$> [0..w-1] <*> [0..h-1]\n where go y x = pixelToBinary $ pixelAt img x y\n -- black is 1, everything else is zero\n pixelToBinary (PixelRGB8 r _ _) =\n fromIntegral $ 1 - signum r\n\nlistToImage :: Int -> Int -> [Int] -> Image PixelRGB8\nlistToImage w h d = generateImage go w h\n where\n -- this is a horrible idea performance wise. yolo\n go x y = let v = d !! (y * w + x)\n pv = fromIntegral $ 255 * (1 - v)\n in PixelRGB8 pv pv pv\n\nloadPixels :: FilePath -> IO (Vector R)\nloadPixels path = do\n img <- readImage path\n let pat = fromRight [] $ pixelsAsList . convertRGB8 <$> img\n let vpat = fromList $ fromIntegral <$> pat\n return vpat\n\n\nmain :: IO ()\nmain = do\n clean <- loadPixels \"data/test.png\"\n noisy <- loadPixels \"data/test_noisy.png\"\n let ws = H.train clean (H.initialWeights (size clean))\n putStrLn . show $ H.energy ws clean\n putStrLn . show $ H.energy ws noisy\n let newImg = H.feed ws noisy\n savePngImage \"data/output_test.png\" . ImageRGB8\n . listToImage 25 25 $ round <$> toList newImg\n", "meta": {"hexsha": "254dde140d589872e39169a0f723bb1ef2786aa9", "size": 1282, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "mfandl/hml", "max_stars_repo_head_hexsha": "2673bf802d5806e27c17d817be33449c97cc1a3e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "mfandl/hml", "max_issues_repo_head_hexsha": "2673bf802d5806e27c17d817be33449c97cc1a3e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "mfandl/hml", "max_forks_repo_head_hexsha": "2673bf802d5806e27c17d817be33449c97cc1a3e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5238095238, "max_line_length": 61, "alphanum_fraction": 0.6521060842, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5556353041602071}} {"text": "{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeInType #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule Learn.Neural.Layer.Recurrent.LSTM (\n LSTM\n ) where\n\nimport Data.Kind\nimport Data.Singletons.Prelude\nimport GHC.Generics (Generic)\nimport GHC.Generics.Numeric\nimport GHC.TypeLits\nimport Learn.Neural.Layer\nimport Numeric.BLAS\nimport Numeric.Backprop\nimport Numeric.Backprop.Iso\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal\nimport qualified Generics.SOP as SOP\n\ndata LSTM :: Type\n\ninstance ( BLAS b\n , KnownNat i\n , KnownNat o\n , Floating (b '[o])\n , Floating (b '[o,i])\n , Floating (b '[o,o])\n )\n => Component LSTM b '[i] '[o] where\n\n data CParam LSTM b '[i] '[o] =\n LP { _lpForgetInp :: !(b '[o,i])\n , _lpForgetState :: !(b '[o,o])\n , _lpForgetBias :: !(b '[o])\n , _lpRememberInp :: !(b '[o,i])\n , _lpRememberState :: !(b '[o,o])\n , _lpRememberBias :: !(b '[o])\n , _lpCommitInp :: !(b '[o,i])\n , _lpCommitState :: !(b '[o,o])\n , _lpCommitBias :: !(b '[o])\n , _lpOutInp :: !(b '[o,i])\n , _lpOutState :: !(b '[o,o])\n , _lpOutBias :: !(b '[o])\n }\n deriving (Generic)\n data CState LSTM b '[i] '[o] =\n LS { _lsCellState :: !(b '[o])\n , _lsHiddenState :: !(b '[o])\n }\n deriving (Generic)\n type CConstr LSTM b '[i] '[o] = (Num (b '[o,i]), Num (b '[o,o]), Num (b '[o]))\n data CConf LSTM b '[i] '[o] = forall d. ContGen d => LC d\n\n componentOp :: forall s. (Num (b '[i]), Num (b '[o]), CConstr LSTM b '[i] '[o])\n => OpB s '[b '[i], CParam LSTM b '[i] '[o], CState LSTM b '[i] '[o]] '[b '[o], CState LSTM b '[i] '[o]]\n componentOp = bpOp . withInps $ \\(x :< p :< s :< \u00d8) -> do\n fI :< fS :< fB :< rI :< rS :< rB :< cI :< cS :< cB :< oI :< oS :< oB :< \u00d8 <- gTuple #<~ p\n sC :< sH :< \u00d8 <- gTuple #<~ s\n let forget = sum [ matVecOp .$ (fI :< x :< \u00d8)\n , matVecOp .$ (fS :< sH :< \u00d8)\n , fB\n ]\n remember = sum [ matVecOp .$ (rI :< x :< \u00d8)\n , matVecOp .$ (rS :< sH :< \u00d8)\n , rB\n ]\n commit = sum [ matVecOp .$ (cI :< x :< \u00d8)\n , matVecOp .$ (cS :< sH :< \u00d8)\n , cB\n ]\n out = sum [ matVecOp .$ (oI :< x :< \u00d8)\n , matVecOp .$ (oS :< sH :< \u00d8)\n , oB\n ]\n forget' <- tmapOp logistic ~$ (forget :< \u00d8)\n remember' <- tmapOp logistic ~$ (remember :< \u00d8)\n commit' <- tmapOp tanh ~$ (commit :< \u00d8)\n out' <- tmapOp logistic ~$ (out :< \u00d8)\n sC' <- tmapOp tanh ~$ ((forget' * sC + remember' * commit') :< \u00d8)\n finalOut <- bindVar $ out' * sC'\n s' :< \u00d8 <- isoVar (from (gTuple @(CState LSTM b '[i] '[o])) . tup1)\n (sC' :< finalOut :< \u00d8)\n return $ finalOut :< s' :< \u00d8\n where\n logistic :: Floating a => a -> a\n logistic x = 1 / (1 + exp (-x))\n\n defConf = LC (normalDistr 0 0.01)\n initParam = \\case\n i `SCons` SNil -> \\case\n so@(o `SCons` SNil) -> \\(LC d) g -> do\n LP <$> genA (o `SCons` (i `SCons` SNil)) (\\_ -> realToFrac <$> genContVar d g)\n <*> genA (o `SCons` (o `SCons` SNil)) (\\_ -> realToFrac <$> genContVar d g)\n <*> genA so (\\_ -> realToFrac <$> genContVar d g)\n <*> genA (o `SCons` (i `SCons` SNil)) (\\_ -> realToFrac <$> genContVar d g)\n <*> genA (o `SCons` (o `SCons` SNil)) (\\_ -> realToFrac <$> genContVar d g)\n <*> genA so (\\_ -> realToFrac <$> genContVar d g)\n <*> genA (o `SCons` (i `SCons` SNil)) (\\_ -> realToFrac <$> genContVar d g)\n <*> genA (o `SCons` (o `SCons` SNil)) (\\_ -> realToFrac <$> genContVar d g)\n <*> genA so (\\_ -> realToFrac <$> genContVar d g)\n <*> genA (o `SCons` (i `SCons` SNil)) (\\_ -> realToFrac <$> genContVar d g)\n <*> genA (o `SCons` (o `SCons` SNil)) (\\_ -> realToFrac <$> genContVar d g)\n <*> genA so (\\_ -> realToFrac <$> genContVar d g)\n _ -> error \"inaccessible\"\n _ -> error \"inaccessible\"\n initState _ so (LC d) g =\n LS <$> genA so (\\_ -> realToFrac <$> genContVar d g)\n <*> genA so (\\_ -> realToFrac <$> genContVar d g)\n\ninstance ( BLAS b\n , KnownNat i\n , KnownNat o\n , Floating (b '[o])\n , Floating (b '[o,i])\n , Floating (b '[o,o])\n )\n => ComponentLayer 'Recurrent LSTM b '[i] '[o] where\n componentRunMode = RMNotFF\n\ninstance SOP.Generic (CState LSTM b '[i] '[o])\ninstance SOP.Generic (CParam LSTM b '[i] '[o])\n\ninstance (Num (b '[o,i]), Num (b '[o,o]), Num (b '[o])) => Num (CParam LSTM b '[i] '[o]) where\n (+) = genericPlus\n (-) = genericMinus\n (*) = genericTimes\n negate = genericNegate\n abs = genericAbs\n signum = genericSignum\n fromInteger = genericFromInteger\n\ninstance (Fractional (b '[o,i]), Fractional (b '[o,o]), Fractional (b '[o])) => Fractional (CParam LSTM b '[i] '[o]) where\n (/) = genericDivide\n recip = genericRecip\n fromRational = genericFromRational\n\ninstance (Floating (b '[o,i]), Floating (b '[o,o]), Floating (b '[o])) => Floating (CParam LSTM b '[i] '[o]) where\n pi = genericPi\n exp = genericExp\n (**) = genericPower\n log = genericLog\n logBase = genericLogBase\n sin = genericSin\n cos = genericCos\n tan = genericTan\n asin = genericAsin\n acos = genericAcos\n atan = genericAtan\n sinh = genericSinh\n cosh = genericCosh\n tanh = genericTanh\n asinh = genericAsinh\n acosh = genericAcosh\n atanh = genericAtanh\n\ninstance (Num (b '[o,i]), Num (b '[o,o]), Num (b '[o])) => Num (CState LSTM b '[i] '[o]) where\n (+) = genericPlus\n (-) = genericMinus\n (*) = genericTimes\n negate = genericNegate\n abs = genericAbs\n signum = genericSignum\n fromInteger = genericFromInteger\n\ninstance (Fractional (b '[o,i]), Fractional (b '[o,o]), Fractional (b '[o])) => Fractional (CState LSTM b '[i] '[o]) where\n (/) = genericDivide\n recip = genericRecip\n fromRational = genericFromRational\n\ninstance (Floating (b '[o,i]), Floating (b '[o,o]), Floating (b '[o])) => Floating (CState LSTM b '[i] '[o]) where\n pi = genericPi\n exp = genericExp\n (**) = genericPower\n log = genericLog\n logBase = genericLogBase\n sin = genericSin\n cos = genericCos\n tan = genericTan\n asin = genericAsin\n acos = genericAcos\n atan = genericAtan\n sinh = genericSinh\n cosh = genericCosh\n tanh = genericTanh\n asinh = genericAsinh\n acosh = genericAcosh\n atanh = genericAtanh\n\n", "meta": {"hexsha": "68c2028bff15c350d61487e8d7432e20efdf635a", "size": 7872, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "old/src/Learn/Neural/Layer/Recurrent/LSTM.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "old/src/Learn/Neural/Layer/Recurrent/LSTM.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "old/src/Learn/Neural/Layer/Recurrent/LSTM.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 39.36, "max_line_length": 122, "alphanum_fraction": 0.4678607724, "num_tokens": 2321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5556053013054337}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE NamedFieldPuns #-}\nmodule Network\n ( NeuralNet (..),\n train,\n test,\n initWB,\n loadData,\n loadTestData,\n ) where\n\nimport Codec.Compression.GZip (decompress)\nimport Control.Monad\nimport qualified Data.Array.IO as A\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Lazy as BL\nimport Data.Int (Int64)\nimport Data.List\nimport GHC.Base (build)\nimport Numeric.LinearAlgebra hiding (build, normalize)\nimport Prelude hiding ((<>))\nimport System.Directory (getCurrentDirectory)\nimport qualified System.Random as R\nimport Util\n\ntype Image = Vector Double\ntype Label = Vector Double\ntype Bias = Vector Double\ntype Weight = Matrix Double\ntype Activation = Matrix Double\ntype Nabla = Matrix Double\ntype ImagesMat = Matrix Double\ntype LabelsMat = Matrix Double\n\ndata NeuralNet = NN\n { weights :: ![Weight] -- ^ List of all weights\n , biases :: ![Bias] -- ^ List of all biases\n , eta :: !Double -- ^ Learning rate\n , epochs :: !Int -- ^ No. of epochs\n , layers :: !Int -- ^ No. of layers\n , layerSize :: !Int -- ^ Size of hidden layers\n , batchSize :: !Int -- ^ Size of mini-batch\n , trainData :: ![(Image, Label)]\n , testData :: ![(ImagesMat, Int)]\n } deriving (Show, Eq)\n\ntest :: NeuralNet -> IO ()\ntest net@NN{epochs, biases, weights, testData} = do\n let (imgs, labels) = unzip testData\n let guesses = [guess img (zip weights $ toMatrix <$> biases) | img <- imgs]\n let c = sum $ (\\(a,b) -> if a == b then 1 else 0) <$> zip guesses labels\n putStrLn $ \"Epoch #\" ++ (show $ 30-epochs) ++ \": \" ++ (show $ c/100) ++ \"%\"\n where\n guess :: ImagesMat -> [(Weight, Matrix Double)] -> Int\n guess i wb = maxIndex . flatten . head $ feedforward i wb\n\n-- | Fully matrix-based approach to backpropagation.\ntrain :: NeuralNet -> IO NeuralNet\ntrain net@NN{weights, batchSize, epochs, trainData} = do\n shuffledData <- shuffle trainData\n let miniBatches = chunkList batchSize shuffledData\n let batches = fmap getMiniBatch miniBatches\n let !(newWs, newBs) = (recurTest batchSize (weights, biases net) batches) :: ([Weight], [Bias])\n let newNet = net { weights = newWs, biases = newBs, epochs = epochs-1 }\n test newNet\n case epochs of\n 1 -> return newNet\n _ -> train newNet\n\nrecurTest :: Int -> ([Weight], [Bias]) -> [(ImagesMat, LabelsMat)] -> ([Weight], [Bias])\nrecurTest batchSize !wb [batch] = trainBatch batchSize wb batch\nrecurTest batchSize !wb (firstBatch:batches) = recurTest batchSize (trainBatch batchSize wb firstBatch) batches\n\ntrainBatch :: Int -> ([Weight], [Bias]) -> (ImagesMat, LabelsMat) -> ([Weight], [Bias])\ntrainBatch batchSize !(ws, bs) (mX, mY) = backprop mY ws bs $ feedforward mX (zip ws $ bTm bs batchSize)\n\n-- | Make biases suitable for full-matrix backprop.\nbTm :: [Bias] -> Int -> [Matrix Double]\nbTm biases batchSize = fmap (fromColumns . replicate batchSize) biases\n\n-- | Turn mini-batch matrices into one matrix.\ngetMiniBatch :: [(Image, Label)] -> (ImagesMat, LabelsMat)\ngetMiniBatch mBatchData = (fromColumns imgs, fromColumns labels)\n where\n (imgs, labels) = unzip mBatchData\n\nfeedforward :: ImagesMat -> [(Weight, Matrix Double)] -> [Activation]\nfeedforward = scanr (\\(w, b) a -> sigmoid $ w <> a + b)\n\nbackprop :: LabelsMat -> [Weight] -> [Bias] -> [Activation] -> ([Weight], [Bias])\nbackprop y ws bs (aL:as) = (zipWithSafe (-) ws (zipWithSafe (<>) deltaList (tr <$> as)), zipWithSafe (-) bs $ meanRows <$> deltaList)\n where\n deltaList :: [Matrix Double]\n deltaList = init $ deltas [edgeDelta y aL] y as ws\n\ndeltas :: [Matrix Double]\n -> LabelsMat\n -> [Activation]\n -> [Weight]\n -> [Matrix Double]\ndeltas deltal _ [] [] = deltal\ndeltas deltal y (a:as) (wlp1:ws) = deltas (deltal++[(tr wlp1 <> last deltal) * sigmoid' a]) y as ws\n\nedgeDelta :: LabelsMat -- ^ Correct output Y for input X\n -> Activation -- ^ Predicted ouput for input X\n -> Matrix Double\nedgeDelta y aL = (aL - y) * sigmoid' aL\n\n{-- Arithmetic Functions --}\ncost :: Matrix Double -> Matrix Double -> Matrix Double\ncost a y = ((a-y)**2) / 2\n\nsigmoid :: Floating a => a -> a\nsigmoid x = 1 / (1 + (exp (-x)))\n\nsigmoid' :: Floating a => a -> a\nsigmoid' x = x * (1 - x)\n\nnormalize :: (Integral a, Floating b) => a -> b\nnormalize x = (fromIntegral x) / 255\n\ngauss :: IO Double\ngauss = do\n u1 <- R.randomRIO (0 :: Double, 1 :: Double)\n u2 <- R.randomRIO (0 :: Double, 1 :: Double)\n return $ (sqrt (-2*log u1)) * (cos (2*pi*u2))\n\n{-- Data Processing Functions --}\ninitWB :: NeuralNet -> IO NeuralNet\ninitWB net@NN{batchSize = bs, layerSize = ls, layers = n} = do\n headW <- randn ls 784\n midW <- replicateM (n-2) (randn ls ls)\n lastW <- randn 10 ls\n\n initB <- replicateM (n-1) (randn ls 1)\n lastB <- randn 10 1\n\n let weights = reverse $ headW : midW ++ [lastW]\n let biases = reverse . fmap flatten $ initB ++ [lastB]\n\n return net { weights = weights\n , biases = biases }\n\nrandomMatrix :: Int -> Int -> IO (Matrix Double)\nrandomMatrix nrows ncols = do\n gaussList <- replicateM (ncols*nrows) gauss\n return $ (nrows> [getImage n imgs | n <- [0..9999]] :: [Matrix Double]\n return $ zip i l\n\ngetData :: FilePath -> IO BL.ByteString\ngetData path = do\n currentDir <- getCurrentDirectory\n fileData <- decompress <$> BL.readFile (currentDir ++ \"/data/mnist_dataset/\" ++ path)\n return fileData\n\ngetImage :: Int -> BS.ByteString -> Image\ngetImage n imgs = fromList [normalize $ BS.index imgs (16 + n*784 + s) | s <- [0..783]]\n\n-- | `getImage` but lazy\ngetImage' :: Int64 -> BL.ByteString -> Image\ngetImage' n imgs = fromList [normalize $ BL.index imgs (16 + n*784 + s) | s <- [0..783]]\n\ngetLabel :: Num a => Int -> BS.ByteString -> a\ngetLabel n labels = fromIntegral $ BS.index labels (n+8)\n\ngetGuess :: [Activation] -> Int\ngetGuess = maxIndex . flatten . head\n\nvectorizeLabel :: Int -> Vector Double\nvectorizeLabel l = fromList $ x ++ 1 : y\n where (x,y) = splitAt l $ replicate 9 0\n\n{-- HELPER FUNCTIONS --}\ntoMatrix :: Vector Double -> Matrix Double\ntoMatrix = reshape 1\n\n-- | Means of rows in matrix as a column vector\nmeanRows :: Matrix Double -> Vector Double\nmeanRows = fst . meanCov . tr\n\n-- | zipWith, but throws error if lengths don't match\nzipWithSafe :: (a -> b -> c) -> [a] -> [b] -> [c]\nzipWithSafe f as bs\n | length as == length bs = zipWith f as bs\n | otherwise = error $ \"zipWith: lengths don't match (\" ++ (show $ length as) ++ \" \" ++ (show $ length bs) ++ \")\"\n\n-- | Randomly shuffle a list\n-- /O(N)/\nshuffle :: [a] -> IO [a]\nshuffle xs = do\n ar <- newArray n xs\n forM [1..n] $ \\i -> do\n j <- R.randomRIO (i,n)\n vi <- A.readArray ar i\n vj <- A.readArray ar j\n A.writeArray ar j vi\n return vj\n where\n n = length xs\n newArray :: Int -> [a] -> IO (A.IOArray Int a)\n newArray n xs = A.newListArray (1,n) xs\n", "meta": {"hexsha": "1b521e6c925dbb09b95e9a6365ecb349e2c65c02", "size": 7995, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Network.hs", "max_stars_repo_name": "WhateverHappns/haskell-mnist", "max_stars_repo_head_hexsha": "88aced9476c7ea985ab0857fc7e1b9c5ce3e30d3", "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/Network.hs", "max_issues_repo_name": "WhateverHappns/haskell-mnist", "max_issues_repo_head_hexsha": "88aced9476c7ea985ab0857fc7e1b9c5ce3e30d3", "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/Network.hs", "max_forks_repo_name": "WhateverHappns/haskell-mnist", "max_forks_repo_head_hexsha": "88aced9476c7ea985ab0857fc7e1b9c5ce3e30d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1764705882, "max_line_length": 133, "alphanum_fraction": 0.6092557849, "num_tokens": 2274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.555512601284292}} {"text": "-- https://github.com/minoki/my-atcoder-solutions\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\nimport Control.Exception (assert)\nimport Control.Monad\nimport Data.Bits\nimport qualified Data.ByteString.Builder as BSB\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char (isSpace)\nimport Data.Coerce\nimport Data.Complex\nimport Data.Int (Int64)\nimport Data.List (unfoldr)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport System.IO (stdout)\n\nmain = do\n n <- readLn @Int -- n <= 10^5\n (as,bs) <- fmap U.unzip $ U.replicateM n $ do\n [a,b] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine\n return (a,b)\n let p, q :: Poly U.Vector Int\n p = Poly $ normalizePoly (0 `U.cons` as)\n q = Poly $ normalizePoly (0 `U.cons` bs)\n -- v = coeffAsc (p * q)\n !v = coeffAsc p `mulFFT` coeffAsc q\n !l = U.length v\n BSB.hPutBuilder stdout $ mconcat\n [ if k < l then\n BSB.intDec (v U.! k) <> BSB.char8 '\\n' -- <= 10^9\n else\n BSB.string8 \"0\\n\"\n | k <- [1..2*n]\n ]\n\n--\n-- Fast Fourier Transform (FFT)\n--\n\nhalve :: G.Vector vec a => vec a -> vec a\nhalve v = let n = G.length v\n in G.generate (n `quot` 2) $ \\j -> v G.! (j * 2)\n\nfft :: forall vec a. (Num a, G.Vector vec a)\n => [vec a] -- ^ For a primitive n-th root of unity @u@, @iterate halve [1,u,u^2 .. u^(n-1)]@\n -> vec a -- ^ a polynomial of length n (= 2^k for some k)\n -> vec a\nfft (u:u2) f | n == 1 = f\n | otherwise = let !n2 = n `quot` 2\n r0, r1', t0, t1' :: vec a\n r0 = G.generate n2 $ \\j -> (f G.! j) + (f G.! (j + n2))\n r1' = G.generate n2 $ \\j -> ((f G.! j) - (f G.! (j + n2))) * u G.! j\n !t0 = fft u2 r0\n !t1' = fft u2 r1'\n in G.generate n $ \\j -> if even j then t0 G.! (j `quot` 2) else t1' G.! (j `quot` 2)\n where n = G.length f\n\nmulFFT :: U.Vector Int -> U.Vector Int -> U.Vector Int\nmulFFT !f !g = let n' = U.length f + U.length g - 2\n k = finiteBitSize n' - countLeadingZeros n'\n !_ = assert (n' < 2^k) ()\n n = bit k\n u :: U.Vector (Complex Double)\n u = U.generate n $ \\j -> cis (fromIntegral j * (2 * pi / fromIntegral n))\n us = iterate halve u\n f' = U.generate n $ \\j -> if j < U.length f then\n fromIntegral (f U.! j)\n else\n 0\n g' = U.generate n $ \\j -> if j < U.length g then\n fromIntegral (g U.! j)\n else\n 0\n f'' = fft us f'\n g'' = fft us g'\n fg = U.generate n $ \\j -> (f'' U.! j) * (g'' U.! j)\n fg' = fft (map (U.map conjugate) us) fg\n in U.generate n $ \\j -> round (realPart (fg' U.! j) / fromIntegral n)\n\n--\n-- Univariate polynomial\n--\n\nnewtype Poly vec a = Poly { coeffAsc :: vec a } deriving Eq\n\nnormalizePoly :: (Eq a, Num a, G.Vector vec a) => vec a -> vec a\nnormalizePoly v | G.null v || G.last v /= 0 = v\n | otherwise = normalizePoly (G.init v)\n\naddPoly :: (Eq a, Num a, G.Vector vec a) => vec a -> vec a -> vec a\naddPoly v w = case compare n m of\n LT -> G.generate m $ \\i -> if i < n\n then v G.! i + w G.! i\n else w G.! i\n GT -> G.generate n $ \\i -> if i < m\n then v G.! i + w G.! i\n else v G.! i\n EQ -> normalizePoly $ G.zipWith (+) v w\n where n = G.length v\n m = G.length w\n\nsubPoly :: (Eq a, Num a, G.Vector vec a) => vec a -> vec a -> vec a\nsubPoly v w = case compare n m of\n LT -> G.generate m $ \\i -> if i < n\n then v G.! i - w G.! i\n else negate (w G.! i)\n GT -> G.generate n $ \\i -> if i < m\n then v G.! i - w G.! i\n else v G.! i\n EQ -> normalizePoly $ G.zipWith (-) v w\n where n = G.length v\n m = G.length w\n\nnaiveMulPoly :: (Num a, G.Vector vec a) => vec a -> vec a -> vec a\nnaiveMulPoly v w = G.generate (n + m - 1) $\n \\i -> sum [(v G.! (i-j)) * (w G.! j) | j <- [max (i-n+1) 0..min i (m-1)]]\n where n = G.length v\n m = G.length w\n\ndoMulP :: (Eq a, Num a, G.Vector vec a) => Int -> vec a -> vec a -> vec a\ndoMulP n !v !w | n <= 16 = naiveMulPoly v w\ndoMulP n !v !w\n | G.null v = v\n | G.null w = w\n | G.length v < n2 = let (w0, w1) = G.splitAt n2 w\n u0 = doMulP n2 v w0\n u1 = doMulP n2 v w1\n in G.generate (G.length v + G.length w - 1)\n $ \\i -> case () of\n _ | i < n2 -> u0 `at` i\n | i < n -> (u0 `at` i) + (u1 `at` (i - n2))\n | i < n + n2 -> (u1 `at` (i - n2))\n | G.length w < n2 = let (v0, v1) = G.splitAt n2 v\n u0 = doMulP n2 v0 w\n u1 = doMulP n2 v1 w\n in G.generate (G.length v + G.length w - 1)\n $ \\i -> case () of\n _ | i < n2 -> u0 `at` i\n | i < n -> (u0 `at` i) + (u1 `at` (i - n2))\n | i < n + n2 -> (u1 `at` (i - n2))\n | otherwise = let (v0, v1) = G.splitAt n2 v\n (w0, w1) = G.splitAt n2 w\n v0_1 = v0 `addPoly` v1\n w0_1 = w0 `addPoly` w1\n p = doMulP n2 v0_1 w0_1\n q = doMulP n2 v0 w0\n r = doMulP n2 v1 w1\n -- s = (p `subPoly` q) `subPoly` r -- p - q - r\n -- q + s*X^n2 + r*X^n\n in G.generate (G.length v + G.length w - 1)\n $ \\i -> case () of\n _ | i < n2 -> q `at` i\n | i < n -> ((q `at` i) + (p `at` (i - n2))) - ((q `at` (i - n2)) + (r `at` (i - n2)))\n | i < n + n2 -> ((r `at` (i - n)) + (p `at` (i - n2))) - ((q `at` (i - n2)) + (r `at` (i - n2)))\n | otherwise -> r `at` (i - n)\n where n2 = n `quot` 2\n at :: (Num a, G.Vector vec a) => vec a -> Int -> a\n at v i = if i < G.length v then v G.! i else 0\n{-# INLINE doMulP #-}\n\nmulPoly :: (Eq a, Num a, G.Vector vec a) => vec a -> vec a -> vec a\nmulPoly !v !w = let k = ceiling ((log (fromIntegral (max n m)) :: Double) / log 2) :: Int\n in doMulP (2^k) v w\n where n = G.length v\n m = G.length w\n{-# INLINE mulPoly #-}\n\nzeroPoly :: (G.Vector vec a) => Poly vec a\nzeroPoly = Poly G.empty\n\nconstPoly :: (Eq a, Num a, G.Vector vec a) => a -> Poly vec a\nconstPoly 0 = Poly G.empty\nconstPoly x = Poly (G.singleton x)\n\nscalePoly :: (Eq a, Num a, G.Vector vec a) => a -> Poly vec a -> Poly vec a\nscalePoly a (Poly xs)\n | a == 0 = zeroPoly\n | otherwise = Poly $ G.map (* a) xs\n\nvalueAtPoly :: (Num a, G.Vector vec a) => Poly vec a -> a -> a\nvalueAtPoly (Poly xs) t = G.foldr' (\\a b -> a + t * b) 0 xs\n\ninstance (Eq a, Num a, G.Vector vec a) => Num (Poly vec a) where\n (+) = coerce (addPoly :: vec a -> vec a -> vec a)\n (-) = coerce (subPoly :: vec a -> vec a -> vec a)\n negate (Poly v) = Poly (G.map negate v)\n (*) = coerce (mulPoly :: vec a -> vec a -> vec a)\n fromInteger = constPoly . fromInteger\n abs = undefined; signum = undefined\n\ndivModPoly :: (Eq a, Fractional a, G.Vector vec a) => Poly vec a -> Poly vec a -> (Poly vec a, Poly vec a)\ndivModPoly f g@(Poly w)\n | G.null w = error \"divModPoly: divide by zero\"\n | degree f < degree g = (zeroPoly, f)\n | otherwise = loop zeroPoly (scalePoly (recip b) f)\n where\n g' = toMonic g\n b = leadingCoefficient g\n -- invariant: f == q * g + scalePoly b p\n loop q p | degree p < degree g = (q, scalePoly b p)\n | otherwise = let q' = Poly (G.drop (degree' g) (coeffAsc p))\n in loop (q + q') (p - q' * g')\n\n toMonic :: (Fractional a, G.Vector vec a) => Poly vec a -> Poly vec a\n toMonic f@(Poly xs)\n | G.null xs = zeroPoly\n | otherwise = Poly $ G.map (* recip (leadingCoefficient f)) xs\n\n leadingCoefficient :: (Num a, G.Vector vec a) => Poly vec a -> a\n leadingCoefficient (Poly xs)\n | G.null xs = 0\n | otherwise = G.last xs\n\n degree :: G.Vector vec a => Poly vec a -> Maybe Int\n degree (Poly xs) = case G.length xs - 1 of\n -1 -> Nothing\n n -> Just n\n\n degree' :: G.Vector vec a => Poly vec a -> Int\n degree' (Poly xs) = case G.length xs of\n 0 -> error \"degree': zero polynomial\"\n n -> n - 1\n\n-- \u7d44\u7acb\u9664\u6cd5\n-- second constPoly (divModByDeg1 f t) = divMod f (Poly (G.fromList [-t, 1]))\ndivModByDeg1 :: (Eq a, Num a, G.Vector vec a) => Poly vec a -> a -> (Poly vec a, a)\ndivModByDeg1 f t = let w = G.postscanr (\\a b -> a + b * t) 0 $ coeffAsc f\n in (Poly (G.tail w), G.head w)\n", "meta": {"hexsha": "5501ff2566e4f78c826767d01b70075f0aa16d67", "size": 9933, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "atc001-c/Main.hs", "max_stars_repo_name": "minoki/my-atcoder-solutions", "max_stars_repo_head_hexsha": "b571a65bae7794b315e39b95ab1b2b62706f3aaa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-25T01:44:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T06:53:26.000Z", "max_issues_repo_path": "atc001-c/Main.hs", "max_issues_repo_name": "minoki/my-atcoder-solutions", "max_issues_repo_head_hexsha": "b571a65bae7794b315e39b95ab1b2b62706f3aaa", "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": "atc001-c/Main.hs", "max_forks_repo_name": "minoki/my-atcoder-solutions", "max_forks_repo_head_hexsha": "b571a65bae7794b315e39b95ab1b2b62706f3aaa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6309012876, "max_line_length": 127, "alphanum_fraction": 0.4347125742, "num_tokens": 2973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5554014002265861}} {"text": "module Main where\n\nimport Vector\nimport Tensor\nimport Data.Complex\nimport System.Random.Stateful\nimport EitherTrans\nimport Control.Monad.Trans.State\n\nfunc i n c = do\n s <- newIOGenM $ mkStdGen 42\n let sT = measure i s\n result <- runEither $ (EitherT . return) x1 >>= execStateT sT\n let result2 = x1 >>= isEntangled [c]\n let result3 = x2 >>= isEntangled [c]\n --either putStrLn (putStrLn . illegalPeek) result3\n either putStrLn print result2\n either putStrLn print result3\n where\n x = initNumQubit0 n :: Either String (Vector (Complex Double))\n x0 = x >>= applyGate hadamard 0\n x1 = x0 >>= applyControl pauliX 0 1\n x2 = x >>= applyGateAll hadamard\n\nmain = func 1 2 0\n", "meta": {"hexsha": "0137c4d32fc640c7124e0e03f1f2055b971705d7", "size": 752, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "w41g87/Qaskell", "max_stars_repo_head_hexsha": "40bfa73d1e4b6ab59921129cd84190d7440eba7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "w41g87/Qaskell", "max_issues_repo_head_hexsha": "40bfa73d1e4b6ab59921129cd84190d7440eba7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "w41g87/Qaskell", "max_forks_repo_head_hexsha": "40bfa73d1e4b6ab59921129cd84190d7440eba7c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9230769231, "max_line_length": 70, "alphanum_fraction": 0.6409574468, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5551161069017204}} {"text": "module MachineLearning.NeuralNetworkTest\n(\n tests\n)\n\nwhere\n\nimport Test.Framework (testGroup)\nimport Test.Framework.Providers.HUnit\nimport Test.HUnit\nimport Test.HUnit.Approx\nimport Test.HUnit.Plus\n\nimport MachineLearning.DataSets (dataset2)\n\nimport qualified Control.Monad.Random as RndM\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified MachineLearning as ML\nimport qualified MachineLearning.Optimization as Opt\nimport MachineLearning.Model\nimport MachineLearning.NeuralNetwork\nimport qualified MachineLearning.NeuralNetwork.TopologyMaker as TM\n\n(x, y) = ML.splitToXY dataset2\n\ngradientCheckingEps = 0.1\n\ncheckGradientTest eps activation loss lambda = do\n let nnt = TM.makeTopology activation loss (LA.cols x) 2 [10]\n model = NeuralNetwork nnt\n thetas = initializeTheta 1511197 nnt\n diffs = take 5 $ map (\\e -> Opt.checkGradient model lambda x y thetas e) [0.005, 0.0051 ..]\n diff = minimum $ filter (not . isNaN) diffs\n assertApproxEqual (show thetas) eps 0 diff\n\n\nxPredict = LA.matrix 2 [ -0.5, 0.5\n , 0.2, -0.2\n , 1, 1\n , 1, 0\n , 0, 0]\nyExpected = LA.vector [1, 1, 0, 0, 1]\n\nlearnTest activation loss minMethod nIters =\n let lambda = L2 $ 0.5 / (fromIntegral $ LA.rows x)\n x1 = ML.mapFeatures 2 x\n nnt = TM.makeTopology activation loss (LA.cols x1) 2 [10]\n model = NeuralNetwork nnt\n xPredict1 = ML.mapFeatures 2 xPredict\n initTheta = initializeTheta 5191711 nnt\n (theta, optPath) = Opt.minimize minMethod model 1e-7 nIters lambda x1 y initTheta\n yPredicted = hypothesis model xPredict1 theta\n js = (LA.toColumns optPath) !! 1\n in do\n assertVector (show js) 0.01 yExpected yPredicted\n\n\ntests = [ testGroup \"gradient checking\" [\n testCase \"Sigmoid - Logistic: non-zero lambda\" $ checkGradientTest 0.1 TM.ASigmoid TM.LLogistic (L2 0.01)\n , testCase \"Sigmoid - Logistic: zero lambda\" $ checkGradientTest 0.1 TM.ASigmoid TM.LLogistic (L2 0)\n , testCase \"ReLU - Softmax: non-zero lambda\" $ checkGradientTest 0.1 TM.ARelu TM.LSoftmax (L2 0.01)\n , testCase \"ReLU - Softmax: zero lambda\" $ checkGradientTest 0.1 TM.ARelu TM.LSoftmax (L2 0)\n , testCase \"Tanh - MultiSvm: non-zero lambda\" $ checkGradientTest 0.1 TM.ATanh TM.LMultiSvm (L2 0.01)\n , testCase \"Tanh - MultiSvm: zero lambda\" $ checkGradientTest 0.1 TM.ATanh TM.LMultiSvm (L2 0)\n , testCase \"Tanh - MultiSvm: no reg\" $ checkGradientTest 0.1 TM.ATanh TM.LMultiSvm RegNone\n ]\n , testGroup \"learn\" [\n testCase \"Sigmoid - Logistic: BFGS\" $ learnTest TM.ASigmoid TM.LLogistic (Opt.BFGS2 0.01 0.7) 50\n , testCase \"ReLU - Softmax: BFGS\" $ learnTest TM.ARelu TM.LSoftmax (Opt.BFGS2 0.1 0.1) 50\n , testCase \"Tanh - MultiSvm: BFGS\" $ learnTest TM.ATanh TM.LMultiSvm (Opt.BFGS2 0.1 0.1) 50\n ]\n ]\n", "meta": {"hexsha": "7387037bbb8bdac47c10605a3803e38a93c825cd", "size": 2956, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/MachineLearning/NeuralNetworkTest.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "test/MachineLearning/NeuralNetworkTest.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "test/MachineLearning/NeuralNetworkTest.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 40.4931506849, "max_line_length": 117, "alphanum_fraction": 0.6684709066, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5550245401321865}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE LambdaCase #-}\n\n{--\n - Author: haym \n -\n - Helper functions common to multiple projects\n--}\n\nmodule Lib where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Char\nimport Data.Colour.Names\nimport Data.Maybe\n\nimport Data.Complex\nimport Graphics.Rendering.Chart.Backend.Diagrams\nimport Graphics.Rendering.Chart.Easy\nimport System.Process\n\ntype C = Complex Double\n\nclass Mag a where\n mag :: a -> Double\n\ninstance Mag Double where\n mag = id\n\ninstance Mag C where\n mag = magnitude\n\nplotPoints' :: FilePath -> String -> Double -> [(Double, Double)] -> IO ()\nplotPoints' file title rad xs = plotPoints file title rad xs >> callCommand (\"inkview \" ++ file)\n\nplotPoints :: FilePath -> String -> Double -> [(Double, Double)] -> IO ()\nplotPoints = plotPointsColor black\n\nplotPointsColor :: Colour Double -> FilePath -> String -> Double -> [(Double, Double)] -> IO ()\nplotPointsColor color file title rad xs = toFile def file $ do\n layout_title .= title\n plot (pointsConfig color rad <$> points \"points\" xs)\n\npointsConfig :: Colour Double -> Double -> PlotPoints x y -> PlotPoints x y \npointsConfig color rad\n = set (plot_points_style.point_color) (opaque color)\n . set (plot_points_style.point_radius) rad\n\ndiverges :: (Mag a) => Int -> (a -> a) -> a -> Bool\ndiverges maxIters func x0 = any (\\x -> mag x > 4) . take maxIters $ iterate func x0\n\nc2t :: Complex Double -> (Double, Double)\nc2t (r :+ i) = (r, i)\n\nletterCoeff :: Char -> Double\nletterCoeff c = fromIntegral (fromEnum (toLower c) - fromEnum 'a') / 10 - 1.2\n\ntype Attractor = (Double -> Double -> Double, Double -> Double -> Double)\n\nmkAttractor :: [Double] -> Attractor\nmkAttractor cs = (fx, fy)\n where\n getNum = get >>= \\case\n (x:xs) -> put xs >> return x\n _ -> return 0\n mkMap = do\n n <- replicateM 6 getNum\n return $ case n of\n [a1, a2, a3, a4, a5, a6] ->\n let f x y = a1 + a2*x + a3*x*x + a4*x*y + a5*y + a6*y*y\n in f\n [] -> error \"lol\"\n\n [fx, fy] = evalState (replicateM 2 mkMap) cs\n\nattrFromLetters :: String -> Attractor\nattrFromLetters = mkAttractor . fmap letterCoeff\n\nrunAttractor :: Attractor -> (Double, Double) -> (Double, Double)\nrunAttractor (fx, fy) (x, y) = (fx x y, fy x y)\n\nclass VSpace a where\n (^+) :: a -> a -> a\n (^*) :: Double -> a -> a\n\ninstance VSpace Double where\n (^+) = (+)\n (^*) = (*)\n\ninstance VSpace (Double, Double) where\n (^+) (x0, y0) (x1, y1) = (x0 + x1, y0 + y1) \n (^*) a (x, y) = (a*x, a*y) \n\ninstance VSpace (Double, Double, Double) where\n (^+) (x0, y0, z0) (x1, y1, z1) = (x0 + x1, y0 + y1, z0 + z1) \n (^*) a (x, y, z) = (a*x, a*y, a*z) \n\nrkStep :: (VSpace a) => (a -> a) -> Double -> (Double, a) -> (Double, a)\nrkStep f dt (t, y) = (t + dt, y ^+ ((dt / 6)^*(k1 ^+ (2.0^*k2) ^+ (2.0^*k3) ^+ k4)))\n where\n k1 = f y\n k2 = f (y ^+ ((0.5*dt)^*k1))\n k3 = f (y ^+ ((0.5*dt)^*k2))\n k4 = f (y ^+ (dt^*k3))\n\nrkStep' :: (VSpace a) => (a -> a -> a) -> Double -> (Double, a, a) -> (Double, a, a)\nrkStep' f dt (t, y, y') = (t + dt, y ^+ (dt^*y'), y'New)\n where\n y'New = y' ^+ ((dt / 6)^*(k1 ^+ (2.0^*k2) ^+ (2.0^*k3) ^+ k4))\n k1 = f y y'\n k2 = f y (y' ^+ ((0.5*dt)^*k1))\n k3 = f y (y' ^+ ((0.5*dt)^*k2))\n k4 = f y (y' ^+ (dt^*k3))\n\neulerStep' :: VSpace a => (a -> a -> a) -> Double -> (Double, a, a) -> (Double, a, a)\neulerStep' a dt (t, y, y') = (tNew, yNew, y'New)\n where\n y'New = y' ^+ (dt^*a y y')\n yNew = y ^+ (dt^*y'New)\n tNew = t + dt\n\neulerStep :: (VSpace a) => (a -> a) -> Double -> (Double, a) -> (Double, a)\neulerStep f dt (t, y) = (t + dt, y ^+ (dt^*f y))\n", "meta": {"hexsha": "8c10595bdc93b898bb54553f904d7d43432c1180", "size": 3775, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "ahaym/dynamics", "max_stars_repo_head_hexsha": "393175c9f9db1449dc121cd3c6f778ee6da024d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "ahaym/dynamics", "max_issues_repo_head_hexsha": "393175c9f9db1449dc121cd3c6f778ee6da024d0", "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": "ahaym/dynamics", "max_forks_repo_head_hexsha": "393175c9f9db1449dc121cd3c6f778ee6da024d0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2, "max_line_length": 96, "alphanum_fraction": 0.5438410596, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5545929012919255}} {"text": "{-# LANGUAGE BangPatterns #-}\nmodule ML.NN.Training\n (\n -- * Training networks\n TrainingConfig(..)\n , Sample(..)\n , Gradient(..)\n , sgd\n , gradientDescentCore\n\n -- * Internal (exposed for testing)\n , computeZsAndAs\n ) where\n\nimport ML.CostFunctions (CostDerivative, mse')\nimport ML.NN\nimport ML.NN.ActivationFunction (ActivationFunctionDerivative)\nimport ML.Sample (Sample(..))\n\nimport Control.Monad.Random (evalRandIO)\nimport Control.Monad.Random.Extended (vshuffle)\nimport Control.Monad.State (State, evalState, get, put)\nimport Data.Foldable (foldl')\nimport Data.List (unfoldr)\nimport qualified Data.Vector as V\nimport Numeric.LinearAlgebra (Matrix, R, Vector, (#>), (<>), asColumn, asRow, cmap, konst, outer, size, tr)\n\n-- | Configuration for training a network.\ndata TrainingConfig = TrainingConfig\n { trainingEta :: R -- ^ \u03b7 - Learning rate.\n , trainingActivation :: ActivationFunction\n , trainingActivationDerivative :: ActivationFunctionDerivative\n , trainingCostDerivative :: CostDerivative\n }\n\n-- | The gradient of the network.\ndata Gradient = Gradient\n { gradientNablaB :: {-# UNPACK #-} !(V.Vector (Vector R))\n , gradientNablaW :: {-# UNPACK #-} !(V.Vector (Matrix R))\n } deriving (Read, Show)\n\nsumGradients :: V.Vector Gradient -> Gradient\nsumGradients = V.foldl1' addGradient\n where (Gradient !lb !lw) `addGradient` (Gradient !rb !rw) =\n Gradient (V.zipWith (+) lb rb) (V.zipWith (+) lw rw)\n\n-- | Return z and activation values for each layer in the network.\n--\n-- The values are returned in reverse order for use by the\n-- backpropogation algorithm. We the State monad so it's more\n-- explicit that the output activation of one layer is the input to\n-- the next.\ncomputeZsAndAs :: ActivationFunction -> Network -> Vector R -> ([Vector R], [Vector R])\ncomputeZsAndAs act (Network layers) input = (reverse zs, reverse (input:as))\n where (zs, as) = unzip $ evalState (mapM computeZA layers) input\n\n computeZA :: Layer -> State (Vector R) (Vector R, Vector R)\n computeZA (Layer b w) = do\n x <- get\n let z = w #> x + b\n a = cmap act z\n put a\n pure $ (z,a)\n\n-- | Compute the gradient for the training example.\nbackpropogation :: ActivationFunction\n -> ActivationFunctionDerivative\n -> CostDerivative\n -> Network\n -> Sample\n -> Gradient\nbackpropogation act act' cost' !net@(Network !layers) (Sample !x !y) =\n Gradient (V.reverse $ V.cons nablaB_L nablaBs) (V.reverse $ V.cons nablaW_L nablaWs)\n where (z:zs, a:a':as) = computeZsAndAs act net x\n delta_L = cost' a y * cmap act' z\n nablaB_L = delta_L\n nablaW_L = asColumn delta_L <> asRow a'\n (nablaBs, nablaWs) =\n backpropogationBackwardsPass act' delta_L zs as (reverse $ tail layers)\n\n-- | Perform the backwards pass of the backpropogation algorithm.\n--\n-- Traverse the previously reverse z values, activations, and layers\n-- from layer L to 2. We thread the delta value along as state\nbackpropogationBackwardsPass :: ActivationFunctionDerivative\n -> Vector R -- ^ delta for the last layer.\n -> [Vector R] -- ^ zs in reverse order.\n -> [Vector R] -- ^ activations in reverse order.\n -> [Layer] -- ^ Layers L to 2.\n -> (V.Vector (Vector R), V.Vector (Matrix R)) -- ^\nbackpropogationBackwardsPass act' delta_L zs as layers = V.unzip output\n where !output = V.fromList $ evalState (mapM processLayer (zip3 layers zs as)) delta_L\n\n processLayer :: (Layer, Vector R, Vector R) -> State (Vector R) (Vector R, Matrix R)\n processLayer ((Layer _bias weights), z, a) = do\n delta <- get\n let actPrime = cmap act' z\n delta' = (tr weights #> delta) * actPrime\n put delta'\n pure (delta', delta' `outer` a)\n\n-- | Update the network's weights and biases by applying gradient\n-- descent for the given sample input.\ngradientDescentCore :: TrainingConfig -> V.Vector Sample -> Network -> Network\ngradientDescentCore (TrainingConfig eta act act' cost') !trainingData !net@(Network !layers) =\n Network layers'\n where sampleGradients :: V.Vector Gradient\n !sampleGradients = V.map (backpropogation act act' cost' net) trainingData\n\n Gradient !nablaB !nablaW = sumGradients sampleGradients\n\n !layers' = V.toList $ V.zipWith3 updateWeightsAndBiases (V.fromList layers) nablaB nablaW\n\n updateWeightsAndBiases :: Layer -> Vector R -> Matrix R -> Layer\n updateWeightsAndBiases (Layer b w) nb nw =\n Layer (b-(konst (eta/numSamples) (size b)) * nb)\n (w-(konst (eta/numSamples) (size w)) * nw)\n where numSamples = fromIntegral $ length trainingData\n\n\n-- | Train the neural network using stochastic gradient descent.\nsgd :: TrainingConfig\n -> Int -- ^ epochs\n -> Int -- ^ mini-batch size\n -> V.Vector Sample\n -> Network\n -> IO Network\nsgd trainingConfig !epochs !miniBatchSize !trainingData !network = trainEpoch 0 network\n where trainEpoch epoch !net\n | epoch == epochs = putStrLn \"done!\" >> pure net\n | otherwise = do\n !shuffledTrainingData <- evalRandIO $ vshuffle trainingData\n let miniBatches = miniBatchSize `vChunksOf` shuffledTrainingData\n !net' = foldl' (flip (gradientDescentCore trainingConfig)) net miniBatches\n putStrLn $ \"Completed epoch: \" ++ show epoch\n trainEpoch (epoch+1) net'\n\nvChunksOf :: Int -> V.Vector a -> [V.Vector a]\nvChunksOf n vec = Data.List.unfoldr makeChunk vec\n where makeChunk :: V.Vector a -> Maybe (V.Vector a, V.Vector a)\n makeChunk v | V.null v = Nothing\n | otherwise = Just $ V.splitAt n v\n", "meta": {"hexsha": "1839d5aca327e523677de6048f7ba6899d6fc688", "size": 6348, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ML/NN/Training.hs", "max_stars_repo_name": "m-renaud/ML", "max_stars_repo_head_hexsha": "7fb9fdac687cd76528d6b3d9080030a0723b01ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-05-15T16:13:43.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-15T16:13:43.000Z", "max_issues_repo_path": "src/ML/NN/Training.hs", "max_issues_repo_name": "m-renaud/ML", "max_issues_repo_head_hexsha": "7fb9fdac687cd76528d6b3d9080030a0723b01ca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ML/NN/Training.hs", "max_forks_repo_name": "m-renaud/ML", "max_forks_repo_head_hexsha": "7fb9fdac687cd76528d6b3d9080030a0723b01ca", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3916083916, "max_line_length": 117, "alphanum_fraction": 0.5942028986, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5545152703117567}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Foreign.BLAS.Level2\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Matrix-Vector operations.\n--\n\nmodule Foreign.BLAS.Level2 (\n BLAS2(..),\n ) where\n \nimport Data.Complex \nimport Foreign( Ptr, Storable, with )\n\nimport Foreign.BLAS.Types\nimport Foreign.BLAS.Level1\nimport Foreign.BLAS.Double\nimport Foreign.BLAS.Zomplex\n \n-- | Types with matrix-vector operations.\nclass (BLAS1 a) => BLAS2 a where\n gbmv :: Trans -> Int -> Int -> Int -> Int -> a -> Ptr a -> Int -> Ptr a -> Int -> a -> Ptr a -> Int -> IO ()\n gemv :: Trans -> Int -> Int -> a -> Ptr a -> Int -> Ptr a -> Int -> a -> Ptr a -> Int -> IO ()\n gerc :: Int -> Int -> a -> Ptr a -> Int -> Ptr a -> Int -> Ptr a -> Int -> IO ()\n geru :: Int -> Int -> a -> Ptr a -> Int -> Ptr a -> Int -> Ptr a -> Int -> IO ()\n\n hbmv :: Uplo -> Int -> Int -> a -> Ptr a -> Int -> Ptr a -> Int -> a -> Ptr a -> Int -> IO ()\n hemv :: Uplo -> Int -> a -> Ptr a -> Int -> Ptr a -> Int -> a -> Ptr a -> Int -> IO ()\n her :: Uplo -> Int -> Double -> Ptr a -> Int -> Ptr a -> Int -> IO ()\n her2 :: Uplo -> Int -> a -> Ptr a -> Int -> Ptr a -> Int -> Ptr a -> Int -> IO ()\n hpmv :: Uplo -> Int -> a -> Ptr a -> Ptr a -> Int -> a -> Ptr a -> Int -> IO () \n hpr :: Uplo -> Int -> Double -> Ptr a -> Int -> Ptr a -> IO ()\n hpr2 :: Uplo -> Int -> a -> Ptr a -> Int -> Ptr a -> Int -> Ptr a -> IO ()\n\n tbmv :: Uplo -> Trans -> Diag -> Int -> Int -> Ptr a -> Int -> Ptr a -> Int -> IO ()\n tbsv :: Uplo -> Trans -> Diag -> Int -> Int -> Ptr a -> Int -> Ptr a -> Int -> IO ()\n tpmv :: Uplo -> Trans -> Diag -> Int -> Ptr a -> Ptr a -> Int -> IO () \n tpsv :: Uplo -> Trans -> Diag -> Int -> Ptr a -> Ptr a -> Int -> IO () \n trmv :: Uplo -> Trans -> Diag -> Int -> Ptr a -> Int -> Ptr a -> Int -> IO ()\n trsv :: Uplo -> Trans -> Diag -> Int -> Ptr a -> Int -> Ptr a -> Int -> IO ()\n\n\nwithEnum :: (Enum a, Storable a) => Int -> (Ptr a -> IO b) -> IO b\nwithEnum = with . toEnum\n{-# INLINE withEnum #-}\n\ninstance BLAS2 Double where\n gemv transa m n alpha pa lda px incx beta py incy =\n withTrans transa $ \\ptransa ->\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n with beta $ \\pbeta ->\n withEnum incy $ \\pincy ->\n dgemv ptransa pm pn palpha pa plda px pincx pbeta py pincy\n {-# INLINE gemv #-}\n \n gbmv transa m n kl ku alpha pa lda px incx beta py incy =\n withTrans transa $ \\ptransa ->\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n withEnum kl $ \\pkl ->\n withEnum ku $ \\pku ->\n with alpha $ \\palpha ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n with beta $ \\pbeta ->\n withEnum incy $ \\pincy ->\n dgbmv ptransa pm pn pkl pku palpha pa plda px pincx pbeta py pincy\n {-# INLINE gbmv #-}\n\n trmv uplo trans diag n pa lda px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n dtrmv puplo ptrans pdiag pn pa plda px pincx\n {-# INLINE trmv #-}\n\n tpmv uplo trans diag n pap px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n dtpmv puplo ptrans pdiag pn pap px pincx\n {-# INLINE tpmv #-}\n\n tpsv uplo trans diag n pap px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n dtpsv puplo ptrans pdiag pn pap px pincx\n {-# INLINE tpsv #-}\n \n tbmv uplo trans diag n k pa lda px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum k $ \\pk ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n dtbmv puplo ptrans pdiag pn pk pa plda px pincx\n {-# INLINE tbmv #-}\n\n trsv uplo trans diag n pa lda px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n dtrsv puplo ptrans pdiag pn pa plda px pincx\n {-# INLINE trsv #-}\n\n tbsv uplo trans diag n k pa lda px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum k $ \\pk ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n dtbsv puplo ptrans pdiag pn pk pa plda px pincx\n {-# INLINE tbsv #-}\n\n hemv uplo n alpha pa lda px incx beta py incy =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n with beta $ \\pbeta ->\n withEnum incy $ \\pincy ->\n dsymv puplo pn palpha pa plda px pincx pbeta py pincy\n {-# INLINE hemv #-}\n\n hbmv uplo n k alpha pa lda px incx beta py incy =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n withEnum k $ \\pk ->\n with alpha $ \\palpha ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n with beta $ \\pbeta ->\n withEnum incy $ \\pincy ->\n dsbmv puplo pn pk palpha pa plda px pincx pbeta py pincy\n {-# INLINE hbmv #-}\n\n gerc m n alpha px incx py incy pa lda =\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n withEnum lda $ \\plda ->\n dger pm pn palpha px pincx py pincy pa plda\n {-# INLINE gerc #-}\n\n geru = gerc\n {-# INLINE geru #-}\n\n her uplo n alpha px incx pa lda =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n withEnum lda $ \\plda ->\n dsyr puplo pn palpha px pincx pa plda\n {-# INLINE her #-}\n\n her2 uplo n alpha px incx py incy pa lda =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n withEnum lda $ \\plda ->\n dsyr2 puplo pn palpha px pincx py pincy pa plda\n {-# INLINE her2 #-}\n\n hpmv uplo n alpha pap px incx beta py incy =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n with beta $ \\pbeta ->\n withEnum incy $ \\pincy ->\n dspmv puplo pn palpha pap px pincx pbeta py pincy\n {-# INLINE hpmv #-}\n\n hpr uplo n alpha px incx pap =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n dspr puplo pn palpha px pincx pap\n {-# INLINE hpr #-}\n\n hpr2 uplo n alpha px incx py incy pap =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n dspr2 puplo pn palpha px pincx py pincy pap\n {-# INLINE hpr2 #-}\n \n\ninstance BLAS2 (Complex Double) where\n gemv transa m n alpha pa lda px incx beta py incy =\n withTrans transa $ \\ptransa ->\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n with beta $ \\pbeta ->\n withEnum incy $ \\pincy ->\n zgemv ptransa pm pn palpha pa plda px pincx pbeta py pincy\n {-# INLINE gemv #-}\n \n gbmv transa m n kl ku alpha pa lda px incx beta py incy =\n withTrans transa $ \\ptransa ->\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n withEnum kl $ \\pkl ->\n withEnum ku $ \\pku ->\n with alpha $ \\palpha ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n with beta $ \\pbeta ->\n withEnum incy $ \\pincy ->\n zgbmv ptransa pm pn pkl pku palpha pa plda px pincx pbeta py pincy\n {-# INLINE gbmv #-}\n\n trmv uplo trans diag n pa lda px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n ztrmv puplo ptrans pdiag pn pa plda px pincx\n {-# INLINE trmv #-}\n\n tpmv uplo trans diag n pap px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n ztpmv puplo ptrans pdiag pn pap px pincx\n {-# INLINE tpmv #-}\n\n tpsv uplo trans diag n pap px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum incx $ \\pincx ->\n ztpsv puplo ptrans pdiag pn pap px pincx\n {-# INLINE tpsv #-}\n \n tbmv uplo trans diag n k pa lda px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum k $ \\pk ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n ztbmv puplo ptrans pdiag pn pk pa plda px pincx\n {-# INLINE tbmv #-}\n\n trsv uplo trans diag n pa lda px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n ztrsv puplo ptrans pdiag pn pa plda px pincx\n {-# INLINE trsv #-}\n\n tbsv uplo trans diag n k pa lda px incx =\n withUplo uplo $ \\puplo ->\n withTrans trans $ \\ptrans ->\n withDiag diag $ \\pdiag ->\n withEnum n $ \\pn ->\n withEnum k $ \\pk ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n ztbsv puplo ptrans pdiag pn pk pa plda px pincx\n {-# INLINE tbsv #-}\n\n hemv uplo n alpha pa lda px incx beta py incy =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n with beta $ \\pbeta ->\n withEnum incy $ \\pincy ->\n zhemv puplo pn palpha pa plda px pincx pbeta py pincy\n {-# INLINE hemv #-}\n\n hbmv uplo n k alpha pa lda px incx beta py incy =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n withEnum k $ \\pk ->\n with alpha $ \\palpha ->\n withEnum lda $ \\plda ->\n withEnum incx $ \\pincx ->\n with beta $ \\pbeta ->\n withEnum incy $ \\pincy ->\n zhbmv puplo pn pk palpha pa plda px pincx pbeta py pincy\n {-# INLINE hbmv #-}\n\n gerc m n alpha px incx py incy pa lda =\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n withEnum lda $ \\plda ->\n zgerc pm pn palpha px pincx py pincy pa plda\n {-# INLINE gerc #-}\n\n geru m n alpha px incx py incy pa lda =\n withEnum m $ \\pm ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n withEnum lda $ \\plda ->\n zgeru pm pn palpha px pincx py pincy pa plda\n {-# INLINE geru #-}\n\n her uplo n alpha px incx pa lda =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n withEnum lda $ \\plda ->\n zher puplo pn palpha px pincx pa plda\n {-# INLINE her #-}\n\n her2 uplo n alpha px incx py incy pa lda =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n withEnum lda $ \\plda ->\n zher2 puplo pn palpha px pincx py pincy pa plda\n {-# INLINE her2 #-}\n\n hpmv uplo n alpha pap px incx beta py incy =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n with beta $ \\pbeta ->\n withEnum incy $ \\pincy ->\n zhpmv puplo pn palpha pap px pincx pbeta py pincy\n {-# INLINE hpmv #-}\n\n hpr uplo n alpha px incx pap =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n zhpr puplo pn palpha px pincx pap\n {-# INLINE hpr #-}\n\n hpr2 uplo n alpha px incx py incy pap =\n withUplo uplo $ \\puplo ->\n withEnum n $ \\pn ->\n with alpha $ \\palpha ->\n withEnum incx $ \\pincx ->\n withEnum incy $ \\pincy ->\n zhpr2 puplo pn palpha px pincx py pincy pap\n {-# INLINE hpr2 #-}\n", "meta": {"hexsha": "1d70523ede5ecaeaf26da788b4dd1b9f820cf3ef", "size": 13419, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Foreign/BLAS/Level2.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Foreign/BLAS/Level2.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Foreign/BLAS/Level2.hs", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 33.8010075567, "max_line_length": 112, "alphanum_fraction": 0.5152395857, "num_tokens": 4091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5544398205851866}} {"text": "{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module : Statistics.Distribution.Hypergeometric\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- The Hypergeometric distribution. This is the discrete probability\n-- distribution that measures the probability of /k/ successes in /l/\n-- trials, without replacement, from a finite population.\n--\n-- The parameters of the distribution describe /k/ elements chosen\n-- from a population of /l/, with /m/ elements of one type, and\n-- /l/-/m/ of the other (all are positive integers).\n\nmodule Statistics.Distribution.Hypergeometric\n (\n HypergeometricDistribution\n -- * Constructors\n , hypergeometric\n -- ** Accessors\n , hdM\n , hdL\n , hdK\n ) where\n\nimport Data.Aeson (FromJSON, ToJSON)\nimport Data.Binary (Binary)\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.MathFunctions.Constants (m_epsilon)\nimport Numeric.SpecFunctions (choose)\nimport qualified Statistics.Distribution as D\nimport Data.Binary (put, get)\nimport Control.Applicative ((<$>), (<*>))\n\ndata HypergeometricDistribution = HD {\n hdM :: {-# UNPACK #-} !Int\n , hdL :: {-# UNPACK #-} !Int\n , hdK :: {-# UNPACK #-} !Int\n } deriving (Eq, Read, Show, Typeable, Data, Generic)\n\ninstance FromJSON HypergeometricDistribution\ninstance ToJSON HypergeometricDistribution\n\ninstance Binary HypergeometricDistribution where\n get = HD <$> get <*> get <*> get\n put (HD x y z) = put x >> put y >> put z\n\ninstance D.Distribution HypergeometricDistribution where\n cumulative = cumulative\n\ninstance D.DiscreteDistr HypergeometricDistribution where\n probability = probability\n\ninstance D.Mean HypergeometricDistribution where\n mean = mean\n\ninstance D.Variance HypergeometricDistribution where\n variance = variance\n\ninstance D.MaybeMean HypergeometricDistribution where\n maybeMean = Just . D.mean\n\ninstance D.MaybeVariance HypergeometricDistribution where\n maybeStdDev = Just . D.stdDev\n maybeVariance = Just . D.variance\n\ninstance D.Entropy HypergeometricDistribution where\n entropy = directEntropy\n\ninstance D.MaybeEntropy HypergeometricDistribution where\n maybeEntropy = Just . D.entropy\n\nvariance :: HypergeometricDistribution -> Double\nvariance (HD m l k) = (k' * ml) * (1 - ml) * (l' - k') / (l' - 1)\n where m' = fromIntegral m\n l' = fromIntegral l\n k' = fromIntegral k\n ml = m' / l'\n\nmean :: HypergeometricDistribution -> Double\nmean (HD m l k) = fromIntegral k * fromIntegral m / fromIntegral l\n\ndirectEntropy :: HypergeometricDistribution -> Double\ndirectEntropy d@(HD m _ _) =\n negate . sum $\n takeWhile (< negate m_epsilon) $\n dropWhile (not . (< negate m_epsilon)) $\n [ let x = probability d n in x * log x | n <- [0..m]]\n\n\nhypergeometric :: Int -- ^ /m/\n -> Int -- ^ /l/\n -> Int -- ^ /k/\n -> HypergeometricDistribution\nhypergeometric m l k\n | not (l > 0) = error $ msg ++ \"l must be positive\"\n | not (m >= 0 && m <= l) = error $ msg ++ \"m must lie in [0,l] range\"\n | not (k > 0 && k <= l) = error $ msg ++ \"k must lie in (0,l] range\"\n | otherwise = HD m l k\n where\n msg = \"Statistics.Distribution.Hypergeometric.hypergeometric: \"\n\n-- Naive implementation\nprobability :: HypergeometricDistribution -> Int -> Double\nprobability (HD mi li ki) n\n | n < max 0 (mi+ki-li) || n > min mi ki = 0\n | otherwise =\n choose mi n * choose (li - mi) (ki - n) / choose li ki\n\ncumulative :: HypergeometricDistribution -> Double -> Double\ncumulative d@(HD mi li ki) x\n | isNaN x = error \"Statistics.Distribution.Hypergeometric.cumulative: NaN argument\"\n | isInfinite x = if x > 0 then 1 else 0\n | n < minN = 0\n | n >= maxN = 1\n | otherwise = D.sumProbabilities d minN n\n where\n n = floor x\n minN = max 0 (mi+ki-li)\n maxN = min mi ki\n", "meta": {"hexsha": "8bc31e21066b2c006c3d2deca2575c6ac7215fe3", "size": 4019, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Hypergeometric.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "Statistics/Distribution/Hypergeometric.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Distribution/Hypergeometric.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8968253968, "max_line_length": 90, "alphanum_fraction": 0.6621050012, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5543118994687893}} {"text": "{-# LANGUAGE FlexibleContexts, RankNTypes #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults #-}\nmodule Main where\nimport Control.Monad.ST (runST)\nimport qualified Data.Vector.Unboxed as U\nimport Control.Monad (replicateM)\nimport System.Random.MWC\nimport Statistics.Distribution\nimport Statistics.Distribution.Uniform\nimport Statistics.Distribution.Normal\nimport Statistics.Distribution.Exponential\nimport Graphics.Rendering.Chart\nimport Graphics.Rendering.Chart.Easy\nimport Graphics.Rendering.Chart.Backend.Diagrams\nimport Data.Default.Class\nimport Control.Lens\n\nplotNumbers xs t = toRenderable $ do\n layout_title .= t\n plot $ fmap histToPlot $ liftEC $ do\n plot_hist_bins .= 15\n plot_hist_values .= xs\n plot_hist_norm_func .= const id\n\n\n-- lineare Kongruenzmethode:\ncreateRandom a b m = random\n where random x = let y = ((a * x) + b) `mod` m in (y:random y)\n\nmain = do\n putStrLn $ show $ take 100 $ createRandom 4 1 9 5\n\n -- erzeuge gleichverteilten Zufallszahlengenerator\n -- dieser Generator erzeugt immer die gleiche Folge an Zufallszahlen!\n -- Das ist hilfreich um reproduzierbare Simulationen zu haben\n -- Um unterschiedliche Zuffalszahlen, bei jedem Lauf zu erhalten,\n -- sollte create mit createSystemRandom ersetzt werden\n mwc <- create\n n_uniform <- replicateM 1000 $ genContVar (uniformDistr 0 5) mwc\n renderableToFile def \"histogramm_uniform.svg\" (plotNumbers n_uniform \"Standardverteilung mit a = 0 und b = 5\")\n n_exp <- replicateM 1000 $ genContVar (exponential 0.6) mwc\n renderableToFile def \"histogramm_exp.svg\" (plotNumbers n_exp \"Exponentialverteilung mit \u03bb = 0.6\")\n n_normal <- replicateM 1000 $ genContVar (normalDistr 0.9 1) mwc\n renderableToFile def \"histogramm_normal.svg\" (plotNumbers n_normal \"Gaussverteilung mit \u03bc = 0.9 und \u03c3 = 1\")\n\n\n", "meta": {"hexsha": "bbac99c1bdd52f67d1d5a6bf776fcf887c5608da", "size": 1861, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "simulation31/Main.hs", "max_stars_repo_name": "Zortaniac/simulation", "max_stars_repo_head_hexsha": "569b45fbaca75acc9af5fadbdcf613cee504244b", "max_stars_repo_licenses": ["CC0-1.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": "simulation31/Main.hs", "max_issues_repo_name": "Zortaniac/simulation", "max_issues_repo_head_hexsha": "569b45fbaca75acc9af5fadbdcf613cee504244b", "max_issues_repo_licenses": ["CC0-1.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": "simulation31/Main.hs", "max_forks_repo_name": "Zortaniac/simulation", "max_forks_repo_head_hexsha": "569b45fbaca75acc9af5fadbdcf613cee504244b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9795918367, "max_line_length": 114, "alphanum_fraction": 0.7533584095, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5542590218100681}} {"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeFamilies #-}\nmodule PCA.Distribution where\n\nimport Numeric.LinearAlgebra.Data (Vector, Matrix)\n\n\ndata family Distr m v\n\ndata instance Distr Double Double = Gamma Double Double\n\ndata instance\n Distr (Vector Double) (Vector Double) = MGamma (Vector Double)\n (Vector Double)\n\n\ndata instance\n Distr (Vector Double) (Matrix Double) = MNormal (Vector Double)\n (Matrix Double)\n\n\ndata instance\n Distr (Matrix Double) (Matrix Double) = MatrixMNormal (Matrix\n Double)\n (Matrix Double)\n\nclass Mean m v where\n mean :: Distr m v -> m\n\ninstance Mean Double Double where\n mean (Gamma s r) = s / r\n\ninstance Mean (Vector Double) (Vector Double) where\n mean (MGamma s r) = s / r\n\ninstance Mean (Vector Double) (Matrix Double) where\n mean (MNormal m v) = m\n\ninstance Mean (Matrix Double) (Matrix Double) where\n mean (MatrixMNormal m v) = m\n\n\nclass Variance m v where\n variance :: Distr m v -> v\n\ninstance Variance (Vector Double) (Matrix Double) where\n variance (MNormal m v) = v\ninstance Variance (Matrix Double) (Matrix Double) where\n variance (MatrixMNormal m v) = v\n", "meta": {"hexsha": "51eee6bb455abd3be9fa3b70b1414ac73f715cf1", "size": 1430, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PCA/Distribution.hs", "max_stars_repo_name": "DbIHbKA/vbpca", "max_stars_repo_head_hexsha": "e9c98743b6303436fbfcab360ac7a500183606bf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PCA/Distribution.hs", "max_issues_repo_name": "DbIHbKA/vbpca", "max_issues_repo_head_hexsha": "e9c98743b6303436fbfcab360ac7a500183606bf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PCA/Distribution.hs", "max_forks_repo_name": "DbIHbKA/vbpca", "max_forks_repo_head_hexsha": "e9c98743b6303436fbfcab360ac7a500183606bf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5, "max_line_length": 74, "alphanum_fraction": 0.5965034965, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5541719555998466}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TemplateHaskell #-}\nmodule Numeric.QuaterFloatTest (runTests) where\n\nimport Numeric.Arbitraries\nimport Numeric.Basics\nimport Numeric.Quaternion\nimport Numeric.Vector\nimport Test.QuickCheck\n\ntype T = Float\n\n-- | Some non-linear function are very unstable;\n-- it would be a downting task to determine the uncertainty precisely.\n-- Instead, I just make sure the tolerance is small enough to find at least\n-- the most obvious bugs.\n-- This function increases the tolerance by the span of magnitudes in q.\nqSpan :: Quater T -> T\nqSpan (Quater a b c d) = asSpan . foldl mm (1,1) $ map (\\x -> x*x) [a, b, c, d]\n where\n mm :: (T,T) -> T -> (T,T)\n mm (mi, ma) x\n | x > M_EPS = (min mi x, max ma x)\n | otherwise = (mi, ma)\n asSpan :: (T,T) -> T\n asSpan (mi, ma) = ma / mi\n\n\nprop_Eq :: Quater T -> Bool\nprop_Eq q = and\n [ q == q\n , Quater (takei q) (takej q) (takek q) (taker q) == q\n , fromVecNum (imVec q) (taker q) == q\n , im q + re q == q\n , fromVec4 (toVec4 q) == q\n ]\n\nprop_DoubleConjugate :: Quater T -> Property\nprop_DoubleConjugate q = property $ conjugate (conjugate q) == q\n\nprop_Square :: Quater T -> Property\nprop_Square q = q * conjugate q =~= realToFrac (square q)\n\nprop_RotScale :: Quater T -> Vector T 3 -> Property\nprop_RotScale q v = fromVecNum (rotScale q v) 0 =~= q * fromVecNum v 0 * conjugate q\n\nprop_GetRotScale :: Vector T 3 -> Vector T 3 -> Property\nprop_GetRotScale a b\n = normL2 a * ab > M_EPS * normL2 b\n ==> approxEq (recip ab) b (rotScale q a)\n where\n q = getRotScale a b\n -- when a and b are almost opposite, precision of getRotScale suffers a lot\n -- compensate it by increasing tolerance:\n ab = min 1 $ 1 + normalized a `dot` normalized b\n\n\nprop_InverseRotScale :: Quater T -> Vector T 3 -> Property\nprop_InverseRotScale q v\n = min (recip s) s > M_EPS ==> v =~= rotScale (1/q) (rotScale q v)\n where\n s = square q\n\nprop_NegateToMatrix33 :: Quater T -> Bool\nprop_NegateToMatrix33 q = toMatrix33 q == toMatrix33 (negate q)\n\nprop_NegateToMatrix44 :: Quater T -> Bool\nprop_NegateToMatrix44 q = toMatrix44 q == toMatrix44 (negate q)\n\nprop_FromToMatrix33 :: Quater T -> Property\nprop_FromToMatrix33 q\n = q /= 0 ==> fromMatrix33 (toMatrix33 q) =~= q\n .||. fromMatrix33 (toMatrix33 q) =~= negate q\n\nprop_FromToMatrix44 :: Quater T -> Property\nprop_FromToMatrix44 q\n = q /= 0 ==> fromMatrix44 (toMatrix44 q) =~= q\n .||. fromMatrix44 (toMatrix44 q) =~= negate q\n\n\nprop_RotationArg :: Quater T -> Property\nprop_RotationArg q | q == 0 = axisRotation (imVec q) (qArg q) =~= 1\n | otherwise = axisRotation (imVec q) (qArg q) =~= signum q\n\nprop_UnitQ :: Quater T -> Property\nprop_UnitQ q\n = square q > M_EPS ==> square (q / q) =~= 1\n\n\nprop_ExpLog :: Quater T -> Property\nprop_ExpLog q | square q < M_EPS = approxEq (qSpan q) q $ log (exp q)\n | otherwise = approxEq (qSpan q) q $ exp (log q)\n\nprop_SinAsin :: Quater T -> Property\nprop_SinAsin q = approxEq (qSpan q `max` qSpan q') q $ sin q'\n where\n q' = asin q\n\nprop_CosAcos :: Quater T -> Property\nprop_CosAcos q = approxEq (qSpan q `max` qSpan q') q $ cos q'\n where\n q' = acos q\n\nprop_TanAtan :: Quater T -> Property\nprop_TanAtan q = approxEq (qSpan q `max` qSpan q') q $ tan q'\n where\n q' = atan q\n\nprop_SinhAsinh :: Quater T -> Property\nprop_SinhAsinh q = approxEq (qSpan q `max` qSpan q') q $ sinh q'\n where\n q' = asinh q\n\nprop_CoshAcosh :: Quater T -> Property\nprop_CoshAcosh q = approxEq (qSpan q `max` qSpan q') q $ cosh q'\n where\n q' = acosh q\n\nprop_TanhAtanh :: Quater T -> Property\nprop_TanhAtanh q = approxEq (qSpan q `max` qSpan q') q $ tanh q'\n where\n q' = atanh q\n\nprop_SqrtSqr :: Quater T -> Property\nprop_SqrtSqr q = approxEq (qSpan q) q $ sqrt q * sqrt q\n\nprop_SinCos :: Quater T -> Property\nprop_SinCos q' = approxEq (qSpan s `max` qSpan c) 1 $ c * c + s * s\n where\n q = signum q' -- avoid exploding exponents\n s = sin q\n c = cos q\n\nprop_SinhCosh :: Quater T -> Property\nprop_SinhCosh q' = approxEq (qSpan s `max` qSpan c) 1 $ c * c - s * s\n where\n q = signum q' -- avoid exploding exponents\n s = sinh q\n c = cosh q\n\nprop_ReadShow :: Quater T -> Bool\nprop_ReadShow q = q == read (show q)\n\nreturn []\nrunTests :: Int -> IO Bool\nrunTests n = $forAllProperties\n $ quickCheckWithResult stdArgs { maxSuccess = n }\n", "meta": {"hexsha": "908f3b7eaeb3abc5a1406d86a6dc05a7c8d0e9fd", "size": 4487, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "easytensor/test/Numeric/QuaterFloatTest.hs", "max_stars_repo_name": "achirkin/fasttensor", "max_stars_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2017-06-30T04:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:46:17.000Z", "max_issues_repo_path": "easytensor/test/Numeric/QuaterFloatTest.hs", "max_issues_repo_name": "achirkin/fasttensor", "max_issues_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-07-17T18:20:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T06:31:42.000Z", "max_forks_repo_path": "easytensor/test/Numeric/QuaterFloatTest.hs", "max_forks_repo_name": "achirkin/fasttensor", "max_forks_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-08T20:44:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T22:08:04.000Z", "avg_line_length": 30.3175675676, "max_line_length": 84, "alphanum_fraction": 0.6329396033, "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5541555491663692}} {"text": "module Data.TestRational where\n\nimport Prelude hiding (Rational, gcd, negate, (*), (+), (-), (/), (^))\n\nimport Domains.Field\nimport Domains.Ring\n\nimport Data.Complex\nimport Data.Rational\n\nimport TestUtil\n\nfr :: Rational Int\nfr = Rational 1 2\n\nrun :: IO ()\nrun = do\n putStrLn (\"(1 / 2) = \" ++ show fr)\n", "meta": {"hexsha": "74dbef69ef2e7deab2713daa42e07377f97129f7", "size": 368, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Data/TestRational.hs", "max_stars_repo_name": "pmilne/algebra", "max_stars_repo_head_hexsha": "7cb00ec1f55b7f0e36fcec87cdb0d6272122992f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Data/TestRational.hs", "max_issues_repo_name": "pmilne/algebra", "max_issues_repo_head_hexsha": "7cb00ec1f55b7f0e36fcec87cdb0d6272122992f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Data/TestRational.hs", "max_forks_repo_name": "pmilne/algebra", "max_forks_repo_head_hexsha": "7cb00ec1f55b7f0e36fcec87cdb0d6272122992f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3684210526, "max_line_length": 86, "alphanum_fraction": 0.5380434783, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5540548930217866}} {"text": "module NeuralNet.LayerSpec (layerSpec) where\n\nimport Test.Hspec\nimport NeuralNet.Net\nimport NeuralNet.Activation\nimport NeuralNet.Example\nimport NeuralNet.Layer\nimport Control.Exception (evaluate)\nimport Numeric.LinearAlgebra\n\n\nlayerSpec :: SpecWith ()\nlayerSpec =\n describe \"NeuralNet.Layer\" $ do\n describe \"layerForward\" $ do\n it \"errors on wrong number of inputs\" $\n let\n nn = buildNNFromList (3, [LayerDefinition ReLU 1]) [1, 2, 3, 4]\n firstLayer = head (nnLayers nn)\n in evaluate (layerForward firstLayer [1]) `shouldThrow` anyErrorCall\n\n it \"calculates correctly for single output\" $\n let\n nn = buildNNFromList (3, [LayerDefinition ReLU 1]) [1, 2, 3, 4]\n firstLayer = head (nnLayers nn)\n in layerForward firstLayer [1, 1, 2] `shouldBe` [13.0]\n\n it \"calculates correctly for multiple output\" $\n let\n nn = buildNNFromList (3, [LayerDefinition ReLU 2]) [1, 4, 2, 5, 3, 6, 7, 8]\n firstLayer = head (nnLayers nn)\n in layerForward firstLayer [1, 1, 2] `shouldBe` [16.0, 28.0]\n\n it \"applies activation\" $\n let\n nn = buildNNFromList (3, [LayerDefinition Sigmoid 2]) [1, -1, -1, 1, 1, -1, 1, -1]\n firstLayer = head (nnLayers nn)\n in layerForward firstLayer [1, 1, 1] `shouldBe` [0.5, 0.5]\n\n describe \"layerForwardSet\" $ do\n it \"calculates correctly for multiple output\" $\n let\n nn = buildNNFromList (3, [LayerDefinition ReLU 2]) [1, 4, 2, 5, 3, 6, 7, 8]\n firstLayer = head (nnLayers nn)\n examples = exampleSetX (createExampleSet [([1, 1, 2], 0)])\n result = layerForwardSet firstLayer examples\n in forwardPropA result `shouldBe` fromLists [[16.0], [28.0]]\n\n it \"calculates correctly for multiple examples, multiple output\" $\n let\n nn = buildNNFromList (3, [LayerDefinition ReLU 2]) [1, 4, 2, 5, 3, 6, 7, 8]\n firstLayer = head (nnLayers nn)\n examples = exampleSetX (createExampleSet [([1, 1, 2], 0), ([1, 1, 0], 0)])\n result = layerForwardSet firstLayer examples\n in forwardPropA result `shouldBe` fromLists [[16, 12], [28, 16]]\n", "meta": {"hexsha": "8e115c3b84a5b65423f7d749504ee0b6d14f2b42", "size": 2189, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/NeuralNet/LayerSpec.hs", "max_stars_repo_name": "danielholmes/neural-net", "max_stars_repo_head_hexsha": "2088c858498fbc58ed326dc85bb370b814b0b6a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-02-18T22:55:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-20T09:23:24.000Z", "max_issues_repo_path": "test/NeuralNet/LayerSpec.hs", "max_issues_repo_name": "danielholmes/neural-net", "max_issues_repo_head_hexsha": "2088c858498fbc58ed326dc85bb370b814b0b6a6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/NeuralNet/LayerSpec.hs", "max_forks_repo_name": "danielholmes/neural-net", "max_forks_repo_head_hexsha": "2088c858498fbc58ed326dc85bb370b814b0b6a6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0892857143, "max_line_length": 92, "alphanum_fraction": 0.6212882595, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5536322039573922}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Audio.FFT.Inplace where\n\nimport Audio.Wav.Sample\nimport Conduit\nimport Control.Arrow ((>>>))\nimport qualified Control.Foldl as L\nimport Control.Monad (forM_, (<$!>))\nimport Control.Monad.Loops (iterateUntilM)\nimport Data.Bits (Bits (bit, shiftR))\nimport Data.Complex (Complex ((:+)), magnitude)\nimport Data.Conduit.Utils (chunkedVector)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Generic.Mutable as MG\nimport qualified Data.Vector.Unboxed.Mutable as MU\nimport Math.NumberTheory.Logarithms\nimport Streaming\nimport qualified Streaming as S\nimport qualified Streaming.Prelude as S\n\nfftC ::\n (Monad m, G.Vector v (Complex Double), G.Vector v Double) =>\n Int ->\n ConduitM Double (v Double) m ()\nfftC n = chunkedVector n .| mapC (G.map magnitude . simpleFFT . G.map (:+ 0))\n\nfftS ::\n (Monad m, G.Vector v (Complex Double), G.Vector v Double, PrimMonad m) =>\n Int ->\n Stream (Of Sample) m () ->\n Stream (Of (v Double)) m ()\n{-# INLINE fftS #-}\nfftS n =\n S.chunksOf n\n >>> S.mapped (L.impurely S.foldM L.vectorM)\n >>> S.map (G.map magnitude . simpleFFT . G.map (:+ 0))\n\nsimpleFFT :: G.Vector v (Complex Double) => v (Complex Double) -> v (Complex Double)\n{-# INLINEABLE simpleFFT #-}\nsimpleFFT = G.modify $ \\inps -> do\n reverseBitM inps\n let !theta = 2 * pi / fromIntegral (MG.length inps)\n go (cos theta) (sin theta) inps\n pure ()\n where\n {-# INLINE go #-}\n go !c !s inps\n | n <= 1 = pure ()\n | otherwise = do\n let half = n `div` 2\n (lh, uh) = MG.splitAt half inps\n !dblCos = 2 * c * c - 1\n !dblSin = 2 * s * c\n !w = c :+ s\n go dblCos dblSin lh\n go dblCos dblSin uh\n forM_ [0 .. half - 1] $ \\k -> do\n !ek <- MG.read lh k\n !ok <- MG.read uh k\n MG.write inps k $ ek + w ^ k * ok\n MG.write inps (half + k) $! ek + w ^ (half + k) * ok\n where\n !n = MG.length inps\n\nreverseBit :: (G.Vector v a) => v a -> v a\n{-# INLINE reverseBit #-}\nreverseBit = G.modify reverseBitM\n\nreverseBitM :: (MG.MVector v a, PrimMonad m) => v (PrimState m) a -> m ()\n{-# INLINEABLE reverseBitM #-}\nreverseBitM vec = do\n let !n = intLog2 $ MG.length vec\n !m = bit (n `shiftR` 1)\n table <- MU.replicate m 0\n MU.write table 0 0\n\n void $\n iterateUntilM\n (\\(!pk, !pl) -> pl + 1 >= pk)\n ( \\(!pk, !pl) -> do\n let !k = bit (pk - 1)\n !l = bit pl\n forM_ [0 .. l - 1] $ \\j ->\n MU.write table (l + j) . (+ k) =<< MU.read table j\n pure (pk - 1, pl + 1)\n )\n (n, 0)\n\n if even n\n then forM_ [1 .. m - 1] $ \\i -> forM_ [0 .. i - 1] $ \\j -> do\n !ji <- (j +) <$!> MU.read table i\n !ij <- (i +) <$!> MU.read table j\n MG.swap vec ji ij\n else forM_ [1 .. m - 1] $ \\i -> forM_ [0 .. i - 1] $ \\j -> do\n !ji <- (j +) <$!> MU.read table i\n !ij <- (i +) <$!> MU.read table j\n MG.swap vec ji ij\n MG.swap vec (ji + m) (ij + m)\n", "meta": {"hexsha": "3303b2256f7f26a6578ee0b5f40bb1d0c07aebfb", "size": 3042, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Audio/FFT/Inplace.hs", "max_stars_repo_name": "konn/genetic-twelve", "max_stars_repo_head_hexsha": "0949d60c8a1443b0e2dbc7a861a7c484a6d7b710", "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/Audio/FFT/Inplace.hs", "max_issues_repo_name": "konn/genetic-twelve", "max_issues_repo_head_hexsha": "0949d60c8a1443b0e2dbc7a861a7c484a6d7b710", "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/Audio/FFT/Inplace.hs", "max_forks_repo_name": "konn/genetic-twelve", "max_forks_repo_head_hexsha": "0949d60c8a1443b0e2dbc7a861a7c484a6d7b710", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1188118812, "max_line_length": 84, "alphanum_fraction": 0.5568704799, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5530870292915921}} {"text": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad.IO.Class (liftIO)\nimport Data.Complex (Complex ((:+)))\nimport Data.Functor.Classes (liftEq2)\nimport Foreign (Storable)\nimport Streamly.Internal.Data.Stream.IsStream (SerialT)\nimport Test.Hspec.Core.Spec (SpecM)\nimport Test.Hspec.QuickCheck (prop)\nimport Test.QuickCheck\n (elements, chooseInt, choose, forAll, Property, vectorOf)\nimport Test.QuickCheck.Monadic (monadicIO, assert)\n\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Set as Set\nimport qualified Data.Vector as V\nimport qualified Statistics.Sample.Powers as STAT\nimport qualified Statistics.Transform as STAT\nimport qualified Streamly.Internal.Data.Array.Foreign.Mut as MA\nimport qualified Streamly.Internal.Data.Array.Foreign.Type as Array\nimport qualified Streamly.Internal.Data.Fold as Fold\nimport qualified Streamly.Internal.Data.Ring.Foreign as Ring\nimport qualified Streamly.Internal.Data.Stream.IsStream as Stream\nimport qualified Streamly.Prelude as S\n\nimport Prelude hiding (sum, maximum, minimum)\n\nimport Streamly.Statistics\nimport Test.Hspec\n\ntolerance :: Double\ntolerance = 0.00001\n\nvalidate :: Double -> Bool\nvalidate delta = delta < tolerance\n\njackKnifeInput :: [Double]\njackKnifeInput = [1.0::Double, 2.0, 3.0, 4.0]\n\njackMeanRes :: [Double]\njackMeanRes = [3.0, 2.6666666666666665, 2.3333333333333335, 2.0]\n\njackVarianceRes :: [Double]\njackVarianceRes =\n [ 0.6666666666666661\n , 1.5555555555555554\n , 1.5555555555555545\n , 0.666666666666667\n ]\n\njackStdDevRes :: [Double]\njackStdDevRes =\n [ 0.8164965809277257\n , 1.247219128924647\n , 1.2472191289246466\n , 0.8164965809277263\n ]\n\ntestDistributions\n :: (STAT.Powers -> Double)\n -> Fold.Fold IO (Double, Maybe Double) Double\n -> Property\ntestDistributions func fld =\n forAll (chooseInt (1, 1000)) $ \\list_length ->\n forAll (vectorOf list_length (choose (-50.0 :: Double, 100.0)))\n $ \\ls ->\n monadicIO $ do\n let var2 = func . STAT.powers 2 $ V.fromList ls\n strm = S.fromList ls\n var1 <-\n liftIO $ S.fold (Ring.slidingWindow list_length fld) strm\n assert (validate $ abs (var1 - var2))\n\ntestVariance :: Property\ntestVariance = testDistributions STAT.variance variance\n\ntestStdDev :: Property\ntestStdDev = testDistributions STAT.stdDev stdDev\n\ntestFuncMD ::\n Fold.Fold IO ((Double, Maybe Double), IO (MA.Array Double)) Double -> Spec\ntestFuncMD f = do\n let c = S.fromList [10.0, 11.0, 12.0, 14.0]\n a1 <- runIO $ S.fold (Ring.slidingWindowWith 2 f) c\n a2 <- runIO $ S.fold (Ring.slidingWindowWith 3 f) c\n a3 <- runIO $ S.fold (Ring.slidingWindowWith 4 f) c\n it (\"MD should be 1.0 , 1.1111111111111114 , 1.25 but actual is \"\n ++ show a1 ++ \" \" ++ show a2 ++ \" \" ++ show a3)\n ( validate (abs (a1 - 1.0))\n && validate (abs (a2 - 1.1111111))\n && validate (abs (a3 - 1.25))\n )\n\ntestFuncKurt :: Spec\ntestFuncKurt = do\n let c = S.fromList\n [21.3 :: Double, 38.4, 12.7, 41.6]\n krt <- runIO $ S.fold (Ring.slidingWindow 4 kurtosis) c\n it ( \"kurtosis should be 1.2762447351370185 Actual is \" ++\n show krt\n )\n\n (validate $ abs (krt - 1.2762447))\n\ntestJackKnife :: (Show a, Eq a, Storable a) =>\n (Array.Array a -> SerialT (SpecM ()) a)\n -> [a]\n -> [a]\n -> Spec\ntestJackKnife f ls expRes = do\n let arr = Array.fromList ls\n res <- Stream.toList $ f arr\n it (\"testJackKnife result should be =\"\n ++ show expRes\n ++ \" Actual is = \" ++show res\n )\n (res == expRes)\n\ntestFuncHistogram :: Spec\ntestFuncHistogram = do\n let strm = S.fromList [1..15]\n res <- runIO $\n S.fold (histogram (binOffsetSize (0::Int) (3::Int))) strm\n let expected = Map.fromList\n [ (0::Int, 2::Int)\n , (1, 3)\n , (2, 3)\n , (3, 3)\n , (4, 3)\n , (5, 1)\n ]\n\n it (\"Map should be = \"\n ++ show expected\n ++ \" Actual is = \"\n ++ show res) (expected == res)\n\ntestFuncbinFromSizeN :: Int -> Int -> Int -> Int -> HistBin Int -> SpecWith (Arg Bool)\ntestFuncbinFromSizeN low binSize nbins x exp0 = do\n let res = binFromSizeN low binSize nbins x\n it (\"Bin should be = \"\n ++ show exp0\n ++ \" Actual is = \"\n ++ show res) (res == exp0)\n\ntestFuncbinFromToN :: Int -> Int -> Int -> Int -> HistBin Int -> SpecWith ()\ntestFuncbinFromToN low high n x exp0 = do\n let res = binFromToN low high n x\n it (\"Bin should be = \"\n ++ show exp0\n ++ \" Actual is = \"\n ++ show res) (res == exp0)\n\ntestFrequency :: [Int] -> Map.Map Int Int -> Spec\ntestFrequency inputList result = do\n freq <- S.fold frequency $ S.fromList inputList\n it (\"Frequency \" ++ show freq) $ liftEq2 (==) (==) freq result\n\ntestMode :: [Int] -> Maybe (Int, Int) -> Spec\ntestMode inputList res = do\n mode0 <- S.fold mode $ S.fromList inputList\n it (\"Mode \" ++ show mode0) $ mode0 == res\n\ntestFFT :: Property\ntestFFT = do\n let lengths = [2, 4, 8, 16]\n forAll (elements lengths) $ \\list_length ->\n forAll (vectorOf list_length (choose (-50.0 :: Double, 100.0)))\n $ \\ls ->\n monadicIO $ do\n let tc = map (\\x -> x :+ 0) ls\n let vr = V.toList (STAT.fft (V.fromList tc)\n :: V.Vector STAT.CD)\n marr <- MA.fromList tc\n fft marr\n res <- MA.toList marr\n assert (vr == res)\n\nsampleList :: [Double]\nsampleList = [1.0, 2.0, 3.0, 4.0, 5.0]\n\ntestResample :: [Double] -> Spec\ntestResample sample = do\n let sampleArr = Array.fromList sample\n sampleSet = Set.fromList sample\n resampleList <- runIO $ S.toList $ S.unfold resample sampleArr\n let resampleSet = Set.fromList resampleList\n sub = Set.isSubsetOf resampleSet sampleSet\n -- XXX We should not use dynamic output in test description\n it (\"resample \" ++ show resampleList)\n (Prelude.length resampleList == Array.length sampleArr && sub)\n\ntestFoldResamples :: Int -> [Double] -> Spec\ntestFoldResamples n sample = do\n let arr = Array.fromList sample\n a <- runIO $ S.toList $ foldResamples n arr Fold.mean\n -- XXX We should not use dynamic output in test description\n it (\"foldResamples \" ++ show a) (Prelude.length a == n)\n\nmain :: IO ()\nmain = hspec $ do\n describe \"Numerical stability while streaming\" $ do\n let numElem = 80000\n winSize = 800\n testCaseChunk = [9007199254740992, 1, 1.0 :: Double,\n 9007199254740992, 1, 1, 1, 9007199254740992]\n testCase = take numElem $ cycle testCaseChunk\n deviationLimit = 1\n testFunc f = do\n let c = S.fromList testCase\n a <- runIO $ S.fold (Ring.slidingWindow winSize f) c\n b <- runIO $ S.fold f $ S.drop (numElem - winSize)\n $ S.map (, Nothing) c\n let c1 = a - b\n it (\"should not deviate more than \" ++ show deviationLimit)\n $ c1 >= -1 * deviationLimit && c1 <= deviationLimit\n\n describe \"Sum\" $ testFunc sum\n describe \"mean\" $ testFunc mean\n describe \"welfordMean\" $ testFunc welfordMean\n\n describe \"Correctness\" $ do\n let winSize = 3\n testCase1 = [31, 41, 59, 26, 53, 58, 97] :: [Double]\n testCase2 = replicate 5 1.0 ++ [7.0]\n\n testFunc tc f sI sW = do\n let c = S.fromList tc\n a <- runIO $ S.toList $ S.postscan f $ S.map (, Nothing) c\n b <- runIO $ S.toList $ S.postscan\n (Ring.slidingWindow winSize f) c\n it \"Infinite\" $ a == sI\n it (\"Finite \" ++ show winSize) $ b == sW\n\n -- Resampling\n describe \"JackKnife Mean\" $\n testJackKnife jackKnifeMean jackKnifeInput jackMeanRes\n describe \"JackKnife Variance\" $ do\n testJackKnife jackKnifeVariance jackKnifeInput jackVarianceRes\n describe \"JackKnife StdDev\" $\n testJackKnife jackKnifeStdDev jackKnifeInput jackStdDevRes\n\n describe \"resample\" $ do\n testResample sampleList\n describe \"foldResamples 4\" $ do\n testFoldResamples 4 sampleList\n describe \"foldResamples 6\" $ do\n testFoldResamples 6 sampleList\n\n -- Spread/Mean\n describe \"MD\" $ testFuncMD md\n describe \"Kurt\" testFuncKurt\n prop \"fft\" testFFT\n describe \"minimum\" $ do\n let scanInf = [31, 31, 31, 26, 26, 26, 26] :: [Double]\n scanWin = [31, 31, 31, 26, 26, 26, 53] :: [Double]\n testFunc testCase1 minimum scanInf scanWin\n describe \"maximum\" $ do\n let scanInf = [31, 41, 59, 59, 59, 59, 97] :: [Double]\n scanWin = [31, 41, 59, 59, 59, 58, 97] :: [Double]\n testFunc testCase1 maximum scanInf scanWin\n describe \"range\" $ do\n let scanInf = [0, 10, 28, 33, 33, 33, 71] :: [Double]\n scanWin = [0, 10, 28, 33, 33, 32, 44] :: [Double]\n testFunc testCase1 range scanInf scanWin\n describe \"sum\" $ do\n let scanInf = [1, 2, 3, 4, 5, 12] :: [Double]\n scanWin = [1, 2, 3, 3, 3, 9] :: [Double]\n testFunc testCase2 sum scanInf scanWin\n describe \"mean\" $ do\n let scanInf = [1, 1, 1, 1, 1, 2] :: [Double]\n scanWin = [1, 1, 1, 1, 1, 3] :: [Double]\n testFunc testCase2 mean scanInf scanWin\n describe \"welfordMean\" $ do\n let scanInf = [1, 1, 1, 1, 1, 2] :: [Double]\n scanWin = [1, 1, 1, 1, 1, 3] :: [Double]\n testFunc testCase2 welfordMean scanInf scanWin\n\n -- Probability Distribution\n describe \"frequency\"\n $ testFrequency\n [1::Int, 1, 2, 3, 3, 3]\n (Map.fromList [(1, 2), (2, 1), (3, 3)])\n describe \"Mode\" $ testMode [1::Int, 1, 2, 3, 3, 3] (Just (3, 3))\n describe \"Mode Empty \" $ testMode ([]::[Int]) Nothing\n\n describe \"histogram\" testFuncHistogram\n describe \"binFromSizeN AboveRange\" $\n testFuncbinFromSizeN (0::Int) 2 10 55 AboveRange\n describe \"binFromSizeN BelowRange\" $\n testFuncbinFromSizeN (0::Int) 2 10 (-1) BelowRange\n describe \"binFromSizeN InRange\" $\n testFuncbinFromSizeN (0::Int) 2 10 19 (InRange 9)\n describe \"binFromSizeN AboveRange\" $\n testFuncbinFromSizeN (0::Int) 2 10 20 AboveRange\n describe \"binFromToN AboveRange\" $\n testFuncbinFromToN (0::Int) 49 10 55 AboveRange\n describe \"binFromToN BelowRange\" $\n testFuncbinFromToN (0::Int) 49 10 (-1) BelowRange\n describe \"binFromToN InRange\" $\n testFuncbinFromToN (0::Int) 49 10 19 (InRange 3)\n describe \"binFromToN AboveRange\" $\n testFuncbinFromToN (0::Int) 50 10 20 (InRange 4)\n prop \"variance\" testVariance\n prop \"stdDev\" testStdDev\n", "meta": {"hexsha": "e8d8f72568d9cab6776c5ff0f009999928e6c396", "size": 11354, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Main.hs", "max_stars_repo_name": "composewell/streamly-statistics", "max_stars_repo_head_hexsha": "e190e70e5317416ddc6019be02a99f69c0a434a7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-26T03:25:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T07:47:51.000Z", "max_issues_repo_path": "test/Main.hs", "max_issues_repo_name": "composewell/streamly-statistics", "max_issues_repo_head_hexsha": "e190e70e5317416ddc6019be02a99f69c0a434a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2021-12-25T02:24:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:42:34.000Z", "max_forks_repo_path": "test/Main.hs", "max_forks_repo_name": "composewell/streamly-statistics", "max_forks_repo_head_hexsha": "e190e70e5317416ddc6019be02a99f69c0a434a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1045751634, "max_line_length": 86, "alphanum_fraction": 0.5738946627, "num_tokens": 3339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5530672309263277}} {"text": "module Number where\nimport Data.Complex --Complex\nimport Data.Ratio --Rational\n\ndata LispNumber = Integer Integer -- Stores a Haskell Integer\n | Real Double | Rational Rational\n | Complex (Complex Double) deriving(Eq)\n\ninstance Show LispNumber where show = showNumber\n\ninstance Num LispNumber where\n (Integer a) + (Integer b) = Integer $ a + b\n (Integer a) + (Real b) = Real $ fromInteger a + b\n (Integer a) + (Rational b) = Rational $ fromInteger a + b\n (Integer a) + (Complex b) = Complex $ fromInteger a + b\n\n (Real a) + (Real b) = Real $ a + b\n (Real a) + (Integer b) = Real $ a + fromInteger b\n (Real a) + (Rational b) = Real $ a + fromRational b\n --(Real a) + (Complex b) = Complex $ \n\n (Rational a) + (Rational b) = Rational $ a + b\n (Complex a) + (Complex b) = Complex $ a + b\n\n (Integer a) - (Integer b) = Integer $ a - b\n (Integer a) - (Real b) = Real $ fromInteger a - b\n (Integer a) - (Rational b) = Rational $ fromInteger a - b\n (Integer a) - (Complex b) = Complex $ fromInteger a - b\n\n (Real a) - (Real b) = Real $ a - b\n (Rational a) - (Rational b) = Rational $ a - b\n (Complex a) - (Complex b) = Complex $ a - b\n\n (Integer a) * (Integer b) = Integer $ a * b\n (Real a) * (Real b) = Real $ a * b\n (Rational a) * (Rational b) = Rational $ a * b\n (Complex a) * (Complex b) = Complex $ a * b\n\n abs (Integer a) = Integer $ abs a\n abs (Real a) = Real $ abs a\n abs (Rational a) = Rational $ abs a\n abs (Complex a) = Complex $ abs a\n\n fromInteger = Integer\n\n signum (Integer a) = Integer $ signum a\n signum (Real a) = Real $ signum a\n signum (Rational a) = Rational $ signum a\n signum (Complex a) = Complex $ signum a\n\ninstance Fractional LispNumber where\n (Integer a) / (Integer b) = Rational $ a % b\n (Real a) / (Real b) = Real $ a / b\n (Complex a) / (Complex b) = Complex $ a / b\n (Rational a) / (Rational b) = Rational $ a / b\n\n fromRational = Rational\n\ninstance Ord LispNumber where\n compare (Integer a) (Integer b) = compare a b\n compare (Integer a) (Rational b) = compare (fromIntegral a) b\n compare (Integer a) (Real b) = compare (fromIntegral a) b\n compare (Integer a) (Complex b) = error \"Cant order complex numbers\"\n\n compare (Rational b) (Integer a)= compare b (fromIntegral a)\n compare (Real b) (Integer a)= compare b (fromIntegral a)\n compare (Complex b) (Integer a) = error \"Cant order complex numbers\"\n\n compare (Real a) (Real b) = compare a b\n compare (Rational a) (Rational b) = compare a b\n compare (Complex _) (Complex _) = error \"Cant order complex numbers\"\n\n\n\nshowNumber :: LispNumber -> String\nshowNumber (Integer a) = show a\nshowNumber (Complex a) = show a\nshowNumber (Rational a) = show (numerator a) ++ \"/\" ++ show (denominator a)\nshowNumber (Real a) = show a\n\n", "meta": {"hexsha": "d1b173c0a324c8486690207e48cd9ae6a37d902c", "size": 2825, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Number.hs", "max_stars_repo_name": "Unaimend/schemehs", "max_stars_repo_head_hexsha": "f4b38bc81f2ff8b0d62818b660577a5eee7d11ec", "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/Number.hs", "max_issues_repo_name": "Unaimend/schemehs", "max_issues_repo_head_hexsha": "f4b38bc81f2ff8b0d62818b660577a5eee7d11ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2020-02-06T13:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-14T09:50:19.000Z", "max_forks_repo_path": "src/Number.hs", "max_forks_repo_name": "Unaimend/schemehs", "max_forks_repo_head_hexsha": "f4b38bc81f2ff8b0d62818b660577a5eee7d11ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8765432099, "max_line_length": 75, "alphanum_fraction": 0.6194690265, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5529169814805213}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n\n-- |\n-- Module : Spiral.Exp\n-- Copyright : (c) 2016-2017 Drexel University\n-- License : BSD-style\n-- Maintainer : mainland@drexel.edu\n\nmodule Spiral.Exp (\n Var(..),\n Const(..),\n Exp(..),\n Unop(..),\n Binop(..),\n BBinop(..),\n\n Type(..),\n Typed(..),\n\n ToConst(..),\n RealFloatConst,\n fromConst,\n fromComplex,\n lower,\n\n LiftNum(..),\n LiftFloating(..),\n\n IfThenElse(..),\n IsEq(..),\n IsOrd(..),\n\n intE,\n complexE,\n unComplexE,\n forceUnComplexE,\n\n isConstE,\n\n IsZeroOne(..),\n isI,\n isNegI,\n\n true,\n false\n ) where\n\nimport Data.Complex\nimport Data.Complex.Cyclotomic\nimport Data.Modular\nimport Data.Modular.Instances ()\nimport Data.Monoid ((<>))\nimport Data.Proxy (Proxy(..))\nimport Data.Ratio\nimport Data.String\nimport Data.Symbol\nimport GHC.TypeLits (KnownNat,\n natVal)\nimport Language.C.Quote (ToIdent(..))\nimport Test.QuickCheck (Arbitrary(..))\nimport Text.PrettyPrint.Mainland\nimport Text.PrettyPrint.Mainland.Class\n\nimport Data.Heterogeneous\nimport Spiral.Globals\nimport Spiral.RootOfUnity\nimport Spiral.Util.Name\nimport Spiral.Util.Pretty\nimport Spiral.Util.Uniq\n\nnewtype Var = Var Name\n deriving (Eq, Ord, Show, IsString, ToIdent, Pretty, Named)\n\ninstance Gensym Var where\n gensymAt s _ = do\n u <- newUnique\n return $ Var $ Name (intern s) (Just u)\n\n uniquify (Var (Name sym _)) = do\n u <- newUnique\n return $ Var $ Name sym (Just u)\n\n-- | Representation of scalar expressions.\ndata Const a where\n BoolC :: Bool -> Const Bool\n IntC :: Int -> Const Int\n IntegerC :: Integer -> Const Integer\n FloatC :: Float -> Const Float\n DoubleC :: Double -> Const Double\n RationalC :: FractionalConst a => Rational -> Const a\n ComplexC :: RealFloatConst a => Const a -> Const a -> Const (Complex a)\n\n -- | Constant multiple of root of unity tagged with n and k.\n W :: RootOfUnity (Const a) => !Int -> !Int -> Const a -> Const a\n\n -- | Cyclotomic numbers\n CycC :: RealFloatConst a => Cyclotomic -> Const (Complex a)\n\n -- | Multiple of $\\pi$\n PiC :: (Floating a, ToConst a) => Rational -> Const a\n\n -- | Integers modulo a prime\n ModularC :: KnownNat p => \u2124/p -> Const (\u2124/p)\n\nderiving instance Show (Const a)\n\ninstance Eq (Const a) where\n (==) = heq\n (/=) = hne\n\ninstance Ord (Const a) where\n compare = hcompare\n\nclass (Eq a, Pretty a) => ToConst a where\n toConst :: a -> Const a\n\ninstance ToConst Bool where\n toConst = BoolC\n\ninstance ToConst Int where\n toConst = IntC\n\ninstance ToConst Integer where\n toConst = IntegerC\n\ninstance ToConst Float where\n toConst x | isIntegral x = RationalC (fromIntegral (truncate x :: Int))\n | otherwise = FloatC x\n\ninstance ToConst Double where\n toConst x | isIntegral x = RationalC (fromIntegral (truncate x :: Int))\n | otherwise = DoubleC x\n\ninstance ToConst Rational where\n toConst = RationalC\n\ninstance RealFloatConst a => ToConst (Complex a) where\n toConst (r :+ i) = ComplexC (toConst r) (toConst i)\n\ninstance KnownNat p => ToConst (\u2124/p) where\n toConst = ModularC\n\nclass ( Fractional a\n , Typed a\n , ToConst a\n ) => FractionalConst a where\n\ninstance FractionalConst Rational where\n\ninstance FractionalConst Float where\n\ninstance FractionalConst Double where\n\ninstance FractionalConst (Complex Float) where\n\ninstance FractionalConst (Complex Double) where\n\nclass ( Eq a\n , RealFloat a\n , Pretty a\n , FractionalConst a\n , Floating (Const a)\n , Floating (Exp a)\n , Floating (Exp (Complex a))\n ) => RealFloatConst a where\n\ninstance RealFloatConst Float where\n\ninstance RealFloatConst Double where\n\n-- | Convert a 'Const a' to the value of type 'a' that it represents.\nfromConst :: Const a -> a\nfromConst (BoolC x) = x\nfromConst (IntC x) = x\nfromConst (IntegerC x) = x\nfromConst (FloatC x) = x\nfromConst (DoubleC x) = x\nfromConst (RationalC x) = fromRational x\nfromConst (ComplexC r i) = fromConst r :+ fromConst i\nfromConst (W _ _ x) = fromConst x\nfromConst (CycC x) = toComplex x\nfromConst (PiC x) = pi*fromRational x\nfromConst (ModularC x) = x\n\nlift :: ToConst a => (a -> a) -> Const a -> Const a\nlift f (IntC x) = IntC (f x)\nlift f (IntegerC x) = IntegerC (f x)\nlift f (FloatC x) = FloatC (f x)\nlift f (DoubleC x) = DoubleC (f x)\nlift f x@RationalC{} = toConst (f (fromConst x))\nlift f x@ComplexC{} = toConst (f (fromConst x))\nlift f x = lift f (lower x)\n\nlift2 :: ToConst a => (a -> a -> a) -> Const a -> Const a -> Const a\nlift2 f (IntC x) (IntC y) = IntC (f x y)\nlift2 f (IntegerC x) (IntegerC y) = IntegerC (f x y)\nlift2 f (FloatC x) (FloatC y) = FloatC (f x y)\nlift2 f (DoubleC x) (DoubleC y) = DoubleC (f x y)\nlift2 f x@RationalC{} y@RationalC{} = toConst (f (fromConst x) (fromConst y))\nlift2 f x@ComplexC{} y@ComplexC{} = toConst (f (fromConst x) (fromConst y))\nlift2 f x y = lift2 f (lower x) (lower y)\n\ninstance Arbitrary (Const Int) where\n arbitrary = IntC <$> arbitrary\n\ninstance Arbitrary (Const Integer) where\n arbitrary = IntegerC <$> arbitrary\n\ninstance Arbitrary (Const Double) where\n arbitrary = DoubleC <$> arbitrary\n\ninstance Arbitrary (Const Float) where\n arbitrary = FloatC <$> arbitrary\n\ninstance Arbitrary (Const Rational) where\n arbitrary = RationalC <$> arbitrary\n\ninstance Arbitrary (Const (Complex Double)) where\n arbitrary = ComplexC <$> arbitrary <*> arbitrary\n\ninstance KnownNat p => Arbitrary (Const (\u2124/p)) where\n arbitrary = ModularC . toMod <$> arbitrary\n\ninstance Pretty (Const a) where\n pprPrec _ (BoolC x) = if x then text \"true\" else text \"false\"\n pprPrec _ (IntC x) = ppr x\n pprPrec _ (IntegerC x) = ppr x\n pprPrec _ (FloatC x) = ppr x <> char 'f'\n pprPrec _ (DoubleC x) = ppr x\n pprPrec p (RationalC x)\n | denominator x == 1 = ppr (numerator x)\n | otherwise = infixop p FDiv (numerator x) (denominator x)\n\n pprPrec p x@ComplexC{} = pprComplex p (fromConst x)\n\n pprPrec _ (W _ 0 _) = text \"1\"\n pprPrec _ (W n 1 _) = text \"\u03c9_\" <> ppr n\n pprPrec _ (W n k _) = text \"\u03c9_\" <> ppr n <> char '^' <> ppr k\n\n pprPrec p (CycC x) = text (showsPrec p x \"\")\n\n pprPrec p (PiC x) = parensIf (p > mulPrec) $\n pprPrec mulPrec1 x <> char '*' <> text \"pi\"\n\n pprPrec p (ModularC x) = pprPrec p x\n\ninstance RootOfUnity (Const (Complex Float)) where\n rootOfUnity n k = mkW (k%n) (CycC (rootOfUnity n k))\n\ninstance RootOfUnity (Const (Complex Double)) where\n rootOfUnity n k = mkW (k%n) (CycC (rootOfUnity n k))\n\ninstance KnownNat p => RootOfUnity (Const (\u2124/p)) where\n rootOfUnity n k = ModularC (rootOfUnity n k)\n\npprComplex :: (Eq a, Num a, Pretty a) => Int -> Complex a -> Doc\npprComplex p (r :+ 0) = pprPrec p r\npprComplex _ (0 :+ 1) = char 'i'\npprComplex _ (0 :+ (-1)) = text \"-i\"\npprComplex _ (0 :+ i) = pprPrec mulPrec i <> char 'i'\npprComplex p (r :+ i) = parensIf (p > addPrec) $\n pprPrec addPrec r <+> text \"+\" <+> pprPrec mulPrec i <> char 'i'\n\n-- | Convert a 'Complex Double' to a 'Const (Complex Double)'\nfromComplex :: RealFloatConst a => Complex a -> Const (Complex a)\nfromComplex (r :+ i) = ComplexC (toConst r) (toConst i)\n\n-- | Convert a constant into the most general value that can be used for exact\n-- comparison.\nexact :: forall m a . Monad m => Const a -> m (Const a)\nexact x@BoolC{} = return x\nexact x@IntC{} = return x\nexact x@IntegerC{} = return x\nexact x@FloatC{} = return x\nexact x@DoubleC{} = return x\n\nexact x@(RationalC r) =\n case tau of\n FloatT -> return $ FloatC $ fromConst x\n DoubleT -> return $ DoubleC $ fromConst x\n RationalT -> return x\n ComplexT{} -> return $ CycC $ fromRational r\n _ -> fail \"Cannot represent exactly\"\n where\n tau :: Type a\n tau = typeOf (undefined :: a)\n\nexact (ComplexC cre cim) | isIntegral re && isIntegral im =\n return $ CycC $ gaussianRat (fromIntegral (round re :: Integer)) (fromIntegral (round im :: Integer))\n where\n re, im :: a ~ Complex b => b\n re = fromConst cre\n im = fromConst cim\n\nexact (W _ _ x) = exact x\nexact x@CycC{} = return x\nexact x@ModularC{} = return x\nexact _ = fail \"Cannot represent exactly\"\n\nisIntegral :: RealFrac a => a -> Bool\nisIntegral x = x == fromInteger (round x)\n\n-- | Lower a constant's representation from a specialized representation to a\n-- standard representation. This ensures the constant is not constructed with\n-- the 'W' or 'CycC' data constructors.\nlower :: forall a . Const a -> Const a\nlower x@(RationalC r) =\n case tau of\n FloatT -> FloatC $ fromConst x\n DoubleT -> DoubleC $ fromConst x\n ComplexT{} -> lower $ ComplexC (RationalC r) 0\n _ -> x\n where\n tau :: Type a\n tau = typeOf (undefined :: a)\n\nlower (ComplexC r i) = ComplexC (lower r) (lower i)\nlower (W _ _ x) = lower x\nlower x@CycC{} = toConst (fromConst x)\nlower x@PiC{} = toConst (fromConst x)\nlower e = e\n\n-- | Representation of scalar constants.\ndata Exp a where\n ConstE :: Const a -> Exp a\n VarE :: Var -> Exp a\n UnopE :: Unop -> Exp a -> Exp a\n BinopE :: Num (Exp a) => Binop -> Exp a -> Exp a -> Exp a\n IdxE :: Var -> [Exp Int] -> Exp a\n\n ComplexE :: (Typed a, Num (Exp a)) => Exp a -> Exp a -> Exp (Complex a)\n ReE :: RealFloatConst a => Exp (Complex a) -> Exp a\n ImE :: RealFloatConst a => Exp (Complex a) -> Exp a\n\n BBinopE :: (Typed a, ToConst a) => BBinop -> Exp a -> Exp a -> Exp Bool\n IfE :: Exp Bool -> Exp a -> Exp a -> Exp a\n\nderiving instance Show (Exp a)\n\ninstance Eq (Exp a) where\n (==) = heq\n (/=) = hne\n\ninstance Ord (Exp a) where\n compare = hcompare\n\ninstance IsString (Exp a) where\n fromString s = VarE (fromString s)\n\ninstance RootOfUnity (Exp (Complex Float)) where\n rootOfUnity n k = ConstE (rootOfUnity n k)\n\ninstance RootOfUnity (Exp (Complex Double)) where\n rootOfUnity n k = ConstE (rootOfUnity n k)\n\ninstance KnownNat p => RootOfUnity (Exp (\u2124/p)) where\n rootOfUnity n k = ConstE (rootOfUnity n k)\n\n--\n-- Heterogeneous quality and comparison\n--\n\nmodPair :: forall p . KnownNat p => \u2124/p -> (Integer, Integer)\nmodPair x = (unMod x, natVal (Proxy :: Proxy p))\n\ninstance HEq Const where\n heq x y =\n case (exact x, exact y) of\n (Just x', Just y') -> go x' y'\n _ -> go (lower x) (lower y)\n where\n go :: Const a -> Const b -> Bool\n go (BoolC x) (BoolC y) = x == y\n go (IntC x) (IntC y) = x == y\n go (IntegerC x) (IntegerC y) = x == y\n go (FloatC x) (FloatC y) = x == y\n go (DoubleC x) (DoubleC y) = x == y\n go (RationalC x) (RationalC y) = x == y\n go (ComplexC r1 i1) (ComplexC r2 i2) = (Some r1, Some i1) == (Some r2, Some i2)\n go (CycC x) (CycC y) = x == y\n go (ModularC x) (ModularC y) = modPair x == modPair y\n go _ _ = False\n\ninstance HEq Exp where\n heq (ConstE c1) (ConstE c2) = heq c1 c2\n heq (VarE x) (VarE y) = x == y\n heq (UnopE op1 e1) (UnopE op2 e2) = (op1, Some e1) == (op2, Some e2)\n heq (BinopE op1 e1a e1b) (BinopE op2 e2a e2b) = (op1, Some e1a, Some e1b) == (op2, Some e2a, Some e2b)\n heq (IdxE v1 es1) (IdxE v2 es2) = (v1, es1) == (v2, es2)\n heq (ComplexE r1 i1) (ComplexE r2 i2) = (Some r1, Some i1) == (Some r2, Some i2)\n heq (ReE e1) (ReE e2) = heq e1 e2\n heq (ImE e1) (ImE e2) = heq e1 e2\n heq (BBinopE op1 e1a e1b) (BBinopE op2 e2a e2b) = (op1, Some e1a, Some e1b) == (op2, Some e2a, Some e2b)\n heq (IfE e1a e1b e1c) (IfE e2a e2b e2c) = (Some e1a, Some e1b, Some e1c) == (Some e2a, Some e2b, Some e2c)\n heq _ _ = False\n\ninstance HOrd Const where\n hcompare x y =\n case (exact x, exact y) of\n (Just x', Just y') -> go x' y'\n _ -> go (lower x) (lower y)\n where\n go :: Const a -> Const b -> Ordering\n go (BoolC x) (BoolC y) = compare x y\n go (IntC x) (IntC y) = compare x y\n go (IntegerC x) (IntegerC y) = compare x y\n go (FloatC x) (FloatC y) = compare x y\n go (DoubleC x) (DoubleC y) = compare x y\n go (RationalC x) (RationalC y) = compare x y\n go (ComplexC r1 i1) (ComplexC r2 i2) = compare (Some r1, Some i1) (Some r2, Some i2)\n go (CycC x) (CycC y) = compare (xr, xi) (yr, yi)\n where\n xr :+ xi = fromConst (CycC x :: Const (Complex Double))\n yr :+ yi = fromConst (CycC y :: Const (Complex Double))\n go (ModularC x) (ModularC y) = compare (modPair x) (modPair y)\n\n go x y = compare (tag x) (tag y)\n where\n tag :: Const a -> Int\n tag BoolC{} = 0\n tag IntC{} = 1\n tag IntegerC{} = 2\n tag FloatC{} = 3\n tag DoubleC{} = 4\n tag RationalC{} = 5\n tag ComplexC{} = 6\n tag W{} = 7\n tag CycC{} = 8\n tag PiC{} = 9\n tag ModularC{} = 10\n\ninstance HOrd Exp where\n hcompare (ConstE c1) (ConstE c2) = hcompare c1 c2\n hcompare (VarE x) (VarE y) = compare x y\n hcompare (UnopE op1 e1) (UnopE op2 e2) = compare (op1, Some e1)(op2, Some e2)\n hcompare (BinopE op1 e1a e1b) (BinopE op2 e2a e2b) = compare (op1, Some e1a, Some e1b) (op2, Some e2a, Some e2b)\n hcompare (IdxE v1 es1) (IdxE v2 es2) = compare (v1, es1) (v2, es2)\n hcompare (ComplexE r1 i1) (ComplexE r2 i2) = compare (Some r1, Some i1) (Some r2, Some i2)\n hcompare (ReE e1) (ReE e2) = hcompare e1 e2\n hcompare (ImE e1) (ImE e2) = hcompare e1 e2\n hcompare (BBinopE op1 e1a e1b) (BBinopE op2 e2a e2b) = compare (op1, Some e1a, Some e1b) (op2, Some e2a, Some e2b)\n hcompare (IfE e1a e1b e1c) (IfE e2a e2b e2c) = compare (Some e1a, Some e1b, Some e1c) (Some e2a, Some e2b, Some e2c)\n hcompare e1 e2 = compare (tag e1) (tag e2)\n where\n tag :: Exp a -> Int\n tag ConstE{} = 0\n tag VarE{} = 1\n tag UnopE{} = 2\n tag BinopE{} = 3\n tag IdxE{} = 4\n tag ComplexE{} = 5\n tag ReE{} = 6\n tag ImE{} = 7\n tag BBinopE{} = 8\n tag IfE{} = 9\n\n-- | Unary operators\ndata Unop = Neg\n | Abs\n | Signum\n | Exp\n | Log\n | Sqrt\n | Sin\n | Cos\n | Asin\n | Acos\n | Atan\n | Sinh\n | Cosh\n | Asinh\n | Acosh\n | Atanh\n deriving (Eq, Ord, Show)\n\n-- | Binary operators\ndata Binop = Add\n | Sub\n | Mul\n | Quot\n | Rem\n | Div\n | Mod\n | FDiv\n deriving (Eq, Ord, Show, Enum)\n\n-- | Boolean binary operators\ndata BBinop = Eq\n | Ne\n | Lt\n | Le\n | Ge\n | Gt\n deriving (Eq, Ord, Show, Enum)\n\ninstance HasFixity Unop where\n fixity Neg = infixr_ 10\n fixity Abs = infixr_ 10\n fixity Signum = infixr_ 10\n fixity Exp = infixr_ 10\n fixity Log = infixr_ 10\n fixity Sqrt = infixr_ 10\n fixity Sin = infixr_ 10\n fixity Cos = infixr_ 10\n fixity Asin = infixr_ 10\n fixity Acos = infixr_ 10\n fixity Atan = infixr_ 10\n fixity Sinh = infixr_ 10\n fixity Cosh = infixr_ 10\n fixity Asinh = infixr_ 10\n fixity Acosh = infixr_ 10\n fixity Atanh = infixr_ 10\n\ninstance HasFixity Binop where\n fixity Add = infixl_ 8\n fixity Sub = infixl_ 8\n fixity Mul = infixl_ 9\n fixity Quot = infixl_ 9\n fixity Rem = infixl_ 9\n fixity Div = infixl_ 9\n fixity Mod = infixl_ 9\n fixity FDiv = infixl_ 9\n\ninstance HasFixity BBinop where\n fixity Eq = infix_ 4\n fixity Ne = infix_ 4\n fixity Lt = infix_ 4\n fixity Le = infix_ 4\n fixity Ge = infix_ 4\n fixity Gt = infix_ 4\n\ninstance Pretty Unop where\n ppr Neg = text \"-\"\n ppr Abs = text \"abs\" <> space\n ppr Signum = text \"signum\" <> space\n ppr Exp = text \"exp\" <> space\n ppr Log = text \"log\" <> space\n ppr Sqrt = text \"sqrt\" <> space\n ppr Sin = text \"sin\" <> space\n ppr Cos = text \"cos\" <> space\n ppr Asin = text \"asin\" <> space\n ppr Acos = text \"acos\" <> space\n ppr Atan = text \"atan\" <> space\n ppr Sinh = text \"sinh\" <> space\n ppr Cosh = text \"cosh\" <> space\n ppr Asinh = text \"asinh\" <> space\n ppr Acosh = text \"acosh\" <> space\n ppr Atanh = text \"atanh\" <> space\n\ninstance Pretty Binop where\n ppr Add = text \"+\"\n ppr Sub = text \"-\"\n ppr Mul = text \"*\"\n ppr Quot = text \"`quot`\"\n ppr Rem = text \"`rem`\"\n ppr Div = text \"`div`\"\n ppr Mod = text \"`mod`\"\n ppr FDiv = text \"/\"\n\ninstance Pretty BBinop where\n ppr Eq = text \"==\"\n ppr Ne = text \"/=\"\n ppr Lt = text \"<\"\n ppr Le = text \"<=\"\n ppr Ge = text \">=\"\n ppr Gt = text \">\"\n\ninstance Pretty (Exp a) where\n pprPrec p (ConstE c) = pprPrec p c\n pprPrec p (VarE v) = pprPrec p v\n\n pprPrec p (UnopE op e) =\n unop p op e\n\n pprPrec p (BinopE op e1 e2) =\n infixop p op e1 e2\n\n pprPrec _ (IdxE ev eis) =\n ppr ev <> mconcat [brackets (ppr ei) | ei <- eis]\n\n pprPrec p (ComplexE er ei) =\n pprComplex p (er :+ ei)\n\n pprPrec _ (ReE e) =\n text \"re\" <> parens (ppr e)\n\n pprPrec _ (ImE e) =\n text \"im\" <> parens (ppr e)\n\n pprPrec p (BBinopE op e1 e2) =\n infixop p op e1 e2\n\n pprPrec _ (IfE e1 e2 e3) =\n text \"if\" <+> ppr e1 <+>\n text \"then\" <+> ppr e2 <+>\n text \"else\" <+> ppr e3\n\n-- | Representation of types.\ndata Type a where\n BoolT :: Type Bool\n IntT :: Type Int\n IntegerT :: Type Integer\n FloatT :: Type Float\n DoubleT :: Type Double\n RationalT :: Type Rational\n ComplexT :: RealFloatConst a => Type a -> Type (Complex a)\n ModPT :: KnownNat p => Integer -> Type (\u2124/p)\n\nderiving instance Eq (Type a)\nderiving instance Show (Type a)\n\ninstance Pretty (Type a) where\n ppr BoolT = text \"bool\"\n ppr IntT = text \"int\"\n ppr IntegerT = text \"integer\"\n ppr FloatT = text \"float\"\n ppr DoubleT = text \"double\"\n ppr RationalT = text \"rational\"\n ppr (ComplexT tau) = text \"complex\" <+> ppr tau\n ppr (ModPT p) = text \"\u2124/\" <> ppr p\n\nclass Typed a where\n typeOf :: a -> Type a\n\ninstance Typed Bool where\n typeOf _ = BoolT\n\ninstance Typed Int where\n typeOf _ = IntT\n\ninstance Typed Integer where\n typeOf _ = IntegerT\n\ninstance Typed Float where\n typeOf _ = FloatT\n\ninstance Typed Double where\n typeOf _ = DoubleT\n\ninstance Typed Rational where\n typeOf _ = RationalT\n\ninstance RealFloatConst a => Typed (Complex a) where\n typeOf _ = ComplexT (typeOf (undefined :: a))\n\ninstance KnownNat p => Typed (\u2124/p) where\n typeOf _ = ModPT (natVal (Proxy :: Proxy p))\n\n--------------------------------------------------------------------------------\n--\n-- Num instances\n--\n--------------------------------------------------------------------------------\n\n-- | Class to lift 'Num' operators.\nclass LiftNum b where\n -- | Lift a unary operation on 'Num' to the type 'b'\n liftNum :: Unop -> (forall a . Num a => a -> a) -> b -> b\n\n -- | Lift a binary operation on 'Num' to the type 'b\n liftNum2 :: Binop -> (forall a . Num a => a -> a -> a) -> b -> b -> b\n\ninstance (Typed a, Num a, ToConst a, Num (Const a)) => LiftNum (Const a) where\n liftNum Neg _ e\n | isZero e = 0\n\n liftNum Neg _ (ComplexC a b) = ComplexC (-a) (-b)\n liftNum Neg _ (CycC c) = CycC (-c)\n\n liftNum Neg _ (W n k c) = mkW (k % n + 1 % 2) (-c)\n\n liftNum _op f (RationalC x) = RationalC (f x)\n liftNum op f (W _ _ c) = liftNum op f c\n liftNum _op f (ModularC x) = ModularC (f x)\n\n liftNum _op f c = lift f c\n\n liftNum2 Add _ e1 e2\n | isZero e1 = e2\n | isZero e2 = e1\n\n liftNum2 Sub _ e1 e2\n | isZero e1 = -e2\n | isZero e2 = e1\n\n liftNum2 Mul _ e1 e2\n | isZero e1 = 0\n | isZero e2 = 0\n | isOne e1 = e2\n | isOne e2 = e1\n | isNegOne e1 = -e2\n | isNegOne e2 = -e1\n\n liftNum2 Add _ (ComplexC a b) (ComplexC c d) = ComplexC (a + c) (b + d)\n liftNum2 Sub _ (ComplexC a b) (ComplexC c d) = ComplexC (a - c) (b - d)\n liftNum2 Mul _ (ComplexC a b) (ComplexC c d) = ComplexC (a*c - b*d) (b*c + a*d)\n\n liftNum2 Mul _ (W n k x) (W n' k' y) = mkW (k % n + k' % n') (x*y)\n\n liftNum2 Add _ (PiC x) (PiC y) = PiC (x + y)\n liftNum2 Sub _ (PiC x) (PiC y) = PiC (x - y)\n\n liftNum2 Mul _ (PiC x) (RationalC y) = PiC (x * y)\n liftNum2 Mul _ (RationalC x) (PiC y) = PiC (x * y)\n\n liftNum2 _op f (RationalC x) (RationalC y) = RationalC (f x y)\n liftNum2 op f (W _ _ c) y = liftNum2 op f c y\n liftNum2 op f x (W _ _ c) = liftNum2 op f x c\n liftNum2 _op f (CycC x) (CycC y) = CycC (f x y)\n liftNum2 _op f (ModularC x) (ModularC y) = ModularC (f x y)\n\n liftNum2 op f x y\n | Just x'@CycC{} <- exact x, Just y'@CycC{} <- exact y = liftNum2 op f x' y'\n | otherwise = lift2 f x y\n\n--- XXX Need UndecidableInstances for this...but we *must* call\n--- liftNum/liftNum2 on constants to ensure they are properly simplified.\n--- The other option would be to forgo the Const instance and push it into the\n--- Exp instance.\ninstance (Typed a, Num (Const a), LiftNum (Const a), Num (Exp a)) => LiftNum (Exp a) where\n liftNum op f (ConstE c) = ConstE $ liftNum op f c\n\n liftNum Neg _ e\n | isZero e = 0\n\n liftNum Neg _ (UnopE Neg x) = x\n liftNum Neg _ (BinopE Sub e1 e2) = e2 - e1\n liftNum Neg _ (ComplexE a b) = ComplexE (-a) (-b)\n\n liftNum op _ e = UnopE op e\n\n liftNum2 op f (ConstE c1) (ConstE c2) = ConstE $ liftNum2 op f c1 c2\n\n liftNum2 Add _ e1 e2\n | isZero e1 = e2\n | isZero e2 = e1\n\n liftNum2 Sub _ e1 e2\n | isZero e1 = -e2\n | isZero e2 = e1\n\n liftNum2 Mul _ e1 e2\n | isZero e1 = 0\n | isZero e2 = 0\n | isOne e1 = e2\n | isOne e2 = e1\n | isNegOne e1 = -e2\n | isNegOne e2 = -e1\n\n -- Simplify multiplication by i and -i\n liftNum2 Mul _ (ConstE k) (ComplexE a b)\n | isI k = ComplexE (-b) a\n | isNegI k = ComplexE b (-a)\n\n liftNum2 Mul _ (ComplexE a b) (ConstE k)\n | isI k = ComplexE (-b) a\n | isNegI k = ComplexE b (-a)\n\n -- Push negation out\n liftNum2 Add _ e1 (UnopE Neg e2) =\n e1 - e2\n\n liftNum2 Add _ (UnopE Neg e1) e2 =\n e2 - e1\n\n liftNum2 Sub _ e1 (UnopE Neg e2) =\n e1 + e2\n\n liftNum2 Sub _ (UnopE Neg e1) e2 =\n -(e1 + e2)\n\n liftNum2 Mul _ e1 (UnopE Neg e2) =\n -(e1 * e2)\n\n liftNum2 Mul _ (UnopE Neg e1) e2 =\n -(e1 * e2)\n\n -- Standard component-wise add/subtract\n liftNum2 Add _ (ComplexE a b) (ComplexE c d) = ComplexE (a + c) (b + d)\n liftNum2 Sub _ (ComplexE a b) (ComplexE c d) = ComplexE (a - c) (b - d)\n\n -- 3-multiply/5-add complex multiplication\n liftNum2 Mul _ (ComplexE a b) (ComplexE c d) | threeMults =\n ComplexE (t1 - t2) (t1 + t3)\n \u00a0 where\n t1 = a*(c+d)\n t2 = d*(b+a)\n t3 = c*(b-a)\n\n -- Usual 4-multiply/4-add complex multiplication\n liftNum2 Mul _ (ComplexE a b) (ComplexE c d) =\n ComplexE (a*c - b*d) (b*c + a*d)\n\n liftNum2 op _ e1 e2 = BinopE op e1 e2\n\ninstance Num (Const Int) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = IntC . fromInteger\n\ninstance Num (Const Integer) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = IntegerC\n\ninstance Num (Const Rational) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = RationalC . fromInteger\n\ninstance Num (Const Float) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = RationalC . fromInteger\n\ninstance Num (Const Double) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = RationalC . fromInteger\n\ninstance Num (Const (Complex Float)) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = RationalC . fromInteger\n\ninstance Num (Const (Complex Double)) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = RationalC . fromInteger\n\ninstance KnownNat p => Num (Const (\u2124/p)) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = ModularC . fromInteger\n\ninstance Num (Exp Int) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = ConstE . fromInteger\n\ninstance Num (Exp Integer) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = ConstE . fromInteger\n\ninstance Num (Exp Float) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = ConstE . fromInteger\n\ninstance Num (Exp Double) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = ConstE . fromInteger\n\ninstance Num (Exp Rational) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = ConstE . fromInteger\n\ninstance Num (Exp (Complex Float)) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = ConstE . fromInteger\n\ninstance Num (Exp (Complex Double)) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = ConstE . fromInteger\n\ninstance KnownNat p => Num (Exp (\u2124/p)) where\n (+) = liftNum2 Add (+)\n (-) = liftNum2 Sub (-)\n (*) = liftNum2 Mul (*)\n\n abs = liftNum Abs abs\n\n negate = liftNum Neg negate\n\n signum = liftNum Signum signum\n\n fromInteger = ConstE . fromInteger\n\n--------------------------------------------------------------------------------\n--\n-- Enum/Real/Integral instances\n--\n--------------------------------------------------------------------------------\n\n-- | Class to lift 'Integral' operators.\nclass LiftIntegral b where\n -- | Lift a binary operation on 'LiftIntegral' to the type 'b\n liftIntegral2 :: Binop -> (forall a . Integral a => a -> a -> a) -> b -> b -> b\n\ninstance LiftIntegral (Const Int) where\n liftIntegral2 _ f (IntC x) (IntC y) = IntC (f x y)\n\n liftIntegral2 _op f c1 c2 = lift2 f c1 c2\n\ninstance Enum (Const Int) where\n toEnum n = IntC (fromIntegral n)\n\n fromEnum (IntC i) = fromIntegral i\n fromEnum RationalC{} = error \"can't happen\"\n fromEnum PiC{} = error \"can't happen\"\n fromEnum W{} = error \"can't happen\"\n\ninstance Real (Const Int) where\n toRational (IntC i) = toRational i\n toRational RationalC{} = error \"can't happen\"\n toRational PiC{} = error \"can't happen\"\n toRational W{} = error \"can't happen\"\n\ninstance Integral (Const Int) where\n quot = liftIntegral2 Quot quot\n rem = liftIntegral2 Rem rem\n div = liftIntegral2 Div div\n mod = liftIntegral2 Mod mod\n\n x `quotRem` y = (x `quot` y, x `rem` y)\n\n x `divMod` y = (x `div` y, x `mod` y)\n\n toInteger (IntC i) = fromIntegral i\n toInteger RationalC{} = error \"can't happen\"\n toInteger W{} = error \"can't happen\"\n toInteger PiC{} = error \"can't happen\"\n\ninstance (LiftIntegral (Const a), Integral (Exp a)) => LiftIntegral (Exp a) where\n liftIntegral2 op f (ConstE x) (ConstE y) = ConstE $ liftIntegral2 op f x y\n\n liftIntegral2 Quot _ (BinopE Mul e1 e2) e2' | e2' == e2 = e1\n liftIntegral2 Rem _ (BinopE Mul _e1 e2) e2' | e2' == e2 = 0\n\n liftIntegral2 Quot _ (BinopE Add (BinopE Mul e1 e2) e3) e2' | e2' == e2 = e1 + e3 `quot` e2\n liftIntegral2 Rem _ (BinopE Add (BinopE Mul _e1 e2) e3) e2' | e2' == e2 = e3 `rem` e2\n\n liftIntegral2 op _ e1 e2 = BinopE op e1 e2\n\ninstance Enum (Exp Int) where\n toEnum n = intE (fromIntegral n)\n\n fromEnum (ConstE (IntC i)) = fromIntegral i\n fromEnum _ = error \"Enum Exp: fromEnum not implemented\"\n\ninstance Real (Exp Int) where\n toRational (ConstE (IntC i)) = toRational i\n toRational _ = error \"Real Exp: toRational not implemented\"\n\ninstance Integral (Exp Int) where\n quot = liftIntegral2 Quot quot\n rem = liftIntegral2 Rem rem\n div = liftIntegral2 Div div\n mod = liftIntegral2 Mod mod\n\n x `quotRem` y = (x `quot` y, x `rem` y)\n\n x `divMod` y = (x `div` y, x `mod` y)\n\n toInteger (ConstE (IntC i)) = fromIntegral i\n toInteger _ = error \"Integral Exp: toInteger not implemented\"\n\n--------------------------------------------------------------------------------\n--\n-- Fractional instances\n--\n--------------------------------------------------------------------------------\n\n-- | Class to lift 'Fractional' operators.\nclass LiftFrac b where\n -- | Lift a binary operation on 'Num' to the type 'b\n liftFrac2 :: Binop -> (forall a . Fractional a => a -> a -> a) -> b -> b -> b\n\ninstance (Fractional a, ToConst a, Fractional (Const a)) => LiftFrac (Const a) where\n liftFrac2 FDiv _ c1 (W n k x) | isOne c1 = mkW (-k % n) (1/x)\n\n liftFrac2 FDiv _ (W n k x) (W n' k' y) = mkW (k % n - k' % n') (x/y)\n\n liftFrac2 FDiv _ (PiC x) (RationalC y) = PiC (x / y)\n\n liftFrac2 FDiv _ c1 c2 | isOne c2 =\n c1\n\n liftFrac2 _op f (RationalC x) (RationalC y) = RationalC (f x y)\n liftFrac2 op f (W _ _ c) y = liftFrac2 op f c y\n liftFrac2 op f x (W _ _ c) = liftFrac2 op f x c\n liftFrac2 _op f (CycC x) (CycC y) = CycC (f x y)\n liftFrac2 _op f (ModularC x) (ModularC y) = ModularC (f x y)\n\n liftFrac2 op f x y\n | Just x'@CycC{} <- exact x, Just y'@CycC{} <- exact y = liftFrac2 op f x' y'\n | otherwise = lift2 f x y\n\ninstance (LiftFrac (Const a), Num (Exp a)) => LiftFrac (Exp a) where\n liftFrac2 op f (ConstE c1) (ConstE c2) = ConstE $ liftFrac2 op f c1 c2\n\n liftFrac2 FDiv _ e1 e2 | isOne e2 =\n e1\n\n liftFrac2 op _ e1 e2 = BinopE op e1 e2\n\ninstance Fractional (Const Rational) where\n (/) = liftFrac2 FDiv (/)\n\n fromRational = RationalC\n\ninstance Fractional (Const Float) where\n (/) = liftFrac2 FDiv (/)\n\n fromRational = RationalC\n\ninstance Fractional (Const Double) where\n (/) = liftFrac2 FDiv (/)\n\n fromRational = RationalC\n\ninstance Fractional (Const (Complex Float)) where\n (/) = liftFrac2 FDiv (/)\n\n fromRational = RationalC\n\ninstance Fractional (Const (Complex Double)) where\n (/) = liftFrac2 FDiv (/)\n\n fromRational = RationalC\n\ninstance KnownNat p => Fractional (Const (\u2124/p)) where\n (/) = liftFrac2 FDiv (/)\n\n fromRational = ModularC . fromRational\n\ninstance Fractional (Exp Float) where\n (/) = liftFrac2 FDiv (/)\n\n fromRational = ConstE . fromRational\n\ninstance Fractional (Exp Double) where\n (/) = liftFrac2 FDiv (/)\n\n fromRational = ConstE . fromRational\n\ninstance Fractional (Exp (Complex Float)) where\n (/) = liftFrac2 FDiv (/)\n\n fromRational = ConstE . fromRational\n\ninstance Fractional (Exp (Complex Double)) where\n (/) = liftFrac2 FDiv (/)\n\n fromRational = ConstE . fromRational\n\ninstance KnownNat p => Fractional (Exp (\u2124/p)) where\n (/) = liftFrac2 FDiv (/)\n\n fromRational = ConstE . fromRational\n\n--------------------------------------------------------------------------------\n--\n-- Floating instances\n--\n--------------------------------------------------------------------------------\n\n-- | Class to lift 'Floating' operators.\nclass LiftFloating b where\n -- | Lift a binary operation on 'Floating' to the type 'b\n liftFloating :: Unop -> (forall a . Floating a => a -> a) -> b -> b\n\ninstance (Floating a, Typed a, ToConst a) => LiftFloating (Const a) where\n liftFloating Sqrt f c@(RationalC r) =\n case tau of\n ComplexT{} -> CycC (sqrtRat r)\n _ -> lift f c\n where\n tau :: Type a\n tau = typeOf (undefined :: a)\n\n liftFloating Sin f c@(PiC r) =\n case tau of\n ComplexT{} -> CycC (sinRev (r / 2))\n _ -> lift f c\n where\n tau :: Type a\n tau = typeOf (undefined :: a)\n\n liftFloating Cos f c@(PiC r) =\n case tau of\n ComplexT{} -> CycC (cosRev (r / 2))\n _ -> lift f c\n where\n tau :: Type a\n tau = typeOf (undefined :: a)\n\n liftFloating _op f c = lift f c\n\ninstance LiftFloating (Const a) => LiftFloating (Exp a) where\n liftFloating op f (ConstE c) = ConstE $ liftFloating op f c\n\n liftFloating op _ e = UnopE op e\n\ninstance Floating (Const Float) where\n pi = PiC 1\n\n exp = liftFloating Exp exp\n log = liftFloating Log log\n sqrt = liftFloating Sqrt sqrt\n asin = liftFloating Asin asin\n acos = liftFloating Acos acos\n atan = liftFloating Atan atan\n sinh = liftFloating Sinh sinh\n cosh = liftFloating Cosh cosh\n asinh = liftFloating Asinh asinh\n acosh = liftFloating Acosh acosh\n atanh = liftFloating Atanh atanh\n sin = liftFloating Sin sin\n cos = liftFloating Cos cos\n\ninstance Floating (Const Double) where\n pi = PiC 1\n\n exp = liftFloating Exp exp\n log = liftFloating Log log\n sqrt = liftFloating Sqrt sqrt\n asin = liftFloating Asin asin\n acos = liftFloating Acos acos\n atan = liftFloating Atan atan\n sinh = liftFloating Sinh sinh\n cosh = liftFloating Cosh cosh\n asinh = liftFloating Asinh asinh\n acosh = liftFloating Acosh acosh\n atanh = liftFloating Atanh atanh\n sin = liftFloating Sin sin\n cos = liftFloating Cos cos\n\ninstance Floating (Const (Complex Float)) where\n pi = PiC 1\n\n exp = liftFloating Exp exp\n log = liftFloating Log log\n sqrt = liftFloating Sqrt sqrt\n asin = liftFloating Asin asin\n acos = liftFloating Acos acos\n atan = liftFloating Atan atan\n sinh = liftFloating Sinh sinh\n cosh = liftFloating Cosh cosh\n asinh = liftFloating Asinh asinh\n acosh = liftFloating Acosh acosh\n atanh = liftFloating Atanh atanh\n sin = liftFloating Sin sin\n cos = liftFloating Cos cos\n\ninstance Floating (Const (Complex Double)) where\n pi = PiC 1\n\n exp = liftFloating Exp exp\n log = liftFloating Log log\n sqrt = liftFloating Sqrt sqrt\n asin = liftFloating Asin asin\n acos = liftFloating Acos acos\n atan = liftFloating Atan atan\n sinh = liftFloating Sinh sinh\n cosh = liftFloating Cosh cosh\n asinh = liftFloating Asinh asinh\n acosh = liftFloating Acosh acosh\n atanh = liftFloating Atanh atanh\n sin = liftFloating Sin sin\n cos = liftFloating Cos cos\n\ninstance Floating (Exp Float) where\n pi = ConstE pi\n\n exp = liftFloating Exp exp\n log = liftFloating Log log\n sqrt = liftFloating Sqrt sqrt\n asin = liftFloating Asin asin\n acos = liftFloating Acos acos\n atan = liftFloating Atan atan\n sinh = liftFloating Sinh sinh\n cosh = liftFloating Cosh cosh\n asinh = liftFloating Asinh asinh\n acosh = liftFloating Acosh acosh\n atanh = liftFloating Atanh atanh\n sin = liftFloating Sin sin\n cos = liftFloating Cos cos\n\ninstance Floating (Exp Double) where\n pi = ConstE pi\n\n exp = liftFloating Exp exp\n log = liftFloating Log log\n sqrt = liftFloating Sqrt sqrt\n asin = liftFloating Asin asin\n acos = liftFloating Acos acos\n atan = liftFloating Atan atan\n sinh = liftFloating Sinh sinh\n cosh = liftFloating Cosh cosh\n asinh = liftFloating Asinh asinh\n acosh = liftFloating Acosh acosh\n atanh = liftFloating Atanh atanh\n sin = liftFloating Sin sin\n cos = liftFloating Cos cos\n\ninstance Floating (Exp (Complex Float)) where\n pi = ConstE pi\n\n exp = liftFloating Exp exp\n log = liftFloating Log log\n sqrt = liftFloating Sqrt sqrt\n asin = liftFloating Asin asin\n acos = liftFloating Acos acos\n atan = liftFloating Atan atan\n sinh = liftFloating Sinh sinh\n cosh = liftFloating Cosh cosh\n asinh = liftFloating Asinh asinh\n acosh = liftFloating Acosh acosh\n atanh = liftFloating Atanh atanh\n sin = liftFloating Sin sin\n cos = liftFloating Cos cos\n\ninstance Floating (Exp (Complex Double)) where\n pi = ConstE pi\n\n exp = liftFloating Exp exp\n log = liftFloating Log log\n sqrt = liftFloating Sqrt sqrt\n asin = liftFloating Asin asin\n acos = liftFloating Acos acos\n atan = liftFloating Atan atan\n sinh = liftFloating Sinh sinh\n cosh = liftFloating Cosh cosh\n asinh = liftFloating Asinh asinh\n acosh = liftFloating Acosh acosh\n atanh = liftFloating Atanh atanh\n sin = liftFloating Sin sin\n cos = liftFloating Cos cos\n\n--------------------------------------------------------------------------------\n--\n-- Staged operations\n--\n--------------------------------------------------------------------------------\n\nclass IfThenElse a b where\n ifThenElse :: a -> b -> b -> b\n\ninstance IfThenElse Bool a where\n ifThenElse c t e = if c then t else e\n\ninfix 4 .==., ./=.\n\nclass IsEq a b | a -> b where\n (.==.) :: a -> a -> b\n (./=.) :: a -> a -> b\n\ninfix 4 .<., .<=., .>=., .>.\n\nclass IsEq a b => IsOrd a b where\n (.<.) :: a -> a -> b\n (.<=.) :: a -> a -> b\n (.>=.) :: a -> a -> b\n (.>.) :: a -> a -> b\n\ninstance (Typed a, ToConst a, Eq a) => IsEq (Exp a) (Exp Bool) where\n e1 .==. e2 = BBinopE Eq e1 e2\n e1 ./=. e2 = BBinopE Ne e1 e2\n\ninstance (Typed a, ToConst a, Eq a) => IsOrd (Exp a) (Exp Bool) where\n e1 .<. e2 = BBinopE Lt e1 e2\n e1 .<=. e2 = BBinopE Le e1 e2\n e1 .>. e2 = BBinopE Gt e1 e2\n e1 .>=. e2 = BBinopE Ge e1 e2\n\ninstance IfThenElse (Exp Bool) (Exp a) where\n ifThenElse = IfE\n\n--------------------------------------------------------------------------------\n--\n-- Smart constructors\n--\n--------------------------------------------------------------------------------\n\nclass IsZeroOne a where\n isZero, isOne, isNegOne :: a -> Bool\n\nisI :: Const (Complex a) -> Bool\nisI RationalC{} = False\nisI (ComplexC r i) = isZero r && isOne i\nisI (W _ _ c) = isI c\nisI (CycC c) = c == i\nisI PiC{} = False\n\nisNegI :: Const (Complex a) -> Bool\nisNegI RationalC{} = False\nisNegI (ComplexC r i) = isZero r && isNegOne i\nisNegI (W _ _ c) = isNegI c\nisNegI (CycC c) = c == -i\nisNegI PiC{} = False\n\ninstance IsZeroOne (Const a) where\n isZero (IntC 0) = True\n isZero (IntegerC 0) = True\n isZero (FloatC 0) = True\n isZero (DoubleC 0) = True\n isZero (RationalC 0) = True\n isZero (ComplexC 0 0) = True\n isZero (CycC 0) = True\n isZero _ = False\n\n isOne (IntC 1) = True\n isOne (IntegerC 1) = True\n isOne (FloatC 1) = True\n isOne (DoubleC 1) = True\n isOne (RationalC 1) = True\n isOne (ComplexC 1 i) = isZero i\n isOne (W n k _) = k % n == 0 || k % n == 1\n isOne (CycC 1) = True\n isOne _ = False\n\n isNegOne (IntC (-1)) = True\n isNegOne (IntegerC (-1)) = True\n isNegOne (FloatC (-1)) = True\n isNegOne (DoubleC (-1)) = True\n isNegOne (RationalC (-1)) = True\n isNegOne (ComplexC (-1) i) = isZero i\n isNegOne (W _ _ c) = isNegOne c\n isNegOne (CycC (-1)) = True\n isNegOne _ = False\n\ninstance IsZeroOne (Exp a) where\n isZero (ConstE c) = isZero c\n isZero _ = False\n\n isOne (ConstE c) = isOne c\n isOne _ = False\n\n isNegOne (ConstE c) = isNegOne c\n isNegOne (UnopE Neg (ConstE c)) = isOne c\n isNegOne _ = False\n\nmkW :: RootOfUnity (Const a) => Ratio Int -> Const a -> Const a\nmkW r c = W n (k `mod` n) c\n where\n k = numerator r\n n = denominator r\n\nisConstE :: Exp a -> Bool\nisConstE ConstE{} = True\nisConstE _ = False\n\n-- | Create an 'Exp Int' from an 'Int'.\nintE :: Int -> Exp Int\nintE = ConstE . IntC\n\n-- | Create an 'Exp (Complex Double)' from a 'Complex Double'.\ncomplexE :: RealFloatConst a => Complex a -> Exp (Complex a)\ncomplexE (r :+ i) = ConstE $ ComplexC (toConst r) (toConst i)\n\n-- | Extract the complex and real portions of a 'Const (Complex a)'.\nunComplexC :: RealFloatConst a => Const (Complex a) -> (Const a, Const a)\nunComplexC (RationalC r) = (RationalC r, 0)\nunComplexC (ComplexC r i) = (r, i)\nunComplexC (W _ _ c) = unComplexC c\nunComplexC (PiC k) = (PiC k, 0)\nunComplexC x@CycC{} = (toConst r, toConst i)\n where\n r :+ i = fromConst x\n\n-- | Extract the complex and real portions of an 'Exp (Complex a)'.\nunComplexE :: RealFloatConst a => Exp (Complex a) -> (Exp a, Exp a)\nunComplexE (ConstE c) =\n (ConstE cr, ConstE ci)\n where\n (cr, ci) = unComplexC c\n\nunComplexE (ComplexE er ei) =\n (er, ei)\n\nunComplexE e =\n (ReE e, ImE e)\n\n-- | Force extraction of the complex and real portions of an 'Exp (Complex a)'.\nforceUnComplexE :: RealFloatConst a => Exp (Complex a) -> (Exp a, Exp a)\nforceUnComplexE (ConstE c) =\n (ConstE cr, ConstE ci)\n where\n (cr, ci) = unComplexC c\n\nforceUnComplexE (ComplexE er ei) =\n (er, ei)\n\nforceUnComplexE (UnopE Neg e) =\n forceUnComplexE $ - (ensureComplexE e)\n\nforceUnComplexE (BinopE Add e1 e2) =\n forceUnComplexE $ ensureComplexE e1 + ensureComplexE e2\n\nforceUnComplexE (BinopE Sub e1 e2) =\n forceUnComplexE $ ensureComplexE e1 - ensureComplexE e2\n\nforceUnComplexE (BinopE Mul e1 e2) =\n forceUnComplexE $ ensureComplexE e1 * ensureComplexE e2\n\nforceUnComplexE e =\n (ReE e, ImE e)\n\n-- | Ensure that a complex expression is represented using its constituent real\n-- and imaginary parts.\nensureComplexE :: RealFloatConst a => Exp (Complex a) -> Exp (Complex a)\nensureComplexE e = ComplexE er ei\n where\n (er, ei) = forceUnComplexE e\n\ntrue, false :: Exp Bool\ntrue = ConstE (BoolC True)\nfalse = ConstE (BoolC False)\n", "meta": {"hexsha": "6647836a097d918fd0955c595e1c74523f2cf992", "size": 44771, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Spiral/Exp.hs", "max_stars_repo_name": "mainland/hspiral", "max_stars_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-05-21T21:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T04:48:25.000Z", "max_issues_repo_path": "Spiral/Exp.hs", "max_issues_repo_name": "mainland/hspiral", "max_issues_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Spiral/Exp.hs", "max_forks_repo_name": "mainland/hspiral", "max_forks_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9779935275, "max_line_length": 128, "alphanum_fraction": 0.5710839606, "num_tokens": 14425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5526624622408709}} {"text": "{-\n - ::= { ( | ) }\n -\n - ::= 'fun' '=' \n -\n - ::= 'val' '=' \n -\n - ::= \n - | 'if' 'then' 'else' \n - | 'let' 'in' 'end'\n - | 'fn' '=>' \n -\n - ::= { ('>' | '=' | '<') }\n -\n - ::= { ('+' | '-') }\n -\n - ::= { ('*' | '/') }\n -\n - ::= { }\n -\n - ::= '(' ')' \n - | \n - | \n -}\n\n {-# LANGUAGE ScopedTypeVariables #-}\n {-# LANGUAGE GeneralizedNewtypeDeriving #-}\n {-# LANGUAGE RankNTypes #-}\n \n {-# LANGUAGE FlexibleContexts #-}\n \n \n module Hw8 () where\n \n -- import Hw1\n -- import Hw2\n -- import Hw3\n -- import Hw4\n -- import Hw5\n -- import Hw6\n -- import Hw7\n import Data.Time.Clock\n import Data.Complex\n \n\n import Text.Parsec\n import Text.Parsec.Expr\n import Text.Parsec.Prim (unexpected)\n import Text.Parsec.Language (emptyDef)\n import Data.Either\n import qualified Text.Parsec.Token as Token\n \n -- Abstract Syntax Tree ----------------------------------------------------------------------------------\n \n -- function/variable declaration\n data Decl = Fun String String Exp -- fun f x = e;\n | Val String Exp -- val x = e;\n \n -- expressions\n data Exp = Lt Exp Exp -- e1 < e2\n | Gt Exp Exp -- e1 > e2\n | Eq Exp Exp -- e1 = e2\n | Plus Exp Exp -- e1 + e2\n | Minus Exp Exp -- e1 - e2\n | Times Exp Exp -- e1 * e2\n | Div Exp Exp -- e1 div e2\n | Var String -- x\n | If Exp Exp Exp -- if e0 then e1 else e2\n | Fn String Exp -- fn x => e\n | Let [Decl] Exp -- let val x = e0; fun f = e1; in e2 end\n | App Exp Exp -- e1 e2\n | Const Integer -- n\n \n instance Show Decl where\n show (Fun f x e) = \"fun \" ++ f ++ \" \" ++ x ++ \" = \" ++ show e \n show (Val x e) = \"val \" ++ x ++ \" = \" ++ show e \n \n instance Show Exp where\n show (Const x) = show x\n show (Plus t1 t2) = showBop t1 \"+\" t2\n show (Times t1 t2) = showBop t1 \"*\" t2\n show (Minus t1 t2) = showBop t1 \"-\" t2\n show (Div t1 t2) = showBop t1 \"/\" t2\n show (Lt t1 t2) = showBop t1 \"<\" t2\n show (Gt t1 t2) = showBop t1 \">\" t2\n show (Eq t1 t2) = showBop t1 \"=\" t2\n show (If t0 t1 t2) = \"if \" ++ show t0 ++ \" then \" ++ show t1 ++ \" else \" ++ show t2\n show (Var s) = s\n show (App t1 t2) = \"(\" ++ show t1 ++ \" \" ++ show t2 ++ \")\"\n show (Fn x t) = \"(fn \" ++ x ++ \" => \" ++ show t ++ \")\"\n show (Let decls e) = \"(let \" ++ show decls ++ \" in \" ++ show e ++ \" end)\"\n \n showBop t1 op t2 = \"(\" ++ show t1 ++ \" \" ++ op ++ \" \" ++ show t2 ++ \")\"\n \n \n -- Parser definitions ----------------------------------------------------------------------------------\n \n type Parser = Parsec [Char] ()\n \n -- Runner\n \n -- print AST or error\n run :: Show a => Parser a -> String -> IO()\n run p input = putStrLn $ case parse p \"\" input of\n Left error -> show error\n Right x -> show x\n \n -- return Either AST or parse error \n runParser :: Parser a -> String -> Either ParseError a\n runParser p input = parse p \"\" input \n \n -- Lexer\n \n lexeme p = do { x <- p; skipMany space \"\"; return x } -- get rid of trailing spaces\n \n symbol name = lexeme $ string name -- parse string and then remove spaces\n \n lexer :: Token.TokenParser ()\n lexer = Token.makeTokenParser style\n where style = emptyDef {\n Token.reservedOpNames = [\"+\",\"*\",\"-\",\"=\", \">\", \"<\", \"in\"],\n Token.reservedNames = [\"let\", \"in\", \"end\"]\n }\n \n parens :: Parser a -> Parser a\n parens = Token.parens lexer\n \n ident :: Parser String -- raw identifier\n ident = (lexeme $ many1 letter) \"identifier\"\n \n integer :: Parser Integer -- parse integer and return numeric value\n integer = (read <$> (lexeme $ many1 digit)) \"integer\"\n \n keyword :: String -> Parser () -- make keyword parser with backtrack\n keyword name = (try $ symbol name) >> return ()\n \n if_ = keyword \"if\" -- keyword parsers\n then_ = keyword \"then\"\n else_ = keyword \"else\"\n fn_ = keyword \"fn\"\n fun_ = keyword \"fun\"\n let_ = keyword \"let\"\n in_ = keyword \"in\"\n end_ = keyword \"end\"\n val_ = keyword \"val\"\n assign_ = keyword \"=\"\n gt_ = keyword \">\"\n lt_ = keyword \"<\"\n eq_ = keyword \"=\"\n pl_ = keyword \"+\"\n mn_ = keyword \"-\"\n tm_ = keyword \"*\"\n dv_ = keyword \"/\"\n fatArrow_ = keyword \"=>\"\n sCol_ = keyword \";\"\n \n identifier :: Parser String -- identifier that won't collide with keywords\n identifier = try $ do \n name <- ident \n if name `elem` reserved \n then unexpected (\"reserved word \" ++ name) -- throw parse error \n else return name \n where \n reserved = [\"if\", \"then\", \"else\", \"fn\", \"fun\", \"let\", \"in\", \"end\", \"val\"]\n \n -- Parser for the (phrase) grammar\n \n prog :: Parser [Decl] \n prog = skipMany space >> declList -- skip leading spaces\n \n declList :: Parser [Decl] -- parse a list of function or variable declarations\n declList = many $ valDecl <|> funDecl\n \n \n funDecl :: Parser Decl\n funDecl = do\n fun_\n name <- identifier\n param <- identifier\n assign_\n t1 <- parseExpression\n return (Fun name param t1)\n \n valDecl :: Parser Decl\n valDecl = do\n val_\n name <- identifier\n assign_\n t1 <- parseExpression\n return (Val name t1)\n \n \n parseExpression :: Parser Exp\n parseExpression = parseIf <|> parseLet <|> expr\n \n parseApp :: Parser Exp\n parseApp = ((factor `chainl1` (return App)) \"parseApp expr\")\n \n expr = expr' `chainl1` compOp\n expr' = term `chainl1` addOp\n term = parseApp `chainl1` mulOp\n factor = parseVar <|> parseInt <|> parseFn <|> parens expr\n \n compOp = do {gt_ ; return gtExpr}\n <|> do {lt_ ; return ltExpr}\n <|> do {eq_ ; return eqExpr}\n \n mulOp = do{ tm_ ; return tmExpr }\n <|> do{ dv_ ; return dvExpr }\n \n addOp = do{ pl_ ; return plExpr }\n <|> do{ mn_ ; return mlExpr }\n \n gtExpr :: Exp -> Exp -> Exp\n gtExpr = Gt\n \n ltExpr :: Exp -> Exp -> Exp\n ltExpr = Lt\n \n eqExpr :: Exp -> Exp -> Exp\n eqExpr = Eq\n \n tmExpr :: Exp -> Exp -> Exp\n tmExpr = Times\n \n dvExpr :: Exp -> Exp -> Exp\n dvExpr = Div\n \n plExpr :: Exp -> Exp -> Exp\n plExpr = Plus\n \n mlExpr :: Exp -> Exp -> Exp\n mlExpr = Minus\n \n \n parseIf :: Parser Exp\n parseIf = do\n if_\n cond <- parseExpression\n then_\n true <- parseExpression\n else_\n false <- parseExpression\n return (If cond true false)\n \n parseFn :: Parser Exp\n parseFn = do\n fn_\n name <- identifier\n fatArrow_\n exp <- parseExpression\n return (Fn name exp)\n \n \n \n -- parseLet :: Parser Exp\n -- parseLet = do\n -- let_\n -- decl <- parseExpression\n -- in_\n -- exp <- parseExpression\n -- end_\n -- return (Let decl exp)\n \n parseVar :: Parser Exp\n parseVar = Var `fmap` identifier\n \n parseInt :: Parser Exp\n parseInt = Const `fmap` integer\n \n parseLet :: Parser Exp\n parseLet = do\n let_\n decls <- declList\n in_\n exp <- parseExpression\n end_\n return (Let decls exp)\n -- Test code ----------------------------------------------------------------------------------\n \n-- main :: IO ()\n-- main = do\n \n-- let fact = \"fun fact x = if x < 1 then 1 else x * fact (x-1)\\n\"\n-- let it = \"val it = let val y = 10 val z = 15 in fact y end\"\n-- let fnFn = \"fun f x = fn z => y\"\n \n-- let d = (fact ++ it)\n-- let test = \"val x = x * 5 / 5 - 5\\n\"\n-- let test2 = \"fun fact x = 5\\n\"\n-- let test3 = \"if x > 1 then 1 else -1\"\n-- let test4 = \"fun fact x = y\"\n-- let bla = (test ++ test2 ++ test3) \n-- -- run prog bla\n-- run prog d\n \n \n -- main = do\n -- Hw2\n -- let n = 2^5\n -- let s1 = map (\\x -> sin(20*pi*x) + sin(40*pi*x)/2) $ range 0 1 n \n -- -- print $ split [1..64]\n -- -- print(rd 3 s1)\n -- start <- getCurrentTime\n -- let dft1 = map (\\x -> x/n) $ absolute $ dft s1 \n -- print(rd 2 dft1)\n -- end <- getCurrentTime\n -- print (diffUTCTime end start)\n -- start2 <- getCurrentTime\n -- let fft1 = map (\\x -> x/n) $ absolute $ fft s1 \n -- print(rd 2 fft1)\n -- end2 <- getCurrentTime\n -- print (diffUTCTime end2 start2)\n -- let v1 = Vec [1.0,2.0,3.0]\n -- let v2 = Vec [2,3,4]\n -- let v3 = Vec [-10,0,10]\n \n -- Hw3\n -- print $ v1 == v2\n -- print $ show v3\n -- print $ v1 + v2\n -- print $ v1 - v2\n -- print $ v1 * v2\n -- print $ v1 / v3\n -- print $ negate v1\n -- print $ signum v3\n -- print $ abs v3\n -- print $ foldr (*) 1 v1\n -- print $ sin $ v1 * (pi / 2)\n -- print $ v1 + (pure' $ sqrt 2)\n -- print $ realV v1\n -- print $ pure' 'a'\n \n -- let v1 = Vec [1.123,2.213,3.321]\n -- let v2 = Vec [2,3,4]\n -- let v3 = Vec [-10,0,10]\n -- print $ v1 + v2\n -- print $ v1 - v2\n -- print $ v1 * v2\n -- print $ v1 / v2\n -- print $ negate v1\n -- print $ signum v3\n -- print $ abs v3\n -- print $ v1 + 10\n -- print $ v2 + 1.2\n -- print $ v1 + (pure' $ sqrt 2)\n -- print $ realV v1\n -- print $ imagV v1\n -- print $ realV v1 + imagV v2\n -- print $ sin $ v1 * (pi / 2)\n -- print $ sum v1\n \n -- Hw4\n -- let n = fromIntegral 2^8\n -- let s1 = realV $ Vec $ fmap (\\x -> sin(20*pi*x) + sin(40*pi*x)/2) $ range 0 1 n \n -- print $ fmap (\\z -> conjugate z) s1\n -- print s1\n -- start <- getCurrentTime\n -- let dft1 = fmap (/n) $ absolute $ dft s1\n -- print(rd 2 dft1)\n -- let n = fromIntegral 2^8\n -- let s1 = fmap (\\x -> sin(20*pi*x) + sin(40*pi*x)/2) $ Vec $ range 0 1 n \n -- print(rd 3 s1)\n -- print s1\n -- let dft1 = fmap (/n) $ absolute $ dft s1\n -- print(rd 2 dft1)\n -- print(rd 2 $ fmap (/n) $ absolute $ idft $ dft s1)\n -- print(rd 2 $ fmap (/n) $ absolute $ ifft $fft s1)\n \n -- end <- getCurrentTime\n -- print (diffUTCTime end start)\n -- start2 <- getCurrentTime\n -- let fft1 = fmap (/n) $ absolute $ fft s1\n -- print(rd 2 fft1)\n -- end2 <- getCurrentTime\n -- print (diffUTCTime end2 start2)\n \n -- let v1 = Vec [1,2,3]\n -- print $ v1 + v2\n -- print $ rd 2 v1\n -- let n = fromIntegral 2^8\n -- let s1 = fmap (\\x -> sin(20*pi*x) + sin(40*pi*x)/2) $ Vec $ range 0 1 n \n -- print(rd 3 s1)\n -- print(rd 3 $ fmap (\\(r:+_) -> r) $ low_pass' 15 $ realV s1) \n -- print(rd 3 $ fmap (\\(r:+_) -> r) $ low_pass 15 $ realV s1)\n -- let a = [2,4,1,11,9]\n -- let b = [3,1,5,0,2]\n -- print $ maxList a \n -- print $ maxList' (<) a\n -- print $ rd 1 $ makeNoise 12345 10 0.0 1.0\n -- let n' = 2^8\n -- let noise = makeNoise 0 n' (-1.0) 1.0\n -- let n = fromIntegral n'\n -- let s = fmap (\\x -> sin(20*pi*x) + sin(40*pi*x)/2) $ Vec $ range 0 1 n \n -- let s1 = s + noise\n -- -- noisy signal \n -- print(rd 2 s1)\n -- -- noisy frequency\n -- print (rd 2 $ fmap (/n) $ absolute $ dft $ realV s1)\n -- -- filtered signal (dft)\n -- print (rd 3 $ fmap (\\(r:+_) -> r) $ low_pass' 15 $ realV s1)\n -- -- filtered signal (fft)\n -- print (rd 2 $ fmap (\\(r:+_) -> r) $ low_pass 15 $ realV s1)", "meta": {"hexsha": "d76682b4c42f309ffb8e5d1720d8aa27e2f91f02", "size": 11444, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Hw8.hs", "max_stars_repo_name": "NikolaPeevski/Haskell-stuff", "max_stars_repo_head_hexsha": "b74684bfd7df53a53f11dd4a3c6f3475f2d9bcf8", "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/Hw8.hs", "max_issues_repo_name": "NikolaPeevski/Haskell-stuff", "max_issues_repo_head_hexsha": "b74684bfd7df53a53f11dd4a3c6f3475f2d9bcf8", "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/Hw8.hs", "max_forks_repo_name": "NikolaPeevski/Haskell-stuff", "max_forks_repo_head_hexsha": "b74684bfd7df53a53f11dd4a3c6f3475f2d9bcf8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3970223325, "max_line_length": 116, "alphanum_fraction": 0.4954561342, "num_tokens": 3645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.5526567512624929}} {"text": "module PropertiesTests\n ( properties\n ) where\n\nimport GradientDescent\nimport Test.Tasty\nimport qualified Test.Tasty.QuickCheck as QC\nimport qualified Test.Tasty.SmallCheck as SC\nimport Numeric.LinearAlgebra\n\n\nproperties :: TestTree\nproperties = testGroup \"Properties\" [scProps, qcProps]\n\n\nscProps =\n testGroup\n \"(checked by SmallCheck)\"\n [checkTranspositionSC, checkMatrixSigmoidSC, checkMatrixSigmoidPrimeSC]\n\n\ncheckTranspositionSC = SC.testProperty \"matrix == tr . tr matrix\" $\n \\list -> ((length list >< 1) (list :: [Double]) :: Matrix Double)\n == (tr $ tr $ (length list><1) (list :: [Double]) :: Matrix Double)\n\n\ncheckMatrixSigmoidSC = SC.testProperty \"check matrixSigmoid\" $\n \\list ->\n (length (list :: [Double])) >=\n 1 SC.==> ((1 >< length list) (sigmoid <$> list) :: Matrix Double)\n == matrixSigmoid ((1 >< length list) list :: Matrix Double)\n\n\ncheckMatrixSigmoidPrimeSC = SC.testProperty \"check matrixSigmoidPrime\" $\n \\list ->\n (length (list :: [Double])) >=\n 1 SC.==> ((1 >< length list) (sigmoidPrime <$> list) :: Matrix Double)\n == matrixSigmoidPrime ((1 >< length list) list :: Matrix Double)\n\n\nqcProps =\n testGroup\n \"(checked by QuickCheck)\"\n [checkTranspositionQC, checkMatrixSigmoidQC, checkMatrixSigmoidPrimeQC]\n\n\ncheckTranspositionQC = QC.testProperty \"matrix == tr . tr matrix\" $\n \\list -> ((length list >< 1) (list :: [Double]) :: Matrix Double)\n == (tr $ tr $ (length list><1) (list :: [Double]) :: Matrix Double)\n\n\ncheckMatrixSigmoidQC = QC.testProperty \"check matrixSigmoid\" $\n \\list ->\n (length (list :: [Double])) >=\n 1 QC.==> ((1 >< length list) (sigmoid <$> list) :: Matrix Double)\n == matrixSigmoid ((1 >< length list) list :: Matrix Double)\n\n\ncheckMatrixSigmoidPrimeQC = QC.testProperty \"check matrixSigmoidPrime\" $\n \\list ->\n (length (list :: [Double])) >=\n 1 QC.==> ((1 >< length list) (sigmoidPrime <$> list) :: Matrix Double)\n == matrixSigmoidPrime ((1 >< length list) list :: Matrix Double)\n\n\n", "meta": {"hexsha": "f9e569368b95d2fdb5b437991d1eabe78e6e2037", "size": 2495, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/PropertiesTests.hs", "max_stars_repo_name": "Malenczuk/HuskNet", "max_stars_repo_head_hexsha": "ce64117b907fd79f4dfae824f16f3fe2e1db2b1b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-29T22:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-29T22:04:24.000Z", "max_issues_repo_path": "test/PropertiesTests.hs", "max_issues_repo_name": "Malenczuk/HuskNet", "max_issues_repo_head_hexsha": "ce64117b907fd79f4dfae824f16f3fe2e1db2b1b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/PropertiesTests.hs", "max_forks_repo_name": "Malenczuk/HuskNet", "max_forks_repo_head_hexsha": "ce64117b907fd79f4dfae824f16f3fe2e1db2b1b", "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.803030303, "max_line_length": 100, "alphanum_fraction": 0.5286573146, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5526567428242611}} {"text": "module P18b where\nimport Data.Complex (magnitude)\nimport Data.Char (isNumber)\nimport Data.Maybe (fromMaybe)\nimport Data.List (tails)\nimport Data.Tuple (swap)\n\ndata SnailNumber = RegularNumber Int | NumberPair SnailNumber SnailNumber deriving (Eq, Show)\n\nrun :: String -> Int\nrun = maximum . map (snailMagnitude . snailSum) . pairs . parse\n\nparse :: String -> [SnailNumber]\nparse = map (fst . parseNumber) . lines\n\nparseNumber :: String -> (SnailNumber, String)\nparseNumber ('[':xs) =\n let (left, ',':xs') = parseNumber xs\n (right, xs'') = parseNumber xs'\n in (NumberPair left right, tail xs'')\nparseNumber xs =\n let (n, xs') = span isNumber xs\n in (RegularNumber (read n), xs')\n\nsnailSum :: (SnailNumber, SnailNumber) -> SnailNumber\nsnailSum (a, b) = snailAdd a b\n\nsnailAdd :: SnailNumber -> SnailNumber -> SnailNumber\nsnailAdd a b = snailReduce (snailAdd' a b)\n\nsnailAdd' :: SnailNumber -> SnailNumber -> SnailNumber\nsnailAdd' = NumberPair\n\nsnailReduce :: SnailNumber -> SnailNumber\nsnailReduce x =\n let x' = snailReduce' x\n in if x == x' then x' else snailReduce x'\n\nsnailReduce' :: SnailNumber -> SnailNumber\nsnailReduce' x =\n let x' = explode x\n in fromMaybe x' (split x')\n\nexplode :: SnailNumber -> SnailNumber\nexplode x =\n let (x', _, _) = explode' 0 x\n in x'\n\nexplode' :: Int -> SnailNumber -> (SnailNumber, Int, Int)\nexplode' 4 (NumberPair (RegularNumber left) (RegularNumber right)) = (RegularNumber 0, left, right)\nexplode' depth (NumberPair left right) =\n let (left', expLeft1, expRight1) = explode' (depth+1) left\n (right', expLeft2, expRight2) = explode' (depth+1) (incrementLeft right expRight1)\n left'' = incrementRight left' expLeft2\n in (NumberPair left'' right', expLeft1, expRight2)\nexplode' _ x = (x, 0, 0)\n\nincrementLeft :: SnailNumber -> Int -> SnailNumber\nincrementLeft (RegularNumber x) a = RegularNumber (x+a)\nincrementLeft (NumberPair left right) x = NumberPair (incrementLeft left x) right\n\nincrementRight :: SnailNumber -> Int -> SnailNumber\nincrementRight (RegularNumber x) a = RegularNumber (x+a)\nincrementRight (NumberPair left right) x = NumberPair left (incrementRight right x)\n\nsplit :: SnailNumber -> Maybe SnailNumber\nsplit n@(RegularNumber x) = if x > 9 then Just (NumberPair (RegularNumber x') (RegularNumber (x - x'))) else Nothing\n where x' = x `div` 2\nsplit (NumberPair left right) =\n case split left of\n Just left' -> Just (NumberPair left' right)\n Nothing -> case split right of\n Just right' -> Just (NumberPair left right')\n Nothing -> Nothing\n\nsnailMagnitude :: SnailNumber -> Int\nsnailMagnitude (RegularNumber x) = x\nsnailMagnitude (NumberPair left right) = 3*snailMagnitude left + 2*snailMagnitude right\n\npairs :: [a] -> [(a, a)]\npairs xs =\n let ps = concatMap (\\xs' -> map (\\x -> (head xs', x)) (tail xs')) $ filter (not . null) (tails xs)\n in ps ++ map swap ps", "meta": {"hexsha": "fdb6ba2adf7c88dfde2edb81d017a71d69b563be", "size": 2915, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/P18b.hs", "max_stars_repo_name": "jontra000/AdventOfCode2021", "max_stars_repo_head_hexsha": "05a7fb3d37946e20fc90282cf3667778dfdb621d", "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/P18b.hs", "max_issues_repo_name": "jontra000/AdventOfCode2021", "max_issues_repo_head_hexsha": "05a7fb3d37946e20fc90282cf3667778dfdb621d", "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/P18b.hs", "max_forks_repo_name": "jontra000/AdventOfCode2021", "max_forks_repo_head_hexsha": "05a7fb3d37946e20fc90282cf3667778dfdb621d", "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.1204819277, "max_line_length": 116, "alphanum_fraction": 0.6823327616, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5525957487778611}} {"text": "module Trainer where\n\nimport Numeric.LinearAlgebra\nimport Models\nimport Layer\nimport Optimization\nimport Data.Foldable\nimport Control.Monad.IO.Class\nimport Utils\n\ndata TrainConfig = TrainConfig {\n trainConfigRowNum :: Int,\n trainConfigColNum :: Int,\n trainConfigLearningRate :: Double,\n trainConfigMomentum :: Double,\n trainConfigDecay :: Double,\n trainConfigEpsilon :: Double,\n trainConfigBatchSize :: Double,\n trainConfigOptimization:: String\n }\n\ntrainSingleData :: Model VLayer -> TrainConfig -> Matrix R -> IO ()\ntrainSingleData (Model []) _ _ = print \"No models !\" >> return ()\ntrainSingleData neuModel trainConfig inputData =\n let r = trainConfigRowNum trainConfig\n c = trainConfigColNum trainConfig\n paramsList = genParamsList neuModel\n gparamsList = genGParamsList neuModel\n accGradList = accMatrixInit paramsList\n accDeltaList = accMatrixInit paramsList\n optimize = Adadelta {\n adaDecay = trainConfigDecay trainConfig,\n adaEpsilon = trainConfigEpsilon trainConfig,\n adaBatchSize = (trainConfigBatchSize trainConfig),\n adaParams = paramsList,\n adaGparams = gparamsList,\n adaAccGrad = accGradList,\n adaAccDelta = accDeltaList\n } in\n -- begin to train\n forM_ [1..10000] $ \\idx -> do\n --print idx\n let output = forward inputData neuModel in\n --print \"backpropagate the model\" >>\n let neuModel = backward \"mse\" output inputData neuModel in\n --print \"neumodel\" >>\n let gparamsList = updateGParamsList neuModel gparamsList in\n --print \"continue\" >> \n if mod idx 100 == 0 && idx >= 100 then\n -- update the params in optimize\n -- update the params in model\n let optimize = paramUpdate optimize\n paramsList = adaParams optimize\n neuModel = updateModelParams neuModel paramsList in\n print (getAverageMat output) >> \n return()\n else return()\n", "meta": {"hexsha": "a0d5fab4bfbab9d5f8f410d3392e1e3436c3dcbe", "size": 2040, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "vortex/Trainer.hs", "max_stars_repo_name": "neutronest/vortex", "max_stars_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-03-16T06:51:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-06T05:07:06.000Z", "max_issues_repo_path": "vortex/Trainer.hs", "max_issues_repo_name": "neutronest/vortex", "max_issues_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "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": "vortex/Trainer.hs", "max_forks_repo_name": "neutronest/vortex", "max_forks_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1724137931, "max_line_length": 67, "alphanum_fraction": 0.6549019608, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5525957487778611}} {"text": "{-# LANGUAGE Strict, StrictData #-}\n{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}\n{-# LANGUAGE TypeFamilies, TypeFamilyDependencies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE DefaultSignatures #-}\n\n------------------------------------------------\n-- |\n-- Module : Numeric.Algebra.Presentation\n-- Copyright : (c) Jun Yoshida 2019\n-- License : BSD3\n--\n-- Matrix presentations of morphisms\n--\n------------------------------------------------\n\nmodule Numeric.Algebra.Presentation where\n\nimport GHC.Generics (Generic)\nimport Control.DeepSeq (NFData, force)\n\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Foldable\n\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Numeric.LinearAlgebra.Devel as LA\n\nimport Numeric.Algebra.FreeModule\nimport Numeric.Matrix.Integral\nimport Numeric.F2 (F2)\nimport qualified Numeric.Matrix.F2 as F2\nimport qualified Numeric.Matrix.F2.Mutable as F2\n\n\n---------------\n-- * Classes\n---------------\n-- | Class which provides matrix presentations for homomorphisms with coefficients in a.\nclass (Eq a, Num a, NFData a, Semigroup (Mat a), NFData (Vec a), NFData (Mat a)) => Coefficient a where\n type Vec a = v | v -> a\n -- ^ The type of vectors with coefficients in a.\n type Mat a = m | m -> a\n -- ^ The type of matrices with coefficients in a.\n ident :: Int -> Mat a\n -- ^ Presentation of the identity of the given rank.\n present :: (Integral a', NFData a', Ord c, NFData c) => (b->FreeMod a' c) -> [b] -> [c] -> Mat a\n -- ^ Present a linear map in a matrix form with respect to a given bases\n vecToList :: Vec a -> [a]\n -- ^ Vec a is convertible to a list.\n rankVec :: Vec a -> Int\n -- ^ The rank of the module where the given vector lies.\n rankDom :: Mat a -> Int\n -- ^ The rank of the domain of the given matrix.\n rankCod :: Mat a -> Int\n -- ^ The rank of the codomain of the given matrix.\n fromVecs :: (Foldable t) => t (Vec a) -> Mat a\n -- ^ Give a matrix whose image is spanned by given vectors.\n -- Typically, it is the matrix with given vectors as columns.\n toVecs :: Mat a -> [Vec a]\n -- ^ Give a set of vectors which span the image of the matrix.\n -- Typically, it is the set of column vectors.\n -- ^ The scalar matrix of the given size.\n (@|>) :: Mat a -> Vec a -> Vec a\n -- ^ Multiplication of matrices and vectors.\n scale :: a -> Vec a -> Vec a\n -- ^ Scalar multiplication on vectors.\n scalar :: Int -> a -> Mat a\n -- ^ Scalar * identity matrix.\n -- | Default implementations\n ident n = scalar n 1\n rankVec = length . vecToList\n (@|>) x = head . toVecs . (x<>) . fromVecs . (:[])\n scale x v = scalar (rankVec v) x @|> v\n scalar n x = fromVecs (map (scale x) (toVecs (ident n)))\n\n-- | Matrix presentations with normal forms.\nclass (Coefficient a, NFData (NormalForm a)) => Normalized a where\n data NormalForm a\n -- ^ The type of normal forms.\n fromNF :: NormalForm a -> Mat a\n -- ^ Convert into a matrix form.\n -- >> let xnf = toNF x\n -- Then\n -- >> x <> basisDom xnf == basisCod xnf <> fromNF xnf\n basisDom :: NormalForm a -> Mat a\n -- ^ The basis matrix on the domain.\n -- It should be invertible.\n basisCod :: NormalForm a -> Mat a\n -- ^ The basis matrix on the codomain.\n -- It should be invertible.\n toNF :: Mat a -> NormalForm a\n -- ^ Compute the normal form.\n invariants :: NormalForm a -> [a]\n -- ^ Each normal form should contain the data of \"invariant factors;\" e.g. those for Smith normal forms of matrices with coefficients in a PID.\n\n\n------------------------------------------------\n-- * Instances in terms of LA.Z using hmatrix\n------------------------------------------------\ninstance Coefficient (LA.Z) where\n type Vec LA.Z = LA.Vector LA.Z\n type Mat LA.Z = LA.Matrix LA.Z\n ident = LA.ident\n present f dom cod\n = let domRk = length dom\n codRk = length cod\n in runST $ do\n stMat <- LA.newUndefinedMatrix LA.RowMajor codRk domRk\n forM_ [0..domRk-1] $ \\j -> do\n let !vals = force $ f (dom !!j)\n forM_ [0..codRk-1] $ \\i -> do\n let coeff = getCoeff (cod !! i) vals\n LA.unsafeWriteMatrix stMat i j (fromIntegral coeff)\n LA.unsafeFreezeMatrix stMat\n vecToList = LA.toList\n rankVec = LA.size\n rankDom = LA.cols\n rankCod = LA.rows\n fromVecs = LA.fromColumns . toList\n toVecs = LA.toColumns\n (@|>) = (LA.#>)\n scale = LA.scale\n\ninstance Normalized (LA.Z) where\n -- | Presentation in Smith normal forms.\n data NormalForm LA.Z = SmithNF {\n _invFactor :: LA.Vector LA.Z, -- Invariant factor\n _basisS :: LA.Matrix LA.Z, -- basis for source\n _basisT :: LA.Matrix LA.Z -- basis for target\n } deriving (Show, Generic, NFData)\n fromNF (SmithNF invs bss bts)\n = runST $ do\n stMat <- LA.newMatrix 0 (LA.cols bts) (LA.cols bss)\n forM_ [0..(LA.size invs)-1] $ \\i ->\n LA.writeMatrix stMat i i (invs `LA.atIndex` i)\n LA.unsafeFreezeMatrix stMat\n basisDom = _basisS\n basisCod = _basisT\n toNF x\n = let (u,s,v) = smithRep x\n in SmithNF (LA.takeDiag s) v u\n invariants = LA.toList . _invFactor\n\n---------------------------------\n-- * Instances in terms of F2\n---------------------------------\ninstance Coefficient F2 where\n type Vec F2 = F2.VectorF2\n type Mat F2 = F2.MatrixF2\n ident = F2.ident\n present f dom cod\n = let domRk = length dom\n codRk = length cod\n in runST $ do\n stMat <- F2.unsafeNewMatrixF2 codRk domRk\n forM_ [0..domRk-1] $ \\j -> do\n let !vals = force $ f (dom !!j)\n forM_ [0..codRk-1] $ \\i -> do\n let coeff = getCoeff (cod !! i) vals\n F2.unsafeWriteMatrixF2 stMat i j (fromIntegral coeff :: F2)\n F2.unsafeFreezeMatrixF2 stMat\n vecToList = F2.toList\n rankVec = F2.sizeF2\n rankDom = F2.cols\n rankCod = F2.rows\n fromVecs = F2.fromColumns . toList\n toVecs = F2.toColumns\n scalar = F2.scalar\n\ninstance Normalized F2 where\n data NormalForm F2 =\n DiagNF {-# UNPACK #-} !Int {-# UNPACK #-} !F2.MatrixF2 {-# UNPACK #-} !F2.MatrixF2\n deriving (Show, Generic,NFData)\n invariants (DiagNF rk _ _) = replicate rk 1\n basisDom (DiagNF _ bss _) = bss\n basisCod (DiagNF _ _ bst) = bst\n fromNF (DiagNF rk bss bst) = F2.diagRectL (rankCod bst) (rankCod bss) (repeat 1 :: [Int])\n toNF x\n = let (u,rk,v) = F2.diagRep x\n in DiagNF rk v u\n", "meta": {"hexsha": "c50a2f93e391d33901f447e4fdf9cda952c63cd5", "size": 6277, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Algebra/Presentation.hs", "max_stars_repo_name": "Junology/linkedgram", "max_stars_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-21T06:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:54:21.000Z", "max_issues_repo_path": "src/Numeric/Algebra/Presentation.hs", "max_issues_repo_name": "Junology/linkedgram", "max_issues_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Algebra/Presentation.hs", "max_forks_repo_name": "Junology/linkedgram", "max_forks_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1141304348, "max_line_length": 145, "alphanum_fraction": 0.6216345388, "num_tokens": 1858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5523279144891646}} {"text": "--\n-- FlattenLayer: flatten/unflatten layer\n--\n\nmodule CNN.FlattenLayer (\n flatten\n, unflatten\n) where\n\nimport qualified Numeric.LinearAlgebra as A\n\nimport CNN.Image\nimport CNN.LayerType\n\n{- |\nflatten: flatten image\n\n IN: Image (=[Matrix R])\n\n>>> let im = [A.fromLists [[2.0,3.0],[4.0,5.0]], A.fromLists [[1.0,2.0],[4.0,3.0]], A.fromLists [[2.0,1.0],[6.0,5.0]]]\n>>> flatten im\n[(1><12)\n [ 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 4.0, 3.0, 2.0, 1.0, 6.0, 5.0 ]]\n\n-}\n\nflatten :: Image -> Image\nflatten im = [A.fromLists [concat $ map (A.toList . A.flatten) im]]\n\n{- |\nunflatten: unflatten image\n\n IN: [Matrix R]\n\n>>> let ds = [A.fromLists [[2.0,3.0,4.0,5.0,1.0,2.0,4.0,3.0,2.0,1.0,6.0,5.0]]]\n>>> unflatten 2 2 ds\n[(2><2)\n [ 2.0, 3.0\n , 4.0, 5.0 ],(2><2)\n [ 1.0, 2.0\n , 4.0, 3.0 ],(2><2)\n [ 2.0, 1.0\n , 6.0, 5.0 ]]\n\n-}\n\nunflatten :: Int -> Int -> Image -> Image\nunflatten x y [m] = map (A.reshape x . A.fromList) $ split (y*x) v\n where\n v = A.toList $ A.flatten m\n split :: Int -> [a] -> [[a]]\n split _ [] = []\n split n ds = d : split n ds'\n where\n (d, ds') = splitAt n ds", "meta": {"hexsha": "a2023eed319548287211a323a261f93fdd70c086", "size": 1087, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "CNN/FlattenLayer.hs", "max_stars_repo_name": "eijian/deeplearning", "max_stars_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-30T01:28:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T18:58:17.000Z", "max_issues_repo_path": "CNN/FlattenLayer.hs", "max_issues_repo_name": "eijian/deeplearning", "max_issues_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CNN/FlattenLayer.hs", "max_forks_repo_name": "eijian/deeplearning", "max_forks_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7636363636, "max_line_length": 118, "alphanum_fraction": 0.5409383625, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5520821736890256}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE IncoherentInstances #-}\n\nmodule Test.Utils where\n\nimport Test.Tasty.QuickCheck\nimport Data.Complex\nimport Data.Matrix.Static.LinearAlgebra\nimport Data.Singletons\nimport qualified Data.Matrix.Static.Dense as D\nimport qualified Data.Matrix.Static.Sparse as S\nimport Data.Vector.Storable (Storable)\nimport Data.List.Ordered\nimport qualified Data.Vector as V\nimport Data.Ord\nimport qualified Data.Vector.Generic as G\nimport Data.AEq\nimport Control.Monad\n\nclass Approx a where\n (~=) :: a -> a -> Bool\n infixl 4 ~=\n\ninstance Approx Double where\n a ~= b = abs (a - b) < 1e-10\n\ninstance Approx Float where\n a ~= b = abs (a - b) < 1e-3\n\ninstance Approx (Complex Double) where\n a ~= b = r1 ~= r2 && i1 ~= i2\n where\n (r1, i1) = polar a\n (r2, i2) = polar b\n\ninstance (SingI m, SingI n, G.Vector v Bool, G.Vector v a, Approx a) =>\n Approx (D.Matrix m n v a) where\n m1 ~= m2 = D.all id $ D.zipWith (~=) m1 m2\n\ninstance (G.Vector v a, Arbitrary a, SingI m, SingI n)\n => Arbitrary (D.Matrix m n v a) where\n arbitrary = D.fromList <$> vector (m*n)\n where\n m = fromIntegral $ fromSing (sing :: Sing m)\n n = fromIntegral $ fromSing (sing :: Sing n)\n shrink _v = []\n\ninstance (G.Vector v a, Arbitrary a, SingI m, SingI n, S.Zero a)\n => Arbitrary (S.SparseMatrix m n v a) where\n arbitrary = do\n vals <- filter (/=S.zero) <$> vector p\n xs <- fmap (nubSortBy (comparing fst)) $ forM vals $ \\v -> do\n i <- choose (0, m-1)\n j <- choose (0, n-1)\n return ((i,j),v)\n return $ S.fromTriplet $ V.fromList $ map (\\((a,b),c) -> (a,b,c)) xs\n where\n p = (m * n) `div` 10\n m = fromIntegral $ fromSing (sing :: Sing m)\n n = fromIntegral $ fromSing (sing :: Sing n)\n shrink _v = []", "meta": {"hexsha": "8b964ee0b5ca6116f0707e9a8b1b1d4c074bb168", "size": 2110, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Test/Utils.hs", "max_stars_repo_name": "kaizhang/matrix-sized", "max_stars_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Test/Utils.hs", "max_issues_repo_name": "kaizhang/matrix-sized", "max_issues_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Test/Utils.hs", "max_forks_repo_name": "kaizhang/matrix-sized", "max_forks_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4925373134, "max_line_length": 80, "alphanum_fraction": 0.5943127962, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5519215009165774}} {"text": "module Main where\n\nimport QuickSpec\nimport Test.QuickCheck\nimport Test.QuickCheck.Arbitrary\nimport Test.QuickCheck.Poly(OrdA(..))\nimport Data.List hiding ( insert )\nimport Data.Ord ( comparing )\nimport Data.Complex\n\n{- Simple laws about addition -}\naddSig :: [Sig]\naddSig = [\n con \"+\" ((+) :: Int -> Int -> Int),\n con \"0\" (0 :: Int)\n ]\n\n{- Simple laws about concat and map -}\nconcatMapSig :: [Sig]\nconcatMapSig = [\n con \"map\" (map :: (A -> B) -> [A] -> [B]),\n con \"concat\" (concat :: [[A]] -> [A]),\n con \"concatMap\" (concatMap :: (A -> [B]) -> [A] -> [B]),\n con \"[]\" ([] :: [A]),\n con \":\" ((:) :: A -> [A] -> [A])\n ]\n\n{- Laws about equivalence of two functions -}\nrev :: [a] -> [a]\nrev [] = []\nrev (x:xs) = rev xs ++ [x]\n\nrevAcc :: [a] -> [a]\nrevAcc = aux []\n where\n aux acc [] = acc\n aux acc (x:xs) = aux (x:acc) xs\n\nrevSig :: [Sig]\nrevSig = [\n con \"rev\" (rev :: [A] -> [A]),\n con \"revAcc\" (revAcc :: [A] -> [A]),\n con \"[]\" ([] :: [A])\n ]\n\n{- Laws about sortedness -}\nsorted :: Ord a => [a] -> Bool \nsorted [] = True \nsorted [x] = True \nsorted (x:y:xs) = x <= y && sorted (y:xs)\n\nsortedSig :: [Sig]\nsortedSig = [\n predicate \"sorted\" (sorted :: [Int] -> Bool),\n background [\n predicate \"<\" ((<) :: Int -> Int -> Bool),\n prelude\n ]\n ]\n\n{- Many, many laws about foldr -}\nfoldrSig :: [Sig]\nfoldrSig = [\n con \"foldr\" (foldr :: (A -> B -> B) -> B -> [A] -> B),\n background [\n con \"length\" (length :: [A] -> Int),\n con \"const\" (const :: A -> B -> A),\n con \"+\" ((+) :: Int -> Int -> Int),\n con \"1\" (1 :: Int),\n con \"0\" (0 :: Int)\n ]\n ]\n\n{- Custom datatypes similar to https://github.com/nick8325/quickspec/blob/master/examples/Heaps.hs -}\ndata Tree a = Leaf | Node (Tree a) a (Tree a) deriving Typeable\n\ninstance Eq a => Eq (Tree a) where\n t1 == t2 = inorder t1 == inorder t2\n\ninstance Ord a => Ord (Tree a) where\n compare = comparing inorder\n\ninstance (Ord a, Arbitrary a) => Arbitrary (Tree a) where\n arbitrary = fromList <$> arbitrary\n\ninorder :: Tree a -> [a]\ninorder Leaf = []\ninorder (Node l v r) = inorder l ++ [v] ++ inorder r\n\nfromList :: Ord a => [a] -> Tree a\nfromList = foldr insert Leaf\n\ninsert :: Ord a => a -> Tree a -> Tree a \ninsert v Leaf = Node Leaf v Leaf\ninsert v (Node l vt r)\n | v <= vt = Node (insert v l) vt r\n | otherwise = Node l vt (insert v r)\n\nmirror :: Tree a -> Tree a\nmirror Leaf = Leaf\nmirror (Node l v r) = Node (mirror r) v (mirror l)\n\n{- Some laws on trees -}\ntreeSig1 :: [Sig]\ntreeSig1 = [\n monoType (Proxy :: Proxy OrdA),\n monoTypeWithVars [\"t\", \"t1\", \"t2\"] (Proxy :: Proxy (Tree OrdA)),\n monoTypeWithVars [\"t\", \"t1\", \"t2\"] (Proxy :: Proxy (Tree Int)),\n con \"mirror\" (mirror :: Tree OrdA -> Tree OrdA),\n con \"rev\" (rev :: [OrdA] -> [OrdA]),\n con \"fromList\" (fromList :: [OrdA] -> Tree OrdA),\n con \"insert\" (insert :: OrdA -> Tree OrdA -> Tree OrdA)\n ]\n\n{- A real challenge... -}\ntreeSig2 :: [Sig]\ntreeSig2 = [\n monoTypeWithVars [\"a\", \"b\", \"c\"] (Proxy :: Proxy OrdA),\n monoTypeWithVars [\"t\", \"t1\", \"t2\"] (Proxy :: Proxy (Tree OrdA)),\n monoTypeWithVars [\"t\", \"t1\", \"t2\"] (Proxy :: Proxy (Tree Int)),\n con \"fromList\" (fromList :: [OrdA] -> Tree OrdA),\n con \"inorder\" (inorder :: Tree OrdA -> [OrdA]),\n predicate \"sorted\" (sorted :: [OrdA] -> Bool)\n ]\n\n{- A \"complex\" example... observational equivalence -}\ncomplexSig :: [Sig]\ncomplexSig = [\n monoTypeObserve (Proxy :: Proxy Float),\n --monoType (Proxy :: Proxy (Complex Int)),\n monoTypeObserve (Proxy :: Proxy (Complex Float)),\n con \"realPart\" (realPart :: Complex Float -> Float),\n con \"imagPart\" (imagPart :: Complex Float -> Float),\n con \":+\" ((:+) :: Float -> Float -> Complex Float),\n background [ prelude ]\n ]\n\nmain :: IO ()\nmain = return ()\n", "meta": {"hexsha": "463f607bd36587d6e5683e85c57c7ec8a6ef99a4", "size": 3708, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "phagenlocher/quickspec-examples", "max_stars_repo_head_hexsha": "3725bec6bc8ec5158f44648b6fda3244f074f063", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "phagenlocher/quickspec-examples", "max_issues_repo_head_hexsha": "3725bec6bc8ec5158f44648b6fda3244f074f063", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main.hs", "max_forks_repo_name": "phagenlocher/quickspec-examples", "max_forks_repo_head_hexsha": "3725bec6bc8ec5158f44648b6fda3244f074f063", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4857142857, "max_line_length": 101, "alphanum_fraction": 0.5671521036, "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5519214826928036}} {"text": "{-# LANGUAGE NoMonomorphismRestriction #-}\nimport Numeric.LinearAlgebra\nimport Linear.V1\nimport Linear.V2\nimport Linear.V3\nimport Linear.Quaternion\nimport Linear.Matrix\nimport Vectorization\nimport Space \nimport Kalman\n\n\n-- Aided Inertial Navigation -- Example 5.4\n\npe0 = (V2 (V2 100 0) (V2 0 100))\nxe0 = V2 0 0\nse0 = (xe0,pe0)\n\n\nhe0 (V2 x _) = V1 x\nhe1 (V2 _ y) = V1 y\nhe2 (V2 x y) = V1 (x*0.7 + 0.3*y)\nhe3 (V2 x y) = V1 (x*0.5 + y*0.5)\n\nm0 = (he0,re0,ye0)\nm1 = (he1,re1,ye1)\nm2 = (he2,re2,ye2)\nm3 = (he3,re3,ye3)\n\nmlist = [m0,m1,m2,m3]\n\nre0 = V1 1\nre1 = V1 1\nre2 = V1 1\nre3 = V1 1\n\nye0 = V1 10.24\nye1 = V1 21.20\nye2 = V1 13.91\nye3 = V1 14.84\n\nmeasure' (h,r,y) = measure h r y\nsef = foldr measure' se0 mlist\n\nse1 = measure he0 re0 ye0 se0\nse2 = measure he1 re1 ye1 se1\nse3 = measure he2 re2 ye2 se2\nse4 = measure he3 re3 ye3 se3\n\n\n", "meta": {"hexsha": "298598fd23c133e24e2441891a267f8b8b2899b9", "size": 831, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "example/Sample1.hs", "max_stars_repo_name": "massudaw/mtk", "max_stars_repo_head_hexsha": "c74570b02d3806f6690c57767e8e717e3d02a1ff", "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": "example/Sample1.hs", "max_issues_repo_name": "massudaw/mtk", "max_issues_repo_head_hexsha": "c74570b02d3806f6690c57767e8e717e3d02a1ff", "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": "example/Sample1.hs", "max_forks_repo_name": "massudaw/mtk", "max_forks_repo_head_hexsha": "c74570b02d3806f6690c57767e8e717e3d02a1ff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2941176471, "max_line_length": 43, "alphanum_fraction": 0.6570397112, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5515036317264067}} {"text": "{-# LANGUAGE ScopedTypeVariables, TypeFamilies #-}\n\nmodule Fuml.Supervised where\n\nimport qualified Fuml.Base.LinearRegression as LR\nimport Fuml.Core\nimport Numeric.LinearAlgebra\nimport Control.Monad.Identity\n\nnewtype Beta = Beta { unBeta :: Vector Double }\n\nols :: Supervisor Identity Double Beta Double\nols = Supervisor $ \\_ theData ->\n let beta = LR.ols theData\n in return $ linPredict beta\n\ntype Weight = Double\n\nolsWeighted :: Supervisor Identity (Double, Weight) Beta Double\nolsWeighted\n = Supervisor $ \\_ theDataW ->\n let wvs = fromList $ map (\\(_,(_,w)) -> w) theDataW\n theData = map (\\(xs,(y,_)) -> (xs,y)) theDataW\n beta = LR.wols wvs theData\n in return $ linPredict beta\n\nridge :: Double -> Supervisor Identity Double Beta Double\nridge gammac = Supervisor $ \\_ xys ->\n let npars = size $ fst $ head xys\n gamma = diag $ konst gammac npars\n beta = LR.ridge gamma xys\n in return $ linPredict beta\n\nlinPredict :: Vector Double -> Predict Beta Double\nlinPredict beta = Predict (Beta beta) (`dot` beta)\n", "meta": {"hexsha": "71c0eb086c710452c64c8fa7d61a15e71fd3f2d0", "size": 1107, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "fuml/lib/Fuml/Supervised.hs", "max_stars_repo_name": "ekalosak/open", "max_stars_repo_head_hexsha": "9faadba7614fc9d9448f1d3000c58cc3e93a8a36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 81, "max_stars_repo_stars_event_min_datetime": "2017-05-22T22:42:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T10:41:20.000Z", "max_issues_repo_path": "fuml/lib/Fuml/Supervised.hs", "max_issues_repo_name": "ekalosak/open", "max_issues_repo_head_hexsha": "9faadba7614fc9d9448f1d3000c58cc3e93a8a36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2017-05-31T09:06:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-18T12:00:27.000Z", "max_forks_repo_path": "fuml/lib/Fuml/Supervised.hs", "max_forks_repo_name": "ekalosak/open", "max_forks_repo_head_hexsha": "9faadba7614fc9d9448f1d3000c58cc3e93a8a36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2017-05-22T15:39:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:26:20.000Z", "avg_line_length": 30.75, "max_line_length": 65, "alphanum_fraction": 0.6603432701, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5514452393150836}} {"text": "{-|\n\nCopyright:\n This file is part of the package zxcvbn-hs. It is subject to the\n license terms in the LICENSE file found in the top-level directory\n of this distribution and at:\n\n https://code.devalot.com/sthenauth/zxcvbn-hs\n\n No part of this package, including this file, may be copied,\n modified, propagated, or distributed except according to the terms\n contained in the LICENSE file.\n\nLicense: MIT\n\n-}\nmodule Text.Password.Strength.Internal.Math\n ( variations\n , variations'\n , bruteForce\n , caps\n ) where\n\n--------------------------------------------------------------------------------\n-- Library Imports:\nimport Control.Lens ((^.))\nimport Data.Char (isUpper)\nimport qualified Data.Text as Text\nimport Numeric.SpecFunctions (choose)\n\n--------------------------------------------------------------------------------\n-- Project Imports:\nimport Text.Password.Strength.Internal.Token\n\n--------------------------------------------------------------------------------\n-- | Equation 2, section 4, page 163 (8/18)\n--\n-- NOTE: The other implementations don't seem to divide the sum by two\n-- but the equation in the paper clearly does.\nvariations :: Int -> Int -> Integer\nvariations 0 _ = 1\nvariations _ 0 = 1\nvariations u l = max 1 (sum (floor . choose (u+l) <$> [1 .. min u l]) `div` 2)\n\n--------------------------------------------------------------------------------\n-- | Like equation 2, but modified for l33t and keyboard variations.\n--\n-- This equation does not appear in the 2016 paper although it is\n-- mentioned. Therefore it was adapted from the CoffeeScript and\n-- Python implementations.\nvariations' :: Int -> Int -> Integer\nvariations' 0 _ = 2\nvariations' _ 0 = 2\nvariations' u l = variations u l\n\n--------------------------------------------------------------------------------\n-- | Calculate the brute force score for text with the given length.\nbruteForce :: Int -> Integer\nbruteForce = (10 ^)\n\n--------------------------------------------------------------------------------\n-- | Score the use of uppercase letters according to the paper. This\n-- is specified in the paragraph preceding equation 2.\ncaps :: Token -> Integer -> Integer\ncaps token n =\n let text = token ^. tokenChars\n upper = Text.length (Text.filter isUpper text)\n lower = Text.length text - upper\n allLower = lower == Text.length text\n allUpper = lower == 0\n firstUpper = upper == 1 && Text.all isUpper (Text.take 1 text)\n lastUpper = upper == 1 && Text.all isUpper (Text.takeEnd 1 text)\n in case () of\n () | allLower -> n\n | firstUpper -> n * 2\n | lastUpper -> n * 2\n | allUpper -> n * 2\n | otherwise -> n * variations upper lower\n\n--------------------------------------------------------------------------------\n-- NOTE: Equation 3 is in Keybaord.hs.\n", "meta": {"hexsha": "ebb2caceee8b91a244e9407d2d6f7a0d1af00017", "size": 2845, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Text/Password/Strength/Internal/Math.hs", "max_stars_repo_name": "k0001/zxcvbn-hs", "max_stars_repo_head_hexsha": "07a224794f0299e4c066056841485e2d86d8b075", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-12T14:59:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-12T14:59:31.000Z", "max_issues_repo_path": "src/Text/Password/Strength/Internal/Math.hs", "max_issues_repo_name": "k0001/zxcvbn-hs", "max_issues_repo_head_hexsha": "07a224794f0299e4c066056841485e2d86d8b075", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-12-09T13:14:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T14:50:32.000Z", "max_forks_repo_path": "src/Text/Password/Strength/Internal/Math.hs", "max_forks_repo_name": "k0001/zxcvbn-hs", "max_forks_repo_head_hexsha": "07a224794f0299e4c066056841485e2d86d8b075", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-26T14:39:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T14:31:02.000Z", "avg_line_length": 34.6951219512, "max_line_length": 80, "alphanum_fraction": 0.5413005272, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5511743935830801}} {"text": "module Main where\n\n--import Data.Complex\nimport Graphics.Gloss\nimport Data.Complex\nimport Data.Ratio\nimport Fractals\n\nwindow :: Display\nwindow = InWindow \"Mandelbrot set\" (1000, 600) (10, 10)\n\nbackground :: Color\nbackground = black\n\ndrawing :: Complex Double -> Picture\n--drawing = bmp 1000 600 (((-0.1011):+0.9563)::Complex Double) 0.0000001\ndrawing z0 = bmp 1000 600 z0 0.0001\n\nmain :: IO ()\n--main = print $ order (mandelbrot ((-1.6) :+ 0.0)) (2.0::Double) 256 (0.0 :+ 0.0)\nmain = print point >> (display window background $ drawing point)\n where point = (tangentPoint (9 % 17))::Complex Double\n", "meta": {"hexsha": "6105d50af57378dc69e4234ba755cf22bec3bdc1", "size": 601, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "arekfu/fractals-haskell", "max_stars_repo_head_hexsha": "7e71fafa64738e7382f459adea79d9fb1f54a3f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "arekfu/fractals-haskell", "max_issues_repo_head_hexsha": "7e71fafa64738e7382f459adea79d9fb1f54a3f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "arekfu/fractals-haskell", "max_forks_repo_head_hexsha": "7e71fafa64738e7382f459adea79d9fb1f54a3f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1304347826, "max_line_length": 82, "alphanum_fraction": 0.690515807, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5505366491754268}} {"text": "{-# LANGUAGE TypeFamilies #-}\nmodule Data.Running\n ( Coord (Coord)\n , PointRecord (PointRecord)\n , pointDistance\n , pointCoord\n , pointLat\n , pointLng\n , pointTime\n , pointSpeed\n) where\nimport Data.Time.Clock (UTCTime)\nimport Data.Time.Format ()\nimport Statistics.Sample (mean, stdDev)\nimport Data.AdditiveGroup\nimport Data.VectorSpace\n\nnewtype Coord = Coord (Double, Double) deriving (Eq, Ord, Show)\n\ndata PointRecord = PointRecord\n { pointTime :: UTCTime\n , pointCoord :: Coord\n , pointDistance :: Double\n , pointSpeed :: Double\n } deriving (Eq, Ord, Show)\n\npointLat (PointRecord _ (Coord (a, _)) _ _) = a\npointLng (PointRecord _ (Coord (_, b)) _ _) = b\n\ninstance AdditiveGroup Coord where\n zeroV = Coord (0, 0)\n Coord (a, b) ^+^ Coord (c, d) = Coord (a + c, b + d)\n negateV (Coord (a, b)) = Coord (-a, -b)\n\ninstance InnerSpace Coord where\n Coord (a, b) <.> Coord (c, d) = a * c + b * d\n\ninstance VectorSpace Coord where\n type Scalar Coord = Double\n s *^ Coord (a, b) = Coord (s * a, s * b)\n\n\n--instance VectorSpace PointRecord where\n-- type Scalar = \n\n", "meta": {"hexsha": "1a2cc3f70415cc60e008415b789a7509b27610ab", "size": 1076, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Running.hs", "max_stars_repo_name": "peter-th3-great/metaplasm", "max_stars_repo_head_hexsha": "7a2b14c627bc123810037241b663d2a0ff4d5660", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/Running.hs", "max_issues_repo_name": "peter-th3-great/metaplasm", "max_issues_repo_head_hexsha": "7a2b14c627bc123810037241b663d2a0ff4d5660", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/Running.hs", "max_forks_repo_name": "peter-th3-great/metaplasm", "max_forks_repo_head_hexsha": "7a2b14c627bc123810037241b663d2a0ff4d5660", "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": 23.3913043478, "max_line_length": 63, "alphanum_fraction": 0.6635687732, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5504550587365716}} {"text": "module Impulse.Impulse where\n\nimport Control.Monad as M\nimport Control.Monad.Parallel as MP\nimport Data.Array.Repa as R\nimport Data.Binary\nimport Data.Complex\nimport Data.List as L\nimport DFT.Plan\nimport Filter.Utils\nimport FokkerPlanck.DomainChange\nimport FokkerPlanck.MonteCarlo\nimport FokkerPlanck.Pinwheel\nimport Image.IO\nimport STC.CompletionField\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Text.Printf\nimport Types\nimport Utils.Array\n\nmain = do\n args@(numPointStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:taoStr:numTrailStr:maxTrailStr:theta0FreqsStr:thetaFreqsStr:scale0FreqsStr:scaleFreqsStr:initDistStr:histFilePath:alphaStr:pinwheelFlagStr:numThreadStr:_) <-\n getArgs\n print args\n let numPoint = read numPointStr :: Int\n numOrientation = read numOrientationStr :: Int\n numScale = read numScaleStr :: Int\n thetaSigma = read thetaSigmaStr :: Double\n scaleSigma = read scaleSigmaStr :: Double\n maxScale = read maxScaleStr :: Double\n tao = read taoStr :: Double\n numTrail = read numTrailStr :: Int\n maxTrail = read maxTrailStr :: Int\n theta0Freq = read theta0FreqsStr :: Double\n theta0Freqs = [-theta0Freq .. theta0Freq]\n thetaFreq = read thetaFreqsStr :: Double\n thetaFreqs = [-thetaFreq .. thetaFreq]\n initDist = read initDistStr :: [R2S1RPPoint]\n scale0Freq = read scale0FreqsStr :: Double\n scaleFreq = read scaleFreqsStr :: Double\n scale0Freqs = [-scale0Freq .. scale0Freq]\n scaleFreqs = [-scaleFreq .. scaleFreq]\n alpha = read alphaStr :: Double\n pinwheelFlag = read pinwheelFlagStr :: Bool\n numThread = read numThreadStr :: Int\n sourceDist = L.take 1 initDist\n sinkDist = L.drop 1 initDist\n folderPath = \"output/test/Impulse\"\n (R2S1RPPoint (_, _, _, s)) = L.head sourceDist\n flag <- doesFileExist histFilePath\n radialArr <-\n if flag\n then R.map magnitude . getNormalizedHistogramArr <$>\n decodeFile histFilePath\n else do\n putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n solveMonteCarloR2Z2T0S0Radial\n numThread\n numTrail\n maxTrail\n numPoint\n numPoint\n thetaSigma\n scaleSigma\n maxScale\n tao\n theta0Freqs\n thetaFreqs\n scale0Freqs\n scaleFreqs\n histFilePath\n (emptyHistogram\n [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n , L.length scale0Freqs\n , L.length theta0Freqs\n , L.length scaleFreqs\n , L.length thetaFreqs\n ]\n 0)\n arrR2Z2T0S0 <-\n computeUnboxedP $\n computeR2Z2T0S0ArrayRadial\n radialArr\n numPoint\n numPoint\n 1\n maxScale\n thetaFreqs\n scaleFreqs\n theta0Freqs\n scale0Freqs\n createDirectoryIfMissing True folderPath\n let arr4d =\n R.slice\n arrR2Z2T0S0\n (Z :. All :. All :. (L.length theta0Freqs - 1) :.\n (L.length scale0Freqs - 1) :.\n All :.\n All)\n createDirectoryIfMissing True (folderPath \"GreensR2Z2T0S0\")\n -- MP.mapM_\n -- (\\(i, j) ->\n -- plotImageRepaComplex\n -- (folderPath \"GreensR2Z2T0S0\" show (i + 1) L.++ \"_\" L.++\n -- show (j + 1) L.++\n -- \".png\") .\n -- ImageRepa 8 .\n -- computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.slice arr4d $\n -- (Z :. i :. j :. All :. All))\n -- [ (i, j)\n -- | i <- [0 .. (L.length thetaFreqs) - 1]\n -- , j <- [0 .. (L.length scaleFreqs) - 1]\n -- ]\n plan <- makeR2Z2T0S0Plan emptyPlan arrR2Z2T0S0\n sourceDistArr <-\n computeInitialDistributionR2T0S0\n plan\n numPoint\n numPoint\n theta0Freqs\n scale0Freqs\n maxScale\n -- initDist\n sourceDist\n arrR2Z2T0S0F <- dftR2Z2T0S0 plan . computeS . makeFilter2D $ arrR2Z2T0S0\n -- Source field\n sourceArr <- convolveR2T0S0 plan arrR2Z2T0S0F sourceDistArr\n sourceR2Z2 <- R.sumP . R.sumS . rotateR2Z2T0S0Array $ sourceArr\n sourceField <-\n fmap (computeS . R.extend (Z :. (1 :: Int) :. All :. All)) .\n R.sumP .\n R.sumS .\n rotate4D .\n rotate4D . r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs $\n sourceR2Z2\n plotImageRepaComplex (folderPath printf \"Source%.0f.png\" s) . ImageRepa 8 $\n sourceField\n", "meta": {"hexsha": "8f294e41073df28c48a25d8c74bc274272a085d9", "size": 4674, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Impulse/Impulse.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Impulse/Impulse.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/Impulse/Impulse.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 33.3857142857, "max_line_length": 247, "alphanum_fraction": 0.6009841677, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5504550567539938}} {"text": "module CNC.IntegrationTests where\n\nimport CNC.Declarative\nimport CNC.HCode\n\nimport Data.Complex\nimport Control.Monad\n\nflake_side = do\n [p1,p2,p3,p4,p5] <- declarePoints 5\n xSize p1 p2 1\n len p2 p3 1\n len p3 p4 1\n xAngle p2 p3 (pi / 3)\n xAngle p3 p4 (- pi / 3)\n xSize p4 p5 1\n\nrenderPolygon :: Int -> Path -> HCode ()\nrenderPolygon n path = render_side 0 path n\n where\n render_side p0 path 0 = return ()\n render_side p0 path k = do\n let d = deltaPath path\n renderPath (posToExpr p0) path\n render_side (p0 + d) (rotate (- 2*pi / fromIntegral n) path) (k-1)\n\ntest1 = do putStrLn \"a snowflake\"\n print $ (figure flake_side)\n putHCode $ renderPolygon 3 (figure flake_side)\n\nintegrationTests = do\n putStrLn \"Integration tests\"\n test1", "meta": {"hexsha": "c83274f8fe6efc6acfd97496155a5b620c785ffa", "size": 777, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/CNC/IntegrationTests.hs", "max_stars_repo_name": "akamaus/gcodec", "max_stars_repo_head_hexsha": "cd515673f408f24d4d92fc85246611c21a4ef433", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/CNC/IntegrationTests.hs", "max_issues_repo_name": "akamaus/gcodec", "max_issues_repo_head_hexsha": "cd515673f408f24d4d92fc85246611c21a4ef433", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/CNC/IntegrationTests.hs", "max_forks_repo_name": "akamaus/gcodec", "max_forks_repo_head_hexsha": "cd515673f408f24d4d92fc85246611c21a4ef433", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5454545455, "max_line_length": 72, "alphanum_fraction": 0.6705276705, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5501526075553023}} {"text": "{-# OPTIONS_GHC -Wall #-}\nmodule Diagrams.Spirograph\n ( Spiro(Spiro)\n , drawSpiros\n , drawSpirosIntermediate\n ) where\n\nimport Data.Complex (Complex(..), mkPolar)\nimport Diagrams.Prelude (Diagram, P2)\nimport qualified Diagrams.Backend.SVG.CmdLine as SVG\nimport qualified Diagrams.Prelude as D\nimport Data.Monoid (Sum(..))\n\ndata Spiro = Spiro\n { offset \u2237 Double\n , speed \u2237 Double\n }\n\nnewtype Path w = Path (Double \u2192 w)\n\nderiving newtype instance Semigroup w \u21d2 Semigroup (Path w)\nderiving newtype instance Monoid w \u21d2 Monoid (Path w)\n\nnewtype P = P (Sum (P2 Double))\n\nrunP \u2237 P \u2192 P2 Double\nrunP (P (Sum p)) = p\n\nderiving newtype instance Semigroup P\nderiving newtype instance Monoid P\n\n-- | @'disk' d@ is the path that @d@ will travel.\ndisk \u2237 Spiro \u2192 Path P\ndisk Spiro{..} = Path $ \\t \u2192 P $ Sum $ p2 $ mkPolar offset (speed * t)\n\ndisks \u2237 [Spiro] \u2192 Path P\ndisks = foldMap disk\n\nallSpiros \u2237 [Spiro] \u2192 [Path P]\nallSpiros = \\case\n [] \u2192 mempty\n (x:xs) \u2192 px : map f pxs\n where\n px = disk x\n pxs = allSpiros xs\n f \u2237 Path P \u2192 Path P\n f p = px <> p\n\n-- | Form a point in diagrams in terms of a complex number.\np2 \u2237 Complex a \u2192 P2 a\np2 (x :+ y) = D.p2 (x, y)\n\n-- | Convert a path into a path.\nsample \u2237 Path P \u2192 [P2 Double]\nsample (Path f) = runP . f <$> enumFromThenTo 0 0.1 100\n\ndrawSpiros \u2237 [Spiro] \u2192 Diagram SVG.B\ndrawSpiros xs = D.fromVertices $ sample (disks xs)\n\ndrawSpirosIntermediate \u2237 [Spiro] \u2192 Diagram SVG.B\ndrawSpirosIntermediate xs = foldMap step (allSpiros xs)\n where\n step p = D.fromVertices $ sample p\n", "meta": {"hexsha": "84af0ea9701c2d00cec2202179611161dacd2e32", "size": 1629, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Diagrams/Spirograph.hs", "max_stars_repo_name": "fredefox/spirograph", "max_stars_repo_head_hexsha": "7dceb6df97d6945d7392c20de5c0318d47e54771", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-22T22:54:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-22T22:54:09.000Z", "max_issues_repo_path": "src/Diagrams/Spirograph.hs", "max_issues_repo_name": "fredefox/spirograph", "max_issues_repo_head_hexsha": "7dceb6df97d6945d7392c20de5c0318d47e54771", "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/Diagrams/Spirograph.hs", "max_forks_repo_name": "fredefox/spirograph", "max_forks_repo_head_hexsha": "7dceb6df97d6945d7392c20de5c0318d47e54771", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.453125, "max_line_length": 70, "alphanum_fraction": 0.62737876, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5501027736643033}} {"text": "{-# LANGUAGE LambdaCase #-}\n\nmodule Statistics.Quantile.Approximate.Sampling (\n sampling\n , samplingJackknife\n) where\n\nimport Control.Applicative\nimport Control.Monad.IO.Class\n\nimport qualified Data.List.Ordered as Bag\nimport Data.Monoid\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector.Unboxed as V\n\nimport Pipes\nimport qualified Pipes.Prelude as P\n\nimport qualified Statistics.Quantile as Q\nimport Statistics.Resampling\nimport Statistics.Types\nimport Statistics.Sample\n\nimport Statistics.Quantile.Types\nimport Statistics.Quantile.Util\n\nimport System.Random.MWC\n\ndata Jackknife = Jackknifed | NotJackknifed\n deriving (Eq, Show)\n\nsampling :: Int\n -> Int\n -> Selector IO\nsampling k n = Selector $ sampling' NotJackknifed k n\n\nsamplingJackknife :: Int\n -> Int\n -> Selector IO\nsamplingJackknife k n = Selector $ sampling' Jackknifed k n\n\n\n-- FIXME: this breaks at 'select' with low probability.\n-- FIXME: fold with something stricter than a tuple\nsampling' :: Jackknife\n -> Int\n -> Int\n -> Quantile\n -> Stream IO\n -> IO Double\nsampling' j k n q (Stream src) = withSystemRandom $ \\gen -> do\n P.foldM (sample gen) (pure ([],0)) (finalize j) src\n where choose :: GenIO -> IO Bool\n choose g = choose' <$> uniformR (0.0, invP) g\n \n choose' :: Double -> Bool\n choose' x\n | x < 1.0 = True\n | otherwise = False\n\n -- 1/P(choose)\n invP :: Double\n invP = (fromIntegral n) / (fromIntegral k)\n\n sample :: GenIO -> ([Double], Int) -> Double -> IO ([Double], Int)\n sample g (vs,c) v = choose g >>= \\case\n True -> let vs' = Bag.insertBag v vs in\n pure (vs', c+1)\n False -> pure (vs,c)\n\n finalize NotJackknifed (vs, c) = pure $ vs !! (qidx q c)\n finalize Jackknifed (vs, _) = pure . estimateQ median $ jackknife (Function $ estimateQ q) $ V.fromList vs\n\nestimateQ :: Quantile -> (Vector Double) -> Double\nestimateQ (Quantile k n) = Q.weightedAvg k n\n", "meta": {"hexsha": "7944abf385e46e27650b9f3f816dc7d4f2ac84ac", "size": 2080, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "2015-08-26-fp-syd-approx-quantiles/approx-quantile/src/Statistics/Quantile/Approximate/Sampling.hs", "max_stars_repo_name": "fractalcat/slides", "max_stars_repo_head_hexsha": "338db16c6998dc4add9d1ebd511b3faf3a4420dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2015-08-26-fp-syd-approx-quantiles/approx-quantile/src/Statistics/Quantile/Approximate/Sampling.hs", "max_issues_repo_name": "fractalcat/slides", "max_issues_repo_head_hexsha": "338db16c6998dc4add9d1ebd511b3faf3a4420dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2015-08-26-fp-syd-approx-quantiles/approx-quantile/src/Statistics/Quantile/Approximate/Sampling.hs", "max_forks_repo_name": "fractalcat/slides", "max_forks_repo_head_hexsha": "338db16c6998dc4add9d1ebd511b3faf3a4420dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3684210526, "max_line_length": 114, "alphanum_fraction": 0.6274038462, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5500969766601183}} {"text": "{-# LANGUAGE DataKinds #-}\n\nmodule Matrix\n ( Matrix4\n , Vector3\n , vec3\n , perspective\n , identity\n , withFloatMatrix\n , translate\n , projection\n , normalize\n , xHat\n , yHat\n , zHat\n , cross\n , vector3ToFloatList\n , unwrap\n ) where\n\nimport Data.Maybe\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport qualified Numeric.LinearAlgebra as L\nimport qualified Numeric.LinearAlgebra.Devel as D\nimport Numeric.LinearAlgebra.Static\n\ntype Matrix4 = L 4 4\n\ntype Vector3 = R 3\n\nxHat = vec3 1 0 0\n\nyHat = vec3 0 1 0\n\nzHat = vec3 0 0 1\n\n--type Matrix4 = Matrix4 Double\nperspective :: Double -> Double -> Double -> Double -> Matrix4\nperspective near far fov aspect = build gen\n where\n gen i j =\n case (i, j) of\n (0, 0) -> 1.0 / (aspect * tan (fov / 2.0))\n (1, 1) -> 1.0 / tan (fov / 2.0)\n (2, 2) -> -(far + near) / (far - near)\n (2, 3) -> -2.0 * far * near / (far - near)\n (3, 2) -> -1.0\n _ -> 0.0\n\nidentity :: Matrix4\nidentity = eye\n\ntranslate :: Vector3 -> Matrix4\ntranslate v = t ||| col (v & 1.0)\n where\n (t, _) = splitCols eye\n\nprojection :: Double -> Matrix4\nprojection = perspective 0.1 10000.0 (pi / 4.0)\n\nwithFloatMatrix ::\n Matrix4 -> (D.MatrixOrder -> CInt -> CInt -> Ptr Float -> IO r) -> IO r\nwithFloatMatrix m f = D.applyRaw singleM id (f (D.orderOf singleM))\n where\n singleM = L.single $ unwrap m\n\nwithFloatVector :: Vector3 -> (CInt -> Ptr Float -> IO r) -> IO r\nwithFloatVector m = D.applyRaw singleV id\n where\n singleV = L.single $ unwrap m\n\n--normalize :: Vector3 -> Vector3\nnormalize v = realToFrac a * v\n where\n a = 1.0 / norm_2 v\n\nvector3ToFloatList :: Vector3 -> [Float]\nvector3ToFloatList = L.toList . L.single . unwrap\n", "meta": {"hexsha": "56172c6f4b77f400107ba20304e6cdd407d71501", "size": 1769, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Matrix.hs", "max_stars_repo_name": "aelg/haskell-render", "max_stars_repo_head_hexsha": "c55fd2e3cfde1899b03910545b835935fef62759", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Matrix.hs", "max_issues_repo_name": "aelg/haskell-render", "max_issues_repo_head_hexsha": "c55fd2e3cfde1899b03910545b835935fef62759", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Matrix.hs", "max_forks_repo_name": "aelg/haskell-render", "max_forks_repo_head_hexsha": "c55fd2e3cfde1899b03910545b835935fef62759", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1125, "max_line_length": 76, "alphanum_fraction": 0.6048615037, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5500969714716367}} {"text": "{-# LANGUAGE DataKinds\n , GADTs\n , KindSignatures\n , OverloadedLists\n , ScopedTypeVariables\n , TypeApplications #-}\n\nmodule MorphGine.Data.Primitives where\n\nimport qualified Data.Vector.Storable as VS\nimport qualified Numeric.LinearAlgebra as L\nimport Numeric.LinearAlgebra ((><))\nimport qualified Numeric.LinearAlgebra.Data as DL --(flatten, reshape,cmap)\nimport GHC.Ptr (Ptr(..))\nimport GHC.TypeLits\nimport qualified Graphics.Rendering.OpenGL.GL as GL\nimport Graphics.Rendering.OpenGL.GL (($=))\nimport qualified Graphics.GL as GLRaw\nimport Graphics.GL (GLfloat)\n\ndata Matrix :: * -> Nat -> Nat -> * where\n M :: VS.Storable a => L.Matrix a -> Matrix a m n\n\nwithPtr :: (VS.Storable a, L.Element a) => Matrix a m n -> (Ptr a -> IO b) -> IO b\nwithPtr (M x) = VS.unsafeWith . L.flatten $ x\n\nprojection :: GLfloat -> GLfloat -> GLfloat -> GLfloat -> Matrix GLfloat 4 4\nprojection fov aspect near far = M . (4><4) $ [ t/aspect, 0, 0, 0\n , 0, t, 0, 0\n , 0, 0, (far+near)/(near-far), (2*far*near)/(near-far)\n , 0, 0,-1, 0]\n where t = 1 / tan (fov/2)\n\ndegProjection :: GLfloat -> GLfloat -> GLfloat -> GLfloat -> Matrix GLfloat 4 4\ndegProjection = projection . (/180) . (*pi)\n", "meta": {"hexsha": "1342082ce7a10275d9eeec9a216d0941f8154f70", "size": 1431, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MorphGine/Data/Primitives.hs", "max_stars_repo_name": "Antystenes/CPG", "max_stars_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MorphGine/Data/Primitives.hs", "max_issues_repo_name": "Antystenes/CPG", "max_issues_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MorphGine/Data/Primitives.hs", "max_forks_repo_name": "Antystenes/CPG", "max_forks_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.75, "max_line_length": 108, "alphanum_fraction": 0.5583508036, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5500070477277238}}