{"text": "{-\nmodule Solve\n ( Ord\n , DoubleMap\n , innerKeys\n , toMatrix\n , toMatrix'\n , trans\n , solve\n , smartSolve ) where\n-}\nmodule Solve where\n\nimport Data.List (elemIndex, nub, sort, union, (\\\\))\nimport Data.List.Extra (groupSortOn)\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as M\nimport Data.Maybe (catMaybes, mapMaybe)\nimport Data.Tuple (swap)\nimport Numeric.LinearAlgebra\n\ntype DoubleMap k l a = Map k (Map l a)\n\npullMaybe :: Monad m => (m a, m b) -> m (a, b)\npullMaybe = (>>= (fmap swap . sequence . swap)) . sequence\n\ninnerKeys :: Eq l => DoubleMap k l a -> [l]\ninnerKeys = nub . concatMap M.keys . M.elems\n\nkeyToInt :: Ord k => k -> DoubleMap k l a -> Maybe Int\nkeyToInt n = elemIndex n . sort . M.keys\n\ninnerKeyToInt :: Ord l => l -> DoubleMap k l a -> Maybe Int\ninnerKeyToInt n = elemIndex n . sort . innerKeys\n\ntoAssocList :: DoubleMap k l a -> [((k, l), a)]\ntoAssocList = fmap f . concatMap sequence . M.toList . fmap M.toList\n where f (n, (i, a)) = ((n, i), a)\n\ntoAssocInt :: (Ord k, Ord l) => DoubleMap k l a -> [((Int, Int), a)]\ntoAssocInt b = mapMaybe f . toAssocList $ b\n where\n f ((n, i), a) = pullMaybe (pullMaybe (keyToInt n b, innerKeyToInt i b), Just a)\n\nfromAssocList :: (Ord k, Ord l) => [((k, l), a)] -> DoubleMap k l a\nfromAssocList = fmap M.fromList . M.fromList . fmap shift . groupSortOn fst . fmap f\n where\n shift xs = (fst . head $ xs, fmap snd xs)\n f ((k, l), a) = (k, (l, a))\n\ntrans :: (Ord k, Ord l) => DoubleMap k l a -> DoubleMap l k a\ntrans = fromAssocList . fmap f . toAssocList\n where f ((l, k), a) = ((k, l), a)\n\n-- Outer keys are rows\ntoMatrix :: (Container Vector a, Num a, Ord k, Ord l)\n => DoubleMap k l a -> Matrix a\ntoMatrix b = assoc (M.size b, length $ innerKeys b) 0 (toAssocInt b)\n\n-- Column matrix from a Map\ntoMatrix' :: (Container Vector a, Num a, Ord k) => Map k a -> Matrix a\ntoMatrix' = toMatrix . fmap (M.fromList . pure . ((),))\n\n-- Are the rows independent?\nisInd :: (Field a, Ord k, Ord l) => DoubleMap k l a -> Bool\nisInd m = rank (toMatrix m) == M.size m\n\n-- Choices of n elements from a list, fast algorithm from stack overflow.\n-- https://stackoverflow.com/questions/21265454/subsequences-of-length-n-from-list-performance/21288092#21288092\nchoices :: Int -> [a] -> [[a]]\nchoices n xs =\n let l = length xs\n in if n>l then [] else subsequencesBySize xs !! (l-n)\n where\n subsequencesBySize [] = [[[]]]\n subsequencesBySize (y:ys) =\n let next = subsequencesBySize ys\n in zipWith (++) ([]:next) (map (map (y:)) next ++ [[]])\n\n-- SubMaps with n keys, excluding some.\nallSizeNSub :: Ord k => Int -> Map k v -> [Map k v]\nallSizeNSub n m =\n [ M.filterWithKey (\\k _ -> k `elem` keyList) m\n | keyList <- choices n . M.keys $ m ]\n\n-- The max rank submatricies with independent rows, excluding some.\nallMaxInd :: (Field a, Ord k, Ord l)\n => DoubleMap k l a -> [DoubleMap k l a]\nallMaxInd m = filter isInd . allSizeNSub (rank $ toMatrix m) $ m\n\n-- The max rank submatricies with independent rows,\n-- including or excluding certain rows.\nchooseInd :: (Field a, Ord k, Ord l)\n => [k] -> [k] -> DoubleMap k l a -> [DoubleMap k l a]\nchooseInd fixedKeys free m = filter hasKeys . allMaxInd $ m'\n where\n hasKeys b = null $ fixedKeys \\\\ M.keys b\n m' = M.filterWithKey (\\k _ -> k `notElem` free) m\n\n-- Maximal sets of independent columns.\nchooseCols :: (Field a, Ord k, Ord l) => DoubleMap k l a -> [DoubleMap k l a]\nchooseCols = fmap trans . allMaxInd . trans\n\n-- All submatricies with independent rows and columns, respecting row preferences.\nchooseBoth :: (Field a, Ord k, Ord l)\n => [k] -> [k] -> DoubleMap k l a -> [DoubleMap k l a]\nchooseBoth fixedKeys free m = concatMap chooseCols (chooseInd fixedKeys free m)\n\n-- All legal constraints where extra terms to zero.\nallExtraZero :: (Field a, Ord k, Num v, Ord l)\n => Map k v -> [k] -> DoubleMap k l a -> [Map k v]\nallExtraZero fixed free = fmap (M.union fixed . fmap (const 0))\n . chooseInd (M.keys fixed) free\n\n-- Solve Ax = B, where B is a column matrix.\ninnerSolver :: (Field a, Ord l, Ord k)\n => DoubleMap k l a -> Map k a -> Maybe (Map l a)\ninnerSolver b c\n | M.keys b == M.keys c = fromCol <$> linearSolve (toMatrix b) (toMatrix' c)\n | otherwise = Nothing\n where\n fromCol = M.fromList . zip (sort . innerKeys $ b) . concat . toLists\n\n-- Takes a list of fixed values, a list of free values,\n-- and a DoubleMap, and attempts to solve.\nsolve :: (Eq a, Field a, Ord k, Ord l)\n => Map k a -> [k] -> DoubleMap k l a -> [Map l a]\nsolve fixed free m = nub . catMaybes $\n [ innerSolver x y\n | x <- chooseBoth (M.keys fixed) free m\n , y <- allExtraZero fixed free m ]\n\n-- Rows with a unique nonzero entry.\nlooseEnds :: (Eq a, Ord k, Num a) => DoubleMap k l a -> [k]\nlooseEnds m =\n [ k\n | k <- M.keys m\n , let rowK = M.findWithDefault M.empty k m\n , (== 1) . M.size . M.filter (/= 0) $ rowK ]\n\n-- Tries setting loose ends to be free,\n-- excluding those already declared to be fixed.\nsmartSolve :: (Field a, Ord k, Ord l, Ord a)\n => Map k a -> [k] -> DoubleMap k l a -> [Map l a]\nsmartSolve fixed free m = case filter (all (>= 0)) . solve fixed free' $ m of\n [] -> solve fixed free m\n xs -> xs\n where\n free' = union free $ looseEnds m \\\\ M.keys fixed\n\n", "meta": {"hexsha": "3aad7bda157fa13c89047220199ce3c660f7451c", "size": 5344, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Solve.hs", "max_stars_repo_name": "alexloomis/factory-planner", "max_stars_repo_head_hexsha": "5ad8ab82f91f799bdc533a6526408c4c0520b9de", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-25T14:07:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T14:07:10.000Z", "max_issues_repo_path": "src/Solve.hs", "max_issues_repo_name": "alexloomis/factory-planner", "max_issues_repo_head_hexsha": "5ad8ab82f91f799bdc533a6526408c4c0520b9de", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Solve.hs", "max_forks_repo_name": "alexloomis/factory-planner", "max_forks_repo_head_hexsha": "5ad8ab82f91f799bdc533a6526408c4c0520b9de", "max_forks_repo_licenses": ["BSD-3-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.3907284768, "max_line_length": 112, "alphanum_fraction": 0.6229416168, "num_tokens": 1686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5499460680406888}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# language BangPatterns #-}\n{-# language LambdaCase #-}\n{-# options_ghc -Wno-unused-imports #-}\nmodule Data.Vector.FFT (\n fft, ifft\n -- * Useful results\n , crossCorrelation\n ) where\n\nimport Control.Monad (when)\nimport Control.Monad.Primitive (PrimMonad(..))\n\nimport Control.Monad.ST (runST)\nimport Data.Bits (shiftR,shiftL,(.&.),(.|.))\nimport Data.Bool (Bool,otherwise)\nimport Data.Complex (Complex(..),conjugate)\nimport Data.Foldable (forM_)\n\nimport Data.Vector.Unboxed as V (Vector, Unbox, map, zipWith, length, unsafeFreeze, (!))\nimport qualified Data.Vector.Unboxed.Mutable as VM (MVector, read, write, new, length)\nimport qualified Data.Vector.Generic as VG (Vector(..), copy)\n\nimport Prelude hiding (read)\n\n{-# RULES\n\"fft/ifft\" forall x. fft (ifft x) = x\n\"ifft/fft\" forall x. ifft (fft x) = x\n #-}\n\n\n-- | (Circular) cross-correlation of two vectors\n--\n-- Defined via the FFT and IFFT for computational efficiency\n--\n-- NB the source vectors should have matching length for meaningful results\ncrossCorrelation :: Vector (Complex Double)\n -> Vector (Complex Double)\n -> Vector (Complex Double)\ncrossCorrelation v1 v2 = ifft $ (cmap conjugate v1hat) `prod` v2hat\n where\n prod = V.zipWith (*)\n v1hat = fft v1\n v2hat = fft v2\n\n\n\n-- | Radix-2 decimation-in-time fast Fourier Transform.\n--\n-- The given array (and therefore the output as well) is zero-padded to the next power of two if necessary.\nfft :: Vector (Complex Double) -> Vector (Complex Double)\nfft arr = runST $ do\n marr <- copyPadded arr\n mfft marr\n V.unsafeFreeze marr\n{-# inlinable [1] fft #-}\n\n-- | Inverse fast Fourier transform.\n--\n-- The given array (and therefore the output as well) is zero-padded to the next power of two if necessary.\nifft :: Vector (Complex Double) -> Vector (Complex Double)\nifft arr = do\n let lenComplex = intToComplexDouble (V.length arr)\n cmap ((/ lenComplex) . conjugate) . fft . cmap conjugate $ arr\n{-# inlinable [1] ifft #-}\n\n\n\n\n-- | Copy the source vector into a zero-padded mutable one\ncopyPadded :: (PrimMonad m, Num a, Unbox a) =>\n Vector a -> m (VM.MVector (PrimState m) a)\ncopyPadded arr = do\n let\n len = V.length arr\n l2 = nextPow2 len\n marr <- VM.new l2\n forM_ [0 .. l2 - 1] $ \\i -> do\n let x | i < len = arr V.! i\n | otherwise = 0\n VM.write marr i x\n pure marr\n{-# inline copyPadded #-}\n\n\n\n\n\n-- | Radix-2 decimation-in-time fast Fourier Transform.\n-- The given array must have a length that is a power of two,\n-- though this property is not checked.\nmfft :: (PrimMonad m) => VM.MVector (PrimState m) (Complex Double) -> m ()\nmfft mut = do {\n let len = VM.length mut\n ; let bitReverse !i !j = do {\n ; if i == len - 1\n then stage 0 1\n else do {\n when (i < j) $ swap mut i j\n ; let inner k l = if k <= l\n then inner (k `shiftR` 1) (l - k)\n else bitReverse (i + 1) (l + k)\n ; inner (len `shiftR` 1) j\n }\n }\n stage l l1 = if l == (log2 len)\n then pure ()\n else do {\n let !l2 = l1 `shiftL` 1\n !e = (negate twoPi) / (intToDouble l2)\n flight j !a = if j == l1\n then stage (l + 1) l2\n else do {\n let butterfly i = if i >= len\n then flight (j + 1) (a + e)\n else do {\n let i1 = i + l1\n ; xi1 :+ yi1 <- VM.read mut i1\n ; let !co = cos a\n !si = sin a\n d = (co * xi1 - si * yi1) :+ (si * xi1 + co * yi1)\n ; ci <- VM.read mut i\n ; VM.write mut i1 (ci - d)\n ; VM.write mut i (ci + d)\n ; butterfly (i + l2)\n }\n ; butterfly j\n }\n ; flight 0 0\n }\n ; bitReverse 0 0\n}\n\n-- wildcard cases should never happen. if they do, really bad things will happen.\nb,s :: Int -> Int\nb = \\case { 0 -> 0x02; 1 -> 0x0c; 2 -> 0xf0; 3 -> 0xff00; 4 -> wordToInt 0xffff0000; 5 -> wordToInt 0xffffffff00000000; _ -> 0; }\ns = \\case { 0 -> 1; 1 -> 2; 2 -> 4; 3 -> 8; 4 -> 16; 5 -> 32; _ -> 0; }\n{-# inline b #-}\n{-# inline s #-}\n\n-- | Next power of 2\nnextPow2 :: Int -> Int\nnextPow2 n\n | mod n 2 == 0 = n\n | otherwise = (2 :: Int) ^ (log2 n + 1)\n\n\nlog2 :: Int -> Int\nlog2 v0 = if v0 <= 0\n then error $ \"Data.Vector.FFT: nonpositive input, got \" ++ show v0\n else go 5 0 v0\n where\n go !i !r !v\n | i == -1 = r\n | v .&. b i /= 0 =\n let si = s i\n in go (i - 1) (r .|. si) (v `shiftR` si)\n | otherwise = go (i - 1) r v\n\n\n{-# inline swap #-}\nswap :: (PrimMonad m, Unbox a) =>\n VM.MVector (PrimState m) a -> Int -> Int -> m ()\nswap mut i j = do\n atI <- VM.read mut i\n atJ <- VM.read mut j\n VM.write mut i atJ\n VM.write mut j atI\n\ntwoPi :: Double\n{-# inline twoPi #-}\ntwoPi = 6.283185307179586\n\nintToDouble :: Int -> Double\n{-# inline intToDouble #-}\nintToDouble = fromIntegral\n\nwordToInt :: Word -> Int\n{-# inline wordToInt #-}\nwordToInt = fromIntegral\n\nintToComplexDouble :: Int -> Complex Double\n{-# inline intToComplexDouble #-}\nintToComplexDouble = fromIntegral\n\n\n{-# inline cmap #-}\ncmap :: (Floating a, Unbox a) => (Complex a -> Complex a) -> V.Vector (Complex a) -> V.Vector (Complex a)\ncmap = V.map\n\n\n--\n\n-- {-# inline copyWhole #-}\n-- copyWhole :: (PrimMonad m, VG.Vector Vector a, Unbox a) => V.Vector a -> m (VM.MVector (PrimState m) a)\n-- copyWhole arr = do\n-- let len = V.length arr\n-- marr <- VM.new len\n-- VG.copy marr arr\n-- pure marr\n\n-- {-# inline arrOK #-}\n-- arrOK :: Unbox a => Vector a -> Bool\n-- arrOK arr =\n-- let n = V.length arr\n-- in (1 `shiftL` log2 n) == n\n", "meta": {"hexsha": "ea823a65e15c5e41cda569c21afb1d65b9b922d3", "size": 6080, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Vector/FFT.hs", "max_stars_repo_name": "ocramz/vector-fft", "max_stars_repo_head_hexsha": "a416c9a5977bb27f135866f667cee65ca5d402ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-28T13:20:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T10:47:27.000Z", "max_issues_repo_path": "src/Data/Vector/FFT.hs", "max_issues_repo_name": "ocramz/vector-fft", "max_issues_repo_head_hexsha": "a416c9a5977bb27f135866f667cee65ca5d402ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-28T11:09:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T15:11:31.000Z", "max_forks_repo_path": "src/Data/Vector/FFT.hs", "max_forks_repo_name": "ocramz/vector-fft", "max_forks_repo_head_hexsha": "a416c9a5977bb27f135866f667cee65ca5d402ff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-13T19:39:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:39:56.000Z", "avg_line_length": 29.3719806763, "max_line_length": 129, "alphanum_fraction": 0.5368421053, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5497066002136055}} {"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 #-}\n{-# LANGUAGE RankNTypes #-}\nmodule AI.Singularity.Data.Network 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 qualified Control.Monad.State as S\nimport Control.Lens\nimport Data.Proxy\nimport Data.List (foldl')\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\nimport AI.Singularity.Data.Vector\n\ndata GeneralNetwork vec mat inp out where\n FFLayer :: forall vec mat m n. (KnownNat m, KnownNat n) =>\n mat (m+1) n ->\n (forall a. Floating a => a -> a) ->\n GeneralNetwork vec mat (vec m) (vec n)\n FFSeq :: forall vec mat a b c.\n GeneralNetwork vec mat a b ->\n GeneralNetwork vec mat b c ->\n GeneralNetwork vec mat a c\n FromFunc :: (Num a) =>\n (forall b. Num b => b -> b) ->\n GeneralNetwork vec mat a a\n FromBinFunc :: forall a vec mat. Fractional a =>\n (forall b. Fractional b => b -> b -> b) ->\n GeneralNetwork vec mat (a,a) a\n FFDiv :: forall vec mat a' a b b'.\n GeneralNetwork vec mat a b ->\n GeneralNetwork vec mat a' b' ->\n GeneralNetwork vec mat (a, a') (b, b')\n Split :: forall vec mat a b c. Num a =>\n GeneralNetwork vec mat a b ->\n GeneralNetwork vec mat a c ->\n GeneralNetwork vec mat a (b,c)\n SplitNet :: forall vec mat n k l c. (KnownNat n, KnownNat k, KnownNat l, (k + l) ~ n) =>\n GeneralNetwork vec mat (vec n) c ->\n GeneralNetwork vec mat (vec k, vec l) c\n Recurse :: forall vec mat a b. (Num b) =>\n GeneralNetwork vec mat (a,b) b ->\n GeneralNetwork vec mat [a] b\n First :: forall vec mat a b c. (Num c) =>\n GeneralNetwork vec mat a b ->\n GeneralNetwork vec mat (a,c) b\n Second :: forall vec mat a b c. (Num c) =>\n GeneralNetwork vec mat a b ->\n GeneralNetwork vec mat (c,a) b\n\n\ntype Network inp out = GeneralNetwork Vector Matrix inp out\n\ntype TrainedNetwork inp out = GeneralNetwork Vector (GeneralInTrainingMat LD.Matrix) inp out\n\ntype STNetwork s = GeneralNetwork Vector (STInTrainMat s)\n\nchangeMatType :: Applicative f => (forall m n. (KnownNat m, KnownNat n) => mat m n -> f (mat' m n)) ->\n GeneralNetwork vec mat inp out -> f (GeneralNetwork vec mat' inp out)\n{-# INLINE changeMatType #-}\nchangeMatType conv (FFLayer m f) = (\\x -> FFLayer x f) <$> conv m\nchangeMatType conv (FFSeq n1 n2) = FFSeq <$> changeMatType conv n1 <*> changeMatType conv n2\nchangeMatType conv (FFDiv n1 n2) = FFDiv <$> changeMatType conv n1 <*> changeMatType conv n2\nchangeMatType conv (FromFunc f) = pure $ FromFunc f\nchangeMatType conv (FromBinFunc f) = pure $ FromBinFunc f\nchangeMatType conv (Split n1 n2) = Split <$> changeMatType conv n1 <*> changeMatType conv n2\nchangeMatType conv (SplitNet n1) = SplitNet <$> changeMatType conv n1\nchangeMatType conv (Recurse n) = Recurse <$> changeMatType conv n\nchangeMatType conv (First n) = First <$> changeMatType conv n\nchangeMatType conv (Second n) = Second <$> changeMatType conv n\n\n\nmatToTrain :: (KnownNat m, KnownNat n) => Matrix m n -> Identity (InTrainMat m n)\nmatToTrain = pure . (\\x -> GeneralInTrainingMat x 0 0)\n\nsaveMat :: Matrix m n -> S.State [LD.Matrix Float] (Matrix m n)\nsaveMat (Mat m) = do\n l <- S.get\n S.put (m:l)\n return (Mat m)\n\nsaveWeights = map LD.toLists . reverse . flip S.execState [] . changeMatType saveMat\n\nloadMat :: Matrix m n -> S.State [LD.Matrix Float] (Matrix m n)\nloadMat _ = do\n (a:l) <- S.get\n S.put l\n return (Mat a)\n\nloadWeights w = flip S.evalState (map LD.fromLists w) . changeMatType loadMat\n\ntoTrain :: Network inp out -> TrainedNetwork inp out\ntoTrain = runIdentity . changeMatType matToTrain\n\nfromTrain :: TrainedNetwork inp out -> Network inp out\nfromTrain = runIdentity . changeMatType (Identity . view trMatr)\n\ntoSTTrain :: Network inp out -> ST s (STNetwork s inp out)\ntoSTTrain = changeMatType toSTInTrainM\n\ninstance Show (Network inp out) where\n show (FFLayer m _) = \"weights:\\n\" ++ show m\n show (FFSeq net1 net2) = show net1 ++ \"\\n\" ++ show net2\n show (FromFunc _ ) = \"FromFunc\"\n show (FFDiv a b) = show a ++ \"\\n\\tdiv \\n\" ++ show b\n show (SplitNet n) = \"\\tSplitNet \\n\" ++ show n\n show (Recurse n) = \"\\tRec\\n\" ++ show n\n\ncreateLayer :: forall m n. (KnownNat m, KnownNat n) => Matrix (m+1) n -> (forall a. Floating a => a -> a) -> Network (Vector m) (Vector n)\ncreateLayer weights activator = FFLayer weights activator\n\nrandomLayer :: forall m n k. (KnownNat m, KnownNat n, KnownNat k, k ~ (m + 1)) => (forall a. Floating a => a -> a) -> IO (Network (Vector m) (Vector n))\nrandomLayer activator = (\\w -> createLayer w activator) <$> randomMat\n\nidentLayer :: Num a => Network a a\nidentLayer = FromFunc id\n\n\ngeneralConductSignal :: forall mat a b. (forall m n. mat m n -> Matrix m n) -> a -> GeneralNetwork Vector mat a b -> b\ngeneralConductSignal _ v (FromFunc f) = f v\ngeneralConductSignal _ v (FromBinFunc f) = uncurry f v\ngeneralConductSignal c v (FFSeq net1 net2) = generalConductSignal c (generalConductSignal c v net1) net2\ngeneralConductSignal c v (FFLayer weights f) = cmap f (c weights #> consV 1 v)\ngeneralConductSignal c v (FFDiv n1 n2) = (generalConductSignal c (fst v) n1, generalConductSignal c (snd v) n2)\ngeneralConductSignal c v (Split n1 n2) = (generalConductSignal c v n1, generalConductSignal c v n2)\ngeneralConductSignal c v (SplitNet n) = generalConductSignal c (uncurry appendV v) n\ngeneralConductSignal c v (First n) = generalConductSignal c (fst v) n\ngeneralConductSignal c v (Second n) = generalConductSignal c (snd v) n\ngeneralConductSignal c v (Recurse n) = foldl' (\\b a -> generalConductSignal c (a,b) n) 0 v\n\n\nconductSignalInTrain = generalConductSignal (view trMatr)\n\nconductSignal :: forall a b. a -> Network a b -> b\nconductSignal = generalConductSignal id\n\nrunNetwork :: Network a b -> a -> b\nrunNetwork = flip conductSignal\n\ncompose :: Network m n -> Network k m -> Network k n\ncompose net2 net1 = FFSeq net1 net2\n\nsigmoid :: Floating a => a -> a\nsigmoid = (1/) . (1+). exp . negate\n\nsoftmax :: forall n. KnownNat n => Vector n -> Vector n\nsoftmax = exp >>> id &&& (foldV (+) 0 >>> fromValV) >>> uncurry (/)\n\n\natFirst :: Num a => Network b c -> Network (b,a) (c,a)\natFirst = flip FFDiv identLayer\natSecond :: Num a => Network b c -> Network (a,b) (a,c)\natSecond = FFDiv identLayer\n\ntakeFst :: (Num c, Num a) => Network (a,c) a\ntakeFst = First identLayer\ntakeSnd :: (Num c, Num a) => Network (c,a) a\ntakeSnd = Second identLayer\n\nprelstm :: forall m n k. (KnownNat m, KnownNat n, KnownNat k) => IO (Network [Vector m] (Vector n, Vector k))\nprelstm = do\n let takeInp = First identLayer\n takeOut = Second . Second $ identLayer\n -- takeMem = Second . First $ identLayer\n splitter = Split takeInp takeOut\n x <- SplitNet <$> randomLayer sigmoid\n y <- SplitNet <$> randomLayer sigmoid\n z <- SplitNet <$> randomLayer tanh\n k <- SplitNet <$> randomLayer sigmoid\n l <- randomLayer tanh\n let\n gateCell = Split (FFSeq splitter x) (Second . First $ identLayer) `FFSeq` FromBinFunc (*)\n secondCell = Split gateCell (splitter `FFSeq` Split y z `FFSeq` FromBinFunc (*)) `FFSeq` FromBinFunc (+)\n thirdCell = Split secondCell (splitter `FFSeq` k) `FFSeq` Split takeFst (atFirst l `FFSeq` FromBinFunc (*))\n -- get2 pre = Split pre (Split)\n return . Recurse $ thirdCell\n-- MnistReader\n\ngru :: forall m n. (KnownNat m, KnownNat n) => IO (Network [Vector m] (Vector n))\ngru = do\n z <- SplitNet <$> randomLayer sigmoid\n r <- SplitNet <$> randomLayer sigmoid\n h <- SplitNet <$> randomLayer tanh\n let\n rxt = Split r takeSnd `FFSeq` FromBinFunc (*)\n ht' = Split rxt takeFst `FFSeq` h\n ht = Split (z `FFSeq` Split (FromFunc (1-)) identLayer) (Split takeSnd ht') `FFSeq` FromBinFunc (*) `FFSeq` FromBinFunc (+)\n return $ Recurse ht\n --beg = Split (Split x takeFst `FFSeq` FromBinFunc (*)) takeFst `FFSeq` z\n\niden :: forall a. (Num a) => a -> a\niden x = x\n", "meta": {"hexsha": "ef24643895f3daca04e5fb018a10692754e436a5", "size": 8492, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Singularity/Data/Network.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/Network.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/Network.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": 40.6315789474, "max_line_length": 152, "alphanum_fraction": 0.6727508243, "num_tokens": 2538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.548898616191494}} {"text": "{-# LANGUAGE BangPatterns, TypeFamilies, TypeOperators, FlexibleInstances, FlexibleContexts, GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses, UndecidableInstances #-}\nmodule Data.NeuralNetwork.Backend.HMatrix.Layers where\n\nimport Numeric.LinearAlgebra hiding (R, C)\nimport Numeric.LinearAlgebra.Devel\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Storable as SV\nimport qualified Data.Vector.Storable.Mutable as SVM\nimport System.Random.MWC\nimport System.Random.MWC.Distributions\nimport Control.Monad.ST\nimport Control.Monad (liftM2, forM_, when)\nimport GHC.Float\nimport Data.STRef\nimport Data.Functor.Identity\nimport Control.DeepSeq\nimport Data.NeuralNetwork\n\ntype R = Float\n\n-- We parameterise the activation layer T, where the parameter indicates how\n-- elements are contained:\n-- SinglC :. Vector, SinglC :. Matrix, MultiC :. Vector, MultiC :. Matrix\n-- SinglC means the input has only one channel, while\n-- MultiC means the input has more than one.\n--\n-- type function composition\ndata (f :: * -> *) :. (g :: * -> *) :: * -> *\n-- type function: Identity\ndata SinglC :: * -> *\ndata MultiC :: * -> *\n\n-- Tags for each form of layer\ndata F\ndata C\ndata A\ndata M\ndata T (c :: * -> *)\ndata S a b\n\ndata RunLayer :: * -> * where\n -- Densely connected layer\n -- input: vector of size m\n -- output: vector of size n\n -- weights: matrix of size m x n\n -- biases: vector of size n\n Full :: !(Matrix R) -> !(Vector R) -> RunLayer F\n -- convolutional layer\n -- input: channels of 2D floats, of the same size (a x b), # of input channels: m\n -- output: channels of 2D floats, of the same size (c x d), # of output channels: n\n -- where c = a + 2*padding + 1 - s\n -- d = b + 2*padding + 1 - t\n -- feature: matrix of (s x t), # of features: m x n\n -- padding: number of 0s padded at each side of channel\n -- biases: bias for each output, # of biases: n\n Conv :: !(V.Vector (V.Vector (Matrix R))) -> !(V.Vector R) -> Int -> RunLayer C\n -- Reshape from channels of matrix to a single vector\n -- input: m channels of 2D matrices\n -- assuming that all matrices are of the same size a x b\n -- output: 1D vector of the concatenation of all input channels\n -- its size: m x a x b\n As1D :: RunLayer A\n -- max pooling layer\n -- input: channels of 2D floats, of the same size (a x b), # of input channels: m\n -- assuming that a and b are both multiple of stride\n -- output: channels of 2D floats, of the same size (c x d), # of output channels: m\n -- where c = a / stride\n -- d = b / stride\n MaxP :: Int -> RunLayer M\n -- Activator\n -- the input can be either a 1D vector, 2D matrix, or channels of either.\n Activation :: (R->R, R->R) -> RunLayer (T c)\n -- stacking two components a and b\n -- the output of a should matches the input of b\n Stack :: !(RunLayer a) -> !(RunLayer b) -> RunLayer (S a b)\n\ninstance Component (RunLayer F) where\n type Run (RunLayer F) = Identity\n type Inp (RunLayer F) = Vector R\n type Out (RunLayer F) = Vector R\n -- trace is (input, weighted-sum)\n newtype Trace (RunLayer F) = DTrace (Vector R, Vector R)\n forwardT (Full w b) !inp =\n let !bv = (inp <# w) `add` b\n in return $ DTrace (inp,bv)\n output (DTrace (_,!a)) = a\n backward l (DTrace (!iv,!bv)) !odelta rate =\n let Full w b = l\n !d = scale (negate rate) odelta\n !m = iv `outer` d\n -- back-propagated error at input\n !idelta = w #> odelta\n -- update to weights\n ---- for what reason, could this expression: w `add` (iv `outer` d)\n ---- entails a huge space leak? especially, neither 'seq' nor\n ---- 'deepseq' helps a bit. The only workaround is to expand the\n ---- add function, and call SV.force on the result vector, which\n ---- explcitly copy and drop reference to orignal computed result.\n !w'= w `add` m\n -- !w'= let (r,c) = size w\n -- dat1 = flatten (tr' w)\n -- dat2 = flatten (tr' m)\n -- in matrixFromVector ColumnMajor r c $ SV.force $ dat1 `add` dat2\n !b'= b `add` d\n in return $ (Full w' b', idelta)\n\ninstance Component (RunLayer C) where\n type Run (RunLayer C) = Identity\n type Inp (RunLayer C) = V.Vector (Matrix R)\n type Out (RunLayer C) = V.Vector (Matrix R)\n -- trace is (input, convoluted output)\n newtype Trace (RunLayer C) = CTrace (Inp (RunLayer C), V.Vector (Matrix R))\n forwardT (Conv fs bs p) !inp =\n let !ov = V.zipWith feature\n (tr fs) -- feature matrix indexed majorly by each output\n bs -- biases by each output\n in return $ CTrace (inp,ov)\n where\n !osize = let (x,y) = size (V.head inp)\n (u,v) = size (V.head $ V.head fs)\n in (x+2*p-u+1, y+2*p-v+1)\n -- transpose the features matrix\n tr :: V.Vector (V.Vector a) -> V.Vector (V.Vector a)\n tr uv = let n = V.length (V.head uv)\n !vu = V.map (\\i -> V.map (V.! i) uv) $ V.enumFromN 0 n\n in vu\n feature :: V.Vector (Matrix R) -> R -> Matrix R\n feature f b = V.foldl1' add (V.zipWith (layerCorr2 p) f inp) `add` konst b osize\n output (CTrace (_,a)) = a\n backward l (CTrace (!iv,!av)) !odelta rate =\n let Conv fs bs p = l\n -- update to the feature matrix\n m :: V.Vector (V.Vector (Matrix R))\n !m = V.zipWith (\\flts chn ->\n -- chn: a single input channel\n -- flts: all features used for chn\n V.zipWith (\\f d ->\n let upd = scale (negate rate) (layerCorr2 p chn d)\n in f `add` upd\n ) flts odelta\n ) fs iv\n -- update to the biases\n b :: V.Vector R\n !b = V.zipWith (\\b d -> b + (negate rate) * sumElements d) bs odelta\n -- back-propagated error at input\n idelta :: V.Vector (Matrix R)\n !idelta = V.map (\\f -> V.foldl1' add $ V.zipWith (layerConv2 p) f odelta) fs\n in --trace (\"CL:\" ++ show odelta)\n return $ (Conv m b p, idelta)\n\ninstance Component (RunLayer A) where\n type Run (RunLayer A) = Identity\n type Inp (RunLayer A) = V.Vector (Matrix R)\n type Out (RunLayer A) = Vector R\n -- trace keeps information of (m, axb, b, output)\n newtype Trace (RunLayer A) = ReshapeTrace (Int, Int, Int, Vector R)\n forwardT _ !inp =\n let !b = V.length inp\n (!r,!c) = size (V.head inp)\n !o = V.foldr' (\\x y -> flatten x SV.++ y) SV.empty inp\n in return $ ReshapeTrace (b, r*c, c, o)\n output (ReshapeTrace (_,_,_,a)) = a\n backward a (ReshapeTrace (b,n,c,_)) !odelta _ =\n let !idelta = V.fromList $ map (reshape c) $ takesV (replicate b n) odelta\n in return $ (a, idelta)\n\ninstance Component (RunLayer M) where\n type Run (RunLayer M) = Identity\n type Inp (RunLayer M) = V.Vector (Matrix R)\n type Out (RunLayer M) = V.Vector (Matrix R)\n -- trace is (dimension of pools, index of max in each pool, pooled matrix)\n -- for each channel.\n newtype Trace (RunLayer M) = PTrace (V.Vector (IndexOf Matrix, Vector Int, Matrix R))\n -- forward is to divide the input matrix in stride x stride sub matrices,\n -- and then find the max element in each sub matrices.\n forwardT (MaxP stride) !inp = return $ PTrace $ V.map mk inp\n where\n mk inp = let (!i,!v) = pool stride inp in (size v, i, v)\n output (PTrace a) = V.map (\\(_,_,!o) ->o) a\n -- use the saved index-of-max in each pool to propagate the error.\n backward l@(MaxP stride) (PTrace t) odelta _ =\n let !idelta = V.zipWith gen t odelta in return $ (l, idelta)\n where\n gen (!si,!iv,_) od = unpool stride iv od\n\ninstance (Component (RunLayer a),\n Component (RunLayer b),\n Run (RunLayer a) ~ Identity,\n Run (RunLayer b) ~ Identity,\n Out (RunLayer a) ~ Inp (RunLayer b)\n ) => Component (RunLayer (S a b)) where\n type Run (RunLayer (S a b)) = Identity\n type Inp (RunLayer (S a b)) = Inp (RunLayer a)\n type Out (RunLayer (S a b)) = Out (RunLayer b)\n newtype Trace (RunLayer (S a b)) = TTrace (Trace (RunLayer b), Trace (RunLayer a))\n forwardT (Stack a b) !i = do\n !tra <- forwardT a i\n !trb <- forwardT b (output tra)\n return $ TTrace (trb, tra)\n output (TTrace !a) = output (fst a)\n backward (Stack a b) (TTrace (!trb,!tra)) !odelta rate = do\n (b', !odelta') <- backward b trb odelta rate\n (a', !idelta ) <- backward a tra odelta' rate\n return (Stack a' b', idelta)\n\ninstance (Container c R, Pairwise c R) => Component (RunLayer (T (MultiC :. c))) where\n type Run (RunLayer (T (MultiC :. c))) = Identity\n type Inp (RunLayer (T (MultiC :. c))) = V.Vector (c R)\n type Out (RunLayer (T (MultiC :. c))) = V.Vector (c R)\n newtype Trace (RunLayer (T (MultiC :. c))) = TTraceM (V.Vector (Trace (RunLayer (T (SinglC :. c)))))\n forwardT (Activation ac) !inp =\n TTraceM <$> V.mapM (forwardT (Activation ac)) inp\n output (TTraceM a) = V.map output a\n backward a@(Activation ac) (TTraceM ts) !odelta r = do\n idelta <- V.zipWithM (\\t d -> snd <$> backward (Activation ac) t d r) ts odelta\n return (a, idelta)\n\ninstance (Container c R, Pairwise c R) => Component (RunLayer (T (SinglC :. c))) where\n type Run (RunLayer (T (SinglC :. c))) = Identity\n type Inp (RunLayer (T (SinglC :. c))) = c R\n type Out (RunLayer (T (SinglC :. c))) = c R\n newtype Trace (RunLayer (T (SinglC :. c))) = TTraceS (c R, c R)\n forwardT (Activation (af,_)) !inp = return $ TTraceS (inp, cmap af inp)\n output (TTraceS (_,!a)) = a\n backward a@(Activation (_,ag)) (TTraceS (!iv,_)) !odelta _ = return $ (a, odelta `hadamard` cmap ag iv)\n\nnewFLayer :: Int -- number of input values\n -> Int -- number of neurons (output values)\n -> IO (RunLayer F) -- new layer\nnewFLayer m n =\n withSystemRandom . asGenIO $ \\gen -> do\n -- we build the weights in column major because in the back-propagation\n -- algo, the computed update to weights is in column major. So it is\n -- good for performance to keep the matrix always in column major.\n w <- buildMatrix (normal 0 0.01 gen) ColumnMajor (m,n)\n b <- return $ konst 1 n\n return $ Full w b\n\nnewCLayer :: Int -- number of input channels\n -> Int -- number of output channels\n -> Int -- size of each feature\n -> Int -- size of padding\n -> IO (RunLayer C) -- new layer\nnewCLayer inpsize outsize sfilter npadding =\n withSystemRandom . asGenIO $ \\gen -> do\n fs <- V.replicateM inpsize $ V.replicateM outsize $\n buildMatrix (truncNormal 0 0.1 gen) RowMajor (sfilter, sfilter)\n bs <- return $ V.replicate outsize 0.1\n return $ Conv fs bs npadding\n where\n truncNormal m s g = do\n x <- standard g\n if x >= 2.0 || x <= -2.0\n then truncNormal m s g\n else return $! m + s * x\n\nbuildMatrix g order (nr, nc) = do\n vals <- SV.replicateM (nr*nc) (double2Float <$> g)\n return $ matrixFromVector order nr nc vals\n\nlayerCorr2 :: Int -> Matrix R -> Matrix R -> Matrix R\nlayerCorr2 p k m = corr2 k padded\n where\n padded = zeroPadded p m\n (w,_) = size k\n\nlayerConv2 :: Int -> Matrix R -> Matrix R -> Matrix R\nlayerConv2 p k m = corr2 (fliprl . flipud $ k) padded\n where\n padded = zeroPadded p m\n\n-- max pool, picking out the maximum element\n-- in each stride x stride sub-matrices.\n-- assuming that the original matrix row and column size are\n-- both multiple of stride\npool :: Int -> Matrix Float -> (Vector Int, Matrix Float)\npool 1 mat = let (r,c) = size mat in (SV.replicate (r*c) 0, mat)\n-- pool 2 mat | orderOf mat == RowMajor = c_max_pool2_f mat\npool stride mat = runST $ do\n ori <- unsafeThawMatrix mat\n mxv <- newUndefinedMatrix RowMajor r' c'\n mxi <- newUndefinedVector (r'*c')\n forM_ [0..r'-1] $ \\i -> do\n forM_ [0..c'-1] $ \\j -> do\n (n,v) <- unsafeMaxIndEle ori (i*stride) (j*stride) stride stride\n unsafeWriteVector mxi (i*c'+j) n\n unsafeWriteMatrix mxv i j v\n a <- unsafeFreezeVector mxi\n b <- unsafeFreezeMatrix mxv\n return (a,b)\n where\n (r,c) = size mat\n r' = r `div` stride\n c' = c `div` stride\n unsafeMaxIndEle mm x y r c = do\n mp <- newSTRef 0\n mv <- newSTRef (-10000.0)\n forM_ [0..r-1] $ \\ i -> do\n forM_ [0..c-1] $ \\ j -> do\n v1 <- unsafeReadMatrix mm (x+i) (y+j)\n v0 <- readSTRef mv\n when (v1 > v0) $ do\n writeSTRef mv v1\n writeSTRef mp (i*2+j)\n p <- readSTRef mp\n v <- readSTRef mv\n return (p, v)\n\n-- the reverse of max pool.\n-- assuming idx and mat are of the same size\nunpool :: Int -> Vector Int -> Matrix Float -> Matrix Float\nunpool stride idx mat = runSTMatrix $ do\n mat' <- newMatrix' 0 r' c'\n forM_ [0..r-1] $ \\i -> do\n forM_ [0..c-1] $ \\j -> do\n let pos = idx SV.! (i*c+j)\n let (oi,oj) = pos `divMod` 2\n let val = mat `atIndex` (i,j)\n unsafeWriteMatrix mat' (i*stride+oi) (j*stride+oj) val\n return mat'\n where\n (r,c) = size mat\n (r',c') = (r*stride, c*stride)\n\n-- a slightly faster way to pading the matrix\n-- camparing to fromBlocks provided by hmatrix.\nzeroPadded :: Int -> Matrix Float -> Matrix Float\nzeroPadded p mat = runSTMatrix $ do\n mat' <- newMatrix' 0 r' c'\n setMatrix mat' p p mat\n return mat'\n where\n (r,c) = size mat\n (r',c') = (r+2*p,c+2*p)\n\n-- a slightly faster version of newMatrix, which based\n-- directly on lower level Vector.Storable creation.\nnewMatrix' :: SVM.Storable t => t -> Int -> Int -> ST s (STMatrix s t)\nnewMatrix' v r c = do\n vec <- SVM.replicate (r*c) v\n vec <- SV.unsafeFreeze vec\n unsafeThawMatrix $ reshape c vec\n\n-- The hmatrix does has a SIMD enabled pairwise product named 'mul' in the\n-- 'Container' class, but unfortunately it is not exported at all.\n-- We define a slow hadamard product here.\nclass Container c e => Pairwise c e where\n hadamard :: c e -> c e -> c e\ninstance Pairwise Vector R where\n hadamard = zipVectorWith (*)\ninstance Pairwise Matrix R where\n hadamard a b = reshape (cols a) $ hadamard (flatten a) (flatten b)\n", "meta": {"hexsha": "a0b2599e03657188ab82c912ea8df36ac934a59e", "size": 14500, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Backend-hmatrix/Data/NeuralNetwork/Backend/HMatrix/Layers.hs", "max_stars_repo_name": "pierric/neural-network", "max_stars_repo_head_hexsha": "406ecaf334cde9b10c9324e1f6c4b8663eae58d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-05-24T17:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T22:25:52.000Z", "max_issues_repo_path": "Backend-hmatrix/Data/NeuralNetwork/Backend/HMatrix/Layers.hs", "max_issues_repo_name": "pierric/neural-network", "max_issues_repo_head_hexsha": "406ecaf334cde9b10c9324e1f6c4b8663eae58d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Backend-hmatrix/Data/NeuralNetwork/Backend/HMatrix/Layers.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.9604519774, "max_line_length": 107, "alphanum_fraction": 0.5915172414, "num_tokens": 4386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5488493976536187}} {"text": "{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n-----------------------------------------------------------------------------\n-- |\n-- Copyright : (c) Edward Kmett 2010-2014\n-- License : BSD3\n-- Maintainer : ekmett@gmail.com\n-- Stability : experimental\n-- Portability : GHC only\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.AD.Newton\n (\n -- * Newton's Method (Forward AD)\n findZero\n , inverse\n , fixedPoint\n , extremum\n -- * Gradient Ascent/Descent (Reverse AD)\n , gradientDescent\n , gradientAscent\n , conjugateGradientDescent\n , conjugateGradientAscent\n ) where\n\nimport Data.Foldable (all, sum)\nimport Data.Reflection (Reifies)\nimport Data.Traversable\nimport Numeric.AD.Internal.Combinators\nimport Numeric.AD.Internal.Forward (Forward)\nimport Numeric.AD.Internal.On\nimport Numeric.AD.Internal.Or\nimport Numeric.AD.Internal.Reverse (Reverse, Tape)\nimport Numeric.AD.Internal.Type (AD(..))\nimport Numeric.AD.Mode\nimport Numeric.AD.Mode.Reverse as Reverse (gradWith')\nimport Numeric.AD.Rank1.Kahn as Kahn (Kahn, grad)\nimport qualified Numeric.AD.Rank1.Newton as Rank1\nimport Prelude hiding (all, mapM, sum)\n\n-- $setup\n-- >>> import Data.Complex\n\n-- | The 'findZero' function finds a zero of a scalar function using\n-- Newton's method; its output is a stream of increasingly accurate\n-- results. (Modulo the usual caveats.) If the stream becomes constant\n-- (\"it converges\"), no further elements are returned.\n--\n-- Examples:\n--\n-- >>> take 10 $ findZero (\\x->x^2-4) 1\n-- [1.0,2.5,2.05,2.000609756097561,2.0000000929222947,2.000000000000002,2.0]\n--\n-- >>> last $ take 10 $ findZero ((+1).(^2)) (1 :+ 1)\n-- 0.0 :+ 1.0\nfindZero :: (Fractional a, Eq a) => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> [a]\nfindZero f = Rank1.findZero (runAD.f.AD)\n{-# INLINE findZero #-}\n\n-- | The 'inverse' function inverts a scalar function using\n-- Newton's method; its output is a stream of increasingly accurate\n-- results. (Modulo the usual caveats.) If the stream becomes\n-- constant (\"it converges\"), no further elements are returned.\n--\n-- Example:\n--\n-- >>> last $ take 10 $ inverse sqrt 1 (sqrt 10)\n-- 10.0\ninverse :: (Fractional a, Eq a) => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> a -> [a]\ninverse f = Rank1.inverse (runAD.f.AD)\n{-# INLINE inverse #-}\n\n-- | The 'fixedPoint' function find a fixedpoint of a scalar\n-- function using Newton's method; its output is a stream of\n-- increasingly accurate results. (Modulo the usual caveats.)\n--\n-- If the stream becomes constant (\"it converges\"), no further\n-- elements are returned.\n--\n-- >>> last $ take 10 $ fixedPoint cos 1\n-- 0.7390851332151607\nfixedPoint :: (Fractional a, Eq a) => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> [a]\nfixedPoint f = Rank1.fixedPoint (runAD.f.AD)\n{-# INLINE fixedPoint #-}\n\n-- | The 'extremum' function finds an extremum of a scalar\n-- function using Newton's method; produces a stream of increasingly\n-- accurate results. (Modulo the usual caveats.) If the stream\n-- becomes constant (\"it converges\"), no further elements are returned.\n--\n-- >>> last $ take 10 $ extremum cos 1\n-- 0.0\nextremum :: (Fractional a, Eq a) => (forall s. AD s (On (Forward (Forward a))) -> AD s (On (Forward (Forward a)))) -> a -> [a]\nextremum f = Rank1.extremum (runAD.f.AD)\n{-# INLINE extremum #-}\n\n-- | The 'gradientDescent' function performs a multivariate\n-- optimization, based on the naive-gradient-descent in the file\n-- @stalingrad\\/examples\\/flow-tests\\/pre-saddle-1a.vlad@ from the\n-- VLAD compiler Stalingrad sources. Its output is a stream of\n-- increasingly accurate results. (Modulo the usual caveats.)\n--\n-- It uses reverse mode automatic differentiation to compute the gradient.\ngradientDescent :: (Traversable f, Fractional a, Ord a) => (forall s. Reifies s Tape => f (Reverse s a) -> Reverse s a) -> f a -> [f a]\ngradientDescent f x0 = go x0 fx0 xgx0 0.1 (0 :: Int)\n where\n (fx0, xgx0) = Reverse.gradWith' (,) f x0\n go x fx xgx !eta !i\n | eta == 0 = [] -- step size is 0\n | fx1 > fx = go x fx xgx (eta/2) 0 -- we stepped too far\n | zeroGrad xgx = [] -- gradient is 0\n | otherwise = x1 : if i == 10\n then go x1 fx1 xgx1 (eta*2) 0\n else go x1 fx1 xgx1 eta (i+1)\n where\n zeroGrad = all (\\(_,g) -> g == 0)\n x1 = fmap (\\(xi,gxi) -> xi - eta * gxi) xgx\n (fx1, xgx1) = Reverse.gradWith' (,) f x1\n{-# INLINE gradientDescent #-}\n\n-- | Perform a gradient descent using reverse mode automatic differentiation to compute the gradient.\ngradientAscent :: (Traversable f, Fractional a, Ord a) => (forall s. Reifies s Tape => f (Reverse s a) -> Reverse s a) -> f a -> [f a]\ngradientAscent f = gradientDescent (negate . f)\n{-# INLINE gradientAscent #-}\n\n-- | Perform a conjugate gradient descent using reverse mode automatic differentiation to compute the gradient, and using forward-on-forward mode for computing extrema.\n--\n-- >>> let sq x = x * x\n-- >>> let rosenbrock [x,y] = sq (1 - x) + 100 * sq (y - sq x)\n-- >>> rosenbrock [0,0]\n-- 1\n-- >>> rosenbrock (conjugateGradientDescent rosenbrock [0, 0] !! 5) < 0.1\n-- True\nconjugateGradientDescent\n :: (Traversable f, Ord a, Fractional a)\n => (forall s. Chosen s => f (Or s (On (Forward (Forward a))) (Kahn a)) -> Or s (On (Forward (Forward a))) (Kahn a))\n -> f a -> [f a]\nconjugateGradientDescent f = conjugateGradientAscent (negate . f)\n{-# INLINE conjugateGradientDescent #-}\n\nlfu :: Functor f => (f (Or F a b) -> Or F a b) -> f a -> a\nlfu f = runL . f . fmap L\n\nrfu :: Functor f => (f (Or T a b) -> Or T a b) -> f b -> b\nrfu f = runR . f . fmap R\n\n-- | Perform a conjugate gradient ascent using reverse mode automatic differentiation to compute the gradient.\nconjugateGradientAscent\n :: (Traversable f, Ord a, Fractional a)\n => (forall s. Chosen s => f (Or s (On (Forward (Forward a))) (Kahn a)) -> Or s (On (Forward (Forward a))) (Kahn a))\n -> f a -> [f a]\nconjugateGradientAscent f x0 = takeWhile (all (\\a -> a == a)) (go x0 d0 d0 delta0)\n where\n dot x y = sum $ zipWithT (*) x y\n d0 = Kahn.grad (rfu f) x0\n delta0 = dot d0 d0\n go xi _ri di deltai = xi : go xi1 ri1 di1 deltai1\n where\n ai = last $ take 20 $ Rank1.extremum (\\a -> lfu f $ zipWithT (\\x d -> auto x + a * auto d) xi di) 0\n xi1 = zipWithT (\\x d -> x + ai*d) xi di\n ri1 = Kahn.grad (rfu f) xi1\n deltai1 = dot ri1 ri1\n bi1 = deltai1 / deltai\n di1 = zipWithT (\\r d -> r + bi1 * d) ri1 di\n{-# INLINE conjugateGradientAscent #-}\n", "meta": {"hexsha": "8d2ba6a6643697ca72d3d6c44e6edcd0f5cac7cc", "size": 6714, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/AD/Newton.hs", "max_stars_repo_name": "silky/ad", "max_stars_repo_head_hexsha": "ea7eaafaf9f287eee3ac809d4c300af10282af5f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T11:33:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T11:33:31.000Z", "max_issues_repo_path": "src/Numeric/AD/Newton.hs", "max_issues_repo_name": "silky/ad", "max_issues_repo_head_hexsha": "ea7eaafaf9f287eee3ac809d4c300af10282af5f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/AD/Newton.hs", "max_forks_repo_name": "silky/ad", "max_forks_repo_head_hexsha": "ea7eaafaf9f287eee3ac809d4c300af10282af5f", "max_forks_repo_licenses": ["BSD-3-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.4941176471, "max_line_length": 168, "alphanum_fraction": 0.6306225797, "num_tokens": 2020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5488263640922261}} {"text": "module XAlg.Languages.Arithmetic.Expr (\n-- * Core data types\n Expr (..),\n Expr_ (..),\n\n-- * Parsing\n lit,\n term,\n expr,\n\n-- * Evaluation\n eval\n\n) where\n\nimport XAlg.Languages.Arithmetic.Number\nimport XAlg.Foundation.Recursion\nimport XAlg.Foundation.Core\nimport XAlg.Foundation.Parsing\n\nimport Data.Set\nimport Data.Data\nimport qualified Data.Map as M\n\nimport Text.Megaparsec\nimport Text.Megaparsec.String\nimport Text.Megaparsec.Expr\nimport Text.Megaparsec.Lexer (float)\nimport qualified Data.Complex as C\n\n-- | Arithmetical expression.\ndata Expr = Lit Number\n | Var String\n | Plus Expr Expr\n | Minus Expr Expr\n | Mult Expr Expr\n | Div Expr Expr\n | Power Expr Expr\n | Neg Expr\n deriving (Show, Eq, Ord, Data)\n\ninfixl 6 `Plus`\ninfixl 6 `Minus`\ninfixl 8 `Mult`\ninfixl 8 `Div`\ninfixl 9 `Power`\n\n\ninstance Num Expr where\n (*) = Mult\n (+) = Plus\n negate = Neg\n abs = undefined\n signum = undefined\n fromInteger = Lit . Int\n\n\ninstance RecursiveData Expr where\n nodeEquality (Lit x) (Lit y) = x == x\n nodeEquality (Var x) (Var y) = x == x\n nodeEquality (Plus _ _) (Plus _ _) = True\n nodeEquality (Minus _ _) (Minus _ _) = True\n nodeEquality (Mult _ _) (Mult _ _) = True\n nodeEquality (Div _ _) (Div _ _) = True\n nodeEquality (Power _ _) (Power _ _) = True\n nodeEquality (Neg _) (Neg _) = True\n nodeEquality _ _ = False\n\n children (Lit x) = []\n children (Var x) = []\n children (Plus x1 x2) = [x1,x2]\n children (Minus x1 x2) = [x1,x2]\n children (Mult x1 x2) = [x1,x2]\n children (Div x1 x2) = [x1,x2]\n children (Power x1 x2) = [x1,x2]\n children (Neg x) = [x]\n\n mapChildren f (Lit x) = Lit x\n mapChildren f (Var x) = Var x\n mapChildren f (Plus x1 x2) = recursively f x1 `Plus` recursively f x2\n mapChildren f (Minus x1 x2) = recursively f x1 `Minus` recursively f x2\n mapChildren f (Mult x1 x2) = recursively f x1 `Mult` recursively f x2\n mapChildren f (Div x1 x2) = recursively f x1 `Div` recursively f x2\n mapChildren f (Power x1 x2) = recursively f x1 `Power` recursively f x2\n mapChildren f (Neg x) = Neg (recursively f x)\n\n\ninstance SymbolicLang Expr Number where\n variable = Var\n isVariable (Var v) = Just v\n isVariable _ = Nothing\n literal = Lit\n isLiteral (Lit x) = Just x\n isLiteral _ = Nothing\n evaluate = eval\n\n\n-----------------------------------------------------------------------------\n-- Functorial data type\n-----------------------------------------------------------------------------\n\ndata Expr_ a = Lit_ Number\n | Var_ String\n | Plus_ a a\n | Minus_ a a\n | Mult_ a a\n | Div_ a a\n | Power_ a a\n | Neg_ a\n deriving (Functor, Foldable, Traversable, Data)\n\n\ninstance Fixable Expr_ Expr where\n foldFix (Lit_ x) = Lit x\n foldFix (Var_ x) = Var x\n foldFix (Plus_ x1 x2) = Plus x1 x2\n foldFix (Minus_ x1 x2) = Minus x1 x2\n foldFix (Mult_ x1 x2) = Mult x1 x2\n foldFix (Div_ x1 x2) = Div x1 x2\n foldFix (Power_ x1 x2) = Power x1 x2\n foldFix (Neg_ x) = Neg x\n\n unfoldFix (Lit x) = Lit_ x\n unfoldFix (Var x) = Var_ x\n unfoldFix (Plus x1 x2) = Plus_ x1 x2\n unfoldFix (Minus x1 x2) = Minus_ x1 x2\n unfoldFix (Mult x1 x2) = Mult_ x1 x2\n unfoldFix (Div x1 x2) = Div_ x1 x2\n unfoldFix (Power x1 x2) = Power_ x1 x2\n unfoldFix (Neg x) = Neg_ x\n\ninstance ParaSymb Expr_ where\n isVariable_ (Var_ v) = Just v\n isVariable_ _ = Nothing\n variable_ = Var_\n\n\n\nderiving instance Show a => Show (Expr_ a)\nderiving instance Show (Fix Expr_)\n\nderiving instance Eq a => Eq (Expr_ a)\nderiving instance Eq (Fix Expr_)\n\n-----------------------------------------------------------------------------\n-- Parsing\n-----------------------------------------------------------------------------\n\nimaginaryFloat :: Parser (C.Complex Double)\nimaginaryFloat = fmap (0 C.:+)\n $ char 'i' *> float <|> float <* char 'i'\n\nimaginaryInt :: Parser (C.Complex Double)\nimaginaryInt = fmap ((0 C.:+) . fromInteger)\n $ char 'i' *> integ <|> integ <* char 'i'\n\nimaginary :: Parser (C.Complex Double)\nimaginary = imaginaryInt <|> imaginaryFloat \"imaginary number\"\n\n-- | Parse a numeric literal.\nlit :: Parser Number\nlit = try (Complex <$> imaginary)\n <|> try (Real <$> float)\n <|> Int <$> integ\n\n-- | Parser an arithmetic expression term.\nterm :: Parser Expr\nterm = parens expr <|> var <|> Lit <$> lit \"term\"\n\n-- | Parse an arithmetic expression.\nexpr :: Parser Expr\nexpr = makeExprParser term table \"expression\"\n\n-- Must be a better way to get spaces:\ntable :: [[Operator Parser Expr]]\ntable = [ prefix \"-\" Neg\n , binary \"^\" Power\n , binary \"*\" Mult ++ binary \"/\" Div\n , binary \"+\" Plus ++ binary \"-\" Minus\n ]\n\n\ninstance Parsable Expr where\n exprParser = expr\n\n\n\n-----------------------------------------------------------------------------\n-- Pretty printing\n-----------------------------------------------------------------------------\n\n-- Only Minus is special, second argument has higher precedence.\nshowNodes :: Algebra Expr_ (Int, String)\nshowNodes (Lit_ x) = (5, show x)\nshowNodes (Var_ x) = (5, x)\nshowNodes (Plus_ x1 x2) = (1, applyParens 1 x1 ++ \" + \" ++ applyParens 1 x2)\nshowNodes (Mult_ x1 x2) = (3, applyParens 3 x1 ++ \"*\" ++ applyParens 3 x2)\nshowNodes (Neg_ x) = (5, \"-\" ++ applyParens 5 x)\nshowNodes (Minus_ x1 x2) = (1, applyParens 1 x1 ++ \" - \" ++ applyParens 2 x2)\nshowNodes (Div_ x1 x2) = (3, applyParens 3 x1 ++ \"/\" ++ applyParens 3 x2)\nshowNodes (Power_ x1 x2) = (4, applyParens 4 x1 ++ \"^\" ++ applyParens 4 x2)\n\n-- target prec, (node prec, shown term) -> apply parens if necessary\napplyParens :: Int -> (Int,String) -> String\napplyParens t (n,str) = if n < t then parenthesize str else str\n\nparenthesize :: String -> String\nparenthesize s = \"(\" ++ s ++ \")\"\n\n\ninstance Renderable Expr where\n render = snd . catamap showNodes\n\ninstance Transcribe Expr\n\ninstance XAlgLang Expr Expr_ Number\n\n\n-------\n\n\ncountNode :: Algebra Expr_ Int\ncountNode (Lit_ x) = 1\ncountNode (Var_ x) = 1\ncountNode (Plus_ x1 x2) = x1 + x2\ncountNode (Mult_ x1 x2) = x1 + x2\ncountNode (Minus_ x1 x2) = x1 + x2\ncountNode (Div_ x1 x2) = x1 + x2\ncountNode (Power_ x1 x2) = x1 + x2\ncountNode (Neg_ x) = succ x\n\n\ncountNodes :: Expr -> Int\ncountNodes = catamap countNode\n\n\n-------\n\ndata Mode = IntMode\n | RealMode\n | ComplexMode deriving (Eq,Ord)\n\ninstance Show Mode where\n show IntMode = \"ℤ\"\n show RealMode = \"ℝ\"\n show ComplexMode = \"ℂ\"\n\nlitMode :: Number -> Mode\nlitMode (Real _) = RealMode\nlitMode (Int _) = IntMode\nlitMode (Complex _) = ComplexMode\n\nmodeNodes :: Algebra Expr_ Mode\nmodeNodes (Lit_ x) = litMode x\nmodeNodes (Var_ x) = IntMode\nmodeNodes (Plus_ x1 x2) = x1 `max` x2\nmodeNodes (Minus_ x1 x2) = x1 `max` x2\nmodeNodes (Mult_ x1 x2) = x1 `max` x2\nmodeNodes (Div_ x1 x2) = x1 `max` x2\nmodeNodes (Power_ x1 x2) = x1 `max` x2\nmodeNodes (Neg_ x) = x\n\n\n---------\n\n\nevalNode :: Algebra Expr_ (EvalResult Expr Number)\nevalNode (Lit_ x) = ValueResult x\nevalNode (Var_ x) = FunctionResult (singleton x) (Var x)\nevalNode (Plus_ x1 x2) = combineWith Plus (+) x1 x2\nevalNode (Minus_ x1 x2) = combineWith Minus (-) x1 x2\nevalNode (Mult_ x1 x2) = combineWith Mult (*) x1 x2\nevalNode (Div_ x1 x2) = combineWith Div (/) x1 x2\nevalNode (Power_ x1 x2) = combineWith Power (**) x1 x2\nevalNode (Neg_ x) = applyWith Neg negate x\n\nevalNodeCtx :: Env Expr -> Algebra Expr_ (EvalResult Expr Number)\nevalNodeCtx m (Var_ s) = case M.lookup s m of\n Just x -> catamap (evalNodeCtx m) x\n Nothing -> FunctionResult (singleton s) (Var s)\nevalNodeCtx _ x = evalNode x\n\neval :: Expr -> EvalResult Expr Number\neval = catamap evalNode\n\n\n-- helpers\n\ntype BinaryOp a = a -> a -> a\ntype UnaryOp a = a -> a\n\ncombineWith :: SymbolicLang x s => BinaryOp x -> BinaryOp s -> BinaryOp (EvalResult x s)\ncombineWith f g (FunctionResult vs x) (FunctionResult ws y) = FunctionResult (union vs ws) (f x y)\ncombineWith f g (FunctionResult vs x) (ValueResult t) = FunctionResult vs $ f x $ literal t\ncombineWith f g (ValueResult s) (FunctionResult ws y) = FunctionResult ws $ f (literal s) y\ncombineWith f g (ValueResult s) (ValueResult t) = ValueResult $ g s t\n\napplyWith :: SymbolicLang x s => UnaryOp x -> UnaryOp s -> UnaryOp (EvalResult x s)\napplyWith f g (FunctionResult s x) = FunctionResult s (f x)\napplyWith f g (ValueResult r) = ValueResult (g r)\n", "meta": {"hexsha": "5f2127cc8271d68893b7b6d4e04cc8e772f190e4", "size": 8609, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/XAlg/Languages/Arithmetic/Expr.hs", "max_stars_repo_name": "BlackBrane/xalg", "max_stars_repo_head_hexsha": "6188d0c6ed7a3c1b3215af47624688dd94d5d6f4", "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/XAlg/Languages/Arithmetic/Expr.hs", "max_issues_repo_name": "BlackBrane/xalg", "max_issues_repo_head_hexsha": "6188d0c6ed7a3c1b3215af47624688dd94d5d6f4", "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/XAlg/Languages/Arithmetic/Expr.hs", "max_forks_repo_name": "BlackBrane/xalg", "max_forks_repo_head_hexsha": "6188d0c6ed7a3c1b3215af47624688dd94d5d6f4", "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.6013289037, "max_line_length": 98, "alphanum_fraction": 0.6012312696, "num_tokens": 2684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5488263550333351}} {"text": "{-# OPTIONS_GHC -Wall #-}\n{-# LANGUAGE Trustworthy #-}\n\n{- | \nModule : Physics.Learn.Schrodinger1D\nCopyright : (c) Scott N. Walck 2015-2018\nLicense : BSD3 (see LICENSE)\nMaintainer : Scott N. Walck \nStability : experimental\n\nThis module contains functions to\nsolve the (time dependent) Schrodinger equation\nin one spatial dimension for a given potential function.\n-}\n\nmodule Physics.Learn.Schrodinger1D\n (\n -- * Potentials\n freeV\n , harmonicV\n , squareWell\n , doubleWell\n , stepV\n , wall\n -- * Initial wavefunctions\n -- , harm\n , coherent\n , gaussian\n , movingGaussian\n -- * Utilities\n , stateVectorFromWavefunction\n , hamiltonianMatrix\n , expectX\n , picture\n , xRange\n , listForm\n )\n where\n\nimport Data.Complex\n ( Complex(..)\n , magnitude\n )\nimport Graphics.Gloss\n ( Picture(..)\n , yellow\n , black\n , Display(..)\n , display\n )\n-- import Math.Polynomial.Hermite\n-- ( evalPhysHermite\n-- )\nimport Numeric.LinearAlgebra\n ( R\n , C\n , Vector\n , Matrix\n , (|>)\n , (<.>)\n , fromLists\n , toList\n , size\n )\nimport Physics.Learn.QuantumMat\n ( probVector\n , timeEv\n )\n\n--i :: Complex Double\n--i = 0 :+ 1\n\n----------------\n-- Potentials --\n----------------\n\n-- | Free potential.\n-- The potential energy is zero everywhere.\nfreeV\n :: Double -- ^ position\n -> Double -- ^ potential energy\nfreeV _x = 0\n\n-- | Harmonic potential.\n-- This is the potential energy of a linear spring.\nharmonicV\n :: Double -- ^ spring constant\n -> Double -- ^ position\n -> Double -- ^ potential energy\nharmonicV k x = k * x**2 / 2\n\n-- | A double well potential.\n-- Potential energy is a quartic function of position\n-- that gives two wells, each approximately harmonic\n-- at the bottom of the well.\ndoubleWell\n :: Double -- ^ width (for both wells and well separation)\n -> Double -- ^ energy height of barrier between wells\n -> Double -- ^ position\n -> Double -- ^ potential energy\ndoubleWell a v0 x = v0 * ((x**2 - a**2)/a**2)**2\n\n-- | Finite square well potential.\n-- Potential is zero inside the well,\n-- and constant outside the well.\n-- Well is centered at the origin.\nsquareWell\n :: Double -- ^ well width\n -> Double -- ^ energy height of well\n -> Double -- ^ position\n -> Double -- ^ potential energy\nsquareWell l v0 x\n | abs x < l/2 = 0\n | otherwise = v0\n\n-- | A step barrier potential.\n-- Potential is zero to left of origin.\nstepV\n :: Double -- ^ energy height of barrier (to the right of origin)\n -> Double -- ^ position\n -> Double -- ^ potential energy\nstepV v0 x\n | x < 0 = 0\n | otherwise = v0\n\n-- | A potential barrier with thickness and height.\nwall\n :: Double -- ^ thickness of wall\n -> Double -- ^ energy height of barrier\n -> Double -- ^ position of center of barrier\n -> Double -- ^ position\n -> Double -- ^ potential energy\nwall w v0 x0 x\n | abs (x-x0) < w/2 = v0\n | otherwise = 0\n\n---------------------------\n-- Initial wavefunctions --\n---------------------------\n\n-- -- | Harmonic oscillator stationary state\n-- harm :: Int -- ^ nonnegative integer n identifying stationary state\n-- -> Double -- ^ x / sqrt(hbar/(m * omega)), i.e. position\n-- -- in units of sqrt(hbar/(m * omega))\n-- -> C -- ^ complex amplitude\n-- harm n u\n-- = exp (-u**2/2) * evalPhysHermite n u / sqrt (2^n * fact n * sqrt pi) :+ 0\n\ncoherent\n :: R -- ^ length scale = sqrt(hbar / m omega)\n -> C -- ^ parameter z\n -> R -> C -- ^ wavefunction\ncoherent l z x\n = ((1/(pi*l**2))**0.25 * exp(-x**2/(2*l**2)) :+ 0)\n * exp(-z**2/2 + (sqrt(2/l**2) * x :+ 0) * z)\n\ngaussian\n :: R -- ^ width parameter\n -> R -- ^ center of wave packet\n -> R -> C -- ^ wavefunction\ngaussian a x0 x = exp(-(x-x0)**2/(2*a**2)) / sqrt(a * sqrt pi) :+ 0\n\nmovingGaussian\n :: R -- ^ width parameter\n -> R -- ^ center of wave packet\n -> R -- ^ l0 = hbar / p0\n -> R -> C -- ^ wavefunction\nmovingGaussian a x0 l0 x = exp((0 :+ x/l0) - ((x-x0)**2/(2*a**2) :+ 0)) / (sqrt(a * sqrt pi) :+ 0)\n\n---------------\n-- Utilities --\n---------------\n\nfact :: Int -> Double\nfact 0 = 1\nfact n = fromIntegral n * fact (n-1)\n\nlinspace :: Double -> Double -> Int -> [Double]\nlinspace left right num\n = let dx = (right - left) / fromIntegral (num - 1)\n in [ left + dx * fromIntegral n | n <- [0..num-1]]\n\n-- | Transform a wavefunction into a state vector.\nstateVectorFromWavefunction :: R -- ^ lowest x\n -> R -- ^ highest x\n -> Int -- ^ dimension of state vector\n -> (R -> C) -- ^ wavefunction\n -> Vector C -- ^ state vector\nstateVectorFromWavefunction left right num psi\n = (num |>) [psi x | x <- linspace left right num]\n\nhamiltonianMatrix :: R -- ^ lowest x\n -> R -- ^ highest x\n -> Int -- ^ dimension of state vector\n -> R -- ^ hbar\n -> R -- ^ mass\n -> (R -> R) -- ^ potential energy function\n -> Matrix C -- ^ Hamiltonian Matrix\nhamiltonianMatrix xmin xmax num hbar m pe\n = let coeff = -hbar**2/(2*m)\n dx = (xmax - xmin) / fromIntegral (num - 1)\n diagKEterm = -2 * coeff / dx**2\n offdiagKEterm = coeff / dx**2\n xs = linspace xmin xmax num\n in fromLists [[case abs(i-j) of\n 0 -> (diagKEterm + pe x) :+ 0\n 1 -> offdiagKEterm :+ 0\n _ -> 0\n | j <- [1..num] ] | (i,x) <- zip [1..num] xs]\n\nexpectX :: Vector C -- ^ state vector\n -> Vector R -- ^ vector of x values\n -> R -- ^ , expectation value of X\nexpectX psi xs = probVector psi <.> xs\n\n\nglossScaleX :: Int -> (Double,Double) -> Double -> Float\nglossScaleX screenWidth (xmin,xmax) x\n = let w = fromIntegral screenWidth :: Double\n in realToFrac $ (x - xmin) / (xmax - xmin) * w - w / 2\n\nglossScaleY :: Int -> (Double,Double) -> Double -> Float\nglossScaleY screenHeight (ymin,ymax) y\n = let h = fromIntegral screenHeight :: Double\n in realToFrac $ (y - ymin) / (ymax - ymin) * h - h / 2\n\nglossScalePoint :: (Int,Int) -- ^ (screenWidth,screenHeight)\n -> (Double,Double) -- ^ (xmin,xmax)\n -> (Double,Double) -- ^ (ymin,ymax)\n -> (Double,Double) -- ^ (x,y)\n -> (Float,Float)\nglossScalePoint (screenWidth,screenHeight) xMinMax yMinMax (x,y)\n = (glossScaleX screenWidth xMinMax x\n ,glossScaleY screenHeight yMinMax y)\n\n\n-- | Produce a gloss 'Picture' of state vector\n-- for 1D wavefunction.\npicture :: (Double, Double) -- ^ y range\n -> [Double] -- ^ xs\n -> Vector C -- ^ state vector\n -> Picture\npicture (ymin,ymax) xs psi\n = Color\n yellow\n (Line\n [glossScalePoint\n (screenWidth,screenHeight)\n (head xs, last xs)\n (ymin,ymax)\n p | p <- zip xs (map magSq $ toList psi)])\n where\n magSq = \\z -> magnitude z ** 2\n screenWidth = 1000\n screenHeight = 750\n\n-- options for representing wave functions\n-- 1. A function R -> C\n-- 2. ([R],Vector C), where lengths match\n-- 3. [(R,C)]\n-- 4. (R,R,Vector C) -- xmin, xmax, state vector (assumes even spacing)\n\n-- 2,4 are best for evolution\n\nlistForm :: (R,R,Vector C) -> ([R],Vector C)\nlistForm (xmin,xmax,v)\n = let dt = (xmax - xmin) / fromIntegral (size v - 1)\n in ([xmin, xmin + dt .. xmax],v)\n\n\n{-\n-- | Given an initial state vector and\n-- state propagation function, produce a simulation.\n-- The 'Float' in the state propagation function is the time\n-- interval for one timestep.\nsimulate1D :: [Double] -> Vector C -> (Float -> (Float,[Double],Vector C) -> (Float,[Double],Vector C)) -> IO ()\nsimulate1D xs initial statePropFunc\n = simulate display black 10 (0,initial) displayFunc (const statePropFunc)\n where\n display = InWindow \"Animation\" (screenWidth,screenHeight) (10,10)\n displayFunc (_t,v) = Color yellow (Line [(\n \n white (\\tFloat -> Pictures [Color blue (Line (points (realToFrac tFloat)))\n ,axes (screenWidth,screenHeight) (xmin,xmax) (ymin,ymax)])\n\n-- | Produce a state propagation function from a time-dependent Hamiltonian.\n-- The float is dt.\nstatePropGloss :: (Double -> Matrix C) -> Float -> (Float,Vector C) -> (Float,Vector C)\nstatePropGloss ham dt (tOld,v)\n = (tNew, timeEv (realToFrac dt) (ham tMid) v)\n where\n tNew = tOld + dt\n tMid = realToFrac $ (tNew + tOld) / 2\n\n-- | Given an initial state vector and a time-dependent Hamiltonian,\n-- produce a visualization of a 1D wavefunction.\nevolutionBlochSphere :: Vector C -> (Double -> Matrix C) -> IO ()\nevolutionBlochSphere psi0 ham\n = simulateBlochSphere 0.01 psi0 (stateProp ham)\n\n-}\n\n\n{-\ndef triDiagMatrixMult(square_arr,arr):\n num = len(arr)\n result = array([0 for n in range(num)],dtype=complex128)\n result[0] = square_arr[0][0] * arr[0] + square_arr[0][1] * arr[1]\n for n in range(1,num-1):\n result[n] = square_arr[n][n-1] * arr[n-1] + square_arr[n][n] * arr[n] \\\n + square_arr[n][n+1] * arr[n+1]\n result[num-1] = square_arr[num-1][num-2] * arr[num-2] \\\n + square_arr[num-1][num-1] * arr[num-1]\n return result\n-}\n\n------------------\n-- Main program --\n------------------\n\n-- n is number of points\n-- n-1 is number of intervals\nxRange :: R -> R -> Int -> [R]\nxRange xmin xmax n\n = let dt = (xmax - xmin) / fromIntegral (n - 1)\n in [xmin, xmin + dt .. xmax]\n\n\n{-\nif __name__ == '__main__':\n m = 1\n omega = 10\n xmin = -2.0\n xmax = 2.0\n num = 256\n num = 128\n dt = 0.0002\n dt = 0.01\n xs = linspace(xmin,xmax,num)\n dx = xs[1] - xs[0]\n\n super = lambda x: (harm0(m,omega)(x) + harm1(m,omega)(x))/sqrt(2)\n shiftedHarm = lambda x: harm0(m,omega)(x-1)\n coh = coherent(m,omega,1)\n\n print sum(conj(psi)*psi)*dx\n\n harmV = harmonicV(m * omega**2)\n\n V = doubleWell(1,0.1*hbar*omega)\n V = squareWell(1.0,hbar*omega)\n V = harmonicV(m*omega**2)\n V = stepV(10*hbar*omega)\n V = wall(0.1,14.0*hbar*omega,0)\n V = freeV\n\n H = matrixH(m,xmin,xmax,num,V)\n I = matrixI(num)\n\n (vals,vecs) = eigh(H)\n\n E0 = vals[0]\n E1 = vals[1]\n psi0 = normalize(transpose(vecs)[0],dx)\n psi1 = normalize(transpose(vecs)[1],dx)\n\n psi = func2psi(gaussian(0.3,1),xmin,xmax,num)\n psi = func2psi(coh,xmin,xmax,num)\n psi = func2psi(movingGaussian(0.3,10,-1),xmin,xmax,num)\n\n psi = psi0\n psi = psi1\n psi = (psi0 + psi1)/sqrt(2)\n\n E = sum(conj(psi)*triDiagMatrixMult(H,psi)).real*dx\n\n Escale = hbar*omega\n\n print E\n print Escale\n\n leftM = I + 0.5 * i * H / hbar * dt\n rightM = I - 0.5 * i * H / hbar * dt\n\n box = display(title='Schrodinger Equation',width=1000,height=1000)\n\n c = curve(pos = psi2rho(psi,xs))\n c.color = color.blue\n c.radius = 0.02\n\n ball = sphere(radius=0.05,color=color.red,pos=(expectX(psi,xs),0,0))\n\n pot_curve = [(x,V(x)/Escale,0) for x in xs if V(x)/Escale < xmax]\n pot = curve(color=color.green,pos=pot_curve,radius=0.01)\n\n Eline = curve(color=(1,1,0),pos=[(x,E/Escale) for x in xs])\n axis = curve(color=color.white,pos=[(x,0) for x in xs])\n\n while 1:\n psi = solve(leftM,triDiagMatrixMult(rightM,psi))\n c.pos = psi2rho(psi,xs)\n ball.x = expectX(psi,xs)\n\nTo Do:\nadd combinators for potentials\nto shift horizontally and vertically,\nand to add potentials\n\n-}\n\n-- Are we committed to SI units for hbar? No.\n-- harmonic oscillator functions depend only on sqrt(hbar/m omega)\n-- which is a length parameter\n-- for moving gaussian, could give hbar/p0 instead of p0\n-- (is that debrogie wavelength? I think it's h/p0)\n", "meta": {"hexsha": "a791583e1638603853da3fb3db605dd468abef5a", "size": 12133, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Physics/Learn/Schrodinger1D.hs", "max_stars_repo_name": "walck/learn-physics", "max_stars_repo_head_hexsha": "99611ca49940b78a0e13402f35082805cc7db294", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 139, "max_stars_repo_stars_event_min_datetime": "2015-11-23T16:40:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:37:24.000Z", "max_issues_repo_path": "src/Physics/Learn/Schrodinger1D.hs", "max_issues_repo_name": "walck/learn-physics", "max_issues_repo_head_hexsha": "99611ca49940b78a0e13402f35082805cc7db294", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Physics/Learn/Schrodinger1D.hs", "max_forks_repo_name": "walck/learn-physics", "max_forks_repo_head_hexsha": "99611ca49940b78a0e13402f35082805cc7db294", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2016-09-16T03:54:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T15:44:56.000Z", "avg_line_length": 29.1658653846, "max_line_length": 112, "alphanum_fraction": 0.556993324, "num_tokens": 3671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5484516008910588}} {"text": "{-# LANGUAGE TemplateHaskell #-}\nmodule Lib\n ( toPicture, export, mandelbrot, burningShip\n , FractalParams(..), Size(..), Position(..), Zoom, Image\n , size, position, zoom, innerColor, outerColor\n , updatePos\n ) where\nimport Codec.BMP(writeBMP, packRGBA32ToBMP24)\nimport Codec.Picture(readBitmap, writeDynamicPng)\nimport Control.Lens(makeLenses, (^.), (+~))\nimport qualified Data.ByteString as BS\nimport Data.Complex(Complex(..),realPart,imagPart)\nimport Data.Word(Word8)\nimport qualified Graphics.Gloss as G\nimport System.Directory(removeFile)\n\ntype ColorPart = Word8\ntype Color = (ColorPart, ColorPart, ColorPart)\ntype Image = ([Color], Size)\ntype Zoom a = a\n\ndata Size = Size {width :: Int, height :: Int}\n\ndata Position a = Pos {_x :: a, _y :: a}\nmakeLenses ''Position\n\ndata FractalParams a =\n F { _size :: Size\n , _position :: Position a\n , _zoom :: Zoom a\n , _innerColor :: G.Color\n , _outerColor :: G.Color\n }\nmakeLenses ''FractalParams\n\nupdatePos :: (Real a, Fractional (Zoom b)) =>\n a -> a -> FractalParams b -> FractalParams b\nupdatePos x' y' fp = newCoord x x' . newCoord y (-y') $ fp\n where newCoord c c' = position.c +~ realToFrac c'/_zoom fp\n\ntoList :: Color -> [ColorPart]\ntoList (r, g, b) = [r, g, b, 255]\n\ntoPicture :: Image -> G.Picture\ntoPicture (pxs, s) = G.bitmapOfByteString (width s) (height s) (pixelsToByteString pxs) True\n where pixelsToByteString = BS.pack . concatMap (reverse . toList)\n\n{-# SPECIALIZE burningShip :: FractalParams Float -> Image #-}\n{-# SPECIALIZE burningShip :: FractalParams Double -> Image #-}\nburningShip :: (Enum (Zoom a), RealFloat (Zoom a)) => FractalParams a -> Image\nburningShip = generateFractal $ iterations abs (255::Int) 3\n\n{-# SPECIALIZE mandelbrot :: FractalParams Float -> Image #-}\n{-# SPECIALIZE mandelbrot :: FractalParams Double -> Image #-}\nmandelbrot :: (Enum (Zoom a), RealFloat (Zoom a)) => FractalParams a -> Image\nmandelbrot = generateFractal $ iterations id (255::Int) 3\n\ngenerateFractal :: (Enum (Zoom a), RealFloat (Zoom a), Real b) =>\n (Complex (Zoom a) -> b) -> FractalParams a -> Image\ngenerateFractal iterationFun fp = (map (getPixel' . iterationFun) coords, _size fp)\n where getPixel' = getPixel (toFloats innerColor) (toFloats outerColor)\n toFloats = G.rgbaOfColor . (fp ^.)\n coords = getCoordinates (_size fp) (toComplex $ _position fp) (_zoom fp)\n toComplex p = _x p :+ _y p\n\ngetCoordinates :: (Enum a, RealFloat a) => Size -> Complex a -> a -> [Complex a]\ngetCoordinates s p z = [ (r/z :+ i/z) + p\n | i <- reverse . range $ height s\n , r <- range $ width s]\n where range n = let half = (fromIntegral n-1)/2 in [-half..half]\n\n{-# SPECIALIZE iterations :: (Float -> Float) -> Int -> Float -> Complex Float -> Int #-}\n{-# SPECIALIZE iterations :: (Double -> Double) -> Int -> Double -> Complex Double -> Int #-}\niterations :: (Eq a, Num a, RealFloat b) => (b -> b) -> a -> b -> Complex b -> a\niterations f iterLimit zlimit c = go c 0\n where magIsGTzLimit (r:+i) = r * r + i * i > zlimit * zlimit\n go prev count | prev `seq` count == iterLimit || magIsGTzLimit prev = count\n | otherwise = go (prev'*prev' + c) (count + 1)\n where prev' = f (realPart prev) :+ f (imagPart prev)\n\ngetPixel :: (Integral a, Real b) => (Float,Float,Float,x) -> (Float,Float,Float,y) -> b -> (a,a,a)\ngetPixel (r1, g1, b1, _) (r2, g2, b2, _) n = (avg r1 r2, avg g1 g2, avg b1 b2)\n where avg start end = truncate $ 255 * (end + frac * (start - end))\n frac = logBase 1.25 (1+realToFrac n::Float)/25\n\nexport :: FilePath -> Image -> IO ()\nexport path (pxs, s) = do\n writeBMP path . packRGBA32ToBMP24 (width s) (height s) .\n BS.pack . concatMap toList $ pxs\n (Right im) <- readBitmap path\n _ <- writeDynamicPng (path ++ \".png\") im\n removeFile path\n", "meta": {"hexsha": "ac69c3405a2d6e9508383a83d09220ee60549de0", "size": 3881, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "sholland1/mandelbrot", "max_stars_repo_head_hexsha": "4fdcb9979f2c0dd03b540c8ec360a3b6201486e1", "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": "sholland1/mandelbrot", "max_issues_repo_head_hexsha": "4fdcb9979f2c0dd03b540c8ec360a3b6201486e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "sholland1/mandelbrot", "max_forks_repo_head_hexsha": "4fdcb9979f2c0dd03b540c8ec360a3b6201486e1", "max_forks_repo_licenses": ["BSD-3-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.7311827957, "max_line_length": 98, "alphanum_fraction": 0.6369492399, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5483272305379588}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE NoStarIsType #-}\n{-# OPTIONS_GHC -Wno-redundant-constraints #-}\n{-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-}\n\n-- | Arrays with a fixed shape, with a HMatrix representation.\nmodule NumHask.Array.HMatrix\n ( -- $usage\n Array (..),\n\n -- * Representation\n --\n -- With no functor instance, we instead supply the representable API\n index,\n tabulate,\n\n -- * Conversion\n shape,\n toDynamic,\n toFixed,\n fromFixed,\n\n -- * Operators\n reshape,\n transpose,\n diag,\n ident,\n singleton,\n selects,\n selectsExcept,\n folds,\n concatenate,\n insert,\n append,\n reorder,\n expand,\n slice,\n squeeze,\n\n -- * Scalar\n --\n -- Scalar specialisations\n Scalar,\n fromScalar,\n toScalar,\n\n -- * Vector\n --\n -- Vector specialisations.\n Vector,\n\n -- * Matrix\n --\n -- Matrix specialisations.\n Matrix,\n col,\n row,\n safeCol,\n safeRow,\n mmult,\n )\nwhere\n\nimport qualified Data.Vector as V\nimport GHC.Exts (IsList (..))\nimport GHC.TypeLits\nimport qualified NumHask.Array.Dynamic as D\nimport qualified NumHask.Array.Fixed as F\nimport NumHask.Array.Shape\nimport NumHask.Prelude as P\nimport qualified Numeric.LinearAlgebra as H\nimport qualified Numeric.LinearAlgebra.Devel as H\nimport qualified Prelude\nimport Data.Proxy (Proxy(..))\n\n-- $setup\n-- >>> :set -XDataKinds\n-- >>> :set -XOverloadedLists\n-- >>> :set -XTypeFamilies\n-- >>> :set -XFlexibleContexts\n-- >>> import GHC.TypeLits\n-- >>> import GHC.Int\n-- >>> let s = [1] :: Array ('[] :: [Nat]) Int64 -- scalar\n-- >>> let v = [1,2,3] :: Array '[3] Int64 -- vector\n-- >>> let m = [0..11] :: Array '[3,4] Int64 -- matrix\n-- >>> let a = [1..24] :: Array '[2,3,4] Int64\n\n-- | a multidimensional array with a type-level shape\n--\n-- >>> let a = [1..24] :: Array '[2,3,4] Int64\n-- >>> a\n-- [[[1, 2, 3, 4],\n-- [5, 6, 7, 8],\n-- [9, 10, 11, 12]],\n-- [[13, 14, 15, 16],\n-- [17, 18, 19, 20],\n-- [21, 22, 23, 24]]]\n--\n-- >>> [1,2,3] :: Array '[2,2] Int64\n-- [[*** Exception: NumHaskException {errorMessage = \"shape mismatch\"}\nnewtype Array s a = Array {unArray :: H.Matrix a}\n deriving (Show, Generic)\n\ninstance\n ( Additive a,\n HasShape s,\n H.Container H.Vector a,\n Num a\n ) =>\n Additive (Array s a)\n where\n (+) (Array x1) (Array x2) = Array $ H.add x1 x2\n\n zero = Array $ H.konst zero (n, m)\n where\n s = shapeVal (toShape @s)\n [n, m] = s\n\ninstance\n ( Multiplicative a,\n HasShape s,\n H.Container H.Vector a,\n Num (H.Vector a),\n Num a\n ) =>\n Multiplicative (Array s a)\n where\n (*) (Array x1) (Array x2) = Array $ H.liftMatrix2 (Prelude.*) x1 x2\n\n one = Array $ H.konst one (n, m)\n where\n s = shapeVal (toShape @s)\n [n, m] = s\n\n-- (<.>) (Array a) (Array b) = H.sumElements $ H.liftMatrix2 (Prelude.*) a b\n\ninstance\n ( Subtractive a,\n HasShape s,\n H.Container H.Vector a,\n Num a\n ) =>\n Subtractive (Array s a)\n where\n negate (Array x1) = Array $ H.cmap negate x1\n\ninstance\n (HasShape s, Multiplicative a, H.Container H.Vector a, Num a) =>\n MultiplicativeAction (Array s a) a\n where\n (.*) s (Array r) = Array $ H.cmap (s *) r\n {-# INLINE (.*) #-}\n\n (*.) (Array r) s = Array $ H.cmap (*s) r\n {-# INLINE (*.) #-}\n\ninstance\n (HasShape s, Additive a, H.Container H.Vector a, Num a) =>\n AdditiveAction (Array s a) a\n where\n (.+) s (Array r) = Array $ H.cmap (s +) r\n {-# INLINE (.+) #-}\n\n (+.) (Array r) s = Array $ H.cmap (+s) r\n {-# INLINE (+.) #-}\n\ninstance\n (HasShape s, Subtractive a, H.Container H.Vector a, Num a) =>\n SubtractiveAction (Array s a) a\n where\n (.-) s (Array r) = Array $ H.cmap (s -) r\n {-# INLINE (.-) #-}\n\n (-.) (Array r) s = Array $ H.cmap (\\x -> x - s) r\n {-# INLINE (-.) #-}\n\ninstance\n (HasShape s, Divisive a, H.Container H.Vector a, Num a) =>\n DivisiveAction (Array s a) a\n where\n (./) s (Array r) = Array $ H.cmap (s /) r\n {-# INLINE (./) #-}\n\n (/.) (Array r) s = Array $ H.cmap (/ s) r\n {-# INLINE (/.) #-}\n\n-- | from flat list\ninstance\n ( HasShape s,\n H.Element a\n ) =>\n IsList (Array s a)\n where\n type Item (Array s a) = a\n\n fromList l =\n bool\n (throw (NumHaskException \"shape mismatch\"))\n (Array $ H.reshape n $ H.fromList l)\n ((length l == 1 && null s) || (length l == size s))\n where\n s = shapeVal (toShape @s)\n n = Prelude.last s\n\n toList (Array v) = H.toList $ H.flatten v\n\n-- | Get shape of an Array as a value.\n--\n-- >>> shape a\n-- [2,3,4]\nshape :: forall a s. (HasShape s) => Array s a -> [Int]\nshape _ = shapeVal $ toShape @s\n{-# INLINE shape #-}\n\n-- | Convert to a dynamic array.\ntoDynamic :: (HasShape s, H.Element a) => Array s a -> D.Array a\ntoDynamic a@(Array h) = D.fromFlatList (shape a) (mconcat $ H.toLists h)\n\n-- | Convert to a fixed array.\ntoFixed :: (HasShape s, H.Element a) => Array s a -> F.Array s a\ntoFixed (Array h) = fromList (mconcat $ H.toLists h)\n\n-- | Convert from a fixed array.\nfromFixed :: (HasShape s, H.Element a) => F.Array s a -> Array s a\nfromFixed a = fromList (P.toList a)\n\n-- | with no fmap, we supply the representable API\nindex ::\n forall s a.\n ( HasShape s,\n H.Element a,\n H.Container H.Vector a\n ) =>\n Array s a ->\n [Int] ->\n a\nindex (Array v) i = H.flatten v `H.atIndex` flatten s i\n where\n s = shapeVal (toShape @s)\n\n-- | tabulate an array with a generating function\n--\n-- >>> tabulate [2,3,4] ((1+) . flatten [2,3,4]) == a\n-- True\ntabulate ::\n forall s a.\n ( HasShape s,\n H.Element a\n ) =>\n ([Int] -> a) ->\n Array s a\ntabulate f =\n fromList (V.toList $ V.generate (size s) (f . shapen s))\n where\n s = shapeVal (toShape @s)\n\n-- | Reshape an array (with the same number of elements).\n--\n-- >>> reshape a :: Array '[4,3,2] Int64\n-- [[[1, 2],\n-- [3, 4],\n-- [5, 6]],\n-- [[7, 8],\n-- [9, 10],\n-- [11, 12]],\n-- [[13, 14],\n-- [15, 16],\n-- [17, 18]],\n-- [[19, 20],\n-- [21, 22],\n-- [23, 24]]]\nreshape ::\n forall a s s'.\n ( Size s ~ Size s',\n HasShape s,\n HasShape s',\n H.Container H.Vector a\n ) =>\n Array s a ->\n Array s' a\nreshape a = tabulate (index a . shapen s . flatten s')\n where\n s = shapeVal (toShape @s)\n s' = shapeVal (toShape @s')\n\n-- | Reverse indices eg transposes the element A/ijk/ to A/kji/.\n--\n-- >>> index (transpose a) [1,0,0] == index a [0,0,1]\n-- True\ntranspose :: forall a s. (H.Element a, H.Container H.Vector a, HasShape s, HasShape (Reverse s)) => Array s a -> Array (Reverse s) a\ntranspose a = tabulate (index a . reverse)\n\n-- | The identity array.\n--\n-- >>> ident :: Array '[3,2] Int64\n-- [[1, 0],\n-- [0, 1],\n-- [0, 0]]\nident :: forall a s. (H.Element a, H.Container H.Vector a, HasShape s, Additive a, Multiplicative a) => Array s a\nident = tabulate (bool zero one . isDiag)\n where\n isDiag [] = True\n isDiag [_] = True\n isDiag [x, y] = x == y\n isDiag (x : y : xs) = x == y && isDiag (y : xs)\n\n-- | Extract the diagonal of an array.\n--\n-- >>> diag (ident :: Array '[3,2] Int64)\n-- [1, 1]\ndiag ::\n forall a s.\n ( HasShape s,\n HasShape '[Minimum s],\n H.Element a,\n H.Container H.Vector a\n ) =>\n Array s a ->\n Array '[Minimum s] a\ndiag a = tabulate go\n where\n go [] = throw (NumHaskException \"Rank Underflow\")\n go (s' : _) = index a (replicate (length ds) s')\n ds = shapeVal (toShape @s)\n\n-- | Create an array composed of a single value.\n--\n-- >>> singleton one :: Array '[3,2] Int64\n-- [[1, 1],\n-- [1, 1],\n-- [1, 1]]\nsingleton :: (H.Element a, H.Container H.Vector a, HasShape s) => a -> Array s a\nsingleton a = tabulate (const a)\n\n-- | Select an array along dimensions.\n--\n-- >>> let s = selects (Proxy :: Proxy '[0,1]) [1,1] a\n-- >>> :t s\n-- s :: Array '[4] Int64\n--\n-- >>> s\n-- [17, 18, 19, 20]\nselects ::\n forall ds s s' a.\n ( HasShape s,\n HasShape ds,\n HasShape s',\n s' ~ DropIndexes s ds,\n H.Element a,\n H.Container H.Vector a\n ) =>\n Proxy ds ->\n [Int] ->\n Array s a ->\n Array s' a\nselects _ i a = tabulate go\n where\n go s = index a (addIndexes s ds i)\n ds = shapeVal (toShape @ds)\n\n-- | Select an index /except/ along specified dimensions.\n--\n-- >>> let s = selectsExcept (Proxy :: Proxy '[2]) [1,1] a\n-- >>> :t s\n-- s :: Array '[4] Int64\n--\n-- >>> s\n-- [17, 18, 19, 20]\nselectsExcept ::\n forall ds s s' a.\n ( HasShape s,\n HasShape ds,\n HasShape s',\n s' ~ TakeIndexes s ds,\n H.Element a,\n H.Container H.Vector a\n ) =>\n Proxy ds ->\n [Int] ->\n Array s a ->\n Array s' a\nselectsExcept _ i a = tabulate go\n where\n go s = index a (addIndexes i ds s)\n ds = shapeVal (toShape @ds)\n\n-- | Fold along specified dimensions.\n--\n-- >>> folds sum (Proxy :: Proxy '[1]) a\n-- [68, 100, 132]\nfolds ::\n forall ds st si so a b.\n ( HasShape st,\n HasShape ds,\n HasShape si,\n HasShape so,\n si ~ DropIndexes st ds,\n so ~ TakeIndexes st ds,\n H.Element a,\n H.Container H.Vector a,\n H.Element b,\n H.Container H.Vector b\n ) =>\n (Array si a -> b) ->\n Proxy ds ->\n Array st a ->\n Array so b\nfolds f d a = tabulate go\n where\n go s = f (selects d s a)\n\n-- | Concatenate along a dimension.\n--\n-- >>> :t concatenate (Proxy :: Proxy 1) a a\n-- concatenate (Proxy :: Proxy 1) a a :: Array '[2, 6, 4] Int64\nconcatenate ::\n forall a s0 s1 d s.\n ( CheckConcatenate d s0 s1 s,\n Concatenate d s0 s1 ~ s,\n HasShape s0,\n HasShape s1,\n HasShape s,\n KnownNat d,\n H.Element a,\n H.Container H.Vector a\n ) =>\n Proxy d ->\n Array s0 a ->\n Array s1 a ->\n Array s a\nconcatenate _ s0 s1 = tabulate go\n where\n go s =\n bool\n (index s0 s)\n ( index\n s1\n ( addIndex\n (dropIndex s d)\n d\n ((s !! d) - (ds0 !! d))\n )\n )\n ((s !! d) >= (ds0 !! d))\n ds0 = shapeVal (toShape @s0)\n d = fromIntegral $ natVal @d Proxy\n\n-- | Insert along a dimension at a position.\n--\n-- >>> insert (Proxy :: Proxy 2) (Proxy :: Proxy 0) a ([100..105])\n-- [[[100, 1, 2, 3, 4],\n-- [101, 5, 6, 7, 8],\n-- [102, 9, 10, 11, 12]],\n-- [[103, 13, 14, 15, 16],\n-- [104, 17, 18, 19, 20],\n-- [105, 21, 22, 23, 24]]]\ninsert ::\n forall a s s' d i.\n ( DropIndex s d ~ s',\n CheckInsert d i s,\n KnownNat i,\n KnownNat d,\n HasShape s,\n HasShape s',\n HasShape (Insert d s),\n H.Element a,\n H.Container H.Vector a\n ) =>\n Proxy d ->\n Proxy i ->\n Array s a ->\n Array s' a ->\n Array (Insert d s) a\ninsert _ _ a b = tabulate go\n where\n go s\n | s !! d == i = index b (dropIndex s d)\n | s !! d < i = index a s\n | otherwise = index a (decAt d s)\n d = fromIntegral $ natVal @d Proxy\n i = fromIntegral $ natVal @i Proxy\n\n-- | Insert along a dimension at the end.\n--\n-- >>> :t append (Proxy :: Proxy 0) a\n-- append (Proxy :: Proxy 0) a\n-- :: Array '[3, 4] Int64 -> Array '[3, 3, 4] Int64\nappend ::\n forall a d s s'.\n ( DropIndex s d ~ s',\n CheckInsert d (Dimension s d - 1) s,\n KnownNat (Dimension s d - 1),\n KnownNat d,\n HasShape s,\n HasShape s',\n HasShape (Insert d s),\n H.Element a,\n H.Container H.Vector a\n ) =>\n Proxy d ->\n Array s a ->\n Array s' a ->\n Array (Insert d s) a\nappend d = insert d (Proxy :: Proxy (Dimension s d - 1))\n\n-- | Change the order of dimensions.\n--\n-- >>> let r = reorder (Proxy :: Proxy '[2,0,1]) a\n-- >>> :t r\n-- r :: Array '[4, 2, 3] Int64\nreorder ::\n forall a ds s.\n ( HasShape ds,\n HasShape s,\n HasShape (Reorder s ds),\n CheckReorder ds s,\n H.Element a,\n H.Container H.Vector a\n ) =>\n Proxy ds ->\n Array s a ->\n Array (Reorder s ds) a\nreorder _ a = tabulate go\n where\n go s = index a (addIndexes [] ds s)\n ds = shapeVal (toShape @ds)\n\n-- | Product two arrays using the supplied binary function.\n--\n-- For context, if the function is multiply, and the arrays are tensors,\n-- then this can be interpreted as a tensor product.\n--\n-- https://en.wikipedia.org/wiki/Tensor_product\n--\n-- The concept of a tensor product is a dense crossroad, and a complete treatment is elsewhere. To quote:\n--\n-- ... the tensor product can be extended to other categories of mathematical objects in addition to vector spaces, such as to matrices, tensors, algebras, topological vector spaces, and modules. In each such case the tensor product is characterized by a similar universal property: it is the freest bilinear operation. The general concept of a \"tensor product\" is captured by monoidal categories; that is, the class of all things that have a tensor product is a monoidal category.\n--\n-- >>> expand (*) v v\n-- [[1, 2, 3],\n-- [2, 4, 6],\n-- [3, 6, 9]]\nexpand ::\n forall s s' a b c.\n ( HasShape s,\n HasShape s',\n HasShape ((++) s s'),\n H.Element a,\n H.Container H.Vector a,\n H.Element b,\n H.Container H.Vector b,\n H.Element c\n ) =>\n (a -> b -> c) ->\n Array s a ->\n Array s' b ->\n Array ((++) s s') c\nexpand f a b = tabulate (\\i -> f (index a (take r i)) (index b (drop r i)))\n where\n r = rank (shape a)\n\n-- | Select elements along positions in every dimension.\n--\n-- >>> let s = slice (Proxy :: Proxy '[[0,1],[0,2],[1,2]]) a\n-- >>> :t s\n-- s :: Array '[2, 2, 2] Int64\n--\n-- >>> s\n-- [[[2, 3],\n-- [10, 11]],\n-- [[14, 15],\n-- [22, 23]]]\n--\n-- >>> let s = squeeze $ slice (Proxy :: Proxy '[ '[0], '[0], '[0]]) a\n-- >>> :t s\n-- s :: Array '[] Int64\n--\n-- >>> s\n-- 1\nslice ::\n forall (pss :: [[Nat]]) s s' a.\n ( HasShape s,\n HasShape s',\n KnownNatss pss,\n KnownNat (Rank pss),\n s' ~ Ranks pss,\n H.Element a,\n H.Container H.Vector a\n ) =>\n Proxy pss ->\n Array s a ->\n Array s' a\nslice pss a = tabulate go\n where\n go s = index a (zipWith (!!) pss' s)\n pss' = natValss pss\n\n-- | Remove single dimensions.\n--\n-- >>> let a = [1..24] :: Array '[2,1,3,4,1] Int64\n-- >>> a\n-- [[[[[1],\n-- [2],\n-- [3],\n-- [4]],\n-- [[5],\n-- [6],\n-- [7],\n-- [8]],\n-- [[9],\n-- [10],\n-- [11],\n-- [12]]]],\n-- [[[[13],\n-- [14],\n-- [15],\n-- [16]],\n-- [[17],\n-- [18],\n-- [19],\n-- [20]],\n-- [[21],\n-- [22],\n-- [23],\n-- [24]]]]]\n-- >>> squeeze a\n-- [[[1, 2, 3, 4],\n-- [5, 6, 7, 8],\n-- [9, 10, 11, 12]],\n-- [[13, 14, 15, 16],\n-- [17, 18, 19, 20],\n-- [21, 22, 23, 24]]]\n--\n-- >>> squeeze ([1] :: Array '[1,1] Double)\n-- 1.0\nsqueeze ::\n forall s t a.\n (t ~ Squeeze s) =>\n Array s a ->\n Array t a\nsqueeze (Array x) = Array x\n\n-- $scalar\n-- Scalar specialisations\n\n-- | \n--\n-- An Array '[] a despite being a Scalar is never-the-less a one-element vector under the hood. Unification of representation is unexplored.\ntype Scalar a = Array ('[] :: [Nat]) a\n\n-- | Unwrapping scalars is probably a performance bottleneck.\n--\n-- >>> let s = [3] :: Array ('[] :: [Nat]) Int64\n-- >>> fromScalar s\n-- 3\nfromScalar :: (H.Element a, H.Container H.Vector a, HasShape ('[] :: [Nat])) => Array ('[] :: [Nat]) a -> a\nfromScalar a = index a ([] :: [Int])\n\n-- | Convert a number to a scalar.\n--\n-- >>> :t toScalar 2\n-- toScalar 2 :: Num a => Array '[] a\ntoScalar :: (H.Element a, H.Container H.Vector a, HasShape ('[] :: [Nat])) => a -> Array ('[] :: [Nat]) a\ntoScalar a = fromList [a]\n\n-- | \ntype Vector s a = Array '[s] a\n\n-- | \ntype Matrix m n a = Array '[m, n] a\n\ninstance\n ( Multiplicative a,\n P.Distributive a,\n Subtractive a,\n H.Numeric a,\n KnownNat m,\n HasShape '[m, m],\n H.Element a,\n H.Container H.Vector a\n ) =>\n Multiplicative (Matrix m m a)\n where\n (*) = mmult\n\n one = ident\n\n-- | Extract specialised to a matrix.\n--\n-- >>> row 1 m\n-- [4, 5, 6, 7]\nrow :: forall m n a. (H.Element a, H.Container H.Vector a, KnownNat m, KnownNat n, HasShape '[m, n]) => Int -> Matrix m n a -> Vector n a\nrow i (Array a) = fromList $ H.toList $ H.subVector (i * n) n (H.flatten a)\n where\n n = fromIntegral $ natVal @n Proxy\n\n-- | Row extraction checked at type level.\n--\n-- >>> safeRow (Proxy :: Proxy 1) m\n-- [4, 5, 6, 7]\n--\n-- >>> safeRow (Proxy :: Proxy 3) m\n-- ...\n-- ... index outside range\n-- ...\nsafeRow :: forall m n a j. (H.Element a, H.Container H.Vector a, 'True ~ CheckIndex j m, KnownNat j, KnownNat m, KnownNat n, HasShape '[m, n]) => Proxy j -> Matrix m n a -> Vector n a\nsafeRow _j (Array a) = fromList $ H.toList $ H.subVector (j * n) n (H.flatten a)\n where\n n = fromIntegral $ natVal @n Proxy\n j = fromIntegral $ natVal @j Proxy\n\n-- | Extract specialised to a matrix.\n--\n-- >>> col 1 m\n-- [1, 5, 9]\ncol :: forall m n a. (H.Element a, H.Container H.Vector a, KnownNat m, KnownNat n, HasShape '[m, n]) => Int -> Matrix m n a -> Vector n a\ncol i (Array a) = Array $ H.takeColumns i a\n\n-- | Column extraction checked at type level.\n--\n-- >>> safeCol (Proxy :: Proxy 1) m\n-- [1, 5, 9]\n--\n-- >>> safeCol (Proxy :: Proxy 4) m\n-- ...\n-- ... index outside range\n-- ...\nsafeCol :: forall m n a j. (H.Element a, H.Container H.Vector a, 'True ~ CheckIndex j n, KnownNat j, KnownNat m, KnownNat n, HasShape '[m, n]) => Proxy j -> Matrix m n a -> Vector n a\nsafeCol _j (Array a) = Array $ H.takeColumns j a\n where\n j = fromIntegral $ natVal @j Proxy\n\n-- | Matrix multiplication.\n--\n-- This is dot sum (*) specialised to matrices\n--\n-- >>> let a = [1, 2, 3, 4] :: Array '[2, 2] Int64\n-- >>> let b = [5, 6, 7, 8] :: Array '[2, 2] Int64\n-- >>> a\n-- [[1, 2],\n-- [3, 4]]\n--\n-- >>> b\n-- [[5, 6],\n-- [7, 8]]\n--\n-- >>> mmult a b\n-- [[19, 22],\n-- [43, 50]]\nmmult ::\n forall m n k a.\n ( KnownNat k,\n KnownNat m,\n KnownNat n,\n HasShape [m, n],\n Ring a,\n H.Numeric a\n ) =>\n Array [m, k] a ->\n Array [k, n] a ->\n Array [m, n] a\nmmult (Array x) (Array y) = Array $ x H.<> y\n", "meta": {"hexsha": "8da5e0c233f1b4b6345cb490d9f7156255605516", "size": 18137, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NumHask/Array/HMatrix.hs", "max_stars_repo_name": "tonyday567/numhask-hmatrix", "max_stars_repo_head_hexsha": "8ad26dffce30e12bf95556318decd7a8bbd7fd97", "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/NumHask/Array/HMatrix.hs", "max_issues_repo_name": "tonyday567/numhask-hmatrix", "max_issues_repo_head_hexsha": "8ad26dffce30e12bf95556318decd7a8bbd7fd97", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NumHask/Array/HMatrix.hs", "max_forks_repo_name": "tonyday567/numhask-hmatrix", "max_forks_repo_head_hexsha": "8ad26dffce30e12bf95556318decd7a8bbd7fd97", "max_forks_repo_licenses": ["BSD-3-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.4025806452, "max_line_length": 481, "alphanum_fraction": 0.5559353807, "num_tokens": 6076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5483272248406006}} {"text": "{-# LANGUAGE DataKinds, TypeFamilies #-}\n{-# OPTIONS_GHC -Wno-missing-export-lists #-}\n-- | Matrix-based (meaning that dual numbers for gradient computation\n-- consider matrices, not scalars, as the primitive differentiable type)\n-- implementation of fully connected neutral network for classification\n-- of MNIST digits. Sports 2 hidden layers.\nmodule HordeAd.Tool.MnistFcnnMatrix where\n\nimport Prelude\n\nimport Control.Exception (assert)\nimport qualified Data.Array.DynamicS as OT\nimport qualified Data.Vector.Generic as V\nimport GHC.Exts (inline)\nimport Numeric.LinearAlgebra (Vector)\n\nimport HordeAd.Core.DualNumber\nimport HordeAd.Core.Engine\nimport HordeAd.Core.PairOfVectors (DualNumberVariables, var1, var2)\nimport HordeAd.Tool.MnistData\n\nfcnnMnistLen2 :: Int -> Int -> (Int, [Int], [(Int, Int)], [OT.ShapeL])\nfcnnMnistLen2 widthHidden widthHidden2 =\n ( 0\n , [widthHidden, widthHidden2, sizeMnistLabel]\n , [ (widthHidden, sizeMnistGlyph)\n , (widthHidden2, widthHidden)\n , (sizeMnistLabel, widthHidden2) ]\n , []\n )\n\n-- | Fully connected neural network for the MNIST digit classification task.\n-- There are two hidden layers and both use the same activation function.\n-- The output layer uses a different activation function.\n-- The width of the layers is determined by the dimensions of the matrices\n-- and vectors given as dual number parameters (variables).\n-- The dimensions, in turn, can be computed by the @len*@ functions\n-- on the basis of the requested widths, see above.\nfcnnMnist2 :: forall d r m. DualMonad d r m\n => (DualNumber d (Vector r) -> m (DualNumber d (Vector r)))\n -> (DualNumber d (Vector r) -> m (DualNumber d (Vector r)))\n -> Vector r\n -> DualNumberVariables d r\n -> m (DualNumber d (Vector r))\nfcnnMnist2 factivationHidden factivationOutput input variables = do\n let !_A = assert (sizeMnistGlyph == V.length input) ()\n weightsL0 = var2 variables 0\n biasesV0 = var1 variables 0\n weightsL1 = var2 variables 1\n biasesV1 = var1 variables 1\n weightsL2 = var2 variables 2\n biasesV2 = var1 variables 2\n let hiddenLayer1 = weightsL0 #>!! input + biasesV0\n nonlinearLayer1 <- factivationHidden hiddenLayer1\n let hiddenLayer2 = weightsL1 #>! nonlinearLayer1 + biasesV1\n nonlinearLayer2 <- factivationHidden hiddenLayer2\n let outputLayer = weightsL2 #>! nonlinearLayer2 + biasesV2\n factivationOutput outputLayer\n\n-- | The neural network applied to concrete activation functions\n-- and composed with the appropriate loss function.\nfcnnMnistLoss2\n :: DualMonad d r m\n => MnistData r -> DualNumberVariables d r -> m (DualNumber d r)\nfcnnMnistLoss2 (input, target) variables = do\n result <- inline fcnnMnist2 logisticAct softMaxActV input variables\n lossCrossEntropyV target result\n\n-- | The neural network applied to concrete activation functions\n-- and composed with the appropriate loss function, using fused\n-- softMax and cross entropy as the loss function.\nfcnnMnistLossFused2\n :: DualMonad d r m\n => MnistData r -> DualNumberVariables d r -> m (DualNumber d r)\nfcnnMnistLossFused2 (input, target) variables = do\n result <- inline fcnnMnist2 logisticAct return input variables\n lossSoftMaxCrossEntropyV target result\n\nfcnnMnistLossFusedRelu2\n :: DualMonad d r m\n => MnistData r -> DualNumberVariables d r -> m (DualNumber d r)\nfcnnMnistLossFusedRelu2 (input, target) variables = do\n result <- inline fcnnMnist2 reluAct return input variables\n lossSoftMaxCrossEntropyV target result\n\n-- | A function testing the neural network given testing set of inputs\n-- and the trained parameters.\nfcnnMnistTest2\n :: forall r. IsScalar 'DModeGradient r\n => [MnistData r] -> Domains r -> r\nfcnnMnistTest2 inputs parameters =\n let matchesLabels :: MnistData r -> Bool\n matchesLabels (glyph, label) =\n let nn = inline (fcnnMnist2 @'DModeGradient)\n logisticAct softMaxActV glyph\n value = primalValue nn parameters\n in V.maxIndex value == V.maxIndex label\n in fromIntegral (length (filter matchesLabels inputs))\n / fromIntegral (length inputs)\n", "meta": {"hexsha": "24b81815f5d390c17d44fb1d4eb19e1095ffc200", "size": 4148, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Tool/MnistFcnnMatrix.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HordeAd/Tool/MnistFcnnMatrix.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "src/HordeAd/Tool/MnistFcnnMatrix.hs", "max_forks_repo_name": "Mikolaj/horde-ad", "max_forks_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.48, "max_line_length": 76, "alphanum_fraction": 0.7297492768, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5482603581349524}} {"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Advection1D\nwhere\n\nimport qualified Basis\nimport Data.List\nimport qualified Element\nimport Flux\nimport Mesh\nimport Numeric.LinearAlgebra\n--import Numeric.LinearAlgebra.HMatrix\nimport Quadrature (integrate)\nimport qualified ShapeFcns\n\n-- Synonym for numeric/fractional constraints\ntype FrElNuFi a = (Fractional a,Element a,Numeric a,Field a)\n\n-- Element stiffness integrand\nstiffnessIntegrand :: (Element.Element e,ShapeFcns.ShapeFcn s,Basis.Basis b,FrElNuFi a) => e a -> s b -> [a] -> Matrix a\n--stiffnessIntegrand elem shpFcn xi = fromLists [[\n-- ShapeFcns.n shpFcn xi i [0] * atIndex (Element.dndx elem shpFcn xi j) 0 * Element.computeJacobianDet elem shpFcn xi\n-- | i <- idxRange] | j <- idxRange]\nstiffnessIntegrand elem shpFcn xi = fromLists [[\n (atIndex (Element.dndx elem shpFcn xi i) 0 * atIndex (Element.dndx elem shpFcn xi j) 0 + ShapeFcns.n shpFcn xi i [0] * ShapeFcns.n shpFcn xi j [0]) * Element.computeJacobianDet elem shpFcn xi\n | i <- idxRange] | j <- idxRange]\n where\n idxRange = [0..(Element.getNumNodes elem - 1)]\n\n-- Element mass integrand\nmassIntegrand :: (Element.Element e,ShapeFcns.ShapeFcn s,Basis.Basis b,FrElNuFi a) => e a -> s b -> [a] -> Matrix a\nmassIntegrand elem shpFcn xi = fromLists [[\n ShapeFcns.n shpFcn xi i [0] * ShapeFcns.n shpFcn xi j [0] * Element.computeJacobianDet elem shpFcn xi\n | i <- idxRange] | j <- idxRange]\n where\n idxRange = [0..(ShapeFcns.getShapeFcnOrder shpFcn)]\n\n-- Computes the element flux matrix assuming an upwind flux.\n-- Assumes that advSpeed is positive.\nelemFluxMatrix :: FrElNuFi a => a -> Matrix a\nelemFluxMatrix advSpeed = scale advSpeed $ fromLists [[-1.0, 0.0, 0.0],[0.0, 0.0, 1.0]]\n\n-- Element mass and stiffness matrices\n-- Must multiply by the determinant of the Jacobian here!!!\nelemMatrices :: (Element.Element e,ShapeFcns.ShapeFcn s,Basis.Basis b,FrElNuFi a) => e a -> s b -> Int -> (Matrix a,Matrix a)\nelemMatrices elem shpFcn ngpts = (stiffnessMat, massMat)\n where\n stiffnessMat = integrate 1 ngpts (stiffnessIntegrand elem shpFcn)\n massMat = integrate 1 ngpts (massIntegrand elem shpFcn)\n\n-- Function which computes the dimensions of the global matrices\nglobalMatrixDimension :: Int -> Int\nglobalMatrixDimension numNodes = 2 * numNodes - 2\n\n-- Function which takes a local element matrix along with an element and transforms it to global\nlocalMatToGlobal :: (Element.Element e,FrElNuFi a) => e a -> Matrix a -> [((Int, Int), a)]\nlocalMatToGlobal elem elemMat = concat [[((Mesh.globalNodeNum en i, Mesh.globalNodeNum en j), atIndex elemMat (i,j) ) | i <- [0..dim-1]] | j <- [0..dim-1]]\n where\n en = Element.getElementNumber elem\n dim = (fst . size) elemMat\n\n-- Function which does the same as the above, but with contributions due to fluxes.\nlocalFluxMatToGlobal :: (Element.Element e,FrElNuFi a) => e a -> Matrix a -> [((Int, Int), a)]\nlocalFluxMatToGlobal elem elemMat = concat [[((Mesh.globalNodeNum en i, Mesh.globalNodeNum en j - 1), atIndex elemMat (i,j) ) | i <- [0..dim-1]] | j <- [0..dim]]\n where\n en = Element.getElementNumber elem\n dim = (fst . size) elemMat\n\n-- Function which assembles global stiffness and mass matrices\n-- This function takes a mesh and returns a tuple which corresponds to the\n-- global stiffness and global mass matrices, respectively.\n-- THIS ONLY WORKS WITH THE DISCONTINUOUS MESH... IT DOES NOT SUM DUPLICATE ENTRIES.\nassembleGlobalMatrices :: (Element.Element e, ShapeFcns.ShapeFcn s,Basis.Basis b, FrElNuFi a) => Mesh e a -> s b -> Int -> a -> [[((Int,Int),a)]]\nassembleGlobalMatrices grid shpFcn ngpts advSpd = [globalK, globalM, globalF]\n where\n elems = Mesh.getMeshElements grid\n nnodes = length (concatMap Element.getElementNodes elems)\n elemMats = map (\\elem -> elemMatrices elem shpFcn ngpts) elems\n elemK = map fst elemMats\n elemM = map snd elemMats\n elemF = elemFluxMatrix advSpd\n globalK = concat (zipWith localMatToGlobal elems elemK)\n globalM = concat (zipWith localMatToGlobal elems elemM)\n globalF = filter (\\entry -> (snd . fst) entry >= 0 && (snd . fst) entry < nnodes) (concatMap (`localFluxMatToGlobal` elemF) elems)\n\n-- This function computes the right hand side of the semi-discrete statement.\n-- udot_j = (M_ij)^(-1) ( a K_ij - F_ij ) u_j.\n-- This is what needs to be integrated point-by-point.\nuDot :: (Floating a,Field a,Num (Vector a)) => Matrix a -> Matrix a -> Matrix a -> a -> Vector a -> Vector a\nuDot globalM globalK globalF advSpd u = inv globalM #> ((scale advSpd globalK - globalF) #> u)\n\n-- This function advances the solution one step in time.\nadvance :: (Floating a,Field a,Num (Vector a)) => Matrix a -> Matrix a -> Matrix a -> a -> Vector a -> a -> Vector a\nadvance globalM globalK globalF advSpd u dt = scale dt (uDot globalM globalK globalF advSpd u - u)\n\n-- This function applies boundary conditions to the semi-discrete system.\napplyBCs _ = []\n\n-- This function computes the solution as a function of time.\n{-\nsolveAdvection numElements icFunc tf = do {\n linBasis <- Lagrange 1;\n shpFcn <- TensorProduct linBasis;\n grid <- genDMesh 0.0 1.0 numElements StructElem;\n }\n-}\n\n", "meta": {"hexsha": "b157b9e8aaf0e95e0ce5a9a4a3c0bbeb2509298a", "size": 5252, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Advection1D.hs", "max_stars_repo_name": "jgrisham4/hfem", "max_stars_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Advection1D.hs", "max_issues_repo_name": "jgrisham4/hfem", "max_issues_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Advection1D.hs", "max_forks_repo_name": "jgrisham4/hfem", "max_forks_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.1834862385, "max_line_length": 193, "alphanum_fraction": 0.7033511043, "num_tokens": 1540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.548041809882974}} {"text": "-- Exercisee/Ch2/Pt1/Ex7.hs\nmodule Ex7 where\n\n-- Exercise 7\n-- Add data types and parsers to support the full numeric tower of Scheme\n-- numeric types. Haskell has built-in types to represent many of these; check\n-- the Prelude. For others, you can define compound types that represent eg. a\n-- `Rational` as a numerator and denominator, or a `Complex` as a real and an\n-- imaginary part (each itself a `Real`).\n\nimport Data.Char (digitToInt, isSpace)\nimport Data.Complex\nimport Data.Ratio\nimport Control.Monad\nimport Numeric\nimport System.Environment\n\nimport Text.ParserCombinators.Parsec hiding (spaces)\n\ndata LispVal = Atom String\n | List [LispVal]\n | DottedList [LispVal] LispVal -- (a b c ... . z)\n | Number LispNum\n | Character String\n | String String\n | Bool Bool\n deriving Show -- debug purposes\n\ndata LispNum = Complex (Complex Float)\n | Real Float\n | Rational (Ratio Integer)\n | Integer Integer\n deriving (Eq, Show)\n\nparseCharacter :: Parser LispVal\nparseCharacter = do\n string \"#\\\\\"\n character <- many $ satisfy $ not . isSpace\n return $ Character character\n \n\nparseString :: Parser LispVal\nparseString = do\n char '\"'\n -- order is important here; need to try parsing an escape sequence first because\n -- otherwise we fail when we reach the second character of the escape\n -- sequence\n x <- many $ choice $ escChars ++ [nonQuote]\n char '\"'\n return $ String x\n where\n nonQuote = noneOf \"\\\"\"\n -- taken from here:\n -- https://en.wikipedia.org/wiki/Escape_sequences_in_C#Table_of_escape_sequences\n -- (excluded characters by oct/hex codes)\n escChars = [ char '\\\\' >> char x | x <- \"abfnrtv\\\\'\\\"?\" ]\n\nparseBool :: Parser LispVal\nparseBool = do\n try (char '#')\n v <- oneOf \"tf\"\n return $ case v of\n 't' -> Bool True\n 'f' -> Bool False\n\nparseAtom :: Parser LispVal\nparseAtom = do\n first <- letter <|> symbol\n rest <- many (letter <|> digit <|> symbol)\n return $ Atom (first:rest)\n\nparseNumber :: Parser LispVal\nparseNumber = do\n n <- (try parseBin) <|> (try parseOct) <|> (try parseHex) <|> (try parseFlt) \n <|> (try parseRat) <|> (try parseCmp) <|> parseDec\n return $ Number n\n where\n parseBin = do\n string \"#b\"\n binStr <- many1 $ oneOf \"01\"\n -- cribbed from http://stackoverflow.com/a/26961027/1893155\n let binVal = foldl (\\acc x -> acc * 2 + digitToInt x) 0 binStr\n return $ Integer (toInteger binVal)\n parseOct = do\n string \"#o\"\n octStr <- many1 octDigit\n let octVal = fst $ (readOct octStr) !! 0 \n return $ Integer octVal\n parseDec = parseDecNoPre <|> parseDecPre\n parseDecNoPre = do\n decStr <- many1 digit\n return $ (Integer . read) decStr\n parseDecPre = do\n string \"#d\"\n decStr <- many1 digit\n return $ (Integer . read) decStr\n parseHex = do\n string \"#x\"\n hexStr <- many1 hexDigit \n let hexVal = fst $ (readHex hexStr) !! 0\n return $ Integer hexVal\n parseFlt = do\n whole <- many1 digit\n string \".\"\n mantissa <- many1 digit\n let fltVal = fst $ (readFloat (whole ++ \".\" ++ mantissa) !! 0)\n return $ Real $ fltVal\n parseRat = do\n m <- many1 digit\n many space\n string \"/\"\n many space\n n <- many1 digit\n let (m', n') = (fst $ (readDec m) !! 0, fst $ (readDec n) !! 0)\n return $ Rational $ m' % n'\n parseCmp = do\n (Real a) <- (try parseDec) <|> parseFlt\n many space\n string \"+\"\n many space\n (Real b) <- (try parseDec) <|> parseFlt\n char 'i'\n return $ Complex $ a :+ b\n\n-- TODO : I don't like all these `try`s -- better way to do this?\nparseExpr :: Parser LispVal\nparseExpr = (try parseNumber)\n <|> (try parseString)\n <|> (try parseCharacter)\n <|> (try parseBool)\n <|> (try parseAtom)\n\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+-/:<=>?@^_~\"\n\nspaces :: Parser ()\nspaces = skipMany1 space\n\nreadExpr :: String -> String\nreadExpr input = case parse parseExpr \"lisp\" input of\n Left err -> \"No match: \" ++ show err\n Right val -> \"Found value\"\n\nmain :: IO ()\nmain = do\n (expr:_) <- getArgs\n putStrLn (readExpr expr)\n\n", "meta": {"hexsha": "549736ff59f0bfffcd1d24aa346380c320b2a5ff", "size": 4304, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Exercises/Ch2/Pt1/Ex7.hs", "max_stars_repo_name": "EFulmer/haskell-scheme-wikibook", "max_stars_repo_head_hexsha": "7eb1d95f08f99bf7ddfcbf7c7a8f518828870591", "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/Exercises/Ch2/Pt1/Ex7.hs", "max_issues_repo_name": "EFulmer/haskell-scheme-wikibook", "max_issues_repo_head_hexsha": "7eb1d95f08f99bf7ddfcbf7c7a8f518828870591", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Exercises/Ch2/Pt1/Ex7.hs", "max_forks_repo_name": "EFulmer/haskell-scheme-wikibook", "max_forks_repo_head_hexsha": "7eb1d95f08f99bf7ddfcbf7c7a8f518828870591", "max_forks_repo_licenses": ["BSD-3-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.8859060403, "max_line_length": 84, "alphanum_fraction": 0.5973513011, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5477636924061886}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-|\nModule : Grenade.Layers.Gelu\nDescription : Gaussian Error Linear Unit (GELU)\nCopyright : (c) Manuel Schneckenreither, 2020\nLicense : BSD2\nStability : experimental\n\nThis module implements the Gaussian Error Linear Unit (GELU) activiation function. See\n\nHendrycks, Dan, and Kevin Gimpel. \"Gaussian error linear units (gelus).\" arXiv preprint arXiv:1606.08415 (2016).\n\nAvailable at: https://arxiv.org/pdf/1606.08415.pdf\n\nAs in the paper we simply let μ = 0 and σ = 1. Futher, we use the simplified and thus fast representation: x * sigmoid (1.702 * x)\n\n-}\nmodule Grenade.Layers.Gelu (\n Gelu (..)\n , SpecGelu (..)\n , specGelu1D\n , specGelu2D\n , specGelu3D\n , gelu\n ) where\n\nimport Control.DeepSeq (NFData (..))\nimport Data.Constraint (Dict (..))\nimport Data.Reflection (reifyNat)\nimport Data.Serialize\nimport Data.Singletons\nimport GHC.Generics (Generic)\nimport GHC.TypeLits\nimport qualified Numeric.LinearAlgebra.Static as LAS\nimport Unsafe.Coerce (unsafeCoerce)\n\nimport Grenade.Core\nimport Grenade.Dynamic\nimport Grenade.Dynamic.Internal.Build\n\n\n-- | A Gaussion Error Linear Unit.\n-- A layer which can act between any shape of the same dimension, acting as a\n-- diode on every neuron individually.\n--\n-- Hendrycks, Dan, and Kevin Gimpel. \"Gaussian error linear units (gelus).\" arXiv preprint arXiv:1606.08415 (2016).\ndata Gelu = Gelu\n deriving (Generic, NFData, Show)\n\ninstance UpdateLayer Gelu where\n type Gradient Gelu = ()\n runUpdate _ _ _ = Gelu\n\ninstance RandomLayer Gelu where\n createRandomWith _ _ = return Gelu\n\ninstance Serialize Gelu where\n put _ = return ()\n get = return Gelu\n\ngeluForwardFast :: Floating x => x -> x\ngeluForwardFast x = x / (e ** (-1.702 * x) + 1) -- = x * sigmoid (1.702 * x)\n where\n e = 2.71828\n\ngeluBackwardFast :: Floating x => x -> x\ngeluBackwardFast x = (e ** (1.702 * x) * (1 + e ** (1.702 * x) + 1.702 * x)) / (1 + e ** (1.702 * x)) ** 2\n where\n e = 2.71828\n\ninstance (KnownNat i) => Layer Gelu ('D1 i) ('D1 i) where\n type Tape Gelu ('D1 i) ('D1 i) = S ('D1 i)\n\n runForwards _ (S1D y) = (S1D y, S1D (gelu y))\n where\n gelu = LAS.dvmap geluForwardFast\n runBackwards _ (S1D y) (S1D dEdy) = ((), S1D (gelu' y * dEdy))\n where\n gelu' = LAS.dvmap geluBackwardFast\n\ninstance (KnownNat i, KnownNat j) => Layer Gelu ('D2 i j) ('D2 i j) where\n type Tape Gelu ('D2 i j) ('D2 i j) = S ('D2 i j)\n\n runForwards _ (S2D y) = (S2D y, S2D (gelu y))\n where\n gelu = LAS.dmmap geluForwardFast\n runBackwards _ (S2D y) (S2D dEdy) = ((), S2D (gelu' y * dEdy))\n where\n gelu' = LAS.dmmap geluBackwardFast\n\ninstance (KnownNat i, KnownNat j, KnownNat k) => Layer Gelu ('D3 i j k) ('D3 i j k) where\n\n type Tape Gelu ('D3 i j k) ('D3 i j k) = S ('D3 i j k)\n\n runForwards _ (S3D y) = (S3D y, S3D (gelu y))\n where\n gelu = LAS.dmmap geluForwardFast\n runBackwards _ (S3D y) (S3D dEdy) = ((), S3D (gelu' y * dEdy))\n where\n gelu' = LAS.dmmap geluBackwardFast\n\n\n-------------------- DynamicNetwork instance --------------------\n\ninstance FromDynamicLayer Gelu where\n fromDynamicLayer inp _ _ = SpecNetLayer $ SpecGelu (tripleFromSomeShape inp)\n\ninstance ToDynamicLayer SpecGelu where\n toDynamicLayer _ _ (SpecGelu (rows, cols, depth)) =\n reifyNat rows $ \\(_ :: (KnownNat rows) => Proxy rows) ->\n reifyNat cols $ \\(_ :: (KnownNat cols) => Proxy cols) ->\n reifyNat depth $ \\(_ :: (KnownNat depth) => Proxy depth) ->\n case (rows, cols, depth) of\n (_, 1, 1) -> return $ SpecLayer Gelu (sing :: Sing ('D1 rows)) (sing :: Sing ('D1 rows))\n (_, _, 1) -> return $ SpecLayer Gelu (sing :: Sing ('D2 rows cols)) (sing :: Sing ('D2 rows cols))\n _ -> case (unsafeCoerce (Dict :: Dict()) :: Dict (KnownNat (rows GHC.TypeLits.* depth))) of\n Dict -> return $ SpecLayer Gelu (sing :: Sing ('D3 rows cols depth)) (sing :: Sing ('D3 rows cols depth))\n\n\n-- | Create a specification for a elu layer.\nspecGelu1D :: Integer -> SpecNet\nspecGelu1D i = specGelu3D (i, 1, 1)\n\n-- | Create a specification for a elu layer.\nspecGelu2D :: (Integer, Integer) -> SpecNet\nspecGelu2D (i, j) = specGelu3D (i, j, 1)\n\n-- | Create a specification for a elu layer.\nspecGelu3D :: (Integer, Integer, Integer) -> SpecNet\nspecGelu3D = SpecNetLayer . SpecGelu\n\n\n-- | Add a Gelu layer to your build.\ngelu :: BuildM ()\ngelu = buildGetLastLayerOut >>= buildAddSpec . SpecNetLayer . SpecGelu\n\n\n-------------------- GNum instances --------------------\n\ninstance GNum Gelu where\n _ |* Gelu = Gelu\n _ |+ Gelu = Gelu\n", "meta": {"hexsha": "ab27a5529852822e438ca2d6e6c58ed395a280fd", "size": 5029, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Gelu.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Layers/Gelu.hs", "max_issues_repo_name": "schnecki/grenade", "max_issues_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Gelu.hs", "max_forks_repo_name": "schnecki/grenade", "max_forks_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-02T01:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:08:47.000Z", "avg_line_length": 33.5266666667, "max_line_length": 130, "alphanum_fraction": 0.6154305031, "num_tokens": 1585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.547632271468626}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# 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 , chiSquaredNDF\n -- * Constructors\n , chiSquared\n , chiSquaredE\n ) where\n\nimport Control.Applicative\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.SpecFunctions ( incompleteGamma,invIncompleteGamma,logGamma,digamma)\nimport Numeric.MathFunctions.Constants (m_neg_inf)\nimport qualified System.Random.MWC.Distributions as MWC\n\nimport qualified Statistics.Distribution as D\nimport Statistics.Internal\n\n\n\n-- | Chi-squared distribution\nnewtype ChiSquared = ChiSquared\n { chiSquaredNDF :: Int\n -- ^ Get number of degrees of freedom\n }\n deriving (Eq, Typeable, Data, Generic)\n\ninstance Show ChiSquared where\n showsPrec i (ChiSquared n) = defaultShow1 \"chiSquared\" n i\ninstance Read ChiSquared where\n readPrec = defaultReadPrecM1 \"chiSquared\" chiSquaredE\n\n-- | Construct chi-squared distribution. Number of degrees of freedom\n-- must be positive.\nchiSquared :: Int -> ChiSquared\nchiSquared n = maybe (error $ errMsg n) id $ chiSquaredE n\n\n-- | Construct chi-squared distribution. Number of degrees of freedom\n-- must be positive.\nchiSquaredE :: Int -> Maybe ChiSquared\nchiSquaredE n\n | n <= 0 = Nothing\n | otherwise = Just (ChiSquared n)\n\nerrMsg :: Int -> String\nerrMsg n = \"Statistics.Distribution.ChiSquared.chiSquared: N.D.F. must be positive. Got \" ++ show n\n\ninstance D.Distribution ChiSquared where\n cumulative = cumulative\n\ninstance D.ContDistr ChiSquared where\n density 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\n logDensity chi x\n | x <= 0 = m_neg_inf\n | otherwise = 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\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\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": "a2a12ce44b43c773f890092db7c3106eb3eb8520", "size": 3663, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/ChiSquared.hs", "max_stars_repo_name": "vmchale/statistics", "max_stars_repo_head_hexsha": "7f19ba0569ff34891c3ec18293a23ffb7eac8edf", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistics/Distribution/ChiSquared.hs", "max_issues_repo_name": "vmchale/statistics", "max_issues_repo_head_hexsha": "7f19ba0569ff34891c3ec18293a23ffb7eac8edf", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Distribution/ChiSquared.hs", "max_forks_repo_name": "vmchale/statistics", "max_forks_repo_head_hexsha": "7f19ba0569ff34891c3ec18293a23ffb7eac8edf", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0714285714, "max_line_length": 99, "alphanum_fraction": 0.6876876877, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5476091734853384}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE Trustworthy #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n#ifndef MIN_VERSION_hashable\n#define MIN_VERSION_hashable(x,y,z) 1\n#endif\n\n-----------------------------------------------------------------------------\n-- |\n-- License : BSD-style (see the file LICENSE)\n-- Maintainer : Edward Kmett \n-- Stability : provisional\n-- Portability : portable\n--\n-- Operations on affine spaces.\n-----------------------------------------------------------------------------\nmodule Linear.Affine where\n\nimport Control.Applicative\nimport Control.DeepSeq\nimport Control.Monad (liftM)\nimport Control.Lens\nimport Data.Binary as Binary\nimport Data.Bytes.Serial\nimport Data.Coerce\nimport Data.Complex (Complex)\nimport Data.Data\nimport Data.Distributive\nimport Data.Foldable as Foldable\nimport Data.Functor.Bind\nimport Data.Functor.Classes\nimport Data.Functor.Product\nimport Data.Functor.Rep as Rep\nimport Data.HashMap.Lazy (HashMap)\nimport Data.Hashable\nimport Data.Hashable.Lifted\nimport Data.IntMap (IntMap)\nimport Data.Ix\nimport Data.Kind\nimport Data.Map (Map)\n#if !(MIN_VERSION_base(4,11,0))\nimport Data.Semigroup (Semigroup)\n#endif\nimport Data.Serialize as Cereal\nimport Data.Vector (Vector)\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed.Base as U\nimport Foreign.Storable\nimport GHC.Generics (Generic, Generic1)\nimport Linear.Epsilon\nimport Linear.Metric\nimport Linear.Plucker\nimport Linear.Quaternion\nimport Linear.V\nimport Linear.V0\nimport Linear.V1\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport Linear.Vector\nimport System.Random (Random(..))\n\n-- | An affine space is roughly a vector space in which we have\n-- forgotten or at least pretend to have forgotten the origin.\n--\n-- > a .+^ (b .-. a) = b@\n-- > (a .+^ u) .+^ v = a .+^ (u ^+^ v)@\n-- > (a .-. b) ^+^ v = (a .+^ v) .-. q@\nclass Additive (Diff p) => Affine p where\n type Diff p :: Type -> Type\n\n infixl 6 .-.\n -- | Get the difference between two points as a vector offset.\n (.-.) :: Num a => p a -> p a -> Diff p a\n\n infixl 6 .+^\n -- | Add a vector offset to a point.\n (.+^) :: Num a => p a -> Diff p a -> p a\n\n infixl 6 .-^\n -- | Subtract a vector offset from a point.\n (.-^) :: Num a => p a -> Diff p a -> p a\n p .-^ v = p .+^ negated v\n {-# INLINE (.-^) #-}\n\ninstance (Affine f, Affine g) => Affine (Product f g) where\n type Diff (Product f g) = Product (Diff f) (Diff g)\n Pair a b .-. Pair c d = Pair (a .-. c) (b .-. d)\n Pair a b .+^ Pair c d = Pair (a .+^ c) (b .+^ d)\n Pair a b .-^ Pair c d = Pair (a .+^ c) (b .+^ d)\n\n-- | Compute the quadrance of the difference (the square of the distance)\nqdA :: (Affine p, Foldable (Diff p), Num a) => p a -> p a -> a\nqdA a b = Foldable.sum (fmap (join (*)) (a .-. b))\n{-# INLINE qdA #-}\n\n-- | Distance between two points in an affine space\ndistanceA :: (Floating a, Foldable (Diff p), Affine p) => p a -> p a -> a\ndistanceA a b = sqrt (qdA a b)\n{-# INLINE distanceA #-}\n\n#define ADDITIVEC(CTX,T) instance CTX => Affine T where type Diff T = T ; \\\n (.-.) = (^-^) ; {-# INLINE (.-.) #-} ; (.+^) = (^+^) ; {-# INLINE (.+^) #-} ; \\\n (.-^) = (^-^) ; {-# INLINE (.-^) #-}\n#define ADDITIVE(T) ADDITIVEC((), T)\n\nADDITIVE([])\nADDITIVE(Complex)\nADDITIVE(ZipList)\nADDITIVE(Maybe)\nADDITIVE(IntMap)\nADDITIVE(Identity)\nADDITIVE(Vector)\nADDITIVE(V0)\nADDITIVE(V1)\nADDITIVE(V2)\nADDITIVE(V3)\nADDITIVE(V4)\nADDITIVE(Plucker)\nADDITIVE(Quaternion)\nADDITIVE(((->) b))\nADDITIVEC(Ord k, (Map k))\nADDITIVEC((Eq k, Hashable k), (HashMap k))\nADDITIVEC(Dim n, (V n))\n\n-- | A handy wrapper to help distinguish points from vectors at the\n-- type level\nnewtype Point f a = P (f a)\n deriving ( Eq, Ord, Show, Read, Monad, Functor, Applicative, Foldable\n , Eq1, Ord1, Show1, Read1\n , Traversable, Apply, Additive, Metric\n , Fractional , Num, Ix, Storable, Epsilon\n , Semigroup, Monoid\n , Random, Hashable\n , Generic, Generic1, Data\n )\n\ninstance Finite f => Finite (Point f) where\n type Size (Point f) = Size f\n toV (P v) = toV v\n fromV v = P (fromV v)\n\ninstance NFData (f a) => NFData (Point f a) where\n rnf (P x) = rnf x\n\ninstance Serial1 f => Serial1 (Point f) where\n serializeWith f (P p) = serializeWith f p\n deserializeWith m = P `liftM` deserializeWith m\n\ninstance Serial (f a) => Serial (Point f a) where\n serialize (P p) = serialize p\n deserialize = P `liftM` deserialize\n\ninstance Binary (f a) => Binary (Point f a) where\n put (P p) = Binary.put p\n get = P `liftM` Binary.get\n\ninstance Serialize (f a) => Serialize (Point f a) where\n put (P p) = Cereal.put p\n get = P `liftM` Cereal.get\n\ninstance Hashable1 f => Hashable1 (Point f) where\n liftHashWithSalt h s (P f) = liftHashWithSalt h s f\n {-# INLINE liftHashWithSalt #-}\n\nlensP :: Lens' (Point g a) (g a)\nlensP afb (P a) = P <$> afb a\n{-# INLINE lensP #-}\n\n_Point :: Iso' (Point f a) (f a)\n_Point = iso (\\(P a) -> a) P\n{-# INLINE _Point #-}\n\ninstance (t ~ Point g b) => Rewrapped (Point f a) t\ninstance Wrapped (Point f a) where\n type Unwrapped (Point f a) = f a\n _Wrapped' = _Point\n {-# INLINE _Wrapped' #-}\n\n-- These are stolen from Data.Profunctor.Unsafe\n(.#) :: Coercible b a => (b -> c) -> (a -> b) -> a -> c\nf .# _ = coerce f\n{-# INLINE (.#) #-}\n\n(#.) :: Coercible c b => (b -> c) -> (a -> b) -> a -> c\n(#.) _ = coerce (\\x -> x :: b) :: forall a b. Coercible b a => a -> b\n{-# INLINE (#.) #-}\n\nunP :: Point f a -> f a\nunP (P x) = x\n{-# INLINE unP #-}\n\n-- We can't use GND to derive 'Bind' because 'join' causes\n-- role troubles. However, GHC 7.8 and above let us use\n-- explicit coercions for (>>-).\ninstance Bind f => Bind (Point f) where\n (>>-) = ((P .) . (. (unP .))) #. (>>-) .# unP\n join (P m) = P $ m >>- \\(P m') -> m'\n\ninstance Distributive f => Distributive (Point f) where\n distribute = P . collect (\\(P p) -> p)\n collect = (P .) #. collect .# (unP .)\n\ninstance Representable f => Representable (Point f) where\n type Rep (Point f) = Rep f\n tabulate = P #. tabulate\n {-# INLINE tabulate #-}\n index = Rep.index .# unP\n {-# INLINE index #-}\n\ntype instance Index (Point f a) = Index (f a)\ntype instance IxValue (Point f a) = IxValue (f a)\n\ninstance Ixed (f a) => Ixed (Point f a) where\n ix l = lensP . ix l\n {-# INLINE ix #-}\n\ninstance Traversable f => Each (Point f a) (Point f b) a b where\n each = traverse\n {-# INLINE each #-}\n\ninstance R1 f => R1 (Point f) where\n _x = lensP . _x\n {-# INLINE _x #-}\n\ninstance R2 f => R2 (Point f) where\n _y = lensP . _y\n {-# INLINE _y #-}\n _xy = lensP . _xy\n {-# INLINE _xy #-}\n\ninstance R3 f => R3 (Point f) where\n _z = lensP . _z\n {-# INLINE _z #-}\n _xyz = lensP . _xyz\n {-# INLINE _xyz #-}\n\ninstance R4 f => R4 (Point f) where\n _w = lensP . _w\n {-# INLINE _w #-}\n _xyzw = lensP . _xyzw\n {-# INLINE _xyzw #-}\n\ninstance Additive f => Affine (Point f) where\n type Diff (Point f) = f\n (.-.) = (. unP) #. (^-^) .# unP\n {-# INLINE (.-.) #-}\n (.+^) = (P .) #. (^+^) .# unP\n {-# INLINE (.+^) #-}\n (.-^) = (P .) #. (^-^) .# unP\n {-# INLINE (.-^) #-}\n\n-- | Vector spaces have origins.\norigin :: (Additive f, Num a) => Point f a\norigin = P zero\n\n-- | An isomorphism between points and vectors, given a reference\n-- point.\nrelative :: (Additive f, Num a) => Point f a -> Iso' (Point f a) (f a)\nrelative p0 = iso (.-. p0) (p0 .+^)\n{-# INLINE relative #-}\n\nnewtype instance U.Vector (Point f a) = V_P (U.Vector (f a))\nnewtype instance U.MVector s (Point f a) = MV_P (U.MVector s (f a))\ninstance U.Unbox (f a) => U.Unbox (Point f a)\n\ninstance U.Unbox (f a) => M.MVector U.MVector (Point f a) where\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicOverlaps #-}\n {-# INLINE basicUnsafeNew #-}\n {-# INLINE basicUnsafeRead #-}\n {-# INLINE basicUnsafeWrite #-}\n basicLength (MV_P v) = M.basicLength v\n basicUnsafeSlice m n (MV_P v) = MV_P (M.basicUnsafeSlice m n v)\n basicOverlaps (MV_P v) (MV_P u) = M.basicOverlaps v u\n basicUnsafeNew n = MV_P `liftM` M.basicUnsafeNew n\n basicUnsafeRead (MV_P v) i = P `liftM` M.basicUnsafeRead v i\n basicUnsafeWrite (MV_P v) i (P x) = M.basicUnsafeWrite v i x\n basicInitialize (MV_P v) = M.basicInitialize v\n {-# INLINE basicInitialize #-}\n\ninstance U.Unbox (f a) => G.Vector U.Vector (Point f a) where\n {-# INLINE basicUnsafeFreeze #-}\n {-# INLINE basicUnsafeThaw #-}\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicUnsafeIndexM #-}\n basicUnsafeFreeze (MV_P v) = V_P `liftM` G.basicUnsafeFreeze v\n basicUnsafeThaw ( V_P v) = MV_P `liftM` G.basicUnsafeThaw v\n basicLength ( V_P v) = G.basicLength v\n basicUnsafeSlice m n (V_P v) = V_P (G.basicUnsafeSlice m n v)\n basicUnsafeIndexM (V_P v) i = P `liftM` G.basicUnsafeIndexM v i\n", "meta": {"hexsha": "0e145246854c1eec0b43830097192ae8f7ce40d3", "size": 9208, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Linear/Affine.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/Affine.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/Affine.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.993485342, "max_line_length": 81, "alphanum_fraction": 0.6155516942, "num_tokens": 2931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6442250928250374, "lm_q1q2_score": 0.5475727546399846}} {"text": "{-# LANGUAGE Arrows, ExistentialQuantification, ScopedTypeVariables #-}\n\nmodule SignalLevel.SpecAnalysis20 where\n\nimport Data.Complex\nimport Data.Maybe (catMaybes,listToMaybe)\nimport qualified Data.Map as M\nimport Control.Arrow.ArrowP\nimport Control.DeepSeq (NFData)\nimport Control.SF.SF (SF(..))\nimport FRP.UISF (SEvent,asyncVT,Time,DeltaT)\nimport FRP.UISF.Asynchrony (Automaton(..))\nimport FRP.UISF.Graphics.Color (rgbE)\n\nimport Euterpea hiding (SF)\nimport HSoM\nimport HSoM.MUI (asyncV)\nimport HSoM.Examples.FFT (fftA,quantize,presentFFT)\n\nimport SignalLevel.SigFun19\n\ndft :: RealFloat a => [Complex a] -> [Complex a]\ndft xs =\n let lenI = length xs\n lenR = fromIntegral lenI\n lenC = lenR :+ 0\n in [let i = -2*pi * fromIntegral k / lenR\n in (1/lenC) * sum [(xs !! n) * exp (0 :+ i * fromIntegral n)\n | n <- [0,1..lenI-1]]\n | k <- [0,1..lenI-1]]\n\n\n-- num = # samples\n-- n = term\n\nmkTerm :: Int -> Double -> [Complex Double]\nmkTerm num n = let f = 2*pi / fromIntegral num\n in [sin (n*f*fromIntegral i) / n :+ 0\n | i <- [0,1..num-1]]\n\nmkxa,mkxb,mkxc :: Int -> [Complex Double]\nmkxa num = mkTerm num 1\nmkxb num = zipWith (+) (mkxa num) (mkTerm num 3)\nmkxc num = zipWith (+) (mkxb num) (mkTerm num 5)\n\nmkPulse :: Int -> [Complex Double]\nmkPulse n = 100 : take (n-1) (repeat 0)\n\nx1 num = let f = 2*pi*pi / fromIntegral num\n in map (:+ 0) [sin (f * fromIntegral i)\n | i <- [0,1..num-1]]\n\nmkPolars :: [Complex Double] -> [Complex Double]\nmkPolars = map ((\\(m,p) -> m :+ p) . polar)\n\n---------------\n-- Exercises --\n---------------\n\n{- Exercise 20.1©:Write a Haskell function idft that implements the inverse DFT\n - as captured in Equation 20.3. Test your code by applying idft to one of the\n - signals used earlier in this section. In other words, show empirically that,\n - up to round-off errors, idft (dft xs) == xs. -}\n\nidft :: RealFloat a => [Complex a] -> [Complex a]\nidft xs = let lenI = length xs \n lenR = fromIntegral lenI\n in [let i = 2*pi* fromIntegral n / lenR\n in sum [(xs !! k) * exp (0 :+ i * fromIntegral k) \n | k <- [0..lenI-1]]\n | n <- [0..lenI-1]]\n\n\n{- Exercise 20.2: Use dft to analyze some of the signals generated using signal\n - functions defined in Chapter 19. -}\n\nfft1 :: forall p . Clock p => SigFun p () (SEvent (M.Map Double Double))\nfft1 = s1 >>> (fftA 128 256) >>> arr (fmap $ presentFFT $ rate (undefined :: p))\n\n\n{- Exercise 20.3:© Define a function mkSqWave :: Int -> Int -> [Complex Double] \n - such that mkSqWave num n is the sum of the first n terms of the Fourier\n - Series of a square wave, having num samples in the result. -}\n\nmkSqWave :: Int -> Int -> [Complex Double]\nmkSqWave num n = \n foldr (zipWith (+) . (\\i -> mkTerm i)) \n (replicate num 0) \n (filter odd [1..(2*n-1)])\n where mkTerm x = let f = 2 * pi / fromIntegral num\n t = fromIntegral x\n in [sin (t*f*fromIntegral i)/t:+0\n | i <- [0,1..num-1]]\n\n\n\n{- Exercise 20.4: -} \n\n{- a. © Prove mathematically that x and x^ are inverses. \n\n Let X^ and X be the NxN matrices defined by\n\n X^(k,n) = (1/N) * w^(kn)\n X(n,k) = (1/N) * w^(-(kn))\n\n where w = e^(-j2π/N)\n and (a,b) corresponds to the entry in the ath row and bth column of the matrix\n\n Prove X^ and X are inverses\n Proof:\n \n It suffices to prove (X^)X = I\n\n Thus I show \n if p=q then X^X(p,q) = 1\n otherwise X^X(p,q) = 0\n\n X^X(p,q) = X^(p,*)·X(*,q) = (1/N) ∑w^(pn)*w^(-(n*q))\n\n where X^(p,*) is the pth row of X^ , X(*,q) is the qth column of X and\n ∑ is a sum from 0 to N-1\n\n if p = q then\n X^X(p,q) = (1/N) ∑ w^(pn)/w^(nq) = (1/N) ∑ 1 = (1/N)*N = 1\n\n if p ≠ q then\n X^X(p,q) = (1/N) ∑ w^(n(p-q)) \n = (1 - (e^(-j*2π(p-q)/N))^N)/(1 - e^(-j*2π(p-q)/N))\n = (1 - (e^(-j*2π(p-q)))/(1 - e^(-j*2π(p-q)/N))\n = (1 - 1/(cos(2π(p-q)) + jsin(2π(p-q))))/(1 - e^(-j*2π(p-q)/N))\n = (1 - 1)/(1 - e^(-j*2π(p-q)/N))\n = 0\n\n Thus X^X = I, proving X^ and X are inverses.\n-}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{- \ne1 = \n \\i -> (1/lenC)*sum[(cxs !! n)*exp(0 :+ i*fromIntegral n) | n <- [0,1..lenI-1]]\n\nf = \\exp -> let lenI = length cxs\n in let lenR = fromIntegral lenI\n in let lenC = lenR :+ 0\n in exp\n\n-> fdft = (f (concatMap \n (\\k -> let i = -2*pi*fromIntegral k/lenR in e1 i) \n [0,1..lenI-1]\n )\n )\n\nfix exp = \\x -> let x = exp x in x\n-}\n\n\n\n{- b. Also prove, using equational reasoning, that dft and idft are \n - inverses. (..., you may assume that Haskell numeric types \n - obey the standard axioms of real arithmetic.)\n\nidft(dft(cxs)) = cxs\n\nidft(dft(cxs)) \n-> idft (let lenI = length cxs\n lenR = fromIntegral lenI\n lenC = lenR :+ 0\n in [let i = -2*pi*fromIntegral k/lenR\n in (1/lenC)*sum[(cxs !! n)*exp (0 :+ i*fromIntegral n)\n | n <- [0,1..lenI-1]]\n |k <- [0,1..lenI-1]] )\n\n-> idft (let lenI = length cxs\n lenR = fromIntegral lenI\n lenC = lenR :+ 0\n in [let i = -2*pi*fromIntegral k/lenR\n in e1 i | k <- [0,1..lenI-1]] )\n\n -> concatMap \n (\\k -> let i = -2*pi*fromIntegral k/lenR in e1 i) \n [0,1..lenI-1]\n\n-> idft (f (concatMap \n (\\k -> let i = -2*pi*fromIntegral k/lenR in e1 i) \n [0,1..lenI-1]\n )\n )\n\n-> let lenI2 = length fdft\n lenR2 = fromIntegral lenI2\n in [let i2 = 2*pi* fromIntegral n2 / lenR2\n in sum [(fdft !! k) * exp (0 :+ i2 * fromIntegral k) | k <- [0..lenI2-1]]\n | n2 <- [0..lenI2-1]]\n\n-> let lenI2 = length fdft\n lenR2 = fromIntegral lenI2\n in [let i2 = 2*pi* fromIntegral n2 / lenR2\n in sum [(fdft !! k) * exp (0 :+ i2 * fromIntegral k) | k <- [0..lenI2-1]]\n | n2 <- [0..lenI2-1]]\n-}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfftEx :: UISF () ()\nfftEx = \n proc _ -> do\n f <- withDisplay $ hSlider (1,2000) 440 -< ()\n d <- clockedSFToUISF (0.1) fftDataSig -< f\n let (ds,ts) = unzip d\n _ <- histogram (makeLayout (Fixed {fixedSize = 500})\n (Fixed {fixedSize = 150})) \n -< listToMaybe (catMaybes (snd $ unzip ds))\n _ <- realtimeGraph (makeLayout (Fixed {fixedSize = 500}) \n (Fixed {fixedSize = 150})) \n 1 Black -< (zip (fst $ unzip ds) ts)\n m <- withDisplay $ hSlider (1,2000) 20 -< ()\n d1 <- clockedSFToUISF (0.1) fftDataSig -< m\n let (ds1,ts1) = unzip d1\n _ <- histogram (makeLayout (Fixed {fixedSize = 500})\n (Fixed {fixedSize = 150})) \n -< listToMaybe (catMaybes (snd $ unzip ds1))\n _ <- realtimeGraph (makeLayout (Fixed {fixedSize = 500}) \n (Fixed {fixedSize = 150})) \n 1 Black -< (zip (fst $ unzip ds1) ts1)\n d3 <- clockedSFToUISF (0.1) fftDataSig -< (f+m)\n let (ds3,ts3) = unzip d3\n _ <- histogram (makeLayout (Fixed {fixedSize = 500})\n (Fixed {fixedSize = 150})) \n -< listToMaybe (catMaybes (snd $ unzip ds3))\n outA -< ()\n where\n fftDataSig :: SigFun CtrRate Double (Double, SEvent [Double])\n fftDataSig = proc f -> do\n s <- osc (tableSinesN 4096 [1]) 0 -< f\n fftData <- fftA 128 256 -< s\n outA -< (s,fftData)\n\nt0 = runMUI (defaultMUIParams\n {uiSize = (500,900),\n uiBackground = rgbE 93 10 13,\n uiTitle = \"FFT Test\"}) \n fftEx\n\nclockedSFToUISF :: forall a b c . (NFData b,Clock c) => \n DeltaT -> SigFun c a b -> UISF a [(b,Time)]\nclockedSFToUISF buffer ~(ArrowP sf) = let r = rate (undefined :: c)\n in asyncV r buffer (toAutomaton sf)\n\ntoAutomaton :: forall a b . SF a b -> Automaton (->) a b\ntoAutomaton ~(SF f) = Automaton $ \\a -> let (b,sf) = f a in (b,toAutomaton sf)\n\n\n{- Exercise 20.5: Modify the program in 20.5 (fftEx) in the following ways:\n -\n - 1. Add a second slider, and use it to control the frequency of a second\n - oscillator.©\n - 2. Let s1 and s2 be the names of the signals whose frequencies are controlled\n - by the first and second sliders, respectively. Instead of displaying the FFT\n - of just s1, try a variety of combinations of s1 and s2, such as \n - s1 + s2\n - s1 - s2\n - s1 * s2\n - 1/s1 + 1/s2\n - s1/s2\n - Comment on the results.\n - 3. Use s2 to control the frequency of s1 (as was done with vibrato in Ch.19).\n - Plot the fft of s1 and comment on the result.\n - 4. Instead of using osc to generate a pure sine wave, try using other\n - oscillators and/or table generators to create more complex tones, and plot\n - their FFTs. Comment on the results. -}\n\n\n\n\n\n\n\n\n\n----------\n-- Util --\n----------\nprintComplexL :: [Complex Double] -> IO ()\nprintComplexL xs = \n let f (i, rl :+ im) =\n do putStr (spaces (3 - length (show i)))\n putStr (show i ++ \": (\" )\n putStr (niceNum rl ++ \", \" )\n putStr (niceNum im ++ \") \\n\" )\n in mapM_ f (zip [0..length xs - 1] xs)\n\nniceNum :: Double -> String\nniceNum d =\n let d' = fromIntegral (round (1e10*d))/1e10\n (dec,fra) = break (== '.') (show d')\n (fra',exp) = break (== 'e') fra\n in spaces (3 - length dec) ++ dec ++ take 11 fra'\n ++ exp ++ spaces (12 - length fra' - length exp)\n\nspaces :: Int -> String\nspaces n = take n (repeat ' ')\n\n", "meta": {"hexsha": "5cd69147f2cce0826b57087f103bf54d1451c1a0", "size": 9651, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SignalLevel/specanalysis20.hs", "max_stars_repo_name": "REBradley/music-lab", "max_stars_repo_head_hexsha": "cbfb47c4295ca956807cbfb6c38cf78d15cd9950", "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/SignalLevel/specanalysis20.hs", "max_issues_repo_name": "REBradley/music-lab", "max_issues_repo_head_hexsha": "cbfb47c4295ca956807cbfb6c38cf78d15cd9950", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SignalLevel/specanalysis20.hs", "max_forks_repo_name": "REBradley/music-lab", "max_forks_repo_head_hexsha": "cbfb47c4295ca956807cbfb6c38cf78d15cd9950", "max_forks_repo_licenses": ["BSD-3-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.4176136364, "max_line_length": 80, "alphanum_fraction": 0.5298932753, "num_tokens": 3202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5475544826359088}} {"text": "{- |\nModule : Numeric.GSL.Fitting\nCopyright : (c) Alberto Ruiz 2010\nLicense : GPL\n\nMaintainer : Alberto Ruiz (aruiz at um dot es)\nStability : provisional\nPortability : uses ffi\n\nNonlinear Least-Squares Fitting\n\n\n\nThe example program in the GSL manual (see examples/fitting.hs):\n\n@dat = [\n ([0.0],([6.0133918608118675],0.1)),\n ([1.0],([5.5153769909966535],0.1)),\n ([2.0],([5.261094606015287],0.1)),\n ...\n ([39.0],([1.0619821710802808],0.1))]\n\nexpModel [a,lambda,b] [t] = [a * exp (-lambda * t) + b]\n\nexpModelDer [a,lambda,b] [t] = [[exp (-lambda * t), -t * a * exp(-lambda*t) , 1]]\n\n(sol,path) = fitModelScaled 1E-4 1E-4 20 (expModel, expModelDer) dat [1,0,0]\n\n\\> path\n(6><5)\n [ 1.0, 76.45780563978782, 1.6465931240727802, 1.8147715267618197e-2, 0.6465931240727797\n , 2.0, 37.683816318260355, 2.858760367632973, 8.092094813253975e-2, 1.4479636296208662\n , 3.0, 9.5807893736187, 4.948995119561291, 0.11942927999921617, 1.0945766509238248\n , 4.0, 5.630494933603935, 5.021755718065913, 0.10287787128056883, 1.0338835440862608\n , 5.0, 5.443976278682909, 5.045204331329302, 0.10405523433131504, 1.019416067207375\n , 6.0, 5.4439736648994685, 5.045357818922331, 0.10404905846029407, 1.0192487112786812 ]\n\\> sol\n[(5.045357818922331,6.027976702418132e-2),\n(0.10404905846029407,3.157045047172834e-3),\n(1.0192487112786812,3.782067731353722e-2)]@\n\n-}\n-----------------------------------------------------------------------------\n\nmodule Numeric.GSL.Fitting (\n -- * Levenberg-Marquardt\n nlFitting, FittingMethod(..),\n -- * Utilities\n fitModelScaled, fitModel\n) where\n\nimport Data.Packed.Internal\nimport Numeric.LinearAlgebra\nimport Numeric.GSL.Internal\n\nimport Foreign.Ptr(FunPtr, freeHaskellFunPtr)\nimport Foreign.C.Types\nimport System.IO.Unsafe(unsafePerformIO)\n\n-------------------------------------------------------------------------\n\ndata FittingMethod = LevenbergMarquardtScaled -- ^ Interface to gsl_multifit_fdfsolver_lmsder. This is a robust and efficient version of the Levenberg-Marquardt algorithm as implemented in the scaled lmder routine in minpack. Minpack was written by Jorge J. More, Burton S. Garbow and Kenneth E. Hillstrom.\n | LevenbergMarquardt -- ^ This is an unscaled version of the lmder algorithm. The elements of the diagonal scaling matrix D are set to 1. This algorithm may be useful in circumstances where the scaled version of lmder converges too slowly, or the function is already scaled appropriately.\n deriving (Enum,Eq,Show,Bounded)\n\n\n-- | Nonlinear multidimensional least-squares fitting.\nnlFitting :: FittingMethod\n -> Double -- ^ absolute tolerance\n -> Double -- ^ relative tolerance\n -> Int -- ^ maximum number of iterations allowed\n -> (Vector Double -> Vector Double) -- ^ function to be minimized\n -> (Vector Double -> Matrix Double) -- ^ Jacobian\n -> Vector Double -- ^ starting point\n -> (Vector Double, Matrix Double) -- ^ solution vector and optimization path\n\nnlFitting method epsabs epsrel maxit fun jac xinit = nlFitGen (fi (fromEnum method)) fun jac xinit epsabs epsrel maxit\n\nnlFitGen m f jac xiv epsabs epsrel maxit = unsafePerformIO $ do\n let p = dim xiv\n n = dim (f xiv)\n fp <- mkVecVecfun (aux_vTov (checkdim1 n p . f))\n jp <- mkVecMatfun (aux_vTom (checkdim2 n p . jac))\n rawpath <- createMatrix RowMajor maxit (2+p)\n app2 (c_nlfit m fp jp epsabs epsrel (fi maxit) (fi n)) vec xiv mat rawpath \"c_nlfit\"\n let it = round (rawpath @@> (maxit-1,0))\n path = takeRows it rawpath\n [sol] = toRows $ dropRows (it-1) path\n freeHaskellFunPtr fp\n freeHaskellFunPtr jp\n return (subVector 2 p sol, path)\n\nforeign import ccall safe \"nlfit\"\n c_nlfit:: CInt -> FunPtr TVV -> FunPtr TVM -> Double -> Double -> CInt -> CInt -> TVM\n\n-------------------------------------------------------\n\ncheckdim1 n _p v\n | dim v == n = v\n | otherwise = error $ \"Error: \"++ show n\n ++ \" components expected in the result of the function supplied to nlFitting\"\n\ncheckdim2 n p m\n | rows m == n && cols m == p = m\n | otherwise = error $ \"Error: \"++ show n ++ \"x\" ++ show p\n ++ \" Jacobian expected in nlFitting\"\n\n------------------------------------------------------------\n\nerr (model,deriv) dat vsol = zip sol errs where\n sol = toList vsol\n c = max 1 (chi/sqrt (fromIntegral dof))\n dof = length dat - (rows cov)\n chi = norm2 (fromList $ cost (resMs model) dat sol)\n js = fromLists $ jacobian (resDs deriv) dat sol\n cov = inv $ trans js <> js\n errs = toList $ scalar c * sqrt (takeDiag cov)\n\n\n\n-- | Higher level interface to 'nlFitting' 'LevenbergMarquardtScaled'. The optimization function and\n-- Jacobian are automatically built from a model f vs x = y and its derivatives, and a list of\n-- instances (x, (y,sigma)) to be fitted.\n\nfitModelScaled\n :: Double -- ^ absolute tolerance\n -> Double -- ^ relative tolerance\n -> Int -- ^ maximum number of iterations allowed\n -> ([Double] -> x -> [Double], [Double] -> x -> [[Double]]) -- ^ (model, derivatives)\n -> [(x, ([Double], Double))] -- ^ instances\n -> [Double] -- ^ starting point\n -> ([(Double, Double)], Matrix Double) -- ^ (solution, error) and optimization path\nfitModelScaled epsabs epsrel maxit (model,deriv) dt xin = (err (model,deriv) dt sol, path) where\n (sol,path) = nlFitting LevenbergMarquardtScaled epsabs epsrel maxit\n (fromList . cost (resMs model) dt . toList)\n (fromLists . jacobian (resDs deriv) dt . toList)\n (fromList xin)\n\n\n\n-- | Higher level interface to 'nlFitting' 'LevenbergMarquardt'. The optimization function and\n-- Jacobian are automatically built from a model f vs x = y and its derivatives, and a list of\n-- instances (x,y) to be fitted.\n\nfitModel :: Double -- ^ absolute tolerance\n -> Double -- ^ relative tolerance\n -> Int -- ^ maximum number of iterations allowed\n -> ([Double] -> x -> [Double], [Double] -> x -> [[Double]]) -- ^ (model, derivatives)\n -> [(x, [Double])] -- ^ instances\n -> [Double] -- ^ starting point\n -> ([Double], Matrix Double) -- ^ solution and optimization path\nfitModel epsabs epsrel maxit (model,deriv) dt xin = (toList sol, path) where\n (sol,path) = nlFitting LevenbergMarquardt epsabs epsrel maxit\n (fromList . cost (resM model) dt . toList)\n (fromLists . jacobian (resD deriv) dt . toList)\n (fromList xin)\n\ncost model ds vs = concatMap (model vs) ds\n\njacobian modelDer ds vs = concatMap (modelDer vs) ds\n\n-- | Model-to-residual for association pairs with sigma, to be used with 'fitModel'.\nresMs :: ([Double] -> x -> [Double]) -> [Double] -> (x, ([Double], Double)) -> [Double]\nresMs m v = \\(x,(ys,s)) -> zipWith (g s) (m v x) ys where g s a b = (a-b)/s\n\n-- | Associated derivative for 'resMs'.\nresDs :: ([Double] -> x -> [[Double]]) -> [Double] -> (x, ([Double], Double)) -> [[Double]]\nresDs m v = \\(x,(_,s)) -> map (map (/s)) (m v x)\n\n-- | Model-to-residual for association pairs, to be used with 'fitModel'. It is equivalent\n-- to 'resMs' with all sigmas = 1.\nresM :: ([Double] -> x -> [Double]) -> [Double] -> (x, [Double]) -> [Double]\nresM m v = \\(x,ys) -> zipWith g (m v x) ys where g a b = a-b\n\n-- | Associated derivative for 'resM'.\nresD :: ([Double] -> x -> [[Double]]) -> [Double] -> (x, [Double]) -> [[Double]]\nresD m v = \\(x,_) -> m v x\n", "meta": {"hexsha": "6343b76daccbb49f6c86b26b12e9854bc2a9eb56", "size": 7703, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/Fitting.hs", "max_stars_repo_name": "curiousleo/liquidhaskell", "max_stars_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 941, "max_stars_repo_stars_event_min_datetime": "2015-01-13T10:51:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:32:32.000Z", "max_issues_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/Fitting.hs", "max_issues_repo_name": "curiousleo/liquidhaskell", "max_issues_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 1300, "max_issues_repo_issues_event_min_datetime": "2015-01-01T05:41:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:11:03.000Z", "max_forks_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/Fitting.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": 43.2752808989, "max_line_length": 307, "alphanum_fraction": 0.6179410619, "num_tokens": 2314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5475544757994906}} {"text": "{-# LANGUAGE ViewPatterns #-}\n\nmodule Statistics.Covariance.Shrinkage.MMSE (\n mmseCov\n , shrinkCov\n , sampleCov\n , naiveCov\n , pinCoef\n , lwShrinkageCoef\n , rblwShrinkCovCoef\n , rblwShrinkageCoef\n , oracleShrinkCovCoef\n , oracleShrinkageCoef\n ) where\n\nimport Numeric.LinearAlgebra hiding ((<>))\nimport Numeric.Sum (kbn, sumVector)\nimport Statistics.Sample (mean)\nimport qualified Data.Vector.Unboxed as VU\n\nmmseCov :: (Matrix Double -> Double) -> Matrix Double -> Herm Double\nmmseCov shrink x = shrinkCov s p f\n where\n s = sampleCov x\n f = naiveCov x\n p = shrink x\n\nshrinkCov :: Herm Double -> Double -> Herm Double -> Herm Double\nshrinkCov sample coef target = scale (1 - coef) sample `add` scale coef target\n\nsampleCov :: Matrix Double -> Herm Double\nsampleCov = snd . meanCov\n\navgVarCov :: Herm Double -> Herm Double\navgVarCov (unSym -> s) = trustSym $ scale s' (ident p)\n where\n p = cols s\n s' = mean $ takeDiag s\n\nnaiveCov :: Matrix Double -> Herm Double\nnaiveCov = avgVarCov . sampleCov\n\npinCoef :: Double -> Double\npinCoef = max 0 . min 1\n\nlwShrinkageCoef :: Matrix Double -> Double\nlwShrinkageCoef x = numer / denom\n where\n n = rows x\n p = cols x\n s = unSym $ sampleCov x\n trs2 = trace $ s <> s\n tr2s = sq $ trace s\n frob ix = let c = x ? [ix] in sq . norm_Frob $ unSym (mTm c) - s\n numer = sumVector kbn (VU.generate n frob) / fromIntegral (sq n)\n denom = trs2 - tr2s / fromIntegral p\n\nrblwShrinkCovCoef :: Int -> Herm Double -> Double\nrblwShrinkCovCoef (fromIntegral -> n) (unSym -> s) = numer / denom\n where\n p = cols s\n trs2 = trace $ s <> s\n tr2s = sq $ trace s\n numer = (n - 2) / n * trs2 + tr2s\n denom = (n + 2) * (trs2 - tr2s / fromIntegral p)\n\nrblwShrinkageCoef :: Matrix Double -> Double\nrblwShrinkageCoef x = rblwShrinkCovCoef n (sampleCov x)\n where n = rows x\n\ndata OASIter = OASIter Double (Herm Double)\n\ndata OAS = OAS Int Int (Herm Double) (Herm Double)\n\noracleStep :: OAS -> Herm Double -> OASIter\noracleStep (OAS n p s f) sj = OASIter pj' sj'\n where\n n' = fromIntegral n\n p' = fromIntegral p\n trss = trace $ unSym sj <> unSym s\n tr2s = sq . trace $ unSym sj\n numer = (1 - 2 / p') * trss + tr2s\n denom = (n' + 1 - 2 / p') * trss + (1 - n' / p') * tr2s\n pj' = numer / denom\n sj' = scale (1 - pj') s `add` scale pj' f\n\noracleIter :: Double -> OAS -> Herm Double -> Double\noracleIter tol oas = go 1 . oracleStep oas\n where\n go p (OASIter p' sj')\n | abs (p - p') < tol = p'\n | otherwise = go p' $ oracleStep oas sj'\n\noracleShrinkCovCoef :: Int -> Herm Double -> Double\noracleShrinkCovCoef n s = oracleIter 1e-6 (OAS n p s f) s\n where\n p = cols $ unSym s\n f = avgVarCov s\n\noracleShrinkageCoef :: Matrix Double -> Double\noracleShrinkageCoef x = oracleShrinkCovCoef n (sampleCov x)\n where n = rows x\n\nsq :: Num a => a -> a\nsq a = a * a\n\ntrace :: Matrix Double -> Double\ntrace = sumVector kbn . takeDiag\n", "meta": {"hexsha": "319be51c0cde70ebbf265515d04f3cd5dd1802df", "size": 2940, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Covariance/Shrinkage/MMSE.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/MMSE.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/MMSE.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": 26.9724770642, "max_line_length": 78, "alphanum_fraction": 0.6425170068, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5471682232335842}} {"text": "module Haskov where\n\nimport System.Random\nimport Data.Tuple (swap)\nimport Data.List (foldl')\nimport Data.Sequence (Seq, (|>))\nimport qualified Data.Sequence as Seqq\nimport Data.Map.Strict (Map, keys, foldlWithKey', foldrWithKey', mapWithKey)\nimport qualified Data.Map.Strict as Map\nimport Numeric.LinearAlgebra (scale, luSolve, luPacked)\n--import qualified Numeric.LinearAlgebra as Lin\nimport Numeric.LinearAlgebra.Data (Matrix, matrix, col, cols, ident, tr)\nimport qualified Numeric.LinearAlgebra.Data as Dat\nimport Numeric.LinearAlgebra.HMatrix (sumElements, cmap)\nimport qualified Numeric.LinearAlgebra.HMatrix as Hma\n\n--------------------------------------------------------------------------------\n\n-- Markov Type --\ntype IndexMap a = Map a Int\ntype ReverseIndexMap a = Map Int a\ntype HMatrixMap = Map (Int, Int) Double\n\ndata Markov a = Markov { imap :: IndexMap a\n , hmap :: HMatrixMap }\n\ninstance (Show a, Ord a) => Show (Markov a) where\n show haskov = show $ toList haskov\n\n--------------------------------------------------------------------------------\n\n-- Query --\n-- Safe query\nlookup :: (Ord a) => a -> a -> Markov a -> Maybe Double\nlookup i j (Markov imap hmap)\n | (Map.member i imap) && (Map.member j imap) = Just (hmap Map.! ((imap Map.!i), (imap Map.! j)))\n | otherwise = Nothing\n\n-- Returns number of states\nsize :: (Ord a) => Markov a -> Int\nsize (Markov imap hmap) = Map.size imap\n\n-- Returns true if the chain is empty\nnull :: (Ord a) => Markov a -> Bool\nnull (Markov imap hmap) = Map.null imap\n\n-- Returns true if input is a state of the chain\nmember :: (Ord a) => a -> Markov a -> Bool\nmember i (Markov imap hmap)\n | (Map.member i imap) = True\n | otherwise = False\n\n-- Returns true if input is not a state of the chain\nnotMember :: (Ord a) => a -> Markov a -> Bool\nnotMember i haskov = not (member i haskov)\n\n-- States of the Markov chain\nstates :: (Ord a) => Markov a -> [a]\nstates (Markov imap hmap) = keys imap\n\nstatesI :: (Ord a) => Markov a -> IndexMap a\nstatesI (Markov imap hmap) = imap\n\n--------------------------------------------------------------------------------\n\n-- Construction --\nempty :: Markov a\nempty = Markov (Map.empty) (Map.empty)\n\ninsert :: (Ord a) => a -> a -> Double -> Markov a -> Markov a\ninsert i j d (Markov imap hmap)\n | hasI && (not hasJ) = Markov (Map.insert j s imap) (Map.insert (imap Map.! i, s) d hmap)\n | (not hasI) && hasJ = Markov (Map.insert i s imap) (Map.insert (s, imap Map.! j) d hmap)\n | (not hasI) && (not hasJ) && (i /= j) = Markov (Map.insert j (s+1) (Map.insert i s imap)) (Map.insert (s, (s+1)) d hmap)\n | (not hasI) && (not hasJ) && (i == j) = Markov (Map.insert i s imap) (Map.insert (s, s) d hmap)\n | otherwise = Markov imap (Map.insert (imap Map.! i, imap Map.! j) d hmap)\n where\n hasI = Map.member i imap\n hasJ = Map.member j imap\n s = Map.size imap\n\ninsertWith :: (Ord a) => (Double -> Double -> Double) -> a -> a -> Double -> Markov a -> Markov a\ninsertWith f i j d (Markov imap hmap)\n | hasI && (not hasJ) = Markov (Map.insert j s imap) (Map.insert (imap Map.! i, s) d hmap)\n | (not hasI) && hasJ = Markov (Map.insert i s imap) (Map.insert (s, imap Map.! j) d hmap)\n | (not hasI) && (not hasJ) && (i /= j) = Markov (Map.insert j (s+1) (Map.insert i s imap)) (Map.insert (s, (s+1)) d hmap)\n | (not hasI) && (not hasJ) && (i == j) = Markov (Map.insert i s imap) (Map.insert (s, s) d hmap)\n | otherwise = Markov imap (Map.insertWith f (imap Map.! i, imap Map.! j) d hmap)\n where\n hasI = Map.member i imap\n hasJ = Map.member j imap\n s = Map.size imap\n\n--------------------------------------------------------------------------------\n\n-- Lists --\nfromList :: (Ord a) => [((a, a), Double)] -> Markov a\nfromList list =\n let imap = foldl' toimap Map.empty list\n hmap = foldl' (tohmap imap) Map.empty list\n in Markov imap hmap\n\ntoList :: (Ord a) => Markov a -> [((a, a), Double)]\ntoList (Markov imap hmap) =\n let rIMap = reverseIMap imap\n in foldrWithKey' (combineImapHmap rIMap) [] hmap\n\n--------------------------------------------------------------------------------\n\n-- Maps --\nfromMap :: (Ord a) => Map (a, a) Double -> Markov a\nfromMap mapp =\n let imap = foldlWithKey' toimap' Map.empty mapp\n hmap = foldlWithKey' (tohmap' imap) Map.empty mapp\n in Markov imap hmap\n\n--------------------------------------------------------------------------------\n\n-- Matrices --\nhmatrix :: (Ord a) => Markov a -> Matrix Double\nhmatrix (Markov imap hmap) =\n let m = Map.size imap\n zeros = matrix m (replicate (m*m) 0)\n hlist = Map.toList hmap\n in Dat.accum zeros (+) hlist\n\n--------------------------------------------------------------------------------\n\n-- Chains --\n\nwalkFrom :: (Ord a, Show a) => a -> Int -> Markov a -> StdGen -> IO [a]\nwalkFrom start n haskov gen = do\n let mat = hmatrix haskov\n imap = statesI haskov\n rimap = transMap imap\n nextRow = mat Dat.? [(imap Map.! start)]\n return (start : (steps rimap mat nextRow n gen))\n\nwalk :: (Ord a, Show a) => Int -> Markov a -> StdGen -> IO [a]\nwalk n haskov gen = do\n let mat = hmatrix haskov\n ss = tr . steady $ mat\n imap = statesI haskov\n rimap = transMap imap\n return (steps rimap mat ss n gen)\n\nsteps :: (Ord a, Show a) => ReverseIndexMap a -> Matrix Double -> Matrix Double -> Int -> StdGen -> [a]\nsteps _ _ _ 0 _ = []\nsteps rimap mat row n gen\n | (sumElements row) == 0 = []\n | otherwise = choice : steps rimap mat newRow (n-1) (snd rand)\n where\n rand = random gen\n index = randomStep row (fst rand) 0.0 0\n choice = rimap Map.! index\n newRow = mat Dat.? [index]\n\nrandomStep :: Matrix Double -> Double -> Double -> Int -> Int\nrandomStep row rand total j\n | newTotal < rand = randomStep row rand newTotal newJ\n | otherwise = j\n where\n newTotal = total + (row Dat.! 0 Dat.! j)\n newJ = (j + 1) `mod` (cols row)\n\n--------------------------------------------------------------------------------\n\n-- Steady State --\nsteadyState :: (Ord a) => Markov a -> [(a, Double)]\nsteadyState haskov = zip (states haskov) (concat . Dat.toLists $ steady (hmatrix haskov))\n\nsteady :: Matrix Double -> Matrix Double\nsteady mat =\n let m = Dat.rows mat -- Number of states\n q = tr $ ident m - mat -- Transpose (I-matrix size m - hmatrix)\n e = col ((replicate (m-1) 0) ++ [1.0]) -- col of zeros size m, last element is 1.0\n x = luSolve (luPacked q) e -- Solve linear system of Q and e (Qx = e)\n in scale (1 / (sumElements x)) x -- Divide x by sum of elements\n\n--------------------------------------------------------------------------------\n\n-- Normalize --\nnormalize :: (Ord a) => Markov a -> Markov a\nnormalize (Markov imap hmap) =\n let ss = foldlWithKey' sumSeq Seqq.empty hmap\n in Markov imap (mapWithKey (calcNorm ss) hmap)\n\ncalcNorm :: Seq Double -> (Int, Int) -> Double -> Double\ncalcNorm ss (i, j) n = n / (Seqq.index ss i)\n\nsumSeq :: Seq Double -> (Int, Int) -> Double -> Seq Double\nsumSeq s (i, j) n =\n if Seqq.length s < (i+1)\n then s |> n\n else Seqq.adjust (+n) i s\n\nnorm :: Matrix Double -> Matrix Double\nnorm row = cmap (/ (sumElements row)) row\n\n--------------------------------------------------------------------------------\n\n---- Mapping --\n--map :: (Ord a) => (Double -> Double) -> Markov a -> Markov a\n--map f (Markov imap hmap) = Markov imap (fmap f hmap)\n\n--mapWithState :: (Ord a) => (a -> Double -> Double) -> Markov a -> Markov a\n--mapWithState f (Markov imap hmap) =\n --let rIMap = reverseIMap imap\n\n--------------------------------------------------------------------------------\n\n-- Delete/Update --\n--delete :: (Ord a) => a -> a -> Markov a -> Markov a\n--delete i j (Markov imap hmap) =\n\nadjust :: (Ord a) => (Double -> Double) -> a -> a -> Markov a -> Markov a\nadjust f i j (Markov imap hmap) =\n if Map.member i imap && Map.member j imap\n then Markov imap (Map.adjust f (imap Map.! i, imap Map.! j) hmap)\n else Markov imap hmap\n\n-- Helper Functions --\n-- for fromList\ntoimap :: (Ord a) => IndexMap a -> ((a, a), Double) -> IndexMap a\ntoimap acc ((i, j), d)\n | i /= j && Map.notMember i acc && Map.notMember j acc = Map.insert j (Map.size acc+1) (Map.insert i (Map.size acc) acc)\n | Map.notMember i acc = Map.insert i (Map.size acc) acc\n | Map.notMember j acc = Map.insert j (Map.size acc) acc\n | otherwise = acc\n\n-- For fromMap\ntoimap' :: (Ord a) => IndexMap a -> (a, a) -> Double -> IndexMap a\ntoimap' acc (i, j) d\n | i /= j && Map.notMember i acc && Map.notMember j acc = Map.insert j (Map.size acc+1) (Map.insert i (Map.size acc) acc)\n | Map.notMember i acc = Map.insert i (Map.size acc) acc\n | Map.notMember j acc = Map.insert j (Map.size acc) acc\n | otherwise = acc\n\n-- For fromList\ntohmap :: (Ord a) => IndexMap a -> HMatrixMap -> ((a, a), Double) -> HMatrixMap\ntohmap imap acc ((i, j), n) = Map.insert (imap Map.! i, imap Map.! j) n acc\n\n-- For fromMap\ntohmap' :: (Ord a) => IndexMap a -> HMatrixMap -> (a, a) -> Double -> HMatrixMap\ntohmap' imap acc (i, j) n = Map.insert (imap Map.! i, imap Map.! j) n acc\n\ncombineImapHmap :: (Ord a) => Map Int a -> (Int, Int) -> Double -> [((a, a), Double)] -> [((a, a), Double)]\ncombineImapHmap rIMap (i, j) d acc = ((rIMap Map.! i, rIMap Map.! j), d) : acc\n\nreverseIMap :: (Ord a) => Map a Int -> Map Int a\nreverseIMap imap = foldrWithKey' reverseIMap' Map.empty imap\n where reverseIMap' state i m = Map.insert i state m\n\n\n-- swap map key and index\ntransMap :: (Ord k, Ord a) => Map k a -> Map a k\ntransMap = Map.fromList . map swap . Map.toList\n\n-- Machine Epsilon --\n\nmachineE :: Double\nmachineE = until ((== 1) . (+1)) (/2) 1\n", "meta": {"hexsha": "5105abec5907c59c09486c2a7008806e7ab585b5", "size": 9830, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Haskov.hs", "max_stars_repo_name": "francisdb/haskov", "max_stars_repo_head_hexsha": "5fe128335238d5a838676fc2396cb85cda56e258", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-04-25T20:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-19T13:14:24.000Z", "max_issues_repo_path": "src/Haskov.hs", "max_issues_repo_name": "francisdb/haskov", "max_issues_repo_head_hexsha": "5fe128335238d5a838676fc2396cb85cda56e258", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-08-22T07:26:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-12T19:03:37.000Z", "max_forks_repo_path": "src/Haskov.hs", "max_forks_repo_name": "francisdb/haskov", "max_forks_repo_head_hexsha": "5fe128335238d5a838676fc2396cb85cda56e258", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-09-26T22:04:01.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-26T22:04:01.000Z", "avg_line_length": 37.3764258555, "max_line_length": 125, "alphanum_fraction": 0.5540183113, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5469648048686402}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_HADDOCK show-extensions #-}\n\nmodule NQS.CG\n ( Operator\n , NQS.CG.cg\n , test\n ) where\n\nimport Data.Complex\nimport Control.Monad.Primitive\n\nimport qualified Data.Vector.Storable as V\nimport qualified Data.Vector.Storable.Mutable as MV\n\nimport Foreign.Storable\n\nimport Lens.Micro\n\nimport NQS.Internal.Types\nimport NQS.Internal.BLAS\n\n\ntype Operator m el = -- forall m. PrimMonad m\n MDenseVector 'Direct (PrimState m) el -- ^ Input\n -> MDenseVector 'Direct (PrimState m) el -- ^ Output\n -> m ()\n\nclass ToComplex a where\n promoteToComplex :: RealOf a -> a\n\ninstance {-# OVERLAPPABLE #-} (a ~ RealOf a) => ToComplex a where\n promoteToComplex = id\n\ninstance {-# OVERLAPS #-} (Num a, a ~ RealOf (Complex a)) => ToComplex (Complex a) where\n promoteToComplex = (:+ 0)\n\ncg :: forall v el m.\n ( PrimMonad m, v ~ MDenseVector 'Direct\n , DOTC v el el, AXPY v el, COPY v el\n , NRM2 v el (RealOf el), SCAL (RealOf el) v el\n , Storable el, Fractional el, ToComplex el, RealFloat (RealOf el)\n )\n => Int -- ^ Max number of iterations\n -> RealOf el -- ^ Tolerance\n -> Operator m el -- ^ A\n -> MDenseVector 'Direct (PrimState m) el -- ^ b\n -> MDenseVector 'Direct (PrimState m) el -- ^ Initial guess x\n -> m (Int, RealOf el)\ncg !maxIter !tol operator !b !x0 = do\n r <- newTempVector n\n p <- newTempVector n\n q <- newTempVector n\n bNorm <- norm b\n -- This will probably never ever happen, but we should check anyway\n if bNorm == 0\n then fill x0 0 >> return (0, 0)\n else do\n -- r := b - max * x0\n copy b r\n operator x0 q\n axpy (-1) q r\n -- Are we done already?\n norm r >>= \\rNorm -> if rNorm < tol * tol * bNorm\n then return $! (0, sqrt (rNorm / bNorm))\n else do\n -- Start the loop\n copy r p\n go bNorm x0 r p q rNorm 0\n where\n n = b ^. dim\n newTempVector size = MDenseVector size 1 <$> newVectorAligned size 64\n norm x = (\\y -> y * y) <$> nrm2 x\n go !bNorm !x !r !p !q !ρ !i\n | i >= maxIter = nrm2 r >>= \\rNorm -> return (i, rNorm / bNorm)\n | otherwise = do\n operator p q\n α <- (promoteToComplex ρ /) <$> dotc p q\n axpy α p x\n axpy (-α) q r\n norm r >>= \\rNorm -> if rNorm < threshold\n then return (i, sqrt (rNorm / bNorm))\n else do copy r q\n let ρ' = rNorm\n β = ρ' / ρ\n scal β p\n axpy 1 q p\n go bNorm x r p q ρ' (i + 1)\n where threshold :: RealOf el\n threshold = tol * tol * bNorm\n\ntest :: IO ()\ntest = do\n let -- operator :: Operator Float\n operator x y = do\n aBuff <- newVectorAligned 9 64 :: IO (MV.MVector (PrimState IO) Float)\n V.copy aBuff $ V.fromList [1, 2, 3, 4, 5, 6, 7, 8, 9]\n let a = MDenseMatrix 3 3 3 aBuff :: MDenseMatrix 'Row (PrimState IO) Float\n gemv NoTranspose 1.0 a x 0.0 y\n bBuff <- V.unsafeThaw $ V.fromList [2, 2, 2 :: Float]\n xBuff <- V.unsafeThaw $ V.fromList [0, 0, 0 :: Float]\n let x = MDenseVector 3 1 xBuff :: MDenseVector 'Direct (PrimState IO) Float\n let b = MDenseVector 3 1 bBuff :: MDenseVector 'Direct (PrimState IO) Float\n print =<< (NQS.CG.cg 30 (1.0E-8 :: Float) operator b x)\n\n", "meta": {"hexsha": "6f8723239ac5b0d9fd183a4e2a6bfe40fd7555fc", "size": 3713, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NQS/CG.hs", "max_stars_repo_name": "twesterhout/tcm-swarm", "max_stars_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NQS/CG.hs", "max_issues_repo_name": "twesterhout/tcm-swarm", "max_issues_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NQS/CG.hs", "max_forks_repo_name": "twesterhout/tcm-swarm", "max_forks_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2016806723, "max_line_length": 88, "alphanum_fraction": 0.5952060329, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.5461977719858785}} {"text": "{-# OPTIONS_GHC -fplugin Numeric.Units.Dimensional.DK.Solver #-}\n\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule Controls\nwhere\n\nimport Numeric.Units.Dimensional.DK.Prelude\nimport Numeric.LinearAlgebra.Dimensional.DK.Shapes\nimport qualified Prelude as P\n\ndata DimMat (s :: Shape) (e :: *) = DimMat\n\n(<>) :: DimMat s1 e -> DimMat s2 e -> DimMat (ShapeProduct s1 s2) e\n_ <> _ = DimMat\n\nadd :: DimMat s e -> DimMat s e -> DimMat s e\nadd _ _ = DimMat\n\ndata ContinuousLiSystem (iv :: Dimension) (xs :: [Dimension]) (ys :: [Dimension]) (us :: [Dimension]) e = ContinuousLiSystem\n {\n a'' :: DimMat (DivideVectorLists (MapDiv iv xs) xs) e,\n b'' :: DimMat (DivideVectorLists (MapDiv iv xs) us) e,\n c'' :: DimMat (DivideVectorLists ys xs) e,\n d'' :: DimMat (DivideVectorLists ys us) e\n }\n\ntype ContinuousLtiSystem = ContinuousLiSystem DTime\n\ntype ExampleSystem = ContinuousLtiSystem\n '[DLength, DVelocity, DPlaneAngle, DAngularVelocity]\n '[DLength, DPlaneAngle]\n '[DForce]\n Double\n\nevaluate :: ContinuousLiSystem iv (x ': xs) (y ': ys) (u ': us) e -> DimMat (VectorShape x xs) e -> DimMat (VectorShape u us) e -> (DimMat (VectorShape (x / iv) (MapDiv iv xs)) e, DimMat (VectorShape y ys) e)\nevaluate sys x u = let\n a = a'' sys\n b = b'' sys\n c = c'' sys\n d = d'' sys\n xDot = (a <> x) `add` (b <> u)\n y = (c <> x) `add` (d <> u)\n in (xDot, y)\n\n{- Example from http://ctms.engin.umich.edu/CTMS/index.php?example=InvertedPendulum§ion=ControlStateSpace -}\n\n-- not really stated on that page, but if you go back a couple of pages in their derivation\n-- you can see that the type of u is a 1x1 matrix whose sole element is a force\n\nmassOfCart = (0.5 :: Double) *~ (kilo gram)\nmassOfPendulum = (0.2 :: Double) *~ (kilo gram)\ncoefficientOfFrictionForCart = (0.1 :: Double) *~ (newton / (meter / second))\nlengthToPendulumCenterOfMass = (0.3 :: Double) *~ meter\nmassMomentOfInertiaOfPendulum = (0.006 :: Double) *~ (kilo gram * meter^pos2)\ng = (9.8 :: Double) *~ (meter / second^pos2)\n\np = massMomentOfInertiaOfPendulum*(massOfCart+massOfPendulum)+(massOfCart*massOfPendulum*lengthToPendulumCenterOfMass*lengthToPendulumCenterOfMass)\n\na22 = negate (massMomentOfInertiaOfPendulum+massOfPendulum * lengthToPendulumCenterOfMass * lengthToPendulumCenterOfMass) * coefficientOfFrictionForCart / p\na23 = (massOfPendulum * massOfPendulum * g * lengthToPendulumCenterOfMass * lengthToPendulumCenterOfMass) / p\na42 = negate (massOfPendulum * lengthToPendulumCenterOfMass * coefficientOfFrictionForCart) / p\na43 = massOfPendulum * g * lengthToPendulumCenterOfMass*(massOfCart + massOfPendulum)/p\n\nb21 = (massMomentOfInertiaOfPendulum + (massOfPendulum * lengthToPendulumCenterOfMass * lengthToPendulumCenterOfMass)) / p\nb41 = massOfPendulum * lengthToPendulumCenterOfMass / p\n\n{-\npendulum = ContinuousLiSystem {\n a'' = [matD| _0, _1, _0, _0;\n _0, a22, a23, _0;\n _0, _0, _0, _1;\n _0, a42, a43, _0 |],\n b'' = [matD| _0;\n b21;\n _0;\n b41 |],\n c'' = [matD| _1, _0, _0, _0;\n _0, _0, _1, _0 |],\n d'' = zeroes\n } :: ExampleSystem\n-}\n\npendulum = ContinuousLiSystem {\n a'' = DimMat,\n b'' = DimMat,\n c'' = DimMat,\n d'' = DimMat\n } :: ExampleSystem\n", "meta": {"hexsha": "ddeada7d72a5ad6922897f6e67a2c71527b66c81", "size": 4202, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/Controls.hs", "max_stars_repo_name": "dmcclean/dimensional-dk-linalg", "max_stars_repo_head_hexsha": "acc39b98d5422b5f5f405efc504edd472c368924", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-02-01T09:15:12.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-01T09:15:12.000Z", "max_issues_repo_path": "examples/Controls.hs", "max_issues_repo_name": "dmcclean/dimensional-dk-linalg", "max_issues_repo_head_hexsha": "acc39b98d5422b5f5f405efc504edd472c368924", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Controls.hs", "max_forks_repo_name": "dmcclean/dimensional-dk-linalg", "max_forks_repo_head_hexsha": "acc39b98d5422b5f5f405efc504edd472c368924", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6739130435, "max_line_length": 209, "alphanum_fraction": 0.5264159924, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5461936102922724}} {"text": "module Statistics.Information.Continuous.TotalCorrelation where\n\nimport Data.Matrix\nimport Statistics.Information.Continuous.Entropy\nimport Statistics.Information.Continuous.MutualInfo\nimport Statistics.Information.Utils.Matrix\nimport Statistics.Information.Utils.Random\nimport System.Random\n\ntc :: RandomGen g => g -> Int -> Int -> Matrix Double -> Double\ntc g k base xs = sum hxs - hx where\n hxs = [entropy gcol k base col | (col, gcol) <- cols]\n hx = entropy g2 k base xs\n (g1, g2) = split g\n cols = (map colVector (columns xs)) `zip` (splitN (ncols xs) g1)\n\nctc :: RandomGen g => g -> Int -> Int -> Matrix Double -> Matrix Double ->\n Double\nctc g k base xs ys = sum hxs - hx where\n hxs = [centropy gcol k base col ys | (col, gcol) <- cols]\n hx = centropy g2 k base xs ys\n (g1, g2) = split g\n cols = (map colVector (columns xs)) `zip` (splitN (ncols xs) g1)\n\ncorex_tcs :: RandomGen g => g -> Int -> Int -> Matrix Double -> Matrix Double ->\n Double\ncorex_tcs g k base xs ys = tc g1 k base xs - ctc g2 k base xs ys where\n (g1, g2) = split g\n\ncorex_mis :: RandomGen g => g -> Int -> Int -> Matrix Double -> Matrix Double ->\n Double\ncorex_mis g k base xs ys = sum mixs - mi_all where\n mixs = [mi gcol k base col ys | (col, gcol) <- cols]\n mi_all = mi g2 k base xs ys\n (g1, g2) = split g\n cols = (map colVector (columns xs)) `zip` (splitN (ncols xs) g1)\n\nresidual :: RandomGen g => g -> Int -> Int -> Matrix Double -> Double\nresidual g k base xs = sum $ [hlessxi i gi | (i, gi) <- igs] where\n hlessxi i gi = let xi = (colVector $ getCol i xs) in\n centropy gi k base xi $ residualMatrix xs i\n igs = [1..(ncols xs)] `zip` (splitN (ncols xs) g)\n\ndtc :: RandomGen g => g -> Int -> Int -> Matrix Double -> Double\ndtc g k base xs = entropy g1 k base xs - residual g2 k base xs where\n (g1, g2) = split g\n", "meta": {"hexsha": "10e0b94d3b9722cd4a3425aa67ba023fdc3a2c5a", "size": 1844, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Information/Continuous/TotalCorrelation.hs", "max_stars_repo_name": "eligottlieb/Shannon", "max_stars_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/Information/Continuous/TotalCorrelation.hs", "max_issues_repo_name": "eligottlieb/Shannon", "max_issues_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Information/Continuous/TotalCorrelation.hs", "max_forks_repo_name": "eligottlieb/Shannon", "max_forks_repo_head_hexsha": "87af5f2cde551fa89a4b1f97a4c190bbae4fcccb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2340425532, "max_line_length": 80, "alphanum_fraction": 0.649132321, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.629774600455747, "lm_q1q2_score": 0.5460370948827566}} {"text": "-- MandelBrot implementation in Haskell\nimport Data.Complex\nimport System.Environment\nimport Control.Parallel.Strategies\nimport Criterion.Measurement\n--import Graphics.UI.SDL \n\n\n--initSDL :: IO Surface\n--initSDL = do\n-- SDL.init [SDL.InitEverything]\n-- SDL.setVideoMode (floor imageWidth) (floor imageHeight) 32 []\n-- SDL.setCaption \"Mandelbrot\" \"Mandelbrot\"- screen <- getVideoSurface\n-- white <- SDL.mapRGB (SDL.surfaceGetPixelFormat screen) 255 255 255\n-- fillRect screen Nothing white >> SDL.flip screen\n-- return screen\n \nmandelbrot :: Num a => a -> Int -> a\nmandelbrot a n = iterate (\\z -> z^2 + a) 0 !! n\n \nmbrot_seq :: Int -> Int -> Int -> [[Bool]]\nmbrot_seq iter w h = [[magnitude (mandelbrot (x :+ y) iter) < 2 \n | x <- [-2, (-2 + incW) .. 2]]\n | y <- [ 2, (2 - incH) .. -2]]\n where incW = 4.0 / (fromIntegral w)\n incH = 4.0 / (fromIntegral h)\n\n\n\nmbrot_par :: Int -> Int -> Int -> [[Bool]]\nmbrot_par iter w h = (mbrot_seq iter w h) `using` parList rdeepseq\n\n\ndraw_image :: Int -> Int -> [[Bool]] -> IO()\ndraw_image x y xs = print \"to be implemented\"\n\nmain = do\n initializeTime\n start_time <- getTime\n args <- getArgs\n if (length args < 4) \n then print \"Expected \\\"par/seq\\\"iterations, image width, and image height\" \n else do\n let nIter = read (args !! 1) :: Int\n let nWidth = read (args !! 2) :: Int\n let nHeight = read (args !! 3) :: Int\n case (args !! 0) of \n \"seq\" -> print $ mbrot_seq nIter nWidth nHeight \n \"par\" -> print $ mbrot_par nIter nWidth nHeight \n otherwise -> print \"expected first argument to be `par` or `seq`\"\n end_time <- getTime\n print $ \"Time elapsed : \" ++ show (floor $ 10000 * (end_time - start_time)) ++ \"ms\"\n \n\n", "meta": {"hexsha": "db9453527d75c8f2112d07511e841a2a7d2faa25", "size": 1878, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "mandelbrot.hs", "max_stars_repo_name": "RossMeikleham/Parallel-Mandelbrot", "max_stars_repo_head_hexsha": "faf75e4975e1c2d75e983c53994f0e24fae298e1", "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": "mandelbrot.hs", "max_issues_repo_name": "RossMeikleham/Parallel-Mandelbrot", "max_issues_repo_head_hexsha": "faf75e4975e1c2d75e983c53994f0e24fae298e1", "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": "mandelbrot.hs", "max_forks_repo_name": "RossMeikleham/Parallel-Mandelbrot", "max_forks_repo_head_hexsha": "faf75e4975e1c2d75e983c53994f0e24fae298e1", "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.1454545455, "max_line_length": 95, "alphanum_fraction": 0.5740149095, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5452929137353592}} {"text": "{-# LANGUAGE MonoLocalBinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE StrictData #-}\nmodule FourierPinwheel.Array where\n\nimport qualified Data.Array.Accelerate as A\nimport qualified Data.Array.Accelerate.LLVM.PTX as A\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 DFT.Plan\nimport Filter.Utils\nimport Graphics.Rendering.Chart.Backend.Cairo\nimport Graphics.Rendering.Chart.Easy\nimport Image.IO\nimport Text.Printf\nimport Utils.Array\nimport Utils.BLAS\nimport Utils.Parallel\nimport FourierMethod.FourierSeries2D\n\ndata FPArray vector = FPArray\n { getFPArrayNumXFreq :: Int\n , getFPArrayNumYFreq :: Int\n , getFPArrayNumRFreq :: Int\n , getFPArrayNumThetaFreq :: Int\n , getFPArrayNumRhoFreq :: Int\n , getFPArrayNumPhiFreq :: Int\n , getFPArray :: [vector]\n }\n\n{-# INLINE toMatrixAcc #-}\ntoMatrixAcc ::\n (VG.Vector vector e, A.Elt e) => FPArray (vector e) -> A.Acc (A.Array A.DIM2 e)\ntoMatrixAcc (FPArray numXFreq numYFreq numRFreq numThetaFreq _ _ arr) =\n A.use .\n A.fromList (A.Z A.:. (numRFreq * numThetaFreq) A.:. (numXFreq * numYFreq)) .\n VG.toList . VG.concat $\n arr\n\n{-# INLINE parMapFPArray #-}\nparMapFPArray ::\n (NFData vector) => (vector -> vector) -> FPArray vector -> FPArray vector\nparMapFPArray f (FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq vecs) =\n FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq .\n parMap rdeepseq f $\n vecs\n\n{-# INLINE parZipWithFPArray #-}\nparZipWithFPArray ::\n (NFData vector)\n => (vector -> vector -> vector)\n -> FPArray vector\n -> FPArray vector\n -> FPArray vector\nparZipWithFPArray f (FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq vecs1) =\n FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq .\n parZipWith rdeepseq f vecs1 . getFPArray\n\n\nplotFPArray ::\n DFTPlan\n -> FilePath\n -> FPArray (VS.Vector (Complex Double))\n -> IO (R.Array R.U R.DIM4 (Complex Double))\nplotFPArray plan filePath arr = do\n let planIDBackward =\n DFTPlanID\n IDFT1DG\n [ getFPArrayNumThetaFreq arr\n , getFPArrayNumXFreq arr\n , getFPArrayNumYFreq arr\n ]\n [1, 2]\n vecsR2 <- dftExecuteBatchP plan planIDBackward . getFPArray $ arr\n arrR2 <-\n R.computeUnboxedP .\n makeFilter2DInverse .\n R.fromUnboxed\n (R.Z R.:. getFPArrayNumRFreq arr R.:. getFPArrayNumThetaFreq arr R.:.\n getFPArrayNumXFreq arr R.:.\n getFPArrayNumYFreq arr) .\n VS.convert . VS.concat $\n vecsR2\n arr1 <-\n R.sumP . R.sumS . R.map (\\x -> magnitude x Prelude.^ 2) . rotate4D2 $ arrR2\n plotImageRepa filePath .\n ImageRepa 8 .\n R.fromUnboxed\n (R.Z R.:. (1 :: Int) R.:. getFPArrayNumXFreq arr R.:.\n getFPArrayNumYFreq arr) .\n -- VG.map (\\x -> log (x + 1)) .\n R.toUnboxed $ arr1\n return arrR2\n\n \nplotFPArrayAcc ::\n (A.Elt (Complex Double))\n => [A.PTX]\n -> FilePath\n -> Int\n -> Double\n -> Double\n -> Int\n -> FPArray (VS.Vector (Complex Double))\n -> IO (R.Array R.U R.DIM4 (Complex Double))\nplotFPArrayAcc ptxs filePath numPoints delta periodR2 numBatch arr@(FPArray numXFreq numYFreq numRFreq numThetaFreq _ _ vecs) = do\n let rows = numRFreq * numThetaFreq\n cols = numXFreq * numYFreq\n arrMat =\n A.transpose .\n A.use .\n A.fromList (A.Z A.:. rows A.:. cols) .\n R.toList .\n makeFilter2DInverse .\n fromUnboxed (Z :. rows :. numXFreq :. numXFreq) . VG.convert . VG.concat $\n vecs\n arrR2 <-\n computeFourierSeriesR2StreamAcc\n ptxs\n numXFreq\n numPoints\n rows\n periodR2\n delta\n numBatch\n arrMat\n (sumP . R.map (\\x -> magnitude x ** 2) . rotate3D $ arrR2) >>=\n plotImageRepa filePath .\n ImageRepa 8 .\n fromUnboxed (Z :. (1 :: Int) :. numPoints :. numPoints) . toUnboxed\n return .\n computeS .\n R.reshape (Z :. numRFreq :. numThetaFreq :. numPoints :. numPoints) $\n arrR2\n\nplotFPArrayFreqency ::\n FilePath\n -> FPArray (VS.Vector (Complex Double))\n -> IO ()\nplotFPArrayFreqency filePath arr = do\n arr1 <-\n R.sumP .\n R.sumS .\n R.map (\\x -> magnitude x Prelude.^ 2) .\n rotate4D2 .\n makeFilter2DInverse .\n R.fromUnboxed\n (R.Z R.:. getFPArrayNumRFreq arr R.:. getFPArrayNumThetaFreq arr R.:.\n getFPArrayNumXFreq arr R.:.\n getFPArrayNumYFreq arr) .\n VS.convert . VS.concat . getFPArray $\n arr\n plotImageRepa filePath .\n ImageRepa 8 .\n R.fromUnboxed\n (R.Z R.:. (1 :: Int) R.:. getFPArrayNumXFreq arr R.:.\n getFPArrayNumYFreq arr) .\n -- VG.map (\\x -> x^2) .\n R.toUnboxed $\n arr1\n\n\nplotRThetaDist ::\n FilePath\n -> FilePath\n -> Int\n -> Int\n -> Int\n -> Double\n -> (Int, Int)\n -> R.Array R.U R.DIM4 (Complex Double)\n -> IO ()\nplotRThetaDist filePathTheta filePathR numPoints numTheta numR periodEnv (x, y) arr = do\n let (Z :. numRFreq :. numThetaFreq :. _ :. _) = extent arr\n center = div numPoints 2\n centerR = div numR 2\n centerTheta = div numTheta 2\n centerRFreq = div numRFreq 2\n centerThetaFreq = div numThetaFreq 2\n vecRTheta =\n VG.convert . R.toUnboxed . R.computeUnboxedS . R.slice arr $\n (R.Z R.:. R.All R.:. R.All R.:. (x + center) R.:. (y + center))\n deltaTheta = 2 * pi / Prelude.fromIntegral numTheta\n deltaLogR = log periodEnv / Prelude.fromIntegral numR\n matrix =\n VG.convert .\n R.toUnboxed .\n R.computeUnboxedS .\n R.fromFunction (R.Z R.:. numR R.:. numTheta :. numRFreq :. numThetaFreq) $ \\(Z :. r :. t :. rf :. tf) ->\n cis\n (fromIntegral ((r - centerR) * (rf - centerRFreq)) * 2 * pi /\n log periodEnv *\n deltaLogR +\n fromIntegral ((t - centerTheta) * (tf - centerThetaFreq)) *\n deltaTheta)\n m = numR * numTheta\n n = 1\n k = numRFreq * numThetaFreq\n vec <- VS.map magnitude <$> gemmBLAS m n k matrix vecRTheta\n let outputArr = fromUnboxed (Z :. numR :. numTheta) . VG.convert $ vec\n outputR = R.toList . sumS $ outputArr\n outputTheta =\n R.toList .\n sumS .\n R.backpermute (Z :. numTheta :. numR) (\\(Z :. i :. j) -> (Z :. j :. i)) $\n outputArr\n toFile def filePathTheta $ do\n layout_title .= printf \"Theta (%d , %d)\" x y\n plot\n (line\n \"\"\n [ L.zip\n [ fromIntegral (i - centerTheta) * deltaTheta\n | i <- [0 .. numTheta - 1]\n ]\n outputTheta\n ])\n toFile def filePathR $ do\n layout_title .= printf \"LogR (%d , %d)\" x y\n plot\n (line\n \"\"\n [ L.zip\n [fromIntegral (i - centerR) * deltaLogR | i <- [0 .. numR - 1]]\n outputR\n ])\n", "meta": {"hexsha": "67c7e8c5f4df568d3eee2300b10997153e8ff743", "size": 7118, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FourierPinwheel/Array.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/Array.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/Array.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.8138528139, "max_line_length": 130, "alphanum_fraction": 0.5927226749, "num_tokens": 2147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5452035196298557}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n\nmodule Backprop.Learn.Model.Neural (\n -- * Fully connected\n -- ** Feed-forward\n FC, pattern FC, FCp, fcBias, fcWeights\n -- *** With activation function\n , FCA, pattern FCA, _fcaActivation\n -- ** Recurrent\n , FCR, pattern FCR, FCRp, fcrBias, fcrInputWeights, fcrStateWeights\n -- *** With activation function\n , FCRA, pattern FCRA, _fcraStore, _fcraActivation\n ) where\n\n\nimport Backprop.Learn.Model.Combinator\nimport Backprop.Learn.Model.Regression\nimport Backprop.Learn.Model.State\nimport Data.Tuple\nimport GHC.TypeNats\nimport Lens.Micro\nimport Numeric.Backprop\nimport Numeric.LinearAlgebra.Static.Backprop\nimport qualified Numeric.LinearAlgebra.Static as H\n\n-- | Fully connected feed-forward layer with bias. Parameterized by its\n-- initialization distribution.\n--\n-- Note that this has no activation function; to use as a model with\n-- activation function, chain it with an activation function using 'RMap',\n-- ':.~', etc.; see 'FCA' for a convenient type synonym and constructor.\n--\n-- Without any activation function, this is essentially a multivariate\n-- linear regression.\n--\n-- With the logistic function as an activation function, this is\n-- essentially multivariate logistic regression. (See 'Logistic')\ntype FC i o = LinReg i o\n\npattern FC :: FC i o\npattern FC = LinReg\n\n-- | Convenient synonym for an 'FC' post-composed with a simple\n-- parameterless activation function.\ntype FCA i o = RMap (R o) (R o) (FC i o)\n\n-- | Construct an 'FCA' using a generating function and activation\n-- function.\n--\n-- Some common ones include 'logistic' and @'vmap' 'reLU'@.\npattern FCA\n :: (forall s. Reifies s W => BVar s (R o) -> BVar s (R o)) -- ^ '_fcaActivation'\n -> FCA i o\npattern FCA { _fcaActivation } = RM _fcaActivation FC\n\ntype FCp = LRp\n\nfcWeights :: Lens (FCp i o) (FCp i' o) (L o i) (L o i')\nfcWeights = lrBeta\n\nfcBias :: Lens' (FCp i o) (R o)\nfcBias = lrAlpha\n\n-- | Fully connected recurrent layer with bias.\n--\n-- Parameterized by its initialization distributions, and also the function\n-- to compute the new state from previous input.\n--\n-- @\n-- instance 'Learn' ('R' i) (R o) ('FCR' h i o) where\n-- type 'LParamMaybe' (FCR h i o) = ''Just' ('FCRp' h i o)\n-- type 'LStateMaybe' (FCR h i o) = 'Just (R h)\n-- @\ntype FCR h i o = Recurrent (R (i + h)) (R i) (R h) (R o) (FC (i + h) o)\n\n-- | Construct an 'FCR'\npattern FCR\n :: (KnownNat h, KnownNat i)\n => (forall s. Reifies s W => BVar s (R o) -> BVar s (R h)) -- ^ '_fcrSTore'\n -> FCR h i o\npattern FCR { _fcrStore } <-\n Rec { _recLoop = _fcrStore\n , _recLearn = FC\n }\n where\n FCR s = Rec { _recSplit = H.split\n , _recJoin = (H.#)\n , _recLoop = s\n , _recLearn = FC\n }\n{-# COMPLETE FCR #-}\n\n-- | Convenient synonym for an 'FCR' post-composed with a simple\n-- parameterless activation function.\ntype FCRA h i o = RMap (R o) (R o) (FCR h i o)\n\n-- | Construct an 'FCRA' using a generating function and activation\n-- function.\n--\n-- Some common ones include 'logistic' and @'vmap' 'reLU'@.\npattern FCRA\n :: (KnownNat h, KnownNat i)\n => (forall s. Reifies s W => BVar s (R o) -> BVar s (R h)) -- ^ '_fcraStore'\n -> (forall s. Reifies s W => BVar s (R o) -> BVar s (R o)) -- ^ '_fcraActivation'\n -> FCRA h i o\npattern FCRA { _fcraStore, _fcraActivation }\n = RM _fcraActivation (FCR _fcraStore)\n\ntype FCRp h i o = FCp (i + h) o\n\nlensIso :: (s -> (a, x)) -> ((b, x) -> t) -> Lens s t a b\nlensIso f g h x = g <$> _1 h (f x)\n\nfcrInputWeights\n :: (KnownNat h, KnownNat i, KnownNat i', KnownNat o)\n => Lens (FCRp h i o) (FCRp h i' o) (L o i) (L o i')\nfcrInputWeights = fcWeights . lensIso H.splitCols (uncurry (H.|||))\n\nfcrStateWeights\n :: (KnownNat h, KnownNat h', KnownNat i, KnownNat o)\n => Lens (FCRp h i o) (FCRp h' i o) (L o h) (L o h')\nfcrStateWeights = fcWeights . lensIso (swap . H.splitCols) (uncurry (H.|||) . swap)\n\nfcrBias :: Lens' (FCRp h i o) (R o)\nfcrBias = fcBias\n\n", "meta": {"hexsha": "5ff602783fe2f945df06d57968b50930848aafaf", "size": 4738, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "old2/src/Backprop/Learn/Model/Neural.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "old2/src/Backprop/Learn/Model/Neural.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "old2/src/Backprop/Learn/Model/Neural.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 34.5839416058, "max_line_length": 94, "alphanum_fraction": 0.5987758548, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571774, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5445220082719927}} {"text": "-- file: Astro/PostNewtonian.hs\n-- Post-Newtonian approximations for two-body problem\n\nmodule Astro.PostNewtonian\n\twhere\n\nimport Astro.Misc\nimport Numeric.LinearAlgebra\n\nimport Data.List (foldl')\n\n-- Calculate Post-Newtonian acceleration functions for non-spin\n-- dependent terms\nmkNonSpinPNs :: Double->Double->Double->Double->\n\t[(Vector Double->Vector Double->Vector Double)]\nmkNonSpinPNs gc c m1 m2 = \t[ a1\n\t\t\t\t, a2\n\t\t\t\t, a2_5\n\t\t\t\t] \n\t\t\twhere\n\t-- Keplerian contribution\n\t--a0 :: Vector Double -> Vector Double -> Vector Double\n\t--a0 rv vv = scale (-gm / r^3) rv where r = norm rv\n\n\ta1 :: Vector Double -> Vector Double -> Vector Double\n\ta1 rv vv = {-# SCC \"a1\" #-} \n\t\tscale (-gmperc2 / r^2) $\n\t\t\tscale nbrac nv + scale vbrac vv\n\t\twhere\n\t\t\tnbrac = -2*(2+eta)*gm/r + (1+3*eta)*v^2 - 3/2*eta*rd^2 \n\t\t\tvbrac = -2*(2-eta)*rd\n\t\t\tr\t= norm rv\n\t\t\tv\t= norm vv\n\t\t\tnv\t= unitV rv\n\t\t\trd\t= (rv <.> vv)/r\n\n\ta2 :: Vector Double -> Vector Double -> Vector Double\n\ta2 rv vv = {-# SCC \"a2\" #-} \n\t\tscale (- gmperc2 / (c^2 * r^2)) $\n\t\t\tscale (nbrac/r) rv + scale ((-rd/2) * vbrac) vv\n\t\twhere\n\t\t\tnbrac = 3/4*(12+29*eta)*(gm/r)^2 + eta*(3-4*eta)*v^4\n\t\t\t\t+ 15/8*eta*(1-3*eta)*rd^4\n\t\t\t\t- 3/2*eta*(3-4*eta)*v^2*rd^2\n\t\t\t\t- 1/2*eta*(13-4*eta)*(gm/r)*v^2\n\t\t\t\t- (2+25*eta+2*eta^2)*(gm/r)*rd^2\n\t\t\tvbrac = eta*(15+4*eta)*v^2 - (eta+41*eta+8*eta^2)*(gm/r)\n\t\t\t\t- 3*eta*(3+2*eta)*rd^2\n\t\t\tr\t= norm rv\n\t\t\tv\t= norm vv\n\t\t\trd\t= (rv <.> vv)/r\n\n\ta2_5 :: Vector Double -> Vector Double -> Vector Double\n\ta2_5 rv vv = {-# SCC \"a2_5\" #-} \n\t\tscale (8/15*(gmperc2)^2*eta/(c*r^2)) $\n\t\t\tscale (nbrac*rd/r) rv + scale (-vbrac) vv\n\t\twhere\n\t\t\tnbrac \t= 9*v^2 + 17*gm/r\n\t\t\tvbrac \t= 3*v^2 + 9*gm/r\n\t\t\tr\t= norm rv\n\t\t\tv\t= norm vv\n\t\t\trd\t= (rv <.> vv)/r\n\tgm \t= gc * m\n\tgmperc2 = gm / c ^2\n\tm \t= m1+m2\n\teta \t= m1*m2/m^2\n\n-- Calculate Post-Newtonian acceleration functions for spin\n-- dependent terms\n--mkSpinPNs :: Double->Double->Double->Double->Double->Double->\n--\t[(Vector Double->Vector Double->Vector Double->Vector Double)]\nmkSpinPNs gc c m1 m2 chi q = \t[ spinOrbit\n\t\t\t\t, quadMonoInteraction\n\t\t\t\t] where\n\t--spinOrbit :: Vector Double -> Vector Double -> Vector Double\n\t--\t\t-> Vector Double\n\tspinOrbit rv vv s = {-# SCC \"SO\" #-} \n\t\tscale (gm^2/(r^3*c^3)*(1+sqrt (1-4*eta))/4*chi) $\n\t\t\t\tscale nbrac nv + scale (nsbrac) (cross nv s')\n\t\t\t\t\t+ scale (-vsbrac) (cross vv s')\n\t\twhere\n\t\t\tnbrac = 12 * s' <.> (cross nv vv)\n\t\t\tnsbrac = (9 + 3 * sqrt (1-4*eta))*rd\n\t\t\tvsbrac = 7 + sqrt(1-4*eta)\n\t\t\tr\t= norm rv\n\t\t\tv\t= norm vv\n\t\t\tnv\t= unitV rv\n\t\t\trd\t= (rv <.> vv)/r\n\t\t\ts'\t= spinCylToSpher s\n\n\t--quadMonoInteraction :: Vector Double -> Vector Double -> Vector Double\n\t--\t\t\t-> Vector Double\n\tquadMonoInteraction rv vv s = {-# SCC \"Q\" #-}\n\t\t-- FIXME: Minus or no minus? Depends on whether\n\t\t-- coordinates fixed on m1 or m2, see OJ287 paper, minus\n\t\t-- in paper.\n\t\tscale (-q*chi^2*3*gc^3*m1^2*m/(2*c^4*r^4)) $\n\t\t\tscale nbrac nv + scale (-2 * nv <.> s') s'\n\t\twhere\n\t\t\tnbrac = 5 * (nv <.> s')^2 - 1\n\t\t\tr\t= norm rv\n\t\t\tv\t= norm vv\n\t\t\tnv\t= unitV rv\n\t\t\ts'\t= spinCylToSpher s\n\tgm \t= gc * m\n\tm \t= m1+m2\n\teta \t= m1*m2/m^2\n\n-- Time derivative of spin unit vector, in spherical coordinates\nspinDt :: Double->Double->Double->Double->Double->Double->\n\tVector Double->Vector Double->Vector Double->Vector Double\nspinDt gc c m1 m2 chi q rv vv s = cross omega s \n\twhere\n\tomega = scale (gm*eta/(2*c^2*r^2)*(7+sqrt (1-4*eta))\n\t\t\t\t/(1+sqrt (1-4*eta))) (cross nv vv)\n\tr = norm rv\n\tnv = scale (1/r) rv\n\tgm \t= gc * m\n\tm \t= m1+m2\n\teta \t= m1*m2/m^2\n\n-- Time derivatives of spin unit vector components in cylindrical\n-- coordinates, with x as the axisymmery axis\nspinDtCyl :: Double->Double->Double->Double->Double->Double->\n\tVector Double->Vector Double->[(Double,Double)->Double]\nspinDtCyl gc c m1 m2 chi q rv vv = [dtheta, dxi]\n\twhere\n\tdtheta (th,xi) = \n\t\t-xiPerRho*(dhs@>1*cos th + dhs@>2*sin th) + dhs@>0\n\t\twhere\n\t\txiPerRho = if abs xi >= 1 then 0 else xi/sqrt (1-xi^2)\n\tdxi (th,xi) =\n\t\trho * (dhs@>1*sin th - dhs@>2 * cos th)\n\t\twhere\n\t\trho = if abs xi >= 1 then 0 else sqrt $ 1 - xi^2\n\tr = norm rv\n\tnv = scale (1/r) rv\n\tdhs = omega\n\tomega = scale (gm*eta/(2*c^2*r^2)*(7+sqrt (1-4*eta))\n\t\t\t\t/(1+sqrt (1-4*eta))) (cross nv vv)\n\tgm \t= gc * m\n\tm \t= m1+m2\n\teta \t= m1*m2/m^2\n\n\n-- Convert spin from cylindrical to cartesian representation\n-- Axisymmetry axis is x-axis\nspinCylToSpher :: (Double,Double)->Vector Double\nspinCylToSpher (theta,xi) = --3|>[rho * cos theta, rho*sin theta, xi]\n\t3|>[xi, rho * cos theta, rho*sin theta]\n\twhere rho = if abs xi >= 1 then 0 else sqrt $ 1 - xi^2\n\n-- Post-Newtonian acceleration functions for highest supported degree\nnonSpinPNAcc gc c m1 m2 rv vv = \n\tsum [f rv vv | f <- mkNonSpinPNs gc c m1 m2]\nspinPNAcc gc c m1 m2 chi q rv vv s = \n\tsum [f rv vv s | f <- mkSpinPNs gc c m1 m2 chi q]\n\ntotalPNAcc gc c m1 m2 chi q rv vv s = ((f1 rv vv) + (f2 rv vv s))\n\twhere (f1, f2) = (nonSpinPNAcc gc c m1 m2, \n\t\t\t\tspinPNAcc gc c m1 m2 chi q)\n\n-- Explicitly calculated total acceleration\ntotalPNAccExp gc c m1 m2 chi q rv vv s = \n\ta1 + spinOrbit + quadMono + a2 + a2_5\n\twhere\n\ta1 = {-# SCC \"a1\" #-} \n\t\tscale (-gmperc2 / r^2) $\n\t\t\tscale nbrac nv + scale vbrac vv\n\t\twhere\n\t\t\tnbrac = -2*(2+eta)*gm/r + (1+3*eta)*v^2 - 3/2*eta*rd^2 \n\t\t\tvbrac = -2*(2-eta)*rd\n\n\ta2 = {-# SCC \"a2\" #-} \n\t\tscale (- gmperc2 / (c^2 * r^2)) $\n\t\t\tscale nbrac nv + scale ((-rd/2) * vbrac) vv\n\t\twhere\n\t\t\tnbrac = 3/4*(12+29*eta)*(gm/r)^2 + eta*(3-4*eta)*v^4\n\t\t\t\t+ 15/8*eta*(1-3*eta)*rd^4\n\t\t\t\t- 3/2*eta*(3-4*eta)*v^2*rd^2\n\t\t\t\t- 1/2*eta*(13-4*eta)*(gm/r)*v^2\n\t\t\t\t- (2+25*eta+2*eta^2)*(gm/r)*rd^2\n\t\t\tvbrac = eta*(15+4*eta)*v^2 - (eta+41*eta+8*eta^2)*(gm/r)\n\t\t\t\t- 3*eta*(3+2*eta)*rd^2\n\n\ta2_5 = {-# SCC \"a2_5\" #-} \n\t\tscale (8/15*(gmperc2)^2*eta/(c*r^2)) $\n\t\t\tscale (nbrac*rd) nv + scale (-vbrac) vv\n\t\twhere\n\t\t\tnbrac \t= 9*v^2 + 17*gm/r\n\t\t\tvbrac \t= 3*v^2 + 9*gm/r\n\n\tspinOrbit = {-# SCC \"SO\" #-} \n\t\tscale (gm^2/(r^3*c^3)*(1+sqrt (1-4*eta))/4*chi) $\n\t\t\t\tscale nbrac nv + scale (nsbrac) (cross nv s')\n\t\t\t\t\t+ scale (-vsbrac) (cross vv s')\n\t\twhere\n\t\t\tnbrac = 12 * s' <.> (cross nv vv)\n\t\t\tnsbrac = (9 + 3 * sqrt (1-4*eta))*rd\n\t\t\tvsbrac = 7 + sqrt(1-4*eta)\n\n\tquadMono = {-# SCC \"Q\" #-}\n\t\tscale (-q*chi^2*3*gc^3*m1^2*m/(2*c^4*r^4)) $\n\t\t\tscale nbrac nv + scale (-2 * nv <.> s') s'\n\t\twhere\n\t\t\tnbrac = 5 * (nv <.> s')^2 - 1\n\tr\t= norm rv\n\tv\t= norm vv\n\ts'\t= spinCylToSpher s\n\tnv\t= scale (1/r) rv\n\trd\t= (rv <.> vv)/r\n\tgm \t= gc * m\n\tgmperc2 = gm / c ^2\n\tm \t= m1+m2\n\teta \t= m1*m2/m^2\n", "meta": {"hexsha": "9c0a58c3cd07dad20b09a9c9049506ff3fac59b1", "size": 6359, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "PostNewtonian.hs", "max_stars_repo_name": "sageh/AstroHaskell", "max_stars_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PostNewtonian.hs", "max_issues_repo_name": "sageh/AstroHaskell", "max_issues_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PostNewtonian.hs", "max_forks_repo_name": "sageh/AstroHaskell", "max_forks_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4398148148, "max_line_length": 73, "alphanum_fraction": 0.5854694134, "num_tokens": 2730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5439988142054014}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\nmodule FokkerPlanck.FourierSeries\n ( fourierMellin\n , sampleScale\n -- , computeFourierCoefficients\n , computeHarmonicsArray\n , computeHarmonicsArraySparse\n -- , computeHarmonicsArrayGPU\n , getHarmonics\n , computeThetaRHarmonics\n , computeFourierSeriesThetaR\n -- , computeFourierSeriesR2\n , normalizeFreqArr\n -- , normalizeFreqArr'\n , plotThetaDimension\n , computeFourierSeriesOfLogPolarHarmonicsArray\n , computeRectangularInverseHarmonics\n ) where\n\nimport Array.UnboxedArray as UA\nimport Control.DeepSeq\nimport Data.Array.IArray as IA\nimport Data.Array.Repa as R\nimport Data.Binary\nimport Data.Complex\nimport Data.DList as DL\nimport Data.List as L\nimport Data.Vector.Generic as VG\nimport Data.Vector.Unboxed as VU\nimport FokkerPlanck.BrownianMotion\nimport FokkerPlanck.Histogram\nimport GHC.Generics (Generic)\nimport Text.Printf\nimport Utils.Array\nimport Utils.Parallel\nimport Utils.Time\nimport Graphics.Rendering.Chart.Backend.Cairo\nimport Graphics.Rendering.Chart.Easy\nimport Image.IO\nimport System.FilePath\nimport Utils.SimpsonRule\nimport Numeric.LinearAlgebra as NL\nimport Numeric.LinearAlgebra.Data as NL\nimport Utils.Distribution\nimport Pinwheel.Base\n\n\n\n-- {-# INLINE fourierMellin' #-}\n-- fourierMellin' :: Int -> Int -> (Double, Double) -> Complex Double\n-- fourierMellin' !angularFreq !radialFreq (!x, !y) =\n-- if x == 0 && y == 0\n-- then 0\n-- else exp $ (-1 * log rho) :+ (tf * atan2 y x + rf * (log rho))\n\n{-# INLINE sampleScale #-}\nsampleScale ::\n Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> [Particle]\n -> Complex Double\nsampleScale !phiFreq !rhoFreq !thetaFreq !rFreq !halfLogPeriod =\n L.sum .\n L.map\n (\\(Particle newPhi newRho theta newR _) ->\n if newRho == 0 -- || newR == 0\n then 0\n else (cos (phiFreq * newPhi + thetaFreq * (theta - newPhi)) :+ 0) *\n (cis $\n (-pi) * (rhoFreq * (newRho) + rFreq * (newR - newRho)) /\n halfLogPeriod))\n\n-- {-# INLINE computeFourierCoefficients #-}\n-- computeFourierCoefficients ::\n-- [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> Double\n-- -> Double\n-- -> [DList Particle]\n-- -> Histogram (Complex Double)\n-- computeFourierCoefficients !phiFreqs !rhoFreqs !thetaFreqs !rFreqs !halfLogPeriod !deltaLogRho !xs =\n-- Histogram\n-- [L.length phiFreqs, L.length rhoFreqs, L.length thetaFreqs, L.length rFreqs]\n-- (L.length ys) .\n-- toUnboxedVector .\n-- UA.accum\n-- (+)\n-- 0\n-- ( (1, 1, 1, 1)\n-- , ( L.length rFreqs\n-- , L.length thetaFreqs\n-- , L.length rhoFreqs\n-- , L.length phiFreqs)) .\n-- L.concat .\n-- parMap\n-- rdeepseq\n-- (\\(particle@(Particle phi rho theta r)) ->\n-- let !n = floor $ (log r + halfLogPeriod) / deltaLogRho\n-- !samples =\n-- -- L.map moveParticle $\n-- particle :\n-- [ -- (Particle\n-- -- phi\n-- -- rho\n-- -- theta\n-- -- (exp $ (fromIntegral i * deltaLogRho - halfLogPeriod)))\n-- -- | i <- [0 .. n]\n-- ]\n-- in L.map\n-- (\\((rFreq, i), (thetaFreq, j), (rhoFreq, k), (phiFreq, l)) ->\n-- ( (i, j, k, l)\n-- , -- (deltaLogRho :+ 0) *\n-- 1/ (16 * pi^2 * halfLogPeriod :+ 0) *\n-- sampleScale\n-- phiFreq\n-- rhoFreq\n-- thetaFreq\n-- rFreq\n-- halfLogPeriod\n-- samples))\n-- freqs) $\n-- ys\n-- where\n-- !ys = DL.toList . DL.concat $ xs\n-- !freqs =\n-- [ (rFreq', thetaFreq', rhoFreq', phiFreq')\n-- | rFreq' <- L.zip rFreqs [1 ..]\n-- , thetaFreq' <- L.zip thetaFreqs [1 ..]\n-- , rhoFreq' <- L.zip rhoFreqs [1 ..]\n-- , phiFreq' <- L.zip phiFreqs [1 ..]\n-- ]\n\n\n-- {-# INLINE normalizeFreqArr #-}\n-- normalizeFreqArr ::\n-- Double\n-- -> [Double]\n-- -> [Double]\n-- -> R.Array U DIM4 (Complex Double)\n-- -> R.Array U DIM4 (Complex Double)\n-- normalizeFreqArr !std !phiFreqs !rhoFreqs arr =\n-- computeUnboxedS .\n-- R.traverse3\n-- arr\n-- (fromListUnboxed (Z :. L.length phiFreqs) phiFreqs)\n-- (fromListUnboxed (Z :. L.length rhoFreqs) rhoFreqs)\n-- (\\sh _ _ -> sh) $ \\fArr fPhi fRho idx@(Z :. r :. theta :. rho :. phi) ->\n-- fArr idx *\n-- ((exp $\n-- (-1) *\n-- ((fPhi (Z :. phi)) ^ 2 + (fPhi (Z :. theta)) ^ 2 + (fRho (Z :. rho)) ^ 2 +\n-- (fRho (Z :. r)) ^ 2) /\n-- 2 /\n-- (std ^ 2)) :+\n-- 0)\n\n{-# INLINE normalizeFreqArr #-}\nnormalizeFreqArr ::\n Double\n -> Double\n -> [Double]\n -> [Double]\n -> R.Array U DIM4 (Complex Double)\n -> R.Array U DIM4 (Complex Double)\nnormalizeFreqArr !stdA !stdR !phiFreqs !rhoFreqs arr\n | stdA == 0 && stdR == 0 = arr\n | stdA == 0 =\n computeUnboxedS .\n R.traverse3\n arr\n (fromListUnboxed (Z :. L.length phiFreqs) phiFreqs)\n (fromListUnboxed (Z :. L.length rhoFreqs) rhoFreqs)\n (\\sh _ _ -> sh) $ \\fArr fPhi fRho idx@(Z :. r :. theta :. rho :. phi) ->\n fArr idx *\n (exp $\n ((-1) * ((fRho (Z :. rho)) ^ 2 + (fRho (Z :. r)) ^ 2) / (2 * stdR ^ 2)) :+\n 0)\n | stdR == 0 =\n computeUnboxedS .\n R.traverse3\n arr\n (fromListUnboxed (Z :. L.length phiFreqs) phiFreqs)\n (fromListUnboxed (Z :. L.length rhoFreqs) rhoFreqs)\n (\\sh _ _ -> sh) $ \\fArr fPhi fRho idx@(Z :. _ :. theta :. rho :. phi) ->\n fArr idx *\n ((exp $\n (-1) * ((fPhi (Z :. phi)) ^ 2 + (fPhi (Z :. theta)) ^ 2) /\n (2 * stdA ^ 2)) :+\n 0)\n | otherwise =\n computeUnboxedS .\n R.traverse3\n arr\n (fromListUnboxed (Z :. L.length phiFreqs) phiFreqs)\n (fromListUnboxed (Z :. L.length rhoFreqs) rhoFreqs)\n (\\sh _ _ -> sh) $ \\fArr fPhi fRho idx@(Z :. r :. theta :. rho :. phi) ->\n fArr idx *\n ((exp $\n (-1) * ((fPhi (Z :. phi)) ^ 2 + (fPhi (Z :. theta)) ^ 2) /\n (2 * stdA ^ 2) -\n ((fRho (Z :. rho)) ^ 2 + (fRho (Z :. r)) ^ 2) / (2 * stdR ^ 2)) :+\n 0)\n\n\n-- {-# INLINE computeHarmonicsArray #-}\ncomputeHarmonicsArray ::\n (VG.Vector vector (Complex Double), NFData (vector (Complex Double)))\n => Int\n -> Double\n -> Int\n -> Double\n -> [Double]\n -> [Double]\n -> [Double]\n -> [Double]\n -> Double\n -> Double\n -> IA.Array (Int, Int) (vector (Complex Double))\ncomputeHarmonicsArray !numRows !deltaRow !numCols !deltaCol !phiFreqs !rhoFreqs !thetaFreqs !rFreqs !halfLogPeriod !cutoff =\n let !centerRow = div numRows 2\n !centerCol = div numCols 2\n rangeFunc1 xs ys = [(L.head xs - L.last ys) .. (L.last xs - L.head ys)]\n rangeFunc2 xs ys =\n (round (L.head xs - L.last ys), round (L.last xs - L.head ys))\n (!tfLB, !tfUB) = rangeFunc2 phiFreqs thetaFreqs\n (!rfLB, !rfUB) = rangeFunc2 rhoFreqs rFreqs\n !xs =\n parMap\n rdeepseq\n (\\(!rf, !tf) ->\n let !vec =\n VG.convert .\n toUnboxed . computeS . fromFunction (Z :. numCols :. numRows) $ \\(Z :. c :. r) ->\n let !x = fromIntegral (c - centerCol) * deltaCol\n !y = fromIntegral (r - centerRow) * deltaRow\n !rho = 0 + (sqrt $ x ^ 2 + y ^ 2)\n !rho2 =\n fromIntegral $\n (c - centerCol) ^ 2 + (r - centerRow) ^ 2\n in if rho2 > cutoff ^ 2 || (rho <= 0) -- || pi * rho < (abs tf) -- || log ((rho + 1) / rho) > (1 / (2 * rf))\n then 0\n -- (x :+ y) ** (tf :+ 0) *\n -- ((x ^ 2 + y ^ 2) :+ 0) **\n -- (((-tf - 0.5) :+ rf) / 2)\n else ((rho :+ 0) ** ((-1) :+ rf)) *\n (cis (tf * atan2 y x))\n in ((round rf, round tf), vec))\n [ (rf, tf)\n | rf <- rangeFunc1 rhoFreqs rFreqs\n , tf <- rangeFunc1 phiFreqs thetaFreqs\n ]\n in IA.array ((rfLB, tfLB), (rfUB, tfUB)) xs\n\n\n-- {-# INLINE computeHarmonicsArraySparse #-}\ncomputeHarmonicsArraySparse ::\n Int\n -> Double\n -> Int\n -> Double\n -> [Double]\n -> [Double]\n -> [Double]\n -> [Double]\n -> Double\n -> Double\n -> Double\n -> IA.Array (Int, Int) (R.Array U DIM2 (Complex Double))\ncomputeHarmonicsArraySparse !numRows !deltaRow !numCols !deltaCol !phiFreqs !rhoFreqs !thetaFreqs !rFreqs !halfLogPeriod !cutoff !envelopeSigma =\n let !centerRow = div numRows 2\n !centerCol = div numCols 2\n rangeFunc1 xs ys =\n [(round $ L.head xs - L.last ys) .. (round $ L.last xs - L.head ys)]\n rangeFunc2 xs ys =\n ((round $ (L.head xs - L.last ys)), (round $ (L.last xs - L.head ys)))\n (!tfLB, !tfUB) = rangeFunc2 phiFreqs thetaFreqs\n (!rfLB, !rfUB) = rangeFunc2 rhoFreqs rFreqs\n !xs =\n parMap\n rseq\n (\\(!rf, !tf) ->\n let !arr =\n computeS . fromFunction (Z :. numCols :. numRows) $ \\(Z :. c :. r) ->\n let !x = fromIntegral (c - centerCol) * deltaCol\n !y = fromIntegral (r - centerRow) * deltaRow\n !rho = ((sqrt $ x ^ 2 + y ^ 2))\n !rho2 =\n fromIntegral $\n (c - centerCol) ^ 2 + (r - centerRow) ^ 2\n in if (rho <= 0) || rho2 > cutoff ^ 2\n then 0\n else (x :+ y) ** (fromIntegral tf :+ 0) *\n (((x ^ 2 + y ^ 2) :+ 0) **\n (((-(fromIntegral tf) - envelopeSigma) :+ (2 * pi / halfLogPeriod * fromIntegral rf)) /\n 2))\n in deepSeqArray arr ((rf, tf), arr))\n [ (rf, tf)\n | rf <- rangeFunc1 rhoFreqs rFreqs\n , tf <- rangeFunc1 phiFreqs thetaFreqs\n ]\n in IA.array ((rfLB, tfLB), (rfUB, tfUB)) xs\n\n-- {-# INLINE computeHarmonicsArrayGPU #-}\n-- computeHarmonicsArrayGPU ::\n-- (VG.Vector vector (Complex Double), NFData (vector (Complex Double)))\n-- => Int\n-- -> Double\n-- -> Int\n-- -> Double\n-- -> [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> Double\n-- -> Double\n-- -> IA.Array (Int, Int) (vector (Complex Double))\n-- computeHarmonicsArrayGPU !numRows !deltaRow !numCols !deltaCol !phiFreqs !rhoFreqs !thetaFreqs !rFreqs !halfLogPeriod !cutoff =\n-- let !centerRow = div numRows 2\n-- !centerCol = div numCols 2\n-- rangeFunc1 xs ys =\n-- [round (L.head xs - L.last ys) .. round (L.last xs - L.head ys)]\n-- rangeFunc2 xs ys =\n-- (round (L.head xs - L.last ys), round (L.last xs - L.head ys))\n-- (!tfLB, !tfUB) = rangeFunc2 phiFreqs thetaFreqs\n-- (!rfLB, !rfUB) = rangeFunc2 rhoFreqs rFreqs\n-- !xs =\n-- parMap\n-- rdeepseq\n-- (\\(!rf, !tf) ->\n-- let !vec =\n-- VG.convert .\n-- toUnboxed . computeS . fromFunction (Z :. numCols :. numRows) $ \\(Z :. c :. r) ->\n-- let !x = fromIntegral (c - centerCol) * deltaCol\n-- !y = fromIntegral (r - centerRow) * deltaRow\n-- !r2 = x ^ 2 + y ^ 2\n-- in if (x == 0 && y == 0) || r2 > cutoff ^ 2\n-- then 0\n-- else cis $\n-- fromIntegral tf * atan2 y x +\n-- (pi * (fromIntegral rf * 0.5 * log r2) /\n-- halfLogPeriod - pi)\n-- in ((rf, tf), vec))\n-- [ (rf, tf)\n-- | rf <- (rangeFunc1 rhoFreqs rFreqs)\n-- , tf <- L.reverse (rangeFunc1 phiFreqs thetaFreqs)\n-- ]\n-- in IA.array ((rfLB, tfLB), (rfUB, tfUB)) xs\n\n{-# INLINE getHarmonics #-}\ngetHarmonics ::\n (VG.Vector vector e)\n => IA.Array (Int, Int) (vector e)\n -> Double\n -> Double\n -> Double\n -> Double\n -> vector e\ngetHarmonics harmonicsArray phiFreq rhoFreq thetaFreq rFreq =\n harmonicsArray IA.! (round (rhoFreq - rFreq), round $ (phiFreq - thetaFreq))\n\n\n-- {-# INLINE computeFourierSeriesR2 #-}\n-- computeFourierSeriesR2 ::\n-- Int\n-- -> Double\n-- -> Int\n-- -> Double\n-- -> [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> Double\n-- -> Double\n-- -> IA.Array (Int, Int) (VU.Vector (Complex Double))\n-- -> R.Array U DIM4 (Complex Double)\n-- -> [VU.Vector (Complex Double)]\n-- computeFourierSeriesR2 numRows deltaRow numCols deltaCol phiFreqs rhoFreqs thetaFreqs rFreqs halfLogPeriod cutoff harmonicsArray arr =\n-- let (Z :. (!numRFreq) :. (!numThetaFreq) :. _ :. _) = extent arr\n-- !initVec = VU.replicate (VU.length (harmonicsArray IA.! (0, 0))) 0\n-- in parMap\n-- rdeepseq\n-- (\\((!r, !rFreq), (!theta, !thetaFreq)) ->\n-- L.foldl'\n-- (\\(!vec) ((!rho, !rhoFreq), (!phi, !phiFreq)) ->\n-- VU.zipWith\n-- (+)\n-- vec\n-- (VU.map\n-- (* (arr R.! (Z :. r :. theta :. rho :. phi)))\n-- (getHarmonics harmonicsArray phiFreq rhoFreq thetaFreq rFreq)))\n-- initVec $\n-- (,) <$> (L.zip [0 ..] rhoFreqs) <*> (L.zip [0 ..] phiFreqs)) $\n-- (,) <$> (L.zip [0 ..] rFreqs) <*> (L.zip [0 ..] thetaFreqs)\n\n-- {-# INLINE computeThetaRHarmonics #-}\ncomputeThetaRHarmonics ::\n Int -> Int -> [Double] -> [Double] -> Double -> [[(Complex Double)]]\ncomputeThetaRHarmonics !numOrientation !numScale !thetaFreqs !rFreqs !halfLogPeriod =\n let !deltaTheta = 2 * pi / fromIntegral numOrientation\n !deltaScale = 2 * halfLogPeriod / fromIntegral numScale\n !numRFreq = L.length rFreqs\n !numThetaFreq = L.length thetaFreqs\n in if numScale == 1\n then parMap\n rdeepseq\n (\\o ->\n L.map\n (\\freq -> cis $ freq * (fromIntegral o * deltaTheta))\n thetaFreqs) $\n [0 .. numOrientation - 1]\n else parMap\n rdeepseq\n (\\(!o, !s) ->\n R.toList .\n R.traverse2\n (fromListUnboxed (Z :. numRFreq) rFreqs)\n (fromListUnboxed (Z :. numThetaFreq) thetaFreqs)\n (\\_ _ -> (Z :. numRFreq :. numThetaFreq)) $ \\fRFreq fThetaFreq idx@(Z :. rFreq :. thetaFreq) ->\n -- exp $\n -- (-0.5 * (fromIntegral s * deltaScale - halfLogPeriod)) :+\n -- ((fRFreq (Z :. rFreq)) *\n -- (fromIntegral s * deltaScale - halfLogPeriod) +\n -- fThetaFreq (Z :. thetaFreq) * fromIntegral o * deltaTheta)\n cis\n ((fRFreq (Z :. rFreq)) *\n (pi * (fromIntegral s * deltaScale - halfLogPeriod) /\n halfLogPeriod) +\n fThetaFreq (Z :. thetaFreq) * fromIntegral o * deltaTheta)\n ) $\n (,) <$> [0 .. numOrientation - 1] <*> [0 .. numScale - 1]\n\n\n{-# INLINE computeFourierSeriesThetaR #-}\ncomputeFourierSeriesThetaR ::\n (VG.Vector vector (Complex Double), NFData (vector (Complex Double)))\n => [[(Complex Double)]]\n -> [vector (Complex Double)]\n -> [vector (Complex Double)]\ncomputeFourierSeriesThetaR !harmonics !vecs =\n let !initVec = VG.replicate (VG.length . L.head $ vecs) 0\n in parMap\n rdeepseq\n (L.foldl'\n (\\vec0 (!vec1, !v) -> VG.zipWith (+) vec0 . VG.map (* v) $ vec1)\n initVec .\n L.zip vecs) $\n harmonics\n\nplotThetaDimension ::\n (R.Source s Double)\n => FilePath\n -> String\n -> (Int, Int)\n -> R.Array s DIM3 Double\n -> IO ()\nplotThetaDimension folderPath prefix (x', y') inputArr = do\n let centerCol = div cols 2\n centerRow = div rows 2\n x = x' + centerCol\n y = y' + centerRow\n (Z :. numOrientation :. cols :. rows) = extent inputArr\n centerArr =\n fromFunction (Z :. (1 :: Int) :. cols :. rows) $ \\(Z :. _ :. i :. j) ->\n if i == x && j == y\n then 1 :: Double\n else 0\n plotImageRepa (folderPath printf \"%s(%d,%d)_center.png\" prefix x' y') .\n ImageRepa 8 . computeS $\n centerArr\n let ys' = R.toList . R.slice inputArr $ (Z :. R.All :. x :. y)\n !maxY = L.maximum ys'\n -- ys = L.map (/maxY) ys'\n ys = ys'\n deltaTheta = (360 ::Double) / fromIntegral numOrientation\n xs = [fromIntegral x * deltaTheta | x <- [0 .. numOrientation - 1]]\n toFile def (folderPath printf \"%s(%d,%d)_theta.png\" prefix x' y') $ do\n layout_title .= printf \"%s(%d,%d)\" prefix x' y'\n layout_x_axis . laxis_generate .= scaledAxis def (0, 359)\n layout_y_axis . laxis_generate .= scaledAxis def (0, maxY)\n plot (line \"\" [L.zip xs ys])\n\n\n-- The codes below compute Fourier series in R2\n\ncomputeFourierSeriesOfLogPolarHarmonicsArray ::\n (VG.Vector vector (Complex Double), NFData (vector (Complex Double)))\n => Double\n -> Double\n -> Int\n -> Int\n -> Int\n -> Int\n -> Int\n -> Double\n -> IA.Array (Int, Int) (vector (Complex Double))\ncomputeFourierSeriesOfLogPolarHarmonicsArray !radius !delta !r2Freq !phiFreq !rhoFreq !thetaFreq !rFreq !halfLogPeriod =\n let ((!angularFreqLB, !angularFreqUB), angularFreqs) =\n freqRange phiFreq thetaFreq\n ((!radialFreqLB, !radialFreqUB), radialFreqs) =\n freqRange phiFreq thetaFreq\n !numPoints' = round $ (2 * radius + 1) / delta\n !numPoints =\n if odd numPoints'\n then numPoints'\n else numPoints' - 1\n !center = div numPoints 2\n !period = 2 * radius + 1\n !periodConstant = delta * 2 * pi / period\n !numR2Freq = 2 * r2Freq + 1\n !std = fromIntegral $ div r2Freq 2\n !simpsonWeights =\n toUnboxed . computeS $\n (computeWeightArrFromListOfShape [numPoints, numPoints] :: R.Array D DIM2 (Complex Double))\n !weightedRectangularHarmonics =\n parMap\n rdeepseq\n (\\(freq1, freq2) ->\n VU.zipWith (*) simpsonWeights .\n toUnboxed . computeS . fromFunction (Z :. numPoints :. numPoints) $ \\(Z :. i :. j) ->\n cis\n (-periodConstant *\n fromIntegral (freq1 * (i - center) + freq2 * (j - center))))\n [ (freq1, freq2)\n | freq1 <- [-r2Freq .. r2Freq]\n , freq2 <- [-r2Freq .. r2Freq]\n ]\n !cartesianGrid =\n toUnboxed . computeS . fromFunction (Z :. numPoints :. numPoints) $ \\(Z :. c :. r) ->\n let !x = fromIntegral (c - center) * delta\n !y = fromIntegral (r - center) * delta\n in (x, y)\n !simpsonNorm = (delta / 3) ^ 2 :+ 0\n !xs =\n parMap\n rdeepseq\n (\\(!radialFreq, !angularFreq) ->\n let !logPolarHarmonics =\n VU.map (fourierMellin 0.5 angularFreq radialFreq) cartesianGrid\n coefficients =\n fromListUnboxed (Z :. numR2Freq :. numR2Freq) .\n L.map (VU.sum . VU.zipWith (*) logPolarHarmonics) $\n weightedRectangularHarmonics\n !coefficientsGaussian =\n VG.convert .\n toUnboxed . computeS . R.traverse coefficients id $ \\f idx@(Z :. xFreq :. yFreq) ->\n simpsonNorm * (f idx) *\n (gaussian2D\n (fromIntegral $ xFreq - r2Freq)\n (fromIntegral $ yFreq - r2Freq)\n std :+\n 0)\n in ((radialFreq, angularFreq), coefficientsGaussian))\n [ (radialFreq, angularFreq)\n | radialFreq <- radialFreqs\n , angularFreq <- angularFreqs\n ]\n in IA.array ((radialFreqLB, angularFreqLB), (radialFreqUB, angularFreqUB)) xs\n\ncomputeRectangularInverseHarmonics ::\n (VG.Vector vector (Complex Double), NFData (vector (Complex Double)))\n => Int\n -> Int\n -> Double\n -> Double\n -> Int\n -> [vector (Complex Double)]\ncomputeRectangularInverseHarmonics !numRows !numCols !delta !radius !maxFreq =\n let !period = 2 * radius + 1\n !periodConstant = delta * 2 * pi / period\n !centerRow = div numRows 2\n !centerCol = div numCols 2\n in parMap\n rdeepseq\n (\\(col, row) ->\n VG.fromList\n [ cis\n (periodConstant *\n fromIntegral\n (freq1 * (row - centerRow) + freq2 * (col - centerCol)))\n | freq1 <- [-maxFreq .. maxFreq]\n , freq2 <- [-maxFreq .. maxFreq]\n ])\n [(col, row) | col <- [0 .. numCols - 1], row <- [0 .. numRows - 1]] \n\n-- Utilities\n\n{-# INLINE freqRange #-}\nfreqRange :: Int -> Int -> ((Int, Int), [Int])\nfreqRange n m =\n let !x = n + m\n in ((-x, x), [-x .. x])\n", "meta": {"hexsha": "7e9724ccab1272dd3c34c324486afece1ce22730", "size": 21513, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FokkerPlanck/FourierSeries.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/FourierSeries.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/FourierSeries.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.855, "max_line_length": 145, "alphanum_fraction": 0.4998373077, "num_tokens": 6332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5439687194297554}} {"text": "{-# LANGUAGE GADTs #-}\nmodule Math.IRT.Model.FourPLM\n ( FourPLM (..)\n ) where\n\nimport Numeric.AD (Mode, Scalar, auto)\nimport Numeric.AD.Mode.Forward.Double\nimport qualified Numeric.AD.Mode.Tower as T\n\nimport Statistics.Distribution\n\nimport Math.IRT.Internal.Distribution\nimport Math.IRT.Internal.LogLikelihood\nimport Math.IRT.Model.Generic\n\n\ndata FourPLM = FourPLM { discrimination :: !Double\n , difficulty :: !Double\n , pseudoGuessing :: !Double\n , asymptote :: !Double\n } deriving (Show)\n\ninstance Distribution FourPLM where\n cumulative = cumulative4PL\n\ninstance ContDistr FourPLM where\n density x = diff (cumulative4PL x)\n quantile _ = error \"This shouldn't be needed\"\n\ninstance DensityDeriv FourPLM where\n densityDeriv x = (!! 2) . T.diffs (cumulative4PL x)\n\ninstance GenericModel FourPLM where\n fromRasch b = FourPLM 1.0 b 0.0 1.0\n fromOnePLM b = FourPLM 1.7 b 0.0 1.0\n fromTwoPLM a b = FourPLM a b 0.0 1.0\n fromThreePLM a b c = FourPLM a b c 1.0\n fromFourPLM = FourPLM\n\ninstance LogLikelihood FourPLM where\n logLikelihood = logLikeFunc cumulative4PL\n\n\ncumulative4PL :: (Mode a, Floating a, Scalar a ~ Double) =>\n FourPLM -- ^The IRT parameters\n -> a -- ^Theta\n -> a\ncumulative4PL params theta =\n let (a, b, c, d) = makeParamAutos params in\n c + ( (d - c)\n -----------------------------------\n / (1 + exp ((-a) * (theta - b))))\n where makeParamAutos (FourPLM sa sb sc sd) =\n let a = auto sa\n b = auto sb\n c = auto sc\n d = auto sd\n in (a, b, c, d)\n", "meta": {"hexsha": "21a846fcb4e327ab4e3251a7a8c8faeea2e75d6b", "size": 1750, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/IRT/Model/FourPLM.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/FourPLM.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/FourPLM.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": 29.6610169492, "max_line_length": 59, "alphanum_fraction": 0.5754285714, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915994285379, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5437420935675357}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Utils where\nimport Control.Monad.Fix\nimport Control.Monad\nimport System.IO\nimport Signal\nimport Circuit\nimport AmpOp\n ( SignalState(SignalTwoNodes),\n AmpOp(openLoopGain),\n Impedance,\n Output,\n Input,\n dc100,\n sen,\n ground,\n lm741,\n r1,\n r2,\n eps )\nimport Data.List\nimport Data.Complex\nimport Simulation\n\ntype Iteration = Int\n\nmakePlotIterations = do\n outh <- openFile \"outputIterations.txt\" WriteMode\n mapM_ (\\(i, o) -> hPutStrLn outh (show i ++ \" \" ++ show o)) (ampOpInvertingList' lm741 12 r1 r2)\n hClose outh\n\nampOpInvertingList' :: AmpOp -> Input -> Impedance -> Impedance -> [(Iteration, Output)]\nampOpInvertingList' model input r1 r2 = fix calculate (100, 0, [], 1)\n where calculate f (vXOld, vOutOld, l, it) = if abs(realPart vOutOld - realPart vOut) <= 0.000001 && abs(realPart vXOld - realPart vX) <= 0.000001 then l ++ [(it, vOut)] else f (vOut, vX, l ++ [(it, vOut)], it + 1)\n where vX = (- vOutOld) / openLoopGain model `at` 0\n vOut = (vXOld * (r1 + r2) `at` 0 - input * r2 `at` 0) / r1 `at` 0\n\ncheckDataIterations :: IO ()\ncheckDataIterations = print (ampOpInvertingList' lm741 12 r1 r2)\n\n\nampOpInvertingList :: AmpOp -> Impedance -> Impedance -> SignalState -> Circuit Input [(Iteration, SignalState)]\nampOpInvertingList model r1 r2 (SignalTwoNodes (vXInit, vOutInit)) =\n ($ (vXInit, vOutInit, [], 1))<$> mfix\n (\\f -> Circuit $ \\vIn -> Signal $ \\time (vXOld, vOutOld, l, it) ->\n let vX = (- vOutOld) / openLoopGain model\n vOut = ((vXOld * (r1 + r2)) - (vIn * r2)) / r1\n in if abs((realPart <$> vOutOld) - (realPart <$> vOut)) <= eps && abs((realPart <$> vXOld) - (realPart <$> vX)) <= eps\n then l ++ [(it, SignalTwoNodes (vX, vOut))]\n else f (vX, vOut, l ++ [(it, SignalTwoNodes (vX, vOut))], it + 1))\n\nmakeSamplesInput :: Signal Input -> [Metric] -> [(Metric, Input)]\nmakeSamplesInput input samples = do time <- samples\n let result = input `at` time\n return (time, result)\n\nmakeSamplesOutput :: SignalState -> (SignalState -> Circuit Input [(Iteration, SignalState)]) -> Signal Input -> [Metric] -> [[(Metric, Iteration, Output)]]\nmakeSamplesOutput _ _ _ [] = []\nmakeSamplesOutput initialState circuit input (t:ts) = map (\\(i, SignalTwoNodes (_, o)) -> (t, i, o `at` t)) results : rest\n where results = circuit initialState `simulate` input `at` t\n rest = makeSamplesOutput (snd $ last results) circuit input ts\n\nampOpInvertingList2 :: AmpOp -> Impedance -> Impedance -> Circuit Input [(Iteration, Output)]\nampOpInvertingList2 model r1 r2 =\n ($ (dc100, ground, [], 1))<$> mfix\n (\\f -> Circuit $ \\vIn -> Signal $ \\time (vXOld, vOutOld, l, it) ->\n let vX = (- vOutOld) / openLoopGain model\n vOut = ((vXOld * (r1 + r2)) - (vIn * r2)) / r1\n in if abs((realPart <$> vOutOld) - (realPart <$> vOut)) <= eps && abs((realPart <$> vXOld) - (realPart <$> vX)) <= eps\n then l ++ [(it, vOut `at` time)]\n else f (vX, vOut, l ++ [(it, vOut `at` time)], it + 1))\n\nmakeSamplesOutput2 :: Signal Input -> [Metric] -> [[(Metric, Iteration, Output)]]\nmakeSamplesOutput2 input samples = do time <- samples\n let results = (ampOpInvertingList2 lm741 r1 r2 `simulate` input) `at` time\n mapM (\\(i, o) -> [(time, i, o)]) results\n\ntestCircuit = ampOpInvertingList lm741 r1 r2\n\nmakePlotMetricOutput = do\n outh <- openFile \"outputMetric.txt\" WriteMode\n mapM_ (\\(t, i, o) -> hPutStrLn outh (show t ++ \" \" ++ show i ++ \" \" ++ show o)) (concat $ makeSamplesOutput iSignalState testCircuit sen (map (:+ 0) [0.1,0.2..10.0]))\n hClose outh\n\nmakePlotMetricInput = do\n outh <- openFile \"inputMetric.txt\" WriteMode\n mapM_ (\\(t, o) -> hPutStrLn outh (show t ++ \" \" ++ show o)) (makeSamplesInput sen (map (:+ 0) [0.1,0.2..10.0]))\n hClose outh \n", "meta": {"hexsha": "a58c370026317bddb13baf6b7f2a4d79f354686d", "size": 4106, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Utils.hs", "max_stars_repo_name": "FP-Modeling/fixingAnalog", "max_stars_repo_head_hexsha": "d86d80210d3c759f6e4041eb1f3b5b75c4589880", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils.hs", "max_issues_repo_name": "FP-Modeling/fixingAnalog", "max_issues_repo_head_hexsha": "d86d80210d3c759f6e4041eb1f3b5b75c4589880", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils.hs", "max_forks_repo_name": "FP-Modeling/fixingAnalog", "max_forks_repo_head_hexsha": "d86d80210d3c759f6e4041eb1f3b5b75c4589880", "max_forks_repo_licenses": ["BSD-3-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.1208791209, "max_line_length": 217, "alphanum_fraction": 0.5913297613, "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.54365841301238}} {"text": "{-# LANGUAGE TemplateHaskell #-}\n\nmodule Shapes where\n\nimport Control.Lens hiding (element)\nimport Graphics.Gloss.Data.Picture\nimport Data.Complex\n\ndata ShapeType = Kite | Dart deriving (Show)\n\ndata Shape = Shape {_shape :: ShapeType\n ,_translate :: Complex Double\n ,_rotate :: Complex Double\n} deriving (Show)\n\nnewtype Vertices = Vertices {_nodes :: [Complex Double]} deriving (Show)\n\nmakeLenses ''Shape\nmakeLenses ''Vertices\n\nstandardKite :: Shape\nstandardKite = Shape {_shape = Kite, _translate = 0, _rotate = 1}\n\nstandardDart :: Shape\nstandardDart = Shape {_shape = Dart, _translate = 0, _rotate = 1}\n\nz :: Complex Double\nz = cis (pi/5)\n\nzPower :: Int -> Complex Double\nzPower n = cis((pi/5) * fromIntegral (n `mod` 10))\n\nlongEdge :: Vertices\nlongEdge = Vertices {_nodes = [0,(0.5 :+ (-0.1))*z,z]}\n\nshortEdge :: Vertices\nshortEdge = Vertices {_nodes = [0,(0.5 :+ 0.1)*(1-z),1-z]}\n\nrotranslate :: Complex Double -> Complex Double -> Vertices -> Vertices\nrotranslate z w = over nodes (map (\\u -> u*z+w))\n\nreverseVertices :: Vertices -> Vertices\nreverseVertices = over nodes reverse\n\nconcatVertices :: [Vertices] -> Vertices\nconcatVertices p = Vertices {_nodes = concatMap (tail._nodes) p}\n\nshapeToVertices :: Shape -> Vertices\nshapeToVertices (Shape Kite z x) = rotranslate x z kiteVertices\nshapeToVertices (Shape Dart z x) = rotranslate x z dartVertices\n\ncomplexToPoint :: Complex Double -> Point\ncomplexToPoint z = (realToFrac x, realToFrac y)\n where\n x = realPart z\n y = imagPart z\n\nverticesToPicture :: Vertices -> Picture\nverticesToPicture = lineLoop . map complexToPoint . view nodes\n\nshapeToPicture :: Shape -> Picture\nshapeToPicture = verticesToPicture . shapeToVertices\n\nrefine :: Shape -> [Shape]\nrefine s@(Shape t w z) = \n let phi = (sqrt 5 - 1)/2 :+ 0\n tr t' u v = Shape t' (z*phi*v+w) (z*u*phi)\n in case t of\n Kite -> [tr Dart 1 0\n ,tr Kite (zPower 3) (1 - zPower 3)\n ,tr Kite (zPower 7) (1 + zPower 2)\n ]\n Dart -> [tr Kite (zPower 9) 0\n ,tr Dart (zPower 6) (1+phi)\n ]\n\ntilings :: [[Shape]]\ntilings = [standardKite] : map (concatMap refine) tilings\n\ntilingPics :: [Picture]\ntilingPics = map (pictures . map shapeToPicture) tilings\n\nkiteVertices :: Vertices\nkiteVertices = concatVertices\n [longEdge\n ,rotranslate 1 z shortEdge\n ,reverseVertices $ rotranslate (zPower 4) (zPower 9) shortEdge\n ,reverseVertices $ rotranslate (zPower 8) 0 longEdge\n ]\n\ndartVertices :: Vertices\ndartVertices = concatVertices\n [reverseVertices $ rotranslate (zPower 4) 1 longEdge\n ,reverseVertices $ rotranslate (zPower 3) x shortEdge\n ,rotranslate (zPower 9) x shortEdge\n ,rotranslate (zPower 2) (zPower 8) longEdge\n ]\n where\n x = (1 + (zPower 4) - (zPower 3))\n\nprintVertices :: Vertices -> IO ()\nprintVertices = mapM_ print . _nodes\n", "meta": {"hexsha": "dee7ac180d7676f7797b0a5d34aec1a3db318ac0", "size": 2838, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Shapes.hs", "max_stars_repo_name": "bnarnold/Penrose", "max_stars_repo_head_hexsha": "84b668496618740798606fb3aef9b0dd7d0f61b4", "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/Shapes.hs", "max_issues_repo_name": "bnarnold/Penrose", "max_issues_repo_head_hexsha": "84b668496618740798606fb3aef9b0dd7d0f61b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Shapes.hs", "max_forks_repo_name": "bnarnold/Penrose", "max_forks_repo_head_hexsha": "84b668496618740798606fb3aef9b0dd7d0f61b4", "max_forks_repo_licenses": ["BSD-3-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.5533980583, "max_line_length": 72, "alphanum_fraction": 0.6807610994, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5435303595431445}} {"text": "\n\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule HLearn.Models.Distributions.Multivariate.MultiNormal\n ( MultiNormal (..)\n )\n where\n\n-- import qualified Control.ConstraintKinds as CK\nimport qualified Data.Foldable as F\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Unboxed as VU\nimport Data.Vector.Unboxed.Deriving\n\nimport Control.DeepSeq\nimport GHC.ST\nimport GHC.TypeLits\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 \ndata MultiNormalVec (n::Nat) prob = MultiNormalVec\n { q0 :: !prob\n , q1 :: !(VU.Vector prob)\n , q2 :: !(V.Vector (VU.Vector prob))\n }\n deriving (Read,Show,Eq,Ord)\n\ninstance NFData (MultiNormalVec n prob) where\n rnf mn = seq mn ()\n\nnewtype MultiNormal prob (xs::[*]) = MultiNormal (MultiNormalVec (Length xs) prob)\n deriving (Read,Show,Eq,Ord,NFData)\n\nderiving instance (Monoid (MultiNormalVec (Length xs) prob)) => Monoid (MultiNormal prob xs)\nderiving instance (Abelian (MultiNormalVec (Length xs) prob)) => Abelian (MultiNormal prob xs)\nderiving instance (Group (MultiNormalVec (Length xs) prob)) => Group (MultiNormal prob xs)\nderiving instance (Module (MultiNormalVec (Length xs) prob)) => Module (MultiNormal prob xs)\n\n-------------------------------------------------------------------------------\n-- algebra\n\ninstance (Num prob, VU.Unbox prob, SingI n) => Abelian (MultiNormalVec n prob)\ninstance (Num prob, VU.Unbox prob, SingI n) => Monoid (MultiNormalVec n prob) where\n mempty = MultiNormalVec\n { q0 = 0\n , q1 = VU.replicate n 0\n , q2 = V.replicate n (VU.replicate n 0)\n }\n where\n n = fromIntegral $ fromSing (sing :: Sing n)\n mn1 `mappend` mn2 = MultiNormalVec\n { q0 = (q0 mn1) + (q0 mn2)\n , q1 = VU.zipWith (+) (q1 mn1) (q1 mn2)\n , q2 = V.zipWith (VU.zipWith (+)) (q2 mn1) (q2 mn2)\n }\n\ninstance (Num prob, VU.Unbox prob, SingI n) => Group (MultiNormalVec n prob) where\n inverse mn = MultiNormalVec\n { q0 = negate $ q0 mn\n , q1 = VU.map negate (q1 mn)\n , q2 = V.map (VU.map negate) (q2 mn)\n }\n \ninstance (Num prob) => HasRing (MultiNormalVec n prob) where\n type Ring (MultiNormalVec n prob) = prob\n\ninstance (Num prob, VU.Unbox prob, SingI n) => Module (MultiNormalVec n prob) where\n r .* mn = MultiNormalVec\n { q0 = r * q0 mn\n , q1 = VU.map (r*) (q1 mn)\n , q2 = V.map (VU.map (r*)) (q2 mn)\n }\n \n---------------------------------------\n\ninstance (Num prob) => HasRing (MultiNormal prob xs) where\n type Ring (MultiNormal prob xs) = prob\n \n-------------------------------------------------------------------------------\n-- training\n\ninstance (SingI n, Num prob, VU.Unbox prob) => HomTrainer (MultiNormalVec n prob) where\n type Datapoint (MultiNormalVec n prob) = (VU.Vector prob) \n train1dp dp = MultiNormalVec\n { q0 = 1\n , q1 = dp\n , q2 = V.generate n (\\i -> VU.generate n (\\j -> (dp VU.! i)*(dp VU.! j)))\n }\n where\n n = fromIntegral $ fromSing (sing :: Sing n)\n\ninstance \n ( SingI (Length xs)\n , Num prob\n , VU.Unbox prob\n , HList2List (Datapoint (MultiNormal prob xs)) prob\n ) => HomTrainer (MultiNormal prob xs) \n where\n type Datapoint (MultiNormal prob xs) = HList xs\n train1dp dp = MultiNormal $ train1dp $ VU.fromList $ hlist2list dp\n\ninstance (Num prob) => NumDP (MultiNormal prob xs) where\n numdp (MultiNormal mn) = q0 mn\n\n-------------------------------------------------------------------------------\n-- distribution\n\nclass (Probabilistic dist) => Covariance dist where\n covar :: dist -> Matrix (Probability dist)\n\ninstance \n ( VU.Unbox prob\n , SingI k\n , Num prob\n ) => Probabilistic (MultiNormalVec k prob) \n where\n type Probability (MultiNormalVec k prob) = prob\n\ninstance \n ( VU.Unbox prob\n , SingI k\n , Fractional prob\n , Enum prob\n , Storable prob\n ) => Covariance (MultiNormalVec k prob) \n where\n covar mn = (k> Probabilistic (MultiNormal prob dpL) \n where\n type Probability (MultiNormal prob dpL) = prob\n\ninstance\n ( HList2List (HList dpL) prob\n , VU.Unbox prob\n , Floating prob\n , Field prob\n , Enum prob\n , SingI (FromNat1 (Length1 dpL))\n-- , Covariance (MultiNormal dpL prob)\n , Storable prob\n ) => PDF (MultiNormal prob dpL) \n where\n pdf (MultiNormal dist) dpL = 1/(sqrt $ (2*pi)^(k)*(det sigma))*(exp $ (-1/2)*(top) )\n where\n top=minElement $ ((trans $ x `sub` mu) LA.<> (inv sigma) LA.<> (x `sub` mu))\n \n k = fromIntegral $ fromSing (sing :: Sing (Length dpL)) :: Int\n x = k><1 $ hlist2list dpL\n n = q0 dist\n sigma = covar dist\n mu = k><1 $ map (/n) $ VU.toList (q1 $ dist)\n-- covarM = (k> Vect C (QBasis n)\n\nrunCircuit :: KnownNat n => QCirc n -> QReg n\nrunCircuit = ($ unit)\n\ntensor :: QReg m -> QReg n -> QReg (m + n)\ntensor vec1 vec2 = vec1 `te` vec2\n\n(⊗) :: KnownNat m => QCirc m -> QCirc n -> QCirc (m + n)\nc1 ⊗ c2 = c1 `tf` c2\n\nunit :: KnownNat n => QReg n\nunit = V [(unit', 1)]\n\nidGate :: QCirc n\nidGate = id\n\nnotGate :: QCirc 1\nnotGate = linear n\n where n :: QBasis 1 -> QReg 1\n n (Cons False Nil) = V [(Cons True Nil, 1)]\n n (Cons True Nil) = V [(Cons False Nil, 1)]\n\nhGate :: QCirc 1\nhGate = linear h\n where h :: QBasis 1 -> QReg 1\n h (Cons False Nil) = V [(Cons False Nil, 1 / sqrt 2)\n ,(Cons True Nil, 1 / sqrt 2)]\n h (Cons True Nil) = V [(Cons False Nil, 1 / sqrt 2)\n ,(Cons True Nil, -1 / sqrt 2)]\n\nrotGate :: Double -> QCirc 1\nrotGate t = linear r\n where r :: QBasis 1 -> QReg 1\n r (Cons False Nil) = V [(Cons False Nil, 1)]\n r (Cons True Nil) = V [(Cons True Nil, cis t)]\n\ncnotGate :: QCirc 2\ncnotGate = linear n\n where n :: QBasis 2 -> QReg 2\n n (Cons False (Cons False Nil)) = V [(Cons False (Cons False Nil), 1)]\n n (Cons False (Cons True Nil)) = V [(Cons False (Cons True Nil), 1)]\n n (Cons True (Cons False Nil)) = V [(Cons True (Cons True Nil), 1)]\n n (Cons True (Cons True Nil)) = V [(Cons True (Cons False Nil), 1)]\n\nswapGate :: QCirc 2\nswapGate = linear s\n where s :: QBasis 2 -> QReg 2\n s (Cons False (Cons False Nil)) = V [(Cons False (Cons False Nil), 1)]\n s (Cons False (Cons True Nil)) = V [(Cons True (Cons False Nil), 1)]\n s (Cons True (Cons False Nil)) = V [(Cons False (Cons True Nil), 1)]\n s (Cons True (Cons True Nil)) = V [(Cons True (Cons True Nil), 1)]", "meta": {"hexsha": "6cd345bf409fcb38fb7f1c5ae65a0f9a558b9a51", "size": 2085, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Aqua.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/Aqua.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/Aqua.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": 30.6617647059, "max_line_length": 80, "alphanum_fraction": 0.5491606715, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5429654671581736}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Blash where\n\nimport qualified Data.Vector.Generic as V\nimport Data.Vector.Generic ((!))\nimport Data.Complex\nimport BlashImpl (fZERO, stride, isample, map_reduce, Size, Inc, Index, copyM, axpyM)\n\n\ncopy :: (V.Vector v a)\n => Size\n -> v a\n -> Inc\n -> v a\n -> Inc\n -> v a\ncopy n dx incx dy incy = V.modify modifier dy\n where\n modifier ys = copyM n dx incx ys incy\n\n\naxpy :: (Ord a, Num a, V.Vector v a)\n => Size\n -> a\n -> v a\n -> Inc\n -> v a\n -> Inc\n -> v a\naxpy n da dx incx dy incy = V.modify modifier dy\n where\n modifier ys = axpyM n da dx incx ys incy\n\n-- /* dot product dx dot dy. */\ndot :: (Num a, V.Vector v a)\n => Size\n -> v a\n -> Inc\n -> v a\n -> Inc\n -> a\ndot n _ _ _ _ | n <= 0 = fZERO\ndot n dx incx dy incy = sum prods\n where\n prods = flip map [0..(n-1)] f\n f i = (dx ! ix i) * (dy ! iy i)\n ix = stride n incx\n iy = stride n incy\n\n-- /* dot product dx dot dy where dx & dy are complex. */\ndotc :: (RealFloat a, V.Vector v (Complex a))\n => Size\n -> v (Complex a)\n -> Inc\n -> v (Complex a)\n -> Inc\n -> Complex a\ndotc n _ _ _ _ | n <= 0 = fZERO :+ fZERO\ndotc n dx incx dy incy = sum prods\n where\n prods = flip map [0..(n-1)] f\n f i = (conjugate (dx ! ix i)) * (dy ! iy i)\n ix = stride n incx\n iy = stride n incy\n \n\n-- /* compute the L2 norm of array DX of length N, stride INCX */\n-- TODO should really be (Num a) - or split between Complex and Real\nnrm2 :: (Ord a, Floating a, V.Vector v a)\n => Size\n -> v a\n -> Inc\n -> a\nnrm2 n _ incx | n <= 0 || incx <= 0 = fZERO\nnrm2 n dx _ | n == 1 = abs $ dx ! 0\nnrm2 n dx incx =\n let dx' = isample n dx incx\n xmax = V.maximum $ V.map abs dx'\n in \n case xmax == fZERO of\n True -> fZERO\n False ->\n let scale = 1.0 / xmax\n scaled_dx' = V.map (* scale) dx'\n n' = V.length scaled_dx'\n scaled_drnm2 = sqrt $ dot n' scaled_dx' 1 scaled_dx' 1\n in\n xmax * scaled_drnm2\n\n-- DASUM takes the sum of the absolute values.\nasum :: (Num a, V.Vector v a)\n => Size\n -> v a\n -> Inc\n -> a\nasum = map_reduce abs V.sum \n\n-- DAMAX takes the max of the absolute values.\niamax :: (Ord a, Num a, V.Vector v a)\n => Size\n -> v a\n -> Inc\n -> Index\niamax = map_reduce abs V.maxIndex\n", "meta": {"hexsha": "3d63029147daf5606b1d1dc2f32c1bf9766a19a5", "size": 2523, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Blash.hs", "max_stars_repo_name": "wyn/blash", "max_stars_repo_head_hexsha": "890cd5ec8d42ccf8e8aa2619cd16417414c480d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-01-03T09:20:41.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-03T09:20:41.000Z", "max_issues_repo_path": "src/Blash.hs", "max_issues_repo_name": "wyn/blash", "max_issues_repo_head_hexsha": "890cd5ec8d42ccf8e8aa2619cd16417414c480d0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-12-16T19:43:16.000Z", "max_issues_repo_issues_event_max_datetime": "2015-12-18T19:21:37.000Z", "max_forks_repo_path": "src/Blash.hs", "max_forks_repo_name": "wyn/blash", "max_forks_repo_head_hexsha": "890cd5ec8d42ccf8e8aa2619cd16417414c480d0", "max_forks_repo_licenses": ["BSD-3-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.8018867925, "max_line_length": 85, "alphanum_fraction": 0.5101070155, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5428425523988331}} {"text": "{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\n-- |\n-- Module : Statistics.Sample.Histogram\n-- Copyright : (c) 2011 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Functions for computing histograms of sample data.\n\nmodule Statistics.Sample.Histogram\n (\n histogram\n -- * Building blocks\n , histogram_\n , range\n ) where\n\nimport Numeric.MathFunctions.Constants (m_epsilon,m_tiny)\nimport Statistics.Function (minMax)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Generic.Mutable as GM\n\n-- | /O(n)/ Compute a histogram over a data set.\n--\n-- The result consists of a pair of vectors:\n--\n-- * The lower bound of each interval.\n--\n-- * The number of samples within the interval.\n--\n-- Interval (bin) sizes are uniform, and the upper and lower bounds\n-- are chosen automatically using the 'range' function. To specify\n-- these parameters directly, use the 'histogram_' function.\nhistogram :: (G.Vector v0 Double, G.Vector v1 Double, Num b, G.Vector v1 b) =>\n Int -- ^ Number of bins (must be positive).\n -> v0 Double -- ^ Sample data (cannot be empty).\n -> (v1 Double, v1 b)\nhistogram numBins xs = (G.generate numBins step, histogram_ numBins lo hi xs)\n where (lo,hi) = range numBins xs\n step i = lo + d * fromIntegral i\n d = (hi - lo) / fromIntegral numBins\n{-# INLINE histogram #-}\n\n-- | /O(n)/ Compute a histogram over a data set.\n--\n-- Interval (bin) sizes are uniform, based on the supplied upper\n-- and lower bounds.\nhistogram_ :: (Num b, RealFrac a, G.Vector v0 a, G.Vector v1 b) =>\n Int\n -- ^ Number of bins. This value must be positive. A zero\n -- or negative value will cause an error.\n -> a\n -- ^ Lower bound on interval range. Sample data less than\n -- this will cause an error.\n -> a\n -- ^ Upper bound on interval range. This value must not be\n -- less than the lower bound. Sample data that falls above\n -- the upper bound will cause an error.\n -> v0 a\n -- ^ Sample data.\n -> v1 b\nhistogram_ numBins lo hi xs0 = G.create (GM.replicate numBins 0 >>= bin xs0)\n where\n bin xs bins = go 0\n where\n go i | i >= len = return bins\n | otherwise = do\n let x = xs `G.unsafeIndex` i\n b = truncate $ (x - lo) / d\n write' bins b . (+1) =<< GM.read bins b\n go (i+1)\n write' bins' b !e = GM.write bins' b e\n len = G.length xs\n d = ((hi - lo) / fromIntegral numBins) * (1 + realToFrac m_epsilon)\n{-# INLINE histogram_ #-}\n\n-- | /O(n)/ Compute decent defaults for the lower and upper bounds of\n-- a histogram, based on the desired number of bins and the range of\n-- the sample data.\n--\n-- The upper and lower bounds used are @(lo-d, hi+d)@, where\n--\n-- @d = (maximum sample - minimum sample) / ((bins - 1) * 2)@\n--\n-- If all elements in the sample are the same and equal to @x@ range\n-- is set to @(x - |x|/10, x + |x|/10)@. And if @x@ is equal to 0 range\n-- is set to @(-1,1)@. This is needed to avoid creating histogram with\n-- zero bin size.\nrange :: (G.Vector v Double) =>\n Int -- ^ Number of bins (must be positive).\n -> v Double -- ^ Sample data (cannot be empty).\n -> (Double, Double)\nrange numBins xs\n | numBins < 1 = error \"Statistics.Histogram.range: invalid bin count\"\n | G.null xs = error \"Statistics.Histogram.range: empty sample\"\n | lo == hi = case abs lo / 10 of\n a | a < m_tiny -> (-1,1)\n | otherwise -> (lo - a, lo + a)\n | otherwise = (lo-d, hi+d)\n where\n d | numBins == 1 = 0\n | otherwise = (hi - lo) / ((fromIntegral numBins - 1) * 2)\n (lo,hi) = minMax xs\n{-# INLINE range #-}\n", "meta": {"hexsha": "7a6414c3fb813d73272bb609bdea660cf14ff09f", "size": 3973, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Sample/Histogram.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/Sample/Histogram.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/Sample/Histogram.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": 36.4495412844, "max_line_length": 78, "alphanum_fraction": 0.5854517996, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5427061380360236}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Copyright : (c) Edward Kmett 2010-2014\n-- License : BSD3\n-- Maintainer : ekmett@gmail.com\n-- Stability : experimental\n-- Portability : GHC only\n--\n-- Root finding using Halley's rational method (the second in\n-- the class of Householder methods). Assumes the function is three\n-- times continuously differentiable and converges cubically when\n-- progress can be made.\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.AD.Rank1.Halley\n (\n -- * Halley's Method (Tower AD)\n findZero\n , inverse\n , fixedPoint\n , extremum\n ) where\n\nimport Prelude hiding (all)\nimport Numeric.AD.Internal.Forward (Forward)\nimport Numeric.AD.Internal.On\nimport Numeric.AD.Internal.Tower (Tower)\nimport Numeric.AD.Mode\nimport Numeric.AD.Rank1.Tower (diffs0)\nimport Numeric.AD.Rank1.Forward (diff)\n\n-- $setup\n-- >>> import Data.Complex\n\n-- | The 'findZero' function finds a zero of a scalar function using\n-- Halley's method; its output is a stream of increasingly accurate\n-- results. (Modulo the usual caveats.) If the stream becomes constant\n-- (\"it converges\"), no further elements are returned.\n--\n-- Examples:\n--\n-- >>> take 10 $ findZero (\\x->x^2-4) 1\n-- [1.0,1.8571428571428572,1.9997967892704736,1.9999999999994755,2.0]\n--\n-- >>> last $ take 10 $ findZero ((+1).(^2)) (1 :+ 1)\n-- 0.0 :+ 1.0\nfindZero :: (Fractional a, Eq a) => (Tower a -> Tower a) -> a -> [a]\nfindZero f = go where\n go x = x : if x == xn then [] else go xn where\n (y:y':y'':_) = diffs0 f x\n xn = x - 2*y*y'/(2*y'*y'-y*y'')\n{-# INLINE findZero #-}\n\n-- | The 'inverse' function inverts a scalar function using\n-- Halley's method; its output is a stream of increasingly accurate\n-- results. (Modulo the usual caveats.) If the stream becomes constant\n-- (\"it converges\"), no further elements are returned.\n--\n-- Note: the @take 10 $ inverse sqrt 1 (sqrt 10)@ example that works for Newton's method\n-- fails with Halley's method because the preconditions do not hold!\ninverse :: (Fractional a, Eq a) => (Tower a -> Tower a) -> a -> a -> [a]\ninverse f x0 y = findZero (\\x -> f x - auto y) x0\n{-# INLINE inverse #-}\n\n-- | The 'fixedPoint' function find a fixedpoint of a scalar\n-- function using Halley's method; its output is a stream of\n-- increasingly accurate results. (Modulo the usual caveats.)\n--\n-- If the stream becomes constant (\"it converges\"), no further\n-- elements are returned.\n--\n-- >>> last $ take 10 $ fixedPoint cos 1\n-- 0.7390851332151607\nfixedPoint :: (Fractional a, Eq a) => (Tower a -> Tower a) -> a -> [a]\nfixedPoint f = findZero (\\x -> f x - x)\n{-# INLINE fixedPoint #-}\n\n\n-- | The 'extremum' function finds an extremum of a scalar\n-- function using Halley's method; produces a stream of increasingly\n-- accurate results. (Modulo the usual caveats.) If the stream becomes\n-- constant (\"it converges\"), no further elements are returned.\n--\n-- >>> take 10 $ extremum cos 1\n-- [1.0,0.29616942658570555,4.59979519460002e-3,1.6220740159042513e-8,0.0]\nextremum :: (Fractional a, Eq a) => (On (Forward (Tower a)) -> On (Forward (Tower a))) -> a -> [a]\nextremum f = findZero (diff (off . f . On))\n{-# INLINE extremum #-}\n", "meta": {"hexsha": "dd6bc8f0a55f2a127cdec3563c16ecc48319ded0", "size": 3249, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/AD/Rank1/Halley.hs", "max_stars_repo_name": "silky/ad", "max_stars_repo_head_hexsha": "ea7eaafaf9f287eee3ac809d4c300af10282af5f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T11:33:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T11:33:31.000Z", "max_issues_repo_path": "src/Numeric/AD/Rank1/Halley.hs", "max_issues_repo_name": "silky/ad", "max_issues_repo_head_hexsha": "ea7eaafaf9f287eee3ac809d4c300af10282af5f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/AD/Rank1/Halley.hs", "max_forks_repo_name": "silky/ad", "max_forks_repo_head_hexsha": "ea7eaafaf9f287eee3ac809d4c300af10282af5f", "max_forks_repo_licenses": ["BSD-3-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.1, "max_line_length": 98, "alphanum_fraction": 0.6398891967, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5424643056833156}} {"text": "{-# LANGUAGE OverloadedLists #-}\n\nmodule Main where\n\nimport Numeric.GSL.ODE\nimport Numeric.LinearAlgebra\n\n-- Differential equation\nf :: Double -> [Double] -> [Double]\nf t [x, v] = [v, - x + mu * v * (1 - x ^ 2)]\n\n-- Mu scalar, dampening strenth\nmu :: Double\nmu = 0.1\n\n-- Boundary conditions\nts :: Vector Double\nts = linspace 1000 (0, 50)\n\n-- Use default solver: Embedded Runge-Kutta-Fehlberg (4, 5) method.\nvanderpol1 :: [Vector Double]\nvanderpol1 = toColumns $ odeSolve f [1, 0] ts\n\n-- Use Runge-Kutta (2,3) solver\nvanderpol2 :: [Vector Double]\nvanderpol2 = toColumns $ odeSolveV RK2 hi epsAbs epsRel (l2v f) [1, 0] ts\n where\n epsAbs = 1.49012e-08\n epsRel = epsAbs\n hi = (ts ! 1 - ts ! 0) / 100\n l2v f = \\t -> fromList . f t . toList\n\nmain :: IO ()\nmain = do\n print vanderpol1\n print vanderpol2\n", "meta": {"hexsha": "74efb22e1a2597c5793e27c579a8dd1f5ff023e1", "size": 811, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/19-numbers/diffeq/Main.hs", "max_stars_repo_name": "aavogt/wiwinwlh", "max_stars_repo_head_hexsha": "c64f5d26e299be85b85e1c370a7a5de6037e2e3e", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": 2479, "max_stars_repo_stars_event_min_datetime": "2015-01-01T14:39:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:34:03.000Z", "max_issues_repo_path": "src/19-numbers/diffeq/Main.hs", "max_issues_repo_name": "aavogt/wiwinwlh", "max_issues_repo_head_hexsha": "c64f5d26e299be85b85e1c370a7a5de6037e2e3e", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": 151, "max_issues_repo_issues_event_min_datetime": "2015-01-16T07:43:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T15:20:06.000Z", "max_forks_repo_path": "src/19-numbers/diffeq/Main.hs", "max_forks_repo_name": "aavogt/wiwinwlh", "max_forks_repo_head_hexsha": "c64f5d26e299be85b85e1c370a7a5de6037e2e3e", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 339, "max_forks_repo_forks_event_min_datetime": "2015-01-01T19:23:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T17:55:39.000Z", "avg_line_length": 21.9189189189, "max_line_length": 73, "alphanum_fraction": 0.6473489519, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5423252159691424}} {"text": "{-# language FlexibleInstances, FlexibleContexts, TypeFamilies #-}\n{-# language ConstrainedClassMethods #-}\n{-# language CPP #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Core.Numeric.BLAS.Class\n-- Copyright : (c) Marco Zocca 2017-2018\n-- License : see the file LICENSE\n--\n-- Maintainer : ocramz fripost org\n-- Stability : experimental\n-- Portability : portable\n--\n-- Typeclasses for linear algebra and related concepts\n--\n-----------------------------------------------------------------------------\nmodule Core.Numeric.BLAS.Class where\n\nimport Data.Complex\nimport Foreign.C.Types (CFloat, CDouble)\n\n\n-- * Matrix and vector elements (optionally Complex)\n--\n-- Uses 'FlexibleContexts' and 'TypeFamilies' \nclass (Eq e , Fractional e, Floating e, Num (EltMag e), Ord (EltMag e)) => Elt e where\n type EltMag e :: *\n -- | Complex conjugate, or identity function if its input is real-valued\n conj :: e -> e\n conj = id\n -- | Magnitude\n mag :: e -> EltMag e\n\ninstance Elt Double where {type EltMag Double = Double ; mag = id}\ninstance Elt Float where {type EltMag Float = Float; mag = id}\ninstance (RealFloat e) => Elt (Complex e) where\n type EltMag (Complex e) = e\n conj = conjugate\n mag = magnitude\n\n\n\ninfixl 6 ^+^, ^-^\n\n-- * Additive group\nclass AdditiveGroup v where\n -- | The zero element: identity for '(^+^)'\n zeroV :: v\n -- | Add vectors\n (^+^) :: v -> v -> v\n -- | Additive inverse\n negateV :: v -> v\n -- | Group subtraction\n (^-^) :: v -> v -> v\n (^-^) x y = x ^+^ negateV y\n\n\ninfixr 7 .*\n\n-- * Vector space @v@.\nclass (AdditiveGroup v, Num (Scalar v)) => VectorSpace v where\n type Scalar v :: *\n -- | Scale a vector\n (.*) :: Scalar v -> v -> v\n\n-- | Adds inner (dot) products.\nclass VectorSpace v => InnerSpace v where\n -- | Inner/dot product\n (<.>) :: v -> v -> Scalar v\n\n-- | Inner product\ndot :: InnerSpace v => v -> v -> Scalar v\ndot = (<.>)\n\n\n-- | Scale a vector by the reciprocal of a number (e.g. for normalization)\n(./) :: (VectorSpace v, s ~ Scalar v, Fractional s) => v -> s -> v\nv ./ s = recip s .* v\n\n-- | Vector multiplied by scalar\n(*.) :: (VectorSpace v, s ~ Scalar v) => v -> s -> v\n(*.) = flip (.*) \n\n\n\n-- | Convex combination of two vectors (NB: 0 <= `a` <= 1). \ncvx :: VectorSpace v => Scalar v -> v -> v -> v\ncvx a u v = a .* u ^+^ ((1-a) .* v)\n\n\n\n\n-- ** Hilbert-space distance function\n\n-- |`hilbertDistSq x y = || x - y ||^2` computes the squared L2 distance between two vectors\nhilbertDistSq :: InnerSpace v => v -> v -> Scalar v\nhilbertDistSq x y = t <.> t where\n t = x ^-^ y\n\n\n-- * Normed vector spaces\n--\n-- Uses 'ConstrainedClassMethods'\nclass (InnerSpace v, Num (RealScalar v), Eq (RealScalar v), Epsilon (Magnitude v), Show (Magnitude v), Ord (Magnitude v)) => Normed v where\n type Magnitude v :: *\n type RealScalar v :: *\n -- | L1 norm\n norm1 :: v -> Magnitude v\n -- | Euclidean (L2) norm squared\n norm2Sq :: v -> Magnitude v\n -- | Lp norm (p > 0)\n normP :: RealScalar v -> v -> Magnitude v\n -- | Normalize w.r.t. Lp norm\n normalize :: RealScalar v -> v -> v\n -- | Normalize w.r.t. L2 norm\n normalize2 :: v -> v\n -- | Normalize w.r.t. norm2' instead of norm2\n normalize2' :: Floating (Scalar v) => v -> v \n normalize2' x = x ./ norm2' x\n -- | Euclidean (L2) norm\n norm2 :: Floating (Magnitude v) => v -> Magnitude v \n norm2 x = sqrt (norm2Sq x)\n -- | Euclidean (L2) norm; returns a Complex (norm :+ 0) for Complex-valued vectors\n norm2' :: Floating (Scalar v) => v -> Scalar v \n norm2' x = sqrt $ x <.> x\n -- | Lp norm (p > 0)\n norm :: Floating (Magnitude v) => RealScalar v -> v -> Magnitude v \n norm p v\n | p == 1 = norm1 v\n | p == 2 = norm2 v\n | otherwise = normP p v\n\n\n\n-- | Infinity-norm (Real)\nnormInftyR :: (Foldable t, Ord a) => t a -> a\nnormInftyR x = maximum x\n\n-- | Infinity-norm (Complex)\nnormInftyC :: (Foldable t, RealFloat a, Functor t) => t (Complex a) -> a\nnormInftyC x = maximum (magnitude <$> x)\n\n\n-- | Lp inner product (p > 0)\ndotLp :: (Set t, Foldable t, Floating a) => a -> t a -> t a -> a\ndotLp p v1 v2 = sum u**(1/p) where\n f a b = (a*b)**p\n u = liftI2 f v1 v2\n\n\n-- | Reciprocal\nreciprocal :: (Functor f, Fractional b) => f b -> f b\nreciprocal = fmap recip\n\n\n-- |Scale\nscale :: (Num b, Functor f) => b -> f b -> f b\nscale n = fmap (* n)\n\n\n\n-- * Matrix ring\n\n-- | A matrix ring is any collection of matrices over some ring R that form a ring under matrix addition and matrix multiplication\n\nclass (AdditiveGroup m, Epsilon (MatrixNorm m)) => MatrixRing m where\n type MatrixNorm m :: *\n -- | Matrix-matrix product\n (##) :: m -> m -> m\n -- | Matrix times matrix transpose (A B^T)\n (##^) :: m -> m -> m\n -- | Matrix transpose times matrix (A^T B)\n (#^#) :: m -> m -> m\n a #^# b = transpose a ## b\n -- | Matrix transpose (Hermitian conjugate in the Complex case)\n transpose :: m -> m\n -- | Frobenius norm\n normFrobenius :: m -> MatrixNorm m\n\n\n\n-- * Linear vector space\n\nclass (VectorSpace v {-, MatrixRing (MatrixType v)-}) => LinearVectorSpace v where\n type MatrixType v :: *\n -- | Matrix-vector action\n (#>) :: MatrixType v -> v -> v\n -- | Dual matrix-vector action\n (<#) :: v -> MatrixType v -> v\n \n\n\n\n\n\n-- * Typeclasses for internal use (not to be exposed to the user)\n\n-- ** FiniteDim : finite-dimensional objects\nclass FiniteDim f where\n type FDSize f\n -- | Dimension (i.e. Int for SpVector, (Int, Int) for SpMatrix)\n dim :: f -> FDSize f\n\n\n-- ** HasData : accessing inner data (do not export)\nclass HasData f where\n type HDData f \n -- | Number of nonzeros\n nnz :: f -> Int\n dat :: f -> HDData f\n\n\n-- ** Sparse : sparse datastructures\nclass (FiniteDim f, HasData f) => Sparse f where\n -- | Sparsity (fraction of nonzero elements)\n spy :: Fractional b => f -> b\n\n\n-- ** Set : types that behave as sets\n--\n-- Example : sparse vector addition operates on the union of the nonzero indices, whereas the sparse vector inner product uses \nclass Functor f => Set f where\n -- | Union binary lift : apply function on _union_ of two \"sets\"\n liftU2 :: (a -> a -> a) -> f a -> f a -> f a\n -- | Intersection binary lift : apply function on _intersection_ of two \"sets\"\n liftI2 :: (a -> a -> b) -> f a -> f a -> f b\n\n\n\n\n\n\n-- * instances\n\n-- | Instances for builtin types\n--\n-- Uses 'CPP'\n#define ScalarType(t) \\\ninstance AdditiveGroup (t) where {zeroV = 0; (^+^) = (+); negateV = negate};\\\ninstance VectorSpace (t) where {type Scalar (t) = t; (.*) = (*) };\n\n-- ScalarType(Int)\n-- ScalarType(Integer)\nScalarType(Float)\nScalarType(Double)\nScalarType(Complex Float)\nScalarType(Complex Double)\n\n#undef ScalarType\n\ninstance InnerSpace Float where {(<.>) = (*)}\ninstance InnerSpace Double where {(<.>) = (*)}\ninstance InnerSpace (Complex Float) where {x <.> y = x * conjugate y}\ninstance InnerSpace (Complex Double) where {x <.> y = x * conjugate y}\n\n#define SimpleNormedInstance(t) \\\ninstance Normed (t) where {type Magnitude (t) = t; type RealScalar (t) = t;\\\n norm1 = abs; norm2Sq = (**2); normP _ = abs; normalize _ = signum;\\\n normalize2 = signum; normalize2' = signum; norm2 = abs; norm2' = abs; norm _ = abs};\n\nSimpleNormedInstance(Float)\nSimpleNormedInstance(Double)\n\n#undef SimpleNormedInstance\n\n#define ComplexNormedInstance(t) \\\ninstance Normed (Complex (t)) where {\\\n type Magnitude (Complex (t)) = t;\\\n type RealScalar (Complex (t)) = t;\\\n norm1 (r :+ i) = abs r + abs i;\\\n norm2Sq (r :+ i) = r*r + i*i;\\\n normP p (r :+ i) = (r**p + i**p)**(1/p);\\\n normalize p c = toC (1 / normP p c) * c;\\\n normalize2 c = (1 / norm2' c) * c;\\\n norm2 = magnitude;\\\n norm2' = toC . magnitude;};\n\nComplexNormedInstance(Float)\nComplexNormedInstance(Double)\n\n#undef ComplexNormedInstance\n\n\n-- * Utilities\n\n-- | Lift a real number onto the complex plane\ntoC :: Num a => a -> Complex a\ntoC r = r :+ 0\n\n\n\n\n\n\n\n-- | Provides a test to see if a quantity is near zero.\n--\n-- Appears originally in ekmett/linear\n--\n-- TODO[ocramz] Uses 'FlexibleInstances', so might be a good idea to move it in a separate module\n--\n-- >>> nearZero (1e-11 :: Double)\n-- False\n--\n-- >>> nearZero (1e-17 :: Double)\n-- True\n--\n-- >>> nearZero (1e-5 :: Float)\n-- False\n--\n-- >>> nearZero (1e-7 :: Float)\n-- True\nclass (Floating a, Num a) => Epsilon a where\n -- | Determine if a quantity is near zero.\n nearZero :: a -> Bool\n\n-- | @'abs' a '<=' 1e-6@\ninstance Epsilon Float where\n nearZero a = abs a <= 1e-6\n\n-- | @'abs' a '<=' 1e-12@\ninstance Epsilon Double where\n nearZero a = abs a <= 1e-12\n\n-- | @'abs' a '<=' 1e-6@\ninstance Epsilon CFloat where\n nearZero a = abs a <= 1e-6\n\n-- | @'abs' a '<=' 1e-12@\ninstance Epsilon CDouble where\n nearZero a = abs a <= 1e-12\n\n\n-- | @'magnitude' a '<=' 1e-6@\ninstance Epsilon (Complex Float) where\n nearZero a = magnitude a <= 1e-6\n\n-- | @'magnitude' a '<=' 1e-12@\ninstance Epsilon (Complex Double) where\n nearZero a = magnitude a <= 1e-12\n\n-- | @'magnitude' a '<=' 1e-6@\ninstance Epsilon (Complex CFloat) where\n nearZero a = magnitude a <= 1e-6\n\n-- | @'magnitude' a '<=' 1e-12@\ninstance Epsilon (Complex CDouble) where\n nearZero a = magnitude a <= 1e-12\n\n\n\n-- * Rounding operations\n\n\n-- | Is this quantity close to 1 ?\nnearOne :: Epsilon a => a -> Bool\nnearOne x = nearZero (1 - x)\n\n-- | Is this quantity distinguishable from 0 ?\nisNz :: Epsilon a => a -> Bool\nisNz x = not (nearZero x)\n\nwithDefault :: (t -> Bool) -> t -> t -> t\nwithDefault q d x | q x = d\n | otherwise = x\n\nroundZero, roundOne, roundZeroOne :: Epsilon a => a -> a\nroundZero = withDefault nearZero (fromIntegral (0 :: Int))\nroundOne = withDefault nearOne (fromIntegral (1 :: Int))\n\nwith2Defaults :: (t -> Bool) -> (t -> Bool) -> t -> t -> t -> t\nwith2Defaults q1 q2 d1 d2 x | q1 x = d1\n | q2 x = d2\n | otherwise = x\n\n-- | Round to respectively 0 or 1\nroundZeroOne = with2Defaults nearZero nearOne (fromIntegral (0 :: Int)) (fromIntegral (1 :: Int))\n", "meta": {"hexsha": "04676a00e713cfb975e0318d5588b7a97567262e", "size": 9911, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "dh-core/src/Core/Numeric/BLAS/Class.hs", "max_stars_repo_name": "Magalame/dh-core", "max_stars_repo_head_hexsha": "28c00d9ce1654300ca81a542f2174e3fd0f582d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T11:26:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T11:26:40.000Z", "max_issues_repo_path": "dh-core/src/Core/Numeric/BLAS/Class.hs", "max_issues_repo_name": "Magalame/dh-core", "max_issues_repo_head_hexsha": "28c00d9ce1654300ca81a542f2174e3fd0f582d3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-10T19:38:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-10T19:38:18.000Z", "max_forks_repo_path": "dh-core/src/Core/Numeric/BLAS/Class.hs", "max_forks_repo_name": "Magalame/dh-core", "max_forks_repo_head_hexsha": "28c00d9ce1654300ca81a542f2174e3fd0f582d3", "max_forks_repo_licenses": ["BSD-3-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.2195767196, "max_line_length": 139, "alphanum_fraction": 0.6038744829, "num_tokens": 3099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.542263851409483}} {"text": "module Numeric.Sundials.ODEOpts where\n\nimport Data.Int (Int32)\nimport qualified Data.Vector.Storable as VS\n\nimport Numeric.LinearAlgebra.HMatrix (Vector, Matrix)\n\n\ntype Jacobian = Double -> Vector Double -> Matrix Double\n\n-- | Adaptive step-size control\n-- functions.\n--\n-- [GSL](https://www.gnu.org/software/gsl/doc/html/ode-initval.html#adaptive-step-size-control)\n-- allows the user to control the step size adjustment using\n-- \\(D_i = \\epsilon^{abs}s_i + \\epsilon^{rel}(a_{y} |y_i| + a_{dy/dt} h |\\dot{y}_i|)\\) where\n-- \\(\\epsilon^{abs}\\) is the required absolute error, \\(\\epsilon^{rel}\\)\n-- is the required relative error, \\(s_i\\) is a vector of scaling\n-- factors, \\(a_{y}\\) is a scaling factor for the solution \\(y\\) and\n-- \\(a_{dydt}\\) is a scaling factor for the derivative of the solution \\(dy/dt\\).\n--\n-- [CVode](https://computation.llnl.gov/projects/sundials/cvode)\n-- allows the user to control the step size adjustment using\n-- \\(\\eta^{rel}|y_i| + \\eta^{abs}_i\\). For compatibility with\n-- [hmatrix-gsl](https://hackage.haskell.org/package/hmatrix-gsl),\n-- tolerances for \\(y\\) and \\(\\dot{y}\\) can be specified but the latter have no\n-- effect.\ndata StepControl = X Double Double -- ^ absolute and relative tolerance for \\(y\\); in GSL terms, \\(a_{y} = 1\\) and \\(a_{dy/dt} = 0\\); in ARKode terms, the \\(\\eta^{abs}_i\\) are identical\n | X' Double Double -- ^ absolute and relative tolerance for \\(\\dot{y}\\); in GSL terms, \\(a_{y} = 0\\) and \\(a_{dy/dt} = 1\\); in ARKode terms, the latter is treated as the relative tolerance for \\(y\\) so this is the same as specifying 'X' which may be entirely incorrect for the given problem\n | XX' Double Double Double Double -- ^ include both via relative tolerance\n -- scaling factors \\(a_y\\), \\(a_{{dy}/{dt}}\\); in ARKode terms, the latter is ignored and \\(\\eta^{rel} = a_{y}\\epsilon^{rel}\\)\n | ScXX' Double Double Double Double (Vector Double) -- ^ scale absolute tolerance of \\(y_i\\); in ARKode terms, \\(a_{{dy}/{dt}}\\) is ignored, \\(\\eta^{abs}_i = s_i \\epsilon^{abs}\\) and \\(\\eta^{rel} = a_{y}\\epsilon^{rel}\\)\n deriving (Eq, Ord, Show, Read)\n\n-- | Stepping functions\ndata ODEMethod = ADAMS\n | BDF\n deriving (Eq, Ord, Show, Read)\n\ndata ODEOpts = ODEOpts {\n maxNumSteps :: Int32\n , minStep :: Double\n , maxFail :: Int32\n , odeMethod :: ODEMethod\n , stepControl :: StepControl\n , initStep :: Maybe Double\n -- ^ initial step size - by default, CVode\n -- estimates the initial step size to be the\n -- solution \\(h\\) of the equation\n -- \\(\\|\\frac{h^2\\ddot{y}}{2}\\| = 1\\), where\n -- \\(\\ddot{y}\\) is an estimated value of the second\n -- derivative of the solution at \\(t_0\\)\n } deriving (Read, Show, Eq, Ord)\n\ndata SundialsDiagnostics = SundialsDiagnostics {\n odeGetNumSteps :: Int\n , odeGetNumStepAttempts :: Int\n , odeGetNumRhsEvals_fe :: Int\n , odeGetNumRhsEvals_fi :: Int\n , odeGetNumLinSolvSetups :: Int\n , odeGetNumErrTestFails :: Int\n , odeGetNumNonlinSolvIters :: Int\n , odeGetNumNonlinSolvConvFails :: Int\n , dlsGetNumJacEvals :: Int\n , dlsGetNumRhsEvals :: Int\n } deriving Show\n\n", "meta": {"hexsha": "3eb142b9a7a72536ce352c9b2b6e0e021325414b", "size": 3308, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Sundials/ODEOpts.hs", "max_stars_repo_name": "regnat/hmatrix-sundials", "max_stars_repo_head_hexsha": "523b91cd3aa0207a2e2bc2a2a91371a119ef0b39", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/Sundials/ODEOpts.hs", "max_issues_repo_name": "regnat/hmatrix-sundials", "max_issues_repo_head_hexsha": "523b91cd3aa0207a2e2bc2a2a91371a119ef0b39", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/ODEOpts.hs", "max_forks_repo_name": "regnat/hmatrix-sundials", "max_forks_repo_head_hexsha": "523b91cd3aa0207a2e2bc2a2a91371a119ef0b39", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-11T12:33:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T12:33:55.000Z", "avg_line_length": 48.6470588235, "max_line_length": 310, "alphanum_fraction": 0.6275695284, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146849, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5416520700958377}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Main where\n\nimport Wigner\nimport BraKet\nimport Operators\nimport QUtil\nimport LinAlg\n\nimport Data.Complex\nimport Data.List.Split\n\nmain :: IO ()\nmain = do\n let expd = computeExpD dim ps dZ (-bound, bound) states\n let n = round . sqrt . fromIntegral . length $ expd\n -- Wigner transform the expected D\n let cplane = getPlane dZ (-bound) bound\n writeComplex \"wigner\" $ wignerTransform cplane (dZ^2) cplane expd \n --writeComplex \"wigner\" . mconcat . wt2d . chunksOf n $ expd \n writeComplex \"cplane\" cplane\n\n-- dimension of vector space to work in\ndim = 40\n-- number of steps in the complex plane to use\n-- computation scales as O(nsteps^2)\nnsteps = 50 \n-- bounds on the complex plane\nbound = 5.0\n-- step size in complex plane\ndZ = 2.0 * bound / fromIntegral nsteps\n\n-- list of states to use\n-- really a list of functions, I use applicative to \n-- convert to a list of sized state vectors\nstates :: [Int -> Ket (Complex Double)]\n-- vacuum \nstates = [vacuum]\n-- squeezed vacuum\n--states = [\\dim -> act (squeeze dim 0.75) $ vacuum dim]\n-- one photon Fock\n--states = [flip fockN 1]\n-- Linear combination\n--states = [\\dim -> vacuum dim <+> fockN dim 1] \n-- coherent state\n--states = [flip coherent (2)]\n-- coherent superposition (AKA schrodinger's cat)\n--states = [\\dim -> coherent dim 2 <+> coherent dim (-2.0)]\n-- Mixed schrodinger cat\n--states = [flip coherent ((-2.0) :+ 0.0), flip coherent (2.0 :+ 0.0)]\n-- Absorbed\n--states = [vacuum, flip fockN 1]\n-- classical probabilities of mixed state\nps = [1.0]\n\n-- Construct the complex plane from a range and step size\ngetPlane :: Double -> Double -> Double -> [Complex Double]\ngetPlane dz zMin zMax = (:+) <$> range <*> range \n where\n range = [zMin, zMin+dz..zMax]\n\n-- Compute the expected value of the displacement operator\n-- over the complex plane\ncomputeExpD :: Int -> [Complex Double] -> Double -> (Double, Double) \n -> [Int -> Ket (Complex Double)] -> [Complex Double]\ncomputeExpD dim ps dz (zMin, zMax) states = (\\z -> expectDisp dim z ps (states <*> [dim])) <$> plane\n where plane = getPlane dz zMin zMax\n\n-- Write complex array to file\nwriteComplex :: FilePath -> [Complex Double] -> IO ()\nwriteComplex fpath = writeFile fpath . complexToPlane\n\n-- Make list of complex numbers easy to parse by python\ncomplexToPlane :: [Complex Double] -> String\ncomplexToPlane [] = \"\"\ncomplexToPlane ((x :+ y):zs) = show x ++ \" \" ++ show y ++ \"\\n\" ++ complexToPlane zs", "meta": {"hexsha": "7ef055b26eedd68c9de86941d53c85518fba331b", "size": 2542, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.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": "app/Main.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": "app/Main.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": 33.012987013, "max_line_length": 104, "alphanum_fraction": 0.6589299764, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5411712367348966}} {"text": "{-# OPTIONS_GHC -Wall #-}\n\n{-# LANGUAGE QuasiQuotes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\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 tableau for the solver.\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 , ButcherTable(..)\n , butcherTable\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, CLong)\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 subVector, subMatrix, (><))\n\nimport Numeric.Sundials.ODEOpts (ODEOpts(..), Jacobian, SundialsDiagnostics(..))\nimport qualified Numeric.Sundials.Arkode as T\nimport Numeric.Sundials.Arkode (arkSMax,\n 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 <> T.sunCtx)\n\nC.include \"\"\nC.include \"\"\nC.include \"\"\nC.include \"\" -- prototypes for ARKODE fcts., consts.\nC.include \"\" -- serial N_Vector types, fcts., macros\nC.include \"\" -- access to dense SUNMatrix\nC.include \"\" -- access to dense SUNLinearSolver\nC.include \"\" -- access to ARKDls interface\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\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) -> 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\nsolveOdeC ::\n CInt ->\n CLong ->\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 = unsafePerformIO $ do\n\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 :: CLong\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 diagnostics :: V.Vector CLong <- createVector 10 -- FIXME\n diagMut <- V.thaw diagnostics\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 int 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 arkode_mem = ARKodeCreate(); /* Create the solver memory */\n if (check_flag((void *)arkode_mem, \"ARKodeCreate\", 0)) return 1;\n\n /* Call ARKodeInit to initialize the integrator memory and specify the */\n /* right-hand side function in y'=f(t,y), the inital time T0, and */\n /* the initial dependent variable vector y. Note: we treat the */\n /* problem as fully implicit and 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 flag = ARKodeInit(arkode_mem, $fun:(int (* funIO) (double t, SunVector y[], SunVector dydt[], void * params)), NULL, T0, y);\n if (check_flag(&flag, \"ARKodeInit\", 1)) return 1;\n } else {\n flag = ARKodeInit(arkode_mem, NULL, $fun:(int (* funIO) (double t, SunVector y[], SunVector dydt[], void * params)), T0, y);\n if (check_flag(&flag, \"ARKodeInit\", 1)) return 1;\n }\n\n flag = ARKodeSetMinStep(arkode_mem, $(double minStep_));\n if (check_flag(&flag, \"ARKodeSetMinStep\", 1)) return 1;\n flag = ARKodeSetMaxNumSteps(arkode_mem, $(long int maxNumSteps_));\n if (check_flag(&flag, \"ARKodeSetMaxNumSteps\", 1)) return 1;\n flag = ARKodeSetMaxErrTestFails(arkode_mem, $(int maxErrTestFails));\n if (check_flag(&flag, \"ARKodeSetMaxErrTestFails\", 1)) return 1;\n\n /* Set routines */\n flag = ARKodeSVtolerances(arkode_mem, $(double rTol), tv);\n if (check_flag(&flag, \"ARKodeSVtolerances\", 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 = ARKDlsSetLinearSolver(arkode_mem, LS, A);\n if (check_flag(&flag, \"ARKDlsSetLinearSolver\", 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 = ARKodeSetInitStep(arkode_mem, $(double ss));\n if (check_flag(&flag, \"ARKodeSetInitStep\", 1)) return 1;\n }\n\n /* Set the Jacobian if there is one */\n if ($(int isJac)) {\n flag = ARKDlsSetJacFn(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, \"ARKDlsSetJacFn\", 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 = ARKodeSetIRKTableNum(arkode_mem, $(int method));\n if (check_flag(&flag, \"ARKodeSetIRKTableNum\", 1)) return 1;\n } else {\n flag = ARKodeSetERKTableNum(arkode_mem, $(int method));\n if (check_flag(&flag, \"ARKodeSetERKTableNum\", 1)) return 1;\n }\n\n /* Main time-stepping loop: calls ARKode to perform the integration */\n /* Stops when the final time has been reached */\n for (i = 1; i < $(int nTs); i++) {\n\n flag = ARKode(arkode_mem, ($vec-ptr:(double *ts))[i], y, &t, ARK_NORMAL); /* call integrator */\n if (check_flag(&flag, \"ARKode 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 = ARKodeGetNumSteps(arkode_mem, &nst);\n check_flag(&flag, \"ARKodeGetNumSteps\", 1);\n ($vec-ptr:(long int *diagMut))[0] = nst;\n\n flag = ARKodeGetNumStepAttempts(arkode_mem, &nst_a);\n check_flag(&flag, \"ARKodeGetNumStepAttempts\", 1);\n ($vec-ptr:(long int *diagMut))[1] = nst_a;\n\n flag = ARKodeGetNumRhsEvals(arkode_mem, &nfe, &nfi);\n check_flag(&flag, \"ARKodeGetNumRhsEvals\", 1);\n ($vec-ptr:(long int *diagMut))[2] = nfe;\n ($vec-ptr:(long int *diagMut))[3] = nfi;\n\n flag = ARKodeGetNumLinSolvSetups(arkode_mem, &nsetups);\n check_flag(&flag, \"ARKodeGetNumLinSolvSetups\", 1);\n ($vec-ptr:(long int *diagMut))[4] = nsetups;\n\n flag = ARKodeGetNumErrTestFails(arkode_mem, &netf);\n check_flag(&flag, \"ARKodeGetNumErrTestFails\", 1);\n ($vec-ptr:(long int *diagMut))[5] = netf;\n\n flag = ARKodeGetNumNonlinSolvIters(arkode_mem, &nni);\n check_flag(&flag, \"ARKodeGetNumNonlinSolvIters\", 1);\n ($vec-ptr:(long int *diagMut))[6] = nni;\n\n flag = ARKodeGetNumNonlinSolvConvFails(arkode_mem, &ncfn);\n check_flag(&flag, \"ARKodeGetNumNonlinSolvConvFails\", 1);\n ($vec-ptr:(long int *diagMut))[7] = ncfn;\n\n flag = ARKDlsGetNumJacEvals(arkode_mem, &nje);\n check_flag(&flag, \"ARKDlsGetNumJacEvals\", 1);\n ($vec-ptr:(long int *diagMut))[8] = ncfn;\n\n flag = ARKDlsGetNumRhsEvals(arkode_mem, &nfeLS);\n check_flag(&flag, \"ARKDlsGetNumRhsEvals\", 1);\n ($vec-ptr:(long int *diagMut))[9] = ncfn;\n\n /* Clean up and return */\n N_VDestroy(y); /* Free y vector */\n N_VDestroy(tv); /* Free tv vector */\n ARKodeFree(&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\ndata ButcherTable = ButcherTable { am :: Matrix Double\n , cv :: Vector Double\n , bv :: Vector Double\n , b2v :: Vector Double\n }\n deriving Show\n\ndata ButcherTable' a = ButcherTable' { am' :: V.Vector a\n , cv' :: V.Vector a\n , bv' :: V.Vector a\n , b2v' :: V.Vector a\n }\n deriving Show\n\nbutcherTable :: ODEMethod -> ButcherTable\nbutcherTable method =\n case getBT method of\n Left c -> error $ show c -- FIXME\n Right (ButcherTable' v w x y, sqp) ->\n ButcherTable { am = subMatrix (0, 0) (s, s) $ (arkSMax >< arkSMax) (V.toList v)\n , cv = subVector 0 s w\n , bv = subVector 0 s x\n , b2v = subVector 0 s y\n }\n where\n s = fromIntegral $ sqp V.! 0\n\ngetBT :: ODEMethod -> Either Int (ButcherTable' Double, V.Vector Int)\ngetBT method = case getButcherTable method of\n Left c ->\n Left $ fromIntegral c\n Right (ButcherTable' a b c d, sqp) ->\n Right $ ( ButcherTable' (coerce a) (coerce b) (coerce c) (coerce d)\n , V.map fromIntegral sqp )\n\ngetButcherTable :: ODEMethod\n -> Either CInt (ButcherTable' CDouble, V.Vector CInt)\ngetButcherTable method = unsafePerformIO $ do\n -- ARKode seems to want an ODE in order to set and then get the\n -- Butcher tableau so here's one to keep it happy\n let funI :: CDouble -> V.Vector CDouble -> V.Vector CDouble\n funI _t ys = V.fromList [ ys V.! 0 ]\n let funE :: CDouble -> V.Vector CDouble -> V.Vector CDouble\n funE _t ys = V.fromList [ ys V.! 0 ]\n f0 = V.fromList [ 1.0 ]\n ts = V.fromList [ 0.0 ]\n dim = V.length f0\n nEq :: CLong\n nEq = fromIntegral dim\n mN :: CInt\n mN = fromIntegral $ getMethod method\n\n btSQP :: V.Vector CInt <- createVector 3\n btSQPMut <- V.thaw btSQP\n btAs :: V.Vector CDouble <- createVector (arkSMax * arkSMax)\n btAsMut <- V.thaw btAs\n btCs :: V.Vector CDouble <- createVector arkSMax\n btBs :: V.Vector CDouble <- createVector arkSMax\n btB2s :: V.Vector CDouble <- createVector arkSMax\n btCsMut <- V.thaw btCs\n btBsMut <- V.thaw btBs\n btB2sMut <- V.thaw btB2s\n let funIOI :: CDouble -> Ptr T.SunVector -> Ptr T.SunVector -> Ptr () -> IO CInt\n funIOI t y f _ptr = do\n sv <- peek y\n poke f $ T.SunVector { T.sunVecN = T.sunVecN sv\n , T.sunVecVals = funI t (T.sunVecVals sv)\n }\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 let funIOE :: CDouble -> Ptr T.SunVector -> Ptr T.SunVector -> Ptr () -> IO CInt\n funIOE t y f _ptr = do\n sv <- peek y\n poke f $ T.SunVector { T.sunVecN = T.sunVecN sv\n , T.sunVecVals = funE t (T.sunVecVals sv)\n }\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 res <- [C.block| int {\n /* general problem variables */\n\n int flag; /* reusable error-checking flag */\n N_Vector y = NULL; /* empty vector for storing solution */\n void *arkode_mem = NULL; /* empty ARKode memory structure */\n int i, j; /* reusable loop indices */\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 arkode_mem = ARKodeCreate(); /* Create the solver memory */\n if (check_flag((void *)arkode_mem, \"ARKodeCreate\", 0)) return 1;\n\n flag = ARKodeInit(arkode_mem, $fun:(int (* funIOE) (double t, SunVector y[], SunVector dydt[], void * params)), $fun:(int (* funIOI) (double t, SunVector y[], SunVector dydt[], void * params)), T0, y);\n if (check_flag(&flag, \"ARKodeInit\", 1)) return 1;\n\n if ($(int mN) >= MIN_DIRK_NUM) {\n flag = ARKodeSetIRKTableNum(arkode_mem, $(int mN));\n if (check_flag(&flag, \"ARKodeSetIRKTableNum\", 1)) return 1;\n } else {\n flag = ARKodeSetERKTableNum(arkode_mem, $(int mN));\n if (check_flag(&flag, \"ARKodeSetERKTableNum\", 1)) return 1;\n }\n\n int s, q, p;\n realtype *ai = (realtype *)malloc(ARK_S_MAX * ARK_S_MAX * sizeof(realtype));\n realtype *ae = (realtype *)malloc(ARK_S_MAX * ARK_S_MAX * sizeof(realtype));\n realtype *ci = (realtype *)malloc(ARK_S_MAX * sizeof(realtype));\n realtype *ce = (realtype *)malloc(ARK_S_MAX * sizeof(realtype));\n realtype *bi = (realtype *)malloc(ARK_S_MAX * sizeof(realtype));\n realtype *be = (realtype *)malloc(ARK_S_MAX * sizeof(realtype));\n realtype *b2i = (realtype *)malloc(ARK_S_MAX * sizeof(realtype));\n realtype *b2e = (realtype *)malloc(ARK_S_MAX * sizeof(realtype));\n flag = ARKodeGetCurrentButcherTables(arkode_mem, &s, &q, &p, ai, ae, ci, ce, bi, be, b2i, b2e);\n if (check_flag(&flag, \"ARKode\", 1)) return 1;\n $vec-ptr:(int *btSQPMut)[0] = s;\n $vec-ptr:(int *btSQPMut)[1] = q;\n $vec-ptr:(int *btSQPMut)[2] = p;\n for (i = 0; i < s; i++) {\n for (j = 0; j < s; j++) {\n /* FIXME: double should be realtype */\n ($vec-ptr:(double *btAsMut))[i * ARK_S_MAX + j] = ai[i * ARK_S_MAX + j];\n }\n }\n\n for (i = 0; i < s; i++) {\n ($vec-ptr:(double *btCsMut))[i] = ci[i];\n ($vec-ptr:(double *btBsMut))[i] = bi[i];\n ($vec-ptr:(double *btB2sMut))[i] = b2i[i];\n }\n\n /* Clean up and return */\n N_VDestroy(y); /* Free y vector */\n ARKodeFree(&arkode_mem); /* Free integrator memory */\n\n return flag;\n } |]\n if res == 0\n then do\n x <- V.freeze btAsMut\n y <- V.freeze btSQPMut\n z <- V.freeze btCsMut\n u <- V.freeze btBsMut\n v <- V.freeze btB2sMut\n return $ Right (ButcherTable' { am' = x, cv' = z, bv' = u, b2v' = v }, y)\n else do\n return $ Left res\n\n-- | Adaptive step-size control\n-- functions.\n--\n-- [GSL](https://www.gnu.org/software/gsl/doc/html/ode-initval.html#adaptive-step-size-control)\n-- allows the user to control the step size adjustment using\n-- \\(D_i = \\epsilon^{abs}s_i + \\epsilon^{rel}(a_{y} |y_i| + a_{dy/dt} h |\\dot{y}_i|)\\) where\n-- \\(\\epsilon^{abs}\\) is the required absolute error, \\(\\epsilon^{rel}\\)\n-- is the required relative error, \\(s_i\\) is a vector of scaling\n-- factors, \\(a_{y}\\) is a scaling factor for the solution \\(y\\) and\n-- \\(a_{dydt}\\) is a scaling factor for the derivative of the solution \\(dy/dt\\).\n--\n-- [ARKode](https://computation.llnl.gov/projects/sundials/arkode)\n-- allows the user to control the step size adjustment using\n-- \\(\\eta^{rel}|y_i| + \\eta^{abs}_i\\). For compatibility with\n-- [hmatrix-gsl](https://hackage.haskell.org/package/hmatrix-gsl),\n-- tolerances for \\(y\\) and \\(\\dot{y}\\) can be specified but the latter have no\n-- effect.\ndata StepControl = X Double Double -- ^ absolute and relative tolerance for \\(y\\); in GSL terms, \\(a_{y} = 1\\) and \\(a_{dy/dt} = 0\\); in ARKode terms, the \\(\\eta^{abs}_i\\) are identical\n | X' Double Double -- ^ absolute and relative tolerance for \\(\\dot{y}\\); in GSL terms, \\(a_{y} = 0\\) and \\(a_{dy/dt} = 1\\); in ARKode terms, the latter is treated as the relative tolerance for \\(y\\) so this is the same as specifying 'X' which may be entirely incorrect for the given problem\n | XX' Double Double Double Double -- ^ include both via relative tolerance\n -- scaling factors \\(a_y\\), \\(a_{{dy}/{dt}}\\); in ARKode terms, the latter is ignored and \\(\\eta^{rel} = a_{y}\\epsilon^{rel}\\)\n | ScXX' Double Double Double Double (Vector Double) -- ^ scale absolute tolerance of \\(y_i\\); in ARKode terms, \\(a_{{dy}/{dt}}\\) is ignored, \\(\\eta^{abs}_i = s_i \\epsilon^{abs}\\) and \\(\\eta^{rel} = a_{y}\\epsilon^{rel}\\)\n", "meta": {"hexsha": "51fe886f243c790180779b1c8799eb0f7c9c4498", "size": 43088, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Sundials/ARKode/ODE.hs", "max_stars_repo_name": "regnat/hmatrix-sundials", "max_stars_repo_head_hexsha": "523b91cd3aa0207a2e2bc2a2a91371a119ef0b39", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/Sundials/ARKode/ODE.hs", "max_issues_repo_name": "regnat/hmatrix-sundials", "max_issues_repo_head_hexsha": "523b91cd3aa0207a2e2bc2a2a91371a119ef0b39", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "regnat/hmatrix-sundials", "max_forks_repo_head_hexsha": "523b91cd3aa0207a2e2bc2a2a91371a119ef0b39", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-11T12:33:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T12:33:55.000Z", "avg_line_length": 47.8755555556, "max_line_length": 310, "alphanum_fraction": 0.5152246565, "num_tokens": 12439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.5411108257247057}} {"text": "import Control.Parallel\n\nimport Numeric.Container hiding (linspace)\nimport Numeric.LinearAlgebra.Util\nimport Numeric.LinearAlgebra.Data hiding (linspace)\nimport Numeric.LinearAlgebra.Algorithms \nimport Numeric.LinearAlgebra.Devel\nimport Data.List hiding (find)\nimport DSP.Basic\n\n\n--gridsize\nn = 75\n\n--index function\nindex :: (Int, Int) -> Int -> Double\nindex (i,j) n\n\t| i == j = 6\n\t| i == j + n*n = -1\n\t| i == j - n*n = -1\n\t| i == j + n = -1\n\t| i == j - n = -1\n\t| i == j + 1 = -1\n\t| i == j - 1 = -1\n\t| otherwise = 0\n\n-- Laplace Matrix in 3 dimensions\nt = buildMatrix (n*n*n) (n*n*n) (\\(i,j) -> index (i,j) n)\neigen = eigenvalues t\t\t\n\n--Calculate corresponding Eigenfunction to n-th energy-eigenvalue\npsi :: Int -> Vector Double\npsi x = nullVector (a x)\n\twhere a x = t - (mapMatrix (* (realPart (eigen @> x))) (ident (n*n*n)) )\n\n--For further image processing\nv = asColumn (psi 56)\n\nmain :: IO ()\nmain = do\n-- write out matrix to visualize with python\nsaveMatrix \"vmat.txt\" \"%f\" v\n", "meta": {"hexsha": "745596901851bde5026d79ccab133b35b412cd08", "size": 999, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "finite_diffs/3d_finite_diff.hs", "max_stars_repo_name": "davidschlegel/hartree-fock", "max_stars_repo_head_hexsha": "381fc9c40e8d8f63c540b092ce51fca173149de9", "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": "finite_diffs/3d_finite_diff.hs", "max_issues_repo_name": "davidschlegel/hartree-fock", "max_issues_repo_head_hexsha": "381fc9c40e8d8f63c540b092ce51fca173149de9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "finite_diffs/3d_finite_diff.hs", "max_forks_repo_name": "davidschlegel/hartree-fock", "max_forks_repo_head_hexsha": "381fc9c40e8d8f63c540b092ce51fca173149de9", "max_forks_repo_licenses": ["BSD-3-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.2325581395, "max_line_length": 73, "alphanum_fraction": 0.6326326326, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5407524921207896}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule TensorOps.BLAS.HMat\n ( HMat\n , HMatD\n ) where\n\nimport Control.DeepSeq\nimport Data.Kind\nimport Data.Singletons\nimport Data.Singletons.TypeLits\nimport Data.Type.Combinator\nimport Data.Type.Vector (Vec, VecT(..))\nimport Data.Type.Vector.Util (curryV2', curryV3')\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Data as LA\nimport Numeric.LinearAlgebra.Devel\nimport TensorOps.BLAS\nimport Type.Class.Higher\nimport Type.Class.Higher.Util\nimport qualified Data.Finite as DF\nimport qualified Data.Finite.Internal as DF\nimport qualified Data.Vector.Storable as VS\n\ntype HMatD = HMat Double\n\ndata HMat :: Type -> BShape Nat -> Type where\n HMV :: { unHMV :: !(Vector a) } -> HMat a ('BV n)\n HMM :: { unHMM :: !(Matrix a) } -> HMat a ('BM n m)\n\ninstance (VS.Storable a, Show a, Element a) => Show (HMat a s) where\n showsPrec p = \\case\n HMV x -> showParen (p > 10) $ showString \"HMV \"\n . showsPrec 11 x\n HMM x -> showParen (p > 10) $ showString \"HMM \"\n . showsPrec 11 x\n\ninstance (VS.Storable a, Show a, Element a) => Show1 (HMat a)\n\ninstance (VS.Storable a, NFData a) => NFData (HMat a s) where\n rnf = \\case\n HMV xs -> rnf xs\n HMM xs -> rnf xs\n {-# INLINE rnf #-}\n\ninstance (VS.Storable a, NFData a) => NFData1 (HMat a)\n\ninstance (SingI s, Container Vector a, Container Matrix a, Num a) => Num (HMat a s) where\n (+) = unsafeZipH add add\n (*) = unsafeZipH (VS.zipWith (*)) (liftMatrix2 (VS.zipWith (*)))\n (-) = unsafeZipH (VS.zipWith (-)) (liftMatrix2 (VS.zipWith (-)))\n negate = unsafeMapH (scale (-1)) (scale (-1))\n abs = unsafeMapH (cmap abs) (cmap abs)\n signum = unsafeMapH (cmap signum) (cmap signum)\n fromInteger = case (sing :: Sing s) of\n SBV n -> HMV . flip konst (fromIntegral (fromSing n)) . fromInteger\n SBM n m -> HMM . flip konst (fromIntegral (fromSing n)\n ,fromIntegral (fromSing m)\n ) . fromInteger\n\n\n-- | WARNING!! Functions should assume equal sized inputs and return\n-- outputs of the same size! This is not checked!!!\nunsafeZipH\n :: (Vector a -> Vector a -> Vector a)\n -> (Matrix a -> Matrix a -> Matrix a)\n -> HMat a s -> HMat a s -> HMat a s\nunsafeZipH f g = \\case\n HMV x -> \\case\n HMV y -> HMV $ f x y\n HMM x -> \\case\n HMM y -> HMM $ g x y\n\n-- | WARNING!! Functions should return outputs of the same size! This is\n-- not checked!!!\nunsafeMapH\n :: (Vector a -> Vector a)\n -> (Matrix a -> Matrix a)\n -> HMat a s -> HMat a s\nunsafeMapH f g = \\case\n HMV x -> HMV $ f x\n HMM x -> HMM $ g x\n\nliftB'\n :: (Numeric a)\n => Sing s\n -> (Vec n a -> a)\n -> Vec n (HMat a s)\n -> HMat a s\nliftB' s f xs = bgen s $ \\i -> f (indexB i <$> xs)\n{-# INLINE liftB' #-}\n\ninstance (Container Vector a, Numeric a) => BLAS (HMat a) where\n type ElemB (HMat a) = a\n\n -- TODO: rewrite rules\n -- write in parallel?\n liftB\n :: forall n s. ()\n => Sing s\n -> (Vec n a -> a)\n -> Vec n (HMat a s)\n -> HMat a s\n liftB s f = \\case\n ØV -> case s of\n SBV sN -> HMV $ konst (f ØV) ( fromIntegral (fromSing sN) )\n SBM sN sM -> HMM $ konst (f ØV) ( fromIntegral (fromSing sN)\n , fromIntegral (fromSing sM)\n )\n I x :* ØV -> case x of\n HMV x' -> HMV (cmap (f . (:* ØV) . I) x')\n HMM x' -> HMM (cmap (f . (:* ØV) . I) x')\n I x :* I y :* ØV -> case x of\n HMV x' -> case y of\n HMV y' -> HMV $ VS.zipWith (curryV2' f) x' y'\n HMM x' -> case y of\n HMM y' -> HMM $ liftMatrix2 (VS.zipWith (curryV2' f)) x' y'\n xs@(I x :* I y :* I z :* ØV) -> case x of\n HMV x' -> case y of\n HMV y' -> case z of\n HMV z' -> HMV $ VS.zipWith3 (curryV3' f) x' y' z'\n _ -> liftB' s f xs\n xs@(_ :* _ :* _ :* _ :* _) -> liftB' s f xs\n\n axpy α (HMV x) my\n = HMV\n . maybe id (add . unHMV) my\n . scale α\n $ x\n {-# INLINE axpy #-}\n dot (HMV x) (HMV y)\n = x <.> y\n {-# INLINE dot #-}\n ger (HMV x) (HMV y)\n = HMM $ x `outer` y\n {-# INLINE ger #-}\n gemv α (HMM a) (HMV x) mβy\n = HMV\n . maybe id (\\(β, HMV y) -> add (scale β y)) mβy\n . (a #>)\n . scale α\n $ x\n {-# INLINE gemv #-}\n gemm α (HMM a) (HMM b) mβc\n = HMM\n . maybe id (\\(β, HMM c) -> add (scale β c)) mβc\n . (a <>)\n . scale α\n $ b\n {-# INLINE gemm #-}\n scaleB α = unsafeMapH (scale α) (scale α)\n {-# INLINE scaleB #-}\n addB = unsafeZipH add add\n {-# INLINE addB #-}\n indexB = \\case\n PBV i -> \\case\n HMV x -> x `atIndex` fromInteger (DF.getFinite i)\n PBM i j -> \\case\n HMM x -> x `atIndex` ( fromInteger (DF.getFinite i)\n , fromInteger (DF.getFinite j)\n )\n {-# INLINE indexB #-}\n indexRowB i (HMM x) = HMV (x ! fromInteger (DF.getFinite i))\n {-# INLINE indexRowB #-}\n transpB (HMM x) = HMM (tr x)\n {-# INLINE transpB #-}\n iRowsB f (HMM x) = fmap (HMM . fromRows)\n . traverse (\\(i,r) -> unHMV <$> f (DF.Finite i) (HMV r))\n . zip [0..]\n . toRows\n $ x\n {-# INLINE iRowsB #-}\n iElemsB f = \\case\n HMV x -> fmap (HMV . fromList)\n . traverse (\\(i,e) -> f (PBV (DF.Finite i)) e)\n . zip [0..]\n . LA.toList\n $ x\n HMM x -> fmap (HMM . fromLists)\n . traverse (\\(i,rs) ->\n traverse (\\(j, e) -> f (PBM (DF.Finite i) (DF.Finite j)) e)\n . zip [0..]\n $ rs\n )\n . zip [0..]\n . toLists\n $ x\n {-# INLINE iElemsB #-}\n -- TODO: can be implemented in parallel maybe?\n bgenA = \\case\n SBV sN -> \\f -> fmap (HMV . fromList)\n . traverse (\\i -> f (PBV (DF.Finite i)))\n $ [0 .. fromSing sN - 1]\n SBM sN sM -> \\f -> fmap (HMM . fromLists)\n . traverse (\\(i, js) ->\n traverse (\\j -> f (PBM (DF.Finite i) (DF.Finite j))) js\n )\n . zip [0 .. fromSing sN - 1]\n $ repeat [0 .. fromSing sM - 1]\n {-# INLINE bgenA #-}\n bgenRowsA\n :: forall f n m. (Applicative f, SingI n)\n => (DF.Finite n -> f (HMat a ('BV m)))\n -> f (HMat a ('BM n m))\n bgenRowsA f = fmap (HMM . fromRows)\n . traverse (fmap unHMV . f . DF.Finite)\n $ [0 .. fromSing (sing @Nat @n) - 1]\n {-# INLINE bgenRowsA #-}\n\n eye = HMM . ident . fromIntegral . fromSing\n {-# INLINE eye #-}\n diagB = HMM . diag . unHMV\n {-# INLINE diagB #-}\n getDiagB = HMV . takeDiag . unHMM\n {-# INLINE getDiagB #-}\n traceB = sumElements . takeDiag . unHMM\n {-# INLINE traceB #-}\n sumB = \\case\n HMV xs -> sumElements xs\n HMM xs -> sumElements xs\n {-# INLINE sumB #-}\n", "meta": {"hexsha": "b4ee06313a2f8ef96e5015ace8f1df2ab15426ca", "size": 7850, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/TensorOps/BLAS/HMat.hs", "max_stars_repo_name": "mstksg/tensor-ops", "max_stars_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2016-08-24T06:50:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T00:31:35.000Z", "max_issues_repo_path": "src/TensorOps/BLAS/HMat.hs", "max_issues_repo_name": "mstksg/tensor-ops", "max_issues_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-09-29T06:01:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T10:52:51.000Z", "max_forks_repo_path": "src/TensorOps/BLAS/HMat.hs", "max_forks_repo_name": "mstksg/tensor-ops", "max_forks_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-09-28T05:44:48.000Z", "max_forks_repo_forks_event_max_datetime": "2017-01-30T11:01:34.000Z", "avg_line_length": 33.8362068966, "max_line_length": 89, "alphanum_fraction": 0.474522293, "num_tokens": 2402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5405903592197765}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\n-----------------------------------------------------------------------------\n{- |\nModule : Numeric.LinearAlgebra\nCopyright : (c) Alberto Ruiz 2006-15\nLicense : BSD3\nMaintainer : Alberto Ruiz\nStability : provisional\n\n\n-}\n-----------------------------------------------------------------------------\nmodule Numeric.LinearAlgebra (\n\n -- * Basic types and data manipulation\n -- | This package works with 2D ('Matrix') and 1D ('Vector')\n -- arrays of real ('R') or complex ('C') double precision numbers.\n -- Single precision and machine integers are also supported for\n -- basic arithmetic and data manipulation.\n module Numeric.LinearAlgebra.Data,\n\n -- * Numeric classes\n -- |\n -- The standard numeric classes are defined elementwise (commonly referred to\n -- as the Hadamard product or the Schur product):\n --\n -- >>> vector [1,2,3] * vector [3,0,-2]\n -- [3.0,0.0,-6.0]\n -- it :: Vector R\n --\n -- >>> matrix 3 [1..9] * ident 3\n -- (3><3)\n -- [ 1.0, 0.0, 0.0\n -- , 0.0, 5.0, 0.0\n -- , 0.0, 0.0, 9.0 ]\n\n -- * Autoconformable dimensions\n -- |\n -- In most operations, single-element vectors and matrices\n -- (created from numeric literals or using 'scalar'), and matrices\n -- with just one row or column, automatically\n -- expand to match the dimensions of the other operand:\n --\n -- >>> 5 + 2*ident 3 :: Matrix Double\n -- (3><3)\n -- [ 7.0, 5.0, 5.0\n -- , 5.0, 7.0, 5.0\n -- , 5.0, 5.0, 7.0 ]\n --\n -- >>> (4><3) [1..] + row [10,20,30]\n -- (4><3)\n -- [ 11.0, 22.0, 33.0\n -- , 14.0, 25.0, 36.0\n -- , 17.0, 28.0, 39.0\n -- , 20.0, 31.0, 42.0 ]\n --\n\n -- * Products\n -- ** Dot\n dot, (<.>),\n -- ** Matrix-vector\n (#>), (<#), (!#>),\n -- ** Matrix-matrix\n (<>),\n -- | The matrix product is also implemented in the \"Data.Monoid\" instance, where\n -- single-element matrices (created from numeric literals or using 'scalar')\n -- are used for scaling.\n --\n -- >>> import Data.Monoid as M\n -- >>> let m = matrix 3 [1..6]\n -- >>> m M.<> 2 M.<> diagl[0.5,1,0]\n -- (2><3)\n -- [ 1.0, 4.0, 0.0\n -- , 4.0, 10.0, 0.0 ]\n --\n -- 'mconcat' uses 'optimiseMult' to get the optimal association order.\n\n\n -- ** Other\n outer, kronecker, cross,\n scale, add,\n sumElements, prodElements,\n\n -- * Linear systems\n -- ** General\n (<\\>),\n linearSolveLS,\n linearSolveSVD,\n -- ** Determined\n linearSolve,\n luSolve, luPacked,\n luSolve', luPacked',\n -- ** Symmetric indefinite\n ldlSolve, ldlPacked,\n -- ** Positive definite\n cholSolve,\n -- ** Triangular\n UpLo(..),\n triSolve,\n -- ** Tridiagonal\n triDiagSolve,\n -- ** Sparse\n cgSolve,\n cgSolve',\n\n -- * Inverse and pseudoinverse\n inv, pinv, pinvTol,\n\n -- * Determinant and rank\n rcond, rank,\n det, invlndet,\n\n -- * Norms\n Normed(..),\n norm_Frob, norm_nuclear,\n\n -- * Nullspace and range\n orth,\n nullspace, null1, null1sym,\n\n -- * Singular value decomposition\n svd,\n thinSVD,\n compactSVD,\n compactSVDTol,\n singularValues,\n leftSV, rightSV,\n\n -- * Eigendecomposition\n eig, geig, eigSH,\n eigenvalues, geigenvalues, eigenvaluesSH,\n geigSH,\n\n -- * QR\n qr, thinQR, rq, thinRQ, qrRaw, qrgr,\n\n -- * Cholesky\n chol, mbChol,\n\n -- * LU\n lu, luFact,\n\n -- * Hessenberg\n hess,\n\n -- * Schur\n schur,\n\n -- * Matrix functions\n expm,\n sqrtm,\n matFunc,\n\n -- * Correlation and convolution\n corr, conv, corrMin, corr2, conv2,\n\n -- * Random arrays\n\n Seed, RandDist(..), randomVector, rand, randn, gaussianSample, uniformSample,\n\n -- * Misc\n meanCov, rowOuters, pairwiseD2, normalize, peps, relativeError, magnit,\n haussholder, optimiseMult, udot, nullspaceSVD, orthSVD, ranksv,\n iC, sym, mTm, trustSym, unSym,\n -- * Auxiliary classes\n Element, Container, Product, Numeric, LSDiv, Herm,\n Complexable, RealElement,\n RealOf, ComplexOf, SingleOf, DoubleOf,\n IndexOf,\n Field, Linear(), Additive(),\n Transposable,\n LU(..),\n LDL(..),\n QR(..),\n CGState(..),\n Testable(..)\n) where\n\nimport Numeric.LinearAlgebra.Data\n\nimport Numeric.Matrix()\nimport Numeric.Vector()\nimport Internal.Matrix\nimport Internal.Container hiding ((<>))\nimport Internal.Numeric hiding (mul)\nimport Internal.Algorithms hiding (linearSolve,Normed,orth,luPacked',linearSolve',luSolve',ldlPacked')\nimport qualified Internal.Algorithms as A\nimport Internal.Util\nimport Internal.Random\nimport Internal.Sparse((!#>))\nimport Internal.CG\nimport Internal.Conversion\n#if MIN_VERSION_base(4,11,0)\nimport Prelude hiding ((<>))\n#endif\n\n{- | dense matrix product\n\n>>> let a = (3><5) [1..]\n>>> a\n(3><5)\n [ 1.0, 2.0, 3.0, 4.0, 5.0\n , 6.0, 7.0, 8.0, 9.0, 10.0\n , 11.0, 12.0, 13.0, 14.0, 15.0 ]\n\n>>> let b = (5><2) [1,3, 0,2, -1,5, 7,7, 6,0]\n>>> b\n(5><2)\n [ 1.0, 3.0\n , 0.0, 2.0\n , -1.0, 5.0\n , 7.0, 7.0\n , 6.0, 0.0 ]\n\n>>> a <> b\n(3><2)\n [ 56.0, 50.0\n , 121.0, 135.0\n , 186.0, 220.0 ]\n\n-}\n(<>) :: Numeric t => Matrix t -> Matrix t -> Matrix t\n(<>) = mXm\ninfixr 8 <>\n\n\n{- | Solve a linear system (for square coefficient matrix and several right-hand sides) using the LU decomposition, returning Nothing for a singular system. For underconstrained or overconstrained systems use 'linearSolveLS' or 'linearSolveSVD'.\n\n@\na = (2><2)\n [ 1.0, 2.0\n , 3.0, 5.0 ]\n@\n\n@\nb = (2><3)\n [ 6.0, 1.0, 10.0\n , 15.0, 3.0, 26.0 ]\n@\n\n>>> linearSolve a b\nJust (2><3)\n [ -1.4802973661668753e-15, 0.9999999999999997, 1.999999999999997\n , 3.000000000000001, 1.6653345369377348e-16, 4.000000000000002 ]\n\n>>> let Just x = it\n>>> disp 5 x\n2x3\n-0.00000 1.00000 2.00000\n 3.00000 0.00000 4.00000\n\n>>> a <> x\n(2><3)\n [ 6.0, 1.0, 10.0\n , 15.0, 3.0, 26.0 ]\n\n-}\nlinearSolve m b = A.mbLinearSolve m b\n\n-- | return an orthonormal basis of the null space of a matrix. See also 'nullspaceSVD'.\nnullspace m = nullspaceSVD (Left (1*eps)) m (rightSV m)\n\n-- | return an orthonormal basis of the range space of a matrix. See also 'orthSVD'.\north m = orthSVD (Left (1*eps)) m (leftSV m)\n\n", "meta": {"hexsha": "9670187c4f7d4c55ef8f2fffe01b4bfc33e595c5", "size": 6258, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra.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.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.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": 23.1777777778, "max_line_length": 245, "alphanum_fraction": 0.5675934803, "num_tokens": 2196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.540392014114548}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Foreign.VMath.VFloating\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Vector Floating operations.\n--\n\nmodule Foreign.VMath.VFloating (\n VFloating(..)\n ) where\n \nimport Foreign( Ptr, Storable, peek, poke, advancePtr )\nimport Data.Complex( Complex(..) )\n\nimport Foreign.VMath.VFractional\nimport Foreign.VMath.Double \nimport Foreign.VMath.Zomplex\n\n-- | Types with vectorized 'Floating' operations.\nclass (VFractional a, Floating a) => VFloating a where\n vExp :: Int -> Ptr a -> Ptr a -> IO ()\n vSqrt :: Int -> Ptr a -> Ptr a -> IO ()\n vLog :: Int -> Ptr a -> Ptr a -> IO () \n vPow :: Int -> Ptr a -> Ptr a -> Ptr a -> IO () \n vSin :: Int -> Ptr a -> Ptr a -> IO () \n vCos :: Int -> Ptr a -> Ptr a -> IO () \n vTan :: Int -> Ptr a -> Ptr a -> IO () \n vASin :: Int -> Ptr a -> Ptr a -> IO () \n vACos :: Int -> Ptr a -> Ptr a -> IO () \n vATan :: Int -> Ptr a -> Ptr a -> IO () \n vSinh :: Int -> Ptr a -> Ptr a -> IO () \n vCosh :: Int -> Ptr a -> Ptr a -> IO () \n vTanh :: Int -> Ptr a -> Ptr a -> IO () \n vASinh :: Int -> Ptr a -> Ptr a -> IO () \n vACosh :: Int -> Ptr a -> Ptr a -> IO () \n vATanh :: Int -> Ptr a -> Ptr a -> IO ()\n\n vExp = vop exp\n vSqrt = vop sqrt\n vLog = vop log\n vPow = vop2 (**)\n vSin = vop sin\n vCos = vop cos\n vTan = vop tan\n vASin = vop asin\n vACos = vop acos\n vATan = vop atan\n vSinh = vop sinh\n vCosh = vop cosh\n vTanh = vop tanh\n vASinh = vop asinh\n vACosh = vop acosh\n vATanh = vop atanh\n \n \nvop :: (Storable a, Storable b)\n => (a -> b) -> Int -> Ptr a -> Ptr b -> IO ()\nvop f n src dst | n <= 0 = return ()\n | otherwise = do\n a <- peek src\n poke dst $ f a\n vop f (n-1) (src `advancePtr` 1) (dst `advancePtr` 1)\n{-# INLINE vop #-}\n\nvop2 :: (Storable a1, Storable a2, Storable b)\n => (a1 -> a2 -> b) -> Int -> Ptr a1 -> Ptr a2 -> Ptr b -> IO ()\nvop2 f n src1 src2 dst | n <= 0 = return ()\n | otherwise = do\n a1 <- peek src1\n a2 <- peek src2\n poke dst $ f a1 a2\n vop2 f (n-1) (src1 `advancePtr` 1) (src2 `advancePtr` 1)\n (dst `advancePtr` 1)\n{-# INLINE vop2 #-}\n \ninstance VFloating Double where\n vExp = vdExp\n {-# INLINE vExp #-}\n vSqrt = vdSqrt\n {-# INLINE vSqrt #-}\n vLog = vdLog\n {-# INLINE vLog #-}\n vPow = vdPow\n {-# INLINE vPow #-}\n vSin = vdSin\n {-# INLINE vSin #-}\n vCos = vdCos\n {-# INLINE vCos #-}\n vTan = vdTan\n {-# INLINE vTan #-}\n vASin = vdASin\n {-# INLINE vASin #-}\n vACos = vdACos\n {-# INLINE vACos #-}\n vATan = vdATan\n {-# INLINE vATan #-}\n vSinh = vdSinh\n {-# INLINE vSinh #-}\n vCosh = vdCosh\n {-# INLINE vCosh #-}\n vTanh = vdTanh\n {-# INLINE vTanh #-}\n vASinh = vdASinh\n {-# INLINE vASinh #-}\n vACosh = vdACosh\n {-# INLINE vACosh #-}\n vATanh = vdATanh\n {-# INLINE vATanh #-}\n\n\ninstance VFloating (Complex Double) where\n vSqrt = vzSqrt\n {-# INLINE vSqrt #-}\n vLog = vzLog\n {-# INLINE vLog #-}\n \n {- These functions have branch cuts in the wrong places \n vExp = vzExp\n {-# INLINE vExp #-}\n vPow = vzPow\n {-# INLINE vPow #-}\n vSin = vzSin\n {-# INLINE vSin #-}\n vCos = vzCos\n {-# INLINE vCos #-}\n vTan = vzTan\n {-# INLINE vTan #-}\n vASin = vzASin\n {-# INLINE vASin #-}\n vACos = vzACos\n {-# INLINE vACos #-}\n vATan = vzATan\n {-# INLINE vATan #-}\n vSinh = vzSinh\n {-# INLINE vSinh #-}\n vCosh = vzCosh\n {-# INLINE vCosh #-}\n vTanh = vzTanh\n {-# INLINE vTanh #-}\n vASinh = vzASinh\n {-# INLINE vASinh #-}\n vACosh = vzACosh\n {-# INLINE vACosh #-}\n vATanh = vzATanh\n {-# INLINE vATanh #-}\n -}\n", "meta": {"hexsha": "c4f73f50b00312bcb244865861ae22d815b14ee1", "size": 4207, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Foreign/VMath/VFloating.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/VMath/VFloating.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/VMath/VFloating.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.6776315789, "max_line_length": 77, "alphanum_fraction": 0.4844307107, "num_tokens": 1337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5402005821041629}} {"text": "module Parser (\n readExpr\n )\n where\n\nimport Text.ParserCombinators.Parsec hiding (spaces)\nimport System.Environment\nimport Control.Monad\nimport Numeric (readOct, readHex, readFloat)\nimport Data.Char (digitToInt)\nimport Data.Ratio ((%), Rational)\nimport Data.Complex (Complex (..))\n\n\ndata LispVal = Atom String\n | List [LispVal]\n | DottedList [LispVal] LispVal\n | Integer Integer\n | String String\n | Bool Bool\n | Ratio Rational\n | Complex (Complex Float)\n | Float Float\n | Character Char\n deriving (Eq, Show)\n\n\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+-/:<=>?@^_~\"\n\nspaces :: Parser ()\nspaces = skipMany1 space\n\nmyEscapes :: Parser Char\nmyEscapes = do\n char '\\\\'\n char_escaped <- oneOf ['\"', 'n', 't', 'r', '\\\\']\n return $ case char_escaped of\n '\\\\' -> '\\\\'\n '\"' -> '\"'\n 'n' -> '\\n'\n 'r' -> '\\r'\n 't' -> '\\t'\n\n-- test escaping quotes with: \"\\\"\\\\\\\"\\\"\" hahaha\nparseString :: Parser LispVal\nparseString = do\n char '\"'\n x <- many (myEscapes <|> noneOf ['\\\\', '\"']) \n char '\"'\n return $ String x\n\nparseAtom :: Parser LispVal\nparseAtom = do \n first <- letter <|> symbol\n rest <- many (letter <|> digit <|> symbol)\n let atom = first:rest\n return $ case atom of\n \"#t\" -> Bool True\n \"#f\" -> Bool False\n _ -> Atom atom\n\n\nparseDecimal :: Parser LispVal\nparseDecimal = liftM (Integer . read) $ many1 digit\n\nreadBinRec :: [Int] -> Integer\nreadBinRec (lsb : rest) = (toInteger lsb) + 2 * readBinRec rest\nreadBinRec [] = 0\n\nreadBinReal :: String -> Integer\nreadBinReal = readBinRec . reverse . map digitToInt\n\nparseBinary :: Parser LispVal\nparseBinary = liftM (Integer. readBinReal) $ many1 (oneOf \"01\")\n\nreadOctReal :: String -> Integer\nreadOctReal s = fst ((readOct s) !! 0)\nparseOctal :: Parser LispVal\nparseOctal = liftM (Integer . readOctReal) $ many1 (oneOf \"01234567\")\n\nreadHexReal :: String -> Integer\nreadHexReal s = fst ((readHex s) !! 0)\nparseHex :: Parser LispVal\nparseHex = liftM (Integer . readHexReal) $ many1 (oneOf \"0123456789ABCDEFabcdef\")\n\nparsePrefixedNumber :: Parser LispVal\nparsePrefixedNumber = do\n char '#'\n radix <- oneOf ['b', 'o', 'd', 'x']\n case radix of\n 'b' -> parseBinary\n 'o' -> parseOctal\n 'd' -> parseDecimal\n 'x' -> parseHex\n\nparseFloat :: Parser LispVal\nparseFloat = do\n whole_num <- many1 digit\n char '.'\n fractional_bit <- many1 digit\n return . Float . fst $ (readFloat (whole_num ++ \".\" ++ fractional_bit) !! 0 )\n\nparseRational :: Parser LispVal\nparseRational = do\n top <- many1 digit\n char '/'\n bottom <- many1 digit\n return $ Ratio (read top % read bottom)\n\nfloatCast :: LispVal -> Float\nfloatCast (Float f) = f\nfloatCast (Integer i) = fromIntegral i\n\nparseComplex :: Parser LispVal\nparseComplex = do\n first_bit <- try parseFloat <|> parseDecimal\n char '+'\n second_bit <- try parseFloat <|> parseDecimal\n char 'i'\n (return . Complex) ((floatCast first_bit) :+ (floatCast second_bit))\n\n-- #b (binary), #o (octal), #d (decimal), and #x (hexadecimal)\nparseNumber :: Parser LispVal\nparseNumber =\n try parseRational\n <|> try parseComplex\n <|> try parseFloat\n <|> try parsePrefixedNumber\n <|> parseDecimal\n\n{-\nparseNumber' :: Parser LispVal\nparseNumber' = do\n digits <- many1 digit\n return ((Number . read) digits)\n\nparseNumber'' :: Parser LispVal\nparseNumber'' = many1 digit >>= (return . Number . read)\n-}\n\n{-Characters are objects that represent printed characters such as letters and digits. Characters are written using the notation #\\ or #\\. For example:\n\n#\\a\t; lower case letter\n#\\A\t; upper case letter\n#\\(\t; left parenthesis\n#\\\t; the space character\n#\\space\t; the preferred way to write a space\n#\\newline\t; the newline character\nCase is significant in #\\, but not in #\\. If in #\\ is alphabetic, then the character following must be a delimiter character such as a space or parenthesis. This rule resolves the ambiguous case where, for example, the sequence of characters ``#\\space'' could be taken to be either a representation of the space character or a representation of the character ``#\\s'' followed by a representation of the symbol ``pace.''\n\nCharacters written in the #\\ notation are self-evaluating. That is, they do not have to be quoted in programs. Some of the procedures that operate on characters ignore the difference between upper case and lower case. The procedures that ignore case have ``-ci'' (for ``case insensitive'') embedded in their names.\n-}\nparseChar :: Parser LispVal\nparseChar = do\n char '#' >> char '\\\\'\n rest <- (string \"space\") <|> (string \"newline\") <|> (anyChar >>= (\\x -> return [x]))\n return (Character $ case rest of\n \"space\" -> ' '\n \"newline\" -> '\\n'\n c -> c !! 0)\n\nparseList :: Parser LispVal\nparseList = liftM List $ sepBy parseExpr spaces\n\nparseDottedList :: Parser LispVal\nparseDottedList = do\n head <- endBy parseExpr spaces\n tail <- char '.' >> spaces >> parseExpr\n return $ DottedList head tail\n\nparseQuoted :: Parser LispVal\nparseQuoted = do\n char '\\''\n x <- parseExpr\n return $ List [Atom \"quote\", x]\n\n{-parseQuasiQuoted :: Parser LispVal\nparseQuasiQuoted = do\n char '`'\n x <- parseExpr\n return $ List [Atom \"quote\", x]-}\nparseExpr :: Parser LispVal\nparseExpr = try parseAtom\n <|> try parseChar\n <|> try parseNumber\n <|> try parseString\n <|> try parseQuoted\n <|> do char '('\n x <- try parseList <|> parseDottedList\n char ')'\n return x\n\nreadExpr :: String -> String\nreadExpr input = case parse parseExpr \"lisp\" input of\n Left err -> \"No match: \" ++ show err ++ \", input: \" ++ input\n Right val -> \"Found value: \" ++ show val\n", "meta": {"hexsha": "31d35699abe1202b2312a7748f46531d69341b20", "size": 5823, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Parser.hs", "max_stars_repo_name": "laudiacay/write-you-a-scheme", "max_stars_repo_head_hexsha": "6ccc64fa3e55d5d0e6dd3ff089daa8470ff64ed9", "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/Parser.hs", "max_issues_repo_name": "laudiacay/write-you-a-scheme", "max_issues_repo_head_hexsha": "6ccc64fa3e55d5d0e6dd3ff089daa8470ff64ed9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Parser.hs", "max_forks_repo_name": "laudiacay/write-you-a-scheme", "max_forks_repo_head_hexsha": "6ccc64fa3e55d5d0e6dd3ff089daa8470ff64ed9", "max_forks_repo_licenses": ["BSD-3-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.4090909091, "max_line_length": 481, "alphanum_fraction": 0.645715267, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.539725536361021}} {"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule DFTPinwheel where\n\nimport Control.Monad as M\nimport qualified Data.Array.Accelerate as A\nimport Data.Array.Accelerate.LLVM.PTX\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Storable as VS\nimport Data.Vector.Unboxed as VU\nimport DFT.Plan\nimport Filter.Utils\nimport Foreign.CUDA.Driver as CUDA\nimport FourierMethod.BlockCudaMatrix\nimport FourierMethod.FourierSeries2D\nimport Image.IO\nimport Pinwheel.Base\nimport Pinwheel.FourierSeries2D\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport System.Random\nimport Utils.SimpsonRule\nimport Utils.Array\nimport Numeric.GSL.Special.Bessel\nimport Utils.Distribution\n\nmain = do\n args@(deviceIDsStr:numPointsStr:numR2FreqStr:deltaStr:deltaReconStr:periodR2Str:angularFreqStr:radialFreqStr:sigmaStr:periodEnvelopeStr:stdStr:numBatchStr:_) <-\n getArgs\n let deviceIDs = read deviceIDsStr :: [Int]\n numPoints = read numPointsStr :: Int\n numR2Freqs = read numR2FreqStr :: Int\n delta = read deltaStr :: Double\n deltaRecon = read deltaReconStr :: Double\n periodR2 = read periodR2Str :: Double\n angularFreq = read angularFreqStr :: Int\n radialFreq = read radialFreqStr :: Int\n sigma = read sigmaStr :: Double\n periodEnvelope = read periodEnvelopeStr :: Double\n std = read stdStr :: Double\n numBatch = read numBatchStr :: Int\n folderPath = \"output/test/DFTPinwheel\"\n removePathForcibly folderPath\n createDirectoryIfMissing True folderPath\n initialise []\n devs <- M.mapM device deviceIDs\n ctxs <- M.mapM (\\dev -> CUDA.create dev []) devs\n ptxs <- M.mapM createTargetFromContext ctxs\n let center = div numPoints 2\n pinwheel =\n computeUnboxedS . R.fromFunction (Z :. numPoints :. numPoints) $ \\(Z :. x :. y) ->\n fourierMellinInvPeriod\n sigma\n (periodEnvelope * sqrt 2)\n angularFreq\n radialFreq\n ( deltaRecon * fromIntegral (x - center)\n , deltaRecon * fromIntegral (y - center))\n pinwheelMat =\n CuMat (numPoints ^ 2) 1 . CuVecHost . VU.convert . toUnboxed $ pinwheel\n centerFreq = div numR2Freqs 2\n -- pinwheelFreq =\n -- computeUnboxedS . R.fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. x :. y) ->\n -- fourierMellin\n -- sigma\n -- angularFreq\n -- radialFreq\n -- ( delta * fromIntegral (x - centerFreq)\n -- , delta * fromIntegral (y - centerFreq))\n -- pinwheelFreqMat =\n -- CuMat 1 (numR2Freqs ^ 2) . CuVecHost . VU.convert . toUnboxed $ -- . computeS . weightedArray\n -- pinwheelFreq\n -- invHarmonics <-\n -- createInverseHarmonicMatriesGPU ptxs 1 numPoints numR2Freqs periodR2 delta\n -- pinwheelCoef <-\n -- computeFourierCoefficientsR2Stream\n -- deviceIDs\n -- ptxs\n -- numR2Freqs\n -- numPoints\n -- periodR2\n -- delta\n -- 1\n -- numBatch\n -- [pinwheelMat]\n -- pinwheelFreqSeries <-\n -- computeFourierSeriesR2\n -- deviceIDs\n -- numR2Freqs\n -- numPoints\n -- periodR2\n -- invHarmonics\n -- [pinwheelFreqMat]\n plotImageRepaComplex (folderPath \"Pinwheel.png\") .\n ImageRepa 8 .\n computeS . extend (Z :. (1 :: Int) :. All :. All) . R.traverse pinwheel id $ \\f idx@(Z :. i :. j) ->\n let x = fromIntegral $ i - center\n y = fromIntegral $ j - center\n r = sqrt $ x ^ 2 + y ^ 2\n -- if r <= 6\n -- then 0\n -- else\n in f idx\n -- plotImageRepaComplex (folderPath \"PinwheelTest.png\") .\n -- ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n -- pinwheelTest\n -- plotImageRepaComplex (folderPath \"PinwheelCoefficients.png\") .\n -- ImageRepa 8 . computeS . R.traverse pinwheelCoef id $ \\f idx@(Z :. _ :. i :. j) ->\n -- let x = fromIntegral $ i - div numR2Freqs 2\n -- y = fromIntegral $ j - div numR2Freqs 2\n -- r = sqrt $ x ^ 2 + y ^ 2\n -- in if r <= 0\n -- then 0\n -- else f idx\n -- plotImageRepaComplex (folderPath \"PinwheelFrequency.png\") .\n -- ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n -- pinwheelFreq\n -- plotImageRepaComplex (folderPath \"PinwheelFrequencySeries.png\") .\n -- ImageRepa 8 $\n -- pinwheelFreqSeries\n initVec <-\n (VS.fromList . L.map (\\x -> x :+ 0)) <$>\n M.replicateM (numPoints ^ 2) randomIO\n lock <- getFFTWLock\n plan <-\n fst <$> idft1dGPlan lock emptyPlan [numPoints, numPoints] [0, 1] initVec\n -- dftPinwheel <-\n -- dftExecute plan (DFTPlanID IDFT1DG [numPoints, numPoints] [0, 1]) .\n -- VU.convert . toUnboxed . computeUnboxedS . makeFilter2D $\n -- pinwheel\n -- plotImageRepaComplex (folderPath \"DFTPinwheel.png\") .\n -- ImageRepa 8 .\n -- computeUnboxedS .\n -- makeFilter2D .\n -- fromUnboxed (Z :. (1 :: Int) :. numPoints :. numPoints) . VS.convert $\n -- dftPinwheel\n let centerR2Freq = div numR2Freqs 2\n gaussian2D =\n computeUnboxedS . fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i' :. j') ->\n let i = i' - centerR2Freq\n j = j' - centerR2Freq\n rho = (sqrt . fromIntegral $ i ^ 2 + j ^ 2) / periodR2 * 2*pi\n in (-- rho ^ (abs angularFreq) *\n exp\n (pi * fromIntegral (i ^ 2 + j ^ 2) /\n ((-1) * periodR2 ^ 2 * std ^ 2)) /\n (2 * pi * std ^ 2)) :+\n 0\n -- pinwheelFreqAnaticalNonGaussian =\n -- centerHollowArray numR2Freqs . computeUnboxedS $\n -- analyticalFourierCoefficients2\n -- numR2Freqs\n -- delta\n -- angularFreq\n -- radialFreq\n -- (-sigma) --(sigma - 1)\n -- periodR2\n -- (periodEnvelope * sqrt 2)\n pinwheelFreqAnatical =\n centerHollowArray numR2Freqs .\n computeUnboxedS \n -- . R.zipWith (*) gaussian2D \n $\n analyticalFourierCoefficients2\n numR2Freqs\n delta\n angularFreq\n radialFreq\n (-sigma) --(sigma - 1)\n periodR2\n (periodEnvelope * sqrt 2)\n -- pinwheelFreqAnaticalMat =\n -- A.use .\n -- A.fromList (A.Z A.:. (numR2Freqs ^ 2) A.:. (1 :: Int)) . R.toList $\n -- pinwheelFreqAnatical\n -- pinwheelFreqAnaticalInner =\n -- centerHollowArray numR2Freqs . computeUnboxedS $\n -- analyticalFourierCoefficients2'\n -- numR2Freqs\n -- (1 / fromIntegral (div numR2Freqs 2))\n -- angularFreq\n -- radialFreq\n -- (-sigma)\n -- periodR2\n -- (periodEnvelope * sqrt 2)\n -- pinwheelFreqAnaticalInnerMat =\n -- A.use .\n -- A.fromList (A.Z A.:. (numR2Freqs ^ 2) A.:. (1 :: Int)) . R.toList $\n -- pinwheelFreqAnaticalInner\n -- pinwheelFreqSeriesAnatical =\n -- computeUnboxedS $\n -- analyticalFourierSeries1\n -- numPoints\n -- 1 -- delta\n -- angularFreq\n -- radialFreq\n -- (sigma - 1)\n -- periodR2\n plotImageRepaComplex (folderPath \"PinwheelCoefficientsAnalytical.png\") .\n ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n pinwheelFreqAnatical\n -- plotImageRepaComplex\n -- (folderPath \"PinwheelCoefficientsAnalyticalNonGaussian.png\") .\n -- ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n -- pinwheelFreqAnaticalNonGaussian\n -- plotImageRepaComplex\n -- (folderPath \"PinwheelCoefficientsAnalyticalInner.png\") .\n -- ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n -- pinwheelFreqAnaticalInner\n -- plotImageRepaComplex (folderPath \"PinwheelFrequencySeriesAnalytical.png\") .\n -- ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n -- pinwheelFreqSeriesAnatical\n -- pinwheelFreqSeriesStream <-\n -- computeFourierSeriesR2Stream\n -- deviceIDs\n -- ptxs\n -- numR2Freqs\n -- numPoints\n -- periodR2\n -- delta\n -- numBatch\n -- [transposeCuMat pinwheelFreqMat]\n -- plotImageRepaComplex (folderPath \"PinwheelFrequencySeriesStream.png\") .\n -- ImageRepa 8 . computeS . R.traverse pinwheelFreqSeriesStream id $ \\f idx@(Z :. _ :. i :. j) ->\n -- let x = fromIntegral $ i - div numPoints 2\n -- y = fromIntegral $ j - div numPoints 2\n -- r = sqrt $ x ^ 2 + y ^ 2\n -- in if r <= 0\n -- then 0\n -- else f idx\n -- pinwheelCoefficientsAnalyticalSeriesStream <-\n -- computeFourierSeriesR2StreamAcc\n -- ptxs\n -- numR2Freqs\n -- numPoints\n -- 1\n -- periodR2\n -- deltaRecon\n -- numBatch\n -- pinwheelFreqAnaticalMat\n -- -- [ transposeCuMat . createCuMat $\n -- -- [VU.convert . toUnboxed $ pinwheelFreqAnatical]\n -- -- ]\n -- plotImageRepaComplex\n -- (folderPath \"PinwheelCoefficientsAnalyticalSeries.png\") .\n -- ImageRepa 8 .\n -- computeS .\n -- extend (Z :. (1 :: Int) :. All :. All) .\n -- R.traverse (sumS . rotate3D $ pinwheelCoefficientsAnalyticalSeriesStream) id $ \\f idx@(Z :. i :. j) ->\n -- let x = fromIntegral $ i - center\n -- y = fromIntegral $ j - center\n -- r = sqrt $ x ^ 2 + y ^ 2\n -- -- if r <= 6\n -- -- then 0\n -- -- else\n -- in f idx\n pinwheelCoefficientsAnalyticalIDFT <-\n dftExecute plan (DFTPlanID IDFT1DG [numPoints, numPoints] [0, 1]) .\n VU.convert . toUnboxed . computeS . makeFilter2D $\n pinwheelFreqAnatical\n plotImageRepaComplex (folderPath \"PinwheelCozefficientsIDFT.png\") .\n ImageRepa 8 .\n computeS .\n makeFilter2DInverse .\n fromUnboxed (Z :. (1 :: Int) :. numPoints :. numPoints) . VS.convert $\n pinwheelCoefficientsAnalyticalIDFT\n -- pinwheelCoefficientsAnalyticalInnerSeriesStream <-\n -- computeFourierSeriesR2StreamAcc'\n -- ptxs\n -- numR2Freqs\n -- numPoints\n -- 1\n -- periodR2\n -- 1 -- (1 / fromIntegral (div numR2Freqs 2))\n -- numBatch\n -- pinwheelFreqAnaticalMat\n -- plotImageRepaComplex\n -- (folderPath \"PinwheelCoefficientsAnalyticalInnverSeries.png\") .\n -- ImageRepa 8 .\n -- computeS . extend (Z :. (1 :: Int) :. All :. All) . sumS . rotate3D $\n -- pinwheelCoefficientsAnalyticalInnerSeriesStream\n -- plotImageRepaComplex\n -- (folderPath \"PinwheelCoefficientsAnalyticalSumSeries.png\") .\n -- ImageRepa 8 .\n -- computeS . extend (Z :. (1 :: Int) :. All :. All) . sumS . rotate3D $\n -- R.zipWith\n -- (+)\n -- pinwheelCoefficientsAnalyticalSeriesStream\n -- pinwheelCoefficientsAnalyticalInnerSeriesStream\n -- computeS . R.traverse pinwheelCoefficientsAnalyticalSeriesStream id $ \\f idx@(Z :. _ :. i :. j) ->\n -- let x = fromIntegral $ i - div numPoints 2\n -- y = fromIntegral $ j - div numPoints 2\n -- r = sqrt $ x ^ 2 + y ^ 2\n -- in if r <= 0\n -- then 0\n -- else f idx\n -- -- pinwheelCoefficientsSeriesStream <-\n -- computeFourierSeriesR2Stream\n -- deviceIDs\n -- ptxs\n -- numR2Freqs\n -- numPoints\n -- periodR2\n -- delta\n -- numBatch\n -- [transposeCuMat . createCuMat $ [VU.convert . toUnboxed $ pinwheelCoef]]\n -- plotImageRepaComplex (folderPath \"PinwheelCoefficientsSeriesStream.png\") .\n -- ImageRepa 8 . computeS . R.traverse pinwheelCoefficientsSeriesStream id $ \\f idx@(Z :. _ :. i :. j) ->\n -- let x = fromIntegral $ i - div numPoints 2\n -- y = fromIntegral $ j - div numPoints 2\n -- r = sqrt $ x ^ 2 + y ^ 2\n -- in if r <= 0\n -- then 0\n -- else f idx\n -- let besselFilter =\n -- computeUnboxedS . fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i :. j) ->\n -- let xFreq = fromIntegral $ i - centerFreq\n -- yFreq = fromIntegral $ j - centerFreq\n -- rho = sqrt $ xFreq ^ 2 + yFreq ^ 2\n -- in if rho == 0\n -- then 1\n -- else (bessel_J1 (2 * pi * rho / periodR2)) / rho :+ 0\n -- plotImageRepaComplex (folderPath \"BesselFilter.png\") .\n -- ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n -- besselFilter\n -- initVec1 <-\n -- (VS.fromList . L.map (\\x -> x :+ 0)) <$>\n -- M.replicateM (numR2Freqs ^ 2) randomIO\n -- lock <- getFFTWLock\n -- plan <-\n -- fst <$>\n -- (dft1dGPlan lock emptyPlan [numR2Freqs, numR2Freqs] [0, 1] initVec1 >>= \\(plan, vec) ->\n -- idft1dGPlan lock plan [numR2Freqs, numR2Freqs] [0, 1] vec)\n -- let besselVec =\n -- VU.convert . toUnboxed . computeS . makeFilter2D $ besselFilter\n -- pinwheelFreqAnaticalVec = VU.convert . toUnboxed $ pinwheelFreqAnatical\n -- besselVecF <-\n -- dftExecute plan (DFTPlanID DFT1DG [numR2Freqs, numR2Freqs] [0, 1]) besselVec\n -- pinwheelFreqAnaticalVecF <-\n -- dftExecute\n -- plan\n -- (DFTPlanID DFT1DG [numR2Freqs, numR2Freqs] [0, 1])\n -- pinwheelFreqAnaticalVec\n -- pinwheelFreqAnatical1 <-\n -- fmap (fromUnboxed (Z :. numR2Freqs :. numR2Freqs) . VS.convert) .\n -- dftExecute plan (DFTPlanID IDFT1DG [numR2Freqs, numR2Freqs] [0, 1]) $\n -- VS.zipWith (*) besselVecF pinwheelFreqAnaticalVecF\n -- plotImageRepaComplex\n -- (folderPath \"BesselFilterConveledPinwheelFreqAnatical.png\") .\n -- ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n -- pinwheelFreqAnatical1\n -- let pinwheelFreqAnatical2 =\n -- R.zipWith (-) pinwheelFreqAnatical pinwheelFreqAnatical1\n -- pinwheelFreqAnaticalMat2 =\n -- A.use .\n -- A.fromList (A.Z A.:. (numR2Freqs ^ 2) A.:. (1 :: Int)) . R.toList $\n -- pinwheelFreqAnatical2\n -- plotImageRepaComplex (folderPath \"pinwheelFreqAnatical2.png\") .\n -- ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n -- pinwheelFreqAnatical2\n -- pinwheelCoefficientsAnalyticalSeriesStream2 <-\n -- computeFourierSeriesR2StreamAcc\n -- ptxs\n -- numR2Freqs\n -- numPoints\n -- 1\n -- periodR2\n -- delta\n -- numBatch\n -- pinwheelFreqAnaticalMat2\n -- plotImageRepaComplex\n -- (folderPath \"PinwheelCoefficientsAnalyticalSeries2.png\") .\n -- ImageRepa 8 .\n -- computeS . extend (Z :. (1 :: Int) :. All :. All) . sumS . rotate3D $\n -- pinwheelCoefficientsAnalyticalSeriesStream2\n -- dftPinwheel <-\n -- fmap (fromUnboxed (Z :. numR2Freqs :. numR2Freqs) . VS.convert) .\n -- dftExecute plan (DFTPlanID DFT1DG [numR2Freqs, numR2Freqs] [0, 1]) .\n -- VU.convert . toUnboxed . computeS . makeFilter2D $\n -- pinwheel\n -- let zeroArr =\n -- fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i :. j) ->\n -- if (sqrt . fromIntegral $ (i - centerFreq) ^ 2 + (j - centerFreq) ^ 2) <\n -- 1\n -- then 0\n -- else 1\n -- plotImageRepaComplex (folderPath \"DFTPinwheel.png\") .\n -- ImageRepa 8 .\n -- computeS .\n -- extend (Z :. (1 :: Int) :. All :. All) .\n -- R.zipWith (*) zeroArr . makeFilter2D $\n -- dftPinwheel\n -- let normFunc arr =\n -- let m = VU.maximum . toUnboxed . computeS . R.map magnitude $ arr\n -- in R.map (/ (m :+ 0)) arr\n -- plotImageRepaComplex (folderPath \"Diff.png\") .\n -- ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n -- R.zipWith\n -- (\\a b ->\n -- if magnitude b == 0\n -- then 0\n -- else a / b)\n -- (normFunc . R.zipWith (*) zeroArr . makeFilter2D $ dftPinwheel)\n -- (normFunc . R.zipWith (*) zeroArr $ pinwheelFreqAnatical)\n", "meta": {"hexsha": "d2fbcb573c27bc9484c72c6a0b0f755db196d1e2", "size": 15877, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/DFTPinwheel/DFTPinwheel.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/DFTPinwheel/DFTPinwheel.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/DFTPinwheel/DFTPinwheel.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": 39.0098280098, "max_line_length": 162, "alphanum_fraction": 0.5774390628, "num_tokens": 5183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.539725319418921}} {"text": "{-# LANGUAGE Trustworthy #-}\n-- |\n-- Module : Statistics.Distribution.Hypergeometric.GenVar\n-- Copyright : (c) 2015 Sam Rijs\n-- (c) 2005 Robert Kern\n-- (c) 1998 Ivan Frohne\n-- License : MIT\n--\n-- Maintainer : srijs@airpost.net\n-- Stability : experimental\n--\n\nmodule Statistics.Distribution.Hypergeometric.GenVar (genVar) where\n\nimport Control.Monad.Primitive (PrimMonad, PrimState)\n\nimport Statistics.Distribution (ContGen(..), DiscreteGen(..))\nimport Statistics.Distribution.Hypergeometric (HypergeometricDistribution, hdM, hdL, hdK)\n\nimport Numeric.SpecFunctions (logGamma)\n\nimport System.Random.MWC (Gen, uniform)\n\nd1 = 1.7155277699214135 -- 2*sqrt(2/e)\nd2 = 0.8989161620588988 -- 3 - 2*sqrt(3/e)\n\ninstance ContGen HypergeometricDistribution\n where genContVar d g = return . fromIntegral =<< genVar (hdM d, hdL d, hdK d) g\n\ninstance DiscreteGen HypergeometricDistribution\n where genDiscreteVar d g = genVar (hdM d, hdL d, hdK d) g \n\n-- | Random variates from the hypergeometric distribution /(m, l, k)/.\n-- Returns the number of white balls drawn when /k/ balls\n-- are drawn at random from an urn containing /m/ white\n-- and /l-m/ black balls.\ngenVar :: (PrimMonad m, Integral a) => (a, a, a) -> Gen (PrimState m) -> m a\ngenVar (good, popsize, sample) gen = return . fix2 . fix1 =<< loop\n where fix1 z = if good > bad then m - z else z\n fix2 z = if m < sample then good - z else z\n mingoodbad = min good bad\n bad = popsize - good\n maxgoodbad = max good bad\n m = min sample (popsize - sample)\n gamma z = sum $ map (logGamma . fromIntegral)\n [ z + 1, mingoodbad - z + 1\n , m - z + 1, maxgoodbad - m + z + 1 ]\n d4 = fromIntegral mingoodbad / fromIntegral popsize\n d5 = 1 - d4\n d6 = fromIntegral m * d4 + 0.5\n d7 = sqrt $ fromIntegral (popsize - m) * fromIntegral sample * d4 * d5 / fromIntegral (popsize - 1) + 0.5\n d8 = d1 * d7 + d2\n d9 = floor $ fromIntegral (m + 1) * fromIntegral (mingoodbad + 1) / fromIntegral (popsize + 2)\n d10 = gamma d9\n d11 = fromIntegral $ min (min m mingoodbad + 1) (floor (d6 + 16 * d7))\n -- 16 for 16-decimal-digit precision in d1 and d2\n loop = do\n x <- uniform gen\n y <- uniform gen\n case () of \n _ | w < 0 || w >= d11 -> loop -- fast rejection\n | x * (4 - x) - 3 <= t -> return z -- fast acceptance\n | x * (x - t) >= 1 -> loop -- fast rejection\n | 2 * (log x) <= t -> return z -- acceptance\n | otherwise -> loop -- rejection\n where w = d6 + d8 * (y - 0.5) / x\n z = floor w\n t = d10 - gamma z\n", "meta": {"hexsha": "838b29bad5e32c2a1ce3558e7cb4423a28cf6dc2", "size": 2766, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Distribution/Hypergeometric/GenVar.hs", "max_stars_repo_name": "srijs/statistics-hypergeometric-gen", "max_stars_repo_head_hexsha": "2fa15add0571a0308535dea0914ed03613266d8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-03-26T15:05:49.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-07T15:32:44.000Z", "max_issues_repo_path": "src/Statistics/Distribution/Hypergeometric/GenVar.hs", "max_issues_repo_name": "srijs/statistics-hypergeometric-gen", "max_issues_repo_head_hexsha": "2fa15add0571a0308535dea0914ed03613266d8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Distribution/Hypergeometric/GenVar.hs", "max_forks_repo_name": "srijs/statistics-hypergeometric-gen", "max_forks_repo_head_hexsha": "2fa15add0571a0308535dea0914ed03613266d8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0869565217, "max_line_length": 113, "alphanum_fraction": 0.5831525669, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5394979808214386}} {"text": "{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, FlexibleContexts,\n FlexibleInstances, UndecidableInstances #-}\n-- |\n-- Module : Statistics.Distribution.Transform\n-- Copyright : (c) 2013 John McDonnell;\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Transformations over distributions\nmodule Statistics.Distribution.Transform\n (\n LinearTransform (..)\n , linTransFixedPoint\n , scaleAround\n ) where\n\nimport Data.Aeson (FromJSON, ToJSON)\nimport Control.Applicative ((<*>))\nimport Data.Binary (Binary)\nimport Data.Binary (put, get)\nimport Data.Data (Data, Typeable)\nimport Data.Functor ((<$>))\nimport GHC.Generics (Generic)\nimport qualified Statistics.Distribution as D\n\n-- | Linear transformation applied to distribution.\n--\n-- > LinearTransform μ σ _\n-- > x' = μ + σ·x\ndata LinearTransform d = LinearTransform\n { linTransLocation :: {-# UNPACK #-} !Double\n -- ^ Location parameter.\n , linTransScale :: {-# UNPACK #-} !Double\n -- ^ Scale parameter.\n , linTransDistr :: d\n -- ^ Distribution being transformed.\n } deriving (Eq, Show, Read, Typeable, Data, Generic)\n\ninstance (FromJSON d) => FromJSON (LinearTransform d)\ninstance (ToJSON d) => ToJSON (LinearTransform d)\n\ninstance (Binary d) => Binary (LinearTransform d) where\n get = LinearTransform <$> get <*> get <*> get\n put (LinearTransform x y z) = put x >> put y >> put z\n\n-- | Apply linear transformation to distribution.\nscaleAround :: Double -- ^ Fixed point\n -> Double -- ^ Scale parameter\n -> d -- ^ Distribution\n -> LinearTransform d\nscaleAround x0 sc = LinearTransform (x0 * (1 - sc)) sc\n\n-- | Get fixed point of linear transformation\nlinTransFixedPoint :: LinearTransform d -> Double\nlinTransFixedPoint (LinearTransform loc sc _) = loc / (1 - sc)\n\ninstance Functor LinearTransform where\n fmap f (LinearTransform loc sc dist) = LinearTransform loc sc (f dist)\n\ninstance D.Distribution d => D.Distribution (LinearTransform d) where\n cumulative (LinearTransform loc sc dist) x = D.cumulative dist $ (x-loc) / sc\n\ninstance D.ContDistr d => D.ContDistr (LinearTransform d) where\n density (LinearTransform loc sc dist) x = D.density dist ((x-loc) / sc) / sc\n logDensity (LinearTransform loc sc dist) x = D.logDensity dist ((x-loc) / sc) - log sc\n quantile (LinearTransform loc sc dist) p = loc + sc * D.quantile dist p\n complQuantile (LinearTransform loc sc dist) p = loc + sc * D.complQuantile dist p\n\ninstance D.MaybeMean d => D.MaybeMean (LinearTransform d) where\n maybeMean (LinearTransform loc _ dist) = (+loc) <$> D.maybeMean dist\n\ninstance (D.Mean d) => D.Mean (LinearTransform d) where\n mean (LinearTransform loc _ dist) = loc + D.mean dist\n\ninstance D.MaybeVariance d => D.MaybeVariance (LinearTransform d) where\n maybeVariance (LinearTransform _ sc dist) = (*(sc*sc)) <$> D.maybeVariance dist\n maybeStdDev (LinearTransform _ sc dist) = (*sc) <$> D.maybeStdDev dist\n\ninstance (D.Variance d) => D.Variance (LinearTransform d) where\n variance (LinearTransform _ sc dist) = sc * sc * D.variance dist\n stdDev (LinearTransform _ sc dist) = sc * D.stdDev dist\n\ninstance (D.MaybeEntropy d) => D.MaybeEntropy (LinearTransform d) where\n maybeEntropy (LinearTransform _ _ dist) = D.maybeEntropy dist\n\ninstance (D.Entropy d) => D.Entropy (LinearTransform d) where\n entropy (LinearTransform _ _ dist) = D.entropy dist\n\ninstance D.ContGen d => D.ContGen (LinearTransform d) where\n genContVar (LinearTransform loc sc d) g = do\n x <- D.genContVar d g\n return $! loc + sc * x\n", "meta": {"hexsha": "d0f4643b9633dd480684cb842b0e824438fb8b2d", "size": 3659, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Transform.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-11T23:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T22:33:10.000Z", "max_issues_repo_path": "Statistics/Distribution/Transform.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-02-26T06:10:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:27:01.000Z", "max_forks_repo_path": "Statistics/Distribution/Transform.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": 38.1145833333, "max_line_length": 88, "alphanum_fraction": 0.6898059579, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.538891371264588}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule WeightDecay\n ( input\n , testdata\n , traindata\n , testY\n , testX\n , trainLinRegUnkownTarget\n , trainAndTestWithData\n , trainAndTestWithRegularization\n , makeTransformedMatrix\n , listToTuple'\n ) where\n\nimport Data.Maybe\nimport LinearRegression\nimport Network.HTTP\nimport NonlinearTransform\nimport Numeric.LinearAlgebra.Data\nimport Numeric.LinearAlgebra.HMatrix as HMatrix\n\n--------------------------------------------------------------\n-- Solutions to homework 6 of \"Learning from data\" question 5-6\n--------------------------------------------------------------\ninput http = do\n response <- simpleHTTP $ getRequest http\n let body = fmap rspBody response\n let rows = fmap (map (map readDouble . words) . lines) body\n return rows\n\nreadDouble :: String -> Double\nreadDouble = read\n\nlistToTuple' :: [a] -> Maybe (a, a)\nlistToTuple' (x:y:xs) = Just (x, y)\nlistToTuple' _ = Nothing\n\n-- | downloads the test data\ntestdata = input \"http://work.caltech.edu/data/out.dta\"\n\n-- | downloads the training data\ntraindata = input \"http://work.caltech.edu/data/in.dta\"\n\ntestY = fmap (fmap makeVectorY) testdata\n where\n makeVectorY lists = vector $ map last lists\n\ntestX = makeDataMatrix testdata\n\ntrainY = fmap (fmap makeVectorY) traindata\n where\n makeVectorY lists = vector $ map last lists\n\ntrainX = makeDataMatrix traindata\n\nmakeLabelVector inputdata = fmap (fmap makeVectorY) inputdata\n where\n makeVectorY lists = vector $ map last lists\n\nmakeDataMatrix inputdata = fmap (fmap makeMatrixX) inputdata\n where\n makeMatrixX lists = matrix 3 $ concatMap xvectors lists\n xvectors list = 1 : init list\n\nmakeTransformedMatrix2 inputdata = fmap (fmap makeMatrixX) inputdata\n where\n makeMatrixX lists =\n createTransformedX2 $ map (fromMaybe (0, 0) . listToTuple') lists\n\nmakeTransformedMatrix k inputdata = fmap (fmap makeMatrixX) inputdata\n where\n makeMatrixX lists =\n createTransformedXk k $ map (fromMaybe (0, 0) . listToTuple') lists\n\ntrainXTransformed2 = makeTransformedMatrix2 traindata\n\ntestXTransformed2 = makeTransformedMatrix2 testdata\n\n-- | Trains linear Regression from the data on the course website\ntrainLinRegUnkownTarget = do\n matrixXTrain <- trainXTransformed2\n vectorYTrain <- trainY\n let weights = linearRegressionWeight <$> matrixXTrain <*> vectorYTrain\n let inSampleError =\n linRegClassificationError <$> matrixXTrain <*> vectorYTrain <*> weights\n return (weights, inSampleError)\n\n-- | Tests linear Regression from the data on the course website\ntestLinRegUnkownTarget weights = do\n matrixXTest <- testXTransformed2\n vectorYTest <- testY\n let outOfSampleError =\n linRegClassificationError <$> matrixXTest <*> vectorYTest <*> weights\n return outOfSampleError\n\n-- | solution for question 2: train and test with given data, with nonlinear transformation but without regularization and print the result\ntrainAndTestWithData :: IO ()\ntrainAndTestWithData = do\n (weights, inSampleError) <- trainLinRegUnkownTarget\n outOfSampleError <- testLinRegUnkownTarget weights\n putStr \"In Sample Error: \"\n print inSampleError\n putStr \"Out of Sample Error: \"\n print outOfSampleError\n\n-- | returns the weights determined by linear regression on the training data with regularization\nlinearRegressionWeightReg :: R -> Matrix R -> Vector R -> Vector R\nlinearRegressionWeightReg regParam matrixOfInputData vectorOfLabels =\n inv\n (tr matrixOfInputData HMatrix.<> matrixOfInputData +\n scalar regParam * (ident $fst $size $tr matrixOfInputData)) HMatrix.#>\n (tr matrixOfInputData #> vectorOfLabels)\n\n-- | Trains linear Regression from the data on the course website with regularization\ntrainLinRegWithRegularization regParam = do\n matrixXTrain <- trainXTransformed2\n vectorYTrain <- trainY\n let weights =\n linearRegressionWeightReg regParam <$> matrixXTrain <*> vectorYTrain\n let inSampleError =\n linRegClassificationError <$> matrixXTrain <*> vectorYTrain <*> weights\n return (weights, inSampleError)\n\n-- | performs training and testing with the regularization parameter provided as an input and prints the in-sample and out-of-sample error\ntrainAndTestWithRegularization :: R -> IO ()\ntrainAndTestWithRegularization regParam = do\n (weights, inSampleError) <- trainLinRegWithRegularization regParam\n outOfSampleError <- testLinRegUnkownTarget weights\n putStr \"In Sample Error: \"\n print inSampleError\n putStr \"Out of Sample Error: \"\n print outOfSampleError\n", "meta": {"hexsha": "c21df3e57f13a013dea1094ce0fbb2df056ca469", "size": 4553, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/hw6/WeightDecay.hs", "max_stars_repo_name": "AR2202/LearningFromData", "max_stars_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-18T06:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T06:07:24.000Z", "max_issues_repo_path": "src/hw6/WeightDecay.hs", "max_issues_repo_name": "AR2202/LearningFromData", "max_issues_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hw6/WeightDecay.hs", "max_forks_repo_name": "AR2202/LearningFromData", "max_forks_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_forks_repo_licenses": ["BSD-3-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.9776119403, "max_line_length": 139, "alphanum_fraction": 0.7298484516, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5388714798896519}} {"text": "{-# OPTIONS_HADDOCK prune #-}\nmodule ForSyDe.Atom.Skel.FastVector.DSP where\n\nimport Data.Complex\nimport qualified Data.Number.FixedFunctions as F\nimport ForSyDe.Atom.MoC as MoC\nimport ForSyDe.Atom.Skel.FastVector.Lib as V hiding (duals, unduals)\nimport ForSyDe.Atom.Skel.FastVector.Matrix as M\nimport ForSyDe.Atom ((><))\n\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.taylor'.\ntaylor :: (Eq a, Floating a)\n => Int -- ^ number of points in the output window.\n -> Int -- ^ Number of nearly constant level sidelobes adjacent to the mainlobe\n -> a -- ^ Desired peak sidelobe level in decibels (db) relative to the mainlobe\n -> Vector a -- ^ The window, with the center value normalized to one (the value\n -- one appears only if the number of samples is odd).\ntaylor n nbar level = V.farm11 (*scale) w\n where\n -- explicit conversions to floating\n bN = fromIntegral n\n nBar = fromIntegral nbar\n ma = map fromIntegral [1 .. nbar-1]\n -- calculate intermediate values\n b = 10**((-level) / 20)\n a = log(b + sqrt(b**2 - 1)) / pi\n s2 = nBar ** 2 / (a**2 + (nBar - 0.5)**2)\n -- functions for calculating coefficients\n fmcalc m = let numer = (-1)**(m+1) * product[1.0 - m**2/s2/(a**2 + (j - 0.5)**2) | j <- ma]\n denom = 2 * product[1 - m**2/j**2 | j <- ma, j /= m]\n in numer / denom\n ccalc m x = cos(2 * pi * x * (m - bN/2 + 1/2) / bN)\n wcalc m = 2 * dotvv (vector $ map fmcalc ma) (vector $ map (ccalc m) ma) + 1\n -- calculate window coefficients\n w = vector $ map (wcalc . fromIntegral) [0..n-1]\n -- normalize (Note that this is not described in the original text [1])\n scale = 1 / wcalc (bN - 1) / 2\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.taylor''.\ntaylor' n = taylor 4 (-30)\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.dotvm'.\ndotvm :: Num a => Vector a -> Vector (Vector a) -> Vector a\ndotvm = dotvm' (+) (*)\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.dotvv'.\ndotvv :: Num a => Vector a -> Vector a -> a \ndotvv a b\n | V.length a == V.length b = V.reduce (+) (V.farm21 (*) a b)\n | otherwise = error \"Vector sizes must match\"\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.dotvv''.\ndotvv' :: Num a\n => ((a -> a -> a) -> f a -> f a -> f a)\n -- ^ higher-order function that can wrap the (*) operation.\n -> Vector (f a) -> Vector (f a) -> f a \ndotvv' wrap a b\n | V.length a == V.length b = V.reduce (wrap (+)) $ V.farm21 (wrap (*)) a b\n | otherwise = error \"Vector sizes must match\"\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.dotmv''.\ndotmv' :: (a -> a -> a) -- ^ kernel function for a row/column reduction, e.g. @(+)@ for dot product\n -> (b -> a -> a) -- ^ binary operation for pair-wise elements, e.g. @(*)@ for dot product\n -> Vector (Vector b) -- ^ /size/ = @(xa,ya)@\n -> Vector a -- ^ /length/ = @xa@\n -> Vector a -- ^ /length/ = @xa@\ndotmv' f g mA y = V.farm11 (\\x -> V.reduce f $ V.farm21 g x y) mA\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.dotvm''.\ndotvm' :: (b -> b -> b) -- ^ kernel function for a row/column reduction, e.g. @(+)@ for dot product\n -> (a -> b -> b) -- ^ binary operation for pair-wise elements, e.g. @(*)@ for dot product\n -> Vector a -- ^ /length/ = @xa@\n -> Vector (Vector b) -- ^ /size/ = @(xa,ya)@\n -> Vector b -- ^ /length/ = @ya@\ndotvm' f g vs = V.reduce (V.farm21 f) . V.farm21 (\\x -> V.farm11 (g x)) vs\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.hanning'.\nhanning :: (Floating n) \n => Int -- ^ The length of the window\n -> Vector n\nhanning size = V.farm11 func $ V.vector [0..size-1]\n where\n func idx = let i = fromIntegral idx\n n = fromIntegral size\n in 0.5 * (1 - cos((2 * pi * i) / (n - 1)))\n \n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.hamming'.\nhamming :: (Floating n) \n => Int -- ^ The length of the window\n -> Vector n\nhamming size = V.farm11 func $ V.vector [0..size-1]\n where\n func idx = let i = fromIntegral idx\n n = fromIntegral size\n in 0.54 - 0.46 * cos((2 * pi * i) / (n - 1))\n \n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.blackman'.\nblackman :: (Floating n) \n => Int -- ^ The length of the window\n -> Vector n\nblackman size = V.farm11 func $ V.vector [0..size-1]\n where\n func idx = let i = fromIntegral idx\n n = fromIntegral size\n in 0.42 - 0.5 * cos((2 * pi * i) / (n - 1)) + 0.08 * cos((4 * pi * i) / (n - 1))\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.fir'.\nfir :: Num a\n => Vector a -- ^ vector of coefficients\n -> Vector a -- ^ input vector of numbers; /size/ = @n@\n -> Vector a -- ^ output vector of numbers; /size/ = @n@\nfir coefs = V.reverse . V.farm11 applyFilter . tails . V.reverse\n where\n applyFilter = V.reduce (+) . V.farm21 (*) coefs \n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.fir''.\nfir' :: (a -> a -> a) -- ^ process/operation replacing '+'\n -> (c -> a -> a) -- ^ process/operation replacing '*'\n -> (a -> a) -- ^ delay process\n -> Vector c -- ^ vector of coefficients\n -> a -- ^ input signal/structure \n -> a -- ^ output signal/structure\nfir' plus times delay coefs =\n -- V.reduce plus . V.farm21 (\\c -> times c) coefs . V.recur (V.fanoutn n delay <: id)\n V.reduce plus . V.farm21 times coefs . V.recuri (V.fanoutn n delay)\n where n = V.length coefs - 1\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.twiddles'.\ntwiddles :: Floating a => Int -> V.Vector (Complex a)\ntwiddles bN = (bitrev . V.take (bN `div` 2)) (V.farm11 bW $ vector [0..])\n where bW x = (cis . negate) (-2 * pi * fromIntegral x / fromIntegral bN)\n\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.fft'.\nfft :: RealFloat a\n => Int -> V.Vector (Complex a) -> V.Vector (Complex a)\nfft k vs | n == 2^k = V.reverse $ bitrev $ (stage `V.pipe1` V.iterate k (*2) 2) vs\n | otherwise = error $ \"n=\" ++ show n ++ \"; k=\" ++ show k\n where\n stage w = V.concat . V.farm21 segment (twiddles n) . V.group w\n segment t = (><) unduals . (><) (V.farm22 (butterfly t)) . duals\n n = V.length vs -- length of input\n -------------------------------------------------\n butterfly w x0 x1 = let t = w * x1 in (x0 + t, x0 - t) -- kernel function\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.fft''.\nfft' :: Floating a\n => (Complex a -> a -> a -> (a, a)) \n -> Int -> V.Vector a -> V.Vector a\nfft' butterfly k vs | n == 2^k = bitrev $ (stage `V.pipe1` (V.iterate k (*2) 2)) vs\n where\n stage w = V.concat . V.farm21 segment (twiddles n) . V.group w\n segment t = (><) unduals . (><) (V.farm22 (butterfly t)) . duals\n n = V.length vs -- length of input\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.duals'.\nduals :: Vector a -> (Vector a, Vector a)\nduals v = (V.take k v, V.drop k v)\n where\n k = V.length v `div` 2\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.unduals'.\nunduals :: Vector a -> Vector a -> Vector a\nunduals x y = x <++> y\n\n-- | See 'ForSyDe.Atom.Skel.Vector.DSP.bitrev'.\nbitrev = V.unsafeLift bitrevF\n where\n bitrevF [x] = [x]\n bitrevF xs = bitrevF (V.evensF xs) ++ bitrevF (V.oddsF xs)\n\n", "meta": {"hexsha": "3e86345d0903590b115f015c9d42670cdd798782", "size": 7229, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ForSyDe/Atom/Skel/FastVector/DSP.hs", "max_stars_repo_name": "forsyde/forsyde-atom", "max_stars_repo_head_hexsha": "6b9cc94775fdcc556126cc0f3aa1fd54d05b4491", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-02-22T09:03:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-20T20:19:27.000Z", "max_issues_repo_path": "src/ForSyDe/Atom/Skel/FastVector/DSP.hs", "max_issues_repo_name": "forsyde/forsyde-atom", "max_issues_repo_head_hexsha": "6b9cc94775fdcc556126cc0f3aa1fd54d05b4491", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2016-06-14T16:31:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T22:02:01.000Z", "max_forks_repo_path": "src/ForSyDe/Atom/Skel/FastVector/DSP.hs", "max_forks_repo_name": "forsyde/forsyde-atom", "max_forks_repo_head_hexsha": "6b9cc94775fdcc556126cc0f3aa1fd54d05b4491", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-06-14T15:27:39.000Z", "max_forks_repo_forks_event_max_datetime": "2017-02-18T21:11:18.000Z", "avg_line_length": 41.7861271676, "max_line_length": 103, "alphanum_fraction": 0.5549868585, "num_tokens": 2392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5388287547375181}} {"text": "module Carlson\n (carlsonRF, carlsonRF',\n carlsonRD, carlsonRD',\n carlsonRJ, carlsonRJ',\n carlsonRC, carlsonRC',\n carlsonRG, carlsonRG')\n where\nimport Data.Complex\nimport Internal\n\nrf_ :: Cplx -> Cplx -> Cplx -> Double -> ((Double,Double,Double), Cplx)\nrf_ x y z err =\n let a = (x+y+z)/3 in\n let delta = map (\\u -> magnitude(1-u/a)) [x,y,z] in\n if maximum delta < err\n then ((delta !! 0, delta !! 1, delta !! 2), a)\n else\n let (sqrtx, sqrty, sqrtz) = (sqrt x, sqrt y, sqrt z) in\n let lambda = sqrtx*sqrty + sqrty*sqrtz + sqrtz*sqrtx in\n rf_ ((x+lambda)/4) ((y+lambda)/4) ((z+lambda)/4) err\n\ncarlsonRF' :: Double -> Cplx -> Cplx -> Cplx -> Cplx\ncarlsonRF' err x y z =\n if zeros > 1\n then error \"At most one of x, y, z can be 0\"\n else\n let ((dx,dy,dz), a) = rf_ x y z err in\n let (e2,e3) = (dx*dy + dy*dz + dz*dx, dx*dy*dz) in\n toCplx(1 - e2/10 + e3/14 + e2*e2/24 - 3*e2*e3/44 - 5*e2*e2*e2/208 +\n 3*e3*e3/104 + e2*e2*e3/16) / sqrt a\n where\n zeros = sum (map (\\u -> fromEnum (u == 0)) [x,y,z])\n\ncarlsonRF :: Cplx -> Cplx -> Cplx -> Cplx\ncarlsonRF = carlsonRF' 1e-15\n\nrd_ :: Cplx -> Cplx -> Cplx -> Cplx -> Cplx -> Double ->\n ((Double,Double,Double), Cplx, Cplx, Cplx)\nrd_ x y z s fac err =\n let a = (x+y+z+z+z)/5 in\n let delta = map (\\u -> magnitude(1-u/a)) [x,y,z] in\n if maximum delta < err\n then ((delta !! 0, delta !! 1, delta !! 2), a, s, fac)\n else\n let (sqrtx, sqrty, sqrtz) = (sqrt x, sqrt y, sqrt z) in\n let lambda = sqrtx*sqrty + sqrty*sqrtz + sqrtz*sqrtx in\n let s' = s + fac / (sqrt z * (z + lambda)) in\n rd_ ((x+lambda)/4) ((y+lambda)/4) ((z+lambda)/4) s' (fac/4) err\n\ncarlsonRD' :: Double -> Cplx -> Cplx -> Cplx -> Cplx\ncarlsonRD' err x y z =\n if zeros > 1\n then error \"At most one of x, y, z can be 0\"\n else\n let ((dx,dy,dz), a, s, fac) = rd_ x y z 0 1 err in\n let\n (e2,e3,e4,e5) = (dx*dy + dy*dz + 3*dz*dz + 2*dz*dx + dx*dz + 2*dy*dz,\n dz*dz*dz + dx*dz*dz + 3*dx*dy*dz + 2*dy*dz*dz + dy*dz*dz + 2*dx*dz*dz,\n dy*dz*dz*dz + dx*dz*dz*dz + dx*dy*dz*dz + 2*dx*dy*dz*dz,\n dx*dy*dz*dz*dz) in\n 3*s + fac * toCplx(1 - 3*e2/14 + e3/6 + 9*e2*e2/88 - 3*e4/22 - 9*e2*e3/52 +\n 3*e5/26 - e2*e2*e2/16 + 3*e3*e3/40 + 3*e2*e4/20 + 45*e2*e2*e3/272 -\n 9*(e3*e4 + e2*e5)/68) / a / sqrt a\n where\n zeros = sum (map (\\u -> fromEnum (u == 0)) [x,y,z])\n\ncarlsonRD :: Cplx -> Cplx -> Cplx -> Cplx\ncarlsonRD = carlsonRD' 1e-15\n\nrj_ :: Cplx -> Cplx -> Cplx -> Cplx -> Cplx -> Double -> Cplx -> Int ->\n Double -> [Cplx] -> [Cplx] -> Double -> (Cplx, Int, [Cplx], [Cplx])\nrj_ x y z p a maxmagns delta f fac d e err =\n let q = (4/err)**(1/6) * maxmagns / fromIntegral f in\n if magnitude a > q\n then (a, f, d, e)\n else\n let dnew = (sqrt p + sqrt x)*(sqrt p + sqrt y)*(sqrt p + sqrt z)\n d' = (fromIntegral f * dnew) : d\n e' = (toCplx fac * delta / dnew / dnew) : e\n lambda = sqrt x * sqrt y + sqrt y * sqrt z + sqrt z * sqrt x\n x' = (x + lambda) / 4\n y' = (y + lambda) / 4\n z' = (z + lambda) / 4\n p' = (p + lambda) / 4\n a' = (a + lambda) / 4\n in\n rj_ x' y' z' p' a' maxmagns delta (4*f) (fac/64) d' e' err\n\ncarlsonRJ' :: Double -> Cplx -> Cplx -> Cplx -> Cplx -> Cplx\ncarlsonRJ' err x y z p =\n if zeros > 1\n then error \"At most one of x, y, z, p can be 0\"\n else\n let a0 = (x + y + z + p + p) / 5\n maxmagns = maximum $ map (\\u -> magnitude(a0-u)) [x, y, z, p]\n delta = (p-x)*(p-y)*(p-z)\n in\n let (a, f, d, e) = rj_ x y z p a0 maxmagns delta 1 1 [] [] err\n f' = fromIntegral f\n in\n let x' = (a0 - x) / f' / a\n y' = (a0 - y) / f' / a\n z' = (a0 - z) / f' / a\n p' = -(x'+y'+z') / 2\n e2 = x'*y' + x'*z' + y'*z' - 3*p'*p'\n e3 = x'*y'*z' + 2*e2*p' + 4*p'*p'*p'\n e4 = p'*(2*x'*y'*z' + e2*p' + 3*p'*p'*p')\n e5 = x'*y'*z'*p'*p'\n h = zipWith (\\u v -> atanx_over_x(sqrt u) / v) e d\n in\n (1 - 3*e2/14 + e3/6 + 9*e2*e2/88 - 3*e4/22 - 9*e2*e3/52 + 3*e5/26) /\n f' / a / sqrt a + 6 * sum h\n where\n zeros = sum (map (\\u -> fromEnum (u == 0)) [x,y,z,p])\n atanx_over_x w = if w == 0 then 1 else atanC w / w\n\ncarlsonRJ :: Cplx -> Cplx -> Cplx -> Cplx -> Cplx\ncarlsonRJ = carlsonRJ' 1e-15\n\n\nrc_ :: Cplx -> Cplx -> Cplx -> Double -> Int -> Double -> (Cplx, Int)\nrc_ x y a magn f err =\n let q = (1/3/err)**(1/8) * magn / fromIntegral f in\n if magnitude a > q\n then (a, f)\n else\n let lambda = 2 * sqrt x * sqrt y + y\n a' = (a + lambda) / 4\n x' = (x + lambda) / 4\n y' = (y + lambda) / 4\n in\n rc_ x' y' a' magn (4*f) err\n\ncarlsonRC' :: Double -> Cplx -> Cplx -> Cplx\ncarlsonRC' err x y =\n if y == 0\n then error \"y cannot be 0\"\n else\n let a0 = (x + y + y) / 3\n magn = magnitude(a0-x)\n in\n let (a, f) = rc_ x y a0 magn 1 err\n f' = fromIntegral f\n in\n let s = (y - a0) / f' / a in\n (1 + 3*s*s/10 + s*s*s/7 + 3*s*s*s*s/8 + 9*s*s*s*s*s/22 +\n 159*s*s*s*s*s*s/208 + 9*s*s*s*s*s*s*s/8) / sqrt a\n\ncarlsonRC :: Cplx -> Cplx -> Cplx\ncarlsonRC = carlsonRC' 1e-15\n\n\ncarlsonRG' :: Double -> Cplx -> Cplx -> Cplx -> Cplx\ncarlsonRG' err x y z =\n if zeros > 1\n then sqrt(x+y+z) / 2\n else\n if z == 0\n then carlsonRG' err z x y\n else\n (z * carlsonRF' err x y z -\n (x-z) * (y-z) * carlsonRD' err x y z / 3 +\n sqrt x * sqrt y / sqrt z) / 2\n where\n zeros = sum (map (\\u -> fromEnum (u == 0)) [x,y,z])\n\ncarlsonRG :: Cplx -> Cplx -> Cplx -> Cplx\ncarlsonRG = carlsonRG' 1e-15\n", "meta": {"hexsha": "cb9d43b5c36b2a7a18bf85a9651f1687c82735b8", "size": 5725, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Carlson.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": "src/Carlson.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": "src/Carlson.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": 33.875739645, "max_line_length": 81, "alphanum_fraction": 0.4894323144, "num_tokens": 2445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5385034517797471}} {"text": "{-# LANGUAGE OverloadedStrings, DuplicateRecordFields, RecordWildCards, NamedFieldPuns #-}\n{-|\n - Module : Numeric.GLP\n - Description : Specifiy a General Linear Problem and transform to a Standardized LP\n - Copyright : (c) Torsten Kemps-Benedix, 2019\n - This module 'Numeric.GLP' specifiies a [Generalized Linear Problem](https://en.wikipedia.org/wiki/Linear_programming) (or LP in short) and provides means to tranform this into a Standardized LP (see module 'Numeric.LP') that may be solved with e.g. the simplex solver in module 'Numeric.LP.Simplex'.\n-}\nmodule Numeric.GLP\n-- (GLP, Numeric.GLP.a, c, m1, m2, m3, dir, mkGLP, standardizeGLP)\nwhere\n\nimport qualified Data.List as L\nimport Control.Monad\nimport qualified Data.Set as S\nimport Data.Set (member, isSubsetOf)\nimport Numeric.LinearAlgebra (I, Element, Matrix, Vector, ident, diagl,\n cols, rows, find, toColumns,\n fromColumns, cmap, fromList, toList,\n (!), (><),\n )\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Devel (modifyMatrix, runSTMatrix,\n thawMatrix, mapVectorWithIndex, fi)\nimport Numeric.LinearAlgebra (vjoin, (|||), (===))\n\n-- | This record defines a General Linear Problem containing ≤\n-- and ≥ inequalities and == equalities. The sum of the numbers of\n-- inequalities ('m1' times ≤ and 'm2' times ≥) and equalities ('m3'\n-- times ==) must match one less than the number of\n-- rows of the matrix 'a'. The first (i.e. the zero-th) row of the matrix\n-- contains the coefficients of the objective function.\n--\n-- We assume that \\(a_{00}\\) is zero. The matrix \\(a\\) shall have \\(m+1\\) rows\n-- and \\(n+1\\) columns.\n--\n-- The formal specification of the problem we intend to solve is as follows:\n--\n-- Maximize resp. minimize (according to 'dir') the following linear objective\n-- function:\n--\n-- \\[ z_0 = \\sum_{i=1}^{n} a_{0,i} x_i \\]\n--\n-- Subject to the following linear constraints:\n--\n-- \\[ z_j = a_{j,0} + \\sum_{i=1}^{n} a_{j,i} x_i,\\, j=1,\\ldots,m\\]\n-- \\[ z_j \\leq 0,\\, j=1,\\ldots,m_1\\]\n-- \\[ z_j \\geq 0,\\, j=m_1+1,\\ldots,m_1+m_2\\]\n-- \\[ z_j = 0,\\, j=m_1+m_2+1,\\ldots,m=m1+m_2+m_3\\]\n--\n-- The original variables \\(x_1, \\ldots, x_n\\) may be constraint to be non-negative,\n-- non-positive or they may be unconstrained according to the n-vector\n-- \\(c\\in\\{-1,0,+1\\}^n\\).\n--\n-- \\[ c_j = -1 \\Rightarrow x_j \\leq 0\\]\n-- \\[ c_j = 1 \\Rightarrow x_j \\geq 0\\]\n-- \\[ c_j = 0 \\Rightarrow x_j \\text{ unrestricted} \\]\ndata GLP = GLP {\n a :: Matrix Double, -- ^ Tableau of coefficients, see above for a formal\n -- description of their meaning\n c :: Vector I, -- ^ Type of constraint for \\(x_j\\), \\(j=1,\\ldots,n\\),\n -- see 'GLP' for further details. The element \\(c_i\\)\n -- corresponds to column \\(i+1\\) of the matrix \\(a\\).\n n :: Int, -- ^ Number of original variables \\(x_1, \\ldots, x_n\\)\n m1 :: Int, -- ^ Number of ≤ inequalities\n m2 :: Int, -- ^ Number of ≥ inequalities\n m3 :: Int, -- ^ Number of = equalities\n dir :: Dir, -- ^ Whether the objective function is to be maximized\n -- or minimzed\n lhs, rhs :: Vector I -- ^ Indices of left and right hand variables respectively.\n -- The original variables \\(x_1,\\ldots,x_n\\) have indices\n -- \\(1,\\ldots,n\\), the slack variables get indices\n -- \\(n+1, \\ldots, n+m_1+m_2+1\\), and the auxiliary variables\n -- finally get indices \\(n+m_1+m_2+2, \\ldots, n+m_1+m_2+m+2\\).\n } deriving (Show)\n\n-- | This smart constructor checks all the pre-conditions for 'GLP' stated in the\n-- description of 'GLP' and initializes the variables 'lhs' and 'rhs'. Initially only\n-- the \\(m\\) auxiliary variables \\(z_1,\\ldots,z_m\\) are on the left hand side and all the\n-- original variables \\(x_1,\\ldots,x_n\\) are on the right hand side. Initially there are\n-- no slack variables \\(y_1,\\ldots,y_{m_1+m_2+1}\\). These will be introdced by the function\n-- 'introduceSlackVariables' below.\nmkGLP :: Matrix Double -> Vector I -> (Int, Int, Int) -> Dir -> Either String GLP\nmkGLP a c (m1,m2,m3) dir =\n let m = rows a - 1\n n = cols a - 1\n in if (m /= m1+m2+m3)\n then Left $ \"rows a - 1 == \"++show m++\" /= m1+m2+m3 == \"++show (m1+m2+m3)\n else if (m <= 0)\n then Left \"The number of constraints is m <= 0\"\n else if (n <= 0)\n then Left \"The number of variables n is <= 0\"\n else if not (S.fromList (LA.toList c) `isSubsetOf` (S.fromList [-1,0,1]))\n then Left \"Vector c has elements other than -1, 0, +1\"\n else if LA.size c /= n\n then Left $ \"Vector c has not the proper length \"++show n\n else Right (GLP a c n m1 m2 m3 dir\n (LA.fromList [fi (n+m1+m2+2)..fi (n+m1+m2+m+2)])\n (LA.fromList [1..fi n]))\n\ndata Dir = Maximize | Minimize deriving Show\n\n-- | Transform the Generalized Linear Problem to a Standardized Linear Problem\n-- by means of the following steps:\n--\n-- 1. If the objective function is to be minimized multiply it by -1.\n-- 2. Turn around the ≥-inequalities by negation of the corresponding rows. After this\n-- step there are 'm1'+'m2' inequalities of the <= type.\n-- 3. For those variables \\(x_i\\) that have a constraint \\(x_i \\leq 0\\) substitute\n-- \\(x_i \\rightarrow -x_i\\). This means multiplying the column \\(i\\) of the matrix\n-- \\(a\\) by \\(-1\\).\n-- 4. For those variables \\(x_i\\) that are unconstrained introduce new non-negative\n-- variables \\(x_i = x_i⁺ - x_i⁻\\). We give these the indices \\(x_i⁺ = x_i\\) and\n-- \\(x_⁻ = x_{i+1}\\). The indices of all other variables \\(x_k\\), \\(k>i\\) have to be\n-- increased by \\(1\\). The matrix \\(a\\) therefore grows by one column.\n-- 5. For the 'm1'+'m2' ≤-inequalities introduce as many slack variables on the right\n-- hand side and make these equalities instead. After this step there are only\n-- equalities left as constraints. We do not represent these slack variables in the\n-- matrix 'a' and therefore nothing really changes in this step.\n-- 6. Introduce artificial variables \\(z_j\\) ( \\(j=1,\\ldots,m\\) ) for each equation.\n-- This changes the optimization problem and the solver has to take this into account.\n--\n-- The function returns a modified and standardized GLP and a matrix \\(b\\) that maps\n-- solution vectors (including the objective functions value) of the modified GLP back\n-- to solution vectors of the original GLP.\nstandardizeGLP :: GLP -> (GLP, Matrix Double)\nstandardizeGLP glp =\n let (glp1, b1) = resolveMin2Max glp\n (glp2, b2) = resolveGeqConstraints glp1\n (glp3, b3) = resolveNonPositiveVars glp2\n (glp4, b4) = resolveUnconstrainedVars glp3\n glp5 = introduceSlackVariables glp4\n in (glp5, b1 <> b2 <> b3 <> b4)\n\nresolveMin2Max :: GLP -> (GLP, Matrix Double)\nresolveMin2Max glp@GLP{..} = case dir of\n Maximize -> (glp, ident (1+m1+m2+m3))\n Minimize -> (glp{a = mapRow a 0 negate, dir = Maximize},\n diagl (-1:(replicate (m1+m2+m3) 1)))\n\nresolveGeqConstraints :: GLP -> (GLP, Matrix Double)\nresolveGeqConstraints glp@GLP{..} =\n let a' = foldl (\\a j -> mapRow a j negate) a [m1+1..m1+m2] -- negate rows from m1+1 to m1+m2\n in (glp{a = a', m1 = m1+m2, m2 = 0},\n ident (1+m1+m2+m3))\n\nresolveNonPositiveVars :: GLP -> (GLP, Matrix Double)\nresolveNonPositiveVars glp@GLP{..} =\n let varsToBeNegated = find (== -1) c\n varsToBeNegatedS = S.fromList varsToBeNegated\n (a', c') = foldl (\\(a,c) i ->\n (mapCol a (i+1) negate,\n mapVectorWithIndex (\\k x -> if k==i\n then 1\n else c!k)\n c))\n (a, c)\n (find (== -1) c)\n in (glp{a = a', c = c'},\n diagl $ 1:[if i `member` varsToBeNegatedS\n then -1\n else 1 | i <- [0..m1+m2+m3-1]])\n\nresolveUnconstrainedVars :: GLP -> (GLP, Matrix Double)\nresolveUnconstrainedVars glp@GLP{..} =\n let m = 1+m1+m2+m3\n zCol = vec1 m 0 1\n (a', c', b) =\n let listOfColsAndCs =\n fmap (\\(c1,ci,i1) ->\n if ci==0\n then ([c1, cmap negate c1],\n [1, 1],\n [vec1 m (i1+1) 1,\n vec1 m (i1+1) (-1)]) -- duplicate and adjust\n else ([c1], [ci],\n [vec1 m (i1+1) 1])) -- return unchanged\n (L.zip3 (toColumns a) (toList c) [0..(cols a)-1])\n columns = L.concat $ fmap (\\(x,_,_) -> x) listOfColsAndCs\n cs = L.concat $ fmap (\\(_,x,_) -> x) listOfColsAndCs\n bs = L.concat $ fmap (\\(_,_,x) -> x) listOfColsAndCs\n in (fromColumns columns, fromList cs, fromColumns $ zCol:bs)\n in (glp{a=a', c=c'}, b)\n\nintroduceSlackVariables :: GLP -> GLP\nintroduceSlackVariables glp@GLP{..} =\n let m3' = m1+m2+m3\n n = cols a - 1\n a' = a ||| ((1><(m1+m2)) (replicate (m1+m2) 0) ===\n diagl ((replicate m1 1)++(replicate m2 (-1))) ===\n (m3><(m1+m2)) (replicate (m3*(m1+m2)) 0))\n rhs' = vjoin [rhs, LA.fromList [fi (n+1)..fi (n+1+m1+m2)]]\n in glp{a=a', m1=0, m2=0, m3=m3', rhs=rhs'}\n\nvec1 :: Int -> Int -> Double -> Vector Double\nvec1 n i x = fromList $ L.replicate i 0++x:L.replicate (n-i-1) 0\n\nmapRow :: (Element t) => Matrix t -> Int -> (t -> t) -> Matrix t\nmapRow a k f = runSTMatrix $ do\n a' <- thawMatrix a\n forM_ [0..cols a-1] (\\i -> modifyMatrix a' k i f)\n return a'\n\nmapCol :: (Element t) => Matrix t -> Int -> (t -> t) -> Matrix t\nmapCol a k f = runSTMatrix $ do\n a' <- thawMatrix a\n forM_ [0..rows a-1] (\\i -> modifyMatrix a' i k f)\n return a'\n\nprettyPrintAsFormulas :: GLP -> String\nprettyPrintAsFormulas glp@GLP{..} =\n let rs = LA.toRows a\n m = cols a - 1\n n = rows a - 1\n objFun = (show dir)++\n \" z_0 = \"++linExp 0\n zRows = fmap (\\k -> \"z_\"++show k++\" = \"++linExp k) [1..n]\n linExp k = L.intercalate \" + \" (\n L.filter (/= \"\") $\n fmap (\\(a,i) ->\n if a /= 0\n then show a++(if i>0 then \" \"++varName i else \"\")\n else \"\") (L.zip (toList $ rs!!k) [0..m]))\n varName i = if i <= n then \"x_\"++show i else \"y_\"++show (i-n)\n zConstr = L.intercalate \", \" $ filter (/= \"\") $\n [if m1 == 1\n then \"z_1 ≤ 0\"\n else if m1 == 2\n then \"z_1, z_2 ≤ 0\"\n else if m1 > 2\n then \"z_1, ..., z_\"++show m1++\" ≤ 0\"\n else \"\",\n if m2 == 1\n then \"z_\"++show (m1+1)++\" ≥ 0\"\n else if m2 > 1\n then \"z_\"++show (m1+1)++\", ..., z_\"++show (m1+m2)++\" ≥ 0\"\n else \"\",\n if m3 == 1\n then \"z_\"++show (m1+m2+1)++\" = 0\"\n else if m3 > 1\n then \"z_\"++show (m1+m2+1)++\", ..., z_\"++show (m1+m2+m3)++\" = 0\"\n else \"\"]\n xConstr ck k = \"x_\"++show k++if ck == -1\n then \" ≤ 0\"\n else if ck == 1\n then \" ≥ 0\"\n else \" unconstrained\"\n xConstrs = fmap (uncurry xConstr) (L.zip (toList c) [1..m])\n in L.intercalate \"\\n\" (\n objFun:\n \"Subject to\":\n (fmap (\\line -> \"\\t\"++line) (zRows++[\"\"]++\n [zConstr, \"\"]++\n xConstrs)))\n ++\"\\n\"\n\n(Right ex1') = ex1\nex1 = let a = (5><5)\n [ 0, 1, 1, 3, -0.5\n , 740, -1, 0, -2, 0\n , 0, 0, -2, 0, 7\n , 0.5, 0, -1, 1, -2\n , 9, -1, -1, -1, -1]\n c = LA.fromList [-1, 1, 0, -1]\n in mkGLP a c (2, 1, 1) Minimize\n\nallEx1 = do\n let g1 = ex1'\n putStr $ prettyPrintAsFormulas g1\n putStrLn $ \"lhs = \"++show (lhs g1)\n putStrLn $ \"rhs = \"++show (rhs g1)\n putStrLn \"\\nResolve min/max\"\n let (g2, b1) = resolveMin2Max g1\n putStr $ prettyPrintAsFormulas g2\n putStrLn $ \"lhs = \"++show (lhs g2)\n putStrLn $ \"rhs = \"++show (rhs g2)\n print b1\n putStrLn \"\\nResove geq constraints\"\n let (g3, b2) = resolveGeqConstraints g2\n putStr $ prettyPrintAsFormulas g3\n putStrLn $ \"lhs = \"++show (lhs g3)\n putStrLn $ \"rhs = \"++show (rhs g3)\n print b2\n putStrLn \"\\nResove non-positive variables\"\n let (g4, b3) = resolveNonPositiveVars g3\n putStr $ prettyPrintAsFormulas g4\n putStrLn $ \"lhs = \"++show (lhs g4)\n putStrLn $ \"rhs = \"++show (rhs g4)\n print b3\n putStrLn \"\\nResove unconstrained variables\"\n let (g5, b4) = resolveUnconstrainedVars g4\n putStr $ prettyPrintAsFormulas g5\n putStrLn $ \"lhs = \"++show (lhs g5)\n putStrLn $ \"rhs = \"++show (rhs g5)\n print b4\n putStrLn \"\\nIntroduce slack variables\"\n let g6 = introduceSlackVariables g5\n putStr $ prettyPrintAsFormulas g6\n putStrLn $ \"lhs = \"++show (lhs g6)\n putStrLn $ \"rhs = \"++show (rhs g6)\n putStrLn \"\\n\"\n return (g6, b1 <> b2 <> b3 <> b4)\n\n\n", "meta": {"hexsha": "d6579e663d8b247105591a16479fb99a34ca5577", "size": 14296, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/GLP.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/GLP.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/GLP.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": 47.0263157895, "max_line_length": 302, "alphanum_fraction": 0.5101426973, "num_tokens": 4241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5384827488111316}} {"text": "{-# LANGUAGE PatternGuards #-}\n-- |\n-- Module : Statistics.Matrix\n-- Copyright : 2011 Aleksey Khudyakov, 2014 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Basic matrix operations.\n--\n-- There isn't a widely used matrix package for Haskell yet, so\n-- we implement the necessary minimum here.\n\nmodule Statistics.Matrix\n ( -- * Data types\n Matrix(..)\n , Vector\n -- * Conversion from/to lists/vectors\n , fromVector\n , fromList\n , fromRowLists\n , fromRows\n , fromColumns\n , toVector\n , toList\n , toRows\n , toColumns\n , toRowLists\n -- * Other\n , generate\n , generateSym\n , ident\n , diag\n , dimension\n , center\n , multiply\n , multiplyV\n , transpose\n , power\n , norm\n , column\n , row\n , map\n , for\n , unsafeIndex\n , hasNaN\n , bounds\n , unsafeBounds\n ) where\n\nimport Prelude hiding (exponent, map)\nimport Control.Applicative ((<$>))\nimport Control.Monad.ST\nimport qualified Data.Vector.Unboxed as U\nimport Data.Vector.Unboxed ((!))\nimport qualified Data.Vector.Unboxed.Mutable as UM\n\nimport Numeric.Sum (sumVector,kbn)\nimport Statistics.Matrix.Function\nimport Statistics.Matrix.Types\nimport Statistics.Matrix.Mutable (unsafeNew,unsafeWrite,unsafeFreeze)\n\n\n\n----------------------------------------------------------------\n-- Conversion to/from vectors/lists\n----------------------------------------------------------------\n\n-- | Convert from a row-major list.\nfromList :: Int -- ^ Number of rows.\n -> Int -- ^ Number of columns.\n -> [Double] -- ^ Flat list of values, in row-major order.\n -> Matrix\nfromList r c = fromVector r c . U.fromList\n\n-- | create a matrix from a list of lists, as rows\nfromRowLists :: [[Double]] -> Matrix\nfromRowLists = fromRows . fmap U.fromList\n\n-- | Convert from a row-major vector.\nfromVector :: Int -- ^ Number of rows.\n -> Int -- ^ Number of columns.\n -> U.Vector Double -- ^ Flat list of values, in row-major order.\n -> Matrix\nfromVector r c v\n | r*c /= len = error \"input size mismatch\"\n | otherwise = Matrix r c v\n where len = U.length v\n\n-- | create a matrix from a list of vectors, as rows\nfromRows :: [Vector] -> Matrix\nfromRows xs\n | [] <- xs = error \"Statistics.Matrix.fromRows: empty list of rows!\"\n | any (/=nCol) ns = error \"Statistics.Matrix.fromRows: row sizes do not match\"\n | nCol == 0 = error \"Statistics.Matrix.fromRows: zero columns in matrix\"\n | otherwise = fromVector nRow nCol (U.concat xs)\n where\n nCol:ns = U.length <$> xs\n nRow = length xs\n\n\n-- | create a matrix from a list of vectors, as columns\nfromColumns :: [Vector] -> Matrix\nfromColumns = transpose . fromRows\n\n-- | Convert to a row-major flat vector.\ntoVector :: Matrix -> U.Vector Double\ntoVector (Matrix _ _ v) = v\n\n-- | Convert to a row-major flat list.\ntoList :: Matrix -> [Double]\ntoList = U.toList . toVector\n\n-- | Convert to a list of lists, as rows\ntoRowLists :: Matrix -> [[Double]]\ntoRowLists (Matrix _ nCol v)\n = chunks $ U.toList v\n where\n chunks [] = []\n chunks xs = case splitAt nCol xs of\n (rowE,rest) -> rowE : chunks rest\n\n\n-- | Convert to a list of vectors, as rows\ntoRows :: Matrix -> [Vector]\ntoRows (Matrix _ nCol v) = chunks v\n where\n chunks xs\n | U.null xs = []\n | otherwise = case U.splitAt nCol xs of\n (rowE,rest) -> rowE : chunks rest\n\n-- | Convert to a list of vectors, as columns\ntoColumns :: Matrix -> [Vector]\ntoColumns = toRows . transpose\n\n\n\n----------------------------------------------------------------\n-- Other\n----------------------------------------------------------------\n\n-- | Generate matrix using function\ngenerate :: Int -- ^ Number of rows\n -> Int -- ^ Number of columns\n -> (Int -> Int -> Double)\n -- ^ Function which takes /row/ and /column/ as argument.\n -> Matrix\ngenerate nRow nCol f\n = Matrix nRow nCol $ U.generate (nRow*nCol) $ \\i ->\n let (r,c) = i `quotRem` nCol in f r c\n\n-- | Generate symmetric square matrix using function\ngenerateSym\n :: Int -- ^ Number of rows and columns\n -> (Int -> Int -> Double)\n -- ^ Function which takes /row/ and /column/ as argument. It must\n -- be symmetric in arguments: @f i j == f j i@\n -> Matrix\ngenerateSym n f = runST $ do\n m <- unsafeNew n n\n for 0 n $ \\r -> do\n unsafeWrite m r r (f r r)\n for (r+1) n $ \\c -> do\n let x = f r c\n unsafeWrite m r c x\n unsafeWrite m c r x\n unsafeFreeze m\n\n\n-- | Create the square identity matrix with given dimensions.\nident :: Int -> Matrix\nident n = diag $ U.replicate n 1.0\n\n-- | Create a square matrix with given diagonal, other entries default to 0\ndiag :: Vector -> Matrix\ndiag v\n = Matrix n n $ U.create $ do\n arr <- UM.replicate (n*n) 0\n for 0 n $ \\i ->\n UM.unsafeWrite arr (i*n + i) (v ! i)\n return arr\n where\n n = U.length v\n\n-- | Return the dimensions of this matrix, as a (row,column) pair.\ndimension :: Matrix -> (Int, Int)\ndimension (Matrix r c _) = (r, c)\n\n-- | Matrix-matrix multiplication. Matrices must be of compatible\n-- sizes (/note: not checked/).\nmultiply :: Matrix -> Matrix -> Matrix\nmultiply m1@(Matrix r1 _ _) m2@(Matrix _ c2 _) =\n Matrix r1 c2 $ U.generate (r1*c2) go\n where\n go t = sumVector kbn $ U.zipWith (*) (row m1 i) (column m2 j)\n where (i,j) = t `quotRem` c2\n\n-- | Matrix-vector multiplication.\nmultiplyV :: Matrix -> Vector -> Vector\nmultiplyV m v\n | cols m == c = U.generate (rows m) (sumVector kbn . U.zipWith (*) v . row m)\n | otherwise = error $ \"matrix/vector unconformable \" ++ show (cols m,c)\n where c = U.length v\n\n-- | Raise matrix to /n/th power. Power must be positive\n-- (/note: not checked).\npower :: Matrix -> Int -> Matrix\npower mat 1 = mat\npower mat n = res\n where\n mat2 = power mat (n `quot` 2)\n pow = multiply mat2 mat2\n res | odd n = multiply pow mat\n | otherwise = pow\n\n-- | Element in the center of matrix (not corrected for exponent).\ncenter :: Matrix -> Double\ncenter mat@(Matrix r c _) =\n unsafeBounds U.unsafeIndex mat (r `quot` 2) (c `quot` 2)\n\n-- | Calculate the Euclidean norm of a vector.\nnorm :: Vector -> Double\nnorm = sqrt . sumVector kbn . U.map square\n\n-- | Return the given column.\ncolumn :: Matrix -> Int -> Vector\ncolumn (Matrix r c v) j= U.generate r (\\i -> v `U.unsafeIndex` (j + i * c))\n{-# INLINE column #-}\n\n-- | Return the given row.\nrow :: Matrix -> Int -> Vector\nrow (Matrix _ c v) i = U.slice (c*i) c v\n\nunsafeIndex :: Matrix\n -> Int -- ^ Row.\n -> Int -- ^ Column.\n -> Double\nunsafeIndex = unsafeBounds U.unsafeIndex\n\n-- | Apply function to every element of matrix\nmap :: (Double -> Double) -> Matrix -> Matrix\nmap f (Matrix r c v) = Matrix r c (U.map f v)\n\n-- | Indicate whether any element of the matrix is @NaN@.\nhasNaN :: Matrix -> Bool\nhasNaN = U.any isNaN . toVector\n\n-- | Given row and column numbers, calculate the offset into the flat\n-- row-major vector.\nbounds :: (Vector -> Int -> r) -> Matrix -> Int -> Int -> r\nbounds k (Matrix rs cs v) r c\n | r < 0 || r >= rs = error \"row out of bounds\"\n | c < 0 || c >= cs = error \"column out of bounds\"\n | otherwise = k v $! r * cs + c\n{-# INLINE bounds #-}\n\n-- | Given row and column numbers, calculate the offset into the flat\n-- row-major vector, without checking.\nunsafeBounds :: (Vector -> Int -> r) -> Matrix -> Int -> Int -> r\nunsafeBounds k (Matrix _ cs v) r c = k v $! r * cs + c\n{-# INLINE unsafeBounds #-}\n\ntranspose :: Matrix -> Matrix\ntranspose m@(Matrix r0 c0 _) = Matrix c0 r0 . U.generate (r0*c0) $ \\i ->\n let (r,c) = i `quotRem` r0\n in unsafeIndex m c r\n", "meta": {"hexsha": "0f82732cb37e76972cc6cafd84282c76112f81f2", "size": 7835, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "dense-linear-algebra/src/Statistics/Matrix.hs", "max_stars_repo_name": "arvindd/dh-core", "max_stars_repo_head_hexsha": "78dee2304790fae0e301af17c7512d9c916a9b3f", "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": "dense-linear-algebra/src/Statistics/Matrix.hs", "max_issues_repo_name": "arvindd/dh-core", "max_issues_repo_head_hexsha": "78dee2304790fae0e301af17c7512d9c916a9b3f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dense-linear-algebra/src/Statistics/Matrix.hs", "max_forks_repo_name": "arvindd/dh-core", "max_forks_repo_head_hexsha": "78dee2304790fae0e301af17c7512d9c916a9b3f", "max_forks_repo_licenses": ["BSD-3-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.454887218, "max_line_length": 80, "alphanum_fraction": 0.5868538609, "num_tokens": 2120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.538390522266041}} {"text": "{-# LANGUAGE BangPatterns #-}\nmodule ListStats (mean, var, stDiv, nCr, varM, qf,unStdNorm,unStdNormSplits, -- cov, corr,\n stDivM, stNorm, erf, cn, erfInv, binomial, cdf, cdF, meanBy, stDivBy,\n normal, gammaln, adjustedMatrix, adjustedMatrixN, adjustedMatrixPN, normalP,\n module ListAlgebra,\n ) where\n\nimport Numeric\nimport Numeric.LinearAlgebra\nimport qualified Data.Vector as V (map, fromList)\nimport Data.List \nimport Control.DeepSeq (NFData)\nimport LINreg2 (foldl'Rnf )\nimport Data.Ord (comparing)\nimport ListAlgebra\n\n----------------------------------------------------------------------------------------\n--- mean, variance and correlations\n----------------------------------------------------------------------------------------\n\ninsertZeros :: Num a => [a] -> [Int] -> [a]\ninsertZeros xs [] = xs\ninsertZeros xs (a:as) =\n let (front,back) = splitAt (a-1) xs in\n (1 :front) ++ (0 : insertZeros back as)\n\n-- map a function then calculate the standard deviation\nstDivBy :: (a -> Double) -> [a] -> Double\nstDivBy f xs = (sumBy (sqr . (\\a -> a - ns) . f) xs) / k\n where\n (sm,k) = foldl' (\\(n,m) a -> (f a + n, m + 1)) (0,0) xs\n ns = sm / k\n sqr x = x * x\n\n-- map a function then calculate the mean\nmeanBy :: (a -> Double) -> [a] -> Double\nmeanBy g xs = sm / k\n where (sm,k) = foldl' (\\(n,m) a -> (g a + n, m + 1)) (0,0) xs\n\n----\nmean :: (NFData a, Fractional a) => [a] -> a\nmean xs = fst suml / (snd suml - 1)\n where suml = foldl'Rnf kF (0, 1) xs\n kF (!n , !r) b = (n + b, 1 + r)\t\t\t\t\t\n---\nvar :: (NFData a, Floating a) => [a] -> a\nvar xs = (fst suml / snd suml)\n where suml = foldl'Rnf kF (0, 0) xs\n kF (!n , !r) b = (n + (b - k)^2 , 1 + r)\t\t\t\t\n k = mean xs\n-- variance of a list of values with the mean given\nvarM :: (NFData a , Floating a) => a -> [a] -> a\nvarM k xs = fst suml / snd suml\n where suml = foldl'Rnf kF (0, 0) xs\n kF (!n , !r) b = (n + (b - k)^2 , 1 + r)\t\t\t\t\n--\n--- the standard deviation without the Mean given\nstDiv :: (NFData a , Floating a) => [a] -> a\nstDiv = sqrt . var\n\n---- standard deviation with the mean given\nstDivM k = sqrt . (varM k)\n\n\n--- standardise by subtracting the mean and dividing by the standard deviation\n--stNorm :: [Double] -> [Double]\nstNorm xs = map (\\ a -> (a - m) / std) xs\n where m = mean xs\n std = stDivM m xs\n---\nunStdNorm xs ys = map (\\a -> std * a + m) ys\n where m = mean xs\n std = stDivM m xs\n\nunStdNormSplits xs zs = unStdNorm (insertZeros xs zs)\n\n--- selecting the 'best' sublist of lenght n of a list of values\nbestN :: (Ord a , Ord b) => (a -> b) -> Int -> [a] -> [a]\nbestN comp lim xs\n | length xs <= lim = xs\n | length back <= lim = myBest lim comp xs\n | otherwise = min (sortBy (comparing comp) front) (bestN comp lim back)\n where\n (front, back) = splitAt lim xs\n myBest n f = myTake n . sortBy (comparing f)\n mn = lim `div` 2\n\n--- computed the weighted average of the residuals of values, which represent\n--- points on the y-axis plotted against x-values [1 .. n], where n is the\n-- length of the list. The weight biased towards is determind as the\nwgtAvgRd :: (NFData a, Enum a, Fractional a) => Int -> [[a]] -> a\nwgtAvgRd n xs = weightsSum / len\n where\n (weightsSum , len) = foldl'Rnf (getWeightedAvg (2 * n)) (0,0) xs\n getWeightedAvg k (wa,ln) ys = (wa + wVal , ln + 1)\n where\n f = fromIntegral\n len = f $ length ys\n ks = [1 .. len]\n sumSqrs as bs = foldl'Rnf (\\a (b,c) -> a + b * c) 0 (zip as bs)\n wVal = (sumSqrs ks ys) / (sumSqrs ks ks) -- (f k / len) *\n\n--------------------------------------------------------------------------------------------\n-- Defining the X matrix for the MML function\n--------------------------------------------------------------------------------------------\n-- We combine adjustMatrix, fillZeros and allPieces to\n-- give the final adjusted matrix. This matrix is standardised, then transposed,\n-- but the transposeition can be removed if we require that to occur later on\nadjustedMatrix xs = [( tS . adjustMatrix . fillZeroes_aux n 0 1) yss | yss <- allPieces xs]\n where n = length xs\n tS = fromLists . map (1:) . transpose . map stNorm\n\nadjustedMatrixN m xs = [tS $ adjustMatrix $ fillZeroes_aux n 0 1 yss | yss <- nPieces m xs]\n where n = length xs\n tS = map (1:). transpose . map stNorm\nadjustedMatrixPN k m xs = [(tS $ adjustMatrix $ fillZeroes_aux n 0 1 yss, cuts) |\n (yss,cuts) <- nPiecesP k m Nothing xs, not $ null cuts]\n where n = length xs\n tS = map (1:). transpose . map stNorm\n--\n-- test function\njoins :: Eq a => [a] -> [[a]]\njoins xs | null xs = [] -- && (length (concat a) > 5)\n | otherwise = joins_aux xs ++ joins (tail xs)\n where\n joins_aux (x : y : ys) = ([x,y] : (map (x :) $ joins_aux (y : ys)))\n joins_aux _ = []\n--------------------------------------------------------------------------------------------\n-- calculating the binomial coefficient, and normal prob density\n-------------------------------------------------------------------------------------------\nnCr :: (Integral a, Ord a) => a -> a -> a\nnCr n r | n < 0 || r < 0 = error \"can find combinations for negative numbers\"\nnCr n 0 = 1\nnCr 0 _ = 0\nnCr !n !k = nCr (n-1) (k-1) * n `div` k\n\n\n--- binomial distribution\nbinomial :: (Integral a, Ord b, Fractional b, Ord a) => a -> a -> b -> b\nbinomial n r p | p > 1 || p < 0 = error \"Invalid probability value\" ---n nCr r *\nbinomial n k p | k >= 0 && k <= n = let nck = fromIntegral (nCr n k) in nck * (p^k) * (1 - p)^(n - k)\n | otherwise = 0\n\n-- value of x from a normal distribution with mean 'mn' and standard deviation \"std\"\nnormal x mn std = (1 / (std * sqrt (2 * pi))) * exp(- 0.5 * ((x - mn)^2) / (std ^2))\n--normal x mn std = cdf (x + eps) mn std - cdf (x - eps) mn std\n where\n eps = 0.0101095\n --z = (x - mn) / std\n\n-- calculating the normal with a given precision\nnormalP eps x mn std = cdf (x + eps) mn std - cdf (x - eps) mn std\n------------------------------------------------------------------------------------------------\n--- approximating the error functions and its inverse\n----------------------------------------------------------------------------------------------\t\t\t\t\t\t\t\nerf\tx\t| x < 0 = -1 * erf (- 1 * x)\n\t\t| otherwise = 1 - t * exp k\n where\n t = 1 / (1 + 0.5 * abs x)\n\tt3 = t * (- 0.82215223 + t * 0.17087277)\n t2 = t * ( 0.27886807 + t * (-1.13520398 + t * 1.48851587 + t3))\n t4 = t * ( 0.37409196 + t * ( 0.09678418 + t * (- 0.18628806) + t2))\n\tk = - x * x - 1.26551223 + t * 1.00002368 + t4\n--\n\n--cn :: Int -> Double\t\t\ncn\t 0\t=\t1\ncn\t n\t=\tfoldr (\\k b -> b + (cn k * cn (n - 1 - k)) / ((k + 1) * (2 * k + 1))) 0 [0.. n - 1]\n\n-- inverse of the error function\n--erfInv :: (Fractional a, Floating a, Enum a) => a -> a\nerfInv\ty | y < -1 || y > 1 = error \"erfInv argument out of range\"\n | abs y == 1 = pol (-y* log (0.0))\n | y < - 0.7 = pol (- 1 * folD z (head c) (tail c) / folD z 1 d)\n | y < 0.7 = pol ( y * folD (y^2) (head a) (tail a) / folD (y^2) 1 b)\n | otherwise = pol (folD z1 (head c) (tail c) / folD z1 1 d)\n where a = [0.886226899, -1.645349621, 0.914624893, -0.140543331]\n b = [-2.118377725, 1.442710462, -0.329097515, 0.012229801]\n c = [-1.970840454, -1.624906493, 3.429567803, 1.641345311]\n d = [3.543889200, 1.637067800]\n z = sqrt(- log ((1.0+y)/2.0))\n z1 = sqrt(- log ((1.0+y)/2.0))\n pol x = x - (erf(x) - y) / (2.0 /(sqrt pi) * exp(-x*x))\n folD zz a ls = foldl'Rnf (\\a b -> a + zz * (fst b + snd b * zz)) a (zipp ls)\n\n\n-- commulative density function\ncdf x mean std | std < 0 = error\"Negative variance to CDF\"\ncdf x mean std | otherwise = 0.5 * (1 + erf ((x - mean) / (std * sqrt 2)))\n\n\n-- the CDF for the standard normal distribution\ncdF n = cdf n 0 1\n\n-- the q function, which is 1 - CDF (x) (here given for the standard normal dist)\nqf x = 1 - cdF x\n--------------------------------------------------------------------------------------\n--- The gamm function takel from wikipedia\n--------------------------------------------------------------------------------------\ngammaln :: Double -> Double\ngammaln xx = -tmp' + log(2.5066282746310005 * ser' / xx)\n\t\t\twhere\n\t\t\ttmp' = (xx+5.5) - (xx+0.5)*log(xx+5.5)\n\t\t\tser' = ser + sum (zipWith (/) cof [xx+1..])\n\t\t\tcof = [76.18009172947146,-86.50532032941677,24.01409824083091,-1.231739572450155,0.001208650973866179,-0.000005395239384953]\n\t\t\tser = 1.000000000190015\n", "meta": {"hexsha": "c638cf0ad058a9b1a9397e0c71d551d5d43dcead", "size": 9614, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "sourceCode/ListStats.hs", "max_stars_repo_name": "rawlep/MML", "max_stars_repo_head_hexsha": "a2c05b50adcae345f745fe3e28b4aa0b7c4f17ba", "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": "sourceCode/ListStats.hs", "max_issues_repo_name": "rawlep/MML", "max_issues_repo_head_hexsha": "a2c05b50adcae345f745fe3e28b4aa0b7c4f17ba", "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": "sourceCode/ListStats.hs", "max_forks_repo_name": "rawlep/MML", "max_forks_repo_head_hexsha": "a2c05b50adcae345f745fe3e28b4aa0b7c4f17ba", "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": 46.4444444444, "max_line_length": 128, "alphanum_fraction": 0.4575618889, "num_tokens": 2980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5383804713062497}} {"text": "-- |\n-- Module : Statistics.Matrix\n-- Copyright : 2011 Aleksey Khudyakov, 2014 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Basic matrix operations.\n--\n-- There isn't a widely used matrix package for Haskell yet, so\n-- we implement the necessary minimum here.\n\nmodule Statistics.Matrix\n (\n Matrix(..)\n , Vector\n , fromList\n , fromVector\n , toVector\n , toList\n , dimension\n , center\n , multiply\n , multiplyV\n , transpose\n , power\n , norm\n , column\n , row\n , map\n , for\n , unsafeIndex\n , hasNaN\n , bounds\n , unsafeBounds\n ) where\n\nimport Prelude hiding (exponent, map, sum)\nimport Statistics.Function (for, square)\nimport Statistics.Matrix.Types\nimport Statistics.Sample.Internal (sum)\nimport qualified Data.Vector.Unboxed as U\n\n-- | Convert from a row-major list.\nfromList :: Int -- ^ Number of rows.\n -> Int -- ^ Number of columns.\n -> [Double] -- ^ Flat list of values, in row-major order.\n -> Matrix\nfromList r c = fromVector r c . U.fromList\n\n-- | Convert from a row-major vector.\nfromVector :: Int -- ^ Number of rows.\n -> Int -- ^ Number of columns.\n -> U.Vector Double -- ^ Flat list of values, in row-major order.\n -> Matrix\nfromVector r c v\n | r*c /= len = error \"input size mismatch\"\n | otherwise = Matrix r c 0 v\n where len = U.length v\n\n-- | Convert to a row-major flat vector.\ntoVector :: Matrix -> U.Vector Double\ntoVector (Matrix _ _ _ v) = v\n\n-- | Convert to a row-major flat list.\ntoList :: Matrix -> [Double]\ntoList = U.toList . toVector\n\n-- | Return the dimensions of this matrix, as a (row,column) pair.\ndimension :: Matrix -> (Int, Int)\ndimension (Matrix r c _ _) = (r, c)\n\n-- | Avoid overflow in the matrix.\navoidOverflow :: Matrix -> Matrix\navoidOverflow m@(Matrix r c e v)\n | center m > 1e140 = Matrix r c (e + 140) (U.map (* 1e-140) v)\n | otherwise = m\n\n-- | Matrix-matrix multiplication. Matrices must be of compatible\n-- sizes (/note: not checked/).\nmultiply :: Matrix -> Matrix -> Matrix\nmultiply m1@(Matrix r1 _ e1 _) m2@(Matrix _ c2 e2 _) =\n Matrix r1 c2 (e1 + e2) $ U.generate (r1*c2) go\n where\n go t = sum $ U.zipWith (*) (row m1 i) (column m2 j)\n where (i,j) = t `quotRem` c2\n\n-- | Matrix-vector multiplication.\nmultiplyV :: Matrix -> Vector -> Vector\nmultiplyV m v\n | cols m == c = U.generate (rows m) (sum . U.zipWith (*) v . row m)\n | otherwise = error $ \"matrix/vector unconformable \" ++ show (cols m,c)\n where c = U.length v\n\n-- | Raise matrix to /n/th power. Power must be positive\n-- (/note: not checked).\npower :: Matrix -> Int -> Matrix\npower mat 1 = mat\npower mat n = avoidOverflow res\n where\n mat2 = power mat (n `quot` 2)\n pow = multiply mat2 mat2\n res | odd n = multiply pow mat\n | otherwise = pow\n\n-- | Element in the center of matrix (not corrected for exponent).\ncenter :: Matrix -> Double\ncenter mat@(Matrix r c _ _) =\n unsafeBounds U.unsafeIndex mat (r `quot` 2) (c `quot` 2)\n\n-- | Calculate the Euclidean norm of a vector.\nnorm :: Vector -> Double\nnorm = sqrt . sum . U.map square\n\n-- | Return the given column.\ncolumn :: Matrix -> Int -> Vector\ncolumn (Matrix r c _ v) i = U.backpermute v $ U.enumFromStepN i c r\n{-# INLINE column #-}\n\n-- | Return the given row.\nrow :: Matrix -> Int -> Vector\nrow (Matrix _ c _ v) i = U.slice (c*i) c v\n\nunsafeIndex :: Matrix\n -> Int -- ^ Row.\n -> Int -- ^ Column.\n -> Double\nunsafeIndex = unsafeBounds U.unsafeIndex\n\nmap :: (Double -> Double) -> Matrix -> Matrix\nmap f (Matrix r c e v) = Matrix r c e (U.map f v)\n\n-- | Indicate whether any element of the matrix is @NaN@.\nhasNaN :: Matrix -> Bool\nhasNaN = U.any isNaN . toVector\n\n-- | Given row and column numbers, calculate the offset into the flat\n-- row-major vector.\nbounds :: (Vector -> Int -> r) -> Matrix -> Int -> Int -> r\nbounds k (Matrix rs cs _ v) r c\n | r < 0 || r >= rs = error \"row out of bounds\"\n | c < 0 || c >= cs = error \"column out of bounds\"\n | otherwise = k v $! r * cs + c\n{-# INLINE bounds #-}\n\n-- | Given row and column numbers, calculate the offset into the flat\n-- row-major vector, without checking.\nunsafeBounds :: (Vector -> Int -> r) -> Matrix -> Int -> Int -> r\nunsafeBounds k (Matrix _ cs _ v) r c = k v $! r * cs + c\n{-# INLINE unsafeBounds #-}\n\ntranspose :: Matrix -> Matrix\ntranspose m@(Matrix r0 c0 e _) = Matrix c0 r0 e . U.generate (r0*c0) $ \\i ->\n let (r,c) = i `quotRem` r0\n in unsafeIndex m c r\n", "meta": {"hexsha": "d2f2c1cb38a747b1b1089f50c2b7a28a0d2a2627", "size": 4599, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Matrix.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/Matrix.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/Matrix.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": 29.8636363636, "max_line_length": 77, "alphanum_fraction": 0.6044792346, "num_tokens": 1296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5383053376585236}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n\n#if MIN_VERSION_base(4,12,0)\n{-# LANGUAGE NoStarIsType #-}\n#endif\n\n\n-- |\n-- Module : Numeric.LinearAlgebra.Static.Backprop\n-- Copyright : (c) Justin Le 2018\n-- License : BSD3\n--\n-- Maintainer : justin@jle.im\n-- Stability : experimental\n-- Portability : non-portable\n--\n-- A wrapper over \"Numeric.LinearAlgebra.Static\" (type-safe vector and\n-- matrix operations based on blas/lapack) that allows its operations to\n-- work with . Also\n-- provides orphan instances of 'Backprop' for types in\n-- \"Numeric.LinearAlgebra.Static\".\n--\n-- In short, these functions are \"lifted\" to work with 'BVar's.\n--\n-- Using 'evalBP' will run the original operation:\n--\n-- @\n-- 'evalBP' :: (forall s. 'Reifies' s 'W'. 'BVar' s a -> 'BVar' s b) -> a -> b\n-- @\n--\n-- But using 'gradBP' or 'backprop' will give you the gradient:\n--\n-- @\n-- 'gradBP' :: (forall s. 'Reifies' s 'W'. 'BVar' s a -> 'BVar' s b) -> a -> a\n-- @\n--\n-- These can act as a drop-in replacement to the API of\n-- \"Numeric.LinearAlgebra.Static\". Just change your imports, and your\n-- functions are automatically backpropagatable. Useful types are all\n-- re-exported.\n--\n-- Also contains 'sumElements' 'BVar' operation.\n--\n-- Formulas for gradients come from the following papers:\n--\n-- * https://people.maths.ox.ac.uk/gilesm/files/NA-08-01.pdf\n-- * http://www.dtic.mil/dtic/tr/fulltext/u2/624426.pdf\n-- * http://www.cs.cmu.edu/~zkolter/course/15-884/linalg-review.pdf\n-- * https://arxiv.org/abs/1602.07527\n--\n-- Some functions are notably unlifted:\n--\n-- * 'H.svd': I can't find any resources that allow you to backpropagate\n-- if the U and V matrices are used! If you find one, let me know, or\n-- feel free to submit a PR! Because of this, Currently only a version\n-- that exports only the singular values is exported.\n-- * 'H.svdTall', 'H.svdFlat': Not sure where to start for these\n-- * 'qr': Same story.\n-- https://github.com/tensorflow/tensorflow/issues/6504 might yield\n-- a clue?\n-- * 'H.her': No 'Num' instance for 'H.Her' makes this impossible at\n-- the moment with the current backprop API\n-- * 'H.exmp': Definitely possible, but I haven't dug deep enough to\n-- figure it out yet! There is a description here\n-- https://people.maths.ox.ac.uk/gilesm/files/NA-08-01.pdf but it\n-- requires some things I am not familiar with yet. Feel free to\n-- submit a PR!\n-- * 'H.sqrtm': Also likely possible. Maybe try to translate\n-- http://people.cs.umass.edu/~smaji/projects/matrix-sqrt/ ? PRs\n-- welcomed!\n-- * 'H.linSolve': Haven't figured out where to start!\n-- * 'H.': Same story\n-- * Functions returning existential types, like 'H.withNullSpace',\n-- 'H.withOrth', 'H.withRows', etc.; not quite sure what the best way\n-- to handle these are at the moment.\n-- * 'H.withRows' and 'H.withColumns' made \"type-safe\", without\n-- existential types, with 'fromRows' and 'fromColumns'.\n\nmodule Numeric.LinearAlgebra.Static.Backprop (\n -- * Vector\n H.R\n , H.ℝ\n , vec2\n , vec3\n , vec4\n , (&)\n , (#)\n , split\n , headTail\n , vector\n , linspace\n , H.range\n , H.dim\n -- * Matrix\n , H.L\n , H.Sq\n , row\n , col\n , (|||)\n , (===)\n , splitRows\n , splitCols\n , unrow\n , uncol\n , tr\n , H.eye\n , diag\n , matrix\n -- * Complex\n , H.ℂ\n , H.C\n , H.M\n , H.𝑖\n , toComplex\n , fromComplex\n , complex\n , real\n , imag\n , sqMagnitude\n , magnitude\n -- * Products\n , (<>)\n , (#>)\n , (<.>)\n -- * Factorizations\n , svd\n , svd_\n , H.Eigen\n , eigensystem\n , eigenvalues\n , chol\n -- * Norms\n , H.Normed\n , norm_0\n , norm_1V\n , norm_1M\n , norm_2V\n , norm_2M\n , norm_InfV\n , norm_InfM\n -- * Misc\n , mean\n , meanCov\n , meanL\n , cov\n , H.Disp(..)\n -- ** Domain\n , H.Domain\n , mul\n , app\n , dot\n , cross\n , diagR\n , vmap\n , vmap'\n , dvmap\n , mmap\n , mmap'\n , dmmap\n , outer\n , zipWithVector\n , zipWithVector'\n , dzipWithVector\n , det\n , invlndet\n , lndet\n , inv\n -- ** Conversions\n , toRows\n , toColumns\n , fromRows\n , fromColumns\n -- ** Misc Operations\n , konst\n , sumElements\n , extractV\n , extractM\n , create\n , H.Diag\n , takeDiag\n , H.Sym\n , sym\n , mTm\n , unSym\n , (<·>)\n -- * Backprop types re-exported\n -- | Re-exported for convenience.\n --\n -- @since 0.1.1.0\n , BVar\n , Backprop\n , Reifies\n , W\n ) where\n\nimport Data.Bifunctor\nimport Data.Coerce\nimport Data.Functor.Identity\nimport Data.Maybe\nimport Data.Proxy\nimport Data.Vinyl (Rec(..))\nimport Foreign.Storable\nimport GHC.TypeLits\nimport Lens.Micro hiding ((&))\nimport Numeric.Backprop\nimport Numeric.Backprop.Class\nimport Unsafe.Coerce\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as VG\nimport qualified Data.Vector.Generic.Sized as SVG\nimport qualified Data.Vector.Sized as SV\nimport qualified Data.Vector.Storable.Sized as SVS\nimport qualified Numeric.Backprop.Explicit as BE\nimport qualified Numeric.LinearAlgebra as HU\nimport qualified Numeric.LinearAlgebra.Static as H\nimport qualified Numeric.LinearAlgebra.Static.Vector as H\nimport qualified Prelude.Backprop as B\n\n#if MIN_VERSION_base(4,11,0)\nimport Prelude hiding ((<>))\n#endif\n\ninstance Backprop (H.R n) where\n zero = zeroNum\n add = addNum\n one = oneNum\n\ninstance Backprop (H.C n) where\n zero = zeroNum\n add = addNum\n one = oneNum\n\ninstance (KnownNat n, KnownNat m) => Backprop (H.L n m) where\n zero = zeroNum\n add = addNum\n one = oneNum\n\ninstance (KnownNat n, KnownNat m) => Backprop (H.M n m) where\n zero = zeroNum\n add = addNum\n one = oneNum\n\ninstance KnownNat n => Backprop (H.Sym n) where\n zero = zeroNum\n add = addNum\n one = oneNum\n\nvec2\n :: Reifies s W\n => BVar s H.ℝ\n -> BVar s H.ℝ\n -> BVar s (H.R 2)\nvec2 = isoVar2 H.vec2 (\\(H.rVec->v) -> (SVS.index v 0, SVS.index v 1))\n{-# INLINE vec2 #-}\n\nvec3\n :: Reifies s W\n => BVar s H.ℝ\n -> BVar s H.ℝ\n -> BVar s H.ℝ\n -> BVar s (H.R 3)\nvec3 = isoVar3 H.vec3 (\\(H.rVec->v) -> (SVS.index v 0, SVS.index v 1, SVS.index v 2))\n{-# INLINE vec3 #-}\n\nvec4\n :: Reifies s W\n => BVar s H.ℝ\n -> BVar s H.ℝ\n -> BVar s H.ℝ\n -> BVar s H.ℝ\n -> BVar s (H.R 4)\nvec4 vX vY vZ vW = isoVarN\n (\\(Identity x :& Identity y :& Identity z :& Identity w :& RNil) -> H.vec4 x y z w)\n (\\(H.rVec->v) -> Identity (SVS.index v 0)\n :& Identity (SVS.index v 1)\n :& Identity (SVS.index v 2)\n :& Identity (SVS.index v 3)\n :& RNil\n )\n (vX :& vY :& vZ :& vW :& RNil)\n{-# INLINE vec4 #-}\n\n(&) :: (KnownNat n, 1 <= n, KnownNat (n + 1), Reifies s W)\n => BVar s (H.R n)\n -> BVar s H.ℝ\n -> BVar s (H.R (n + 1))\n(&) = isoVar2 (H.&) (\\(H.split->(dxs,dy)) -> (dxs, fst (H.headTail dy)))\ninfixl 4 &\n{-# INLINE (&) #-}\n\n(#) :: (KnownNat n, KnownNat m, Reifies s W)\n => BVar s (H.R n)\n -> BVar s (H.R m)\n -> BVar s (H.R (n + m))\n(#) = isoVar2 (H.#) H.split\ninfixl 4 #\n{-# INLINE (#) #-}\n\nsplit\n :: forall p n s. (KnownNat p, KnownNat n, p <= n, Reifies s W)\n => BVar s (H.R n)\n -> (BVar s (H.R p), BVar s (H.R (n - p)))\nsplit v = (t ^^. _1, t ^^. _2)\n where\n t = isoVar H.split (uncurry (H.#)) v\n {-# NOINLINE t #-}\n{-# INLINE split #-}\n\nheadTail\n :: (Reifies s W, KnownNat n, 1 <= n)\n => BVar s (H.R n)\n -> (BVar s H.ℝ, BVar s (H.R (n - 1)))\nheadTail v = (t ^^. _1, t ^^. _2)\n where\n t = isoVar H.headTail\n (\\(d, dx) -> (H.konst d :: H.R 1) H.# dx)\n v\n {-# NOINLINE t #-}\n{-# INLINE headTail #-}\n\n-- | Potentially extremely bad for anything but short lists!!!\nvector\n :: forall n s. (KnownNat n, Reifies s W)\n => SV.Vector n (BVar s H.ℝ)\n -> BVar s (H.R n)\nvector = BE.isoVar afSV\n (H.vecR . SVG.convert) (SVG.convert . H.rVec)\n . collectVar\n{-# INLINE vector #-}\n\nlinspace\n :: forall n s. (KnownNat n, Reifies s W)\n => BVar s H.ℝ\n -> BVar s H.ℝ\n -> BVar s (H.R n)\nlinspace = liftOp2 . op2 $ \\l u ->\n ( H.linspace (l, u)\n , \\d -> let n1 = fromInteger $ natVal (Proxy @n) - 1\n dDot = ((H.range - 1) H.<.> d) / n1\n dSum = HU.sumElements . H.extract $ d\n in (dSum - dDot, dDot)\n )\n{-# INLINE linspace #-}\n\nrow :: Reifies s W\n => BVar s (H.R n)\n -> BVar s (H.L 1 n)\nrow = isoVar H.row H.unrow\n{-# INLINE row #-}\n\ncol :: (KnownNat n, Reifies s W)\n => BVar s (H.R n)\n -> BVar s (H.L n 1)\ncol = isoVar H.col H.uncol\n{-# INLINE col #-}\n\n(|||) :: (KnownNat c, KnownNat r1, KnownNat (r1 + r2), Reifies s W)\n => BVar s (H.L c r1)\n -> BVar s (H.L c r2)\n -> BVar s (H.L c (r1 + r2))\n(|||) = isoVar2 (H.|||) H.splitCols\ninfixl 3 |||\n{-# INLINE (|||) #-}\n\n(===) :: (KnownNat c, KnownNat r1, KnownNat (r1 + r2), Reifies s W)\n => BVar s (H.L r1 c)\n -> BVar s (H.L r2 c)\n -> BVar s (H.L (r1 + r2) c)\n(===) = isoVar2 (H.===) H.splitRows\ninfixl 2 ===\n{-# INLINE (===) #-}\n\nsplitRows\n :: forall p m n s. (KnownNat p, KnownNat m, KnownNat n, p <= m, Reifies s W)\n => BVar s (H.L m n)\n -> (BVar s (H.L p n), BVar s (H.L (m - p) n))\nsplitRows v = (t ^^. _1, t ^^. _2)\n where\n t = isoVar H.splitRows (uncurry (H.===)) v\n {-# NOINLINE t #-}\n{-# INLINE splitRows #-}\n\nsplitCols\n :: forall p m n s. (KnownNat p, KnownNat m, KnownNat n, KnownNat (n - p), p <= n, Reifies s W)\n => BVar s (H.L m n)\n -> (BVar s (H.L m p), BVar s (H.L m (n - p)))\nsplitCols v = (t ^^. _1, t ^^. _2)\n where\n t = isoVar H.splitCols (uncurry (H.|||)) v\n {-# NOINLINE t #-}\n{-# INLINE splitCols #-}\n\nunrow\n :: (KnownNat n, Reifies s W)\n => BVar s (H.L 1 n)\n -> BVar s (H.R n)\nunrow = isoVar H.unrow H.row\n{-# INLINE unrow #-}\n\nuncol\n :: (KnownNat n, Reifies s W)\n => BVar s (H.L n 1)\n -> BVar s (H.R n)\nuncol = isoVar H.uncol H.col\n{-# INLINE uncol #-}\n\ntr :: (HU.Transposable m mt, HU.Transposable mt m, Backprop m, Reifies s W)\n => BVar s m\n -> BVar s mt\ntr = isoVar H.tr H.tr\n{-# INLINE tr #-}\n\ndiag\n :: (KnownNat n, Reifies s W)\n => BVar s (H.R n)\n -> BVar s (H.Sq n)\ndiag = liftOp1 . op1 $ \\x -> (H.diag x, H.takeDiag)\n{-# INLINE diag #-}\n\n-- | Potentially extremely bad for anything but short lists!!!\nmatrix\n :: forall m n s. (KnownNat m, KnownNat n, Reifies s W)\n => [BVar s H.ℝ]\n -> BVar s (H.L m n)\nmatrix = maybe (error \"matrix: invalid number of elements\")\n ( isoVar (H.vecL . SVG.convert . runABP) (ABP . SVG.convert . H.lVec)\n . collectVar\n . ABP\n )\n . SV.fromList @(m * n)\n{-# INLINE matrix #-}\n\n-- | Matrix product\n(<>)\n :: (KnownNat m, KnownNat k, KnownNat n, Reifies s W)\n => BVar s (H.L m k)\n -> BVar s (H.L k n)\n -> BVar s (H.L m n)\n(<>) = mul\ninfixr 8 <>\n{-# INLINE (<>) #-}\n\n-- | Matrix-vector product\n(#>)\n :: (KnownNat m, KnownNat n, Reifies s W)\n => BVar s (H.L m n)\n -> BVar s (H.R n)\n -> BVar s (H.R m)\n(#>) = app\ninfixr 8 #>\n{-# INLINE (#>) #-}\n\n-- | Dot product\n(<.>)\n :: (KnownNat n, Reifies s W)\n => BVar s (H.R n)\n -> BVar s (H.R n)\n -> BVar s H.ℝ\n(<.>) = dot\ninfixr 8 <.>\n{-# INLINE (<.>) #-}\n\n-- | Can only get the singular values, for now. Let me know if you find an\n-- algorithm that can compute the gradients based on differentials for the\n-- other matricies!\n--\nsvd :: forall m n s. (KnownNat m, KnownNat n, Reifies s W)\n => BVar s (H.L m n)\n -> BVar s (H.R n)\nsvd = liftOp1 . op1 $ \\x ->\n let (u, σ, v) = H.svd x\n in ( σ\n , \\(dΣ :: H.R n) -> (u H.<> H.diagR 0 dΣ) H.<> H.tr v\n -- must manually associate because of bug in diagR in\n -- hmatrix-0.18.2.0\n )\n{-# INLINE svd #-}\n\n-- | Version of 'svd' that returns the full SVD, but if you attempt to find\n-- the gradient, it will fail at runtime if you ever use U or V.\nsvd_\n :: forall m n s. (KnownNat m, KnownNat n, Reifies s W)\n => BVar s (H.L m n)\n -> (BVar s (H.L m m), BVar s (H.R n), BVar s (H.L n n))\nsvd_ r = (t ^^. _1, t ^^. _2, t ^^. _3)\n where\n o :: Op '[H.L m n] (H.L m m, H.R n, H.L n n)\n o = op1 $ \\x ->\n let msv@(u, _, v) = H.svd x\n in ( msv\n , \\(dU, dΣ, dV) ->\n if H.norm_0 dU == 0 && H.norm_0 dV == 0\n then (u H.<> H.diagR 0 dΣ) H.<> H.tr v\n else error \"svd_: Cannot backprop if U and V are used.\"\n )\n {-# INLINE o #-}\n t = liftOp1 o r\n {-# NOINLINE t #-}\n{-# INLINE svd_ #-}\n\nhelpEigen :: KnownNat n => H.Sym n -> (H.R n, H.L n n, H.L n n, H.L n n)\nhelpEigen x = (l, v, H.inv v, H.tr v)\n where\n (l, v) = H.eigensystem x\n{-# INLINE helpEigen #-}\n\n-- | /NOTE/ The gradient is not necessarily symmetric! The gradient is not\n-- meant to be retireved directly; insteadl, 'eigenvalues' is meant to be\n-- used as a part of a larger computation, and the gradient as an\n-- intermediate step.\neigensystem\n :: forall n s. (KnownNat n, Reifies s W)\n => BVar s (H.Sym n)\n -> (BVar s (H.R n), BVar s (H.L n n))\neigensystem u = (t ^^. _1, t ^^. _2)\n where\n o :: Op '[H.Sym n] (H.R n, H.L n n)\n o = op1 $ \\x ->\n let (l, v, vInv, vTr) = helpEigen x\n lRep = H.rowsL . SV.replicate $ l\n fMat = (1 - H.eye) * (lRep - H.tr lRep)\n in ( (l, v)\n , \\(dL, dV) -> unsafeCoerce $\n H.tr vInv\n H.<> (H.diag dL + fMat * (vTr H.<> dV))\n H.<> vTr\n )\n {-# INLINE o #-}\n t = liftOp1 o u\n {-# NOINLINE t #-}\n{-# INLINE eigensystem #-}\n\n-- | /NOTE/ The gradient is not necessarily symmetric! The gradient is not\n-- meant to be retireved directly; insteadl, 'eigenvalues' is meant to be\n-- used as a part of a larger computation, and the gradient as an\n-- intermediate step.\neigenvalues\n :: forall n s. (KnownNat n, Reifies s W)\n => BVar s (H.Sym n)\n -> BVar s (H.R n)\neigenvalues = liftOp1 . op1 $ \\x ->\n let (l, _, vInv, vTr) = helpEigen x\n in ( l\n , \\dL -> unsafeCoerce $\n H.tr vInv H.<> H.diag dL H.<> vTr\n )\n{-# INLINE eigenvalues #-}\n\n-- | Algorithm from https://arxiv.org/abs/1602.07527\n--\n-- The paper also suggests a potential imperative algorithm that might\n-- help. Need to benchmark to see what is best.\n--\n-- /NOTE/ The gradient is not necessarily symmetric! The gradient is not\n-- meant to be retireved directly; insteadl, 'eigenvalues' is meant to be\n-- used as a part of a larger computation, and the gradient as an\n-- intermediate step.\nchol\n :: forall n s. (KnownNat n, Reifies s W)\n => BVar s (H.Sym n)\n -> BVar s (H.Sq n)\nchol = liftOp1 . op1 $ \\x ->\n let l = H.chol x\n lInv = H.inv l\n phi :: H.Sq n\n phi = H.build $ \\i j -> case compare i j of\n LT -> 1\n EQ -> 0.5\n GT -> 0\n in ( l\n , \\dL -> let s = H.tr lInv H.<> (phi * (H.tr l H.<> dL)) H.<> lInv\n in unsafeCoerce $ s + H.tr s - H.eye * s\n )\n{-# INLINE chol #-}\n\n-- | Number of non-zero items\nnorm_0\n :: (H.Normed a, Backprop a, Reifies s W)\n => BVar s a\n -> BVar s H.ℝ\nnorm_0 = liftOp1 . op1 $ \\x -> (H.norm_0 x, const (zero x))\n{-# INLINE norm_0 #-}\n\n-- | Sum of absolute values\nnorm_1V\n :: (KnownNat n, Reifies s W)\n => BVar s (H.R n)\n -> BVar s H.ℝ\nnorm_1V = liftOp1 . op1 $ \\x -> (H.norm_1 x, (* signum x) . H.konst)\n{-# INLINE norm_1V #-}\n\n-- | Maximum 'H.norm_1' of columns\nnorm_1M\n :: (KnownNat n, KnownNat m, Reifies s W)\n => BVar s (H.L n m)\n -> BVar s H.ℝ\nnorm_1M = liftOp1 . op1 $ \\x ->\n let n = H.norm_1 x\n in (n, \\d -> let d' = H.konst d\n in H.colsL\n . SV.map (\\c -> if H.norm_1 c == n\n then d' * signum c\n else 0\n )\n . H.lCols\n $ x\n )\n{-# INLINE norm_1M #-}\n\n-- | Square root of sum of squares\n--\n-- Be aware that gradient diverges when the norm is zero\nnorm_2V\n :: (KnownNat n, Reifies s W)\n => BVar s (H.R n)\n -> BVar s H.ℝ\nnorm_2V = liftOp1 . op1 $ \\x ->\n let n = H.norm_2 x\n in (n, \\d -> x * H.konst (d / n))\n{-# INLINE norm_2V #-}\n\n-- | Maximum singular value\nnorm_2M\n :: (KnownNat n, KnownNat m, Reifies s W)\n => BVar s (H.L n m)\n -> BVar s H.ℝ\nnorm_2M = liftOp1 . op1 $ \\x ->\n let n = H.norm_2 x\n (head.H.toColumns->u1,_,head.H.toColumns->v1) = H.svd x\n in (n, \\d -> H.konst d * (u1 `H.outer` v1))\n{-# INLINE norm_2M #-}\n\n-- | Maximum absolute value\nnorm_InfV\n :: (KnownNat n, Reifies s W)\n => BVar s (H.R n)\n -> BVar s H.ℝ\nnorm_InfV = liftOp1 . op1 $ \\x ->\n let n :: H.ℝ\n n = H.norm_Inf x\n in (n, \\d -> H.vecR\n . SVS.map (\\e -> if abs e == n\n then signum e * d\n else 0\n )\n . H.rVec\n $ x\n )\n{-# ANN norm_InfV \"HLint: ignore Use camelCase\" #-}\n{-# INLINE norm_InfV #-}\n\n-- | Maximum 'H.norm_1' of rows\nnorm_InfM\n :: (KnownNat n, KnownNat m, Reifies s W)\n => BVar s (H.L n m)\n -> BVar s H.ℝ\nnorm_InfM = liftOp1 . op1 $ \\x ->\n let n = H.norm_Inf x\n in (n, \\d -> let d' = H.konst d\n in H.rowsL\n . SV.map (\\c -> if H.norm_1 c == n\n then d' * signum c\n else 0\n )\n . H.lRows\n $ x\n )\n{-# ANN norm_InfM \"HLint: ignore Use camelCase\" #-}\n{-# INLINE norm_InfM #-}\n\nmean\n :: (KnownNat n, 1 <= n, Reifies s W)\n => BVar s (H.R n)\n -> BVar s H.ℝ\nmean = liftOp1 . op1 $ \\x -> (H.mean x, H.konst . (/ H.norm_0 x))\n{-# INLINE mean #-}\n\ngradCov\n :: forall m n. (KnownNat m, KnownNat n)\n => H.L m n\n -> H.R n\n -> H.Sym n\n -> H.L m n\ngradCov x μ dσ = H.rowsL\n . SV.map (subtract (dDiffsSum / m))\n . H.lRows\n $ dDiffs\n where\n diffs = H.rowsL . SV.map (subtract μ) . H.lRows $ x\n dDiffs = H.konst (2/n) * (diffs H.<> H.tr (H.unSym dσ))\n dDiffsSum = sum . H.toRows $ dDiffs\n m = fromIntegral $ natVal (Proxy @m)\n n = fromIntegral $ natVal (Proxy @n)\n{-# INLINE gradCov #-}\n\n-- | Mean and covariance. If you know you only want to use one or the\n-- other, use 'meanL' or 'cov'.\nmeanCov\n :: forall m n s. (KnownNat n, KnownNat m, 1 <= m, Reifies s W)\n => BVar s (H.L m n)\n -> (BVar s (H.R n), BVar s (H.Sym n))\nmeanCov v = (t ^^. _1, t ^^. _2)\n where\n m = fromInteger $ natVal (Proxy @m)\n t = ($ v) . liftOp1 . op1 $ \\x ->\n let ms@(μ, _) = H.meanCov x\n in ( ms\n , \\(dμ, dσ) ->\n let gradMean = H.rowsL\n . SV.replicate\n $ (dμ / H.konst m)\n in gradMean + gradCov x μ dσ\n )\n {-# NOINLINE t #-}\n{-# INLINE meanCov #-}\n\n-- | 'meanCov', but if you know you won't use the covariance.\nmeanL\n :: forall m n s. (KnownNat n, KnownNat m, 1 <= m, Reifies s W)\n => BVar s (H.L m n)\n -> BVar s (H.R n)\nmeanL = liftOp1 . op1 $ \\x ->\n ( fst (H.meanCov x)\n , H.rowsL . SV.replicate . (/ H.konst m)\n )\n where\n m = fromInteger $ natVal (Proxy @m)\n{-# INLINE meanL #-}\n\n-- | 'cov', but if you know you won't use the covariance.\ncov\n :: forall m n s. (KnownNat n, KnownNat m, 1 <= m, Reifies s W)\n => BVar s (H.L m n)\n -> BVar s (H.Sym n)\ncov = liftOp1 . op1 $ \\x ->\n let (μ, σ) = H.meanCov x\n in (σ, gradCov x μ)\n{-# INLINE cov #-}\n\nmul :: ( KnownNat m\n , KnownNat k\n , KnownNat n\n , H.Domain field vec mat\n , Backprop (mat m k)\n , Backprop (mat k n)\n , HU.Transposable (mat m k) (mat k m)\n , HU.Transposable (mat k n) (mat n k)\n , Reifies s W\n )\n => BVar s (mat m k)\n -> BVar s (mat k n)\n -> BVar s (mat m n)\nmul = liftOp2 . op2 $ \\x y ->\n ( x `H.mul` y\n , \\d -> (d `H.mul` H.tr y, H.tr x `H.mul` d)\n )\n{-# INLINE mul #-}\n\napp :: ( KnownNat m\n , KnownNat n\n , H.Domain field vec mat\n , HU.Transposable (mat m n) (mat n m)\n , Backprop (mat m n)\n , Backprop (vec n)\n , Reifies s W\n )\n => BVar s (mat m n)\n -> BVar s (vec n)\n -> BVar s (vec m)\napp = liftOp2 . op2 $ \\xs y ->\n ( xs `H.app` y\n , \\d -> (d `H.outer` y, H.tr xs `H.app` d)\n )\n{-# INLINE app #-}\n\ndot :: ( KnownNat n\n , H.Domain field vec mat\n , H.Sized field (vec n) d\n , Num (vec n)\n , Backprop (vec n)\n , Reifies s W\n )\n => BVar s (vec n)\n -> BVar s (vec n)\n -> BVar s field\ndot = liftOp2 . op2 $ \\x y ->\n ( x `H.dot` y\n , \\d -> let d' = H.konst d\n in (d' * y, x * d')\n )\n{-# INLINE dot #-}\n\ncross\n :: ( H.Domain field vec mat\n , Reifies s W\n , Backprop (vec 3)\n )\n => BVar s (vec 3)\n -> BVar s (vec 3)\n -> BVar s (vec 3)\ncross = liftOp2 . op2 $ \\x y ->\n ( x `H.cross` y\n , \\d -> (y `H.cross` d, d `H.cross` x)\n )\n{-# INLINE cross #-}\n\n-- | Create matrix with diagonal, and fill with default entries\ndiagR\n :: forall m n k field vec mat s.\n ( H.Domain field vec mat\n , Num (vec k)\n , Num (mat m n)\n , KnownNat m\n , KnownNat n\n , KnownNat k\n , HU.Container HU.Vector field\n , H.Sized field (mat m n) HU.Matrix\n , H.Sized field (vec k) HU.Vector\n , Backprop field\n , Backprop (vec k)\n , Reifies s W\n )\n => BVar s field -- ^ default value\n -> BVar s (vec k) -- ^ diagonal\n -> BVar s (mat m n)\ndiagR = liftOp2 . op2 $ \\c x ->\n ( H.diagR c x\n , \\d -> ( HU.sumElements . H.extract $ H.diagR 1 (0 :: vec k) * d\n , fromJust . H.create . HU.takeDiag . H.extract $ d\n )\n )\n{-# INLINE diagR #-}\n\n-- | Note: if possible, use the potentially much more performant 'vmap''.\nvmap\n :: (KnownNat n, Reifies s W)\n => (BVar s H.ℝ -> BVar s H.ℝ)\n -> BVar s (H.R n)\n -> BVar s (H.R n)\nvmap f = isoVar (H.vecR . SVG.convert @V.Vector . runABP)\n (ABP . SVG.convert . H.rVec)\n . B.fmap f\n . isoVar (ABP . SVG.convert . H.rVec) (H.vecR . SVG.convert . runABP)\n{-# INLINE vmap #-}\n\n-- | 'vmap', but potentially more performant. Only usable if the mapped\n-- function does not depend on any external 'BVar's.\nvmap'\n :: ( Num (vec n)\n , Storable field\n , H.Sized field (vec n) HU.Vector\n , Backprop (vec n)\n , Backprop field\n , Reifies s W\n )\n => (forall s'. Reifies s' W => BVar s' field -> BVar s' field)\n -> BVar s (vec n)\n -> BVar s (vec n)\nvmap' f = liftOp1 . op1 $ bimap (fromJust . H.create . VG.convert)\n ((*) . fromJust . H.create . VG.convert)\n . V.unzip\n . V.map (backprop f)\n . VG.convert\n . H.extract\n{-# INLINE vmap' #-}\n\n-- TODO: Can be made more efficient if backprop exports\n-- a custom-total-derivative version\n\n-- | Note: Potentially less performant than 'vmap''.\ndvmap\n :: ( KnownNat n\n , H.Domain field vec mat\n , Num (vec n)\n , Backprop (vec n)\n , Backprop field\n , Reifies s W\n )\n => (forall s'. Reifies s' W => BVar s' field -> BVar s' field)\n -> BVar s (vec n)\n -> BVar s (vec n)\ndvmap f = liftOp1 . op1 $ \\x ->\n ( H.dvmap (evalBP f) x\n , (H.dvmap (gradBP f) x *)\n )\n{-# INLINE dvmap #-}\n\n-- | Note: if possible, use the potentially much more performant 'mmap''.\nmmap\n :: (KnownNat n, KnownNat m, Reifies s W)\n => (BVar s H.ℝ -> BVar s H.ℝ)\n -> BVar s (H.L n m)\n -> BVar s (H.L n m)\nmmap f = isoVar (H.vecL . SVG.convert @V.Vector . runABP)\n (ABP . SVG.convert . H.lVec)\n . B.fmap f\n . isoVar (ABP . SVG.convert . H.lVec) (H.vecL . SVG.convert . runABP)\n{-# INLINE mmap #-}\n\n-- | 'mmap', but potentially more performant. Only usable if the mapped\n-- function does not depend on any external 'BVar's.\nmmap'\n :: forall n m mat field s.\n ( KnownNat m\n , Num (mat n m)\n , Backprop (mat n m)\n , Backprop field\n , H.Sized field (mat n m) HU.Matrix\n , HU.Element field\n , Reifies s W\n )\n => (forall s'. Reifies s' W => BVar s' field -> BVar s' field)\n -> BVar s (mat n m)\n -> BVar s (mat n m)\nmmap' f = liftOp1 . op1 $ bimap (fromJust . H.create . HU.reshape m . VG.convert)\n ((*) . fromJust . H.create . HU.reshape m . VG.convert)\n . V.unzip\n . V.map (backprop f)\n . VG.convert\n . HU.flatten\n . H.extract\n where\n m :: Int\n m = fromInteger $ natVal (Proxy @m)\n{-# INLINE mmap' #-}\n\n-- | Note: Potentially less performant than 'mmap''.\ndmmap\n :: ( KnownNat n\n , KnownNat m\n , H.Domain field vec mat\n , Num (mat n m)\n , Backprop (mat n m)\n , Backprop field\n , Reifies s W\n )\n => (forall s'. Reifies s' W => BVar s' field -> BVar s' field)\n -> BVar s (mat n m)\n -> BVar s (mat n m)\ndmmap f = liftOp1 . op1 $ \\x ->\n ( H.dmmap (evalBP f) x\n , (H.dmmap (gradBP f) x *)\n )\n{-# INLINE dmmap #-}\n\nouter\n :: ( KnownNat m\n , KnownNat n\n , H.Domain field vec mat\n , HU.Transposable (mat n m) (mat m n)\n , Backprop (vec n)\n , Backprop (vec m)\n , Reifies s W\n )\n => BVar s (vec n)\n -> BVar s (vec m)\n -> BVar s (mat n m)\nouter = liftOp2 . op2 $ \\x y ->\n ( x `H.outer` y\n , \\d -> ( d `H.app` y\n , H.tr d `H.app` x)\n )\n{-# INLINE outer #-}\n\n-- | Note: if possible, use the potentially much more performant\n-- 'zipWithVector''.\nzipWithVector\n :: (KnownNat n, Reifies s W)\n => (BVar s H.ℝ -> BVar s H.ℝ -> BVar s H.ℝ)\n -> BVar s (H.R n)\n -> BVar s (H.R n)\n -> BVar s (H.R n)\nzipWithVector f x y = isoVar (H.vecR . SVG.convert . runABP)\n (ABP . SVG.convert . H.rVec)\n $ B.liftA2 @(ABP (SV.Vector _)) f (iv x) (iv y)\n where\n iv = isoVar (ABP . SVG.convert . H.rVec) (H.vecR . SVG.convert . runABP)\n{-# INLINE zipWithVector #-}\n\nzipWithVector'\n :: ( Num (vec n)\n , Backprop (vec n)\n , Storable field\n , Backprop field\n , H.Sized field (vec n) HU.Vector\n , Reifies s W\n )\n => (forall s'. Reifies s' W => BVar s' field -> BVar s' field -> BVar s' field)\n -> BVar s (vec n)\n -> BVar s (vec n)\n -> BVar s (vec n)\nzipWithVector' f = liftOp2 . op2 $ \\(VG.convert.H.extract->x) (VG.convert.H.extract->y) ->\n let (z, dx, dy) = V.unzip3 $ V.zipWith (\\x' -> retup . backprop2 f x') x y\n in ( fromJust (H.create (VG.convert z))\n , \\d -> ( d * fromJust (H.create (VG.convert dx))\n , d * fromJust (H.create (VG.convert dy))\n )\n )\n where\n retup (x, (y, z)) = (x, y, z)\n{-# INLINE zipWithVector' #-}\n\n-- | A version of 'zipWithVector'' that is potentially less performant but\n-- is based on 'H.zipWithVector' from 'H.Domain'.\ndzipWithVector\n :: ( KnownNat n\n , H.Domain field vec mat\n , Num (vec n)\n , Backprop (vec n)\n , Backprop field\n , Reifies s W\n )\n => (forall s'. Reifies s' W => BVar s' field -> BVar s' field -> BVar s' field)\n -> BVar s (vec n)\n -> BVar s (vec n)\n -> BVar s (vec n)\ndzipWithVector f = liftOp2 . op2 $ \\x y ->\n ( H.zipWithVector (evalBP2 f) x y\n , \\d -> let dx = H.zipWithVector (\\x' -> fst . gradBP2 f x') x y\n dy = H.zipWithVector (\\x' -> snd . gradBP2 f x') x y\n in (d * dx, d * dy)\n )\n{-# INLINE dzipWithVector #-}\n\ndet :: ( KnownNat n\n , Num (mat n n)\n , Backprop (mat n n)\n , H.Domain field vec mat\n , H.Sized field (mat n n) d\n , HU.Transposable (mat n n) (mat n n)\n , Reifies s W\n )\n => BVar s (mat n n)\n -> BVar s field\ndet = liftOp1 . op1 $ \\x ->\n let xDet = H.det x\n xInv = H.inv x\n in ( xDet, \\d -> H.konst (d * xDet) * H.tr xInv )\n{-# INLINE det #-}\n\n-- | The inverse and the natural log of the determinant together. If you\n-- know you don't need the inverse, it is best to use 'lndet'.\ninvlndet\n :: forall n mat field vec d s.\n ( KnownNat n\n , Num (mat n n)\n , H.Domain field vec mat\n , H.Sized field (mat n n) d\n , HU.Transposable (mat n n) (mat n n)\n , Backprop field\n , Backprop (mat n n)\n , Reifies s W\n )\n => BVar s (mat n n)\n -> (BVar s (mat n n), (BVar s field, BVar s field))\ninvlndet v = (t ^^. _1, (t ^^. _2, t ^^. _3))\n where\n o :: Op '[mat n n] (mat n n, field, field)\n o = op1 $ \\x ->\n let (i,(ldet, s)) = H.invlndet x\n iTr = H.tr i\n in ( (i, ldet, s)\n , \\(dI, dLDet, _) ->\n let gradI = - iTr `H.mul` dI `H.mul` iTr\n gradLDet = H.konst dLDet * H.tr i\n in gradI + gradLDet\n )\n {-# INLINE o #-}\n t = liftOp1 o v\n {-# NOINLINE t #-}\n{-# INLINE invlndet #-}\n\n-- | The natural log of the determinant.\nlndet\n :: forall n mat field vec d s.\n ( KnownNat n\n , Num (mat n n)\n , Backprop (mat n n)\n , H.Domain field vec mat\n , H.Sized field (mat n n) d\n , HU.Transposable (mat n n) (mat n n)\n , Reifies s W\n )\n => BVar s (mat n n)\n -> BVar s field\nlndet = liftOp1 . op1 $ \\x ->\n let (i,(ldet,_)) = H.invlndet x\n in (ldet, (* H.tr i) . H.konst)\n{-# INLINE lndet #-}\n\ninv :: ( KnownNat n\n , Num (mat n n)\n , Backprop (mat n n)\n , H.Domain field vec mat\n , HU.Transposable (mat n n) (mat n n)\n , Reifies s W\n )\n => BVar s (mat n n)\n -> BVar s (mat n n)\ninv = liftOp1 . op1 $ \\x ->\n let xInv = H.inv x\n xInvTr = H.tr xInv\n in ( xInv, \\d -> - xInvTr `H.mul` d `H.mul` xInvTr )\n{-# INLINE inv #-}\n\ntoRows\n :: forall m n s. (KnownNat m, KnownNat n, Reifies s W)\n => BVar s (H.L m n)\n -> SV.Vector m (BVar s (H.R n))\ntoRows = runABP . sequenceVar\n . isoVar (coerce (H.lRows @m)) (coerce H.rowsL)\n{-# INLINE toRows #-}\n\ntoColumns\n :: forall m n s. (KnownNat m, KnownNat n, Reifies s W)\n => BVar s (H.L m n)\n -> SV.Vector n (BVar s (H.R m))\ntoColumns = runABP . sequenceVar\n . isoVar (coerce (H.lCols @_ @n)) (coerce H.colsL)\n{-# INLINE toColumns #-}\n\nfromRows\n :: forall m n s. (KnownNat m, KnownNat n, Reifies s W)\n => SV.Vector m (BVar s (H.R n))\n -> BVar s (H.L m n)\nfromRows = isoVar (coerce H.rowsL) (coerce (H.lRows @m))\n . collectVar . ABP\n{-# INLINE fromRows #-}\n\nfromColumns\n :: forall m n s. (KnownNat n, KnownNat m, Reifies s W)\n => SV.Vector n (BVar s (H.R m))\n -> BVar s (H.L m n)\nfromColumns = isoVar (coerce H.colsL) (coerce (H.lCols @_ @n))\n . collectVar . ABP\n{-# INLINE fromColumns #-}\n\nkonst\n :: forall t s d q.\n ( H.Sized t s d\n , HU.Container d t\n , Backprop t\n , Reifies q W\n )\n => BVar q t\n -> BVar q s\nkonst = liftOp1 . op1 $ \\x ->\n ( H.konst x\n , HU.sumElements . H.extract\n )\n{-# INLINE konst #-}\n\nsumElements\n :: forall t s d q.\n ( H.Sized t s d\n , HU.Container d t\n , Backprop s\n , Reifies q W\n )\n => BVar q s\n -> BVar q t\nsumElements = liftOp1 . op1 $ \\x ->\n ( HU.sumElements . H.extract $ x\n , H.konst\n )\n{-# INLINE sumElements #-}\n\n-- | If there are extra items in the total derivative, they are dropped.\n-- If there are missing items, they are treated as zero.\nextractV\n :: forall t s q.\n ( H.Sized t s HU.Vector\n , HU.Konst t Int HU.Vector\n , HU.Container HU.Vector t\n , Backprop s\n , Reifies q W\n )\n => BVar q s\n -> BVar q (HU.Vector t)\nextractV = liftOp1 . op1 $ \\x ->\n let n = H.size x\n in ( H.extract x\n , \\d -> let m = HU.size d\n m' = case compare n m of\n LT -> HU.subVector 0 n d\n EQ -> d\n GT -> HU.vjoin [d, HU.konst 0 (n - m)]\n in fromJust . H.create $ m'\n )\n{-# INLINE extractV #-}\n\n-- | If there are extra items in the total derivative, they are dropped.\n-- If there are missing items, they are treated as zero.\nextractM\n :: forall t s q.\n ( H.Sized t s HU.Matrix\n , Backprop s\n , HU.Konst t (Int, Int) HU.Matrix\n , HU.Container HU.Matrix t\n , Num (HU.Matrix t)\n , Reifies q W\n )\n => BVar q s\n -> BVar q (HU.Matrix t)\nextractM = liftOp1 . op1 $ \\x ->\n let (xI,xJ) = H.size x\n in ( H.extract x\n , \\d -> let (dI,dJ) = HU.size d\n m' = case (compare xI dI, compare xJ dJ) of\n (LT, LT) -> d HU.?? (HU.Take xI, HU.Take xJ)\n (LT, EQ) -> d HU.?? (HU.Take xI, HU.All)\n (LT, GT) -> d HU.?? (HU.Take xI, HU.All)\n HU.||| HU.konst 0 (xI, xJ - dJ)\n (EQ, LT) -> d HU.?? (HU.All , HU.Take xJ)\n (EQ, EQ) -> d\n (EQ, GT) -> d HU.?? (HU.All, HU.All)\n HU.||| HU.konst 0 (xI, xJ - dJ)\n (GT, LT) -> d HU.?? (HU.All, HU.Take xJ)\n HU.=== HU.konst 0 (xI - dI, xJ)\n (GT, EQ) -> d HU.?? (HU.All, HU.All)\n HU.=== HU.konst 0 (xI - dI, xJ)\n (GT, GT) -> HU.fromBlocks\n [[d,0 ]\n ,[0,HU.konst 0 (xI - dI, xJ - dJ)]\n ]\n in fromJust . H.create $ m'\n )\n{-# INLINE extractM #-}\n\ncreate\n :: (H.Sized t s d, Backprop s, Num (d t), Backprop (d t), Reifies q W)\n => BVar q (d t)\n -> Maybe (BVar q s)\ncreate = sequenceVar . isoVar H.create (maybe 0 H.extract)\n{-# INLINE create #-}\n\n\ntakeDiag\n :: ( KnownNat n\n , H.Diag (mat n n) (vec n)\n , H.Domain field vec mat\n , Num field\n , Backprop (mat n n)\n , Reifies s W\n )\n => BVar s (mat n n)\n -> BVar s (vec n)\ntakeDiag = liftOp1 . op1 $ \\x ->\n ( H.takeDiag x\n , H.diagR 0\n )\n{-# INLINE takeDiag #-}\n\n-- |\n-- \\[\n-- \\frac{1}{2} (M + M^T)\n-- \\]\nsym :: (KnownNat n, Reifies s W)\n => BVar s (H.Sq n)\n -> BVar s (H.Sym n)\nsym = liftOp1 . op1 $ \\x ->\n ( H.sym x\n , H.unSym . H.sym . H.unSym\n )\n{-# INLINE sym #-}\n\n-- |\n-- \\[\n-- M^T M\n-- \\]\nmTm :: (KnownNat m, KnownNat n, Reifies s W)\n => BVar s (H.L m n)\n -> BVar s (H.Sym n)\nmTm = liftOp1 . op1 $ \\x ->\n ( H.mTm x\n , \\d -> 2 * (x H.<> H.unSym d)\n )\n{-# INLINE mTm #-}\n\n-- | Warning: the gradient is going necessarily symmetric, and so is /not/\n-- meant to be used directly. Rather, it is meant to be used in the middle\n-- (or at the end) of a longer computation.\nunSym\n :: (KnownNat n, Reifies s W)\n => BVar s (H.Sym n)\n -> BVar s (H.Sq n)\nunSym = isoVar H.unSym unsafeCoerce\n{-# INLINE unSym #-}\n\n-- | Unicode synonym for '<.>>'\n(<·>)\n :: (KnownNat n, Reifies s W)\n => BVar s (H.R n)\n -> BVar s (H.R n)\n -> BVar s H.ℝ\n(<·>) = dot\ninfixr 8 <·>\n{-# INLINE (<·>) #-}\n\nafSV :: Backprop a => BE.AddFunc (SV.Vector n a)\nafSV = BE.AF (SV.zipWith add)\n{-# INLINE afSV #-}\n\n\n\n-- support for complex types\ntoComplex :: (KnownNat n, Reifies s W)\n => BVar s (H.R n) -> BVar s (H.R n) -> BVar s (H.C n)\ntoComplex = isoVar2 (curry H.toComplex) H.fromComplex\n{-# INLINE toComplex #-}\n\nfromComplex :: (KnownNat n, Reifies s W)\n => BVar s (H.C n) -> (BVar s (H.R n), BVar s (H.R n))\nfromComplex c = let ri = isoVar H.fromComplex H.toComplex c in (ri ^^. _1, ri ^^. _2)\n{-# INLINE fromComplex #-}\n\ncomplex :: (KnownNat n, Reifies s W)\n => BVar s (H.R n) -> BVar s (H.C n)\ncomplex = isoVar H.complex H.real\n{-# INLINE complex #-}\n\nreal :: (KnownNat n, Reifies s W)\n => BVar s (H.C n) -> BVar s (H.R n)\nreal = isoVar H.real (\\r -> H.toComplex (r, H.konst 0))\n{-# INLINE real #-}\n\nimag :: (KnownNat n, Reifies s W)\n => BVar s (H.C n) -> BVar s (H.R n)\nimag = isoVar H.imag (\\r -> H.toComplex (H.konst 0, r))\n{-# INLINE imag #-}\n\nsqMagnitude :: (KnownNat n, Reifies s W)\n => BVar s (H.C n) -> BVar s (H.R n)\nsqMagnitude c = let (r,i) = fromComplex c in r**2 + i**2\n{-# INLINE sqMagnitude #-}\n\nmagnitude :: (KnownNat n, Reifies s W)\n => BVar s (H.C n) -> BVar s (H.R n)\nmagnitude c = sqrt $ sqMagnitude c\n{-# INLINE magnitude #-}\n", "meta": {"hexsha": "360cb8fca8ccb655851bdec3f57518dc4972058f", "size": 37996, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/Static/Backprop.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": "src/Numeric/LinearAlgebra/Static/Backprop.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": "src/Numeric/LinearAlgebra/Static/Backprop.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": 28.0827790096, "max_line_length": 98, "alphanum_fraction": 0.5042372881, "num_tokens": 12737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.769080247656264, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5377827585025055}} {"text": "{-# OPTIONS_GHC -Wall #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TypeFamilies #-}\nmodule DataRep where\n\nimport Prelude hiding ((.), id, curry, uncurry)\nimport Control.Exception (assert)\nimport Data.List\nimport Data.Proxy\nimport qualified Data.Vector.Generic as VG\nimport Foreign.Storable\nimport qualified Numeric.LinearAlgebra as HM\n\nimport qualified Base\nimport Base hiding (Scalable (..))\n\n-- ------------------------------------------------------------------------\n\nclass (Fractional (Scalar a), Storable (Scalar a), HM.Numeric (Scalar a), Additive a) => VectorSpace a where\n type Scalar a\n dim :: Proxy a -> Int\n toVector :: a -> HM.Vector (Scalar a)\n fromVector :: HM.Vector (Scalar a) -> a\n\n scale :: Scalar a -> a -> a\n scale a = fromVector . HM.scale a . toVector\n\nlinComb :: VectorSpace a => [(a, Scalar a)] -> a\nlinComb xs = foldl' (.+.) zero [scale s a | (a,s) <- xs]\n\ninstance VectorSpace Double where\n type Scalar Double = Double\n scale = (*)\n dim _ = 1\n toVector = VG.singleton\n fromVector = (VG.! 0)\n\ninstance (VectorSpace a, VectorSpace b, Scalar a ~ Scalar b) => VectorSpace (a, b) where\n type Scalar (a, b) = Scalar a\n scale s (a,b) = (scale s a, scale s b)\n dim _ = dim (Proxy :: Proxy a) + dim (Proxy :: Proxy b)\n toVector (a,b) = toVector a <> toVector b\n fromVector v =\n case VG.splitAt (dim (Proxy :: Proxy a)) v of\n (v1, v2) -> (fromVector v1, fromVector v2)\n\n-- ------------------------------------------------------------------------\n\nnewtype LinMap s a b = LinMap (HM.Matrix s)\n\n{-\ninfixr 0 ⊸\n\ndata a ⊸ b where\n LinMap :: (Scalar a ~ Scalar b) => !(HM.Matrix (Scalar a)) -> a ⊸ b\n\nと書けると格好良いが、スカラー型の異なるベクトル空間の直積とかで困ったことになる。\n-}\n\ninstance Category (LinMap s) where\n type Obj (LinMap s) a = (VectorSpace a, Scalar a ~ s)\n\n id :: forall a. Obj (LinMap s) a => LinMap s a a\n id = LinMap $ HM.ident $ dim (Proxy :: Proxy a)\n\n LinMap m1 . LinMap m2 = LinMap (m1 HM.<> m2)\n\ninstance ToFun (LinMap s) where\n toFun (LinMap m) a = fromVector (m HM.#> toVector a)\n\ninstance (VectorSpace a, VectorSpace b, Scalar a ~ s, Scalar b ~ s) => Additive (LinMap s a b) where\n zero = LinMap $ HM.konst 0 (m, n)\n where\n m = dim (Proxy :: Proxy a)\n n = dim (Proxy :: Proxy b)\n LinMap m1 .+. LinMap m2 = LinMap $ HM.add m1 m2\n\ninstance (VectorSpace a, VectorSpace b, Scalar a ~ s, Scalar b ~ s) => VectorSpace (LinMap s a b) where\n type Scalar (LinMap s a b) = s\n scale s (LinMap m) = LinMap (HM.scale s m)\n dim _ = dim (Proxy :: Proxy a) * dim (Proxy :: Proxy b)\n toVector (LinMap m) = HM.flatten m\n fromVector v = LinMap (HM.reshape (dim (Proxy :: Proxy b)) v)\n\ninstance Monoidal (LinMap s) where\n LinMap m1 >< LinMap m2 = LinMap $ HM.diagBlock [m1, m2]\n monObj = ObjR\n\ninstance Cartesian (LinMap s) where\n exl :: forall a b. (Obj (LinMap s) a, Obj (LinMap s) b) => LinMap s (a,b) a\n exl = LinMap $ HM.ident m HM.||| HM.konst 0 (m, n)\n where\n m = dim (Proxy :: Proxy a)\n n = dim (Proxy :: Proxy b)\n\n exr :: forall a b. (Obj (LinMap s) a, Obj (LinMap s) b) => LinMap s (a,b) b\n exr = LinMap $ HM.konst 0 (n, m) HM.||| HM.ident n\n where\n m = dim (Proxy :: Proxy a)\n n = dim (Proxy :: Proxy b)\n\n dup :: forall a. Obj (LinMap s) a => LinMap s a (a,a)\n dup = LinMap $\n HM.ident n\n HM.===\n HM.ident n\n where\n n = dim (Proxy :: Proxy a)\n\ninstance Cocartesian (LinMap s) where\n inl :: forall a b. (Obj (LinMap s) a, Obj (LinMap s) b) => LinMap s a (a,b)\n inl = LinMap $\n HM.ident m\n HM.===\n HM.konst 0 (n, m)\n where\n m = dim (Proxy :: Proxy a)\n n = dim (Proxy :: Proxy b)\n\n inr :: forall a b. (Obj (LinMap s) a, Obj (LinMap s) b) => LinMap s b (a,b)\n inr = LinMap $\n HM.konst 0 (n, m)\n HM.===\n HM.ident m\n where\n m = dim (Proxy :: Proxy a)\n n = dim (Proxy :: Proxy b)\n\n jam :: forall a. (Obj (LinMap s) a) => LinMap s (a,a) a\n jam = LinMap $ HM.ident n HM.||| HM.ident n\n where\n n = dim (Proxy :: Proxy a)\n\ninstance (VectorSpace s, Scalar s ~ s) => Base.Scalable (LinMap s) s where\n scale s = assert (dim (Proxy :: Proxy s) == 1) $ LinMap ((1 HM.>< 1) [s])\n\n-- ------------------------------------------------------------------------\n\n-- | Dual vector space\nnewtype Dual a = Dual (LinMap (Scalar a) a (Scalar a))\n\ninstance VectorSpace a => Additive (Dual a) where\n zero = Dual $ LinMap $ HM.konst 0 (n, 1)\n where\n n = dim (Proxy :: Proxy a)\n Dual (LinMap m1) .+. Dual (LinMap m2) = Dual $ LinMap $ HM.add m1 m2\n\ninstance VectorSpace a => VectorSpace (Dual a) where\n type Scalar (Dual a) = Scalar a\n scale s (Dual (LinMap m)) = Dual (LinMap (HM.scale s m))\n dim _ = dim (Proxy :: Proxy a)\n toVector (Dual (LinMap m)) = HM.flatten m\n fromVector v = Dual (LinMap (HM.reshape 1 v))\n\ntoDual :: VectorSpace a => a -> Dual a\ntoDual a = Dual $ LinMap $ HM.asRow (toVector a)\n\ntoDualMap :: forall a b s. (VectorSpace a, VectorSpace b, Scalar a ~ s, Scalar b ~ s) => LinMap s a b -> LinMap s (Dual b) (Dual a)\ntoDualMap (LinMap m) = LinMap (HM.tr' m)\n\nfromDual :: forall a. VectorSpace a => Dual a -> a\nfromDual (Dual (LinMap m)) = fromVector $ HM.flatten m\n\nfromDualMap :: forall a b s. (VectorSpace a, VectorSpace b, Scalar a ~ s, Scalar b ~ s) => LinMap s (Dual b) (Dual a) -> LinMap s a b\nfromDualMap (LinMap m) = LinMap (HM.tr' m)\n\ninstance (VectorSpace u, VectorSpace s, Scalar u ~ s, Scalar s ~ s) => Base.HasDot (LinMap s) s u where\n dot x = case toDual x of Dual f -> f\n undot f = fromDual (Dual f)\n\n-- ------------------------------------------------------------------------\n\ntestDual = (toFun f (2,1) == 7, toFun f2 (2,1) == 7)\n where\n f :: LinMap Double (Double, Double) Double\n f = LinMap $ HM.asRow (VG.fromList [2,3])\n f2 = fromDualMap (toDualMap f)\n\n-- ------------------------------------------------------------------------\n\ndata a :⊗ b where\n TensorProd :: (Scalar a ~ s, Scalar b ~ s) => HM.Matrix s -> a :⊗ b\n\ninstance (VectorSpace a, VectorSpace b, Scalar a ~ Scalar b) => Additive (a :⊗ b) where\n zero = TensorProd (HM.konst 0 (m, n))\n where\n m = dim (Proxy :: Proxy a)\n n = dim (Proxy :: Proxy b)\n TensorProd m1 .+. TensorProd m2 = TensorProd $ m1 `HM.add` m2\n\ninstance (VectorSpace a, VectorSpace b, Scalar a ~ Scalar b) => VectorSpace (a :⊗ b) where\n type Scalar (a :⊗ b) = Scalar a\n scale s (TensorProd m) = TensorProd $ HM.scale s m\n dim _ = dim (Proxy :: Proxy a) * dim (Proxy :: Proxy b)\n toVector (TensorProd m) = HM.flatten m\n fromVector v = TensorProd (HM.reshape (dim (Proxy :: Proxy b)) v)\n\n\ncurry\n :: forall a b c s. (VectorSpace a, VectorSpace b, VectorSpace c, Scalar a ~ s, Scalar b ~ s, Scalar c ~ s)\n => LinMap s (a :⊗ b) c -> LinMap s a (LinMap s b c)\ncurry (LinMap m) = LinMap $ HM.reshape (nb*nc) $ HM.flatten m\n where\n nb = dim (Proxy :: Proxy b)\n nc = dim (Proxy :: Proxy c)\n\nuncurry\n :: forall a b c s. (VectorSpace a, VectorSpace b, VectorSpace c, Scalar a ~ s, Scalar b ~ s, Scalar c ~ s)\n => LinMap s a (LinMap s b c) -> LinMap s (a :⊗ b) c\nuncurry (LinMap m) = LinMap $ HM.reshape nc $ HM.flatten m\n where\n nc = dim (Proxy :: Proxy c)\n\nmapTensor\n :: forall a b c d s.\n (VectorSpace a, VectorSpace b, VectorSpace c, VectorSpace d, Scalar a ~ s, Scalar b ~ s, Scalar c ~ s, Scalar d ~ s)\n => LinMap s a b -> LinMap s c d -> LinMap s (a :⊗ c) (b :⊗ d)\nmapTensor (LinMap m1) (LinMap m2) = LinMap $ ((na*nc) HM.>< (nb*nd)) [(m1 `HM.atIndex` (i, k)) * (m2 `HM.atIndex` (j, l)) | i <- [0..na-1], j <- [0..nc-1], k <- [0..nb-1], l <- [0..nd-1]]\n where\n na = dim (Proxy :: Proxy a)\n nb = dim (Proxy :: Proxy b)\n nc = dim (Proxy :: Proxy c)\n nd = dim (Proxy :: Proxy d)\n\nTensorProd test_Tensor = toFun h t\n where\n f, g :: LinMap Double Double Double\n f = Base.scale 2\n g = Base.scale 3\n h :: LinMap Double (Double :⊗ Double) (Double :⊗ Double)\n h = mapTensor f g\n\n t :: Double :⊗ Double\n t = TensorProd $ (1 HM.>< 1) [4]\n", "meta": {"hexsha": "f450a3b502889023e948b7cd905008a9f7fa8fc6", "size": 8132, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/DataRep.hs", "max_stars_repo_name": "msakai/essence-of-ad", "max_stars_repo_head_hexsha": "3a3b83e574b57a0deadb3039ffd654970d61f31f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-03-05T07:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T22:18:47.000Z", "max_issues_repo_path": "src/DataRep.hs", "max_issues_repo_name": "msakai/essence-of-ad", "max_issues_repo_head_hexsha": "3a3b83e574b57a0deadb3039ffd654970d61f31f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DataRep.hs", "max_forks_repo_name": "msakai/essence-of-ad", "max_forks_repo_head_hexsha": "3a3b83e574b57a0deadb3039ffd654970d61f31f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-05T07:00:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T07:00:29.000Z", "avg_line_length": 33.7427385892, "max_line_length": 187, "alphanum_fraction": 0.5785784555, "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5375871576343819}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_HADDOCK show-extensions #-}\n\n-- |\n-- Module : Swarm\n-- Description : Particle Swarm Optimisation\n-- Copyright : (c) Tom Westerhout, 2017\n-- License : BSD3\n-- Maintainer : t.westerhout@student.ru.nl\n-- Stability : experimental\nmodule PSO.Swarm\n ( -- * Idea\n --\n -- | This module implements different variants of Particle Swarm\n -- Optimisation (PSO), so if you're completely unfamiliar with PSO, go read\n -- https://en.wikipedia.org/wiki/Particle_swarm_optimization first, it's a\n -- nice introduction.\n --\n -- Let there be \\(M\\in\\mathbb{N}\\) 'Bee's in the swarm. Bees live in a phase\n -- space (which is a vector space). What this means is that each bee is\n -- described by a phase \\(\\psi\\). The two most common choices of the phase\n -- are:\n --\n -- * \\((q, p)\\in\\mathcal{H}^2\\) with \\(q\\) being the canonical coordinate\n -- and \\(p\\) being the canonical momentum.\n -- * \\(|\\psi\\rangle\\in\\mathcal{H}^2\\), i.e. a vector in Hilbert space.\n --\n -- While flying around, bees may pick up some information about the\n -- surrounding environment. We call the part of it that bees remember a\n -- local (or private) /guide/. It's a guide because it helps bees decide\n -- where to move next. The simplest and most common guide is 'BeeGuide'.\n --\n -- The whole point of having a swarm of bees rather than one bee is\n -- collective behavior. In case of PSO this is achieved by having a /global\n -- guide/. Each bee then uses this global guide, its own local guide, and\n -- its current phase to compute the next phase. This is represented by\n -- 'PhaseUpdater'.\n --\n -- The whole optimisation process then looks more or less like this:\n --\n -- 1. __Initialisation__ (see 'mkSwarm' function).\n --\n -- * Generate initial phases \\((\\psi^{(0)}_i)_{i\\in\\{1\\dots M\\}}\\).\n -- * Evaluate fitness in these phases, i.e. compute\n -- \\((f(\\psi^{(0)}_i))_{i\\in\\{1\\dots M\\}}\\) (see 'mkBee' function).\n -- * Initialise local guides \\((g^{(0)}_{l,i})_{i\\in\\{1\\dots M\\}}\\)\n -- (see 'mkLocalG' function).\n -- * Construct bees using phases, fitness values, and guides (see\n -- 'mkBee' function).\n -- * Initialise global guide \\(g^{(0)}_g\\) (see 'mkGlobalG'\n -- function).\n -- * Construct swarm using bees and global guide.\n --\n -- 2. __Main Loop__. While the termination condition is not met, do the\n -- following (see 'updateSwarm' function):\n --\n -- * Update each bee (see 'updateBee' function), i.e.\n --\n -- * Using global guide \\(g^{(n)}_g\\), local guide\n -- \\(g^{(n)}_{l,i}\\), current phase \\(\\psi^{(n)}_i\\), and\n -- \\(f(\\psi^{(n)}_i)\\), come up with a new phase\n -- \\(\\psi^{(n+1)}_i\\) (see 'PhaseUpdater').\n -- * Evaluate the fitness in this new phase, i.e. compute\n -- \\(f(\\psi^{(n+1)}_i)\\).\n -- * Using \\(\\psi^{(n+1)}_i\\) and \\(f(\\psi^{(n+1)}_i)\\), compute\n -- the local guide in the next iteration \\(g^{(n+1)}_i\\) (see\n -- 'updateLocalG' function).\n --\n -- * Update the global guide (see 'updateGlobalG' function).\n --\n\n -- * Basic types\n Bee(..)\n , CMState(..)\n , QMState(..)\n , LocalGuide(..)\n , BeeGuide(..)\n , GlobalGuide(..)\n , SwarmGuide(..)\n , Swarm(..)\n , PhaseUpdater(..)\n\n -- * Important functions\n , wpgUpdater\n -- , kickUpdater\n , deltaUpdater\n , absorbUpdater\n , mkCMState\n , mkQMState\n , optimiseND\n , optimiseNDFromList\n\n -- * Details\n , VelocityUpdater(..)\n , upScale\n , upLocal\n , upGlobal\n , upStep\n , updateBee\n , updateSwarm\n , mkBee\n , mkSwarm\n , fromPure\n , iterateNM\n , iterateWhileM\n , Absorbable(..)\n , DeltaWell(..)\n , Scalable(..)\n\n -- * Lenses\n , HasPos(..)\n , HasVal(..)\n , HasVar(..)\n , HasGuide(..)\n , HasState(..)\n , HasRun(..)\n , HasBees(..)\n , HasUpdater(..)\n , HasIteration(..)\n ) where\n\nimport Data.Complex\nimport Data.Ord(comparing)\nimport qualified Data.List as List\n-- import Data.Monoid\nimport Data.Semigroup\nimport qualified Data.Vector.Generic as GV\nimport qualified Data.Vector.Storable as V\n\nimport Control.Arrow\n-- import Control.Lens\nimport Lens.Micro\nimport Lens.Micro.TH\nimport Lens.Micro.Extras\nimport Control.DeepSeq\nimport Control.Monad\nimport Control.Monad.Primitive\nimport Control.Monad.Reader\n\nimport qualified Foreign\nimport Foreign.Storable.Tuple\n\nimport GHC.Float (float2Double)\nimport GHC.Generics(Generic)\n\n-- import qualified Numeric.LinearAlgebra as LA\n-- import Numeric.LinearAlgebra.Devel(matrixFromVector, orderOf, MatrixOrder(..))\n-- import Numeric.LinearAlgebra.Data(flatten, tr)\n-- import qualified Numeric.LinearAlgebra.Devel as LADevel\n\nimport PSO.VectorSpace\nimport PSO.Random\n\n\n-- | A bee in our swarm.\n--\n-- * @α@ is the type of a point in our phase space (i.e. position-velocity pair\n-- in the classical case and wave function in the quantum mechanical)\n-- * @β@ is the type of the local guide, i.e. \\\"memory\\\" of the bee.\n-- * @r@ return type of the function we're minimising.\n--\n-- /Note:/ use 'state', 'guide', and 'val' lenses to access the fields.\ndata Bee α β r = Bee\n { _beeState :: !α\n , _beeGuide :: !β\n , _beeVal :: !r\n } deriving (Generic, Show, NFData)\n\nmakeLensesWith abbreviatedFields ''Bee\n\n\n-- | Point in the classical phase space.\n--\n-- @χ@ -- vector in coordinate space. We always use time steps of 1, so physical\n-- dimension of velocity is equal to the one of coordinate. The type of velocity\n-- is thus also @χ@.\n--\n-- /Note:/ use 'pos' and 'vel' lenses to access the fields.\ndata CMState χ = CMState\n { _cmstatePos :: !χ\n , _cmstateVel :: !χ\n } deriving (Generic, Show, NFData)\n\nmakeLensesWith abbreviatedFields ''CMState\n\n-- | Point in our quantum mechanical phase space (i.e. Hilbert space).\n--\n-- /Note:/ use 'pos' lens to access the field.\ndata QMState χ = QMState\n { _qmstatePos :: !χ\n } deriving (Generic, Show, NFData)\n\nmakeLensesWith abbreviatedFields ''QMState\n\n-- | Rather than limiting ourselves to a single type of local guide (because who\n-- knows which info we might want to keep track of), we define a type class.\n-- @LocalGuide β α r@ means that @β@ is a local guide for a bee with phase of\n-- type @α@ and fitness function returning @r@.\nclass LocalGuide β α r where\n -- | Initialisation of a guide. Given a phase \\(\\psi^{(0)}\\) and its fitness\n -- \\(f(\\psi^{(0)})\\), @mkLocalG@ creates local guide \\(g^{(0)}_l\\).\n mkLocalG :: α -> r -> β\n -- | Update step. After computing the phase \\(\\psi^{(n+1)}\\) (of type @α@) and\n -- its fitness \\(f(\\psi^{(n+1)})\\) (of type @r@) in the @(n+1)@'st iteration,\n -- we use @updateLocalG@ to compute \\(g^{(n+1)}_l\\) given \\(g^{(n)}_l\\).\n updateLocalG :: α -> r -> β -> β\n\n-- | Similar to 'LocalGuide' we define a class of global guides rather than a\n-- single one. Here, @GlobalGuide γ β@ means that @γ@ can serve as a global\n-- guide for local guides of type @β@.\nclass (LocalGuide β α r) => GlobalGuide γ β α r where\n -- | Initialisation of a guide. Given a collection of bees, @mkLocalG@\n -- initialises global guide \\(g^{(0)}_g\\).\n mkGlobalG :: (Foldable t, Functor t) => t (Bee α β r) -> γ\n -- | Update step. After computing phases, values, and local guides of bees in\n -- the @(n+1)@'st iteration, we use @updateLocalG@ to compute \\(g^{(n+1)}_g\\)\n -- given \\(g^{(n)}_g\\).\n updateGlobalG :: (Foldable t, Functor t) => t (Bee α β r) -> γ -> γ\n\n-- | A guide that remembers position and its corresponding fitness.\n--\n-- /Note:/ use 'pos' and 'val' lenses to access the fields.\ndata BeeGuide χ r = BeeGuide\n { _beeguidePos :: !χ -- ^ Position.\n , _beeguideVal :: !r -- ^ Fitness value.\n } deriving (Generic, Show)\n\nmakeLensesWith abbreviatedFields ''BeeGuide\n\ninstance (NFData χ, NFData r) => NFData (BeeGuide χ r)\n\n-- | We compare guides by their fitness values.\ninstance Eq r => Eq (BeeGuide χ r) where\n x == y = (x ^. val) == (y ^. val)\n\n-- | We compare guides by their fitness values.\ninstance Ord r => Ord (BeeGuide χ r) where\n compare = comparing (view val)\n\n-- | 'BeeGuide' is the simplest and, probably, the most useful example of a\n-- 'LocalGuide'. It keeps track of the best position and its fitness. That is,\n-- if we've run @n@ iterations (calls to 'updateLocalG'), then the best position\n-- is given by \\(\\operatorname{argmin}_{k\\in\\{0\\dots n\\}}f(\\psi^{(k)}_i)\\), and\n-- its fitness is just \\(\\operatorname{min}_{k\\in\\{0\\dots n\\}}f(\\psi^{(k)}_i)\\).\ninstance (HasPos α χ, Ord r) => LocalGuide (BeeGuide χ r) α r where\n mkLocalG ψ fψ = BeeGuide (ψ ^. pos) fψ\n updateLocalG ψ fψ g\n | fψ < g ^. val = g & (pos .~ (ψ ^. pos))\n & (val .~ fψ)\n | otherwise = g\n\n-- | 'BeeGuide' can also serve as a 'GlobalGuide'. It keeps track of the overall\n-- best position among all bees and iterations and its fitness. So after @n@\n-- iterations, the best position is given by\n-- \\(\\operatorname{argmin}_{k\\in\\{0\\dots n\\},i\\in\\{1\\dots M\\}}f(\\psi^{(k)}_i)\\),\n-- and its fitness is\n-- \\(\\operatorname{min}_{k\\in\\{0\\dots n\\},i\\in\\{1\\dots M\\}}f(\\psi^{(k)}_i)\\).\ninstance (LocalGuide (BeeGuide χ r) α r, Ord (BeeGuide χ r))\n => GlobalGuide (BeeGuide χ r) (BeeGuide χ r) α r where\n mkGlobalG = minimum . fmap (view guide)\n updateGlobalG xs _ = minimum . fmap (view guide) $ xs\n\n-- | A guide that remembers\n--\n-- * Best position throughout the whole swarm.\n-- * Fitness value at this position.\n-- * Current iteration.\n-- * Variance in the fitness values of the local guides.\n--\n-- /Note:/ use 'pos', 'val', 'iteration', and 'var' lenses to access the fields.\ndata SwarmGuide χ r = SwarmGuide\n { _swarmguidePos :: !χ\n , _swarmguideVal :: !r\n , _swarmguideIteration :: !Int\n , _swarmguideVar :: () -- !r\n } deriving (Generic, Show)\n\nmakeLensesWith abbreviatedFields ''SwarmGuide\n\ninstance (NFData χ, NFData r) => NFData (SwarmGuide χ r)\n\n-- | Calculates the mean value of a sequence.\nmean :: (Fractional a, Foldable v) => v a -> a\nmean xs = sum xs / fromIntegral (length xs)\n\n-- | Calculates the variance in a sequence.\nvariance :: (Fractional a, Foldable v, Functor v) => v a -> a\nvariance xs = let m = mean xs in mean . fmap (\\x -> (x - m)^^2) $ xs\n\n-- | 'SwarmGuide' is another example of a 'GlobalGuide'. On top of keeping track\n-- of the best position and its fitness value (what 'BeeGuide' does), we\n-- remember the current iteration ('mkGlobalG' sets it to @0@, and each call to\n-- 'updateGlobalG' increases the iteration by @1@). And finally, each iteration\n-- we compute the variance \\(\\operatorname{Var}\\{f(\\psi^{(n)}_i)\\}_i\\) in the\n-- fitness values of bees.\ninstance (LocalGuide (BeeGuide χ r) α r, Ord (BeeGuide χ r))\n => GlobalGuide (SwarmGuide χ r) (BeeGuide χ r) α r where\n mkGlobalG xs = SwarmGuide (x ^. pos) (x ^. val) 0 var\n where x = minimum . fmap (view guide) $ xs\n var = () -- variance . fmap (view val) $ xs\n updateGlobalG xs g = mkGlobalG xs & iteration .~ (g ^. iteration + 1)\n\n-- | Given global guide and bee in the @n@'th iteration, calculates the phase of\n-- the bee in the @(n+1)@'st iteration. This calculation is done in some 'Monad'\n-- @m@ which allows us to, for example, use random numbers when updating the\n-- phase.\n--\n-- /Note:/ use 'run' lens to unpack the function.\nnewtype PhaseUpdater m γ β α r = PhaseUpdater\n { _phaseupdaterRun :: γ -> Bee α β r -> m α\n }\n\nmakeLensesWith abbreviatedFields ''PhaseUpdater\n\n-- | 'PhaseUpdater's can be combined to build more difficult ones.\ninstance (Monad m) => Semigroup (PhaseUpdater m γ β α r) where\n (PhaseUpdater a) <> (PhaseUpdater b) = PhaseUpdater update\n where update guide bee = a guide bee >>= \\ψ ->\n b guide (bee & state .~ ψ)\n\n-- | Our swarm.\ndata Swarm m γ β α r = Swarm\n { _swarmBees :: ![Bee α β r] -- ^ Collection of bees.\n , _swarmGuide :: !γ -- ^ Global guide.\n , _swarmFunc :: !(α -> m r) -- ^ Fitness function.\n , _swarmUpdater :: !(PhaseUpdater m γ β α r) -- ^ Updater.\n }\n\nmakeLensesWith abbreviatedFields ''Swarm\n\n-- | Updates the canonical momentum in the classical phase. Given a global guide\n-- and a bee described by classical mechanics, returns the momentum of the bee\n-- in the next iteration. 'VelocityUpdater's can be combined using '<>' operator\n-- and afterwards converted to 'PhaseUpdater's using 'upStep' function.\nnewtype VelocityUpdater m γ χ r = VelocityUpdater\n { _velocityupdaterRun :: γ -> Bee (CMState χ) (BeeGuide χ r) r -> m χ\n }\n\nmakeLensesWith abbreviatedFields ''VelocityUpdater\n\n-- | 'VelocityUpdater's can be combined to form more complex ones.\ninstance (Monad m) => Semigroup (VelocityUpdater m γ χ r) where\n (VelocityUpdater a) <> (VelocityUpdater b) = VelocityUpdater $ update\n where update guide bee =\n a guide bee >>= \\v -> b guide (bee & (state . vel) .~ v)\n\n-- | Given a constant \\(\\varphi_l\\), creates a 'VelocityUpdater' that updates\n-- momentum according to\n-- \\[\n-- p^{(n+1)} = p^{(n)} + \\varphi_l U(0, 1) \\circ (g^{(n)}_l - q^{(n)}) \\;,\n-- \\]\n-- where \\(\\circ\\) denotes the Hadamard product, \\(U(0, 1)\\) is a vector\n-- whose elements are uniformly distributed in the \\([0, 1)\\) interval, and\n-- \\(g^{(n)}_l\\) is local best position in the @n@'th iteration.\nupLocal :: (RandomScalable m χ, VectorSpace χ λ) => λ -> VelocityUpdater m γ χ r\nupLocal φl = VelocityUpdater $ upLocalImpl φl\n\nupLocalImpl ::\n (RandomScalable m χ, VectorSpace χ λ, HasPos α χ, HasVel α χ, HasPos β χ)\n => λ -> γ -> Bee α β r -> m χ\nupLocalImpl φ _ bee =\n let δq = bee ^. guide . pos - bee ^. state . pos\n p = bee ^. state . vel\n in liftM (scale φ) (randScale δq) >>= \\δp -> return (p + δp)\n\n-- | Given a constant \\(\\varphi_g\\), creates a 'VelocityUpdater' that updates\n-- momentum according to\n-- \\[\n-- p^{(n+1)} = p^{(n)} + \\varphi_g U(0, 1) \\circ (g^{(n)}_g - q^{(n)}) \\;,\n-- \\]\n-- where \\(\\circ\\) denotes the Hadamard product, \\(U(0, 1)\\) is a vector\n-- whose elements are uniformly distributed in the \\([0, 1)\\) interval, and\n-- \\(g^{(n)}_g\\) is global best position in the @n@'th iteration.\nupGlobal ::\n (RandomScalable m χ, VectorSpace χ λ, HasPos γ χ)\n => λ -> VelocityUpdater m γ χ r\nupGlobal φg = VelocityUpdater $ upGlobalImpl φg\n\nupGlobalImpl ::\n (RandomScalable m χ, VectorSpace χ λ, HasPos α χ, HasVel α χ, HasPos γ χ)\n => λ -> γ -> Bee α β r -> m χ\nupGlobalImpl φ g bee = do\n let δq = g ^. pos - bee ^. state . pos\n p = bee ^. state . vel\n in liftM (scale φ) (randScale δq) >>= \\δp -> return (p + δp)\n\n-- | Given a constant \\(\\omega\\), creates a 'VelocityUpdater' that updates\n-- momentum according to\n-- \\[\n-- p^{(n+1)} = \\omega p^{(n)} \\;.\n-- \\]\nupScale :: (Monad m, Scalable λ χ) => λ -> VelocityUpdater m γ χ r\nupScale ω = VelocityUpdater $ upScaleImpl ω\n\nupScaleImpl :: (Monad m, Scalable λ χ, HasVel α χ) => λ -> γ -> Bee α β r -> m χ\nupScaleImpl ω _ = return . scale ω . view (state . vel)\n\n-- | Converts a 'VelocityUpdater' into a 'PhaseUpdater'. This is done by first\n-- running the velocity updater to compute \\(p^{(n+1)}\\). \\(q^{(n+1)}\\) is then\n-- calculated as \\(q^{(n)} + p^{(n+1)}\\).\nupStep ::\n (Monad m, Num χ)\n => VelocityUpdater m γ χ r -> PhaseUpdater m γ (BeeGuide χ r) (CMState χ) r\nupStep (VelocityUpdater upVel) = PhaseUpdater update\n where update guide bee = do\n δq <- upVel guide bee\n let x = bee ^. state\n q = x ^. pos\n return $ x & (vel .~ δq)\n & (pos .~ q + δq)\n\n-- | Creates the standard \\\"WPG\\\" updater. Given constants\n-- \\(\\omega,\\varphi_l,\\varphi_g\\), creates a 'PhaseUpdater' that updates the\n-- phase according to\n-- \\[\n-- \\left\\{\n-- \\begin{aligned}\n-- p^{(n+1)} &= \\omega p^{(n)}\n-- + \\varphi_l U_l(0, 1) \\circ (g^{(n)}_l - q^{(n)})\n-- + \\varphi_g U_g(0, 1) \\circ (g^{(n)}_g - q^{(n)}) \\;, \\\\\n-- q^{(n+1)} &= q^{(n)} + p^{(n+1)} \\;,\n-- \\end{aligned}\n-- \\right.\n-- \\]\n-- where \\(\\circ\\) denotes the Hadamard product and \\(U_l(0, 1)\\) and\n-- \\(U_g(0,1)\\) are vectors whose elements are uniformly distributed in the\n-- \\([0, 1)\\) interval.\nwpgUpdater ::\n (RandomScalable m χ, VectorSpace χ λ, HasPos γ χ)\n => (λ, λ, λ) -> PhaseUpdater m γ (BeeGuide χ r) (CMState χ) r\nwpgUpdater (ω, φl, φg) =\n upStep $ (upScale ω) <> (upLocal φl) <> (upGlobal φg)\n\n\n-- | Creates the standard updater which uses constriction rather than inertia\n-- parameter. Given constants\n-- \\(\\kappa,\\varphi_l,\\varphi_g\\), creates a 'PhaseUpdater' that updates the\n-- phase according to\n-- \\[\n-- \\left\\{\n-- \\begin{aligned}\n-- p^{(n+1)} &= \\kappa \\left( p^{(n)}\n-- + \\varphi_l U_l(0, 1) \\circ (g^{(n)}_l - q^{(n)})\n-- + \\varphi_g U_g(0, 1) \\circ (g^{(n)}_g - q^{(n)}) \\right) \\;, \\\\\n-- q^{(n+1)} &= q^{(n)} + p^{(n+1)} \\;,\n-- \\end{aligned}\n-- \\right.\n-- \\]\n-- where \\(\\circ\\) denotes the Hadamard product and \\(U_l(0, 1)\\) and\n-- \\(U_g(0,1)\\) are vectors whose elements are uniformly distributed in the\n-- \\([0, 1)\\) interval.\nconstrictedUpdater ::\n (RandomScalable m χ, VectorSpace χ λ, HasPos γ χ)\n => (λ, λ, λ) -> PhaseUpdater m γ (BeeGuide χ r) (CMState χ) r\nconstrictedUpdater (κ, φl, φg) =\n upStep $ (upLocal φl) <> (upGlobal φg) <> (upScale κ)\n\n-- randomWalkUpdater :: (UniformDist p gen m)\n-- => (p, p) -> Updater m gen s g p r\n-- randomWalkUpdater bounds = Updater $ f\n-- where f _ _ = do\n-- randGen <- ask\n-- v' <- lift $ uniform bounds randGen\n-- return v'\n-- \n-- kickUpdater ::\n-- ( RandomScalable p gen m\n-- , UniformDist p gen m\n-- , VectorSpace p a\n-- , Scalable r p\n-- , HasVar s r\n-- , HasPos s p\n-- , HasPos g p\n-- , Floating r\n-- , Ord r\n-- , s ~ SwarmGuide p r\n-- )\n-- => (r, r) -> (p, p) -> (a, a, a) -> Updater m gen s g p r\n-- kickUpdater cutoff bounds wpg = Updater $ kickUpdaterImpl cutoff bounds wpg\n-- \n-- kickUpdaterImpl ::\n-- ( RandomScalable p gen m\n-- , UniformDist p gen m\n-- , VectorSpace p a\n-- , Scalable r p\n-- , HasVar s r\n-- , HasPos s p\n-- , HasPos g p\n-- , Floating r\n-- , Ord r\n-- )\n-- => (r, r) -> (p, p) -> (a, a, a) -> s -> Bee p r g -> ReaderT gen m p\n-- kickUpdaterImpl (cutoff, c) bounds wpg stats x = runUpdater updater stats x\n-- where updater = if (stats ^. var) < cutoff\n-- then randomWalkUpdater bounds\n-- <> upScale (c * sqrt (stats ^.var))\n-- else standardUpdater wpg\n\n\n-- | Update the position according to QDPSO (Quantum Delta well Particle Swarm\n-- Optimisation).\nclass (Monad m) => DeltaWell m λ χ where\n upDeltaWell :: λ -> χ -> χ -> m χ\n\n-- | 1D QDPSO updater. Given a constant \\(\\kappa\\in\\mathbb{R}\\), center\n-- \\(g^{(n)}\\in\\mathbb{R}\\) of the density distribution, and bees current\n-- position \\(q^{(n)}\\in\\mathbb{R}\\), its position in the next iteration is\n-- computed as\n-- \\[\n-- q^{(n+1)} =\n-- q^{(n)} + \\sgn(2\\cdot\\operatorname{rand}(0,1) - 1) \\kappa\n-- \\log(\\frac{1}{\\operatorname{rand}(0, 1)}) \\cdot\n-- |q^{(n)} - g^{(n)}| \\;.\n-- \\]\ninstance (Monad m, RealFloat λ, Ord λ, Randomisable m λ)\n => DeltaWell m λ λ where\n upDeltaWell κ p x = do\n u <- random\n sign <- (\\c -> signum (2 * c - 1)) <$> random\n return $ p + (sign * (log . recip $ u) / κ) * abs (x - p)\n\n-- | Extending QDPSO to \\(\\mathbb{C}\\). 1D real version is simply applied to\n-- both real and imaginary parts.\ninstance (RealFloat λ, DeltaWell m λ λ)\n => DeltaWell m λ (Complex λ) where\n upDeltaWell κ p x =\n let f getter = uncurry (upDeltaWell κ) . over each getter\n in return (:+) `ap` f realPart (p, x)\n `ap` f imagPart (p, x)\n\n-- | Extending QDPSO to multidimensional case. 1D version is simply applied to\n-- each component.\ninstance (Monad m, Foreign.Storable ξ, DeltaWell m λ ξ)\n => DeltaWell m λ (V.Vector ξ) where\n upDeltaWell κ p x = V.zipWithM (upDeltaWell κ) p x\n\n{-\nliftMatrix2M ::\n (Monad m, LA.Element α, LA.Element β, LA.Element γ,\n LA.Container V.Vector α, Num α,\n LA.Container V.Vector β, Num β,\n LA.Transposable (LA.Matrix α) (LA.Matrix α),\n LA.Transposable (LA.Matrix β) (LA.Matrix β))\n => (LA.Vector α -> LA.Vector β -> m (LA.Vector γ))\n -> LA.Matrix α -> LA.Matrix β -> m (LA.Matrix γ)\nliftMatrix2M f m1@(LA.size -> (r,c)) m2\n | LA.size m1 /= LA.size m2 = error \"nonconformant matrices in liftMatrix2M\"\n | orderOf m1 == RowMajor =\n return (matrixFromVector RowMajor r c) `ap` f (flatten m1) (flatten m2)\n | otherwise =\n return (matrixFromVector ColumnMajor r c) `ap`\n f (flatten . tr $ m1) (flatten . tr $ m2)\n\ninstance (Monad m, Num ξ, LA.Container V.Vector ξ, LA.Transposable (LA.Matrix ξ)(LA.Matrix ξ), DeltaWell m λ ξ)\n => DeltaWell m λ (LA.Matrix ξ) where\n upDeltaWell κ = liftMatrix2M (V.zipWithM (upDeltaWell κ))\n-}\n\n\n-- | Creates a QDPSO updater.\ndeltaUpdater :: forall m g γ β χ λ r.\n ( Randomisable m λ\n , RealFloat λ\n , Ord λ\n , VectorSpace χ λ\n , DeltaWell m λ χ\n , HasPos β χ\n , HasPos γ χ\n )\n => λ -> γ -> Bee (QMState χ) β r -> m (QMState χ)\ndeltaUpdater κ g bee = do\n φ₁ <- random :: m λ\n φ₂ <- random :: m λ\n -- lift $ putStrLn $ \"φ₁ = \" ++ show φ₁ ++ \", φ₂ = \" ++ show φ₂\n let center = (φ₁ / (φ₁ + φ₂)) `scale` (g ^. pos)\n + (φ₂ / (φ₁ + φ₂)) `scale` (bee ^. guide . pos)\n x <- upDeltaWell κ center (bee ^. state . pos)\n -- lift $ putStrLn $ \"p - x = \" ++ show (bee ^. state . pos - p)\n return $ (bee ^. state) & (pos .~ x)\n\n\n\ndata RelativePosition = Inside | LeftOf | RightOf\n\nclass RelativelyPositioned α β where\n getRelPos :: α -> β -> RelativePosition\n\ninstance (Ord λ) => RelativelyPositioned (λ, λ) λ where\n getRelPos (l, h) x\n | x < l = LeftOf\n | x > h = RightOf\n | otherwise = Inside\n\nclass Absorbable λ α where\n absorb :: (λ, λ) -> α -> α\n\nclass Reflectable λ α where\n reflect :: (λ, λ) -> α -> α\n\ninstance (Ord χ) => Absorbable χ χ where\n absorb (l, h) x\n | x < l = l\n | x > h = h\n | otherwise = x\n\ninstance (Ord λ) => Absorbable λ (Complex λ) where\n absorb bs = over each (absorb bs)\n\ninstance (Ord λ, Num λ)\n => Absorbable λ (λ, λ) where\n absorb (l, h) (q, p) = case getRelPos (l, h) q of\n Inside -> (q, p)\n LeftOf -> (l, 0)\n RightOf -> (h, 0)\n\nzipWithTuple :: (a -> b -> c) -> (a, a) -> (b, b) -> (c, c)\nzipWithTuple f (x₁, x₂) (y₁, y₂) = (f x₁ y₁, f x₂ y₂)\n\ninstance (Ord λ, Num λ)\n => Absorbable λ (Complex λ, Complex λ) where\n absorb bounds ψ =\n let f getter = absorb bounds . over each getter\n in zipWithTuple (:+) (f realPart ψ) (f imagPart ψ)\n\ninstance (Absorbable λ (ξ, ξ), GV.Vector χ ξ, GV.Vector χ (ξ, ξ))\n => Absorbable λ (CMState (χ ξ)) where\n absorb bounds ψ =\n let (q, p) = GV.unzip . GV.map (absorb bounds)\n $ GV.zip (ψ ^. pos) (ψ ^. vel)\n in ψ & (pos .~ q) & (vel .~ p)\n\ninstance (Absorbable λ ξ, GV.Vector χ ξ)\n => Absorbable λ (QMState (χ ξ)) where\n absorb bounds = pos %~ GV.map (absorb bounds)\n\nabsorbUpdater :: (Monad m, Absorbable λ α) => (λ, λ) -> PhaseUpdater m γ β α r\nabsorbUpdater bounds = PhaseUpdater $ upAbsorbImpl bounds\n\nupAbsorbImpl :: (Monad m, Absorbable λ α) => (λ, λ) -> γ -> Bee α β r -> m α\nupAbsorbImpl bounds _ = return . absorb bounds . view state\n\n\n-- | Given a swarm and bee in the @n@'th iteration, returns a computation that\n-- returns the bee in the @(n+1)@'st iteration.\nupdateBee ::\n (Monad m, LocalGuide β α r)\n => Swarm m γ β α r -> Bee α β r -> m (Bee α β r)\nupdateBee xs x = do\n ψ' <- (xs ^. updater . run) (xs ^. guide) x\n fψ' <- (xs ^. func) ψ'\n return $ x & (state .~ ψ')\n & (val .~ fψ')\n & (guide %~ updateLocalG ψ' fψ')\n\n\n-- | Given a swarm in the @n@'th iteration, returns a computation that returns\n-- the swarm in the @(n+1)@'st iteration.\nupdateSwarm :: (Monad m, GlobalGuide γ β α r)\n => Swarm m γ β α r -> m (Swarm m γ β α r)\nupdateSwarm swarm = do\n xs <- mapM (updateBee swarm) (swarm ^. bees)\n return $ swarm & (bees .~ xs)\n & (guide %~ updateGlobalG xs)\n\n-- | Applies \\(f\\) to \\(x\\) \\(\\max(0, n - 1)\\) times and accumulates the\n-- results. Returned list will have \\(n\\) elements.\niterateNM ::\n (Monad m)\n => Int -- ^ \\(n\\), number of times to apply \\(f\\)\n -> (a -> m a) -- ^ function \\(f\\) to apply\n -> a -- ^ initial value \\(x\\)\n -> m [a]\niterateNM n f x\n | n == 0 = return [x]\n | otherwise = do\n y <- f x\n ys <- iterateNM (n - 1) f y\n return $ x : ys\n\niterateWhileM ::\n (Monad m)\n => (a -> Bool)\n -> (a -> m a) -- ^ function \\(f\\) to apply\n -> a -- ^ initial value \\(x\\)\n -> m [a]\niterateWhileM predicate func x\n | predicate x = do\n y <- func x\n ys <- iterateWhileM predicate func y\n return $ x : ys\n | otherwise = return [x]\n\n\nmkCMState :: (UniformDist m χ, Num χ) => (χ, χ) -> m (CMState χ)\nmkCMState bounds = liftM (\\q -> CMState q 0) $ uniform bounds\n\nmkQMState :: (UniformDist m χ, Num χ) => (χ, χ) -> m (QMState χ)\nmkQMState bounds = liftM (\\q -> QMState q) $ uniform bounds\n\n\n-- | @mkSwarm updater initialiser inside func n@ creates a new 'Swarm' where\n--\n-- * @updater@ is the update strategy used to obtain velocities of bees in the\n-- next iteration.\n-- * @initialiser@ creates a new random 'Bee'. It is assumed that position of a\n-- bee created using @initialiser@ will satisfy @inside@.\n-- * Given a position \\(x\\in\\mathcal{H}\\) returns whether \\(x\\in\\mathcal{V}\\)\n-- holds.\n-- * @func@ is the function \\(f\\) we're trying to minimise.\n-- * @n@ is number of bees in the newly created swarm.\nmkSwarm ::\n (Monad m, GlobalGuide γ β α r)\n => m α\n -> PhaseUpdater m γ β α r\n -> (α -> m r)\n -> Int\n -> m (Swarm m γ β α r)\nmkSwarm newState updater func n = (sequence . replicate n $ newState) >>=\n mapM (mkBee func) >>= \\xs ->\n return $ Swarm xs (mkGlobalG xs) func updater\n\nmkSwarmFromList ::\n (Monad m, GlobalGuide γ β α r)\n => [α]\n -> PhaseUpdater m γ β α r\n -> (α -> m r)\n -> m (Swarm m γ β α r)\nmkSwarmFromList states updater func =\n mapM (mkBee func) states >>= \\xs ->\n return $ Swarm xs (mkGlobalG xs) func updater\n\nfromPure :: (Monad m, HasPos α χ) => (χ -> r) -> α -> m r\nfromPure f ψ = return $ f (ψ ^. pos)\n-- \n-- class Between a b where\n-- isBetween :: (a, a) -> b -> Bool\n-- \n-- instance (Ord a) => Between a a where\n-- isBetween (l, h) x = l <= x && x <= h\n-- \n-- instance {-# OVERLAPS #-} (Between a a) => Between (Complex a) (Complex a) where\n-- isBetween (rl :+ il, rh :+ ih) (rx :+ ix) =\n-- isBetween (rl, rh) rx && isBetween (il, ih) ix\n-- \n-- instance {-# OVERLAPS #-} (Foreign.Storable a, Between a a)\n-- => Between (V.Vector a) (V.Vector a) where\n-- isBetween (low, high) x =\n-- V.and $ V.zipWith3 (\\l h x -> isBetween (l, h) x) low high x\n-- \n-- -- | Creates a new 'Bee' with a random position inside a given 1D interval and\n-- -- zero velocity.\n-- randomBee1D ::\n-- (Num p, UniformDist p gen m)\n-- => (p, p) -- ^ @[low, high]@ interval. It is assumed that @low <= high@.\n-- -> (p -> ReaderT gen m r) -- ^ Function we're minimising.\n-- -> ReaderT gen m (Bee p r (BeeGuide p r))\n-- randomBee1D bounds func = do\n-- g <- ask\n-- x <- lift $ uniform bounds g\n-- fx <- func x\n-- return $ Bee x 0 fx (BeeGuide x fx)\n\n\n-- | Given a fitness function \\(f\\) and phase \\(\\psi^{(0)}\\), creates a new\n-- 'Bee'.\nmkBee :: (Monad m, LocalGuide β α r)\n => (α -> m r) -> α -> m (Bee α β r)\nmkBee f ψ = do\n fψ <- f ψ\n return $ Bee ψ (mkLocalG ψ fψ) fψ\n\n-- -- | Simplified @mkSwarm@ for 1D pure functions.\n-- -- simpleInit1D ::\n-- -- ( Num a\n-- -- , RandomScalable a gen m\n-- -- , UniformDist a gen m\n-- -- , Between a a\n-- -- , Ord r\n-- -- , s ~ g\n-- -- , g ~ BeeGuide a r\n-- -- )\n-- -- => (a, a, a) -- ^ WPG parameters \\((\\omega,\\varphi_l,\\varphi_g)\\).\n-- -- -> (a, a) -- ^ Boundaries \\([a, b]\\).\n-- -- -> (a -> r) -- ^ Function \\(f\\) we're minimising.\n-- -- -> Int -- ^ Number of bees.\n-- -- -> ReaderT gen m (Swarm m gen s g a r)\n-- -- simpleInit1D wpg (low, high) func =\n-- -- let updater = standardUpdater wpg\n-- -- initialiser = randomBee1D (low, high)\n-- -- boundaries = isBetween (low, high)\n-- -- in mkSwarm updater initialiser boundaries (fromPure func)\n-- \n-- \n-- unpackToV :: (Foreign.Storable a) => [(a, a)] -> (V.Vector a, V.Vector a)\n-- unpackToV xs = let a = V.fromList . map fst $ xs\n-- b = V.fromList . map snd $ xs\n-- in (a, b)\n-- \n-- -- | Simplified @mkSwarm@ for N-dimensional functions.\n-- simpleInitND ::\n-- ( Foreign.Storable a\n-- , VectorSpace p a\n-- , RandomScalable p gen m\n-- , UniformDist p gen m\n-- , Between p p\n-- , Ord r\n-- , p ~ V.Vector a\n-- , GlobalGuide s g p r\n-- )\n-- => Updater m gen s g p r -- ^ PWG parameters \\((\\omega,\\varphi_l,\\varphi_g)\\)\n-- -> [(a, a)]\n-- -> [(a, a)] -- ^ List of intervals \\([a_i,b_i]\\). \\(\\mathcal{V}\\) is then\n-- -- \\(\\prod_i [a_i,b_i]\\).\n-- -> (p -> r) -- ^ Function \\(f\\) we're minimising.\n-- -> Int -- ^ Number of bees.\n-- -> ReaderT gen m (Swarm m gen s g p r)\n-- simpleInitND updater initBounds bounds func =\n-- let initialiser = randomBeeND (unpackToV initBounds)\n-- boundaries = isBetween (unpackToV bounds)\n-- in mkSwarm updater initialiser boundaries (fromPure func)\n-- \n-- -- optimise1D ::\n-- -- ( Num a\n-- -- , RandomScalable a gen m\n-- -- , UniformDist a gen m\n-- -- , Between a a\n-- -- , Ord r\n-- -- , s ~ g\n-- -- , g ~ BeeGuide a r\n-- -- )\n-- -- => (a, a, a)\n-- -- -> (a, a)\n-- -- -> (a -> r)\n-- -- -> Int\n-- -- -> (Swarm m gen s g a r -> Bool)\n-- -- -> ReaderT gen m [Swarm m gen s g a r]\n-- -- optimise1D wpg bounds func n predicate = do\n-- -- swarm <- simpleInit1D wpg bounds func n\n-- -- iterateWhileM (not . predicate) updateSwarm swarm\n\noptimiseND ::\n ( Monad m\n , HasPos α χ\n , GlobalGuide γ β α r\n )\n => m α\n -> PhaseUpdater m γ β α r\n -> (α -> m r)\n -> Int\n -> (Swarm m γ β α r -> Bool)\n -> m [Swarm m γ β α r]\noptimiseND newState updater func n predicate = do\n swarm <- mkSwarm newState updater func n\n iterateWhileM (not . predicate) updateSwarm swarm\n\noptimiseNDFromList ::\n ( Monad m\n , HasPos α χ\n , GlobalGuide γ β α r\n )\n => [α]\n -> PhaseUpdater m γ β α r\n -> (α -> m r)\n -> (Swarm m γ β α r -> Bool)\n -> (Swarm m γ β α r -> m ())\n -> m (Swarm m γ β α r)\noptimiseNDFromList states updater func predicate process =\n do\n swarm <- mkSwarmFromList states updater func\n go swarm\n where\n go x\n | predicate x = return x\n | otherwise = process x >> updateSwarm x >>= go\n", "meta": {"hexsha": "47bd2c3ba81ea7a8c3123dddc3164314cc3aa75f", "size": 31383, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PSO/Swarm.hs", "max_stars_repo_name": "twesterhout/tcm-swarm", "max_stars_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PSO/Swarm.hs", "max_issues_repo_name": "twesterhout/tcm-swarm", "max_issues_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PSO/Swarm.hs", "max_forks_repo_name": "twesterhout/tcm-swarm", "max_forks_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4610169492, "max_line_length": 111, "alphanum_fraction": 0.5914348533, "num_tokens": 10196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5367633439271982}} {"text": "module Gosadenban \n( main3\n\n) where\n\n-------------------------------------------------------------\n--module\n-------------------------------------------------------------\n\nimport Numeric.LinearAlgebra\nimport System.Random\nimport qualified Data.ByteString.Lazy as B\nimport Data.List\nimport Data.Time\n\nimport Tools\nimport Durstenfeld\nimport ForMNIST\n\n------------------------------------------------\n\ndata ActivationFunction = ActivationFunction\n { func :: Double -> Double , \n func' :: Double -> Double ,\n description :: String\n }\n\ndata Params = Params\n { weight :: Matrix Double ,\n bias :: Matrix Double\n } deriving (Show)\n\ndata DParams = DParams\n { dweight :: Matrix Double ,\n dbias :: Matrix Double\n } deriving (Show)\n\ndata LayerProp = LayerProp\n { params :: Params ,\n af :: ActivationFunction\n }\n\ndata HyperProp = HyperProp\n { vw0 :: Matrix Double ,\n vb0 :: Matrix Double\n }\n\ndata Hyperparameter = Hyperparameter\n { learningrate :: Double ,\n alpha0 :: Double ,\n beta0 :: Double ,\n beta1 :: Double\n }\n\ndata Network = Network\n { layers :: [LayerProp] ,\n hprop :: [HyperProp] ,\n hpara :: Hyperparameter\n }\n\ndata PropagateLayer \n = PropagateLayer\n { inData :: Matrix Double ,\n outData :: Matrix Double ,\n pAf :: ActivationFunction ,\n pParams :: Params\n }\n | PropagateSensorLayer\n { outData :: Matrix Double\n }\n\ndata BackPropagateLayer\n = BackPropagateLayer\n { inGrad :: Matrix Double ,\n outGrad :: Matrix Double ,\n bpAf :: ActivationFunction ,\n bpParams :: Params ,\n dParams :: DParams\n }\n | BackPropagateLastLayer\n { outGrad :: Matrix Double\n }\n\ndata ErrorLayer\n = ErrorLayer\n { lastData :: Matrix Double ,\n teachData :: Matrix Double ,\n errorValue :: Double ,\n grad :: Matrix Double\n } deriving (Show)\n\n-------------------------------------------------------------\n\npropagate :: PropagateLayer -> LayerProp -> PropagateLayer\npropagate dataJ layerK = PropagateLayer\n { inData = x ,\n outData = y ,\n pAf = functions ,\n pParams = p\n }\n where x = outData dataJ\n p = params layerK\n w = weight p\n b = bias p \n a = add b $ x Numeric.LinearAlgebra.<> w\n functions = af layerK\n h = func functions\n y = cmap h a \n\npropagateNetwork :: Matrix Double -> Network -> [PropagateLayer]\npropagateNetwork input net = calcs\n where calcs = scanl propagate layer0 (layers net)\n layer0 = PropagateSensorLayer { outData = input}\n\n-------------------------------------------------------------\n\nbackpropagate :: PropagateLayer -> BackPropagateLayer -> BackPropagateLayer\nbackpropagate pLayerJ bpLayerK = BackPropagateLayer\n { inGrad = indx ,\n outGrad = dx ,\n bpAf = af ,\n bpParams = p ,\n dParams = dP\n }\n where af = pAf pLayerJ\n p = pParams pLayerJ\n h' = func' af\n indx = outGrad bpLayerK\n y = outData pLayerJ\n dL' = cmap h' y\n dL = indx * dL'\n db = dL\n x = inData pLayerJ\n w = weight p\n dw = (tr x) Numeric.LinearAlgebra.<> dL\n dx = dL Numeric.LinearAlgebra.<> (tr w)\n dP = DParams { dweight = dw, dbias = db}\n \n\nbackpropagateNetwork :: ErrorLayer -> [PropagateLayer] ->[BackPropagateLayer]\nbackpropagateNetwork el prL = tail ans1\n where ans1 = scanr backpropagate layerFin prL\n layerFin = BackPropagateLastLayer {outGrad = grad0}\n grad0 = grad el\n\n-------------------------------------------------------------\n\n--Softmax & cross entropy error\nerrorNetwork :: Matrix Double -> Matrix Double -> ErrorLayer \nerrorNetwork ld td = ErrorLayer\n { lastData = dataFromSoftmaxFunction ,\n teachData = td ,\n errorValue = e / len ,\n grad = g\n }\n where dataFromSoftmaxFunction = softmaxBatch' ld\n g = add dataFromSoftmaxFunction $ scale (-1) td\n y = map asRow $ toRows dataFromSoftmaxFunction\n t = map asRow $ toRows td\n e' = zipWith cee t y\n e = sum e'\n len = length' t\n\n-------------------------------------------------------------\n\ninference :: Matrix Double -> Int -> Double\ninference x t = ans\n where (r, c) = maxIndex x\n ans = if c == t then 1.0 else 0.0\n\naccuracyNet :: Network -> Matrix Double -> Int -> Double\naccuracyNet net x t = a\n where ans' = propagateNetwork x net\n ans = last $ map outData ans'\n a = inference ans t \n\naccuracyNetwork :: Network -> [Matrix Double] -> [Int] -> Double\naccuracyNetwork net xs ts = sumans / lenans\n where f x t = accuracyNet net x t \n ans = zipWith f xs ts\n sumans = sum ans\n lenans = length' xs\n\n----------------------------------------------------------------------\nsgd :: Matrix Double -> Matrix Double -> Hyperparameter -> Matrix Double\nsgd x dx hp = x - scale eta dx\n where eta = learningrate hp\n\n\n\nupdate :: Hyperparameter -> Params -> DParams -> Params\nupdate hp p dp = newParam\n where b = bias p\n w = weight p\n db = dbias dp\n dw = dweight dp\n new_b = sgd b db hp\n new_w = sgd w dw hp\n newParam = Params {bias = new_b, weight = new_w}\n\nupdateNetowrk :: Network -> [DParams] -> Network\nupdateNetowrk net dp = new_Network\n where layerList = layers net\n hp = hpara net\n hpp = hprop net\n paramList = map params layerList\n afList = map af layerList\n f = update hp\n new_Para = zipWith f paramList dp\n new_Layer = zipWith makeLayerProp new_Para afList\n new_Network = Network{layers = new_Layer, hpara = hp, hprop = hpp }\n\n\nmomentum :: Matrix Double -> Matrix Double -> Hyperparameter -> Matrix Double -> ( Matrix Double, Matrix Double)\nmomentum x dx hp v = (x + new_v, new_v)\n where eta = learningrate hp\n alpha = alpha0 hp\n new_v = (scale alpha v) - scale eta dx\n\nadagrad :: Matrix Double -> Matrix Double -> Hyperparameter -> Matrix Double -> ( Matrix Double, Matrix Double)\nadagrad x dx hp v = (new_x, new_v')\n where eta = learningrate hp\n alpha = alpha0 hp\n new_v' = v + dx*dx\n new_v = cmap sqrt new_v'\n new_v'' = cmap devdev new_v\n new_x = x - scale eta ( dx/new_v'' )\n\ndevdev :: Double -> Double\ndevdev x =\n if x == 0 \n then 1.0\n else x\n\nupdate' :: Hyperparameter -> (HyperProp , Params) -> DParams -> (Params, HyperProp)\nupdate' hp (hpp, p) dp = (newParam, newHpp)\n where b = bias p\n w = weight p\n db = dbias dp\n dw = dweight dp\n vw = vw0 hpp\n vb = vb0 hpp\n (new_w, new_vw) = momentum w dw hp vw\n (new_b, new_vb) = momentum b db hp vb\n newParam = Params {bias = new_b, weight = new_w}\n newHpp = HyperProp {vw0 = new_vw, vb0 = new_vb}\n\nupdateNetowrk' :: Network -> [DParams] -> Network\nupdateNetowrk' net dp = new_Network\n where layerList = layers net\n hp = hpara net\n hpp = hprop net\n paramList = map params layerList\n afList = map af layerList\n f = update' hp \n hppp = zip hpp paramList\n new_Para_And_Hpp = zipWith f hppp dp\n new_Para = map fst new_Para_And_Hpp\n new_Hpp = map snd new_Para_And_Hpp \n new_Layer = zipWith makeLayerProp new_Para afList\n new_Network = Network{layers = new_Layer, hpara = hp, hprop = new_Hpp }\n\n----------------------------------------------------------------------\n \nmakeLayerProp :: Params -> ActivationFunction -> LayerProp\nmakeLayerProp p aF = LayerProp {params = p, af = aF }\n\n----------------------------------------------------------------------\n\nloadL :: B.ByteString -> [Matrix Double]\nloadL xs = tL4\n where tLabel = loadLabel xs\n f x = pickUpNum x tLabel\n tL1 = map f batch_List\n tL2 = map ( map oneHotEncoder ) tL1\n tL3 = map ( map flatten ) tL2\n tL4 = map fromRows tL3\n\nloadI :: B.ByteString -> [Matrix Double] \nloadI xs = tI4\n where tImage = loadImage xs\n g x = pickUpNum x tImage\n tI1 = map g batch_List\n tI2 = map ( map (scale (1/255.0) )) tI1\n tI3 = map ( map flatten ) tI2\n tI4 = map fromRows tI3\n\n----------------------------------------------------------------------\n\nfinPara :: Matrix Double -> Matrix Double -> Params\nfinPara b w = Params {bias = b, weight = w}\n \nfinLayer :: Params -> ActivationFunction -> LayerProp\nfinLayer p a = LayerProp {params = p, af = a }\n\n----------------------------------------------------------------------\n\nsigmoidFunction :: Floating a => a -> a\nsigmoidFunction x = 1 / (1 + exp (-x) )\n\nsigmoidFunctionBack :: Floating a => a -> a\nsigmoidFunctionBack x = x*(1-x) \n\nsigmoidFunc :: ActivationFunction\nsigmoidFunc = ActivationFunction\n { func = sigmoidFunction, \n func' = sigmoidFunctionBack,\n description = \"Sigmoid Function\"\n }\n \n \nreluFunction :: Double -> Double\nreluFunction x\n | x <= 0 = 0.0\n | x > 0 = x\n\nreluFunctionBack :: Double -> Double\nreluFunctionBack x\n | x <= 0 = 0.0\n | x > 0 = 1.0\n\nreluFunc :: ActivationFunction\nreluFunc = ActivationFunction\n { func = reluFunction,\n func' = reluFunctionBack,\n description = \"Relu Function\"\n }\n\n\nidentity :: ActivationFunction\nidentity = ActivationFunction\n { func = id,\n func' = backOne,\n description = \"id\"\n } \n\nbackOne :: Double -> Double\nbackOne x = 1.0\n\n-------------------------------------------------------------\n\n\nsoftmax :: (Linear t c, Floating t, Container c t) => c t -> c t\nsoftmax m = scale (1/bunbo) newM \n where maxValue = maxElement m\n newM = cmap (\\x -> exp $ x - maxValue ) m\n bunbo = sumElements newM\n\nsoftmaxBatch' :: Matrix Double -> Matrix Double\nsoftmaxBatch' m = m1\n where list = toRows m\n list1 = fmap softmax list\n m1 = fromRows list1\n\ncee :: Matrix Double -> Matrix Double -> Double\ncee t y = (-1.0)*e\n where delta = 0.0000001\n y1 = cmap (\\x -> log (x + delta) ) y\n y2 = flatten y1\n y3 = diag y2\n e = sumElements (t Numeric.LinearAlgebra.<> y3)\n\n----------------------------------------------------------------------\n\n\ncheckIt (e0, net) (x ,t) = (e, newNetwork)\n where ans' = propagateNetwork x net\n ans = map outData ans'\n answer = last ans\n answer2 = errorNetwork answer t\n e = errorValue answer2\n finalAnswer' = backpropagateNetwork answer2 ans'\n finalA = map dParams $ init finalAnswer'\n newNetwork = updateNetowrk' net finalA\n\nchecking net0 lt = ans\n where ans = scanl checkIt net0 lt \n\nchecking' net0 lt = ans\n where ans = foldl checkIt net0 lt \n\n\n-------------------------------------------------------------\n--Parameter\n-------------------------------------------------------------\n\ndata_size = 10000\nbatch_size = 100\ntrials_num = 2000\n\ninput_size = 784\nhidden_size = 50\noutput_size = 10\n\n------------------------------------------------\n\n-------------------------------------------------------------\n--Initial Condition (?)\n-------------------------------------------------------------\n\nnw1 = randomMatrix input_size hidden_size (mkStdGen 101) :: (Matrix Double)\nnw2 = randomMatrix hidden_size output_size (mkStdGen 102) :: (Matrix Double)\n\nnb1 = matrix hidden_size $ take (batch_size * hidden_size) $ repeat 0.0\nnb2 = matrix output_size $ take (batch_size * output_size) $ repeat 0.0\n\nnv_w1 = matrix hidden_size $ take (input_size * hidden_size) $ repeat 0.0\nnv_w2 = matrix output_size $ take (hidden_size * output_size) $ repeat 0.0\n\nnv_b1 = matrix hidden_size $ take (batch_size * hidden_size) $ repeat 0.0\nnv_b2 = matrix output_size $ take (batch_size * output_size) $ repeat 0.0\n\n------------------------------------------------\n\nparam1 = Params {bias = nb1, weight = nw1}\nlayer1 = LayerProp {params = param1, af = reluFunc}\nhprop1 = HyperProp { vw0 = nv_w1, vb0 = nv_b1 }\n\nparam2 = Params {bias = nb2, weight = nw2}\nlayer2 = LayerProp {params = param2, af = identity }\nhprop2 = HyperProp { vw0 = nv_w2, vb0 = nv_b2}\n\nhyperParam = Hyperparameter {learningrate = 0.0001, alpha0 = 0.9, beta0 = 0.0, beta1 = 0.0}\n\n\nnetworkA = Network {layers = [layer1,layer2], hpara = hyperParam, hprop = [hprop1,hprop2]}\n\n--makeBatchList gen num_of_trials data_size batch_size\nbatch_List = makeBatchList 100000 trials_num data_size batch_size\n\nmain3 = do\n\n z <- getZonedTime\n print z\n\n x <- getCurrentTime\n\n contents1 <- B.readFile \"MNIST/train-labels.idx1-ubyte\" \n contents2 <- B.readFile \"MNIST/train-images.idx3-ubyte\"\n\n let tL4 = loadL contents1\n --tL4 = [[Batch X 10],[Batch X 10],...] :: [Matrix Double]\n\n tI4 = loadI contents2\n --tI4 = [[Batch X data_size],[Batch X data_size],...] :: [Matrix Double]\n\n test_Image_and_Label = zip tI4 tL4\n\n --e1 = checking' (0.0,networkA) test_Image_and_Label\n --e2 = fst e1\n\n e1' = checking (0.0,networkA) test_Image_and_Label\n e2' = tail $ map fst e1'\n net1' = last $ map snd e1'\n\n \n --print e2\n writeFile \"logs/e_mmt-0.0001.dat\" $ encorderForDat2 e2'\n \n contents3 <- B.readFile \"MNIST/t10k-labels.idx1-ubyte\" \n contents4 <- B.readFile \"MNIST/t10k-images.idx3-ubyte\"\n\n let xs = loadImageTest contents4\n ts = loadLabelTest contents3\n --a = accuracyNet net1' xs ts\n --acc = accuracyNetwork net1' xs ts\n bs = map toRows $ map bias $ map params $ layers net1' \n bs' = map (foldl1 add) bs\n bsl = map recip $ map length' bs\n newbs = map asRow $ zipWith scale bsl bs'\n w = map weight $ map params $ layers net1' \n para = zipWith finPara newbs w\n acfunc = map af $ layers net1' \n newLayer = zipWith finLayer para acfunc\n finNetwork = Network {layers = newLayer, hpara = Hyperparameter {learningrate = 1.0, alpha0 = 0.0, beta0 = 0.0, beta1 = 0.0},hprop = [hprop1,hprop2]}\n\n acc = accuracyNetwork finNetwork xs ts\n \n\n print acc\n\n \n\n y <- getCurrentTime\n print$ diffUTCTime y x\n\n\n---------------------------------------------------------------------- \n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nloopCheck x net t = (e, finalA, newNetwork)\n where ans' = propagateNetwork x net\n ans = map outData ans'\n answer = last ans\n answer2 = errorNetwork answer t\n e = errorValue answer2\n finalAnswer' = backpropagateNetwork answer2 ans'\n finalA = map dParams $ init finalAnswer'\n newNetwork = updateNetowrk net finalA\n\nloop _ _ _ 0 = []\nloop x network t n = e : loop x newNetwork t (n-1)\n where (e, finalA, newNetwork) = loopCheck x network t\n\n\nrandomList = randomChoice 10 10 (mkStdGen 10 )\n\n----------------------------------------------------------------------", "meta": {"hexsha": "b8c79f13dc0b6614b9bef3ceddfed53cf0223653", "size": 15276, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Gosadenban.hs", "max_stars_repo_name": "llbxg/Fukami", "max_stars_repo_head_hexsha": "28e5cb963e372db7f2fe532043092a4bbc4c0101", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-08T10:00:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-08T10:00:17.000Z", "max_issues_repo_path": "src/Gosadenban.hs", "max_issues_repo_name": "llbxg/Fukami", "max_issues_repo_head_hexsha": "28e5cb963e372db7f2fe532043092a4bbc4c0101", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Gosadenban.hs", "max_forks_repo_name": "llbxg/Fukami", "max_forks_repo_head_hexsha": "28e5cb963e372db7f2fe532043092a4bbc4c0101", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9529411765, "max_line_length": 157, "alphanum_fraction": 0.5431395653, "num_tokens": 3960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.536583825981782}} {"text": "\n{-# LANGUAGE FunctionalDependencies #-}\n\nmodule Distribution ( \n Dist, pdf, logpdf, samplefrom,\n Uniform(..), Normal(..), Bernoulli(..), \n Exponential(..), Gamma(..), Poisson(..), \n Binomial(..), Beta(..), \n Prob, Weight, Weighted\n) where\n\nimport Randomness ( Random(..), uniform, Prob, Weight, Weighted )\nimport Numeric.Log ( Log(..) )\nimport qualified Data.Random.Distribution.Uniform as R ( uniform )\nimport qualified Data.Random.Distribution.Normal as R ( normal )\nimport qualified Data.Random.Distribution.Bernoulli as R ( bernoulli )\nimport qualified Data.Random.Distribution.Binomial as R ( binomial )\nimport qualified Data.Random.Distribution.Poisson as R ( poisson )\nimport qualified Statistics.Distribution as S ( ContDistr(density, logDensity, quantile), DiscreteDistr(probability, logProbability) )\nimport qualified Statistics.Distribution.Uniform as S ( uniformDistr )\nimport qualified Statistics.Distribution.Normal as S ( normalDistr )\nimport qualified Statistics.Distribution.Binomial as S ( binomial )\nimport qualified Statistics.Distribution.Poisson as S ( poisson )\nimport qualified Statistics.Distribution.Gamma as S ( gammaDistr )\nimport qualified Statistics.Distribution.Exponential as S ( exponential )\nimport qualified Statistics.Distribution.Binomial as S ( binomial )\nimport qualified Statistics.Distribution.Beta as S ( betaDistr )\nimport qualified Statistics.Distribution.DiscreteUniform as S ( discreteUniformAB )\n\nclass Dist d a | d -> a where\n samplefrom :: d -> Random a\n\n pdf :: d -> a -> Double\n pdf d = exp . ln . logpdf d\n\n logpdf :: d -> a -> Weight\n logpdf d = Exp . log . pdf d\n\n\ndata Uniform = Uniform Double Double\n-- data DiscreteUniform = DiscreteUniform Int Int\ndata Normal = Normal Double Double\ndata Bernoulli = Bernoulli Prob\ndata Exponential = Exponential Double\ndata Gamma = Gamma Double Double\ndata Poisson = Poisson Double\ndata Binomial = Binomial Int Prob\ndata Beta = Beta Double Double\n\ninstance Dist Uniform Double where\n pdf (Uniform a b) = S.density $ S.uniformDistr a b\n logpdf (Uniform a b) = Exp . S.logDensity (S.uniformDistr a b)\n samplefrom (Uniform a b) = do \n u <- uniform\n return $ a + u * (b - a)\n\n{-\ninstance Dist DiscreteUniform Int where\n pdf (DiscreteUniform a b) = S.probability $ S.discreteUniformAB a b\n logpdf (DiscreteUniform a b) = Exp . S.logProbability (S.discreteUniformAB a b)\n samplefrom (DiscreteUniform a b) = uniform (a, b)\n-}\n\ninstance Dist Normal Double where\n pdf (Normal mu sig) = S.density $ S.normalDistr mu sig\n logpdf (Normal mu sig) = Exp . S.logDensity (S.normalDistr mu sig)\n samplefrom (Normal mu sig) = S.quantile (S.normalDistr mu sig) <$> uniform\n\ninstance Dist Bernoulli Bool where\n pdf (Bernoulli p) b = if b then p else 1-p\n logpdf (Bernoulli p) b = if b then Exp $ log p else Exp $ log (1-p)\n samplefrom (Bernoulli p) = (<= p) <$> uniform\n\ninstance Dist Gamma Double where\n pdf (Gamma k theta) = S.density $ S.gammaDistr k theta\n logpdf (Gamma k theta) = Exp . S.logDensity (S.gammaDistr k theta)\n samplefrom (Gamma k theta) = S.quantile (S.gammaDistr k theta) <$> uniform\n\ninstance Dist Exponential Double where\n pdf (Exponential lambda) = S.density $ S.exponential lambda\n logpdf (Exponential lambda) = Exp . S.logDensity (S.exponential lambda)\n samplefrom (Exponential lambda) = S.quantile (S.exponential lambda) <$> uniform\n\ninstance Dist Beta Double where\n pdf (Beta a b) = S.density $ S.betaDistr a b\n logpdf (Beta a b) = Exp . S.logDensity (S.betaDistr a b)\n samplefrom (Beta a b) = do\n x <- samplefrom (Gamma a 1)\n y <- samplefrom (Gamma b 1)\n return $ x / (x+y)\n\ninstance Dist Poisson Int where\n pdf (Poisson lambda) = S.probability $ S.poisson lambda\n logpdf (Poisson lambda) = Exp . S.logProbability (S.poisson lambda)\n samplefrom (Poisson lambda) = step 0 1.0 \n where \n l = exp (-lambda)\n step k p = do\n u <- uniform\n let p' = p*u\n if p' <= l then return k \n else step (k+1) p'\n\n\ninstance Dist Binomial Int where\n pdf (Binomial n p) = S.probability $ S.binomial n p\n logpdf (Binomial n p) = Exp . S.logProbability (S.binomial n p)\n samplefrom d@(Binomial n p) | n <= 10 = sumBernoullis n 0\n | otherwise = do\n let a = 1 + n `div` 2\n let b = 1 + n - a\n x <- samplefrom $ Beta (fromIntegral a) (fromIntegral b) \n if x >= p \n then samplefrom $ Binomial (a-1) (p/x)\n else do \n s <- samplefrom (Binomial (b-1) ((p-x)/(1-x)))\n return (s + a)\n where \n sumBernoullis 0 s = return s\n sumBernoullis n s = do\n u <- uniform\n if u <= p then sumBernoullis (n-1) (s+1) else sumBernoullis (n-1) s\n", "meta": {"hexsha": "086062b4fa709ba91a405c4b5f90ea8bb4af533b", "size": 4913, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Distribution.hs", "max_stars_repo_name": "kai-pischke/ppl", "max_stars_repo_head_hexsha": "f98efe5ffd494a8f7955866a16bc25c5bb8bc835", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Distribution.hs", "max_issues_repo_name": "kai-pischke/ppl", "max_issues_repo_head_hexsha": "f98efe5ffd494a8f7955866a16bc25c5bb8bc835", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Distribution.hs", "max_forks_repo_name": "kai-pischke/ppl", "max_forks_repo_head_hexsha": "f98efe5ffd494a8f7955866a16bc25c5bb8bc835", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9430894309, "max_line_length": 134, "alphanum_fraction": 0.6568288215, "num_tokens": 1327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.536570280038487}} {"text": "\nimport Control.Monad (replicateM)\nimport System.Random.MWC (create, GenIO)\nimport System.Random.MWC.Distributions (beta, bernoulli, dirichlet)\nimport Numeric.LinearAlgebra.HMatrix\n (Matrix, matrix, Vector, vector, konst, fromRows, (!), toList, fromList, size)\nimport qualified Data.Vector.Storable as V\n\nimport Utils (multinomial)\nimport VB (lQ, calculateEQZ, calculateQZ, calculateEQmu, calculateQmu, expectationBeta, em)\n\n\ngenerateSampleMatrix :: Double -- ^ alpha parameter for Beta distribution\n -> Double -- ^ beta parameter for Beta distribution\n -> Vector Double -- ^ alpha parameter for Dirichlet distr\n -> Int -- ^ number of samples\n -> Int -- ^ vector size\n -> Int -- ^ Number of mixins\n -> IO (Matrix Double, Vector Double)\ngenerateSampleMatrix a b alpha n d k = do\n gen <- create\n pivT <- dirichlet (toList alpha) gen\n let piv = fromList pivT\n muK <-\n replicateM\n k\n (replicateM\n d\n (beta a b gen) >>=\n \\m ->\n return (vector m))\n let mu = fromRows muK\n genData <-\n replicateM\n n\n (generateVectors piv mu gen)\n return (fromRows genData, piv)\n where generateVectors :: Vector Double\n -> Matrix Double\n -> GenIO\n -> IO (Vector Double)\n generateVectors piv mu gen = do\n zn <- multinomial piv gen\n let Just j = V.findIndex (== 1) zn\n xn <-\n mapM\n (\\i ->\n bernoulli\n ((mu ! j) !\n i)\n gen >>=\n \\b ->\n if b\n then return 1.0\n else return 0.0)\n [0 .. d - 1]\n return (vector xn)\n\n-- | L(q) function must increase\ntestLQ = do\n let k = 6\n n = 1000\n d = 3\n a = 0.6\n b = 1\n alpha = konst (1 / 6) k\n (mX, piV) <- generateSampleMatrix a b alpha n d k\n let test_k = 10\n test_alpha = konst 0.1 test_k\n test_a = matrix d [0.5 | _ <- [1..test_k*d]]\n test_b = matrix d [0.5 | _ <- [1..test_k*d]]\n gen <- create\n pivT <- dirichlet (toList test_alpha) gen\n let piv = fromList pivT\n let qZ = fromRows (replicate n piv)\n let eQz = calculateEQZ qZ\n let qMu = (test_a, test_b)\n let eQmu = calculateEQmu qMu\n print (lQ mX eQz eQmu)\n let qZ' = calculateQZ mX eQmu eQz\n eQz' = calculateEQZ qZ'\n qMu' = calculateQmu mX eQz' qMu\n eQmu' = calculateEQmu qMu'\n print (lQ mX eQz' eQmu')\n let qZ'' = calculateQZ mX eQmu' eQz'\n eQz'' = calculateEQZ qZ''\n qMu'' = calculateQmu mX eQz'' qMu'\n eQmu'' = calculateEQmu qMu''\n print (lQ mX eQz'' eQmu'')\n\n-- | EM first step. Can't imagine.\ntestEM = do\n let k = 6\n n = 1000\n d = 3\n a = 0.6\n b = 1\n alpha = konst (1 / 6) k\n (mX, piV) <- generateSampleMatrix a b alpha n d k\n let test_k = 10\n test_alpha = konst 0.1 test_k\n test_a = 0.5\n test_b = 0.5\n gen <- create\n pivT <- dirichlet (toList test_alpha) gen\n let piv = fromList pivT\n print \"Original pi vector\"\n print piV\n print \"Calculated pi vector\"\n print (em mX piv test_alpha test_a test_b)\n\n\nmain :: IO ()\nmain = do\n putStrLn \"Test suite not yet implemented\"\n let k = 3\n n = 10\n d = 3\n a = 1\n b = 1\n alpha = konst 0.01 k\n d <- generateSampleMatrix a b alpha n d k\n print d\n putStrLn \"Test L(q). Must increase.\"\n testLQ\n putStrLn \"Test EM work or not :)\"\n testEM\n return ()\n\n \n", "meta": {"hexsha": "c47cc2c8acc5bfcb70a892c59d52b9fd7a5598d5", "size": 3840, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Spec.hs", "max_stars_repo_name": "DbIHbKA/mnistvb", "max_stars_repo_head_hexsha": "e284682b048f29673fef4fba949f7cae0b32710f", "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": "DbIHbKA/mnistvb", "max_issues_repo_head_hexsha": "e284682b048f29673fef4fba949f7cae0b32710f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "DbIHbKA/mnistvb", "max_forks_repo_head_hexsha": "e284682b048f29673fef4fba949f7cae0b32710f", "max_forks_repo_licenses": ["BSD-3-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.3129770992, "max_line_length": 91, "alphanum_fraction": 0.51328125, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5351057352424596}} {"text": "{-# LANGUAGE CPP\n , TypeOperators\n , KindSignatures\n , TypeApplications\n , ScopedTypeVariables\n , AllowAmbiguousTypes\n , TypeFamilies\n , FlexibleContexts\n , DeriveFunctor\n , DeriveFoldable\n , DeriveTraversable\n , TemplateHaskell\n , RankNTypes\n , UndecidableInstances\n -- , DeriveAnyClass\n -- , GeneralizedNewtypeDeriving \n -- , DatatypeContexts\n #-}\n{-# OPTIONS_GHC -Wall #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad (unless)\nimport Data.Complex\nimport Data.Traversable\nimport System.Exit (exitFailure)\nimport Test.QuickCheck (choose, vectorOf) -- , elements, collect)\nimport Test.QuickCheck.Arbitrary\nimport Test.QuickCheck.All (quickCheckAll)\n\ndft :: [Complex Double] -> [Complex Double] \ndft xs = [ sum [ x * exp((0.0 :+ (-1.0)) * 2 * pi / lenXs * fromIntegral(k * n)) \n | (x, n) <- zip xs [0..] ] \n | k <- [0..(length xs - 1)] ] \n where lenXs = fromIntegral $ length xs\n\ntype Unop a = a -> a\n\ndft' :: forall f a. ( Applicative f, Traversable f, Sized f\n , RealFloat a) => Unop (f (Complex a))\ndft' xs = omegas (size @f) `cross` xs\n\ncross :: (Functor n, Foldable m, Applicative m, Num a) =>\n n (m a) -> m a -> n a -- matrix * vector\nmat `cross` vec = dot vec <$> mat\n\ndot :: (Foldable f, Applicative f, Num a) =>\n f a -> f a -> a -- dot product\nu `dot` v = sum (liftA2 (*) u v)\n\nnewtype (g :. f) a = O (g (f a))\n deriving (Eq, Functor, Foldable, Traversable)\n\ninstance (Show a, Show (f a), Show (g String), Functor g) => Show ((g :. f) a) where\n show (O x) = show $ fmap show x\n\ninstance (Applicative f, Applicative g) => Applicative (g :. f) where\n pure = O . pure . pure\n O h <*> (O x) = O $ fmap (<*>) h <*> x\n\nclass Sized (f :: * -> *) where\n size :: Integer\n \ninstance (Sized f, Sized g) => Sized (g :. f) where\n size = size @f * size @g\n\nclass FFT f where\n type Reverse f :: * -> *\n fft :: RealFloat a => f (Complex a) -> Reverse f (Complex a)\n\n-- Constraints filled in, by responding to compiler errors incrementally.\ninstance (Traversable g, Traversable (Reverse g),\n Applicative (Reverse g),\n FFT g,\n Traversable f,\n Applicative f, Applicative (Reverse f),\n FFT f, Sized f, Sized (Reverse g) ) =>\n FFT (g :. f) where\n type Reverse (g :. f) = Reverse f :. Reverse g\n fft = O . fft' . transpose . twiddle . fft' . unO\nfft' :: ( Traversable g\n , Applicative (Reverse g)\n , FFT g\n , Traversable f\n , Applicative f\n , RealFloat a ) =>\n g (f (Complex a)) -> Reverse g (f (Complex a))\nfft' = transpose . fmap fft . transpose \n\ntwiddle :: forall g f a. ( Applicative g, Traversable g, Sized g \n , Applicative f, Traversable f, Sized f\n , RealFloat a ) =>\n g (f (Complex a)) -> g (f (Complex a))\ntwiddle = (liftA2 . liftA2) (*) (omegas (size @(g :. f)))\n\nomegas :: ( Applicative g, Traversable g\n , Applicative f, Traversable f\n , RealFloat a) =>\n Integer -> g (f (Complex a))\n-- 'i' was unrecognized.\n-- omegas n = powers <$> powers (exp (-i * 2 * pi / fromIntegral n))\nomegas n = powers <$> powers (cis (2 * pi / fromIntegral n))\n\npowers :: ( Applicative f, Traversable f\n , Fractional a) => a -> f a\n-- I don't have time to digest Conal's \"Generic Parallel Scan\" talk, right now.\n-- powers = fst . lscanAla Product . pure\n-- But, I do need to accomodate all applicative functors, as opposed to just lists.\n-- So, I'll try the Traversable approach.\npowers w = fmap (/ w) . snd . mapAccumL (\\x y -> (x * y, x * y)) 1 $ pure w\n\nunO :: (g :. f) a -> g (f a)\nunO (O x) = x\n\n-- Copied from Conal's generic-fft library.\ntranspose :: (Traversable g, Applicative f) => g (f a) -> f (g a)\ntranspose = sequenceA\n\n-- Quad\nnewtype Quad a = Quad ((a,a),(a,a))\n deriving (Show, Functor, Foldable, Traversable)\ninstance Applicative Quad where\n pure x = Quad ((x,x),(x,x))\n Quad ((g,h),(u,v)) <*> Quad ((w,x),(y,z)) = Quad ((g w, h x),(u y, v z))\ninstance Sized Quad where\n size = 4\n\n-- Pair\ndata Pair a = a :# a\n deriving ( Show, Eq, Functor, Foldable, Traversable )\ninstance Applicative Pair where\n pure x = x :# x\n g :# h <*> (x :# y) = g x :# h y\ninstance Sized Pair where\n size = 2\ninstance FFT Pair where\n type Reverse Pair = Pair\n fft (x :# y) = (x + y) :# (x - y)\n\n-- Tree of Pairs\ndata Tree a = Leaf (Pair a)\n | Branch (Pair (Tree a))\n deriving (Show, Eq, Functor, Foldable, Traversable)\n\n-- Tree building utility.\nmkTree :: Integer -> [a] -> Tree a\nmkTree n xs | n == 0 = Leaf (head xs :# head (tail xs))\n | otherwise = Branch (mkTree (n-1) (evens xs) :# mkTree (n-1) (odds xs))\n\n-- Pair of Pair building utility.\nmkPofP :: [a] -> Pair (Pair a)\n-- mkPofP [] = error \"Empty list provided!\"\n-- mkPofP [w] = error \"Wrong number of elements given!\"\n-- mkPofP [w,x] = error \"Wrong number of elements given!\"\n-- mkPofP [w,x,y] = error \"Wrong number of elements given!\"\n-- mkPofP [w,x,y,z] = O ((w :# x) :# (y :# z))\n-- mkPofP xs = O (unO (mkPofP (evens xs)) :# (unO (mkPofP (odds xs))))\nmkPofP [w,x,y,z] = (w :# y) :# (x :# z)\n-- mkPofP xs = mkPofP (evens xs) :# mkPofP (odds xs)\nmkPofP _ = error \"Wrong number of elements given!\"\n\nevens :: [a] -> [a]\nevens [] = []\nevens (x:xs) = x : odds xs\n\nodds :: [a] -> [a]\nodds [] = []\nodds (_:xs) = evens xs\n\nnewtype Id a = Id {unId :: a}\n deriving ( Show, Eq, Functor, Foldable, Traversable )\n\ninstance Applicative Id where\n pure = Id\n Id g <*> (Id x) = Id (g x)\n\ninstance Sized Id where\n size = 1\n\ninstance FFT Id where\n type Reverse Id = Id\n fft (Id x) = Id x\n\ntoList :: Foldable f => f a -> [a]\ntoList = foldr (:) []\n\nassertion1 :: Bool\nassertion1 = dft (map (:+ 0.0) [1.0, 0.0, 0.0, 0.0]) == [1.0 :+ 0.0, 1.0 :+ 0.0, 1.0 :+ 0.0, 1.0 :+ 0.0]\n\nassertion2 :: Bool\nassertion2 = dft (map (:+ 0.0) [1.0, 0.0, 0.0, 0.0]) == toList (dft' (fmap (:+ 0.0) (Quad ((1.0, 0.0), (0.0, 0.0)))))\n\nassertion3 :: Bool\nassertion3 = fft (fmap (:+ (0 :: Double)) (O ((1 :# 0) :# (0 :# 0)))) == dft' (fmap (:+ (0::Double)) (O ((1 :# 0) :# (0 :# 0))))\n\nexeMain :: IO ()\nexeMain = do\n print (powers (cis (2 * pi / 4)) :: Quad (Complex Float))\n print assertion1\n print assertion2\n print assertion3\n\n-- QuickCheck types & propositions\nnewtype FFTTestVal f g = FFTTestVal {\n getVal :: (g :. f) (Complex Double)\n} -- deriving (Show)\n\ninstance (Show (f (Complex Double)), Show (g String), Functor g) =>\n Show (FFTTestVal f g) where\n show = show . getVal\n\ninstance (Applicative f, Applicative g) => Arbitrary (FFTTestVal f g) where\n arbitrary = do\n depth <- choose (2, 5)\n -- rvals <- vectorOf (2^depth) (choose (-1.0, 1.0))\n -- ivals <- vectorOf (2^depth) (choose (-1.0, 1.0))\n -- let values = zipWith (:+) rvals ivals\n -- return $ FFTTestVal (fmap (:+ 0.0) (mkP depth))\n -- return $ FFTTestVal (tree2FuncComp $ mkTree depth values)\n return $ FFTTestVal $ O (pure (pure (depth :+ (0.0::Double))))\n\n-- prop_fail = False -- Test that QuickCheck is, actually, running.\n\nprop_fft_test testVal = fft val == dft' val\n where types = testVal :: FFTTestVal Pair Pair\n val = getVal testVal\n\n-- Entry point for unit tests.\nreturn []\nrunTests = $quickCheckAll\n\ntestMain :: IO ()\ntestMain = do\n -- allPass <- $quickCheckAll -- Run QuickCheck on all prop_ functions\n allPass <- runTests\n unless allPass exitFailure\n putStrLn \"Success!\"\n\n-- This is a clunky, but portable, way to use the same Main module file\n-- for both an application and for unit tests.\n-- MAIN_FUNCTION is preprocessor macro set to exeMain or testMain.\n-- That way we can use the same file for both an application and for tests.\n-- #ifndef MAIN_FUNCTION\n-- #define MAIN_FUNCTION exeMain\n-- #endif\nmain :: IO ()\n-- main = MAIN_FUNCTION\nmain = testMain\n\n", "meta": {"hexsha": "35a778ed54e6cb0be3e219846dbc7445c6288c26", "size": 8010, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Conals_FFT/func_comp_fft.hs", "max_stars_repo_name": "capn-freako/Haskell_Misc", "max_stars_repo_head_hexsha": "a6b0745b1391576a61a51227f6d1155b11970749", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-02-08T09:06:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T23:15:35.000Z", "max_issues_repo_path": "Conals_FFT/func_comp_fft.hs", "max_issues_repo_name": "capn-freako/Haskell_Misc", "max_issues_repo_head_hexsha": "a6b0745b1391576a61a51227f6d1155b11970749", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Conals_FFT/func_comp_fft.hs", "max_forks_repo_name": "capn-freako/Haskell_Misc", "max_forks_repo_head_hexsha": "a6b0745b1391576a61a51227f6d1155b11970749", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-12-31T17:36:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T23:15:40.000Z", "avg_line_length": 31.9123505976, "max_line_length": 128, "alphanum_fraction": 0.5846441948, "num_tokens": 2595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5351057276768754}} {"text": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances, GADTs, TypeOperators, FlexibleContexts #-}\n\nmodule Physics.Quantum.Algebra where\n\nimport Numeric.Field.Class (Field)\nimport Numeric.Algebra.Class (LeftModule((.*)), Multiplicative((*)), Monoidal(zero))\nimport Numeric.Additive.Class (Additive((+)))\nimport Numeric.Algebra.Unital (Unital(one))\n\nimport Prelude hiding ((+), (*), Complex)\n\nimport qualified Data.Map as M\nimport qualified Data.List as L\nimport Data.Maybe (catMaybes)\n\nimport Data.Complex (Complex, conjugate)\n\nimport qualified Data.Array.Repa as R\nimport qualified Data.Array.Repa.Eval as R\nimport qualified Data.Array.Repa.Repr.Unboxed as R\nimport qualified Data.Array.Repa.Repr.Vector as R\n\nimport Data.Functor.Identity (runIdentity)\n\nimport qualified Data.Eigen.SparseMatrix as ES\nimport qualified Data.Eigen.Matrix as E\n\n\n\n\n\n-- a vector space m over field k\nclass (Field k, Additive m) => VectorSpace k m | m -> k where\n (*^) :: k -> m -> m\n\n{-\n-- lhs type ‘m’ does not determine rhs type ‘k’\ninstance (Field k, LeftModule k m) => VectorSpace k m where\n (*^) = (.*)\n-}\n\nclass VectorSpace k m => LieAlgebra k m | m -> k where\n lieBr :: m -> m -> m\n\n\nclass (VectorSpace k a, VectorSpace k b) => DualVectors k a b | a b -> k where\n dual :: a -> b\n\nclass VectorSpace k m => InnerProductSpace k m | m -> k where\n (<.>) :: m -> m -> k\n\n\n\n-- Endo-morphism of vector space\n-- Data structure for operator may be different for different use cases\n-- A Map be suitable for sparse operator, matrix for discreet vector indices, and functions for continuous vector indices.\nclass VectorSpace k v => SimpleOperator k v o | o -> k, o -> v where\n op :: o -> v -> v\n\n-- Once we have simple operator, we can extract the map information from that\n-- and get addition and multiplication operations\ndata OperatorMap v where\n OperatorMap :: VectorSpace k v => (v -> v) -> OperatorMap v\n\nunOperatorMap :: OperatorMap v -> (v -> v)\nunOperatorMap (OperatorMap m) = m\n\nextractOperatorMap :: SimpleOperator k v o => o -> OperatorMap v\nextractOperatorMap = OperatorMap . op\n\ninstance Additive v => Additive (OperatorMap v) where\n (+) (OperatorMap operator1) (OperatorMap operator2) = OperatorMap $ \\vec -> (operator1 vec) + (operator2 vec)\n\ninstance Multiplicative (OperatorMap o) where\n (*) (OperatorMap operator1) (OperatorMap operator2) = OperatorMap $ \\vec -> operator1 (operator2 vec)\n\n\n\nclass (DualVectors k cv v, SimpleOperator k v o) => Operator k v cv o | o -> k where\n (|><|) :: v -> cv -> o\n\n\n(<|>) :: (InnerProductSpace k v, DualVectors k cv v) => cv -> v -> k\n(<|>) covec vec = (dual covec) <.> vec\n\n\n(|>) :: SimpleOperator k v o => o -> v -> v\n(|>) = op\n\n\n(<|) :: (InnerProductSpace k v, DualVectors k cv v, Operator k v cv o) => cv -> o -> (v -> k)\n(<|) covector operator = \\vector -> covector <|> (operator |> vector)\n\n \n\nclass IsComplex a where\n complexConjugate :: a -> a\n\ninstance Num a => IsComplex (Complex a) where\n complexConjugate = conjugate\n\n \n----------------------------------\n-- Constructions of vector spaces\n\n\n-- m is a set of vector indices indices\n-- May or may not represent orthogonal vectors, write instance of InnerProductSpace separately\n-- kets are represented as maps from indices to coefficients\n-- sparse kets have finite number of non zero entries\ndata SparseKet k m where\n SparseKet :: (Field k, Ord m) => M.Map m k -> SparseKet k m\n\n \nunSparseKet :: SparseKet k m -> M.Map m k\nunSparseKet (SparseKet ketMap) = ketMap\n \ndata SparseBra k m where\n SparseBra :: (Field k, Ord m) => M.Map m k -> SparseBra k m\n\nunSparseBra :: SparseBra k m -> M.Map m k\nunSparseBra (SparseBra braMap) = braMap\n\n\ninstance (Show k, Show m) => Show (SparseKet k m) where\n show ket@(SparseKet map) = show map\n\ninstance (Show k, Show m) => Show (SparseBra k m) where\n show ket@(SparseBra map) = show map\n\ninstance (Ord m, Field k) => Additive (SparseKet k m) where\n (+) (SparseKet a) (SparseKet b) = SparseKet $ M.unionWith (+) a b\n\ninstance (Ord m, Field k) => Additive (SparseBra k m) where\n (+) (SparseBra a) (SparseBra b) = SparseBra $ M.unionWith (+) a b\n\ninstance (Ord m, Field k) => VectorSpace k (SparseKet k m) where\n (*^) s (SparseKet v) = SparseKet $ M.map (s *) v\n\ninstance (Field k, Ord m) => VectorSpace k (SparseBra k m) where\n (*^) s (SparseBra v) = SparseBra $ M.map (s *) v\n\ninstance (Field k, IsComplex k, Ord m) => DualVectors k (SparseKet k m) (SparseBra k m) where\n dual (SparseKet a) = SparseBra $ M.map complexConjugate a\n\ninstance (Field k, IsComplex k, Ord m) => DualVectors k (SparseBra k m) (SparseKet k m) where\n dual (SparseBra a) = SparseKet $ M.map complexConjugate a\n\n\n\n-- very generic mappings\ndata InfKet k m = InfKet { unContKet :: (m -> k) }\ndata InfBra k m = InfBra { unContBra :: (m -> k) }\n\n\ninstance Field k => Additive (InfKet k m) where\n (+) (InfKet a) (InfKet b) = InfKet $ \\x -> a x + b x\n\ninstance Field k => Additive (InfBra k m) where\n (+) (InfBra a) (InfBra b) = InfBra $ \\x -> a x + b x\n\ninstance Field k => VectorSpace k (InfKet k m) where\n (*^) s (InfKet v) = InfKet $ \\x -> s * (v x)\n \ninstance Field k => VectorSpace k (InfBra k m) where\n (*^) s (InfBra v) = InfBra $ \\x -> s * (v x)\n\ninstance (Field k, IsComplex k) => DualVectors k (InfKet k m) (InfBra k m) where\n dual (InfKet a) = InfBra $ \\x -> complexConjugate $ a x\n\ninstance (Field k, IsComplex k) => DualVectors k (InfBra k m) (InfKet k m) where\n dual (InfBra a) = InfKet $ \\x -> complexConjugate $ a x\n\n\n\n-- a vector of coefficients at lattice points\ndata LatticeKet k m = LatticeKet { unLatticeKet :: R.Array R.D R.DIM1 k }\ndata LatticeBra k m = LatticeBra { unLatticeBra :: R.Array R.D R.DIM1 k }\n\n\ninstance (Show k, Show m) => Show (LatticeKet k m) where\n -- Delayed representation doesn't have show instance\n show (LatticeKet vec) = show $! compute vec\n where compute :: Show k => R.Array R.D R.DIM1 k -> R.Array R.V R.DIM1 k\n compute = R.computeS\n\ninstance (Show k, Show m) => Show (LatticeBra k m) where\n -- Delayed representation doesn't have show instance\n show (LatticeBra vec) = show $! compute vec\n where compute :: Show k => R.Array R.D R.DIM1 k -> R.Array R.V R.DIM1 k\n compute = R.computeS\n\ninstance Field k => Additive (LatticeKet k m) where\n (+) (LatticeKet a) (LatticeKet b) = LatticeKet $! R.zipWith (+) a b\n\ninstance Field k => Additive (LatticeBra k m) where\n (+) (LatticeBra a) (LatticeBra b) = LatticeBra $! R.zipWith (+) a b\n\ninstance Field k => VectorSpace k (LatticeKet k m) where\n (*^) s (LatticeKet v) = LatticeKet $! R.map (s *) v\n \ninstance Field k => VectorSpace k (LatticeBra k m) where\n (*^) s (LatticeBra v) = LatticeBra $! R.map (s *) v\n\ninstance (Field k, IsComplex k) => DualVectors k (LatticeKet k m) (LatticeBra k m) where\n dual (LatticeKet a) = LatticeBra $! R.map complexConjugate a\n\ninstance (Field k, IsComplex k) => DualVectors k (LatticeBra k m) (LatticeKet k m) where\n dual (LatticeBra a) = LatticeKet $! R.map complexConjugate a\n\n\n\n-- n x 1 matrix\ndata SparseMatKet k ck m where\n SparseMatKet :: E.Elem k ck => ES.SparseMatrix k ck -> SparseMatKet k ck m\n \nunSparseMatKet :: SparseMatKet k ck m -> ES.SparseMatrix k ck\nunSparseMatKet (SparseMatKet mat) = mat\n\ndata SparseMatBra k ck m where\n SparseMatBra :: E.Elem k ck => ES.SparseMatrix k ck -> SparseMatBra k ck m\n \nunSparseMatBra :: SparseMatBra k ck m -> ES.SparseMatrix k ck\nunSparseMatBra (SparseMatBra mat) = mat\n\n\ninstance (Show k) => Show (SparseMatKet k ck m) where\n show (SparseMatKet mat) = show mat\n\ninstance (Show k) => Show (SparseMatBra k ck m) where\n show (SparseMatBra mat) = show mat \n\ninstance Additive (SparseMatKet k ck m) where\n (+) (SparseMatKet a) (SparseMatKet b) = SparseMatKet $! ES.add a b\n\ninstance Additive (SparseMatBra k ck m) where\n (+) (SparseMatBra a) (SparseMatBra b) = SparseMatBra $! ES.add a b\n\ninstance Field k => VectorSpace k (SparseMatKet k ck m) where\n (*^) s (SparseMatKet v) = SparseMatKet $! ES.scale s v\n \ninstance Field k => VectorSpace k (SparseMatBra k ck m) where\n (*^) s (SparseMatBra v) = SparseMatBra $! ES.scale s v\n\n\n-------------------------------------\n-- Constructions of operators\n\n\n-- Operator formed from outerproduct of two vectors\ndata OuterOperator k v cv where\n OuterOperator :: (InnerProductSpace k v, DualVectors k cv v) => [(v, cv)] -> OuterOperator k v cv\n \nunOuterOperator :: OuterOperator k v cv -> [(v, cv)]\nunOuterOperator (OuterOperator outerProducts) = outerProducts\n\ninstance ( InnerProductSpace k v\n , DualVectors k cv v\n )\n => SimpleOperator k v (OuterOperator k v cv) where\n op (OuterOperator outerProducts) vec = L.foldr1 (+) $ map (\\(ovec,ocovec) -> (ocovec <|> vec) *^ ovec) $ outerProducts\n\ninstance ( InnerProductSpace k v\n , DualVectors k cv v\n )\n => Operator k v cv (OuterOperator k v cv) where\n (|><|) vec covec = OuterOperator [(vec, covec)]\n\ninstance Additive (OuterOperator k v cv) where\n (+) (OuterOperator o1) (OuterOperator o2) = OuterOperator $ o1 L.++ o2\n\n\n\n\n-- a sparse operator represented as a map from (i,j) to coefficient of |i> = |i> and therefore the operation requires inner product to be defined\ndata SparseOperator k m = SparseOperator { unSparseOperator :: M.Map (m, m) k }\n\n\ninstance ( Field k, Ord m,\n InnerProductSpace k (SparseKet k m),\n DualVectors k (SparseBra k m) (SparseKet k m)\n )\n => SimpleOperator k (SparseKet k m) (SparseOperator k m) where \n op (SparseOperator opMap) ket = SparseKet $! M.fromListWith (+) $!\n map (\\(veci, coveci) -> ( veci\n , (SparseBra $! M.fromListWith (+) $! catMaybes $! [fmap ((,) coveci) $! M.lookup (veci, coveci) opMap]) <|> ket\n )\n ) $!\n (M.keys opMap) \n\ninstance ( Field k, Ord m,\n InnerProductSpace k (SparseKet k m),\n DualVectors k (SparseBra k m) (SparseKet k m)\n )\n => Operator k (SparseKet k m) (SparseBra k m) (SparseOperator k m) where \n (|><|) (SparseKet vecMap) (SparseBra covecMap) = SparseOperator $! M.fromListWith (+) $!\n catMaybes [(,) (i,j) <$> (fmap (*) (M.lookup i vecMap) <*> (M.lookup j covecMap)) | i <- M.keys vecMap, j <- M.keys covecMap ]\n\ninstance ( Field k, Ord m,\n InnerProductSpace k (SparseKet k m),\n DualVectors k (SparseBra k m) (SparseKet k m)\n )\n => Additive (SparseOperator k m) where \n (+) (SparseOperator a) (SparseOperator b) = SparseOperator $! M.unionWith (+) a b\n\ninstance ( Field k, Ord m,\n InnerProductSpace k (SparseKet k m),\n DualVectors k (SparseBra k m) (SparseKet k m)\n )\n => Multiplicative (SparseOperator k m) where \n (*) (SparseOperator a) (SparseOperator b) = SparseOperator $! M.fromListWith (+) $! multiplyMaps a b []\n where\n -- chaoose one index i and sum (over j and k) |j> M.Map (m,m) k -> M.Map (m,m) k -> [((m,m), k)] -> [((m,m), k)]\n multiplyMaps mapA mapB oldResult = case null mapA || null mapB of\n True -> oldResult\n False ->\n -- toList uses list fusion so this should not go through entire map\n let oneElement = L.take 1 $ M.toList $ mapA\n in case oneElement of\n [] -> oldResult\n elementToUse : _ -> let indexToUse = (snd $! fst elementToUse)\n\n -- \n indexKet = SparseKet $! M.singleton indexToUse one\n indexSquaredNorm = indexKet <.> indexKet\n\n -- take all keys from mapA which have this index in snd of key\n (mapAToUse, mapAToPass) = M.partitionWithKey (\\key _ -> snd key == indexToUse) mapA\n -- take all keys from mapA which have this index in snd of key\n (mapBToUse, mapBToPass) = M.partitionWithKey (\\key _ -> fst key == indexToUse) mapB\n\n -- we can discard second index from mapAToUse and first index from mapBToUse\n -- we also know that the preserved indices will occur uniquely in index\n -- so we can just take the cross product\n listAToUse = M.toList $! mapAToUse\n listBToUse = M.toList $! mapBToUse\n newResult = [((a,b), va * vb * indexSquaredNorm) | ((a,_), va) <- listAToUse,\n ((_,b), vb) <- listBToUse\n ]\n\n in multiplyMaps mapAToPass mapBToPass $! newResult ++ oldResult\n\ninstance ( Field k, Ord m,\n InnerProductSpace k (SparseKet k m),\n DualVectors k (SparseBra k m) (SparseKet k m)\n )\n => LeftModule k (SparseOperator k m) where\n (.*) scalar (SparseOperator b) = SparseOperator $! M.map (scalar *) b\n\n\n\n-- a more general operator represented as a map from j to Map i_n s_n where operator takes |i_n> to s_n |j>\n-- this construct may not suffice when there are uncountable such i_n\ndata InfOperator k m = InfOperator { unInfOperator :: m -> M.Map m k }\n\ninstance (Field k) => SimpleOperator k (InfKet k m) (InfOperator k m) where\n op operator = \\(InfKet coeffMap) -> InfKet $ \\index -> foldr1 (+) $\n map ( \\(invIndex, factor) -> factor * coeffMap invIndex ) $\n M.toList $ unInfOperator operator $ index\n\ninstance (Field k, Ord m) => Additive (InfOperator k m) where\n (+) (InfOperator op1) (InfOperator op2) = InfOperator $ \\index -> M.unionWith (+) (op1 index) (op2 index)\n\ninstance (Field k, Ord m) => Multiplicative (InfOperator k m) where\n (*) (InfOperator op1) (InfOperator op2) = InfOperator $ \\index ->\n foldr1 (M.unionWith (+)) $\n map (\\(i,s) -> M.map (s *) $ op2 i) $\n M.toList $ op1 index\n\n\n\n-- A matrix to transfom LatticeKet vector\ndata LatticeOperator k m where\n LatticeOperator :: (Field k, R.Elt k, R.Unbox k, Num k) => R.Array R.D R.DIM2 k -> LatticeOperator k m\n\nunLatticeOperator :: LatticeOperator k m -> R.Array R.D R.DIM2 k\nunLatticeOperator (LatticeOperator mat) = mat\n\n-- Num k is required because of sumP in method definition\ninstance Field k => SimpleOperator k (LatticeKet k m) (LatticeOperator k m) where\n op (LatticeOperator matrix) (LatticeKet vector) = LatticeKet $! R.delay $! runIdentity $! mvMultP matrix vector\n\ninstance Additive (LatticeOperator k m) where\n (+) (LatticeOperator op1) (LatticeOperator op2) = LatticeOperator $! R.zipWith (+) op1 op2\n\n-- Num k is required because of sumP in method definition\ninstance Multiplicative (LatticeOperator k m) where\n (*) (LatticeOperator op1) (LatticeOperator op2) = LatticeOperator $! R.delay $! runIdentity $! mmMultP op1 op2\n\ninstance Field k => LeftModule k (LatticeOperator k m) where\n (.*) scalar (LatticeOperator matrix) = LatticeOperator $! R.map (scalar *) matrix\n\n\n-- Taken from Repa wiki, extended it to Additive and Multiplicative structures\nmmMultP :: (Monad m, R.Source r k, Additive k, Multiplicative k, R.Elt k, R.Unbox k, Num k)\n => R.Array r R.DIM2 k\n -> R.Array r R.DIM2 k\n -> m (R.Array R.U R.DIM2 k)\nmmMultP a b = R.sumP (R.zipWith (*) aRepl bRepl)\n where\n -- Note: transpose transposes the lowest two dimensions\n t = R.transpose b\n aRepl = R.extend (R.Z R.:.R.All R.:.colsB R.:.R.All) a\n bRepl = R.extend (R.Z R.:.rowsA R.:.R.All R.:.R.All) t\n\n (R.Z R.:.colsA R.:.rowsA) = R.extent a\n (R.Z R.:.colsB R.:.rowsB) = R.extent b\n\n-- Multiply a martix with a vector\n-- based on the above matrix matrix multiplication\nmvMultP :: (Monad m, R.Source r k, Additive k, Multiplicative k, R.Elt k, R.Unbox k, Num k)\n => R.Array r R.DIM2 k\n -> R.Array r R.DIM1 k\n -> m (R.Array R.U R.DIM1 k)\nmvMultP a b = R.sumP (R.zipWith (*) aRepl bRepl)\n where\n aRepl = a\n bRepl = R.extend (R.Z R.:.rowsA R.:.R.All) b\n (R.Z R.:.rowsA R.:.colsA) = R.extent a\n\n\n\n\n-- A matrix to transfom LatticeKet vector\ndata SparseMatOperator k ck m where\n SparseMatOperator :: E.Elem k ck => ES.SparseMatrix k ck -> SparseMatOperator k ck m\n \nunSparseMatOperator :: SparseMatOperator k ck m -> ES.SparseMatrix k ck\nunSparseMatOperator (SparseMatOperator mat) = mat\n\n\n-- Num k is required because of sumP in method definition\ninstance Field k => SimpleOperator k (SparseMatKet k ck m) (SparseMatOperator k ck m) where\n op (SparseMatOperator matrix) (SparseMatKet vector) = SparseMatKet $! ES.mul matrix vector\n\ninstance Field k => Additive (SparseMatOperator k ck m) where\n (+) (SparseMatOperator op1) (SparseMatOperator op2) = SparseMatOperator $! ES.add op1 op2\n\ninstance Field k => Multiplicative (SparseMatOperator k ck m) where\n (*) (SparseMatOperator op1) (SparseMatOperator op2) = SparseMatOperator $! ES.mul op1 op2\n\ninstance Field k => LeftModule k (SparseMatOperator k ck m) where\n (.*) scalar (SparseMatOperator matrix) = SparseMatOperator $! ES.scale scalar matrix\n", "meta": {"hexsha": "b859f80cae78ea14e08361278919ba0cec596570", "size": 18088, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "has-sci-physics/src/Physics/Quantum/Algebra.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/src/Physics/Quantum/Algebra.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/src/Physics/Quantum/Algebra.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": 40.1955555556, "max_line_length": 144, "alphanum_fraction": 0.6118973905, "num_tokens": 5214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5345318094783255}} {"text": "-- Filename: fft.hs\n-- Created by: Daniel Winograd-Cort\n-- Created on: unknown\n-- Last Modified by: Daniel Winograd-Cort\n-- Last Modified on: 12/12/2013\n\n-- -- DESCRIPTION --\n-- This code was inspired by Euterpea. It uses UISF to present a GUI that \n-- shows the sum of two waves (whose frequencies are specified by the user) \n-- as well as the Fast Fourier Transform of that sum.\n-- \n-- This module requires the array and pure-fft packages.\n\n{-# LANGUAGE Arrows #-}\nmodule FRP.UISF.Examples.FFT where\nimport FRP.UISF\nimport Numeric.FFT (fft)\nimport Data.Complex\nimport Data.Map (Map)\nimport Data.Maybe (listToMaybe, catMaybes)\nimport qualified Data.Map as Map\n\nimport Data.Array.Unboxed\n\n\n\n-- | Alternative for working with Math.FFT instead of Numeric.FFT\n--import qualified Math.FFT as FFT\n--import Data.Array.IArray\n--import Data.Array.CArray\n--myFFT n lst = elems $ (FFT.dft) (listArray (0, n-1) lst)\n\n\n--------------------------------------\n-- Sine wave oscillators\n--------------------------------------\n\n-- Table definition\ntype Table = UArray Int Double\n\n-- Sine table generator. Takes an integer representing the number of samples to generate\n-- and a list of relative intensities for the overtones of the sine wave.\n\ntableSinesN :: Int -> [Double] -> Table\ntableSinesN size amps = \n let wave x = sum (zipWith (*) [sin (2*pi*x*n) | n <- [1..]] amps)\n delta = 1 / fromIntegral size\n waveform = take size $ map wave [0,delta..]\n divisor = (maximum . map abs) waveform\n in listArray (0,size) (map (/divisor) waveform)\n\n-- Two example sine tables.\n\ntab1, tab2 :: Table\ntab1 = tableSinesN 4096 [1] -- Basic sine wave\ntab2 = tableSinesN 4096 [1.0,0.5,0.33]\n\n-- Table-driven oscillator\n\nosc :: ArrowCircuit a => Table -> Double -> a Double Double\nosc table sr = proc freq -> do\n rec \n let delta = 1 / sr * freq\n phase = if next > 1 then frac next else next\n next <- delay 0 -< frac (phase + delta)\n returnA -< ((table!).(`mod` size).round.(*rate)) phase\n where (_,size) = bounds table\n rate = fromIntegral size\n frac x = if x > 1 then x - fromIntegral (truncate x) else x\n\n\n--------------------------------------\n-- Fast Fourier Transform\n--------------------------------------\n\n-- | Returns n samples of type b from the input stream at a time, \n-- updating after k samples. This function is good for chunking \n-- data and is a critical component to fftA\nquantize :: ArrowCircuit a => Int -> Int -> a b (SEvent [b])\nquantize n k = proc d -> do\n rec (ds,c) <- delay ([],0) -< (take n (d:ds), c+1)\n returnA -< if c >= n && c `mod` k == 0 then Just ds else Nothing\n\n-- | Converts the vector result of a dft into a map from frequency to magnitude.\n-- One common use is:\n-- fftA >>> arr (fmap $ presentFFT clockRate)\npresentFFT :: Double -> [Double] -> Map Double Double\npresentFFT clockRate a = Map.fromList $ zipWith (curry mkAssoc) [0..] a where \n mkAssoc (i,c) = (freq, c) where\n samplesPerPeriod = fromIntegral (length a)\n freq = fromIntegral i * (clockRate / samplesPerPeriod)\n\n-- | Given a quantization frequency (the number of samples between each \n-- successive FFT calculation) and a fundamental period, this will decompose\n-- the input signal into its constituent frequencies.\n-- NOTE: The fundamental period must be a power of two!\nfftA :: ArrowCircuit a => Int -> Int -> a Double (SEvent [Double])\nfftA qf fp = proc d -> do\n carray <- quantize fp qf -< d :+ 0\n returnA -< fmap (map magnitude . take (fp `div` 2) . fft) carray\n\n\n--------------------------------------\n-- UISF Example\n--------------------------------------\n\n-- This example shows off the histogram and realtimeGraph widgets by \n-- summing two sin waves and displaying them. Additionally, it makes \n-- use of two horizontal sliders.\n-- This example also shows off asyncUISFV and how to take a SigFun, \n-- of the type used to create sound, and convert it to a UISF.\nfftEx :: UISF () ()\nfftEx = proc _ -> do\n f1 <- hSlider (1, 2000) 440 -< ()\n _ <- leftRight (label \"Freq 1: \" >>> display) -< f1\n f2 <- hSlider (1, 2000) 440 -< ()\n _ <- leftRight (label \"Freq 2: \" >>> display) -< f2\n d <- asyncVT sr 0.1 myAutomaton -< (f1, f2)\n let fft = listToMaybe $ catMaybes $ map (snd . fst) d\n s = map (\\((s, _), t) -> (s,t)) d\n _ <- histogram (makeLayout (Stretchy 10) (Fixed 150)) -< fft\n _ <- realtimeGraph (makeLayout (Stretchy 10) (Fixed 150)) 2 Black -< s\n returnA -< ()\n where\n sr = 1000 -- signal rate\n myAutomaton = proc (f1, f2) -> do\n s1 <- osc tab1 sr -< f1\n s2 <- osc tab2 sr -< f2\n let s = (s1 + s2)/2\n fftData <- fftA 100 256 -< s\n returnA -< (s, fftData)\n\n-- This test is run separately from the others.\nmain :: IO ()\nmain = runUI (defaultUIParams {uiSize=(500, 600), uiTitle=\"FFT Example\"}) fftEx\n", "meta": {"hexsha": "fb62fe0ef016ca77bbc2d4a51db09e7927bdc05c", "size": 4886, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "FRP/UISF/Examples/fft.hs", "max_stars_repo_name": "dwincort/UISF", "max_stars_repo_head_hexsha": "291a6155e41f351d938daed3d2be6f8baf832a19", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2015-02-06T11:38:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T13:11:29.000Z", "max_issues_repo_path": "FRP/UISF/Examples/fft.hs", "max_issues_repo_name": "dwincort/UISF", "max_issues_repo_head_hexsha": "291a6155e41f351d938daed3d2be6f8baf832a19", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-01-26T15:17:37.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-25T11:32:05.000Z", "max_forks_repo_path": "FRP/UISF/Examples/fft.hs", "max_forks_repo_name": "dwincort/UISF", "max_forks_repo_head_hexsha": "291a6155e41f351d938daed3d2be6f8baf832a19", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-04-20T19:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-17T07:42:12.000Z", "avg_line_length": 35.9264705882, "max_line_length": 88, "alphanum_fraction": 0.6176831764, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5340285621239956}} {"text": "{-# LANGUAGE NoMonomorphismRestriction, ImpredicativeTypes ,RankNTypes, TypeOperators #-}\nimport Kalman \nimport qualified Data.Vector as V\nimport Vectorization.Instances\nimport Local\nimport Linear.V1\nimport Data.Distributive\nimport qualified Data.Foldable as F\nimport Linear.V2\nimport Data.Complex \nimport CartesianProduct\nimport System.Random.MWC.Distributions\nimport Vectorization\nimport Foreign.Storable\nimport Foreign.Cholesky\nimport Space.Class\nimport Control.Applicative\nimport Control.Monad\nimport System.Random.MWC\nimport Graphics.Gnuplot.Simple\nimport Statistics.Autocorrelation\nimport Statistics.Sample\nimport Data.Functor.Compose\nimport Foreign.FStorable\nimport Foreign.FStorable\n\ntype Model = V1 :|: V1 :|: V1 :|: V1\n\npredSin :: V1 Double -> Model Double -> Model Double\npredSin dt s@(theta :|: omega :|: amp :|: accel) = s |+| ((omega*dt ) :|: 0 :|: (dt*accel ) :|: 0 )\n \n\nprojSin :: Model Double -> V1 Double\nprojSin (theta :|: omega :|: amp :|: accel) = amp * (fmap sin theta )\n\nnx :: Model (Model Double)\nnx = diag $ fmap (*1e-3)((1/3) :|: 1 :|: 0.1 :|: 0.1)\n\ngetMean :: Functor f => (forall b . g b -> V1 b) -> f (g b , g (g b)) -> f b\ngetMean s = fmap ( unV1 . s . fst )\n\ngetCov :: (Num b ,Functor f )=> (forall b . g b -> V1 b) -> f (g b , g (g b)) -> f b\ngetCov s = fmap ( abs .unV1 . s . unV1 . s . snd )\n\nsigmaBound :: Num b => (forall b . g b -> V1 b) -> [(g b , g (g b))] -> [[b]]\nsigmaBound s f = [zipWith (+) (getMean s f) (getCov s f), getMean s f,zipWith (-) (getMean s f) (getCov s f)]\n\nsigmas :: Num b => (forall b . g b -> V1 b) -> [[(g b , g (g b))]] -> [[b]]\nsigmas s = concat . map (sigmaBound s) \n\nallSigmas :: Num b => [forall b . g b -> V1 b] -> [[(g b , g (g b))]] -> [[[b]]]\nallSigmas s d = map (flip sigmas $ d) s \n\nunV1 (V1 x) = x \nexecute = do \n seed <- create \n let n = 500\n v <- replicateM n (normal 0 0.25 seed) \n let noisedData = testeSet v\n cleanData = testeSet (replicate n 0)\n let ny :: (V1 (V1 Double))\n ny = 1 \n xo :: Model Double\n xo = 0.1 :|: 0.1 :|: 1 :|: 1e-3 \n alpha = 1e-2\n iteration r = full (predSin 1) nx projSin ny r \n backwardIteration = smoothing (predSin 1 ) nx \n forwards = scanl (flip iteration) (xo,nx) (fmap V1 $ testeSet v)\n backwards = reverse $ scanl1 (flip backwardIteration) $ reverse forwards \n project = fmap (unV1 . projSin . fst ) \n getAmp = fmap ( unV1 . amp . fst )\n getAmpCov = fmap ( unV1 . amp . unV1 . amp . snd) \n get x = fmap ( unV1 . x . fst )\n -- print projections\n plotLists [] [testeSet (replicate n 0) ,testeSet v,project backwards ] \n -- print all parameters \n mapM_ (plotLists []) (allSigmas [amp ,accel,omega] [backwards])\n let ampCov = V.fromList noiseSignalBackward \n noiseSignalBackward = zipWith (-) cleanData (project backwards)\n noiseSignalForward = zipWith (-) cleanData (project forwards)\n -- Print residuals\n plotLists [] [noiseSignalForward , noiseSignalBackward ,v] \n print $ mean ampCov\n print $ stdDev ampCov\n print $ mean $ V.fromList $ zipWith (-) (getAmp forwards) (getAmp backwards)\n print $ stdDev $ V.fromList $ zipWith (-) (getAmp forwards) (getAmp backwards)\n\namp :: Model a -> V1 a\namp ( x :|: _ :|: amp :|: _ ) = amp \naccel ( x :|: _ :|: amp :|: accel ) = accel \nomega ( x :|: omega :|: amp :|: accel ) = omega \ntheta ( theta :|: _ :|: amp :|: accel ) = theta \n \nmatI :: Num a => Int -> [[a]]\nmatI n = [ [fromIntegral $ fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]\n\ndiag = liftIdent\nliftIdent ::(R f,Num a,Storable a,Vectorize f,Functor f,Applicative f)=> f a -> f ( f a)\nliftIdent x = fmap (liftA2 (*) x) (fromLists $ matI n )\n where n = dimM x\n\ntesteSet v = zipWith (+) (map (function.fromIntegral) [1..length v]) v where\n function x = (1+x/500) * sin(16 * x/500 * pi)\n", "meta": {"hexsha": "08e5863f9c56c20ef8ba433de87fac6791b98f22", "size": 3847, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "example/Sine.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/Sine.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/Sine.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": 36.9903846154, "max_line_length": 111, "alphanum_fraction": 0.6129451521, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5334282495233217}} {"text": "{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE BangPatterns #-}\n\n{-|\nModule : Statistics.FastBayes.Linear\nDescription : Bayesian linear regression via maximum marginal likelihood.\nCopyright : (c) Melinae, 2014\n Chad Scherrer, 2014\nLicense : MIT\nMaintainer : chad.scherrer@gmail.com\nStability : experimental\nPortability : POSIX\n\nThis module gives an implementation of Bayesian linear regression, with the scale of the prior chosen by marginal likelihood.\n\nThe inputs for a Bayesian linear model are identical to those of a classical linear model, except that in addition to a design matrix and response, we must also specify a prior distribution on the weights and the noise. This leaves us with an open question of how these should be specified.\n\nIn his book /Pattern Recognition and Machine Learning/, Christopher Bishop provides details for an approach that simplifies the situation significantly, and allows for much faster inference. The structure of the linear model allows us to integrate the posterior over the weights, resulting in the /marginal likelihood/, expressed as a function of the prior precision and noise precision. This, in turn, can be easily optimized.\n-}\n\nmodule Statistics.FastBayes.Linear \n ( test\n , Fit\n , fit0\n , fit1\n , priorPrecision \n , noisePrecision \n , effectiveNumParameters\n , logEvidence \n , mapWeights \n , intercept \n , hessian \n , features\n , Predict\n , predict\n , studentize\n , studentizeM\n , inputs\n , fitted\n , fittedSD\n )\n where\n\nimport qualified Data.Vector.Storable as V\nimport Data.Packed.Matrix\nimport Numeric.LinearAlgebra\n\ndata Fit a = Fit\n { priorPrecision :: Double -- ^The precision (inverse variance) of the prior distribution, determined by maximizing the marginal likelihood\n , noisePrecision :: Double -- ^The precision (inverse variance) of the noise\n , effectiveNumParameters :: Double -- ^The effective number of parameters in the model\n , logEvidence :: Double -- ^The log of the evidence, which is useful for model comparison (different features, same response)\n , mapWeights :: Vector Double -- ^The MAP (maximum a posteriori) values for the parameter weights\n , intercept :: Double -- ^The y-intercept\n , hessian :: Matrix Double -- ^The Hessian (matrix of second derivatives) for the posterior distribution\n , features :: a → Vector Double -- ^Extract features from a data point\n }\n\n-- instance Show (Fit a) where\n\n-- |@fit0 lim x y@ fits a Bayesian linear model to a design matrix @x@ and response vector @y@. This is an iterative algorithm, resulting in a sequence (list) of (α,β) values. Here α is the prior precision, and β is the noise precision. The @lim@ function passed in is used to specify how the limit of this sequence should be computed.\nfit0 :: \n ([(Double, Double)] → (Double, Double)) -- ^How to take the limit of the (α,β) sequence. A simple approach is, /e.g./, @fit (!! 1000) x y@\n → Bool -- ^Whether to studentize (translate and re-scale) the features\n → (a → Vector Double) -- ^The features\n → [a] -- ^The input data\n → Vector Double -- ^The response vector\n → Fit a\nfit0 lim student f xs y = Fit α β γ logEv m 0 h f'\n where\n (x, f') | not student = (fromRows $ map f xs, f)\n | student = ( x0, fs . f)\n where\n (x0, fs) = studentizeM . fromRows . map f $ xs\n n = rows x\n p = cols x\n α0 = 1.0\n β0 = 1.0\n\n -- A vector of the eigenvalues of xtx\n (_,sqrtEigs,_) = compactSVD x\n eigs = V.map square sqrtEigs\n\n xtx = trans x <> x\n xty = trans x <> y\n getHessian a b = diag (V.replicate p a) + scale b xtx\n\n m = scale β $ h <\\> xty\n \n go :: Double → Double → [(Double, Double)]\n go a0 b0 = (a0, b0) : go a b\n where\n h0 = getHessian a0 b0\n m0 = scale b0 $ h0 <\\> xty \n c = V.sum $ V.map (\\x' → x' / (a0 + x')) eigs\n a = c / (m0 <.> m0)\n b = recip $ (normSq $ y - x <> m0) / (fromIntegral n - c)\n \n γ = V.sum $ V.map (\\x' → x' / (α + x')) eigs\n\n h = getHessian α β \n logEv = 0.5 * \n ( fromIntegral p * log α \n + fromIntegral n * log β \n - (β * normSq (y - x <> m) + α * (m <.> m))\n - logDetH \n - fromIntegral n * log (2*pi)\n )\n where\n (_,(logDetH, _)) = invlndet h\n\n (α, β) = lim $ go α0 β0\n\nfit1 :: \n ([(Double, Double)] → (Double, Double)) -- ^How to take the limit of the (α,β) sequence. A simple approach is, /e.g./, @fit (!! 1000) x y@\n → Bool -- ^Whether to studentize (translate and re-scale) the features\n → (a → Vector Double) -- ^The features\n → [a] -- ^The input data\n → Vector Double -- ^The response vector\n → Fit a\nfit1 lim student f xs y = f0 {intercept = μ}\n where\n μ = mean y\n n = V.length y\n f0 = fit0 lim student f xs (y - konst μ n)\n\n\nsquare :: Double → Double\nsquare x = x * x\n\nnormSq :: Vector Double → Double\nnormSq x = x <.> x\n\nmean :: Vector Double -> Double\nmean v = V.sum v / fromIntegral (V.length v)\n\nstudentizeM :: Matrix Double -> (Matrix Double, Vector Double → Vector Double)\nstudentizeM m = (x, f)\n where\n (xs, fs) = unzip . map studentize . toColumns $ m\n x = fromColumns xs\n f = fromList . zipWith ($) fs . toList\n\nstudentize :: Vector Double -> (Vector Double, Double → Double)\nstudentize v = (scale (1/σ) v0, f)\n where\n n = V.length v\n μ = mean v\n v0 = v - konst μ n\n σ = sqrt $ normSq v0 / fromIntegral n\n f x = (x - μ) / σ\n\ntest = myFit 11\n where\n x = [1,1.1..pi] \n y = fromList $ map sin x\n f n x = fromList . map (x **) $ [1..n]\n myFit n = fit1 (!!100) True (f n) x y\n\ndata Predict a = Predict\n { inputs :: [a]\n , fitted :: [Double]\n , fittedSD :: [Double]\n }\n\npredict :: Fit a -> [a] -> Predict a\npredict myFit xs = Predict xs ys (toList . V.map sqrt $ konst (1/β) n + takeDiag cov)\n where\n n = rows x\n α = priorPrecision myFit \n β = noisePrecision myFit \n w = mapWeights myFit \n y0 = intercept myFit \n h = hessian myFit \n f = features myFit \n x = fromRows $ map f xs\n cov = x <> (h <\\> trans x)\n y = x <> w + konst y0 n\n ys = toList y", "meta": {"hexsha": "62e0ef0b7f1d0ab34c33ed9389498e79161139ff", "size": 6500, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/FastBayes/Linear.hs", "max_stars_repo_name": "cscherrer/fastbayes", "max_stars_repo_head_hexsha": "e6feb877905fbad799c2c4427eb85b968238c2ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-07-29T15:30:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-17T00:37:46.000Z", "max_issues_repo_path": "src/Statistics/FastBayes/Linear.hs", "max_issues_repo_name": "cscherrer/fastbayes", "max_issues_repo_head_hexsha": "e6feb877905fbad799c2c4427eb85b968238c2ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/FastBayes/Linear.hs", "max_forks_repo_name": "cscherrer/fastbayes", "max_forks_repo_head_hexsha": "e6feb877905fbad799c2c4427eb85b968238c2ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:30:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:30:45.000Z", "avg_line_length": 36.312849162, "max_line_length": 427, "alphanum_fraction": 0.5949230769, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5323425213998123}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# 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 , binomialE\n -- * Accessors\n , bdTrials\n , bdProbability\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 (choose,logChoose,incompleteBeta,log1p)\nimport Numeric.MathFunctions.Constants (m_epsilon)\n\nimport qualified Statistics.Distribution as D\nimport qualified Statistics.Distribution.Poisson.Internal as I\nimport Statistics.Internal\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, Typeable, Data, Generic)\n\ninstance Show BinomialDistribution where\n showsPrec i (BD n p) = defaultShow2 \"binomial\" n p i\ninstance Read BinomialDistribution where\n readPrec = defaultReadPrecM2 \"binomial\" binomialE\n\ninstance ToJSON BinomialDistribution\ninstance FromJSON BinomialDistribution where\n parseJSON (Object v) = do\n n <- v .: \"bdTrials\"\n p <- v .: \"bdProbability\"\n maybe (fail $ errMsg n p) return $ binomialE n p\n parseJSON _ = empty\n\ninstance Binary BinomialDistribution where\n put (BD x y) = put x >> put y\n get = do\n n <- get\n p <- get\n maybe (fail $ errMsg n p) return $ binomialE n p\n\n\n\ninstance D.Distribution BinomialDistribution where\n cumulative = cumulative\n\ninstance D.DiscreteDistr BinomialDistribution where\n probability = probability\n logProbability = logProbability\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 -- choose could overflow Double for n >= 1030 so we switch to\n -- log-domain to calculate probability\n | n < 1000 = choose n k * p^k * (1-p)^(n-k)\n | otherwise = exp $ logChoose n k + log p * k' + log1p (-p) * nk'\n where\n k' = fromIntegral k\n nk' = fromIntegral $ n - k\n\nlogProbability :: BinomialDistribution -> Int -> Double\nlogProbability (BD n p) k\n | k < 0 || k > n = (-1)/0\n | n == 0 = 0\n | otherwise = logChoose n k + log p * k' + log1p (-p) * nk'\n where\n k' = fromIntegral k\n nk' = fromIntegral $ 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 = maybe (error $ errMsg n p) id $ binomialE n p\n\n-- | Construct binomial distribution. Number of trials must be\n-- non-negative and probability must be in [0,1] range\nbinomialE :: Int -- ^ Number of trials.\n -> Double -- ^ Probability.\n -> Maybe BinomialDistribution\nbinomialE n p\n | n < 0 = Nothing\n | p >= 0 || p <= 1 = Just (BD n p)\n | otherwise = Nothing\n\nerrMsg :: Int -> Double -> String\nerrMsg n p\n = \"Statistics.Distribution.Binomial.binomial: n=\" ++ show n\n ++ \" p=\" ++ show p ++ \"but n>=0 and p in [0,1]\"\n", "meta": {"hexsha": "cdae86730c45beb04933f6f1ff4303755a86de9f", "size": 5276, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Binomial.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-11T23:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T22:33:10.000Z", "max_issues_repo_path": "Statistics/Distribution/Binomial.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-02-26T06:10:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:27:01.000Z", "max_forks_repo_path": "Statistics/Distribution/Binomial.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": 31.5928143713, "max_line_length": 83, "alphanum_fraction": 0.6489764973, "num_tokens": 1428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5319431128639316}} {"text": "{-# LANGUAGE OverloadedLists#-}\n{-# LANGUAGE RankNTypes#-}\n{-# LANGUAGE ScopedTypeVariables #-}\n--{-# LANGUAGE Strict#-}\nmodule Lib where\n\nimport Control.Monad.ST\nimport Debug.Trace\nimport qualified Numeric.AD as AD\nimport Numeric.AD.Internal.Reverse\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Data\nimport qualified Data.Vector.Storable as VS\nimport System.Random\nimport Debug.Trace\nimport Text.Printf\nimport Control.Monad\nimport Control.Concurrent\nimport Data.List (permutations)\n\nsomeFunc :: IO ()\nsomeFunc = putStrLn \"someFunc\"\n\ndata Neuron = Neuron {\n w :: Vector Double,\n f :: Double -> Double }\n\ndata MNeuron = MNeuron {\n mw :: Matrix Double,\n mf :: Double -> Double }\n\ninstance Show Neuron where\n show = show . w\n\ninstance Show MNeuron where\n show = show . mw\n\napplyMNeuron :: MNeuron -> Vector Double -> Vector Double\napplyMNeuron (MNeuron wagi funkcja) = VS.map funkcja . (wagi #>) . VS.cons 1\n\napplyNeuron :: Neuron -> Vector Double -> Double\napplyNeuron (Neuron w f) = f . (w <.>) . VS.cons 1\n\nacFunc :: Double -> Double\nacFunc x | x >= 0 = 1\n | otherwise = 0\n\nnotN = Neuron [1,-1.5] acFunc\n\nandN = Neuron [-2, 1.5, 1.5] acFunc\n\nnandN = Neuron [2, -1.5, -1.5] acFunc\n\norN = Neuron [-1, 1.5, 1.5] acFunc\n\n-- 2. Picture classification\n\ntrainSet :: [(Vector Double, Double)]\ntrainSet = [([ 0, 0, 0, 0, 0\n , 0, 1, 1, 0, 0\n , 0, 0, 1, 0, 0\n , 0, 0, 1, 0, 0\n , 0, 0, 1, 0, 0], 1)\n\n , ([ 0, 0, 1, 1, 0\n , 0, 0, 0, 1, 0\n , 0, 0, 0, 1, 0\n , 0, 0, 0, 0, 0\n , 0, 0, 0, 0, 0], 1)\n\n , ([ 0, 0, 0, 0, 0\n , 1, 1, 0, 0, 0\n , 0, 1, 0, 0, 0\n , 0, 1, 0, 0, 0\n , 0, 1, 0, 0, 0], 1)\n\n , ([ 0, 0, 0, 0, 0\n , 0, 1, 1, 1, 0\n , 0, 1, 0, 1, 0\n , 0, 1, 1, 1, 0\n , 0, 0, 0, 0, 0], 0)\n\n , ([ 0, 0, 0, 0, 0\n , 0, 0, 0, 0, 0\n , 1, 1, 1, 0, 0\n , 1, 0, 1, 0, 0\n , 1, 1, 1, 0, 0], 0)]\n\ntest :: [Vector Double]\ntest = [[ 0, 1, 1, 0, 0\n , 0, 0, 1, 0, 0\n , 0, 0, 1, 0, 0\n , 0, 0, 0, 0, 0\n , 0, 0, 0, 0, 0\n ]\n ,[ 1, 1, 1, 0, 0\n , 1, 0, 1, 0, 0\n , 1, 0, 1, 0, 0\n , 1, 1, 1, 0, 0\n , 0, 0, 0, 0, 0\n ]\n ,[ 0, 0, 1, 0, 0\n , 0, 0, 1, 0, 0\n , 0, 0, 1, 0, 0\n , 0, 0, 1, 0, 0\n , 0, 0, 0, 0, 0\n ]\n ,[ 0, 0, 0, 0, 0\n , 0, 0, 0, 0, 0\n , 1, 1, 1, 0, 0\n , 1, 0, 1, 0, 0\n , 1, 1, 1, 0, 0\n ]]\n\ntrain st perc trSet = go st 0 perc (cycle trSet) (length trSet)\n where\n go st iters n@(Neuron w f) ((inp,z):xs) c =\n if c <=0 then\n (iters, n)\n else\n go st (iters+1) (Neuron newW f) xs newC\n where\n y = applyNeuron n inp\n newC = if z == y then c - 1 else 5\n newW = w + VS.map (\\x -> x * st * (z - y)) (VS.cons 1 inp)\n\nperceptron :: Neuron\nperceptron = Neuron (VS.fromList . replicate 26 $ 1) acFunc\n\n-- 3. Picture recognition\n\nprPrint :: Vector Double -> String\nprPrint = morph (\\x (acc, count) -> ((if x <= 0 then \" \" else \"■\") ++ (if count `mod` 5 == 0 then \"\\n\" else []) ++ acc, count+1)) []\n where\n morph f a = fst . VS.foldr f (a,0)\n\nreadPic :: String -> Vector Double\nreadPic = VS.fromList . foldr (\\x acc -> case x of\n ' ' -> (-1):acc\n '*' -> 1:acc\n '\\n'-> acc) []\npics :: [String]\npics = [ \" \\n *** \\n * * \\n *** \\n \"\n , \" \\n ** \\n * \\n * \\n \"]\n\nsgn :: Double -> Double\nsgn x\n | x >= 0 = 1\n | x < 0 = -1\n\npicTaker :: MNeuron\npicTaker = MNeuron weights sgn\n where\n [v1, v2] = map readPic pics\n w1 = cmap (/25) (v1 `outer` v1)\n w2 = cmap (/25) (v2 `outer` v2)\n weights = w1 + w2\n\napMNeu2 (MNeuron weights f) = VS.map f . (weights #>)\n\npics2 :: [String]\npics2 = [ \" *** \\n * * \\n * * \\n *** \\n \"\n , \" * \\n * \\n * \\n * \\n * \"]\n\n-- 4. Gradient Descent\ngradStep :: Floating a => a\ngradStep = 0.1\n\neps :: Floating a => a\neps = 0.000001\n\ngradDesc :: (Floating a, Ord a, Show a) => (forall b. (Floating b, Ord b, Show b) => [b] -> b) -> [a] -> ([a], a)\ngradDesc f x = if diff < eps then (newX, f newX) else gradDesc f newX\n where gr = AD.grad f x\n newX = zipWith (-) x . map (gradStep *) $ gr\n diff = abs . foldr (+) 0 . zipWith (-) x $ newX\n\nfunkcja1 :: Num a => [a] -> a\nfunkcja1 [x,y,z] = (2 * x * x) + (2 * y * y) + (z * z) - (2 * x * y) - (2 * y * z) - (2 * x) + 3\n\ndfunkcja1 :: Num a => [a] -> [a]\ndfunkcja1 [x,y,z] = [(4*x) - (2*y) - 2, 4*y - 2*x - 2*z, 2*z - 2*y]\n\nfunkcja2 :: Num a => [a] -> a\nfunkcja2 [x,y] = (3 * x * x * x * x) + (4 * x * x* x) - (12 * x * x) + (12 * y * y) - (27 * y)\n\ndfunkcja2 :: Num a => [a] -> [a]\ndfunkcja2 [x,y] = [12* x* x* x + 12* x* x - 24* x, 24 * y - 24]\n\n-- 5. Backpropagation\n\nbeta :: Double\nbeta = 1.25\n\nkrok :: Double\nkrok = 1\n\nsig :: Double -> Double\nsig = (1/).(1+).exp.negate\n\ndsig :: Double -> Double\ndsig x = sig x * (1 - sig x)\n\ntrainSetXOR :: [(Vector Double, Double)]\ntrainSetXOR =\n [([0,0],0)\n ,([1,0],1)\n ,([0,1],1)\n ,([1,1],0)]\n\nfstLayer :: IO (Neuron, Neuron)\nfstLayer = do\n randVec1 <- VS.replicateM 3 randomIO\n randVec2 <- VS.replicateM 3 randomIO\n return (Neuron randVec1 sig, Neuron randVec2 sig)\n\noutLayer :: IO Neuron\noutLayer = do\n randVec <- VS.replicateM 3 randomIO\n return (Neuron randVec sig)\n\nbeginning :: ((Neuron, Neuron), Neuron)\nbeginning = ((Neuron [2,0,1] sig, Neuron [2,0,1] sig), Neuron [2,0,1] sig)\n\napplyXor :: ((Neuron,Neuron), Neuron) -> Vector Double -> Double\napplyXor ((h1, h2), o) u = applyNeuron o out\n where\n x1 = applyNeuron h1 u\n x2 = applyNeuron h2 u\n out= [x1, x2]\n\ninfixr 3 #*\n(#*) :: Double -> Vector Double -> Vector Double\nx #* v = VS.map (*x) v\n\nzipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]\nzipWith4 f x y z = zipWith ($) (zipWith3 f x y z)\n\ntrainXOR perc trSet = go 0 perc\n where\n go iters n@((n1@(Neuron w1 f1), n2@(Neuron w2 f2)), n3@(Neuron s f3)) =\n if eps > (maximum . VS.toList . VS.map abs $ difference) then\n (iters, newN)\n else\n-- (if iters `mod` 10000 == 0 then trace (show iters ++ \" iterations. Gradients:\\n\" ++ unlines [show gradS,show gradW1,show gradW2] ++ \"\\nDifference:\\n\" ++ show difference ++ \"\\n\") else id ) $\n go (iters+1) newN\n where\n difference = (w1 VS.++ w2 VS.++s) - (newW1 VS.++ newW2 VS.++ newS)\n newN = ((Neuron newW1 f1, Neuron newW2 f2), Neuron newS f3)\n u = map (VS.cons 1 . fst) trSet\n x1s = map (applyNeuron n1 . fst) trSet\n x2s = map (applyNeuron n2 . fst) trSet\n x :: [Vector Double]\n x = zipWith (\\x1 x2 -> [1,x1,x2]) x1s x2s\n y = map (applyXor n . fst) trSet\n z = map snd trSet\n grs x y z = dsig (x<.>s) * (y - z) #* x\n gradsS= zipWith3 grs x y z\n gradS = foldr (+) [0,0,0] gradsS\n newS = s - (VS.map (*gradStep) gradS)\n [_,s1,s2] = s\n grw w sx x y z u= (y-z) * sx * dsig (x<.>s) * dsig (w<.>u) #* u\n gradsW w s = zipWith4 (grw w s) x y z u\n gradW w s = foldr (+) [0,0,0] $ gradsW w s\n gradW1 = gradW w1 s1\n gradW2 = gradW w2 s2\n newW1 = w1 - (VS.map (*gradStep) $ gradW w1 s1)\n newW2 = w2 - (VS.map (*gradStep) $ gradW w2 s2)\n\nprettyPrintVals :: [Double] -> String\nprettyPrintVals = unwords . map (printf \"%.4f\")\n\n-- Zad. 6 Encoder - Decoder\n\nautoEncTrain = map readPic [ \" \\n ** \\n * \\n * \\n * \"\n , \" ** \\n * \\n * \\n \\n \"\n , \" \\n** \\n * \\n * \\n * \"]\n\ntype EncDec = (MNeuron, MNeuron)\n\nmakeDec (_, MNeuron w _) = MNeuron w acFunc\n\nzeroM inp out = (out> x - 0.5) <$> replicateM (25*26) (randomIO :: IO Double)\n m2 <- map (\\x -> x - 0.5) <$> replicateM (25*17) (randomIO :: IO Double)\n return (MNeuron ((16><26) m1) sig, MNeuron ((25><17) m2) sig)\n\ndecode (_,a) = applyMNeuron a\n\nencode (a,_) = applyMNeuron a\n\nende a = applyMNeuron (makeDec a) . encode a\n\nalfa = 0.8\n\ntrainED trSet = trainHelp 0\n where trainHelp old ed@(MNeuron w f1, MNeuron w' f2) =\n if abs (old - rmse) < 0.000001 then ed\n else trace (\"RMSE = \"++ show rmse) $ trainHelp rmse (MNeuron nW f1, MNeuron nW' f2)\n where nW = w - cmap (*alfa) gradW\n nW' = w'- cmap (*alfa) gradW'\n diffDecode :: Vector Double -> Vector Double\n diffDecode = cmap dsig . (#>) w' . VS.cons 1\n diffEncode = cmap dsig . (#>) w . VS.cons 1\n gradDec x y x'= let dx = (x' - x) * diffDecode y\n in dx `outer` VS.cons 1 y\n gradEnc x y x'= let dx = (x' - x) * diffDecode y\n dy = VS.tail (tr w' #> dx) * diffEncode x\n in dy `outer` VS.cons 1 x\n triples = map (\\x -> (x, encode ed x,decode ed . encode ed $ x )) trSet\n gradsW' = map (\\(x,y,x') -> gradDec x y x') triples\n gradsW = map (\\(x,y,x') -> gradEnc x y x') triples\n rmse = sqrt . VS.foldr (+) 0 . foldr (\\(x,_,x') acc -> (x-x')^2 +acc ) (fromList . replicate 25 $ 0) $ triples\n gradW' = foldr (+) (zeroM 17 25) gradsW'\n gradW = foldr (+) (zeroM 26 16) gradsW\n\n-- Zad 7. Sieci Hopfielda\n\nreadPic2 :: String -> Vector Double\nreadPic2 = VS.fromList . foldr (\\x acc -> case x of\n ' ' -> 0:acc\n '*' -> 1:acc\n '\\n'-> acc) []\n\njedynka :: Vector Double\njedynka = readPic2 \" \\n ** \\n * \\n * \\n * \"\n\nwagi :: Matrix Double\nwagi = cmap (*2) $ (xs `outer` xs) * (cmap ((+1).negate) $ ident 25)\n where xs = cmap (flip (-) 0.5) jedynka\n\nbias :: Vector Double\nbias = cmap (pred.(/2)) (wagi #> fromList (replicate 25 1))\n\niteration :: Vector Double -> Vector Double\niteration = (flip (-) bias).(wagi #>) >>= VS.zipWith (\\u x -> if u > 0 then 1 else if u < 0 then 0 else x)\n\ninp :: Vector Double\ninp = readPic2 \" * \\n * \\n* * \\n *\\n * \"\n\nprocess = process . iteration . (prPrint >>= trace)\n\nrandInp :: IO (Vector Double)\nrandInp = VS.fromList . map (\\x -> if x > 0.5 then 1 else 0) <$> replicateM 25 (randomIO :: IO Double)\n\nzeroV :: Vector Double\nzeroV = readPic2 \" *** \\n * * \\n * * \\n * * \\n *** \"\n\nwagi2 :: Matrix Double\nwagi2 = cmap (*2) (((cx `outer` cx) + (dx `outer` dx)) * (cmap ((+1).negate) $ ident 25))\n where dx = cmap (flip (-) 0.5) zeroV\n cx = cmap (flip (-) 0.5) jedynka\n\nbias2 :: Vector Double\nbias2 = cmap (pred.pred.(/2)) (wagi2 #> fromList (replicate 25 1))\n\niterate2 = (flip (-) bias2).(wagi2 #>) >>= VS.zipWith (\\u x -> if u > 0 then 1 else if u < 0 then 0 else x)\n\ninp2 :: Vector Double\ninp2 = readPic2 \" * \\n * * \\n \\n* * \\n *\"\n\n-- Boltzmann\n\nprob :: Double -> Double -> Double\nprob t x = (1/).(1+).exp.negate $ (x/t)\n\nboltzStep :: Double -> Vector Double -> IO (Vector Double)\nboltzStep temp = VS.mapM (\\x -> randomIO >>= \\y -> if y <= prob temp x then return 1 else return 0).(flip (-) bias).(wagi#>)\n\n--replicateIO :: (a -> IO a) -> a -> IO [a]\n--replicateIO f a = [ a : rest | rest <- replicateIO f nA , nA <- f a ]\n\nannealing :: Double -> Vector Double -> IO ()\nannealing = aSt 0\n\naSt :: Double -> Double -> Vector Double -> IO ()\naSt x inT input = do\n nv <- boltzStep (tann inT x) input\n threadDelay 300000\n putStrLn $ \"Step number: \" ++ show x\n putStrLn $ \"Temperature: \" ++ show (tann inT x)\n putStrLn . prPrint $ input\n aSt (x+1) inT nv\n\nbSt :: Double -> Vector Double -> IO ()\nbSt temp input = do\n nv <- boltzStep temp input\n threadDelay 300000\n putStrLn . prPrint $ input\n bSt temp nv\n\ntann :: Double -> Double -> Double\ntann t = (t/).(1+).log.(1+)\n\n-- TSP\n\nrandomPermutation :: Int -> IO [Int]\nrandomPermutation n = do\n let ps= permutations [0..n-1]\n x = length ps\n r <- randomRIO (0,x-1) :: IO Int\n return $ ps !! r\n\nodleglosci1 = cmap abs (row [1..10] - col [1..10]) - (col (8:replicate 9 0) * row (replicate 9 0 ++ [1])) - (col (replicate 9 0++[8]) * row (1 : replicate 9 0))\n", "meta": {"hexsha": "91bc03ca19fdb852b409e22deac0989d3dabf489", "size": 12618, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "Antystenes/Sieci", "max_stars_repo_head_hexsha": "2c29af4f911aa1c795cb5011d6a4afac724711c4", "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": "Antystenes/Sieci", "max_issues_repo_head_hexsha": "2c29af4f911aa1c795cb5011d6a4afac724711c4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Sieci", "max_forks_repo_head_hexsha": "2c29af4f911aa1c795cb5011d6a4afac724711c4", "max_forks_repo_licenses": ["BSD-3-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.9264705882, "max_line_length": 199, "alphanum_fraction": 0.4944523696, "num_tokens": 4868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.531325045253428}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n-- |\n-- Module : Data.Array.Accelerate.Math.Qtfd\n-- Copyright : [2017] Rinat Stryungis\n-- License : BSD3\n--\n-- Maintainer : Rinat Stryungis \n-- Stability : experimental\n-- Portability : non-portable (GHC extensions)\n--\n-- Computation of quadratic time-frequency distributions using the accelerate-fft library.\n--\n-- This module uses the accelerate-fft library. And the base implementation of fft\n-- uses a naive divide-and-conquer fft implementation\n-- whose absolute performance is appalling. It also requires that you know on\n-- the Haskell side the size of the data being transformed, and that this is\n-- a power-of-two in each dimension.\n--\n-- For performance, compile accelerate-fft against the foreign library bindings (using any\n-- number of '-fllvm-ptx', and '-fllvm-cpu' for the accelerate-llvm-ptx, and\n-- accelerate-llvm-native backends, respectively), which have none of the above\n-- restrictions.\n-- Both of this flags are enabled by default.\n\nmodule Data.Array.Accelerate.Math.Qtfd where\n\nimport Data.Array.Accelerate as A\nimport qualified Data.Array.Accelerate.Data.Complex as ADC\nimport qualified Data.Array.Accelerate.Math.BornJordan as BJ\nimport qualified Data.Array.Accelerate.Math.ChoiWilliams as CW\nimport qualified Data.Array.Accelerate.Math.FFT as AMF\nimport qualified Data.Array.Accelerate.Math.ModifiedB as EMB\nimport qualified Data.Array.Accelerate.Math.PseudoWigner as P\nimport Data.Array.Accelerate.Math.Wigner'\n\nimport Data.Complex\nimport Data.List\nimport Math.Gamma\n-- | Wigner-ville distribution. It takes 1D array of complex floating numbers and returns 2D array of real numbers.\n-- Columns of result array represents time and rows - frequency. Frequency range is from 0 to n/4, where n is a sampling frequency.\n\nwignerVille :: (A.RealFloat e, A.IsFloating e, A.FromIntegral Int e, Elt e, Elt (ADC.Complex e), AMF.Numeric e)\n => Acc (Array DIM1 (ADC.Complex e)) -- ^ Data array\n -> Acc (Array DIM2 e)\nwignerVille arr =\n let times = A.enumFromN (A.index1 leng) 0 :: Acc (Array DIM1 Int)\n leng = A.length arr\n taumx = taumaxs times\n lims = limits taumx\n in A.map ADC.real . A.transpose . AMF.fft AMF.Forward $ createMatrix arr taumx lims\n\nwignerVilleNew :: (A.RealFloat e, A.IsFloating e, A.FromIntegral Int e, Elt e, Elt (ADC.Complex e), AMF.Numeric e)\n => Acc (Array DIM1 (ADC.Complex e)) -- ^ Data array\n -> Acc (Array DIM2 e)\nwignerVilleNew arr =\n let times = A.enumFromN (A.index1 leng) 0 :: Acc (Array DIM1 Int)\n leng = A.length arr\n taumx = taumaxs times\n lims = limits taumx\n in A.map ADC.real . A.transpose . AMF.fft AMF.Forward $ createMatrix arr taumx lims\n\n-- | Pseudo Wigner-ville distribution.\n-- It takes 1D array of complex floating numbers, window and returns 2D array of real numbers.\n-- Columns of result array represents time and rows - frequency. Frequency range is from 0 to n/4, where n is a sampling frequency.\n\npWignerVille :: (A.RealFloat e, A.IsFloating e, A.FromIntegral Int e, Elt e, Elt (ADC.Complex e), AMF.Numeric e)\n => Acc (Array DIM1 e) -- ^ Smoothing window. Length of it must be odd.\n -> Acc (Array DIM1 (ADC.Complex e)) -- ^ Data array\n -> Acc (Array DIM2 e)\npWignerVille window arr =\n let times = A.enumFromN (A.index1 leng) 0 :: Acc (Array DIM1 Int)\n leng = A.length arr\n taumx = P.taumaxs times window\n lims = P.limits taumx\n in A.map ADC.real $ A.transpose $ AMF.fft AMF.Forward $ P.createMatrix arr window taumx lims\n\n-- | Choi-Williams distribution. It takes 1D array of complex floating numbers,\n-- and returns 2D array of real numbers.\n-- Columns of result array represents time and rows - frequency. Frequency range is from 0 to n/4, where n is a sampling frequency.\n\nchoiWilliams :: (A.RealFloat e, A.IsFloating e, A.FromIntegral Int e, Elt e, Elt (ADC.Complex e), AMF.Numeric e)\n => A.Exp e -- ^ sigma\n -> Maybe (Acc (Array DIM1 e), Acc (Array DIM1 e))\n -> A.Exp Int -- ^ Smoothing window over mu, must be odd and symmetrical\n -> A.Exp Int -- ^ Smoothing window over tau, must be odd and symmetrical\n -> Bool -- ^ If normalise\n -> Acc (Array DIM1 (ADC.Complex e)) -- ^ Data array\n -> Acc (Array DIM2 e)\nchoiWilliams sigma mWindowArrays uWindow nWindow normalise arr =\n let times = A.enumFromN (A.index1 leng) 0 :: Acc (Array DIM1 Int)\n leng = A.length arr\n taumx = taumaxs times\n lims = limits taumx\n in A.transpose $ A.map ((*4) . ADC.real) $\n AMF.fft AMF.Forward $\n CW.summedOverMu arr taumx lims sigma mWindowArrays uWindow nWindow normalise\n\nbornJordan :: (A.RealFloat e, A.IsFloating e, A.FromIntegral Int e, Elt e, Elt (ADC.Complex e), AMF.Numeric e)\n => A.Exp e -- ^ sigma\n -> Maybe (Acc (Array DIM1 e), Acc (Array DIM1 e))\n -> A.Exp Int -- ^ Smoothing window over mu, must be odd and symmetrical\n -> A.Exp Int -- ^ Smoothing window over tau, must be odd and symmetrical\n -> Acc (Array DIM1 (ADC.Complex e)) -- ^ Data array\n -> Acc (Array DIM2 e)\nbornJordan sigma mWindowArrays uWindow nWindow arr =\n let times = A.enumFromN (A.index1 leng) 0 :: Acc (Array DIM1 Int)\n leng = A.length arr\n taumx = taumaxs times\n lims = limits taumx\n in A.transpose $ A.map ((*2) . ADC.real) $\n AMF.fft AMF.Forward $\n BJ.summedOverMu arr taumx lims sigma mWindowArrays uWindow nWindow\n\n\neModifiedB :: (A.RealFloat e, A.IsFloating e, A.FromIntegral Int e, Elt e, Elt (ADC.Complex e), AMF.Numeric e)\n => A.Exp e -- ^ alpha\n -> (Acc (Array DIM1 e)) -- ^ gammas\n -> Maybe (Acc (Array DIM1 e), Acc (Array DIM1 e))\n -> A.Exp Int\n -> A.Exp Int\n -> Bool \n -> Acc (Array DIM1 (ADC.Complex e)) -- ^ Data array\n -> Acc (Array DIM2 e)\neModifiedB alpha gammas mWindowArrays uWindow nWindow normalise arr =\n let times = A.enumFromN (A.index1 leng) 0 :: Acc (Array DIM1 Int)\n leng = A.length arr\n taumx = taumaxs times\n lims = limits taumx\n in A.transpose $ A.map (*2) $ A.map ADC.real $ AMF.fft AMF.Forward $ A.transpose $ EMB.summedOverMu arr taumx lims alpha gammas mWindowArrays uWindow nWindow normalise\n\nmakeGammaArray2 :: Double -> Int -> [Double]\nmakeGammaArray2 beta wLength =\n let dwLength = Prelude.fromIntegral wLength :: Double\n v = [(-0.5), ((-0.5) + 1.0/dwLength)..0.5]\n s = Prelude.map (\\x -> beta :+ pi*x) v\n f = Prelude.map (\\x -> abs $ ((magnitude $ gamma x) Prelude.^ 2)/((gamma beta) Prelude.^ 2)) s\n n = Prelude.floor $ (Prelude.fromIntegral $ Prelude.length f)/2.0\n frst = Data.List.take (n-1) f\n secnd = Data.List.drop n f\n in secnd Prelude.++ frst\n", "meta": {"hexsha": "5c5836d7ec3ee16851f407b28dad2b7e94bd1d36", "size": 6814, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Array/Accelerate/Math/Qtfd.hs", "max_stars_repo_name": "Haskell-mouse/wigner-ville-accelerate", "max_stars_repo_head_hexsha": "af2db06f71f054d4b45ba75688b2b725fd179b9c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-10-23T13:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T13:35:33.000Z", "max_issues_repo_path": "src/Data/Array/Accelerate/Math/Qtfd.hs", "max_issues_repo_name": "Haskell-mouse/wigner-ville-accelerate", "max_issues_repo_head_hexsha": "af2db06f71f054d4b45ba75688b2b725fd179b9c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Array/Accelerate/Math/Qtfd.hs", "max_forks_repo_name": "Haskell-mouse/wigner-ville-accelerate", "max_forks_repo_head_hexsha": "af2db06f71f054d4b45ba75688b2b725fd179b9c", "max_forks_repo_licenses": ["BSD-3-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.3262411348, "max_line_length": 169, "alphanum_fraction": 0.6718520693, "num_tokens": 1954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.530305968988951}} {"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule STC.PowerMethodNormalization where\n\nimport Data.Array.Repa as R\nimport Data.Array.Unboxed as AU\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Storable as VS\nimport DFT.Plan\nimport Filter.Utils\nimport Types\nimport Utils.Array\nimport Utils.Parallel\n\ndata PowerMethodNormalizationOption\n = PowerMethodPatchNorm (VS.Vector (Complex Double))\n | PowerMethodGlobal\n | PowerMethodConnection [[(Int, Int)]]\n | PowerMethodConnectionMax [[(Int, Int)]]\n\n-- {-# INLINE makePatchNormFilter #-}\n-- makePatchNormFilter ::\n-- DFTPlan\n-- -> Int\n-- -> Int\n-- -> Bool\n-- -> Int\n-- -> IO (DFTPlan, PowerMethodNormalizationOption)\n-- makePatchNormFilter plan cols rows True n = do\n-- let arr =\n-- makeFilter2D . fromFunction (Z :. cols :. rows) $ \\(Z :. i :. j) ->\n-- if (sqrt . fromIntegral $ (i - div cols 2) ^ 2 + (j - div rows 2) ^ 2) <=\n-- fromIntegral n\n-- then 1\n-- else 0\n-- lock <- getFFTWLock\n-- (p, vec) <-\n-- dft1dGPlan lock plan [cols, rows] [0, 1] . VS.convert . toUnboxed . computeS $\n-- arr\n-- (newPlan, _) <- idft1dGPlan lock p [cols, rows] [0, 1] $ vec\n-- return (newPlan, PowerMethodPatchNorm vec)\n-- makePatchNormFilter plan _ _ False _ = return (plan, PowerMethodGlobal)\n\n-- {-# INLINE patchNorm #-}\n-- patchNorm ::\n-- (R.Source s (Complex Double))\n-- => DFTPlan\n-- -> VS.Vector (Complex Double)\n-- -> R.Array s DIM4 (Complex Double)\n-- -> IO (R.Array U DIM4 (Complex Double))\n-- patchNorm plan filterF arr = do\n-- let (Z :. numThetaFreq :. numScaleFreq :. cols :. rows) = extent arr\n-- arrSum <- (R.sumP . rotate4D . rotate4D . R.map magnitude $ arr) >>= R.sumP\n-- arrSumF <-\n-- dftExecute plan (DFTPlanID DFT1DG [cols, rows] [0, 1]) .\n-- VS.convert . toUnboxed . computeS . R.map (:+ 0) $\n-- arrSum\n-- arrPatchSum <-\n-- fmap (fromUnboxed (Z :. cols :. rows) . VS.convert) .\n-- dftExecute plan (DFTPlanID IDFT1DG [cols, rows] [0, 1]) $\n-- VS.zipWith (*) arrSumF filterF\n-- computeP . R.traverse2 arr arrPatchSum const $ \\f fNorm idx@(Z :. _ :. _ :. i :. j) ->\n-- if fNorm (Z :. i :. j) == 0\n-- then 0\n-- else f idx / fNorm (Z :. i :. j)\n\n-- {-# INLINE powerMethodNormalization #-}\n-- powerMethodNormalization ::\n-- (R.Source s (Complex Double))\n-- => DFTPlan\n-- -> PowerMethodNormalizationOption\n-- -> R.Array s DIM4 (Complex Double)\n-- -> IO (R.Array U DIM4 (Complex Double))\n-- powerMethodNormalization plan (PowerMethodPatchNorm filterF) arr =\n-- patchNorm plan filterF arr\n-- powerMethodNormalization _ PowerMethodGlobal arr = do\n-- s <- R.sumAllP . rotate4D . rotate4D . R.map magnitude $ arr\n-- return . computeS . R.map (/ (s :+ 0)) $ arr\n\n{-# INLINE powerMethodNormalization #-}\npowerMethodNormalization ::\n (R.Source s (Complex Double))\n => PowerMethodNormalizationOption\n -> R.Array s DIM4 (Complex Double)\n -> IO (R.Array U DIM4 (Complex Double))\npowerMethodNormalization PowerMethodGlobal arr = do\n -- s <- R.sumAllP . rotate4D . rotate4D . R.map (\\x -> (magnitude x) ^ 2) $ arr\n s <- R.foldAllP max 0 . rotate4D . rotate4D . R.map (\\x -> magnitude x) $ arr\n return . computeS . R.map (/ (s :+ 0)) $ arr\npowerMethodNormalization (PowerMethodConnection xss) arr = do\n let (Z :. _ :. _ :. cols :. rows) = extent arr\n arrNorm =\n fromListUnboxed (Z :. cols :. rows) . AU.elems $\n (AU.accumArray (+) 0 ((0, 0), (cols - 1, rows - 1)) .\n L.concat .\n parMap\n rdeepseq\n (\\xs ->\n let s =\n L.maximum .\n L.map\n (\\(i, j) ->\n R.foldAllS max 0 .\n R.slice (R.map (\\x -> magnitude x) arr) $\n (Z :. All :. All :. i :. j)) $\n xs\n in L.map\n (\\x ->\n ( x\n , if s == 0\n then 0\n else 1 / s))\n xs) $\n xss :: UArray (Int, Int) Double)\n return . computeS . R.traverse2 arr arrNorm const $ \\f fNorm idx@(Z :. _ :. _ :. i :. j) ->\n f idx * ((fNorm (Z :. i :. j)) :+ 0) \npowerMethodNormalization (PowerMethodConnectionMax xss) arr = do\n let (Z :. numThetaFreq :. numScaleFreq :. cols :. rows) = extent arr\n arrMax =\n fromListUnboxed (Z :. cols :. rows) . AU.elems $\n (AU.accumArray (+) 0 ((0, 0), (cols - 1, rows - 1)) .\n L.concat .\n parMap\n rdeepseq\n (\\xs ->\n let s =\n sqrt .\n L.maximum .\n L.map\n (\\(i, j) ->\n R.sumAllS .\n R.slice (R.map (\\x -> (magnitude x) ^ 2) arr) $\n (Z :. All :. All :. i :. j)) $\n xs\n in L.map (\\x -> (x, s)) xs) $\n xss :: UArray (Int, Int) Double)\n arrSum =\n fromListUnboxed (Z :. cols :. rows) . AU.elems $\n (AU.accumArray (+) 0 ((0, 0), (cols - 1, rows - 1)) .\n L.concat .\n parMap\n rdeepseq\n (\\xs ->\n L.map\n (\\(i, j) ->\n ( (i, j)\n , sqrt .\n R.sumAllS . R.slice (R.map (\\x -> (magnitude x) ^ 2) arr) $\n (Z :. All :. All :. i :. j))) $\n xs) $\n xss :: UArray (Int, Int) Double)\n return . computeS . R.traverse3 arr arrMax arrSum (\\s1 s2 s3 -> s1) $ \\f fMax fSum idx@(Z :. k :. l :. i :. j) ->\n if fSum (Z :. i :. j) > 0.9 * fMax (Z :. i :. j) && k == div numThetaFreq 2 && l == div numScaleFreq 2\n then 1 -- (f idx) / (fSum (Z :. i :. j) :+ 0)\n else 0\n\n", "meta": {"hexsha": "1b4c1f846a0f87ce192e1d5fc642b748961d3b6a", "size": 5953, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/STC/PowerMethodNormalization.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/STC/PowerMethodNormalization.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/STC/PowerMethodNormalization.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.9171974522, "max_line_length": 115, "alphanum_fraction": 0.4965563581, "num_tokens": 1782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5296650125422994}} {"text": "{-# LANGUAGE RecordWildCards, BangPatterns #-}\n\nmodule NeuralNetwork where\n\nimport qualified Statistics.Matrix as M\nimport Control.Monad.Random\n\n\n-- hyperparameters\n\ndata NeuralNetwork =\n NeuralNetwork { inputLayerSize :: Int\n , outputLayerSize :: Int\n , hiddenLayerSize :: Int\n , weight1Matrix :: M.Matrix\n , weight2Matrix :: M.Matrix\n }\n\n\ninitNetwork :: MonadRandom r => Int -> Int -> Int -> r NeuralNetwork\ninitNetwork inputSize outputSize hiddenSize = do\n rs <- getRandomRs (0.0, 1.0)\n rs' <- getRandomRs (0.0, 1.0)\n return $ NeuralNetwork { inputLayerSize = inputSize\n , outputLayerSize = outputSize\n , hiddenLayerSize = hiddenSize\n , weight1Matrix = M.fromList inputSize hiddenSize $ take (inputSize * hiddenSize) rs\n , weight2Matrix = M.fromList hiddenSize outputSize $ take (outputSize * hiddenSize) rs'\n }\n\nforwardRs :: NeuralNetwork -> M.Matrix -> (M.Matrix, M.Matrix, M.Matrix, M.Matrix)\nforwardRs NeuralNetwork{..} matrix =\n let !z2 = matrix * weight1Matrix\n !a2 = M.map sigmoid z2\n !z3 = a2 * weight2Matrix\n in (M.map sigmoid z3, z2, a2, z3)\n\nforward :: NeuralNetwork -> M.Matrix -> M.Matrix\nforward nn matrix =\n let (r, _, _, _) = forwardRs nn matrix\n in r\n\n\nsigmoid :: Double -> Double\nsigmoid z = 1 / (1 + exp (-z))\n\n-- | Derivative of sigmoid function\nsigmoidPrime :: Double -> Double\nsigmoidPrime z = ez / ((1 + ez) ** 2)\n where ez = exp (-z)\n\ncostFunction :: NeuralNetwork -> M.Matrix -> M.Matrix -> Double\ncostFunction nn@NeuralNetwork{..} x y =\n let yHat = nn `forward` x\n err = sum . map (**2) . M.toList $ y - yHat\n in 0.5 * err\n\n\ncostFunctionPrime :: NeuralNetwork -> M.Matrix -> M.Matrix -> (M.Matrix, M.Matrix)\ncostFunctionPrime nn@NeuralNetwork{..} x y = \n let (yHat, z2, a2, z3) = nn `forwardRs` x\n !delta3 = (- (y - yHat)) `pointMultiply` (M.map sigmoidPrime z3)\n !dJdW2 = (M.transpose a2) * delta3\n\n !delta2 = delta3 * (M.transpose weight2Matrix) * (M.map sigmoidPrime z2)\n !dJdW1 = M.transpose x * delta2\n\n in (dJdW1, dJdW2)\n\n\npointMultiply :: M.Matrix -> M.Matrix -> M.Matrix\npointMultiply m1 m2 =\n let (r, c) = (M.rows m1, M.cols m1)\n (l1, l2) = (M.toList m1, M.toList m2)\n in M.fromList r c (foldr (\\(a,b) xs -> (a * b) : xs) [] (zip l1 l2))\n\n\ninstance Num M.Matrix where\n m1 + m2 = let (r, c) = (M.rows m1, M.cols m1)\n (l1, l2) = (M.toList m1, M.toList m2)\n in M.fromList r c (foldr (\\(a,b) xs -> (a + b) : xs) [] (zip l1 l2))\n\n negate m = let (r, c) = (M.rows m, M.cols m)\n l = M.toList m\n in M.fromList r c (map negate l)\n\n m1 * m2 = m1 `M.multiply` m2\n\n abs m = undefined\n signum m = undefined\n fromInteger m = undefined", "meta": {"hexsha": "8d635d89917a39d3cd7363055a4f132cc782b631", "size": 3072, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NeuralNetwork.hs", "max_stars_repo_name": "cirquit/nn-playground", "max_stars_repo_head_hexsha": "53c210fc41d23623bce80eaaaee0259a424bd528", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NeuralNetwork.hs", "max_issues_repo_name": "cirquit/nn-playground", "max_issues_repo_head_hexsha": "53c210fc41d23623bce80eaaaee0259a424bd528", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "cirquit/nn-playground", "max_forks_repo_head_hexsha": "53c210fc41d23623bce80eaaaee0259a424bd528", "max_forks_repo_licenses": ["BSD-3-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.7582417582, "max_line_length": 116, "alphanum_fraction": 0.5511067708, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.5296650087166741}} {"text": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE EmptyCase #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE DefaultSignatures #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n\n-- {-# OPTIONS_GHC -O -ddump-rule-firings #-}\n\n\n-- | Provides the class `ParamSet` which is used to represent the set of\n-- parameters of a particular model. The goal of SGD is then to find the\n-- parameter values which minimize a given objective function.\n\n\nmodule Numeric.SGD.ParamSet\n ( \n -- * Class\n ParamSet(..)\n -- * Generics\n , GPMap\n , GAdd\n , GSub\n , GDiv\n , GMul\n , GNorm2\n ) where\n\n\nimport GHC.Generics\nimport GHC.TypeNats (KnownNat)\n\nimport Prelude hiding (div)\n\nimport qualified Data.Map.Strict as M\n\nimport qualified Numeric.LinearAlgebra.Static as LA\n\n\n-- | Class of types that can be treated as parameter sets. It provides basic\n-- element-wise operations (addition, multiplication, mapping) which are\n-- required to perform stochastic gradient descent. Many of the operations\n-- (`add`, `mul`, `sub`, `div`, etc.) have the same interpretation and follow\n-- the same laws (e.g. associativity) as the corresponding operations in `Num`\n-- and `Fractional`. \n-- \n-- `zero` takes a parameter set as argument and \"zero out\"'s all its elements\n-- (as in the backprop library). This allows instances for `Maybe`, `M.Map`,\n-- etc., where the structure of the parameter set is dynamic. This leads to\n-- the following property:\n--\n-- @add (zero x) x = x@\n--\n-- However, `zero` does not have to obey @(add (zero x) y = y)@.\n--\n-- A `ParamSet` can be also seen as a (structured) vector, hence `pmap` and\n-- `norm_2`. The latter is not strictly necessary to perform SGD, but it is\n-- useful to control the training process.\n--\n-- `pmap` should obey the following law:\n--\n-- @pmap id x = x@\n--\n-- If you leave the body of an instance declaration blank, GHC Generics will be\n-- used to derive instances if the type has a single constructor and each field\n-- is an instance of `ParamSet`.\nclass ParamSet a where\n -- | Element-wise mapping\n pmap :: (Double -> Double) -> a -> a\n\n -- | Zero-out all elements\n zero :: a -> a\n zero = pmap (const 0.0)\n\n-- -- | Element-wise negation\n-- neg :: a -> a\n-- neg = pmap (\\x -> -x)\n\n -- | Element-wise addition\n add :: a -> a -> a\n -- | Elementi-wise substruction\n sub :: a -> a -> a\n\n -- | Element-wise multiplication\n mul :: a -> a -> a\n -- | Element-wise division\n div :: a -> a -> a\n\n -- | L2 norm\n norm_2 :: a -> Double\n\n-- default zero :: (Generic a, GZero (Rep a)) => a -> a\n-- zero = genericZero\n-- {-# INLINE zero #-}\n\n default pmap\n :: (Generic a, GPMap (Rep a))\n => (Double -> Double) -> a -> a\n pmap = genericPMap\n {-# INLINE pmap #-}\n\n\n default add :: (Generic a, GAdd (Rep a)) => a -> a -> a\n add = genericAdd\n {-# INLINE add #-}\n\n default sub :: (Generic a, GSub (Rep a)) => a -> a -> a\n sub = genericSub\n {-# INLINE sub #-}\n\n default mul :: (Generic a, GMul (Rep a)) => a -> a -> a\n mul = genericMul\n {-# INLINE mul #-}\n\n default div :: (Generic a, GDiv (Rep a)) => a -> a -> a\n div = genericDiv\n {-# INLINE div #-}\n\n default norm_2 :: (Generic a, GNorm2 (Rep a)) => a -> Double\n norm_2 = genericNorm2\n {-# INLINE norm_2 #-}\n\n\n{-# RULES\n\"ParamSet pmap/pmap\" forall f g p. pmap f (pmap g p) = pmap (f . g) p\n #-}\n\n\n-- {-# RULES\n-- \"ParamSet pmap/add/pmap\" forall f g p h q. \n-- pmap f (add (pmap g p) (pmap h q))\n-- = add (pmap (f . g) p) (pmap (f . h) q)\n-- #-}\n\n\n-- -- | 'add' using GHC Generics; works if all fields are instances of\n-- -- 'ParamSet', but only for values with single constructors.\n-- genericZero :: (Generic a, GZero (Rep a)) => a -> a\n-- genericZero x = to $ gzero (from x)\n-- {-# INLINE genericZero #-}\n\n\n-- | 'add' using GHC Generics; works if all fields are instances of\n-- 'ParamSet', but only for values with single constructors.\ngenericAdd :: (Generic a, GAdd (Rep a)) => a -> a -> a\ngenericAdd x y = to $ gadd (from x) (from y)\n{-# INLINE genericAdd #-}\n\n\n-- | 'sub' using GHC Generics; works if all fields are instances of\n-- 'ParamSet', but only for values with single constructors.\ngenericSub :: (Generic a, GSub (Rep a)) => a -> a -> a\ngenericSub x y = to $ gsub (from x) (from y)\n{-# INLINE genericSub #-}\n\n\n-- | 'div' using GHC Generics; works if all fields are instances of\n-- 'ParamSet', but only for values with single constructors.\ngenericDiv :: (Generic a, GDiv (Rep a)) => a -> a -> a\ngenericDiv x y = to $ gdiv (from x) (from y)\n{-# INLINE genericDiv #-}\n\n\n-- | 'mul' using GHC Generics; works if all fields are instances of\n-- 'ParamSet', but only for values with single constructors.\ngenericMul :: (Generic a, GMul (Rep a)) => a -> a -> a\ngenericMul x y = to $ gmul (from x) (from y)\n{-# INLINE genericMul #-}\n\n\n-- | 'norm_2' using GHC Generics; works if all fields are instances of\n-- 'ParamSet', but only for values with single constructors.\ngenericNorm2 :: (Generic a, GNorm2 (Rep a)) => a -> Double\ngenericNorm2 x = gnorm_2 (from x)\n{-# INLINE genericNorm2 #-}\n\n\n-- | 'pmap' using GHC Generics; works if all fields are instances of\n-- 'ParamSet', but only for values with single constructors.\ngenericPMap :: (Generic a, GPMap (Rep a)) => (Double -> Double) -> a -> a\ngenericPMap f x = to $ gpmap f (from x)\n{-# INLINE genericPMap #-}\n\n\n--------------------------------------------------\n-- Generics\n--\n-- Partially borrowed from the backprop library\n--------------------------------------------------\n\n\n-- -- | Helper class for automatically deriving 'add' using GHC Generics.\n-- class GZero f where\n-- gzero :: f t -> f t\n-- \n-- instance ParamSet p => GZero (K1 i p) where\n-- gzero (K1 x) = K1 (zero x)\n-- {-# INLINE gzero #-}\n-- \n-- instance (GZero f, GZero g) => GZero (f :*: g) where\n-- gzero (x1 :*: y1) = x2 :*: y2\n-- where\n-- !x2 = gzero x1\n-- !y2 = gzero y1\n-- {-# INLINE gzero #-}\n-- \n-- instance GZero V1 where\n-- gzero = \\case {}\n-- {-# INLINE gzero #-}\n-- \n-- instance GZero U1 where\n-- gzero _ = U1\n-- {-# INLINE gzero #-}\n-- \n-- instance GZero f => GZero (M1 i c f) where\n-- gzero (M1 x) = M1 (gzero x)\n-- {-# INLINE gzero #-}\n-- \n-- -- instance GZero f => GZero (f :.: g) where\n-- -- gzero = Comp1 gzero\n-- -- {-# INLINE gzero #-}\n\n\n-- | Helper class for automatically deriving 'add' using GHC Generics.\nclass GAdd f where\n gadd :: f t -> f t -> f t\n\ninstance ParamSet a => GAdd (K1 i a) where\n gadd (K1 x) (K1 y) = K1 (add x y)\n {-# INLINE gadd #-}\n\ninstance (GAdd f, GAdd g) => GAdd (f :*: g) where\n gadd (x1 :*: y1) (x2 :*: y2) = x3 :*: y3\n where\n !x3 = gadd x1 x2\n !y3 = gadd y1 y2\n {-# INLINE gadd #-}\n\ninstance GAdd V1 where\n gadd = \\case {}\n {-# INLINE gadd #-}\n\ninstance GAdd U1 where\n gadd _ _ = U1\n {-# INLINE gadd #-}\n\ninstance GAdd f => GAdd (M1 i c f) where\n gadd (M1 x) (M1 y) = M1 (gadd x y)\n {-# INLINE gadd #-}\n\n-- instance GAdd f => GAdd (f :.: g) where\n-- gadd (Comp1 x) (Comp1 y) = Comp1 (gadd x y)\n-- {-# INLINE gadd #-}\n\n\n-- | Helper class for automatically deriving 'sub' using GHC Generics.\nclass GSub f where\n gsub :: f t -> f t -> f t\n\ninstance ParamSet a => GSub (K1 i a) where\n gsub (K1 x) (K1 y) = K1 (sub x y)\n {-# INLINE gsub #-}\n\ninstance (GSub f, GSub g) => GSub (f :*: g) where\n gsub (x1 :*: y1) (x2 :*: y2) = x3 :*: y3\n where\n !x3 = gsub x1 x2\n !y3 = gsub y1 y2\n {-# INLINE gsub #-}\n\ninstance GSub V1 where\n gsub = \\case {}\n {-# INLINE gsub #-}\n\ninstance GSub U1 where\n gsub _ _ = U1\n {-# INLINE gsub #-}\n\ninstance GSub f => GSub (M1 i c f) where\n gsub (M1 x) (M1 y) = M1 (gsub x y)\n {-# INLINE gsub #-}\n\n-- instance GSub f => GSub (f :.: g) where\n-- gsub (Comp1 x) (Comp1 y) = Comp1 (gsub x y)\n-- {-# INLINE gsub #-}\n\n\n-- | Helper class for automatically deriving 'mul' using GHC Generics.\nclass GMul f where\n gmul :: f t -> f t -> f t\n\ninstance ParamSet a => GMul (K1 i a) where\n gmul (K1 x) (K1 y) = K1 (mul x y)\n {-# INLINE gmul #-}\n\ninstance (GMul f, GMul g) => GMul (f :*: g) where\n gmul (x1 :*: y1) (x2 :*: y2) = x3 :*: y3\n where\n !x3 = gmul x1 x2\n !y3 = gmul y1 y2\n {-# INLINE gmul #-}\n\ninstance GMul V1 where\n gmul = \\case {}\n {-# INLINE gmul #-}\n\ninstance GMul U1 where\n gmul _ _ = U1\n {-# INLINE gmul #-}\n\ninstance GMul f => GMul (M1 i c f) where\n gmul (M1 x) (M1 y) = M1 (gmul x y)\n {-# INLINE gmul #-}\n\n-- instance GMul f => GMul (f :.: g) where\n-- gmul (Comp1 x) (Comp1 y) = Comp1 (gmul x y)\n-- {-# INLINE gmul #-}\n\n\n-- | Helper class for automatically deriving 'div' using GHC Generics.\nclass GDiv f where\n gdiv :: f t -> f t -> f t\n\ninstance ParamSet a => GDiv (K1 i a) where\n gdiv (K1 x) (K1 y) = K1 (div x y)\n {-# INLINE gdiv #-}\n\ninstance (GDiv f, GDiv g) => GDiv (f :*: g) where\n gdiv (x1 :*: y1) (x2 :*: y2) = x3 :*: y3\n where\n !x3 = gdiv x1 x2\n !y3 = gdiv y1 y2\n {-# INLINE gdiv #-}\n\ninstance GDiv V1 where\n gdiv = \\case {}\n {-# INLINE gdiv #-}\n\ninstance GDiv U1 where\n gdiv _ _ = U1\n {-# INLINE gdiv #-}\n\ninstance GDiv f => GDiv (M1 i c f) where\n gdiv (M1 x) (M1 y) = M1 (gdiv x y)\n {-# INLINE gdiv #-}\n\n-- instance GDiv f => GDiv (f :.: g) where\n-- gdiv (Comp1 x) (Comp1 y) = Comp1 (gdiv x y)\n-- {-# INLINE gdiv #-}\n\n\n-- | Helper class for automatically deriving 'norm_2' using GHC Generics.\nclass GNorm2 f where\n gnorm_2 :: f t -> Double\n\ninstance ParamSet a => GNorm2 (K1 i a) where\n gnorm_2 (K1 x) = norm_2 x\n {-# INLINE gnorm_2 #-}\n\ninstance (GNorm2 f, GNorm2 g) => GNorm2 (f :*: g) where\n gnorm_2 (x1 :*: y1) =\n sqrt ((x2 ^ (2 :: Int)) + (y2 ^ (2 :: Int)))\n where\n !x2 = gnorm_2 x1\n !y2 = gnorm_2 y1\n {-# INLINE gnorm_2 #-}\n\ninstance GNorm2 V1 where\n gnorm_2 = \\case {}\n {-# INLINE gnorm_2 #-}\n\ninstance GNorm2 U1 where\n gnorm_2 _ = 0\n {-# INLINE gnorm_2 #-}\n\ninstance GNorm2 f => GNorm2 (M1 i c f) where\n gnorm_2 (M1 x) = gnorm_2 x\n {-# INLINE gnorm_2 #-}\n\n-- -- TODO: Make sure this makes sense\n-- instance GNorm2 f => GNorm2 (f :.: g) where\n-- gnorm_2 (Comp1 x) = gnorm_2 x\n-- {-# INLINE gnorm_2 #-}\n\n\n-- | Helper class for automatically deriving 'pmap' using GHC Generics.\nclass GPMap f where\n gpmap :: (Double -> Double) -> f t -> f t\n\ninstance ParamSet a => GPMap (K1 i a) where\n gpmap f (K1 x) = K1 (pmap f x)\n {-# INLINE gpmap #-}\n\ninstance (GPMap f, GPMap g) => GPMap (f :*: g) where\n gpmap f (x1 :*: y1) = x2 :*: y2\n where\n !x2 = gpmap f x1\n !y2 = gpmap f y1\n {-# INLINE gpmap #-}\n\ninstance GPMap V1 where\n gpmap _ = \\case {}\n {-# INLINE gpmap #-}\n\ninstance GPMap U1 where\n gpmap _ _ = U1\n {-# INLINE gpmap #-}\n\ninstance GPMap f => GPMap (M1 i c f) where\n gpmap f (M1 x) = M1 (gpmap f x)\n {-# INLINE gpmap #-}\n\n-- instance GPMap f => GPMap (f :.: g) where\n-- gpmap f (Comp1 x) = Comp1 (gpmap f x)\n-- {-# INLINE gpmap #-}\n\n\n--------------------------------------------------\n-- Basic instances\n--------------------------------------------------\n\n\ninstance ParamSet Double where\n zero = const 0\n pmap = id\n add = (+)\n sub = (-)\n mul = (*)\n div = (/)\n norm_2 = abs\n\n\ninstance (ParamSet a, ParamSet b) => ParamSet (a, b) where\n pmap f (x, y) = (pmap f x, pmap f y)\n add (x1, y1) (x2, y2) = (x1 `add` x2, y1 `add` y2)\n sub (x1, y1) (x2, y2) = (x1 `sub` x2, y1 `sub` y2)\n mul (x1, y1) (x2, y2) = (x1 `mul` x2, y1 `mul` y2)\n div (x1, y1) (x2, y2) = (x1 `div` x2, y1 `div` y2)\n norm_2 (x, y)\n = sqrt . sum . map ((^(2::Int)))\n $ [norm_2 x, norm_2 y]\n\n\ninstance (KnownNat n) => ParamSet (LA.R n) where\n zero = const 0\n pmap = LA.dvmap\n add = (+)\n sub = (-)\n mul = (*)\n div = (/)\n norm_2 = LA.norm_2\n\n\ninstance (KnownNat n, KnownNat m) => ParamSet (LA.L n m) where\n zero = const 0\n pmap = LA.dmmap\n add = (+)\n sub = (-)\n mul = (*)\n div = (/)\n norm_2 = LA.norm_2\n\n\n-- | `Nothing` represents a deactivated parameter set component. If `Nothing`\n-- is given as an argument to one of the `ParamSet` operations, the result is\n-- `Nothing` as well.\n--\n-- This differs from the corresponding instance in the backprop library, where\n-- `Nothing` is equivalent to `Just 0`. However, the implementation below\n-- seems to correspond adequately enough to the notion that a particular\n-- component is either active or not in both the parameter set and the\n-- gradient, hence it doesn't make sense to combine `Just` with `Nothing`.\ninstance (ParamSet a) => ParamSet (Maybe a) where\n zero = fmap zero\n pmap = fmap . pmap\n\n add (Just x) (Just y) = Just (add x y)\n add _ _ = Nothing\n\n sub (Just x) (Just y) = Just (sub x y)\n sub _ _ = Nothing\n\n mul (Just x) (Just y) = Just (mul x y)\n mul _ _ = Nothing\n\n div (Just x) (Just y) = Just (div x y)\n div _ _ = Nothing\n\n norm_2 = maybe 0 norm_2\n\n\n-- | A map with different parameter sets (of the same type) assigned to the\n-- individual keys.\n--\n-- When combining two maps with different sets of keys, only their intersection\n-- is preserved.\ninstance (Ord k, ParamSet a) => ParamSet (M.Map k a) where\n zero = fmap zero\n pmap f = fmap (pmap f)\n add = M.intersectionWith add\n sub = M.intersectionWith sub\n mul= M.intersectionWith mul\n div= M.intersectionWith div\n norm_2 = sqrt . sum . map ((^(2::Int)) . norm_2) . M.elems\n", "meta": {"hexsha": "6bce9ca864780ecbfeacd699ddb67f7eb806c796", "size": 13451, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/SGD/ParamSet.hs", "max_stars_repo_name": "kawu/sgd", "max_stars_repo_head_hexsha": "7c44ed771b6fcf485bff32230a81f69115ff9bd4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-04-07T08:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T13:34:10.000Z", "max_issues_repo_path": "src/Numeric/SGD/ParamSet.hs", "max_issues_repo_name": "kawu/sgd", "max_issues_repo_head_hexsha": "7c44ed771b6fcf485bff32230a81f69115ff9bd4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-01-14T08:41:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-14T02:43:24.000Z", "max_forks_repo_path": "src/Numeric/SGD/ParamSet.hs", "max_forks_repo_name": "kawu/sgd", "max_forks_repo_head_hexsha": "7c44ed771b6fcf485bff32230a81f69115ff9bd4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-06T13:40:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:40:06.000Z", "avg_line_length": 26.5830039526, "max_line_length": 79, "alphanum_fraction": 0.5789160657, "num_tokens": 4464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5296212000859837}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE RebindableSyntax #-}\n{-# LANGUAGE TypeSynonymInstances #-}\nmodule DSLsofMath.W06 where\nimport DSLsofMath.FunExp hiding (eval, derive)\nimport DSLsofMath.W05\nimport DSLsofMath.Algebra\nimport Prelude hiding (Num(..),(/),(^),Fractional(..),Floating(..))\nimport Prelude (abs)\nimport Data.Complex ()\n\nevalAll :: Transcendental a => FunExp -> [a -> a]\nevalAll e = (evalFunExp e) : evalAll (derive e)\n\nhelp a b as bs = as * (b : bs) + (a : as) * bs\n\nmulStream :: Ring a => Stream a -> Stream a -> Stream a\nmulStream [] _ = []\nmulStream _ [] = []\nmulStream (a : as) (b : bs) = (a*b) : (as * (b : bs) + (a : as) * bs)\n\ntype Stream a = [a]\ninstance Additive a => Additive (Stream a) where\n zero = repeat zero\n (+) = addStream\ninstance AddGroup a => AddGroup (Stream a) where\n negate = negStream\ninstance Ring a => Multiplicative (Stream a) where\n one = one : zero\n (*) = mulStream\n\naddStream :: Additive a => Stream a -> Stream a -> Stream a\naddStream = zipWithLonger (+)\n\nnegStream :: AddGroup a => Stream a -> Stream a\nnegStream = map negate\n\ntype Taylor a = Stream a\n\ntoMaclaurin :: Ring a => PowerSeries a -> Taylor a\ntoMaclaurin (Poly as) = zipWith (*) as factorials\n\nfromMaclaurin :: Field a => Taylor a -> PowerSeries a\nfromMaclaurin as = Poly (zipWith (/) as factorials)\n\nfactorials :: Ring a => [a]\nfactorials = factorialsFrom 0 1\n\nfactorialsFrom :: Ring a => a -> a -> [a]\nfactorialsFrom n factn = factn : factorialsFrom (n+1) (factn * (n + 1))\n\nex3, ex4 :: (Eq a, Field a) => Taylor a\nex3 = toMaclaurin (x^3 + two * x)\nex4 = toMaclaurin sinx\n\nida a = toMaclaurin (evalP (X :+: Const a))\n\nd f a = take 10 (toMaclaurin (evalP (f (X :+: Const a))))\n\ndP f a = toMaclaurin (f (idx + Poly [a]))\n\nintegT :: a -> Taylor a -> Taylor a\nintegT = (:)\n\ninteg :: Field a => a -> PowerSeries a -> PowerSeries a\ninteg a0 (Poly as) = Poly (integL a0 as)\n\nintegL :: Field a => a -> [a] -> [a]\nintegL c cs = c : zipWith (/) cs oneUp\n\ntype PS a = PowerSeries a\n \nsolve :: Field a => a -> (PS a -> PS a) -> PS a\nsolve f0 g = f -- solves |f' = g f|, |f 0 = f0|\n where f = integ f0 (g f)\n\nidx :: Field a => PS a\nidx = solve 0 (\\_f -> 1) -- \\(f'(x) = 1\\), \\(f(0) = 0\\)\n\nexpx :: Field a => PS a\nexpx = solve 1 (\\f -> f) -- \\(f'(x) = f(x)\\), \\(f(0) = 1\\)\nexpf :: Field a => a -> a\nexpf = evalPS 100 expx\n\ntestExp :: Double\ntestExp = maximum (map diff [0,0.001..1::Double])\n where diff = abs . (expf - exp) -- using the function instance for |exp|\n\ntestExpUnits :: Double\ntestExpUnits = testExp / epsilon\n\nepsilon :: Double -- one bit of |Double| precision\nepsilon = last (takeWhile (\\x -> 1 + x /= 1) (iterate (/2) 1))\n\nsinx, cosx :: Field a => PS a\nsinx = integ 0 cosx\ncosx = integ 1 (-sinx)\n\nsinf, cosf :: Field a => a -> a\nsinf = evalPS 100 sinx\ncosf = evalPS 100 cosx\n\nsx,cx::[Double]\nsx = 0 : 1 : neg 0 : frac (neg 1) 6 : error \"TODO\"\ncx = 1 : neg 0 : frac (neg 1) 2 : 0 : error \"TODO\"\n\ninstance (Eq a, Transcendental a) => Transcendental (PowerSeries a) where\n pi = Poly [pi]\n exp = expPS\n sin = sinPS\n cos = cosPS\n\nexpPS, sinPS, cosPS :: (Eq a, Transcendental a) => PS a -> PS a\nexpPS as = integ (exp (val as)) (expPS as * deriv as)\nsinPS as = integ (sin (val as)) (cosPS as * deriv as)\ncosPS as = integ (cos (val as)) (-sinPS as * deriv as)\n\nval :: Additive a => PS a -> a\nval (Poly (a:_)) = a\nval _ = zero\n\nevalP :: (Eq r, Transcendental r) => FunExp -> PS r\nevalP (Const x) = Poly [fromRational (toRational x)]\nevalP (e1 :+: e2) = evalP e1 + evalP e2\nevalP (e1 :*: e2) = evalP e1 * evalP e2\nevalP X = idx\nevalP (Negate e) = negate (evalP e)\nevalP (Recip e) = recip (evalP e)\nevalP (Exp e) = exp (evalP e)\nevalP (Sin e) = sin (evalP e)\nevalP (Cos e) = cos (evalP e)\n\nevalFunExp :: Transcendental a => FunExp -> a -> a\nevalFunExp (Const alpha) = const (fromRational (toRational alpha))\nevalFunExp X = id\nevalFunExp (e1 :+: e2) = evalFunExp e1 + evalFunExp e2 \nevalFunExp (e1 :*: e2) = evalFunExp e1 * evalFunExp e2 \nevalFunExp (Exp e) = exp (evalFunExp e) \nevalFunExp (Sin e) = sin (evalFunExp e)\nevalFunExp (Cos e) = cos (evalFunExp e)\nevalFunExp (Recip e) = recip (evalFunExp e)\nevalFunExp (Negate e) = negate (evalFunExp e)\n\nderive (Const _) = Const 0\nderive X = Const 1\nderive (e1 :+: e2) = derive e1 :+: derive e2\nderive (e1 :*: e2) = (derive e1 :*: e2) :+: (e1 :*: derive e2)\nderive (Recip e) = let re = Recip e in Negate (re:*:re) :*: derive e\nderive (Negate e) = Negate (derive e)\nderive (Exp e) = Exp e :*: derive e\nderive (Sin e) = Cos e :*: derive e\nderive (Cos e) = Const (-1) :*: Sin e :*: derive e\n\ninstance Additive FunExp where\n (+) = (:+:)\n zero = Const 0\n\ninstance AddGroup FunExp where\n negate x = Const (-1) * x\n\ninstance Multiplicative FunExp where\n (*) = (:*:)\n one = Const 1\n\ninstance MulGroup FunExp where\n recip = Recip\n\ninstance Transcendental FunExp where\n pi = Const pi\n exp = Exp\n sin = Sin\n cos = Cos\n\ninstance Additive a => Additive (a, a) where\n (f, f') + (g, g') = (f + g, f' + g')\n zero = (zero, zero)\n\ninstance AddGroup a => AddGroup (a, a) where\n negate (f, f') = (negate f, negate f')\n\ninstance Ring a => Multiplicative (a,a) where\n (f, f') * (g, g') = (f * g, f' * g + f * g')\n one = (one,zero)\n\ninstance Field a => MulGroup (a, a) where\n (f, f') / (g, g') = (f / g, (f' * g - g' * f) / (g * g))\n\ninstance Transcendental a => Transcendental (a, a) where\n pi = (pi, zero)\n exp (f, f') = (exp f, (exp f) * f')\n sin (f, f') = (sin f, cos f * f')\n cos (f, f') = (cos f, -(sin f) * f')\n\n", "meta": {"hexsha": "9903fe213399e6d08f182f91ef7da63d987979a6", "size": 6084, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "L/06/W06_code.hs", "max_stars_repo_name": "Nexya/DSLsofMath", "max_stars_repo_head_hexsha": "d5d4fc0f79bc1477cef5f3143c78c83a2a12e2df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-24T21:27:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T21:27:31.000Z", "max_issues_repo_path": "L/06/W06_code.hs", "max_issues_repo_name": "Nexya/DSLsofMath", "max_issues_repo_head_hexsha": "d5d4fc0f79bc1477cef5f3143c78c83a2a12e2df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "L/06/W06_code.hs", "max_forks_repo_name": "Nexya/DSLsofMath", "max_forks_repo_head_hexsha": "d5d4fc0f79bc1477cef5f3143c78c83a2a12e2df", "max_forks_repo_licenses": ["BSD-3-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.2, "max_line_length": 78, "alphanum_fraction": 0.553583169, "num_tokens": 2239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.529445621739018}} {"text": "module Numeric.Tensile.Operations.Linear.Internal where\n\nimport Data.Vector.Sized (Vector)\nimport Numeric.Tensile.Dimensions\nimport Numeric.Tensile.Tensor.Internal\nimport Unsafe.Coerce (unsafeCoerce)\n\nimport qualified Data.Finite as F\nimport qualified Data.Vector.Sized as N\nimport qualified Data.Vector.Storable as S\nimport qualified Data.Vector.Storable.Mutable as M\n\n-- import qualified Numeric.LinearAlgebra.HMatrix as Ma\n\n\n\n-- f :: (Dims d' -> Perm n -> Perm n) -> Perm n -> Tensor d e -> Tensor d e'\n-- f dim2Idx perm t = Tensor $ reifySomeDims (permuteDims perm (dims @d)) $ \\p ->\n-- modifyIdx (reflect p) (modify (permuteIdxs (dim2Idx (reflect p) perm) _)) (reflect p)) t -- basically make user derive the Idxs d' -> Idxs d'\n\n-- dim2Idx :: Rank d ~ n => Dims d -> Perm n -> Perm n\n-- takes a perm on dimensions and derives a perm in indices, eg\n-- dim2Idx d p = lowerPerm' ...\n-- --\n-- otherwise consider using the raw index fold and lowerPerm???\n-- could also create : Perm d d'\n\n\n--------------------------------------\n--\n\n\n\ntranspose \n :: Elt e \n => Permutable d d'\n => Dims d -> Perm (Rank d) -> Tensor d e -> Tensor d' e\ntranspose d p (Tensor v) = Tensor v'\n where v' = modifyIdxs d v $ \\i m -> \n remapIdxs p d i $ \\d' i' -> \n M.modify m (const $ v S.! fromIdxs d' (unsafePermute p i)) (fromIdxs d' i')\n\n\n{-\ngen# \n :: forall s t d. PrimBytes t \n => Int# -- ^ number of elements, not checked!\n -- Avoid using this argument if possible.\n -> (s -> (# s, t #))\n -> s -> (# s, ArrayBase t d #)\ngen# n f z0 = go (byteSize @e undefined *# n)\n where\n go bsize = case runRW#\n ( \\s0 -> case newByteArray# bsize s0 of\n (# s1, mba #) -> case loop0 mba 0# z0 s1 of\n (# s2, z1 #) -> case unsafeFreezeByteArray# mba s2 of\n (# s3, ba #) -> (# s3, (# z1, ba #) #)\n ) of (# _, (# z1, ba #) #) -> (# z1, ArrayBase (# | (# 0# , n , ba #) #) #)\n {-# NOINLINE go #-}\n loop0 mba i z s\n | isTrue# (i ==# n) = (# s, z #)\n | otherwise = case f z of\n (# z', x #) -> loop0 mba (i +# 1#) z' (writeArray mba i x s)\n\n3-D tensor `a` w shape=[2, 2, 3]\n[[[ 1, 2, 3],\n [ 4, 5, 6]],\n [[ 7, 8, 9],\n [10, 11, 12]]]\n\n\n3-D tensor `b` w shape=[2, 3, 2]\n[[[13, 14],\n [15, 16],\n [17, 18]],\n [[19, 20],\n [21, 22],\n [23, 24]]]\n )\n\nmul `a` `b` has shape=[2,2,2]\n[[[ 94, 100],\n [229, 244]],\n [[508, 532],\n [697, 730]]]\n-}\n\n\n{-\n\n-- <#\n-- same as tf.matmul\nproductN\n :: forall a b c x. All KnownDim '[a, b, c]\n => KnownDims x\n => T (x +: a +: b) \n -> T (x +: b +: c)\n -> T (x +: a +: c)\nproductN = undefined\n where\n d = dims @x\n --s = unsafeCoerce a\n\nproduct \n :: forall m x y. KnownDim m\n => KnownDims x\n => KnownDims y\n => T (x +: m) -> T (m :+ y) -> T (x ++ y)\nproduct t u\n | I# m <- fromIntegral $ dimVal @m\n , I# n <- fromIntegral $ totalDim' @x\n , I# k <- fromIntegral $ totalDim' @y\n , nk <- n *# k\n = let loop1 i j l r | isTrue# (l ==# m) = r\n | otherwise = loop1 i j (l +# 1#)\n (r + ix# (i +# n *# l) t * ix# (l +# m *# j) u)\n\n loop2 (T# i j) | isTrue# (j ==# k) = (# T# i j, 0 #)\n | isTrue# (i ==# n) = loop2 (T# 0# (j +# 1#))\n | otherwise = (# T# (i +# 1#) j, loop1 i j 0# 0 #)\n in case gen# nk loop2 (T# 0# 0#) of\n (# _, r #) -> r\n\ndata T# = T# Int# Int#\n\n-- mode-i tensor-matrix product\n-- see http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=4A0663C7848627DADDBA6A243BC43E78?doi=10.1.1.130.782&rep=rep1&type=pdf\nproduct\n :: forall m x y. KnownDim m\n => KnownDims x\n => KnownDims y\n => T (x ++ [m] ++ y) \n -> T '[m, n]\n -> T (x ++ n ++ y)\n\n-- #>\nproductR\n :: All KnownDim '[a, b, c]\n => KnownDims x\n => T (a :+ b :+ x)\n -> T (b :+ c :+ x)\n -> T (a :+ c :+ x)\nproductR = undefined\n\n-- <#\n-- same as tf.matmul\nproductN\n :: All KnownDim '[a, b, c]\n => KnownDims x\n => T (x +: a +: b) \n -> T (x +: b +: c)\n -> T (x +: a +: c)\nproductN = undefined\n\n\ntranspose\n :: forall m n x. All KnownDim '[m, n]\n => T '[n, m] --(n :+ m :+ x) \n -> T '[m, n] --(m :+ n :+ x)\ntranspose t = case elemSize0 t of\n 0# -> broadcast (ix# 0# t)\n nm | I# m <- fromIntegral $ dimVal @m\n , I# n <- fromIntegral $ dimVal @n\n -> let f ( I# i, I# j )\n | isTrue# (i ==# m) = f ( 0 , I# (j +# 1#) ) -- skip to next col\n | otherwise = (# ( I# (i +# 1#), I# j ), ix# (i *# n +# j) t #) --col-major indexing\n in case gen# nm f (0,0) of\n (# _, r #) -> r\n\n\n-}\n\n\n", "meta": {"hexsha": "8881ae30d7652843ab1030a7c508e46b4e36ead1", "size": 4587, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tensile/ref/src/Numeric/Tensile/Operations/Linear/Internal.hs", "max_stars_repo_name": "cmk/tensile", "max_stars_repo_head_hexsha": "53c1e46c6b4e7ea8782600875ff3c063a1ce9639", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-25T06:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-15T04:30:24.000Z", "max_issues_repo_path": "tensile/ref/src/Numeric/Tensile/Operations/Linear/Internal.hs", "max_issues_repo_name": "cmk/tensile", "max_issues_repo_head_hexsha": "53c1e46c6b4e7ea8782600875ff3c063a1ce9639", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tensile/ref/src/Numeric/Tensile/Operations/Linear/Internal.hs", "max_forks_repo_name": "cmk/tensile", "max_forks_repo_head_hexsha": "53c1e46c6b4e7ea8782600875ff3c063a1ce9639", "max_forks_repo_licenses": ["BSD-3-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.3620689655, "max_line_length": 146, "alphanum_fraction": 0.4931327665, "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5294393009344519}} {"text": "module Numeric.LinearAlgebra.Matrix.Mat44 where\n\nimport Numeric.LinearAlgebra.Matrix.Class\nimport Numeric.LinearAlgebra.Matrix.Mat33 ( det33 )\n\nimport Data.List ( foldl1' )\nimport Data.NumInstances() -- Add function instances to Num\n\ndata Mat44 a = Mat44\n { m00 :: !a, m01 :: !a, m02 :: !a, m03 :: !a\n , m10 :: !a, m11 :: !a, m12 :: !a, m13 :: !a\n , m20 :: !a, m21 :: !a, m22 :: !a, m23 :: !a\n , m30 :: !a, m31 :: !a, m32 :: !a, m33 :: !a\n }\n deriving (Read, Show, Eq, Ord)\n\ninstance Matrix Mat44 where\n {-# INLINE mDim #-}\n mDim _ = 4\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 0 3 = m03 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 1 3 = m13 m\n mElement m 2 0 = m20 m\n mElement m 2 1 = m21 m\n mElement m 2 2 = m22 m\n mElement m 2 3 = m23 m\n mElement m 3 0 = m30 m\n mElement m 3 1 = m31 m\n mElement m 3 2 = m32 m\n mElement m 3 3 = m33 m\n mElement _ i j = error (\"Index \" ++ show i ++ \", \" ++ show j ++ \": out of range, must be 0,0 to 3,3\")\n {-# INLINE mZip #-}\n mZip f m n = Mat44 (f (m00 m) (m00 n)) (f (m01 m) (m01 n)) (f (m02 m) (m02 n)) (f (m03 m) (m03 n))\n (f (m10 m) (m10 n)) (f (m11 m) (m11 n)) (f (m12 m) (m12 n)) (f (m13 m) (m13 n))\n (f (m20 m) (m20 n)) (f (m21 m) (m21 n)) (f (m22 m) (m22 n)) (f (m23 m) (m23 n))\n (f (m30 m) (m30 n)) (f (m31 m) (m31 n)) (f (m32 m) (m32 n)) (f (m33 m) (m33 n))\n {-# INLINE mFold #-}\n mFold f m = foldl1' f [ mElement m i j | i <- [ 0 .. 3 ], j <- [ 0 .. 3 ] ]\n {-# INLINE mIndexOf #-}\n mIndexOf p m = fst (foldl1' p' [ ((i,j), mElement m i j) | j <- [ 3, 2 .. 0 ], i <- [ 3, 2 .. 0 ] ])\n where\n p' x@(_, a) y@(_, a') | a `p` a' = x\n | otherwise = y\n {-# INLINE det #-}\n det = det44\n\ninstance Functor Mat44 where\n {-# INLINE fmap #-}\n fmap f m = Mat44 (f (m00 m)) (f (m01 m)) (f (m02 m)) (f (m03 m))\n (f (m10 m)) (f (m11 m)) (f (m12 m)) (f (m13 m))\n (f (m20 m)) (f (m21 m)) (f (m22 m)) (f (m23 m))\n (f (m30 m)) (f (m31 m)) (f (m32 m)) (f (m33 m))\n\n{-# SPECIALIZE det44 :: Mat44 Double -> Double #-}\n{-# SPECIALIZE det44 :: Mat44 Float -> Float #-}\ndet44 :: Num a => Mat44 a -> a\ndet44 = m00 * det33 m11 m12 m13\n m21 m22 m23\n m31 m32 m33\n - m01 * det33 m10 m12 m13\n m20 m22 m23\n m30 m32 m33\n + m02 * det33 m10 m11 m13\n m20 m21 m23\n m30 m31 m33\n - m03 * det33 m10 m11 m12\n m20 m21 m22\n m30 m31 m32\n\n{-# SPECIALIZE inv44 :: Mat44 Double -> Mat44 Double #-}\n{-# SPECIALIZE inv44 :: Mat44 Float -> Mat44 Float #-}\ninv44 :: Fractional a => Mat44 a -> Mat44 a\ninv44 m = mApply m' m\n where\n d = const $ det44 m\n m' = Mat44 (det33 m11 m12 m13\n m21 m22 m23\n m31 m32 m33 / d)\n (-(det33 m01 m02 m03\n m21 m22 m23\n m31 m32 m33 / d))\n (det33 m01 m02 m03\n m11 m12 m13\n m31 m32 m33 / d)\n (-(det33 m01 m02 m03\n m11 m12 m13\n m21 m22 m23 / d))\n \n (-(det33 m10 m12 m13\n m20 m22 m23\n m30 m32 m33 / d))\n (det33 m00 m02 m03\n m20 m22 m23\n m30 m32 m33 / d)\n (-(det33 m00 m02 m03\n m10 m12 m13\n m30 m32 m33 / d))\n (det33 m00 m02 m03\n m10 m12 m13\n m20 m22 m23 / d)\n\n (det33 m10 m11 m13\n m20 m21 m23\n m30 m31 m33 / d)\n (-(det33 m00 m01 m03\n m20 m21 m23\n m30 m31 m33 / d))\n (det33 m00 m01 m03\n m10 m11 m13\n m30 m31 m33 / d)\n (-(det33 m00 m01 m03\n m10 m11 m13\n m20 m21 m23 / d))\n\n (-(det33 m10 m11 m12\n m20 m21 m22\n m30 m31 m32 / d))\n (det33 m00 m01 m02\n m20 m21 m22\n m30 m31 m32 / d)\n (-(det33 m00 m01 m02\n m10 m11 m12\n m30 m31 m32 / d))\n (det33 m00 m01 m02\n m10 m11 m12\n m20 m21 m22 / d)\n", "meta": {"hexsha": "ae1b1224056c881ab10abd7199f8bf9776db187e", "size": 4550, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/Matrix/Mat44.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/Mat44.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/Mat44.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": 34.2105263158, "max_line_length": 103, "alphanum_fraction": 0.4296703297, "num_tokens": 1648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5292038359718396}} {"text": "module Numbers where\n\nimport Control.Monad.Except (throwError)\nimport Data.Complex\nimport Data.Ratio\nimport DataTypes\n (Arity(..), LispError(..), LispVal(..), PrimitiveFunc, ThrowsError)\n\nnumPrimitives :: [(String, PrimitiveFunc)]\nnumPrimitives =\n [ (\"+\", numAdd)\n , (\"-\", numSub)\n , (\"*\", numMul)\n , (\"/\", numDiv)\n , (\"modulo\", numMod)\n , (\"Integer?\", isNumber)\n , (\"complex?\", isComplex)\n , (\"real?\", isReal)\n , (\"rational?\", isRational)\n , (\"integer?\", isInteger)\n , (\"=\", numBoolBinopEq)\n , (\"/=\", numBoolBinopNeq)\n , (\">\", numBoolBinopGt)\n , (\"<\", numBoolBinopLt)\n , (\">=\", numBoolBinopGte)\n , (\"<=\", numBoolBinopLte)\n , (\"quotient\", numQuotient)\n , (\"remainder\", numRem)\n , (\"sin\", numSine)\n , (\"cos\", numCos)\n ]\n\nfoldlM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a\nfoldlM f v (x:xs) = (f v x) >>= \\a -> foldlM f a xs\nfoldlM _ v [] = return v\n\nfoldl1M :: Monad m => (a -> a -> m a) -> [a] -> m a\nfoldl1M f (x:xs) = foldlM f x xs\nfoldl1M _ _ = error \"Unexpected error in foldl1M\"\n\nnumAdd :: PrimitiveFunc\nnumAdd [] = return $ Integer 0\nnumAdd a = foldlM (\\b c -> doAdd =<< (numCast [b, c])) (Integer 0) a\n where\n doAdd :: LispVal -> ThrowsError LispVal\n doAdd (List [Integer c, Integer d]) = return $ Integer (c + d)\n doAdd (List [Rational c, Rational d]) = return $ Rational (c + d)\n doAdd (List [Float c, Float d]) = return $ Float (c + d)\n doAdd (List [Complex c, Complex d]) = return $ Complex (c + d)\n doAdd _ = throwError $ Default \"Unexpected error in +\"\n\nnumSub :: PrimitiveFunc\nnumSub [] = throwError $ NumArgs (Min 1) 0 []\nnumSub a = foldl1M (\\b c -> doSub =<< (numCast [b, c])) a -- TODO zero args check\n where\n doSub :: LispVal -> ThrowsError LispVal\n doSub (List [Integer c, Integer d]) = return $ Integer (c - d)\n doSub (List [Rational c, Rational d]) = return $ Rational (c - d)\n doSub (List [Float c, Float d]) = return $ Float (c - d)\n doSub (List [Complex c, Complex d]) = return $ Complex (c - d)\n doSub _ = throwError $ Default \"Unexpected error in -\"\n\nnumMul :: PrimitiveFunc\nnumMul [] = return $ Integer 1\nnumMul a = foldl1M (\\b c -> doMul =<< (numCast [b, c])) a\n where\n doMul :: LispVal -> ThrowsError LispVal\n doMul (List [Integer c, Integer d]) = return $ Integer (c * d)\n doMul (List [Rational c, Rational d]) = return $ Rational (c * d)\n doMul (List [Float c, Float d]) = return $ Float (c * d)\n doMul (List [Complex c, Complex d]) = return $ Complex (c * d)\n doMul _ = throwError $ Default \"Unexpected error in -\"\n\nnumDiv :: PrimitiveFunc\nnumDiv [] = throwError $ NumArgs (Min 1) 0 []\nnumDiv a = foldl1M (\\b c -> doDiv =<< (numCast [b, c])) a -- TODO: Zero division error\n where\n doDiv :: LispVal -> ThrowsError LispVal\n doDiv (List [Integer c, Integer d]) =\n if d == 0\n then throwError $ Default \"Zero division error\"\n else return $ Rational (c % d)\n doDiv (List [Rational c, Rational d]) =\n if d == 0\n then throwError $ Default \"Zero division error\"\n else return $ Rational (c / d)\n doDiv (List [Float c, Float d]) =\n if d == 0.0\n then throwError $ Default \"Zero division error\"\n else return $ Float (c / d)\n doDiv (List [Complex c, Complex d]) =\n if d == 0\n then throwError $ Default \"Zero division error\"\n else return $ Complex (c / d)\n doDiv _ = throwError $ Default \"Unexpected error in /\"\n\nnumMod :: PrimitiveFunc\nnumMod [] = throwError $ NumArgs (MinMax 2 2) 0 []\nnumMod (a:[]) = throwError $ NumArgs (MinMax 2 2) 1 [a]\nnumMod [a, b] = do\n c <- numCast $ [a, b]\n doMod c\n where\n doMod :: LispVal -> ThrowsError LispVal\n doMod (List [Integer c, Integer d]) = return $ Integer (c `mod` d)\n doMod (List [c@(Rational _), d@(Rational _)]) = do\n Integer c' <- numToInt c\n Integer d' <- numToInt d\n return $ Rational ((c' `mod` d') % 1)\n doMod (List [c@(Float _), d@(Float _)]) = do\n Integer c' <- numToInt c\n Integer d' <- numToInt d\n return $ Float (fromInteger (c' `mod` d'))\n doMod (List [c@(Complex _), d@(Complex _)]) = do\n Integer c' <- numToInt c\n Integer d' <- numToInt d\n return $ Complex (fromInteger (c' `mod` d') :+ 0)\n doMod _ = throwError $ Default \"Unexpected error in modulo\"\nnumMod a = throwError $ NumArgs (MinMax 2 2) (length a) a\n\nnumRem :: PrimitiveFunc\nnumRem [] = throwError $ NumArgs (MinMax 2 2) 0 []\nnumRem (a:[]) = throwError $ NumArgs (MinMax 2 2) 1 [a]\nnumRem [a, b] = do\n c <- numCast $ [a, b]\n doRem c\n where\n doRem :: LispVal -> ThrowsError LispVal\n doRem (List [Integer c, Integer d]) = return $ Integer (c `rem` d)\n doRem (List [c@(Rational _), d@(Rational _)]) = do\n Integer c' <- numToInt c\n Integer d' <- numToInt d\n return $ Rational ((c' `rem` d') % 1)\n doRem (List [c@(Float _), d@(Float _)]) = do\n Integer c' <- numToInt c\n Integer d' <- numToInt d\n return $ Float (fromInteger (c' `rem` d'))\n doRem (List [c@(Complex _), d@(Complex _)]) = do\n Integer c' <- numToInt c\n Integer d' <- numToInt d\n return $ Complex (fromInteger (c' `rem` d') :+ 0)\n doRem _ = throwError $ Default \"Unexpected error in remainder\"\nnumRem a = throwError $ NumArgs (MinMax 2 2) (length a) a\n\nisInteger :: PrimitiveFunc\nisInteger [Integer _] = return $ Bool True\nisInteger [_] = return $ Bool False\nisInteger a = throwError $ NumArgs (MinMax 1 1) (length a) a\n\nisRational :: PrimitiveFunc\nisRational [Rational _] = return $ Bool True\nisRational a = isInteger a\n\nisReal :: PrimitiveFunc\nisReal [Float _] = return $ Bool True\nisReal a = isRational a\n\nisComplex :: PrimitiveFunc\nisComplex [Complex _] = return $ Bool True\nisComplex a = isReal a\n\nisNumber :: PrimitiveFunc\nisNumber = isComplex\n\nnumToInt :: LispVal -> ThrowsError LispVal\nnumToInt a@(Integer _) = return a\nnumToInt (Rational a) =\n if denominator a == 1\n then return $ Integer (numerator a)\n else throwError $ Default \"Could not convert rational to integer\"\nnumToInt (Float a) =\n if a == fromInteger (round a)\n then return $ Integer (round a)\n else throwError $ Default \"Could not convert float to integer\"\nnumToInt (Complex a) =\n let rp = realPart a\n in if imagPart a == 0 && rp == fromInteger (round rp)\n then return $ Integer (round rp)\n else throwError $ Default \"Could not convert complex to integer\"\nnumToInt _ = throwError $ Default \"Could not convert non-number to integer\"\n\nnumCast :: [LispVal] -> ThrowsError LispVal\nnumCast [a@(Integer _), b@(Integer _)] = return $ List [a, b]\nnumCast [a@(Rational _), b@(Rational _)] = return $ List [a, b]\nnumCast [a@(Float _), b@(Float _)] = return $ List [a, b]\nnumCast [a@(Complex _), b@(Complex _)] = return $ List [a, b]\n-- Integer\nnumCast [(Integer a), b@(Rational _)] = return $ List [Rational (a % 1), b]\nnumCast [(Integer a), b@(Float _)] = return $ List [Float (fromInteger a), b]\nnumCast [(Integer a), b@(Complex _)] =\n return $ List [Complex (fromInteger a :+ 0), b]\n-- Rational\nnumCast [a@(Rational _), (Integer b)] = return $ List [a, Rational (b % 1)]\nnumCast [(Rational a), b@(Float _)] = return $ List [Float (fromRational a), b]\nnumCast [(Rational a), b@(Complex _)] =\n return $ List [Complex (fromRational a :+ 0), b]\n-- Float\nnumCast [a@(Float _), (Rational b)] = return $ List [a, Float (fromRational b)]\nnumCast [a@(Float _), (Integer b)] = return $ List [a, Float (fromInteger b)]\nnumCast [(Float a), b@(Complex _)] = return $ List [Complex (a :+ 0), b]\n-- Complex\nnumCast [a@(Complex _), (Rational b)] =\n return $ List [a, Complex (fromRational b :+ 0)]\nnumCast [a@(Complex _), (Float b)] = return $ List [a, Complex (b :+ 0)]\nnumCast [a@(Complex _), (Integer b)] =\n return $ List [a, Complex (fromInteger b :+ 0)]\nnumCast [a, b] =\n case a of\n Integer _ -> doThrowError b\n Float _ -> doThrowError b\n Rational _ -> doThrowError b\n Complex _ -> doThrowError b\n _ -> doThrowError a\n where\n doThrowError :: LispVal -> ThrowsError LispVal\n doThrowError num = throwError $ TypeMismatch \"Integer\" num\nnumCast _ = throwError $ Default \"Unexpected error in numCast\"\n\nnumBoolBinop ::\n String\n -> (LispVal -> LispVal -> ThrowsError LispVal)\n -> LispVal\n -> [LispVal]\n -> ThrowsError LispVal\nnumBoolBinop name' op b (c:d) = do\n List [b', c'] <- numCast [b, c]\n result <- op b' c'\n case result of\n Bool True -> numBoolBinop name' op c' d\n Bool False -> return $ Bool False\n _ -> throwError $ Default $ \"Unexpected error in \" ++ name'\nnumBoolBinop _ _ _ _ = return $ Bool True\n\nnumBoolBinopEq :: [LispVal] -> ThrowsError LispVal\nnumBoolBinopEq [] = throwError $ NumArgs (Min 1) 0 []\nnumBoolBinopEq (x:xs) = numBoolBinop \"=\" fn x xs\n where\n fn :: LispVal -> LispVal -> ThrowsError LispVal\n fn (Integer c) (Integer d) = return $ Bool (c == d)\n fn (Rational c) (Rational d) = return $ Bool (c == d)\n fn (Float c) (Float d) = return $ Bool (c == d)\n fn (Complex c) (Complex d) = return $ Bool (c == d)\n fn _ _ = throwError $ Default \"Unexpected error in =\"\n\nnumBoolBinopNeq :: [LispVal] -> ThrowsError LispVal\nnumBoolBinopNeq [] = throwError $ NumArgs (Min 1) 0 []\nnumBoolBinopNeq (x:xs) = numBoolBinop \"/=\" fn x xs\n where\n fn :: LispVal -> LispVal -> ThrowsError LispVal\n fn (Integer c) (Integer d) = return $ Bool (c /= d)\n fn (Rational c) (Rational d) = return $ Bool (c /= d)\n fn (Float c) (Float d) = return $ Bool (c /= d)\n fn (Complex c) (Complex d) = return $ Bool (c /= d)\n fn _ _ = throwError $ Default \"Unexpected error in /=\"\n\nnumBoolBinopLt :: [LispVal] -> ThrowsError LispVal\nnumBoolBinopLt [] = throwError $ NumArgs (Min 1) 0 []\nnumBoolBinopLt (x:xs) = numBoolBinop \"<\" fn x xs\n where\n fn :: LispVal -> LispVal -> ThrowsError LispVal\n fn (Integer c) (Integer d) = return $ Bool (c < d)\n fn (Rational c) (Rational d) = return $ Bool (c < d)\n fn (Float c) (Float d) = return $ Bool (c < d)\n fn (Complex _) (Complex _) =\n throwError $ Default \"< not defined for complex numbers\"\n fn _ _ = throwError $ Default \"Unexpected error in <\"\n\nnumBoolBinopLte :: [LispVal] -> ThrowsError LispVal\nnumBoolBinopLte [] = throwError $ NumArgs (Min 1) 0 []\nnumBoolBinopLte (x:xs) = numBoolBinop \"<=\" fn x xs\n where\n fn :: LispVal -> LispVal -> ThrowsError LispVal\n fn (Integer c) (Integer d) = return $ Bool (c <= d)\n fn (Rational c) (Rational d) = return $ Bool (c <= d)\n fn (Float c) (Float d) = return $ Bool (c <= d)\n fn (Complex _) (Complex _) =\n throwError $ Default \"<= not defined for complex numbers\"\n fn _ _ = throwError $ Default \"Unexpected error in <=\"\n\nnumBoolBinopGt :: [LispVal] -> ThrowsError LispVal\nnumBoolBinopGt [] = throwError $ NumArgs (Min 1) 0 []\nnumBoolBinopGt (x:xs) = numBoolBinop \">\" fn x xs\n where\n fn :: LispVal -> LispVal -> ThrowsError LispVal\n fn (Integer c) (Integer d) = return $ Bool (c > d)\n fn (Rational c) (Rational d) = return $ Bool (c > d)\n fn (Float c) (Float d) = return $ Bool (c > d)\n fn (Complex _) (Complex _) =\n throwError $ Default \"> not defined for complex numbers\"\n fn _ _ = throwError $ Default \"Unexpected error in >\"\n\nnumBoolBinopGte :: [LispVal] -> ThrowsError LispVal\nnumBoolBinopGte [] = throwError $ NumArgs (Min 1) 0 []\nnumBoolBinopGte (x:xs) = numBoolBinop \">=\" fn x xs\n where\n fn :: LispVal -> LispVal -> ThrowsError LispVal\n fn (Integer c) (Integer d) = return $ Bool (c >= d)\n fn (Rational c) (Rational d) = return $ Bool (c >= d)\n fn (Float c) (Float d) = return $ Bool (c >= d)\n fn (Complex _) (Complex _) =\n throwError $ Default \">= not defined for complex numbers\"\n fn _ _ = throwError $ Default \"Unexpected error in >=\"\n\nnumQuotient :: PrimitiveFunc\nnumQuotient args =\n if length args /= 2\n then throwError $ NumArgs (MinMax 2 2) (length args) args\n else do\n nums <- numCast args\n case nums of\n List [Integer a, Integer b] -> return $ Integer (a `quot` b)\n _ -> throwError $ Default \"Unexpected error in <=\" -- TODO better errors\n\nunaryTrig ::\n (Double -> Double) -> (Double -> Double -> Complex Double) -> PrimitiveFunc\nunaryTrig op complexOp args =\n if length args /= 1\n then throwError $ NumArgs (MinMax 1 1) (length args) args\n else case args of\n [Integer a] -> return $ Float (op $ fromInteger a)\n [Rational a] -> return $ Float (op $ fromRational a)\n [Float a] -> return $ Float (op a)\n [Complex a] -> return $ Complex $ complexOp (realPart a) (imagPart a)\n _ -> throwError $ Default \"Numerical input expected\"\n\nnumSine :: PrimitiveFunc\nnumSine = unaryTrig sin (\\r i -> ((sin r) * (cosh i)) :+ ((cos r) * (sinh i)))\n\nnumCos :: PrimitiveFunc\nnumCos =\n unaryTrig cos (\\r i -> ((cos r) * (cosh i)) :+ (-1 * ((sin r) * (sinh i))))\n", "meta": {"hexsha": "deca09a230d1bb2feffe8456e2df088fe9834064", "size": 12785, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numbers.hs", "max_stars_repo_name": "ebenpack/hascheme", "max_stars_repo_head_hexsha": "a56a2236d4c005283ebb94703fe19d418f2c07d4", "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/Numbers.hs", "max_issues_repo_name": "ebenpack/hascheme", "max_issues_repo_head_hexsha": "a56a2236d4c005283ebb94703fe19d418f2c07d4", "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/Numbers.hs", "max_forks_repo_name": "ebenpack/hascheme", "max_forks_repo_head_hexsha": "a56a2236d4c005283ebb94703fe19d418f2c07d4", "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.5090361446, "max_line_length": 86, "alphanum_fraction": 0.6183026985, "num_tokens": 4053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5290298957688815}} {"text": "module HollowPinwheel where\n\nimport Control.Monad as M\nimport qualified Data.Array.Accelerate as A\nimport Data.Array.Accelerate.LLVM.PTX\nimport Data.Array.IArray as IA\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Storable as VS\nimport Data.Vector.Unboxed as VU\nimport FokkerPlanck.FourierSeries\nimport FokkerPlanck.GreensFunction\nimport FokkerPlanck.Histogram\nimport Foreign.CUDA.Driver as CUDA\nimport FourierMethod.BlockMatrixAcc\nimport FourierMethod.FourierSeries2D\nimport Image.IO\nimport Pinwheel.FourierSeries2D\nimport STC\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Text.Printf\nimport Utils.Array\nimport Utils.List\nimport Utils.Time\nimport Graphics.Rendering.Chart.Easy\nimport Utils.Parallel\nimport Graphics.Rendering.Chart.Backend.Cairo\nimport Utils.SimpsonRule\n\nmain = do\n args@(deviceIDsStr:numPointsStr:numR2FreqStr:periodR2Str:phiFreqsStr:rhoFreqsStr:thetaFreqsStr:scaleFreqsStr:stdStr:radiusStr:sStr:idxStr:numBatchStr:aStr:bStr:deltaStr:radialFreqStr:numThreadStr:_) <-\n getArgs\n let deviceIDs = read deviceIDsStr :: [Int]\n numPoints = read numPointsStr :: Int\n numR2Freq = read numR2FreqStr :: Int\n periodR2 = read periodR2Str :: Double\n phiFreq = read phiFreqsStr :: Int\n phiFreqs = L.map fromIntegral [-phiFreq .. phiFreq]\n rhoFreq = read rhoFreqsStr :: Int\n rhoFreqs = L.map fromIntegral [-rhoFreq .. rhoFreq]\n thetaFreq = read thetaFreqsStr :: Int\n thetaFreqs = L.map fromIntegral [-thetaFreq .. thetaFreq]\n scaleFreq = read scaleFreqsStr :: Int\n scaleFreqs = L.map fromIntegral [-scaleFreq .. scaleFreq]\n std = read stdStr :: Double\n radius = read radiusStr :: Double\n s = read sStr :: Double\n idx = read idxStr :: (Int, Int)\n numBatch = read numBatchStr :: Int\n numThread = read numThreadStr :: Int\n folderPath = \"output/test/HollowPinwheel\"\n createDirectoryIfMissing True folderPath\n initialise []\n devs <- M.mapM device deviceIDs\n ctxs <- M.mapM (\\dev -> CUDA.create dev []) devs\n ptxs <- M.mapM createTargetFromContext ctxs\n let harmonicsArray' =\n pinwheelFourierCoefficientsAnatical\n numR2Freq\n phiFreq\n rhoFreq\n thetaFreq\n scaleFreq\n (-s)\n periodR2\n (periodR2 * sqrt 2)\n hpf = idealLowPassFilter radius periodR2 numR2Freq\n hpfMat =\n A.use .\n A.fromList (A.Z A.:. (numR2Freq ^ 2) A.:. (1 :: Int)) . VS.toList $\n hpf\n plotImageRepaComplex (folderPath \"Filter_Coef.png\") .\n ImageRepa 8 .\n fromUnboxed (Z :. (1 :: Int) :. numR2Freq :. numR2Freq) . VS.convert $\n hpf\n plan <-\n makePlan\n folderPath\n emptyPlan\n numPoints\n numPoints\n numR2Freq\n (2 * thetaFreq + 1)\n (2 * scaleFreq + 1)\n harmonicsArray <- convolveFrequency plan numR2Freq hpf harmonicsArray'\n -- let harmonicsArray = centerHollow numR2Freq harmonicsArray'\n let pinwheelMat =\n A.use .\n A.fromList (A.Z A.:. (numR2Freq ^ 2) A.:. (1 :: Int)) . VS.toList $\n (harmonicsArray' IA.! idx)\n pinwheelHPMat =\n A.use .\n A.fromList (A.Z A.:. (numR2Freq ^ 2) A.:. (1 :: Int)) . VS.toList $\n (harmonicsArray IA.! idx)\n plotImageRepaComplex (folderPath \"FilteredPinhweel_Coef.png\") .\n ImageRepa 8 .\n fromUnboxed (Z :. (1 :: Int) :. numR2Freq :. numR2Freq) . VS.convert $\n (harmonicsArray IA.! idx)\n pinwheelR2 <-\n computeFourierSeriesR2StreamAcc\n ptxs\n numR2Freq\n numPoints\n 1\n periodR2\n 1\n numBatch\n pinwheelMat\n pinwheelHPR2 <-\n computeFourierSeriesR2StreamAcc\n ptxs\n numR2Freq\n numPoints\n 1\n periodR2\n 1\n numBatch\n pinwheelHPMat\n hpfR2' <-\n computeFourierSeriesR2StreamAcc\n ptxs\n numR2Freq\n numPoints\n 1\n periodR2\n 1\n numBatch\n hpfMat\n plotImageRepaComplex (folderPath \"Pinwheel.png\") .\n ImageRepa 8 .\n computeS . extend (Z :. (1 :: Int) :. All :. All) . sumS . rotate3D $\n pinwheelR2\n printf\n \"pinwheel center: %f\\n\"\n (magnitude $\n (pinwheelR2 R.!\n (Z :. (0 :: Int) :. (div numPoints 2) :. (div numPoints 2 - 1))))\n plotImageRepaComplex (folderPath \"Pinwheel_HighPass.png\") .\n ImageRepa 8 .\n computeS . extend (Z :. (1 :: Int) :. All :. All) . sumS . rotate3D $\n pinwheelHPR2\n printf\n \"lowpassed pinwheel center: %f\\n\"\n (magnitude $\n (pinwheelHPR2 R.!\n (Z :. (0 :: Int) :. (div numPoints 2) :. (div numPoints 2 - 1))))\n plotImageRepaComplex (folderPath \"Pinwheel_Coef.png\") .\n ImageRepa 8 .\n fromUnboxed (Z :. (1 :: Int) :. numR2Freq :. numR2Freq) . VS.convert $\n (harmonicsArray' IA.! idx)\n printf\n \"filter center: %f\\n\"\n (magnitude $\n (hpfR2' R.! (Z :. (0 :: Int) :. (div numPoints 2) :. (div numPoints 2 - 1))))\n plotImageRepaComplex (folderPath \"HighPass.png\") .\n ImageRepa 8 .\n computeS . extend (Z :. (1 :: Int) :. All :. All) . sumS . rotate3D $\n hpfR2'\n plotImageRepaComplex (folderPath \"PinwheelHollow.png\") .\n ImageRepa 8 .\n computeS .\n extend (Z :. (1 :: Int) :. All :. All) .\n sumS . rotate3D . R.zipWith (-) pinwheelR2 $\n pinwheelHPR2\n", "meta": {"hexsha": "aa6959b0cea016e91fadffecd6ce95d30c79a9aa", "size": 5625, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/HollowPinwheel/HollowPinwheel.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/HollowPinwheel/HollowPinwheel.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/HollowPinwheel/HollowPinwheel.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.4821428571, "max_line_length": 203, "alphanum_fraction": 0.6071111111, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5290298916884717}} {"text": "\n{-# OPTIONS_GHC -Wall #-}\n{-# LANGUAGE CPP #-}\n\n{-|\n\n Module : AutoBench.Internal.Regression\n Description : Generating and fitting models for regression analysis.\n Copyright : (c) 2018 Martin Handley\n License : BSD-style\n Maintainer : martin.handley@nottingham.ac.uk\n Stability : Experimental\n Portability : GHC\n\n This module is responsible for generating and fitting regression models.\n See 'LinearType', 'LinearCandidate' and 'LinearFit' for more details.\n\n The system uses ridge regression because it has a closed-form solution so \n is fast. Previously used LASSO implemented using the HVX library but \n it was too computationally expensive, (see bottom of this file).\n\n-}\n\n{-\n ----------------------------------------------------------------------------\n :\n ----------------------------------------------------------------------------\n - Too much white space;\n -\n-}\n\nmodule AutoBench.Internal.Regression\n (\n\n -- * Candidate generation \n generateLinearCandidate -- Generate a 'LinearCandidate' from a 'LinearType' by filling \n -- in the details of the model necessary to fit it to a given dataset. \n -- * Regression analysis \n , fitOLS -- Given a data set (a list of xy-'Coord's) and a 'LinearCandidate', \n -- fit the model to the data using the OLS method.\n , fitRidgeRegress -- Given a data set (a list of xy-'Coord's) and a 'LinearCandidate', \n -- fit the model to the data using ridge regression.\n\n ) where \n\nimport Data.List (minimumBy, nub)\nimport Data.Ord (comparing)\nimport qualified Data.Vector.Storable as V\n\nimport Numeric.LinearAlgebra\n ( Element\n , Matrix\n , Vector\n , (<>)\n , (<\\>)\n , (#>)\n , asColumn\n , cmap\n , diag\n , dot\n , fromColumns\n , fromRows\n , konst\n , norm_2\n , norm_Inf\n , qr\n , rows\n , scale\n , subVector\n , sumElements\n , takeRows\n , toColumns\n , tr'\n , vjoin\n )\n\nimport qualified AutoBench.Internal.Expr as E\nimport AutoBench.Internal.Types \n ( Coord\n , Exp\n , LinearCandidate(..) \n , LinearType(..)\n , numPredictors \n )\n\n#ifdef MIN_VERSION_base\n#if MIN_VERSION_base(4,11,0)\nimport Prelude hiding ((<>))\n#endif\n#endif\n\n-- * 'LinearCandidate' generation\n\n-- | Generate a 'LinearCandidate' from a 'LinearType' by filling in the \n-- details of the model necessary to fit it to a given dataset. \n-- Makes use of the generation helper functions 'generateLinearCandidateExpr'\n-- and 'generateLinearCandidateYHat'.\ngenerateLinearCandidate :: LinearType -> LinearCandidate\ngenerateLinearCandidate t@(Poly _) = \n LinearCandidate \n { \n _lct = t\n , _fxs = id\n , _fex = generateLinearCandidateExpr t\n , _fyhat = generateLinearCandidateYHat t\n }\ngenerateLinearCandidate t@(Log b _) =\n LinearCandidate \n { \n _lct = t\n , _fxs = cmap $ logBase (fromIntegral b)\n , _fex = generateLinearCandidateExpr t\n , _fyhat = generateLinearCandidateYHat t \n }\ngenerateLinearCandidate t@(PolyLog b _) =\n LinearCandidate \n { \n _lct = t\n , _fxs = cmap (\\x -> x * logBase (fromIntegral b) x)\n , _fex = generateLinearCandidateExpr t\n , _fyhat = generateLinearCandidateYHat t \n }\ngenerateLinearCandidate t@(Exp n) =\n LinearCandidate \n { \n _lct = t\n , _fxs = cmap (flip (**) $ fromIntegral n)\n , _fex = generateLinearCandidateExpr t\n , _fyhat = generateLinearCandidateYHat t \n }\n\n-- * Linear fitting\n\n-- | Given a data set (a list of xy-'Coord's) and a 'LinearCandidate',\n-- fit the model to the data using the ordinary least squares (OLS) method. The \n-- result is the model's coefficients.\nfitOLS :: [Coord] -> LinearCandidate -> Vector Double\nfitOLS coords c = head $ toColumns $ (_preds <\\> _resps)\n where (_preds, _resps) = genFitMatrices coords c\n \n-- | Given a data set (a list of xy-'Coord's) and a 'LinearCandidate',\n-- fit the model to the data using ridge regression. The result is the model's\n-- coefficients.\nfitRidgeRegress :: [Coord] -> LinearCandidate -> Vector Double\nfitRidgeRegress coords c =\n -- Select the lambda that minimises mean squared error.\n fst $ minimumBy (comparing snd) $ zip fits errs\n where \n n = length coords\n (xs, ys) = unzip coords \n vXs = V.fromList xs\n vYs = V.fromList ys\n -- Fitting error is mean squared error.\n calcMse m vec = ((norm_2 $ V.zipWith (-) vYs vec) ** 2.0) / fromIntegral m\n -- Generate the matrices to solve.\n (_preds, _resps) = genFitMatrices coords c\n ---------------------------------------------------------------------------\n --------------------------------------------------------------------------- \n -- Using ridge regression with maximum tuning parameter:\n -- https://stats.stackexchange.com/questions/289075/what-is-the-\n -- smallest-lambda-that-gives-a-0-component-in-lasso?noredirect=1&lq=1\n ---------------------------------------------------------------------------\n maxLam = (1.0 / fromIntegral n) * norm_Inf (tr' _preds <> _resps)\n -- Minimise 'mse' to select best tuning parameter.\n lamStep = maxLam / 10\n lamRange = [lamStep, 2 * lamStep .. maxLam]\n fits = nub $ fmap (head \n . toColumns \n . ridgeRegress _preds _resps\n ) lamRange\n -- ** Do not use vFxs here, use vXs ** \n errs = fmap (calcMse n . flip (_fyhat c) vXs) fits \n --------------------------------------------------------------------------- \n --------------------------------------------------------------------------- \n -- Closed form solution of ridge regression.\n -- https://github.com/chris-taylor/aima-haskell/blob/master/src/AI/\n -- Learning/LinearRegression.hs\n ---------------------------------------------------------------------------\n ridgeRegress\n :: Matrix Double -- X\n -> Matrix Double -- Y\n -> Double -- λ\n -> Matrix Double -- (X'X + λI)^−1 X'Y.\n ridgeRegress x y lambda = \n let m = rows x\n (_, r) = qr x\n rr = takeRows m r\n ww = diag $ vjoin [0, konst 1 (m - 1)]\n in (tr' rr <> rr + (lambda `scale` ww)) <\\> (tr' x <> y)\n\n-- * Helpers\n\n-- | Generate an expression ('Exp') for a 'LinearCandidate' that will allow\n-- its model's equation to be pretty printed at a later time. Important note: \n-- the vectors are assumed to be of the correct form, /no/ checking is \n-- performed currently.\ngenerateLinearCandidateExpr \n :: LinearType -- Model.\n -> Vector Double -- Coefficients of the model.\n -> Exp -- Model's equation as an expression for pretty printing.\n--\n-- Given coefficients: \n--\n-- a_0, a_1, ..., a_n \n-- \n-- Generate:\n--\n-- a_0 + a_1 * x^1 + a_2 * x^2 + ... + a_n * x^n \n--\ngenerateLinearCandidateExpr (Poly n) coeffs = \n foldr1 E.Add . take (n + 1) $ zipWith ($) terms (V.toList coeffs)\n where terms = E.Num -- a_0\n : ( \\a_k -> E.Mul (E.Num a_k) (E.Var \"x\") -- a_1 * x\n ) \n : fmap ( \\p a_k -> E.Mul (E.Num a_k) -- a_k * x^k, k > 1\n (E.Pow (E.Var \"x\") \n (E.Num p)\n )\n ) [2.0..] \n--\n-- Given coefficients: \n-- \n-- a_0, a_1, ..., a_n\n--\n-- Generate: \n-- \n-- a_0 + a_1 * log_b^1(x) + a_2 * log_b^2(x) + ... + a_n * log_b^n(x)\n--\ngenerateLinearCandidateExpr (Log b n) coeffs = \n foldr1 E.Add $ take (n + 1) $ zipWith ($) terms (V.toList coeffs)\n where terms = E.Num -- a_0\n : ( \\a_k -> E.Mul (E.Num a_k) -- a_1 * log_b(x)\n (E.Log (E.Num $ fromIntegral b) \n (E.Var \"x\")\n )\n ) \n : fmap ( \\p a_k -> E.Mul (E.Num a_k) -- a_k * log_b^k(x), k > 1\n (E.Pow (E.Log (E.Num $ fromIntegral b) \n (E.Var \"x\")\n )\n (E.Num p)\n )\n ) [2.0..]\n--\n-- Given coefficients: \n-- \n-- a_0, a_1, ..., a_n\n--\n-- Generate:\n-- \n-- a_0 + a_1 * x^1 * log_b^1(x) + a_2 * x^2 * log_b^2(x) + ... + a_n * x^n * log_b^n(x) \n--\ngenerateLinearCandidateExpr (PolyLog b n) coeffs = \n foldr1 E.Add $ take (n + 1) $ zipWith ($) terms (V.toList coeffs)\n where terms = E.Num -- a_0\n : ( \\a_k -> E.Mul (E.Num a_k) -- a_1 * x * log_b(x)\n (E.Mul (E.Var \"x\") \n (E.Log (E.Num $ fromIntegral b) \n (E.Var \"x\")\n )\n )\n )\n : fmap ( \\p a_k -> E.Mul (E.Num a_k) -- a_k * x^k * log_b^k(x), k > 1\n (E.Mul (E.Pow (E.Var \"x\") \n (E.Num p)\n )\n (E.Pow (E.Log (E.Num $ fromIntegral b) \n (E.Var \"x\")\n )\n (E.Num p)\n )\n )\n ) [2.0..]\n--\n-- Given coefficients: \n-- \n-- a_0, a_1\n--\n-- Generate:\n-- \n-- a_0 + a_1 * n^x \n--\ngenerateLinearCandidateExpr (Exp n) coeffs = \n foldr1 E.Add $ zipWith ($) terms (V.toList coeffs)\n where terms = [ E.Num -- a_0\n , \\a_1 -> E.Mul (E.Num a_1) -- a_1 *\n (E.Pow (E.Num $ fromIntegral n) -- n^x\n (E.Var \"x\")\n ) \n ]\n\n-- | For a given set of x-coordinates, generate the y-coordinates that are \n-- predicted by the model of a 'LinearCandidate'. Important note: the vectors \n-- are assumed to be of the correct form, /no/ checking is performed currently.\ngenerateLinearCandidateYHat \n :: LinearType\n -> Vector Double -- Coefficients of the model.\n -> Vector Double -- x-coordinates.\n -> Vector Double -- Predicted y-coordinates.\n--\n-- Given coefficients and x-coords:\n--\n-- a_0, a_1, ..., a_n x_0, x_1, ..., x_m\n-- \n-- For each x_i, generate: \n--\n-- a_0 + a_1 * x_i^1 + a_2 * x_i^2 + ... + a_n * x_i^n \n--\ngenerateLinearCandidateYHat (Poly n) coeffs xs =\n (fromColumns $ V.fromList (replicate m 1.0) : xs') #> coeffs\n where \n m = V.length xs\n xs' = zipWith vecPow [1.0..] (replicate n xs)\n--\n-- Given coefficients and x-coords: \n-- \n-- a_0, a_1, ..., a_n x_0, x_1, ..., x_m\n-- \n-- For each x_i, generate: \n-- \n-- a_0 + a_1 * log_b^1(x_i) + a_2 * log_b^2(x_i) + ... + a_n * log_b^n(x_i)\n--\ngenerateLinearCandidateYHat (Log b n) coeffs xs =\n (fromColumns $ V.fromList (replicate m 1.0) : xs') #> coeffs\n where\n m = V.length xs\n xs' = zipWith (vecLogPow $ fromIntegral b) [1.0..] (replicate n xs) \n--\n-- Given coefficients and x-coords: \n-- \n-- a_0, a_1, .., a_n x_0, x_1, ..., x_m\n--\n-- For each x_i, generate:\n-- \n-- a_0 + a_1 * x_i^1 * log_b^1(x_i) + a_2 * x_i^2 * log_b^2(x_i) + ... + a_n * x_i^n * log_b^n(x_i) \n--\ngenerateLinearCandidateYHat (PolyLog b n) coeffs xs =\n (fromColumns $ V.fromList (replicate m 1.0) : xs') #> coeffs\n where\n m = V.length xs\n xs' = zipWith (vecPolyLogPow $ fromIntegral b) [1.0..] (replicate n xs)\n--\n-- Given coefficients and x-coords: \n-- \n-- a_0, a_1 x_0, x_1, ..., x_m\n--\n-- For each x_i, generate:\n-- \n-- a_0 + a_1 * n^x_i \n-- \ngenerateLinearCandidateYHat (Exp n) coeffs xs =\n (fromColumns $ V.fromList (replicate m 1.0) : xs') #> coeffs\n where\n m = V.length xs\n xs' = zipWith (vecBasePow $ fromIntegral n) [1.0..] (replicate 1 xs) \n\n-- | Constructs predictor (@preds@) and responder (@resps@) matrices so that \n-- regression equations can be solved in their matrix form.\ngenFitMatrices :: [Coord] -> LinearCandidate -> (Matrix Double, Matrix Double)\ngenFitMatrices coords c = gen (numPredictors (_lct c) - 1) \n where \n\n gen :: Int -> (Matrix Double, Matrix Double)\n gen k = let\n _xPows = xPows k\n _xSumPows = xSumPows _xPows\n _ySums = ySums _xPows k\n _preds = preds _xSumPows k\n _resps = resps _ySums \n in (_preds, asColumn _resps)\n\n ---------------------------------------------------------------------------\n --\n --\n (xs, ys) = unzip coords\n -- Transform the x-coords using the candidate's 'fxs' function. This allows \n -- us to fit different models to the data in a generic way. For example, a \n -- 'Log b n' candidate will first take 'LogBase b' of the x-coords. We can \n -- then use (a variant of) linear least squares to fit a straight line \n -- through the resulting data points. Although this is a straight line on \n -- the /resulting data/, it corresponds to a logarithmic function on the\n -- /initial/ data. This technique is standard. \n vFxs = (_fxs c) (V.fromList xs)\n vYs = V.fromList ys\n -- Number of data points.\n n = length coords\n -- As the x-'Coords' have been transformed by the candidate's 'fxs'\n -- function, this method works generically for any model and 'k' \n -- coefficients.\n ---------------------------------------------------------------------------\n --\n -- Helper functions to construct the matrices to solve using linear \n -- regression. Note: these functions are to be used in a particular way so \n -- their names reflect their use.\n --\n -- x_i^j for j = 1, 2, .., 2 * k\n xPows :: Int -> [Vector Double]\n xPows k = zipWith vecPow [1.0..] (replicate (2 * k) vFxs)\n -- SUM x_i^j for j = 1, 2, .., 2 * k\n xSumPows :: [Vector Double] -> [Double]\n xSumPows = fmap sumElements\n -- SUM y_i, SUM x_i * y_i, SUM x_i^2 * y_i, .., SUM x_i^j * y_i\n ySums :: [Vector Double] -> Int -> [Double]\n ySums vs k = zipWith dot (V.fromList (replicate n 1.0) : vs) (replicate (k + 1) vYs)\n --\n -- Convert xSumPows into a matrix by 'chunking' off rows from the initial vector.\n --\n -- Rows are length k + 1, the initial rows are:\n -- \n -- n , SUM x_i , SUM x_i^2, .., SUM x_i^k\n -- \n -- SUM x_i, SUM x_i^2, SUM x_i^3, .., SUM x_i^(k + 1)\n --\n -- The last row is:\n --\n -- SUM x_i^j, SUM x_i^(j + 1), .., SUM x_i^(2 * k)\n -- \n -- These values are the /predictors/.\n --\n preds :: [Double] -> Int -> Matrix Double\n preds ds k = vecToMatrix (V.fromList $ fromIntegral n : ds) (k + 1)\n -- 'ySums' are the /responders/.\n resps :: [Double] -> Vector Double\n resps = V.fromList\n\n\n-- | Raise each double in a vector of doubles to a given power.\nvecPow :: Double -> Vector Double -> Vector Double\nvecPow pow = cmap (** pow)\n\n-- | For each double 'x' in a vector of doubles, apply the following \n-- calculation:\n--\n-- > \\x -> base ** (x * pow)\n--\n-- for a given 'base' and 'pow'.\nvecBasePow :: Double -> Double -> Vector Double -> Vector Double\nvecBasePow base pow = cmap (\\x -> base ** (x * pow))\n\n-- | For each double 'x' in a vector of doubles, apply the following \n-- calculation:\n--\n-- > \\x -> (x ** pow) * (logBase b x ** pow)\n--\n-- for a given 'b' and 'pow'.\nvecPolyLogPow :: Double -> Double -> Vector Double -> Vector Double \nvecPolyLogPow b pow = cmap (\\x -> (x ** pow) * ((logBase b x) ** pow))\n\n-- | For each double 'x' in a vector of doubles, apply the following \n-- calculation:\n--\n-- > \\x -> logBase b x ** pow\n--\n-- for a given 'b' and 'pow'.\nvecLogPow :: Double -> Double -> Vector Double -> Vector Double \nvecLogPow b pow = cmap (\\x -> (logBase b x) ** pow)\n\n-- | Create a matrix by 'chunking' off rows of a given length from a vector.\n-- Works similarly to 'tails'.\nvecToMatrix :: (V.Storable a, Element a) => Vector a -> Int -> Matrix a\nvecToMatrix v j = fromRows [ subVector i j v | i <- [0..j - 1] ]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{- \n\nLASSO has been retired for the time being due to computational expense.\n\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE DataKinds #-}\n\nimport HVX.Internal.Constraints ((<=~))\nimport HVX.Primitives ((+~), (*~), neg, norm, quadform)\nimport HVX.Internal.Solvers (ellipsoidMinimize)\nimport qualified HVX.Internal.Primitives as HVX\n\n\n-- ** LASSO (Least Absolute Shrinkage and Selection Operator)\n\n\nfitLASSO :: [Coord] -> LinearCandidate -> Vector Double\nfitLASSO coords c =\n -- Select the lambda that minimises mean squared error.\n fst $ minimumBy (comparing snd) $ zip fits errs\n where \n n = length coords\n (xs, ys) = unzip coords \n vXs = V.fromList xs\n vYs = V.fromList ys\n -- Fitting error is mean squared error.\n calcMse m vec = ((norm_2 $ V.zipWith (-) vYs vec) ** 2.0) / fromIntegral m\n -- Generate the matrices to solve.\n (_preds, _resps) = genFitMatrices coords c\n ---------------------------------------------------------------------------\n --------------------------------------------------------------------------- \n initCoeffs = _preds <\\> _resps \n maxT = V.sum $ cmap abs $ flatten initCoeffs\n -- Minimise 'mse' to select best tuning parameter.\n tStep = maxT / 10\n tRange = [0 + tStep, 0 + (2 * tStep) .. maxT]\n fits = filter (all (\\m -> not (isNaN m || isInfinite m)) . V.toList) \n . nub \n $ fmap (head \n . toColumns \n . lassoRegress _preds _resps\n ) tRange\n -- ** Do not use vFxs here, use vXs ** \n errs = fmap (calcMse n . flip (fyhat c) vXs) fits\n ---------------------------------------------------------------------------\n --------------------------------------------------------------------------- \n -- LASSO regression (convex equation using the subgradient method in HVX).\n lassoRegress \n :: Matrix Double -- ^ n >< n matrix X.\n -> Matrix Double -- ^ n >< 1 matrix Y.\n -> Double -- ^ Constraint on sum of coefficients.\n -> Matrix Double -- ^ Optimal variable values.\n lassoRegress x y t = snd . head $ res\n where \n (res, _, _) = ellipsoidMinimize expr [constr] [(\"a\", m)] 1e-20 (2 * maxT)\n m = rows x \n constr = norm 1 (HVX.EVar \"a\") <=~ (HVX.EConst $ konst t (1, 1))\n expr = quadform (HVX.EConst $ ident m) $ ((HVX.EConst y) +~ neg (HVX.EConst x *~ HVX.EVar \"a\"))\n\n-}", "meta": {"hexsha": "a9f3bae7aca91a3a6678a391597904d2521465dd", "size": 19197, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AutoBench/Internal/Regression.hs", "max_stars_repo_name": "recursion-ninja/AutoBench", "max_stars_repo_head_hexsha": "15b7da6fb39e01a5dd542e91fe4d9859f03acc0f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-18T15:14:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-18T15:14:24.000Z", "max_issues_repo_path": "src/AutoBench/Internal/Regression.hs", "max_issues_repo_name": "recursion-ninja/AutoBench", "max_issues_repo_head_hexsha": "15b7da6fb39e01a5dd542e91fe4d9859f03acc0f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AutoBench/Internal/Regression.hs", "max_forks_repo_name": "recursion-ninja/AutoBench", "max_forks_repo_head_hexsha": "15b7da6fb39e01a5dd542e91fe4d9859f03acc0f", "max_forks_repo_licenses": ["BSD-3-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.4188191882, "max_line_length": 105, "alphanum_fraction": 0.5070063031, "num_tokens": 5182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5290298876080617}} {"text": "module Main where\n\nimport RayLib\nimport Numeric.LinearAlgebra\nimport qualified Graphics.Image as G\n\nmain :: IO ()\nmain = do let screen = Screen 256 256\n let ka = MatParam (fromList [0,1,1])\n let ks = MatParam (fromList [1,1,0])\n let kd = MatParam (fromList [0.4,0.4,0])\n let ke = MatParam (fromList [0,0,0])\n let kr = MatParam (fromList [0,0,0])\n let kt = MatParam (fromList [0,0,0])\n let shininess = 64\n let material = Material ka ks kd ke kr kt shininess\n let sphere1 = Sphere (fromList [0,0,0]) 1.5 material\n let scene = Scene [] [sphere1] (fromList [1,0,0.1])\n putStrLn . show $ scene\n let camera = Camera (fromList [0,0,-4]) (fromList [0,0,1]) (fromList [0,1,0]) 1 90\n putStrLn . show $ camera\n putStrLn . show $ screen\n let image = traceImage scene screen camera\n let toWrite = render image\n G.writeImage \"test.png\" toWrite\n", "meta": {"hexsha": "9ebdc09671a7785afa498ae28520a3e70f242c08", "size": 983, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "0AdityaD/raytracer", "max_stars_repo_head_hexsha": "dbfb66062814f2665a4907d237e97b980171f08d", "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": "0AdityaD/raytracer", "max_issues_repo_head_hexsha": "dbfb66062814f2665a4907d237e97b980171f08d", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "0AdityaD/raytracer", "max_forks_repo_head_hexsha": "dbfb66062814f2665a4907d237e97b980171f08d", "max_forks_repo_licenses": ["BSD-3-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.8076923077, "max_line_length": 92, "alphanum_fraction": 0.5808748728, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.52864415682877}} {"text": "{-# LANGUAGE OverloadedStrings, ExistentialQuantification, FlexibleContexts #-}\n\nmodule BNN where\n\nimport System.Random.MWC (createSystemRandom)\n\n--import Data.Aeson (ToJSON(toJSON), Value)\n--import Data.Aeson (encode)\nimport qualified Data.ByteString.Lazy.Char8 as BL\n\nimport Data.List (sort, partition)\nimport qualified Data.Histogram as DH\nimport qualified Data.Histogram.Fill as DF\nimport qualified Data.Histogram.Bin.Bin2D as Bin2D\nimport Data.Vector.Unboxed.Base (Unbox)\nimport qualified Data.Vector.Unboxed as Vec\n\nimport Control.Monad (liftM2, replicateM, forM, forM_)\nimport Control.Monad.IO.Class (liftIO)\nimport Control.Monad.Bayes.Class\nimport Control.Monad.Bayes.Sampler\nimport Control.Monad.Bayes.Traced\nimport Control.Monad.Bayes.Weighted\nimport Control.Monad.Bayes.Inference.SMC as SMC\nimport Control.Monad.Bayes.Inference.RMSMC as RMSMC\nimport Control.Monad.Bayes.Sequential\nimport Control.Monad.Bayes.Population\nimport Control.Monad.Bayes.Traced.Static (Traced)\nimport Numeric.LinearAlgebra (Matrix, Vector, toList, vector, matrix, dot, (#>), (!), cmap, scalar, size)\n\nimport Numeric.Log\n\n-- Plotting\n\nhisto2D :: (Foldable f, Unbox val, Num val) =>\n (Double, Int, Double)\n -> (Double, Int, Double)\n -> f (Double, Double)\n -> DH.Histogram (Bin2D.Bin2D DH.BinD DH.BinD) val\nhisto2D (xmin, xn, xmax) (ymin, yn, ymax) = DF.fillBuilder buildr\n where\n binX = DH.binD xmin xn xmax\n binY = DH.binD ymin yn ymax\n bins = Bin2D.Bin2D binX binY\n buildr = DF.mkSimple bins\n \nhisto :: (Foldable v, Unbox a, Num a) =>\n (Double, Int, Double)\n -> v Double\n -> DH.Histogram DF.BinD a\nhisto (xmin, n, xmax) = DF.fillBuilder buildr\n where\n bins = DH.binD xmin n xmax\n buildr = DF.mkSimple bins\n\n-- A SIMPLE NEURAL NETWORK\n-- Model Setup\n\ndata NN\n = NN\n { biass :: Vector Double,\n weights :: Vector Double,\n sigma :: Double\n }\n deriving (Eq, Show)\n\ndata Data\n = Data\n { xValue :: Double,\n yValue :: Double\n }\n deriving (Eq, Show)\n\nforwardNN :: NN -> Double -> Double\nforwardNN (NN bs ws _) x =\n ws `dot` cmap activation (scalar x - bs)\n where activation x = if x < 0 then 0 else 1\n\nerrorModel :: Double -> Double -> Double -> Log Double\nerrorModel mean std = normalPdf mean std\n\nlikelihood :: NN -> Data -> Log Double \nlikelihood nn (Data xObs yObs) =\n errorModel yMean ySigma yObs\n where\n ySigma = sigma nn\n yMean = forwardNN nn xObs\n\n-- Prior, Posterior and Predictive Distribution\n\npostNN :: MonadInfer m => m NN -> [Data] -> m NN\npostNN pr obs = do\n nn <- pr\n forM_ obs (score . likelihood nn)\n return nn\n\nuniformVec :: MonadSample m => (Double, Double) -> Int -> m (Vector Double)\nuniformVec (wmin, wmax) nelements =\n vector <$> replicateM nelements (uniform wmin wmax)\n\npriorNN :: MonadSample m => Int -> m NN\npriorNN nnodes = do\n bias <- uniformVec (0, 10) nnodes\n weight <- uniformVec (-10, 10) nnodes\n sigma <- uniform 0.5 1.5\n return $ NN bias weight sigma\n\npredDist :: MonadInfer m => m NN -> m (NN, Data)\npredDist pr = do\n nn <- pr\n x <- uniform 0 10\n y <- uniform (-5) 10\n score $ likelihood nn (Data x y)\n return (nn, Data x y)\n ", "meta": {"hexsha": "c7ad0554c3b6d05e0dedf315cc0c0622f1145b5d", "size": 3168, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/BNN.hs", "max_stars_repo_name": "leduin/Bayesian-Neural-Network", "max_stars_repo_head_hexsha": "841d684fc50d71719695fb76a11096f786867728", "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/BNN.hs", "max_issues_repo_name": "leduin/Bayesian-Neural-Network", "max_issues_repo_head_hexsha": "841d684fc50d71719695fb76a11096f786867728", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BNN.hs", "max_forks_repo_name": "leduin/Bayesian-Neural-Network", "max_forks_repo_head_hexsha": "841d684fc50d71719695fb76a11096f786867728", "max_forks_repo_licenses": ["BSD-3-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.547826087, "max_line_length": 105, "alphanum_fraction": 0.6875, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5286429986516815}} {"text": "module AI.Learning.Bootstrap where\n\nimport Control.Monad.Random\nimport Foreign.Storable (Storable)\nimport Numeric.LinearAlgebra\nimport qualified Data.List as L\n\nimport AI.Util.Matrix\nimport AI.Util.Util\n\n---------------\n-- Bootstrap --\n---------------\n\n-- |Generate a bootstrap sample of size @sz@.\ngenBootstrapSample :: RandomGen g => Int -> Rand g [Int]\ngenBootstrapSample sz = go sz []\n where go 0 accum = return accum\n go n accum = do\n i <- getRandomR (0,sz-1)\n go (n - 1) (i:accum)\n\nsampleVector :: (Storable a, RandomGen g) => Vector a -> Rand g (Vector a)\nsampleVector v = do\n idx <- genBootstrapSample (dim v)\n return (v `subRefVec` idx)\n\nsampleMatrixRows :: (Element a, RandomGen g) => Matrix a -> Rand g (Matrix a)\nsampleMatrixRows m = do\n idx <- genBootstrapSample (rows m)\n return $ m `subRefRows` idx\n\nsampleMatrixCols :: (Element a, RandomGen g) => Matrix a -> Rand g (Matrix a)\nsampleMatrixCols m = do\n idx <- genBootstrapSample (cols m)\n return $ m `subRefCols` idx\n\n-- |Generate a bootstrap sample of a statistic from a data set of type /a/.\nbootStrapResample :: RandomGen g =>\n (a -> Rand g a) -- Sampling function\n -> (a -> b) -- Statistic to be resampled\n -> Int -- Number of resamples\n -> a -- Data\n -> Rand g [b]\nbootStrapResample sample func nSamples x = go [] nSamples\n where\n go samples 0 = return samples\n go samples n = do\n x' <- sample x\n go (func x' : samples) (n-1)\n", "meta": {"hexsha": "d0e92c010cc57e231965e90302d87b09aa1bf9c5", "size": 1620, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Learning/Bootstrap.hs", "max_stars_repo_name": "cagix/aima-haskell", "max_stars_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 245, "max_stars_repo_stars_event_min_datetime": "2015-01-08T18:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T06:58:10.000Z", "max_issues_repo_path": "src/AI/Learning/Bootstrap.hs", "max_issues_repo_name": "bemcho/aima-haskell-1", "max_issues_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-09T12:56:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-10T23:14:19.000Z", "max_forks_repo_path": "src/AI/Learning/Bootstrap.hs", "max_forks_repo_name": "bemcho/aima-haskell-1", "max_forks_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2015-01-12T00:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T03:09:12.000Z", "avg_line_length": 31.7647058824, "max_line_length": 77, "alphanum_fraction": 0.5845679012, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5282105049281697}} {"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 , normalDistrErr\n , standard\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_sqrt_2, m_sqrt_2_pi)\nimport Numeric.SpecFunctions (erfc, invErfc)\nimport qualified System.Random.MWC.Distributions as MWC\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 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 ToJSON NormalDistribution\ninstance FromJSON NormalDistribution where\n parseJSON (Object v) = do\n m <- v .: \"mean\"\n sd <- v .: \"stdDev\"\n either fail return $ normalDistrErr m sd\n parseJSON _ = empty\n\ninstance Binary NormalDistribution where\n put (ND m sd _ _) = put m >> put sd\n get = do\n m <- get\n sd <- get\n either fail return $ normalDistrErr m sd\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\ninstance D.MaybeMean NormalDistribution where\n maybeMean = Just . D.mean\n\ninstance D.Mean NormalDistribution where\n mean = mean\n\ninstance D.MaybeVariance NormalDistribution where\n maybeStdDev = Just . D.stdDev\n maybeVariance = Just . D.variance\n\ninstance D.Variance NormalDistribution where\n stdDev = stdDev\n\ninstance D.Entropy NormalDistribution where\n entropy d = 0.5 * log (2 * pi * exp 1 * D.variance d)\n\ninstance D.MaybeEntropy NormalDistribution where\n maybeEntropy = Just . D.entropy\n\ninstance D.ContGen NormalDistribution where\n genContVar d = MWC.normal (mean d) (stdDev d)\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.\nnormalDistr :: Double -- ^ Mean of distribution\n -> Double -- ^ Standard deviation of distribution\n -> NormalDistribution\nnormalDistr m sd = either error id $ normalDistrErr m sd\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 = either (const Nothing) Just $ normalDistrErr m sd\n\n-- | Create normal distribution from parameters.\n--\nnormalDistrErr :: Double -- ^ Mean of distribution\n -> Double -- ^ Standard deviation of distribution\n -> Either String NormalDistribution\nnormalDistrErr m sd\n | sd > 0 = Right $ ND { mean = m\n , stdDev = sd\n , ndPdfDenom = log $ m_sqrt_2_pi * sd\n , ndCdfDenom = m_sqrt_2 * sd\n }\n | otherwise = Left $ errMsg m sd\n\nerrMsg :: Double -> Double -> String\nerrMsg _ sd = \"Statistics.Distribution.Normal.normalDistr: standard deviation must be positive. Got \" ++ show sd\n\n-- | Variance is estimated using maximum likelihood method\n-- (biased estimation).\n--\n-- Returns @Nothing@ if sample contains less than one element or\n-- variance is zero (all elements are equal)\ninstance D.FromSample NormalDistribution Double where\n fromSample xs\n | G.length xs <= 1 = Nothing\n | v == 0 = Nothing\n | otherwise = Just $! normalDistr m (sqrt v)\n where\n (m,v) = S.meanVariance xs\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": "e509b5bb72f23da57677b7e974dca98235d15a12", "size": 6231, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Normal.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/Normal.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/Normal.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": 33.320855615, "max_line_length": 112, "alphanum_fraction": 0.6421120205, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5281958828371976}} {"text": "module DeltaSigma.PowerSpectrumDensity where\n\nimport Numeric.FFT\nimport Data.Complex\n\npsd :: [Double] -> [Double]\npsd xs = take n_half . fmap (/ (fromIntegral n_half))\n . fmap magnitude . fft . fmap (:+ 0) $ take n xs\n where\n n = length xs\n n_half = n `div` 2\n", "meta": {"hexsha": "7d5c86392d4e89c019e38c667e8a0c142a465cdc", "size": 274, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/DeltaSigma/PowerSpectrumDensity.hs", "max_stars_repo_name": "7akase/deltasigma-haskell", "max_stars_repo_head_hexsha": "9b96fe2f5d9521158e539d1d46c5f951f3769a39", "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/DeltaSigma/PowerSpectrumDensity.hs", "max_issues_repo_name": "7akase/deltasigma-haskell", "max_issues_repo_head_hexsha": "9b96fe2f5d9521158e539d1d46c5f951f3769a39", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DeltaSigma/PowerSpectrumDensity.hs", "max_forks_repo_name": "7akase/deltasigma-haskell", "max_forks_repo_head_hexsha": "9b96fe2f5d9521158e539d1d46c5f951f3769a39", "max_forks_repo_licenses": ["BSD-3-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.8333333333, "max_line_length": 56, "alphanum_fraction": 0.6532846715, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5279540370124136}} {"text": "{-# LANGUAGE BangPatterns , RankNTypes, GADTs, DataKinds #-}\n\n{- | The 'Numerical.HBLAS.BLAS' module provides a fully general\nyet type safe BLAS API.\n\nWhen in doubt about the semantics of an operation,\nconsult your system's BLAS api documentation, or just read the documentation\nfor\n\n\nA few basic notes about how to invoke BLAS routines.\n\nMany BLAS operations take one or more arguments of type 'Transpose'.\n'Tranpose' has the following different constructors, which tell BLAS\nroutines what transformation to implicitly apply to an input matrix @mat@ with dimension @n x m@.\n\n* 'NoTranspose' leaves the matrix @mat@ as is.\n\n* 'Transpose' treats the @mat@ as being implicitly transposed, with dimension\n @m x n@. Entry @mat(i,j)@ being treated as actually being the entry\n @mat(j,i)@. For Real matrices this is also the matrix adjoint operation.\n ie @Tranpose(mat)(i,j)=mat(j,i)@\n\n* 'ConjNoTranspose' will implicitly conjugate @mat@, which is a no op for Real ('Float' or 'Double') matrices, but for\n'Complex Float' and 'Complex Double' matrices, a given matrix entry @mat(i,j)==x':+'y@\nwill be treated as actually being @conjugate(mat)(i,j)=y':+'x@.\n\n* 'ConjTranpose' will implicitly transpose and conjugate the input matrix.\nConjugateTranpose acts as matrix adjoint for both real and complex matrices.\n\n\n\nThe *gemm operations work as follows (using 'sgemm' as an example):\n\n* @'sgemm trLeft trRight alpha beta left right result'@, where @trLeft@ and @trRight@\nare values of type 'Transpose' that respectively act on the matrices @left@ and @right@.\n\n* the generalized matrix computation thusly formed can be viewed as being\n@result = alpha * trLeft(left) * trRight(right) + beta * result@\n\n\nthe *gemv operations are akin to the *gemm operations, but with @right@ and @result@\nbeing vectors rather than matrices.\n\n\nthe *trsv operations solve for @x@ in the equation @A x = y@ given @A@ and @y@.\nThe 'MatUpLo' argument determines if the matrix should be treated as upper or\nlower triangular and 'MatDiag' determines if the triangular solver should treat\nthe diagonal of the matrix as being all 1's or not. A general pattern of invocation\nwould be @'strsv' matuplo tranposeMatA matdiag matrixA xVector@.\nA key detail to note is that the input vector is ALSO the result vector,\nie 'strsv' and friends updates the vector place.\n\n-}\n\nmodule Numerical.HBLAS.BLAS(\n GemvFun\n ,GemmFun\n ,TrsvFun\n\n ,dgemm\n ,sgemm\n ,cgemm\n ,zgemm\n\n ,sgemv\n ,dgemv\n ,cgemv\n ,zgemv\n\n ,sger\n ,dger\n\n ,strsv\n ,dtrsv\n ,ctrsv\n ,ztrsv\n ) where\n\n\nimport Numerical.HBLAS.UtilsFFI\nimport Numerical.HBLAS.BLAS.FFI\nimport Numerical.HBLAS.BLAS.Internal\nimport Control.Monad.Primitive\nimport Data.Complex\n\n\n\n\nsgemm :: PrimMonad m=> GemmFun Float orient (PrimState m) m\nsgemm = gemmAbstraction \"sgemm\" cblas_sgemm_safe cblas_sgemm_unsafe (\\x f -> f x )\n\n\ndgemm :: PrimMonad m=> GemmFun Double orient (PrimState m) m\ndgemm = gemmAbstraction \"dgemm\" cblas_dgemm_safe cblas_dgemm_unsafe (\\x f -> f x )\n\n\ncgemm :: PrimMonad m=> GemmFun (Complex Float) orient (PrimState m) m\ncgemm = gemmAbstraction \"cgemm\" cblas_cgemm_safe cblas_cgemm_unsafe withRStorable_\n\nzgemm :: PrimMonad m=> GemmFun (Complex Double) orient (PrimState m) m\nzgemm = gemmAbstraction \"zgemm\" cblas_zgemm_safe cblas_zgemm_unsafe withRStorable_\n\n\nsgemv :: PrimMonad m => GemvFun Float orient (PrimState m) m\nsgemv = gemvAbstraction \"sgemv\" cblas_sgemv_safe cblas_sgemv_unsafe (flip ($))\n\ndgemv :: PrimMonad m => GemvFun Double orient (PrimState m) m\ndgemv = gemvAbstraction \"dgemv\" cblas_dgemv_safe cblas_dgemv_unsafe (flip ($))\n\ncgemv :: PrimMonad m => GemvFun (Complex Float) orient (PrimState m) m\ncgemv = gemvAbstraction \"cgemv\" cblas_cgemv_safe cblas_cgemv_unsafe withRStorable_\n\nzgemv :: PrimMonad m => GemvFun (Complex Double) orient (PrimState m) m\nzgemv = gemvAbstraction \"zgemv\" cblas_zgemv_safe cblas_zgemv_unsafe withRStorable_\nstrsv :: PrimMonad m => TrsvFun Float orient (PrimState m) m\nstrsv = trsvAbstraction \"strsv\" cblas_strsv_safe cblas_strsv_unsafe\n\ndtrsv :: PrimMonad m => TrsvFun Double orient (PrimState m) m\ndtrsv = trsvAbstraction \"dtrsv\" cblas_dtrsv_safe cblas_dtrsv_unsafe\n\nctrsv :: PrimMonad m => TrsvFun (Complex Float) orient (PrimState m) m\nctrsv = trsvAbstraction \"ctrsv\" cblas_ctrsv_safe cblas_ctrsv_unsafe\n\nztrsv :: PrimMonad m => TrsvFun (Complex Double) orient (PrimState m) m\nztrsv = trsvAbstraction \"ztrsv\" cblas_ztrsv_safe cblas_ztrsv_unsafe\n\nsger :: PrimMonad m => GerFun Float orient (PrimState m) m\nsger = gerAbstraction \"sger\" cblas_sger_safe cblas_sger_unsafe\n\ndger :: PrimMonad m => GerFun Double orient (PrimState m) m\ndger = gerAbstraction \"dger\" cblas_dger_safe cblas_dger_unsafe\n", "meta": {"hexsha": "da1dcb6165e83b3d1584a5c1b97bb2ff754d4313", "size": 4928, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numerical/HBLAS/BLAS.hs", "max_stars_repo_name": "archblob/hblas", "max_stars_repo_head_hexsha": "7165a333c356963fbcc5e05648b9bb8b300af0e5", "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/Numerical/HBLAS/BLAS.hs", "max_issues_repo_name": "archblob/hblas", "max_issues_repo_head_hexsha": "7165a333c356963fbcc5e05648b9bb8b300af0e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numerical/HBLAS/BLAS.hs", "max_forks_repo_name": "archblob/hblas", "max_forks_repo_head_hexsha": "7165a333c356963fbcc5e05648b9bb8b300af0e5", "max_forks_repo_licenses": ["BSD-3-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.0526315789, "max_line_length": 119, "alphanum_fraction": 0.7406655844, "num_tokens": 1484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5279255256847274}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ExplicitNamespaces #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE RecordWildCards #-}\nmodule Data.Matrix.Static.LinearAlgebra\n ( module Data.Matrix.Static.LinearAlgebra.Types\n , Arithmetic(..)\n , Factorization(..)\n , LinearAlgebra(..)\n , EigenOptions(..)\n , defaultEigenOptions\n , SortRule(..)\n\n -- * Dense matrix operation\n , zeros\n , ones\n , inverse\n , eig\n , svd\n , cond\n ) where\n\nimport qualified Data.Vector.Storable as VS\nimport Data.Vector.Storable (Vector)\nimport System.IO.Unsafe (unsafePerformIO)\nimport Data.Complex (Complex)\nimport Data.Singletons.Prelude hiding ((@@), type (==), type (-), type (<=))\nimport Data.Type.Equality\nimport GHC.TypeLits\nimport Data.Maybe (fromMaybe)\n\nimport qualified Data.Matrix.Static.Dense as D\nimport qualified Data.Matrix.Static.Sparse as S\nimport qualified Data.Matrix.Static.Generic.Mutable as CM\nimport qualified Data.Matrix.Static.Generic as C\nimport qualified Data.Matrix.Static.Internal as Internal\nimport Data.Matrix.Static.LinearAlgebra.Types\nimport Data.Matrix.Static.LinearAlgebra.Internal\n\nclass Arithmetic (mat1 :: C.MatrixKind) (mat2 :: C.MatrixKind) where\n -- | Matrix multiplication between different types of matrices.\n (@@) :: ( Numeric a, SingI n, SingI m\n , If (mat1 == mat2) mat1 D.Matrix ~ mat3 )\n => mat1 n p Vector a\n -> mat2 p m Vector a\n -> mat3 n m Vector a\n infixr 8 @@\n\n -- | Element-wise addition between different types of matrices.\n (%+%) :: ( Numeric a, SingI n, SingI m\n , If (mat1 == mat2) mat1 D.Matrix ~ mat3 )\n => mat1 n m Vector a\n -> mat2 n m Vector a\n -> mat3 n m Vector a\n infixr 8 %+%\n\n -- | Element-wise substraction between different types of matrices.\n (%-%) :: ( Numeric a, SingI n, SingI m\n , If (mat1 == mat2) mat1 D.Matrix ~ mat3 )\n => mat1 n m Vector a\n -> mat2 n m Vector a\n -> mat3 n m Vector a\n infixr 8 %-%\n\n -- | Element-wise multiplication between different types of matrices.\n (%*%) :: ( Numeric a, SingI n, SingI m\n , If (mat1 == mat2) mat1 S.SparseMatrix ~ mat3 )\n => mat1 n m Vector a\n -> mat2 n m Vector a\n -> mat3 n m Vector a\n infixr 8 %*%\n\ninstance Arithmetic D.Matrix D.Matrix where\n (@@) = withFun2 Internal.c_dd_mul\n (%+%) = (+)\n (%-%) = (-)\n (%*%) = (*)\n\ninstance Arithmetic D.Matrix S.SparseMatrix where\n (@@) = withDS Internal.c_ds_mul\n (%+%) = flip (%+%)\n (%-%) a b = a %+% C.map negate b\n (%*%) = undefined\n\ninstance Arithmetic S.SparseMatrix D.Matrix where\n (@@) = withSD Internal.c_sd_mul\n (%+%) = withSD Internal.c_sd_plus\n (%-%) a b = a %+% C.map negate b\n (%*%) = undefined\n\ninstance Arithmetic S.SparseMatrix S.SparseMatrix where\n (@@) = withSS Internal.c_ss_mul\n (%+%) = withSS Internal.c_ss_plus\n (%-%) a b = a %+% C.map negate b\n (%*%) = withSS Internal.c_ss_cmul\n\nclass LinearAlgebra (mat :: C.MatrixKind) where\n ident :: (Numeric a, SingI n) => mat n n Vector a\n\n colSum :: (Numeric a, SingI n, C.Matrix mat Vector a)\n => mat m n Vector a\n -> Matrix 1 n a\n colSum mat = D.create $ do\n m <- CM.replicate 0\n flip C.imapM_ mat $ \\(_,j) v -> CM.unsafeModify m (+v) (0, j)\n return m\n {-# INLINE colSum #-}\n\n rowSum :: (Numeric a, SingI m, C.Matrix mat Vector a)\n => mat m n Vector a\n -> Matrix m 1 a\n rowSum mat = D.create $ do\n m <- CM.replicate 0\n flip C.imapM_ mat $ \\(i,_) x -> CM.unsafeModify m (+x) (i, 0)\n return m\n {-# INLINE rowSum #-}\n\ninstance LinearAlgebra D.Matrix where\n ident = D.diag 0 $ D.replicate 1\n\ninstance LinearAlgebra S.SparseMatrix where\n ident = S.diag $ D.replicate 1\n\ndata EigenOptions = EigenOptions\n { _sigma :: Maybe Double -- ^ Find eigenvalues near sigma using shift-invert mode.\n , _ncv :: Maybe Int -- ^ Parameter that controls the convergence\n -- speed of the algorithm. Typically a larger ncv\n -- means faster convergence, but it may also result\n -- in greater memory use and more matrix operations\n -- in each iteration. This parameter must satisfy\n -- k+2 <= ncv <= n, and is advised to take ncv > 2k+1.\n -- Default: min(n, max(2*k + 1, 20))\n , _maxit :: Maybe Int -- ^ Maximum number of iterations allowed in the algorithm.\n , _tol :: Double -- Precision parameter for the calculated eigenvalues.\n , _sort_rule :: SortRule\n }\n\ndefaultEigenOptions :: EigenOptions\ndefaultEigenOptions = EigenOptions\n { _sigma = Nothing\n , _ncv = Nothing\n , _maxit = Nothing\n , _tol = 2.2204460492503131e-16\n , _sort_rule = LM }\n\ndata SortRule = LM\n | LR\n | LI\n | LA\n | SM\n | SR\n | SI\n | SA\n | BE\n deriving (Enum)\n\nclass Factorization mat where\n -- | Eigenvalues (from largest to smallest) and\n -- eigenvectors (as columns) of a general square matrix.\n eigS :: (SingI k, SingI n, k <= n - 2)\n => Sing k\n -> mat n n Vector Double\n -> (Matrix k 1 (Complex Double), Matrix n k (Complex Double))\n eigS a b = eigS' a b defaultEigenOptions\n\n eigS' :: (SingI k, SingI n, k <= n - 2)\n => Sing k\n -> mat n n Vector Double\n -> EigenOptions\n -> (Matrix k 1 (Complex Double), Matrix n k (Complex Double))\n\n -- | Eigenvalues (from largest to smallest) and\n -- eigenvectors (as columns) of a symmetric square matrix.\n eigSH :: (SingI k, SingI n, k <= n - 1)\n => Sing k\n -> mat n n Vector Double\n -> (Matrix k 1 Double, Matrix n k Double)\n eigSH a b = eigSH' a b defaultEigenOptions\n\n eigSH' :: (SingI k, SingI n, k <= n - 1)\n => Sing k\n -> mat n n Vector Double\n -> EigenOptions\n -> (Matrix k 1 Double, Matrix n k Double)\n\n -- | Generalized eigen solver for real symmetric matrices\n geigSH :: (SingI k, SingI n, k <= n - 1)\n => Sing k\n -> mat n n Vector Double\n -> SparseMatrix n n Double\n -> (Matrix k 1 Double, Matrix n k Double)\n geigSH a b c = geigSH' a b c defaultEigenOptions\n\n geigSH' :: (SingI k, SingI n, k <= n - 1)\n => Sing k\n -> mat n n Vector Double\n -> SparseMatrix n n Double\n -> EigenOptions\n -> (Matrix k 1 Double, Matrix n k Double)\n\n -- | Cholesky decomposition\n cholesky :: (Numeric a, SingI n) => mat n n Vector a -> mat n n Vector a\n\n\ninstance Factorization D.Matrix where\n eigS' s mat EigenOptions{..}\n | D.all (==0) mat = ( D.replicate 0, D.replicate 1)\n | otherwise = unsafePerformIO $ do\n m1 <- CM.new\n m2 <- CM.new\n info <- fmap Internal.computationInfo $ unsafeWith' m1 $ \\v1 _ _ ->\n unsafeWith' m2 $ \\v2 _ _ -> unsafeWith mat $ \\v n _ ->\n Internal.c_eigs k v1 v2 v n ncv' maxit _tol mode sigma $ fromIntegral $ fromEnum _sort_rule\n case info of\n Nothing -> do\n m1' <- C.unsafeFreeze m1\n m2' <- C.unsafeFreeze m2\n return (m1', m2')\n Just err -> error err\n where\n ncv' = case _ncv of\n Just x -> fromIntegral x\n Nothing -> min d $ max 20 $ 2 * k + 1\n maxit = case _maxit of\n Just x -> fromIntegral x\n Nothing -> d * 10\n mode = case _sigma of\n Nothing -> 0\n _ -> 1\n sigma = fromMaybe 0 _sigma\n k = fromIntegral $ fromSing s\n d = fromIntegral $ D.rows mat\n {-# INLINE eigS' #-}\n\n eigSH' s mat EigenOptions{..}\n | D.all (==0) mat = (D.replicate 0, D.replicate 1)\n | otherwise = unsafePerformIO $ do\n m1 <- CM.new\n m2 <- CM.new\n ( fmap Internal.computationInfo $ unsafeWith' m1 $ \\v1 _ _ ->\n unsafeWith' m2 $ \\v2 _ _ -> unsafeWith mat $ \\v n _ ->\n Internal.c_eigsh k v1 v2 v n ncv' maxit _tol mode sigma $\n fromIntegral $ fromEnum _sort_rule ) >>= maybe\n ( do\n m1' <- C.unsafeFreeze m1\n m2' <- C.unsafeFreeze m2\n return (m1', m2') ) error\n where\n ncv' = case _ncv of\n Just x -> fromIntegral x\n Nothing -> min d $ max 20 $ 2 * k + 1\n maxit = case _maxit of\n Just x -> fromIntegral x\n Nothing -> d * 10\n mode = case _sigma of\n Nothing -> 0\n _ -> 1\n sigma = fromMaybe 0 _sigma\n k = fromIntegral $ fromSing s\n d = fromIntegral $ D.rows mat\n {-# INLINE eigSH' #-}\n\n geigSH' s matA matB EigenOptions{..} = unsafePerformIO $ do\n m1 <- CM.new\n m2 <- CM.new\n ( fmap Internal.computationInfo $ unsafeWith' m1 $ \\v1 _ _ ->\n unsafeWith' m2 $ \\v2 _ _ -> unsafeWith matA $ \\v n _ ->\n unsafeWithS matB $ \\pv pin po _ _ size ->\n Internal.c_geigsh k v1 v2 v n pv po pin size\n ncv' maxit _tol $ fromIntegral $ fromEnum _sort_rule ) >>= maybe\n ( do\n m1' <- C.unsafeFreeze m1\n m2' <- C.unsafeFreeze m2\n return (m1', m2') ) error\n where\n ncv' = case _ncv of\n Just x -> fromIntegral x\n Nothing -> min d $ max 20 $ 2 * k + 1\n maxit = case _maxit of\n Just x -> fromIntegral x\n Nothing -> d * 10\n k = fromIntegral $ fromSing s\n d = fromIntegral $ D.rows matA\n {-# INLINE geigSH' #-}\n\n cholesky mat = flip withFun1 mat $\n \\code p1 c1 _ p2 _ _ -> Internal.c_cholesky code p1 p2 c1\n {-# INLINE cholesky #-}\n\ninstance Factorization S.SparseMatrix where\n eigS' s mat EigenOptions{..} = unsafePerformIO $ do\n m1 <- CM.new\n m2 <- CM.new\n ( fmap Internal.computationInfo $ unsafeWith' m1 $ \\v1 _ _ ->\n unsafeWith' m2 $ \\v2 _ _ -> unsafeWithS mat $ \\pv pin po n _ size ->\n Internal.c_seigs k v1 v2 pv po pin n size\n ncv' maxit _tol mode sigma $ fromIntegral $ fromEnum _sort_rule\n ) >>= maybe\n ( do\n m1' <- C.unsafeFreeze m1\n m2' <- C.unsafeFreeze m2\n return (m1', m2') ) error\n where\n ncv' = case _ncv of\n Just x -> fromIntegral x\n Nothing -> min d $ max 20 $ 2 * k + 1\n maxit = case _maxit of\n Just x -> fromIntegral x\n Nothing -> d * 10\n mode = case _sigma of\n Nothing -> 0\n _ -> 1\n sigma = fromMaybe 0 _sigma\n k = fromIntegral $ fromSing s\n d = fromIntegral $ D.rows mat\n {-# INLINE eigS' #-}\n\n eigSH' s mat EigenOptions{..} = unsafePerformIO $ do\n m1 <- CM.new\n m2 <- CM.new\n ( fmap Internal.computationInfo $ unsafeWith' m1 $ \\v1 _ _ ->\n unsafeWith' m2 $ \\v2 _ _ -> unsafeWithS mat $ \\pv pin po n _ size ->\n Internal.c_seigsh k v1 v2 pv po pin n size\n ncv' maxit _tol mode sigma $ fromIntegral $ fromEnum _sort_rule\n ) >>= maybe\n ( do \n m1' <- C.unsafeFreeze m1\n m2' <- C.unsafeFreeze m2\n return (m1', m2') ) error\n where\n ncv' = case _ncv of\n Just x -> fromIntegral x\n Nothing -> min d $ max 20 $ 2 * k + 1\n maxit = case _maxit of\n Just x -> fromIntegral x\n Nothing -> d * 10\n mode = case _sigma of\n Nothing -> 0\n _ -> 1\n sigma = fromMaybe 0 _sigma\n k = fromIntegral $ fromSing s\n d = fromIntegral $ D.rows mat\n {-# INLINE eigSH' #-}\n\n cholesky = undefined\n\ntype family R a where\n R Float = Float\n R Double = Double\n R (Complex Double) = Double\n R (Complex Float) = Float\n\nzeros :: (SingI m, SingI n) => Matrix m n Double\nzeros = D.replicate 0\n{-# INLINE zeros #-}\n\nones :: (SingI m, SingI n) => Matrix m n Double\nones = D.replicate 1\n{-# INLINE ones #-}\n \n-- | The inverse of a dense matrix.\ninverse :: (SingI n, Numeric a) => Matrix n n a -> Matrix n n a\ninverse = withFun1 Internal.c_inverse\n{-# INLINE inverse #-}\n\n-- | Compute the full eigendecomposition for dense matrix.\neig :: forall n . SingI n\n => Matrix n n Double\n -> (Matrix n 1 (Complex Double), Matrix n n (Complex Double))\neig mat = unsafePerformIO $ do\n m1 <- CM.new\n m2 <- CM.new\n _ <- unsafeWith' m1 $ \\v1 _ _ -> unsafeWith' m2 $ \\v2 _ _ ->\n unsafeWith mat $ \\v n _ -> Internal.c_eig v1 v2 v n\n m1' <- C.unsafeFreeze m1\n m2' <- C.unsafeFreeze m2\n return (m1', m2')\n{-# INLINE eig #-}\n\n\n-- | Compute the full singular value decomposition for dense matrix.\nsvd :: forall n p a m. (Numeric (R a), Numeric a, SingI n, SingI p, SingI m, m ~ Min n p)\n => Matrix n p a\n -> (Matrix n m a, Matrix m 1 (R a), Matrix p m a)\nsvd mat = unsafePerformIO $ do\n mu <- CM.new\n ms <- CM.new\n mv <- CM.new\n checkResult $ unsafeWith' mu $ \\pu _ _ -> unsafeWith' ms $ \\ps _ _ ->\n unsafeWith' mv $ \\pv _ _ -> unsafeWith mat $ \\px r c ->\n Internal.c_bdcsvd (foreignType (undefined :: a))\n pu ps pv px r c\n u <- C.unsafeFreeze mu\n s <- C.unsafeFreeze ms\n v <- C.unsafeFreeze mv\n return (u, s, v)\n{-# INLINE svd #-}\n\n-- | Condition number.\ncond :: ( Numeric a, Numeric (R a), Ord (R a), Fractional (R a)\n , SingI n, SingI m, SingI (Min n m))\n => Matrix n m a -> R a\ncond mat = VS.maximum val / VS.minimum val\n where\n val = VS.filter (/=0) $ D.flatten s\n (_,s,_) = svd mat\n{-# INLINE cond #-}\n", "meta": {"hexsha": "b779adc45319d842746493b4938f6b070255341c", "size": 14403, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Matrix/Static/LinearAlgebra.hs", "max_stars_repo_name": "kaizhang/matrix-sized", "max_stars_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/Matrix/Static/LinearAlgebra.hs", "max_issues_repo_name": "kaizhang/matrix-sized", "max_issues_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/Matrix/Static/LinearAlgebra.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": 34.456937799, "max_line_length": 111, "alphanum_fraction": 0.5434284524, "num_tokens": 4038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5278363406352289}} {"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\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 Numeric.LinearAlgebra.Static\n\n-- * Weights\n--\n\ndata Weights i o = W { wBiases :: !(R o)\n , wNodes :: !(L o i)\n }\n deriving (Show, Generic)\n\ninstance (KnownNat i, KnownNat o) => Binary (Weights i o)\n\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\nrunLayer :: (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 :: (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\nhiddenStruct :: Network i hs o -> [Integer]\nhiddenStruct = \\case\n O _ -> []\n _ :&~ (n' :: Network h hs' o)\n -> natVal (Proxy @h)\n : hiddenStruct n'\n\nrandomNet' :: 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 :: forall m i hs o. (MonadRandom m, KnownNat i, SingI hs, KnownNat o)\n => m (Network i hs o)\nrandomNet = randomNet' sing\n\nputNet :: (KnownNat i, KnownNat o)\n => Network i hs o\n -> Put\nputNet = \\case\n O w -> put w\n w :&~ n -> put w *> putNet n\n\ngetNet :: forall i hs o. (KnownNat i, KnownNat o)\n => Sing hs\n -> Get (Network i hs o)\ngetNet = \\case\n SNil -> O <$> get\n SNat `SCons` ss -> (:&~) <$> get <*> getNet ss\n\ninstance (KnownNat i, SingI hs, KnownNat o) => Binary (Network i hs o) where\n put = putNet\n get = getNet sing\n\n-- * OpaqueNet\n--\n\ndata OpaqueNet :: Nat -> Nat -> * where\n ONet :: Network i hs o -> OpaqueNet i o\n\nrunOpaqueNet :: (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\nrandomONet :: (MonadRandom m, KnownNat i, KnownNat o)\n => [Integer]\n -> m (OpaqueNet i o)\nrandomONet hs = case toSing hs of\n SomeSing ss -> ONet <$> randomNet' ss\n\nputONet :: (KnownNat i, KnownNat o)\n => OpaqueNet i o\n -> Put\nputONet (ONet net) = do\n put (hiddenStruct net)\n putNet net\n\ngetONet :: (KnownNat i, KnownNat o)\n => Get (OpaqueNet i o)\ngetONet = do\n hs <- get\n withSomeSing hs $ \\ss ->\n ONet <$> getNet ss\n\ninstance (KnownNat i, KnownNat o) => Binary (OpaqueNet i o) where\n put = putONet\n get = getONet\n\n-- * OpaqueNet'\n--\n\ntype OpaqueNet' i o r = (forall hs. Network i hs o -> r) -> r\n\noNet' :: Network i hs o -> OpaqueNet' i o r\noNet' n = \\f -> f n\n\nrunOpaqueNet' :: (KnownNat i, KnownNat o)\n => OpaqueNet' i o (R o)\n -> R i\n -> R o\nrunOpaqueNet' oN x = oN (\\n -> runNet n 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\nwithRandomONet' :: (MonadRandom m, KnownNat i, KnownNat o)\n => [Integer]\n -> (forall hs. Network i hs o -> m r)\n -> m r\n-- aka, => [Integer]\n-- -> OpaqueNet' i o (m r)\nwithRandomONet' hs f = withSomeSing hs $ \\ss -> do\n net <- randomNet' ss\n f net\n\nputONet' :: (KnownNat i, KnownNat o)\n => OpaqueNet' i o Put\n -> Put\nputONet' oN = oN $ \\net -> do\n put (hiddenStruct net)\n putNet net\n\ngetONet' :: (KnownNat i, KnownNat o)\n => (forall hs. Network i hs o -> Get r)\n -> Get r\n-- aka, => OpaqueNet' i o (Get r)\ngetONet' f = do\n hs <- get :: Get [Integer]\n withSomeSing hs $ \\ss -> do\n n <- getNet ss\n f n\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) -> do\n print net\n -- blah blah stuff with our dynamically generated 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) -> do\n print net\n -- blah blah stuff with our dynamically generated net\n\n-- * SomeNet\n--\n\ndata SomeNet where\n SNet :: (KnownNat i, KnownNat o)\n => Network i hs o\n -> SomeNet\n\nwithONet :: SomeNet\n -> (forall i o. (KnownNat i, KnownNat o) => OpaqueNet i o -> r)\n -> r\nwithONet (SNet n) f = f (ONet n)\n\nrandomSNet :: forall m. MonadRandom m\n => Integer\n -> [Integer]\n -> Integer\n -> m SomeNet\nrandomSNet i hs o =\n withSomeSing i $ \\(SNat :: Sing (i :: Nat )) ->\n withSomeSing hs $ \\(ss :: Sing (hs :: [Nat])) ->\n withSomeSing o $ \\(SNat :: Sing (o :: Nat )) ->\n SNet <$> (randomNet' ss :: m (Network i hs o))\n\nwithRandomSNet' :: forall m r. MonadRandom m\n => Integer\n -> [Integer]\n -> Integer\n -> (forall i hs o. (KnownNat i, KnownNat o) => Network i hs o -> m r)\n -> m r\nwithRandomSNet' i hs o f =\n withSomeSing i $ \\(SNat :: Sing (i :: Nat )) ->\n withSomeSing hs $ \\(ss :: Sing (hs :: [Nat])) ->\n withSomeSing o $ \\(SNat :: Sing (o :: Nat )) -> do\n n <- randomNet' ss :: m (Network i hs o)\n f n\n\ninstance Binary SomeNet where\n put (SNet (net :: Network i hs o)) = do\n put $ natVal (Proxy @i)\n put $ hiddenStruct net\n put $ natVal (Proxy @o)\n putNet net\n get = do\n i <- get :: Get Integer\n hs <- get :: Get [Integer]\n o <- get :: Get Integer\n withSomeSing i $ \\(SNat :: Sing (i :: Nat )) ->\n withSomeSing hs $ \\(ss :: Sing (hs :: [Nat])) ->\n withSomeSing o $ \\(SNat :: Sing (o :: Nat )) -> do\n n <- getNet ss :: Get (Network i hs o)\n return (SNet n)\n\n", "meta": {"hexsha": "be367626e6dcdce9a54abfdb83620d5817938588", "size": 7615, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "code-samples/dependent-haskell/NetworkTyped2.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/dependent-haskell/NetworkTyped2.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/dependent-haskell/NetworkTyped2.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": 27.5905797101, "max_line_length": 85, "alphanum_fraction": 0.5065003283, "num_tokens": 2301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5276536521395494}} {"text": "module Main where\n\nimport MnistLoader\nimport Network\n\nimport Numeric.LinearAlgebra as L\n\nmain :: IO ()\nmain = testMnist\n\ntestMnist = do\n net <- initNet [784, 30, 10]\n exemplars <- loadDataWrapper\n test <- loadTestWrapper\n\n -- let eta = 0.050\n -- let batchSize = 20\n -- let epochs = 30\n\n let eta = 0.5\n let batchSize = 16\n let epochs = 30\n\n putStrLn \"Running Stochastic Gradient Descent \"\n putStrLn $ \"eta: \" ++ (show eta)\n putStrLn $ \"Batch Size: \" ++ (show batchSize)\n putStrLn $ \"Epochs: \" ++ (show epochs)\n\n trainedNetwork <- sgd net exemplars test epochs 0 batchSize eta\n return ()\n\ntest = do\n net <- initNet [3, 5]\n \n putStrLn \"The Net\"\n putStrLn $ show net\n \n putStrLn \"Feed Forward\"\n putStrLn $ show $ feedForward net (vect 3 [0, 1, 0])\n \n putStrLn \"A ForwardPass\"\n putStrLn $ show $ forwardPass net (vect 3 [0, 1, 0])\n \n putStrLn \"Entire backprop\"\n let eb = backprop net (vect 3 [0, 1, 0]) (vect 5 [1, 0, 1, 0, 1])\n putStrLn $ show $ length eb\n putStrLn $ show $ eb\n\n putStrLn \"A Minibatch\"\n let x = vect 3 [0,1,0]\n let y = vect 5 [1, 0, 1, 0, 1]\n let batch = [(x, y), (x, y), (x, y)]\n let newn = updateMiniBatch net batch 3.0\n putStrLn $ show newn\n return newn\n\nvect n = (n><1)", "meta": {"hexsha": "4d9c6fce77f6a91d96a7fbcdaefa7267ce4a7b4c", "size": 1223, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.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": "app/Main.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": "app/Main.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": 21.4561403509, "max_line_length": 67, "alphanum_fraction": 0.6287816844, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5276536483386415}} {"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.LeastSquares where\n\nimport qualified Math.HMatrixUtils as HU\nimport qualified Math.Regression.Regression as RE\n\nimport qualified Polysemy as P\nimport qualified Knit.Effect.Logger as Log\n\nimport qualified Data.List as List\n\nimport Numeric.LinearAlgebra ( (#>)\n , (<.>)\n , (<\\>)\n )\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Data ( Matrix\n , R\n , Vector\n )\n\n-- matrix dimensions given in (row x column) form\n-- if A is (m x n), its transpose, A' is (n x m)\n-- ||A|| is the Frobenius norm of A, the sum of the squares of the elements.\n-- if A (m x l) and B (m x k) have the same number of rows, [A B] is the (m x (l+k)) matrix formed by appending the columns of B to the columns of A\n-- A: an (m x n) matrix, of m observations of n observables\n-- B: an (m x d) matrix, of observations (often d=1 and B is just a length m column-vector)\n-- Q: an ((n+d)m x (n+d)m) matrix of covariances, the covariance matrix of [A B]. Given? Computed?\n\n-- we want an (n x d) matrix X which solves, or \"best solves\", AX = B.\n\n-- OLS: minimize ||AX - B||\nordinaryLS\n :: Log.LogWithPrefixesLE effs\n => Bool\n -> Matrix R\n -> Vector R\n -> P.Sem effs (RE.RegressionResult R)\nordinaryLS withConstant mA vB = do\n let mAwc = if withConstant then addBiasCol (LA.size vB) mA else mA -- add a constant, e.g., the b in y = mx + b\n (n, p) = LA.size mAwc\n dof = n - p\n HU.checkVectorMatrix \"b\" \"A\" vB mAwc -- vB <> mA is legal, b has same length as A has rows\n let vX = mAwc <\\> vB\n vU = vB - (mAwc #> vX) -- residuals\n mse = (vU <.> vU) / realToFrac dof\n cov = LA.scale mse (LA.inv $ LA.tr mAwc LA.<> mAwc)\n RE.FitStatistics rSq aRSq fStat <- RE.goodnessOfFit p vB Nothing vU\n return $ RE.RegressionResult (RE.estimates cov vX)\n (realToFrac dof)\n mse\n rSq\n aRSq\n fStat\n cov\n\nweightedLS\n :: Log.LogWithPrefixesLE effs\n => Bool\n -> Matrix R\n -> Vector R\n -> Vector R\n -> P.Sem effs (RE.RegressionResult R)\nweightedLS withConstant mA vB vW = do\n HU.checkEqualVectors \"b\" \"w\" vB vW\n let mW = LA.diag vW\n vWB = mW #> vB\n mAwc = if withConstant then addBiasCol (LA.size vB) mA else mA -- add a constant, e.g., the b in y = mx + b\n (_, p) = LA.size mAwc\n HU.checkVectorMatrix \"b\" \"A\" vB mAwc\n let mWA = mW LA.<> mAwc\n vX = mWA <\\> vWB\n vU = vB - (mAwc #> vX)\n vWU = mW #> vU\n sumW = LA.sumElements vW\n effN = (sumW * sumW) / (vW <.> vW)\n mse = effN / (effN - realToFrac p) * (vWU <.> vWU) / sumW\n cov = LA.scale mse (LA.inv $ LA.tr mAwc LA.<> mAwc)\n RE.FitStatistics rSq aRSq fStat <- RE.goodnessOfFit p vB (Just vW) vU\n return $ RE.RegressionResult (RE.estimates cov vX)\n (effN - realToFrac p)\n mse\n rSq\n aRSq\n fStat\n cov\n\ntotalLS\n :: Log.LogWithPrefixesLE effs\n => Bool\n -> Matrix R\n -> Vector R\n -> P.Sem effs (RE.RegressionResult R)\ntotalLS withConstant mA vB = do\n let mAwc = if withConstant then addBiasCol (LA.size vB) mA else mA -- add a constant, e.g., the b in y = mx + b\n (n, p) = LA.size mAwc\n dof = realToFrac (n - p)\n HU.checkVectorMatrix \"b\" \"Awc\" vB mAwc\n let mAB = mAwc LA.||| LA.asColumn vB\n (_, mV') = LA.rightSV mAB\n-- gSV = sv V.! 0\n-- tol = gSV * LA.eps\n sV22 = mV' LA.! p LA.! p\n vV12 = List.head $ LA.toColumns $ LA.subMatrix (0, p) (p, 1) mV' --LA.?? (LA.DropLast 1, LA.TakeLast 1)\n vX = LA.scale (-1 / sV22) vV12 -- this is the TLS solution. But in a shifted basis.??\n-- mV2 = mV' LA.?? (LA.All, LA.TakeLast 1)\n-- mABt = mAB LA.<> mV2 LA.<> (LA.tr mV2)\n-- mAt = mABt LA.?? (LA.All, LA.DropLast 1)\n vBfit = mAwc #> vX --(mAwc - mAt) #> vX -- this is confusing.\n vU = vB - vBfit\n-- (rSq, aRSq) = RE.goodnessOfFit p vB vU --(vB - mA #> vX)\n mse = (vU <.> vU) / realToFrac (n - p)\n cov = LA.scale mse (LA.inv $ LA.tr mAwc LA.<> mAwc)\n RE.FitStatistics rSq aRSq fStat <- RE.goodnessOfFit p vB Nothing vU\n return $ RE.RegressionResult (RE.estimates cov vX) dof mse rSq aRSq fStat cov\n\nweightedTLS\n :: Log.LogWithPrefixesLE effs\n => Bool\n -> Matrix R\n -> Vector R\n -> Vector R\n -> P.Sem effs (RE.RegressionResult R)\nweightedTLS withConstant mA vB vW = do\n HU.checkEqualVectors \"b\" \"w\" vB vW\n let mW = LA.diag vW\n vWB = mW #> vB\n mAwc = if withConstant then addBiasCol (LA.size vB) mA else mA -- add a constant, e.g., the b in y = mx + b\n (_, p) = LA.size mAwc\n HU.checkVectorMatrix \"b\" \"Awc\" vB mAwc\n let mWA = mW LA.<> mAwc\n mWAB = mWA LA.||| LA.asColumn vWB\n (_, mV') = LA.rightSV mWAB\n-- gSV = sv V.! 0\n-- tol = gSV * LA.eps\n sV22 = mV' LA.! p LA.! p\n vV12 = List.head $ LA.toColumns $ LA.subMatrix (0, p) (p, 1) mV' --LA.?? (LA.DropLast 1, LA.TakeLast 1)\n vX = LA.scale (-1 / sV22) vV12 -- this is the WTLS solution. But in a shifted basis.??\n-- mV2 = mV' LA.?? (LA.All, LA.TakeLast 1)\n-- mWABt = mWAB LA.<> mV2 LA.<> (LA.tr mV2)\n-- mWAt = mWABt LA.?? (LA.All, LA.DropLast 1)\n-- vBfit = mAwc #> vX -- (mWA - mWAt) #> vX -- this is confusing\n vU = vB - (mAwc #> vX)\n vWU = mW #> vU\n sumW = LA.sumElements vW\n effN = (sumW * sumW) / (vW <.> vW)\n dof = effN - realToFrac p\n mse = effN / dof * (vWU <.> vWU) / sumW\n-- (rSq, aRSq) = RE.goodnessOfFit p vWB vWU --(vB - mA #> vX)\n cov = LA.scale mse (LA.inv $ LA.tr mAwc LA.<> mAwc)\n RE.FitStatistics rSq aRSq fStat <- RE.goodnessOfFit p vB (Just vW) vU\n return $ RE.RegressionResult (RE.estimates cov vX) dof mse rSq aRSq fStat cov\n\naddBiasCol :: Int -> Matrix R -> Matrix R\naddBiasCol rows mA =\n let colList = List.replicate rows 1\n in if LA.size mA == (0, 0)\n then LA.matrix 1 colList\n else LA.col colList LA.||| mA\n", "meta": {"hexsha": "24642bc335e88a6a13b406d620794956a48149f7", "size": 7076, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Regression/LeastSquares.hs", "max_stars_repo_name": "teto/Frames-utils", "max_stars_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Math/Regression/LeastSquares.hs", "max_issues_repo_name": "teto/Frames-utils", "max_issues_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/Regression/LeastSquares.hs", "max_forks_repo_name": "teto/Frames-utils", "max_forks_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6235294118, "max_line_length": 148, "alphanum_fraction": 0.5257207462, "num_tokens": 2300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5276476571298938}} {"text": "{-# LANGUAGE TypeOperators,TypeFamilies,MultiParamTypeClasses,FlexibleContexts, BangPatterns,PolyKinds, DataKinds, GADTs, GeneralizedNewtypeDeriving,DeriveDataTypeable,FlexibleInstances,ScopedTypeVariables #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE CPP #-}\n{- | Fixed point arithmetic \n\nFixed point arithmetic with signed, unsigned and saturation\n\n-}\nmodule Fixed(\n nbFractionalBits\n , HasDoubleRepresentation(..)\n , FixedPoint(..)\n , Resolution(..)\n , AMulConstraint(..)\n , ConvertConstraint(..)\n , withSaturation \n , withoutSaturation\n , withRounding\n , withNoRounding\n , Fixed\n , Saturation(..)\n , Rounding(..)\n , Int16\n , Int32 \n , Int40\n , Word16 \n , Word32\n , Word40\n , Int128\n , Conversion(..)\n , amul\n , amulc\n , roundf\n ) where \n\nimport Data.Typeable\nimport GHC.TypeLits\nimport Data.Word\nimport Data.Int\nimport Data.Bits\nimport Text.Printf\nimport Data.Ratio\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Generic.Mutable as M\nimport Control.Monad(liftM)\nimport Common(HasDoubleRepresentation(..))\nimport Data.Complex\nimport SpecialInt \nimport Control.DeepSeq\nimport System.Random\n\nimport Debug.Trace\n\ndebug a = trace (show a) a \n\ninstance HasDoubleRepresentation Double where \n toDouble = id \n fromDouble = id\n\ninstance HasDoubleRepresentation Float where \n toDouble = realToFrac \n fromDouble = realToFrac\n\ninstance HasDoubleRepresentation Int where \n toDouble = fromIntegral\n fromDouble = floor\n\nnewtype Fixed :: * -> Nat -> Saturation -> Rounding -> * where Fixed :: a -> Fixed a n sa r\n\ndata Saturation = Sat | Unsat deriving(Eq)\ndata Rounding = RO | NR deriving(Eq)\n\nnewtype instance Sing (n :: Saturation) = SatC Saturation\nnewtype instance Sing (n :: Rounding) = RoundC Rounding\n\ninstance SingI Sat where \n sing = SatC Sat\n\ninstance SingI Unsat where \n sing = SatC Unsat\n\ninstance SingE (Kind :: Saturation) Saturation where\n fromSing (SatC n) = n\n\ninstance SingI RO where \n sing = RoundC RO\n\ninstance SingI NR where \n sing = RoundC NR\n\ninstance SingE (Kind :: Rounding) Rounding where\n fromSing (RoundC n) = n\n\nnewtype instance U.MVector s (Fixed a n sat r) = MVFixed (U.MVector s a)\nnewtype instance U.Vector (Fixed a n sat r) = VFixed (U.Vector a)\n\ninstance (U.Unbox a) => M.MVector U.MVector (Fixed a n s r) where\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicOverlaps #-}\n {-# INLINE basicUnsafeNew #-}\n {-# INLINE basicUnsafeRead #-}\n {-# INLINE basicUnsafeWrite #-}\n basicLength (MVFixed v) = M.basicLength v\n basicUnsafeSlice a b (MVFixed v) = MVFixed $ M.basicUnsafeSlice a b v\n basicOverlaps (MVFixed a) (MVFixed b) = M.basicOverlaps a b \n basicUnsafeNew n = MVFixed `liftM` M.basicUnsafeNew n\n basicUnsafeRead (MVFixed v) i = do \n r <- M.basicUnsafeRead v i\n return (Fixed r)\n basicUnsafeWrite (MVFixed v) i (Fixed r) = do \n M.basicUnsafeWrite v i r \n\ninstance (U.Unbox a) => G.Vector U.Vector (Fixed a n s r) where\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeFreeze #-}\n {-# INLINE basicUnsafeThaw #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicUnsafeIndexM #-}\n basicLength (VFixed v) = G.basicLength v\n basicUnsafeFreeze (MVFixed v) = VFixed `liftM`G.basicUnsafeFreeze v\n basicUnsafeThaw (VFixed v) = MVFixed `liftM`G.basicUnsafeThaw v\n basicUnsafeSlice a b (VFixed v) = VFixed (G.basicUnsafeSlice a b v)\n basicUnsafeIndexM (VFixed v) i = Fixed `liftM` G.basicUnsafeIndexM v i \n\ninstance (RealFloat a, U.Unbox a) => U.Unbox (Fixed a n sat r)\n\n{-# INLINE getFract #-}\ngetFract :: Fixed a (n :: Nat) sa r -> Sing n -> Integer \ngetFract _ s = fromSing s \n\n{-# INLINE nbFractionalBits #-}\nnbFractionalBits :: SingI n => Fixed a (n :: Nat) sa r -> Int \nnbFractionalBits f = fromIntegral $ getFract f sing\n\n{-# INLINE getSaturationMode #-}\ngetSaturationMode :: Fixed a n sa r -> Sing sa -> Saturation \ngetSaturationMode _ s = fromSing s \n\n{-# INLINE saturationMode #-}\nsaturationMode :: SingI sa => Fixed a n sa r -> Saturation \nsaturationMode f = getSaturationMode f sing\n\n{-# INLINE getRoundingMode #-}\ngetRoundingMode :: Fixed a n s (r :: Rounding) -> Sing r -> Rounding \ngetRoundingMode _ s = fromSing s \n\n{-# INLINE roundingMode #-}\nroundingMode :: SingI r => Fixed a n sa r -> Rounding\nroundingMode f = getRoundingMode f sing\n\n{-# INLINE saturateWithMode #-}\nsaturateWithMode :: (SingI sa, SaturateConstraint a)\n => Fixed a n sa r\n -> SuperInt a \n -> a \nsaturateWithMode f su | saturationMode f == Unsat = fromIntegral su \n | otherwise = saturate (witness f) su\n where \n witness (Fixed a) = a\n\n{-# INLINE roundWithMode #-}\nroundWithMode :: (SingI r, Bits b, Ord b, Num b)\n => Fixed a n sa r \n -> Int \n -> Int\n -> b\n -> b \nroundWithMode f na nb su = rounding (roundingMode f) na nb su\n \n{-# INLINE roundf #-}\nroundf :: (SingI n, SingI r, SingI sa, SaturateConstraint a, Bits (SuperInt a)) \n => Fixed a n sa r \n -> Fixed a n sa r \nroundf f@(Fixed a) = \n let na = nbFractionalBits f \n in \n Fixed $ saturateWithMode f (roundWithMode f na 0 (fromIntegral a))\n\n{-# INLINE rounding #-}\nrounding :: (Bits a, Num a, Ord a) \n => Rounding \n -> Int -- ^ Current fractional bits \n -> Int -- ^ Future fractional bits \n -> a \n -> a \nrounding r cf ff v | cf <= ff = v\n | otherwise = \n case r of \n RO -> nearR \n NR -> v\n where \n rpos = cf - ff\n roundingMask = complement ((1 `shiftL` rpos) - 1)\n nearR = (v + (1 `shiftL` (rpos - 1))) .&. roundingMask -- near\n \n\ninstance Eq a => Eq (Fixed a n sa r) where\n (Fixed a) == (Fixed b) = a == b\n\ninstance Ord a => Ord (Fixed a n sa r) where \n compare (Fixed a) (Fixed b) = compare a b\n\ntype AMulConstraint a b = (Num (BaseValue b), Bits b, Integral b, Integral (SuperInt b), Num (SuperInt b), Integral a, NumberInfo (SuperInt b), NumberInfo a, NumberInfo b, RawValue b, Num b) \n\n{-# INLINE amul #-}\namul :: (SingI na, SingI nb, SingI s, AMulConstraint a b)\n => Fixed a na s r \n -> Fixed a nb s r \n -> Fixed b (na + nb) s r\namul fa@(Fixed a) (Fixed b) = \n let la = fromIntegral a\n lb = fromIntegral b\n r = (la * lb)\n result = Fixed (saturateWithMode result r)\n in\n result\n\n{-# INLINE amulc #-}\namulc :: (SingI na,SingI nb, SingI s, AMulConstraint a b,Num (Fixed b (na+nb) s r)) \n => Complex (Fixed a na s r) \n -> Complex (Fixed a nb s r) \n -> Complex (Fixed b (na+nb) s r)\namulc (xr :+ xi) (yr :+ yi) = (amul xr yr - amul xi yi) :+ (amul xr yi + amul xi yr)\n\ntype ConvertConstraint a b = (Integral a, Bits a, Bits (SuperInt b), NumberInfo a, NumberInfo b, SaturateConstraint b)\n\nclass Conversion a b where \n {-# INLINE convert #-}\n convert :: (SingI na, SingI nb, SingI sb, SingI r, ConvertConstraint a b) \n => Fixed a na sa r\n -> Fixed b nb sb r\n convert fa@(Fixed a) = fb\n where \n fb = Fixed b\n b | la <= lb = saturateWithMode fb (fromIntegral a `shift` shiftValue)\n | otherwise = saturateWithMode fb (fromIntegral ((roundWithMode fa la lb a) `shift` shiftValue))\n sa = nbFractionalBits fa\n sb = nbFractionalBits fb \n shiftValue = sb - sa\n la = nbBits a \n lb = nbBits b \n\ninstance Conversion Int32 Int16 where\ninstance Conversion Int16 Int32 where\ninstance Conversion Int40 Int16 where\ninstance Conversion Int64 Int16 where\ninstance Conversion Int16 Int64 where\ninstance Conversion Int16 Int40 where\ninstance Conversion Int32 Int64 where\ninstance Conversion Int64 Int32 where\ninstance Conversion Int32 Int40 where \ninstance Conversion Int40 Int32 where\n\n\ninstance Conversion Word32 Word16 where \ninstance Conversion Word16 Word32 where \ninstance Conversion Word40 Word16 where\ninstance Conversion Word16 Word40 where\n\ninstance Conversion Int16 Int16 where\ninstance Conversion Int32 Int32 where\ninstance Conversion Int40 Int40 where\n\ninstance Conversion Word16 Word16 where\ninstance Conversion Word32 Word32 where\ninstance Conversion Word40 Word40 where\n\n{-# INLINE genericOperator #-}\ngenericOperator :: (SingI s, Bits a, Integral (SuperInt a), Num (BaseValue a), Num (SuperInt a), Integral a, NumberInfo (SuperInt a), NumberInfo a, RawValue a)\n => (SuperInt a -> SuperInt a -> SuperInt a) \n -> Fixed a n s r\n -> Fixed a n s r\n -> Fixed a n s r\ngenericOperator op f@(Fixed a) (Fixed b) = \n let la = (fromIntegral a)\n lb = (fromIntegral b)\n in\n Fixed (saturateWithMode f $ op la lb)\n\n{-# INLINE genericMulOperator #-}\ngenericMulOperator :: (SingI s, SingI n, SingI r, Bits a, Bits (SuperInt a), Integral (SuperInt a), Num (BaseValue a), Num (SuperInt a), Integral a, NumberInfo (SuperInt a), NumberInfo a, RawValue a)\n => Fixed a n s r\n -> Fixed a n s r\n -> Fixed a n s r\ngenericMulOperator f@(Fixed a) (Fixed b) = \n let la = (fromIntegral a)\n lb = (fromIntegral b)\n na = (nbFractionalBits f)\n r = (roundWithMode f (na + na) na (la * lb)) `shiftR` (nbFractionalBits f)\n in\n Fixed (saturateWithMode f $ r)\n\n{-# INLINE genericAbs #-}\ngenericAbs (Fixed a) | a == minBound = Fixed maxBound \n | otherwise = Fixed (abs a)\n\n{-# INLINE genericFromInteger #-}\ngenericFromInteger a = r\n where \n b = a `shiftL` (nbFractionalBits r) \n theMax = maxBound \n theMin = minBound\n r | b > (fromIntegral theMax) = Fixed theMax \n | b < (fromIntegral theMin) = Fixed theMin\n | otherwise = Fixed (fromIntegral b)\n\n{-# INLINE genericProperFraction #-}\ngenericProperFraction f@(Fixed a) = \n let l = nbFractionalBits f \n b = a `shiftR` l \n na = f - fromIntegral b\n in \n (fromIntegral b,na)\n\n{-\n \nFor Random instance\n\n-} \n\n{-# INLINE genericRandomR #-}\ngenericRandomR :: (RandomGen g, Random a, FixedPoint a)\n => (Fixed a n s r, Fixed a n s r) \n -> g \n -> (Fixed a n s r, g) \ngenericRandomR (Fixed mi,Fixed ma) g = \n let (na,ng) = randomR (mi,ma) g \n in \n (fromRawValue na,ng)\n\n{-# INLINE genericRandom #-}\ngenericRandom :: (Random (Fixed a n s r),Bounded (Fixed a n s r), RandomGen g, Random a, FixedPoint a) \n => g \n -> (Fixed a n s r, g)\ngenericRandom g = randomR (minBound, maxBound) g\n\nclass Resolution a where \n smallestValue :: a -> a\n maxValue :: a -> a \n minValue :: a -> a\n signedFormat :: a -> Bool\n bitWidth :: a -> Int\n\n\n#define FIXED_INSTANCES(INT) \\\ninstance NFData (Fixed INT n s r) where {\\\n rnf (Fixed a) = rnf a };\\\ninstance (SingI n, SingI s, SingI r) => Random (Fixed INT n s r) where {\\\n randomR = genericRandomR \\\n; random = genericRandom }; \\\ninstance (SingI n, SingI s, SingI r) => Num (Fixed INT n s r) where {\\\n (+) = genericOperator (+) \\\n; (-) = genericOperator (-) \\\n; abs = genericAbs \\\n; (*) = genericMulOperator \\\n; signum (Fixed a) = Fixed (signum a) \\\n; fromInteger = genericFromInteger}; \\\ninstance (SingI n, SingI s, SingI r) => Bounded (Fixed INT n s r) where {\\\n maxBound = fromRawValue maxBound \\\n; minBound = fromRawValue minBound };\\\ninstance (SingI n, SingI s, SingI r) => Resolution (Fixed INT n s r) where {\\\n smallestValue _ = fromRawValue 1 \\\n; maxValue _ = maxBound \\\n; minValue _ = minBound \\\n; signedFormat a = signed (toRawValue a)\\\n; bitWidth (Fixed a) = nbBits a};\\\ninstance FixedPoint INT where {\\\n fromRawValue = Fixed \\\n; toRawValue (Fixed a) = a}; \\\ninstance (SingI n, SingI s) => HasDoubleRepresentation (Fixed INT n s r) where {\\\n toDouble = genericToDouble \\\n; fromDouble = genericFromDouble}; \\\ninstance (SingI n, SingI s, SingI r) => Fractional (Fixed INT n s r) where {\\\n (/) = genericDiv \\\n; fromRational = genericFromRational}; \\\ninstance (SingI n,SingI s, SingI r) => Real (Fixed INT n s r) where {\\\n toRational = toRational . toDouble }; \\\ninstance (SingI n, SingI s, SingI r) => RealFrac (Fixed INT n s r) where {\\\n properFraction = genericProperFraction }; \\\ninstance (SingI n, SingI s, SingI r) => Floating (Fixed INT n s r) where {\\\n pi = fromDouble pi \\\n; exp = fromDouble . exp . toDouble \\\n; log = fromDouble . log . toDouble \\\n; sin = fromDouble . sin . toDouble \\\n; cos = fromDouble . cos . toDouble \\\n; sinh = fromDouble . sinh . toDouble \\\n; cosh = fromDouble . cosh . toDouble \\\n; asin = fromDouble . asin . toDouble \\\n; acos = fromDouble . acos . toDouble \\\n; atan = fromDouble . atan . toDouble \\\n; asinh = fromDouble . asinh . toDouble \\\n; acosh = fromDouble . acosh . toDouble \\\n; atanh = fromDouble . atanh . toDouble}; \\\ninstance (SingI n, SingI s, SingI r) => RealFloat (Fixed INT n s r) where {\\\n isInfinite = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; isDenormalized = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; isNegativeZero = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; isIEEE = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; isNaN = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; encodeFloat = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; decodeFloat = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; floatRange = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; floatRadix = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; floatDigits = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; exponent = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; significand = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; scaleFloat = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") \\\n; atan2 = error (\"RealFloat has no meaning for a fixed point number and is needed only because of Complex\") };\n\n\n-- RealFloat is only required because Complex a is requiring it of a.\n-- It has no meaning for a fixed point \n-- Which means that some function of Complex caannot be used (like magnitude)\nFIXED_INSTANCES(Int16)\nFIXED_INSTANCES(Int32)\nFIXED_INSTANCES(Int40)\nFIXED_INSTANCES(Int64)\nFIXED_INSTANCES(Int128)\n\nFIXED_INSTANCES(Word16)\nFIXED_INSTANCES(Word32)\nFIXED_INSTANCES(Word40)\nFIXED_INSTANCES(Word64)\n\ninstance (SingI n, Integral a) => Show (Fixed a n s r) where \n show f@(Fixed a) = \n let fp = nbFractionalBits f \n fr = 2**(- fromIntegral fp) :: Double\n in \n printf (\"%f\") ((fromIntegral a)*fr)\n\n{-# INLINE withSaturation #-}\nwithSaturation :: Fixed n s sa r -> Fixed n s Sat r\nwithSaturation (Fixed a) = Fixed a \n\n{-# INLINE withoutSaturation #-}\nwithoutSaturation :: Fixed n s sa r -> Fixed n s Unsat r\nwithoutSaturation (Fixed a) = Fixed a \n\n{-# INLINE withRounding #-}\nwithRounding :: Fixed n s sa r -> Fixed n s sa RO\nwithRounding (Fixed a) = Fixed a \n\n{-# INLINE withNoRounding #-}\nwithNoRounding :: Fixed n s sa r -> Fixed n s sa NR\nwithNoRounding (Fixed a) = Fixed a \n\n{-# INLINE genericDiv #-}\ngenericDiv :: (SingI n, SingI s, Bits a, NumberInfo (SuperInt a), NumberInfo a, RawValue a, Num (BaseValue a), Integral a, Bits (SuperInt a),Integral (SuperInt a), Num (SuperInt a)) \n => Fixed a n s r \n -> Fixed a n s r \n -> Fixed a n s r \ngenericDiv f@(Fixed a) (Fixed b) = \n let la = (fromIntegral a) \n lb = (fromIntegral b)\n (q,_) = (la `shiftL` (nbFractionalBits f)) `quotRem` lb\n result = q\n in\n Fixed (saturateWithMode f $ result)\n\n{-# INLINE genericFromRational #-}\ngenericFromRational r = fromDouble (fromRational r)\n\nclass FixedPoint a where\n fromRawValue :: a -> Fixed a n s r \n toRawValue :: Fixed a n s r -> a\n\n{-# INLINE genericFromDouble #-}\ngenericFromDouble :: (SingI n, SingI sa, Bits a, Integral (SuperInt a), FixedPoint a, Num a, Num (BaseValue a), Integral a, NumberInfo (SuperInt a), NumberInfo a, RawValue a) \n => Double \n -> Fixed a n sa r\ngenericFromDouble a = let la = saturateWithMode ra (floor (a * 2**(fromIntegral $ nbFractionalBits ra)))\n ra = fromRawValue la\n in \n ra\n\n{-# INLINE genericToDouble #-}\ngenericToDouble :: (SingI n, Integral a) => Fixed a n s r -> Double \ngenericToDouble f@(Fixed a) = fromIntegral a * 2**(- fromIntegral (nbFractionalBits f))\n\n\n", "meta": {"hexsha": "e01037304e9a8bbe496d58648582b0abb1708499", "size": 17249, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Fixed.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": "Fixed.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": "Fixed.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": 35.6384297521, "max_line_length": 209, "alphanum_fraction": 0.6460664386, "num_tokens": 4782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5276042632577402}} {"text": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveGeneric #-}\n\nmodule Lib\n ( genImage\n , ViewPort(..)\n ) where\n\nimport Codec.Picture\nimport Codec.Picture.Types\nimport Data.Fixed (mod')\nimport Data.Word (Word8)\nimport Data.Array\nimport Data.Hashable\nimport Data.Complex\nimport Control.Parallel.Strategies\nimport GHC.Generics\n\ndata ViewPort = ViewPort { _centerX :: Double \n , _centerY :: Double\n , _magnification :: Double\n , _maxIterations :: Int\n , _rotation :: Double\n , _superScaling :: Int\n } deriving (Eq, Show, Generic)\n \ninstance Hashable ViewPort\n \ngenImage :: Int -> Int -> ViewPort -> DynamicImage\ngenImage w h v = ImageRGB8 $ generateImage (renderImage v w h) w h\n\nrenderImage :: ViewPort -> Int -> Int -> (Int -> Int -> PixelRGB8)\nrenderImage (ViewPort cx cy mg mi _ s) w h = \n let aspectRatio = fromIntegral w / fromIntegral h :: Double\n (rw, rh) = if aspectRatio <= 4.0 / 3.0 then (4.0 / mg, 4.0 / mg / aspectRatio)\n else (3.0 / mg * aspectRatio, 3.0 / mg)\n f x y = let ps = [(x * s + ix, y * s + iy) | ix <- [0..s-1], iy <- [0..s-1]]\n r x' = cx - (rw / 2.0) + ((fromIntegral x' + 0.5) / fromIntegral (w * s) :: Double) * rw\n i y' = cy - (rh / 2.0) + ((fromIntegral y' + 0.5) / fromIntegral (h * s) :: Double) * rh\n rs = fmap (\\(x', y') -> (r x', i y')) ps\n qs = fmap (\\(r0, i0) -> color (fastRender (realToFrac r0 :+ realToFrac i0) mi)) rs\n (rc, gc, bc) = foldr (\\(PixelRGB8 r g b) (rc :: Int, gc :: Int, bc :: Int) -> (rc + fromIntegral r, gc + fromIntegral g, bc + fromIntegral b)) (0, 0, 0) qs\n in PixelRGB8 (fromIntegral (rc `div` (s*s))) (fromIntegral (gc `div` (s*s))) (fromIntegral (bc `div` (s*s))) \n in f\n\nmag2 :: (RealFloat a, Num a) => Complex a -> a\nmag2 (r :+ i) = r*r + i*i\n\nrender :: (RealFloat a, Num a) => Complex a -> Int -> Maybe (Complex a, Int)\nrender c maxI = loop (0 :+ 0) 0\n where loop z i = if mag2 z <= 4 && i <= maxI\n then loop (step z) (i + 1)\n else if i < maxI\n then Just (step $ step z, i)\n else Nothing\n step z = z*z + c\n\nfastRender :: (RealFloat a, Num a) => Complex a -> Int -> Maybe (Complex a, Int)\nfastRender c maxI = fastLoop (0 :+ 0) 0\n where fastLoop z i = let zn = (step . step . step . step . step . step . step . step) z\n in if mag2 zn <= 4 && (i + 8) <= maxI\n then fastLoop zn (i + 8)\n else slowLoop z i\n slowLoop z i = if mag2 z <= 4 && i <= maxI\n then slowLoop (step z) (i + 1)\n else if i < maxI\n then Just (step $ step z, i)\n else Nothing\n step z = z*z + c\n\ncolor :: (RealFloat a, Num a) => Maybe (Complex a, Int) -> PixelRGB8\ncolor Nothing = PixelRGB8 0 0 0\ncolor (Just (z, i)) = let mu = ((fromIntegral (i + 1)) - (logBase 2 . log . mag2) z) / 80.0\n frac = snd (properFraction mu)\n in getColor $ if frac < 0 then frac + 1.0 else frac\n{-\nrenderPoint :: Double -- ^ The real coordinate\n -> Double -- ^ The imaginary coordinate\n -> Int -- ^ The max iterations\n -> PixelRGB8 -- ^ The resulting pixel\nrenderPoint r0 i0 mi = case loop (0, 0) 0 of\n Left (p, iter) -> let (r2, i2) = step . step $ p\n mu = ((fromIntegral (iter + 1)) - (logBase 2 . log) (r2 * r2 + i2 * i2)) / 80.0\n frac = snd (properFraction mu)\n in getColor $ if frac < 0 then frac + 1.0 else frac\n Right _ -> PixelRGB8 0 0 0\n where loop (r, i) iter = if r*r + i*i <= 4 && iter <= mi\n then loop (step (r, i)) (iter + 1)\n else if iter < mi\n then Left ((r, i), iter)\n else Right ()\n step (r, i) = (r*r - i*i + r0, 2*r*i + i0)\n-}\n\npalette :: (RealFloat a, Num a) => [(a, PixelRGB8)]\npalette = [ (0.0, PixelRGB8 0 7 100)\n , (0.16, PixelRGB8 32 107 203)\n , (0.42, PixelRGB8 237 255 255)\n , (0.6425, PixelRGB8 255 170 0)\n , (0.8575, PixelRGB8 0 2 0)\n , (1.0, PixelRGB8 0 7 100)\n ]\n\ngetColor :: (RealFloat a, Num a) => a -> PixelRGB8\ngetColor f = let ((li, (PixelRGB8 lr lg lb)), (ri, (PixelRGB8 rr rg rb))) = pair palette\n index = (f - li) / (ri - li)\n index2 = index * index\n index3 = index * index2\n r = fromIntegral . floor $ (2.0 * (fromIntegral lr - fromIntegral rr) * index3) - (3.0 * (fromIntegral lr - fromIntegral rr) * index2) + fromIntegral lr\n g = fromIntegral . floor $ (2.0 * (fromIntegral lg - fromIntegral rg) * index3) - (3.0 * (fromIntegral lg - fromIntegral rg) * index2) + fromIntegral lg\n b = fromIntegral . floor $ (2.0 * (fromIntegral lb - fromIntegral rb) * index3) - (3.0 * (fromIntegral lb - fromIntegral rb) * index2) + fromIntegral lb\n in PixelRGB8 r g b\n where pair (c:cs) = if f >= fst (head cs) then pair cs else (c, head cs)", "meta": {"hexsha": "fb3d53673d1e2fd4e2e62046a9f428676c1607f3", "size": 5650, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "micahhahn/DeepBlue", "max_stars_repo_head_hexsha": "6f42c598c95203b4afcd3428545f9cd74fc8e740", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-20T21:48:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-19T10:50:49.000Z", "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "micahhahn/DeepBlue", "max_issues_repo_head_hexsha": "6f42c598c95203b4afcd3428545f9cd74fc8e740", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lib.hs", "max_forks_repo_name": "micahhahn/DeepBlue", "max_forks_repo_head_hexsha": "6f42c598c95203b4afcd3428545f9cd74fc8e740", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.0, "max_line_length": 175, "alphanum_fraction": 0.4755752212, "num_tokens": 1653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.527602746464867}} {"text": "{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Numeric.LinearAlgebra\nimport Control.Monad\nimport Control.Monad.Random\nimport Control.Applicative (liftA2)\n\n\n\ndata Weights = W { wBiases :: !(Vector Double) -- n\n , wNodes :: !(Matrix Double) -- n x m\n } -- \"m to n\" layer\n\ndata Network :: * where\n O :: !Weights -> Network\n (:~) :: !Weights -> !Network -> Network\n\ninfixr 5 :~\n\n-- | Generate random weights.\n\nrandomWeights :: MonadRandom m => Int -> Int -> m Weights\nrandomWeights i o = do\n seed1 :: Int <- getRandom\n seed2 :: Int <- getRandom\n let wB = randomVector seed1 Uniform o\n wN = uniformSample seed2 o (replicate i (-1, 1))\n return $ W wB wN\n\n-- | Generate a random Network\nrandomNet :: MonadRandom m => Int -> [Int] -> Int -> m Network\nrandomNet i [] o = O <$> randomWeights i o\nrandomNet i (h:hs) o = liftA2 (:~) (randomWeights i h) (randomNet i hs o)\n\n-- | Relu function\nrelu :: (Floating a, Ord a) => a -> a\nrelu = max 0\n\nrelu' :: (Floating a, Ord a) => a -> a\nrelu' x | x < 0 = 0\n | otherwise = 1\n\ntrain :: Double -> Vector Double -> Vector Double -> Network -> Network\ntrain = undefined\n", "meta": {"hexsha": "57e73c47a370af6d06e894890a4f408ef1813c50", "size": 1297, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NeuralNet.hs", "max_stars_repo_name": "Lockne/neural-network-from-scratch", "max_stars_repo_head_hexsha": "66d5666e75ebe2f43d91ad458b613fe06d276fe4", "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/NeuralNet.hs", "max_issues_repo_name": "Lockne/neural-network-from-scratch", "max_issues_repo_head_hexsha": "66d5666e75ebe2f43d91ad458b613fe06d276fe4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NeuralNet.hs", "max_forks_repo_name": "Lockne/neural-network-from-scratch", "max_forks_repo_head_hexsha": "66d5666e75ebe2f43d91ad458b613fe06d276fe4", "max_forks_repo_licenses": ["BSD-3-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.4693877551, "max_line_length": 73, "alphanum_fraction": 0.6044718581, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.527087397531734}} {"text": "{-# LANGUAGE ConstraintKinds, DataKinds, FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses, NoImplicitPrelude, PolyKinds #-}\n{-# LANGUAGE QuasiQuotes, TemplateHaskell #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults #-}\nmodule Main (module Algebra.Algorithms.Groebner, module Algebra.Prelude\n , module Main\n ) where\nimport Algebra.Algorithms.Groebner\nimport Algebra.Algorithms.ZeroDim\nimport Algebra.Ring.Ideal\nimport Algebra.Ring.Polynomial.Quotient\nimport Algebra.Prelude\nimport Control.Monad.Random hiding (fromList)\nimport Data.Complex\nimport Data.Convertible\nimport Data.List (find, nub, partition, sortBy)\nimport qualified Data.Matrix as M\nimport qualified Data.Sized as SV\nimport qualified Data.Vector as V\nimport Debug.Trace\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Prelude as P\n\ntr :: Show a => a -> a\ntr a = trace (show a) a\n\nx, y, z :: Polynomial (Fraction Integer) 3\n[x, y, z] = vars\n\nseed :: Polynomial (Fraction Integer) 3\nseed = -412742019532366985 * x -7641395389638504101 * y + 4362835172800530323 * z\n\nseedMat :: LA.Matrix Double\nseedMat = LA.fromLists $ map (map toDouble) $ reifyQuotient eqn02 $ \\pxy -> matrixRep (modIdeal' pxy seed)\n\ntoDouble :: Fractional a => Fraction Integer -> a\ntoDouble rat = fromIntegral (numerator rat) P./ fromIntegral (denominator rat)\n\nfromRight :: Either t t1 -> t1\nfromRight (Right a) = a\nfromRight _ = error \"fromRight\"\n\nprintLvl :: Show a => Int -> a -> IO ()\nprintLvl lvl = putStrLn . unlines . map (replicate lvl '\\t' ++) . lines . show\n\neqn01 :: Ideal (Polynomial (Fraction Integer) 3)\neqn01 = toIdeal [x^2 - 2*x*z + 5, x*y^2+y*z+1, 3*y^2 - 8*x*z]\n\neqn02 :: Ideal (Polynomial (Fraction Integer) 3)\neqn02 =\n toIdeal [x^2 + 2*y^2 - y - 2*z\n ,x^2 - 8*y^2 + 10*z - 1\n ,x^2 - 7*y*z\n ]\n\neqn03 :: Ideal (Polynomial (Fraction Integer) 3)\neqn03 = toIdeal [x^2 + y^2 + z^2 - 2*x\n ,x^3 - y*z - x\n ,x - y + 2*z\n ]\n\njdeal :: Ideal (Polynomial (Fraction Integer) 3)\njdeal = toIdeal [x*y + z - x*z, x^2 - z, 2*x^3 - x^2 * y * z - 1]\n\n\nvs :: [V.Vector (Fraction Integer)]\nvs = reifyQuotient eqn03 $ \\pxy -> map (vectorRep . modIdeal' pxy) [var 0 ^ i | i <- [0..6::Natural]]\n\nmat :: M.Matrix (Fraction Integer)\nmat = fromCols $ take 4 vs\n\nfromCols :: [V.Vector a] -> M.Matrix a\nfromCols = foldr1 (M.<|>) . map M.colVector\n\nfindUnivar :: (CoeffRing r, IsMonomialOrder n ord, KnownNat n)\n => OrderedPolynomial r ord n -> Maybe (Ordinal n)\nfindUnivar poly =\n let os = enumOrdinal (sArity' poly)\n ms = map snd $ getTerms poly\n in find (\\a -> all (`isPowerOf` (leadingMonomial (var a `asTypeOf` poly))) ms) os\n\ntoCoeffList :: (CoeffRing r, KnownNat n, IsMonomialOrder n ord) => Ordinal n -> OrderedPolynomial r ord n -> [r]\ntoCoeffList on f =\n let v = var on `asTypeOf` f\n in [ coeff (leadingMonomial $ v ^ i) f | i <- [0.. fromIntegral (totalDegree' f)]]\n\nshowSols :: (KnownNat n, IsMonomialOrder n order, Convertible a Double)\n => Double -> Ideal (OrderedPolynomial a order n) -> [Sized n1 (Complex Double)] -> IO ()\nshowSols err eqn sols = do\n let (rs, is) = partition (all ((> putStr \"\\terror: \">> print (maximum $ subs a b c)\n putStrLn $ \"- \" ++ show (length rs) ++ \" real solution(s):\"\n mapM_ showCase $ sortBy (comparing $ map magnitude) rs\n putStrLn $ \"- \" ++ show (length is) ++ \" imaginary solution(s):\"\n mapM_ showCase $ sortBy (comparing $ map magnitude) is\n let errs = concatMap (\\ [a,b,c] -> subs a b c) $ rs ++ is\n putStrLn $ \"- maximum error: \" ++ show (maximum errs)\n putStrLn $ \"- minimum error: \" ++ show (minimum errs)\n putStrLn $ \"- average error: \" ++ show (sum errs P./ fromIntegral (length errs))\n\nmain :: IO ()\nmain = do\n putStrLn \"---- solving equation system\"\n let err = 1e-10\n putStrLn \"< naive method\"\n showSols err eqn01 $ solve' err eqn01\n putStrLn \"\\n< randomized method\"\n showSols err eqn01 =<< evalRandIO (solveM eqn01)\n putStrLn \"\\n< companion characteristics\"\n showSols err eqn01 $ solveViaCompanion err eqn01\n putStrLn \"\\n< univariate spanning\"\n showSols err eqn01 $ solve' err eqn01\n\n putStrLn \"\\n\\n---- exercise 8\"\n putStrLn \"< Solving 1-6\"\n putStrLn \"< Naive Method: \"\n showSols err eqn02 $ nub $ solve' err eqn02\n putStrLn \"\\n< new method\"\n showSols err eqn02 =<< evalRandIO (solveM eqn02)\n\n putStrLn \"\\n< Solving 1-7\"\n putStrLn \"< Naive Method: \"\n showSols err eqn03 $ nub $ solve' err eqn03\n putStrLn \"\\n< new method\"\n showSols err eqn03 =<< evalRandIO (solveM eqn03)\n putStrLn \"\\n\\n---- FGLM Algorithm\"\n print $ fglm jdeal\n print $ calcGroebnerBasisWith Lex jdeal\n print $ univPoly 0 jdeal\n print $ univPoly 1 jdeal\n print $ univPoly 2 jdeal\n return ()\n\nsubstIdeal :: IsMonomialOrder 3 order\n => [OrderedPolynomial (Fraction Integer) Grevlex 3]\n -> Ideal (OrderedPolynomial (Fraction Integer) order 3)\n -> Ideal (OrderedPolynomial (Fraction Integer) Grevlex 3)\nsubstIdeal = mapIdeal . substWith (.*.) . SV.unsafeFromList'\n\ntoComplex :: Convertible r Double => r -> Complex Double\ntoComplex = (:+ 0) . convert\n", "meta": {"hexsha": "f22ee24b8c3dccf800a01a65925fed924baecce7", "size": 5617, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "computational-algebra/examples/solve.hs", "max_stars_repo_name": "hangingman/computational-algebra", "max_stars_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2015-02-09T01:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T04:37:09.000Z", "max_issues_repo_path": "computational-algebra/examples/solve.hs", "max_issues_repo_name": "hangingman/computational-algebra", "max_issues_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-09-18T16:31:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T08:28:37.000Z", "max_forks_repo_path": "computational-algebra/examples/solve.hs", "max_forks_repo_name": "hangingman/computational-algebra", "max_forks_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-12-22T16:04:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T19:35:53.000Z", "avg_line_length": 38.7379310345, "max_line_length": 113, "alphanum_fraction": 0.6254228236, "num_tokens": 1689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5267289305502562}} {"text": "{-# LANGUAGE MultiParamTypeClasses #-}\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 log normal distribution. This is a continuous probability\n-- distribution that describes data whose log is clustered around a\n-- mean. For example, the multiplicative product of many independent\n-- positive random variables.\n\nmodule Statistics.Distribution.Lognormal\n (\n LognormalDistribution\n -- * Constructors\n , lognormalDistr\n , lognormalDistrErr\n , lognormalDistrMeanStddevErr\n , lognormalStandard\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_huge, m_sqrt_2_pi)\nimport Numeric.SpecFunctions (expm1, log1p)\nimport qualified Data.Vector.Generic as G\n\nimport qualified Statistics.Distribution as D\nimport qualified Statistics.Distribution.Normal as N\nimport Statistics.Internal\n\n\n-- | The lognormal distribution.\nnewtype LognormalDistribution = LND N.NormalDistribution\n deriving (Eq, Typeable, Data, Generic)\n\ninstance Show LognormalDistribution where\n showsPrec i (LND d) = defaultShow2 \"lognormalDistr\" m s i\n where\n m = D.mean d\n s = D.stdDev d\ninstance Read LognormalDistribution where\n readPrec = defaultReadPrecM2 \"lognormalDistr\" $\n (either (const Nothing) Just .) . lognormalDistrErr\n\ninstance ToJSON LognormalDistribution\ninstance FromJSON LognormalDistribution\n\ninstance Binary LognormalDistribution where\n put (LND d) = put m >> put s\n where\n m = D.mean d\n s = D.stdDev d\n get = do\n m <- get\n sd <- get\n either fail return $ lognormalDistrErr m sd\n\ninstance D.Distribution LognormalDistribution where\n cumulative = cumulative\n complCumulative = complCumulative\n\ninstance D.ContDistr LognormalDistribution where\n logDensity = logDensity\n quantile = quantile\n complQuantile = complQuantile\n\ninstance D.MaybeMean LognormalDistribution where\n maybeMean = Just . D.mean\n\ninstance D.Mean LognormalDistribution where\n mean (LND d) = exp (m + v / 2)\n where\n m = D.mean d\n v = D.variance d\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 d) = expm1 v * exp (2 * m + v)\n where\n m = D.mean d\n v = D.variance d\n\ninstance D.Entropy LognormalDistribution where\n entropy (LND d) = logBase 2 (s * exp (m + 0.5) * m_sqrt_2_pi)\n where\n m = D.mean d\n s = D.stdDev d\n\ninstance D.MaybeEntropy LognormalDistribution where\n maybeEntropy = Just . D.entropy\n\ninstance D.ContGen LognormalDistribution where\n genContVar d = D.genContinuous d\n\n-- | Standard log normal distribution with mu 0 and sigma 1.\n--\n-- Mean is @sqrt e@ and variance is @(e - 1) * e@.\nlognormalStandard :: LognormalDistribution\nlognormalStandard = LND N.standard\n\n-- | Create log normal distribution from parameters.\nlognormalDistr\n :: Double -- ^ Mu\n -> Double -- ^ Sigma\n -> LognormalDistribution\nlognormalDistr mu sig = either error id $ lognormalDistrErr mu sig\n\n-- | Create log normal distribution from parameters.\nlognormalDistrErr\n :: Double -- ^ Mu\n -> Double -- ^ Sigma\n -> Either String LognormalDistribution\nlognormalDistrErr mu sig\n | sig >= sqrt (log m_huge - 2 * mu) = Left $ errMsg mu sig\n | otherwise = LND <$> N.normalDistrErr mu sig\n\nerrMsg :: Double -> Double -> String\nerrMsg mu sig =\n \"Statistics.Distribution.Lognormal.lognormalDistr: sigma must be > 0 && < \"\n ++ show lim ++ \". Got \" ++ show sig\n where lim = sqrt (log m_huge - 2 * mu)\n\n-- | Create log normal distribution from mean and standard deviation.\nlognormalDistrMeanStddevErr\n :: Double -- ^ Mu\n -> Double -- ^ Sigma\n -> Either String LognormalDistribution\nlognormalDistrMeanStddevErr m sd = LND <$> N.normalDistrErr mu sig\n where r = sd / m\n sig2 = log1p (r * r)\n sig = sqrt sig2\n mu = log m - sig2 / 2\n\n-- | Variance is estimated using maximum likelihood method\n-- (biased estimation) over the log of the data.\n--\n-- Returns @Nothing@ if sample contains less than one element or\n-- variance is zero (all elements are equal)\ninstance D.FromSample LognormalDistribution Double where\n fromSample = fmap LND . D.fromSample . G.map log\n\nlogDensity :: LognormalDistribution -> Double -> Double\nlogDensity (LND d) x\n | x > 0 = let lx = log x in D.logDensity d lx - lx\n | otherwise = 0\n\ncumulative :: LognormalDistribution -> Double -> Double\ncumulative (LND d) x\n | x > 0 = D.cumulative d $ log x\n | otherwise = 0\n\ncomplCumulative :: LognormalDistribution -> Double -> Double\ncomplCumulative (LND d) x\n | x > 0 = D.complCumulative d $ log x\n | otherwise = 1\n\nquantile :: LognormalDistribution -> Double -> Double\nquantile (LND d) = exp . D.quantile d\n\ncomplQuantile :: LognormalDistribution -> Double -> Double\ncomplQuantile (LND d) = exp . D.complQuantile d\n", "meta": {"hexsha": "87d917c2d49da5af40da9efccca3a968d88ebaf8", "size": 5252, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Lognormal.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/Lognormal.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/Lognormal.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": 30.3583815029, "max_line_length": 77, "alphanum_fraction": 0.7022086824, "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5266513456754215}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n{-# OPTIONS_GHC -fno-warn-missing-methods #-}\n\n{- |\nModule : Internal.Modular\nCopyright : (c) Alberto Ruiz 2015\nLicense : BSD3\nStability : experimental\n\nProof of concept of statically checked modular arithmetic.\n\n-}\n\nmodule Internal.Modular(\n Mod, type (./.)\n) where\n\nimport Internal.Vector\nimport Internal.Matrix hiding (size)\nimport Internal.Numeric\nimport Internal.Element\nimport Internal.Container\nimport Internal.Vectorized (prodI,sumI,prodL,sumL)\nimport Internal.LAPACK (multiplyI, multiplyL)\nimport Internal.Algorithms(luFact,LU(..))\nimport Internal.Util(Normed(..),Indexable(..),\n gaussElim, gaussElim_1, gaussElim_2,\n luST, luSolve', luPacked', magnit, invershur)\nimport Internal.ST(mutable)\n#if MIN_VERSION_base(4,11,0)\nimport GHC.TypeLits hiding (Mod)\n#else\nimport GHC.TypeLits\n#endif\nimport Data.Proxy(Proxy)\nimport Foreign.ForeignPtr(castForeignPtr)\nimport Foreign.Storable\nimport Data.Ratio\nimport Data.Complex\nimport Control.DeepSeq ( NFData(..) )\n#if MIN_VERSION_base(4,11,0)\nimport Prelude hiding ((<>))\n#endif\n\n\n-- | Wrapper with a phantom integer for statically checked modular arithmetic.\nnewtype Mod (n :: Nat) t = Mod {unMod:: t}\n deriving (Storable)\n\ninstance (NFData t) => NFData (Mod n t)\n where\n rnf (Mod x) = rnf x\n\ninfixr 5 ./.\ntype (./.) x n = Mod n x\n\ninstance (Integral t, Enum t, KnownNat m) => Enum (Mod m t)\n where\n toEnum = l0 (\\m x -> fromIntegral $ x `mod` (fromIntegral m))\n fromEnum = fromIntegral . unMod\n\ninstance (Eq t, KnownNat m) => Eq (Mod m t)\n where\n a == b = (unMod a) == (unMod b)\n\ninstance (Ord t, KnownNat m) => Ord (Mod m t)\n where\n compare a b = compare (unMod a) (unMod b)\n\ninstance (Integral t, Real t, KnownNat m, Integral (Mod m t)) => Real (Mod m t)\n where\n toRational x = toInteger x % 1\n\ninstance (Integral t, KnownNat m, Num (Mod m t)) => Integral (Mod m t)\n where\n toInteger = toInteger . unMod\n quotRem a b = (Mod q, Mod r)\n where\n (q,r) = quotRem (unMod a) (unMod b)\n\n-- | this instance is only valid for prime m\ninstance (Show (Mod m t), Num (Mod m t), Eq t, KnownNat m) => Fractional (Mod m t)\n where\n recip x\n | x*r == 1 = r\n | otherwise = error $ show x ++\" does not have a multiplicative inverse mod \"++show m'\n where\n r = x^(m'-2 :: Integer)\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n fromRational x = fromInteger (numerator x) / fromInteger (denominator x)\n\nl2 :: forall m a b c. (Num c, KnownNat m) => (c -> a -> b -> c) -> Mod m a -> Mod m b -> Mod m c\nl2 f (Mod u) (Mod v) = Mod (f m' u v)\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n\nl1 :: forall m a b . (Num b, KnownNat m) => (b -> a -> b) -> Mod m a -> Mod m b\nl1 f (Mod u) = Mod (f m' u)\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n\nl0 :: forall m a b . (Num b, KnownNat m) => (b -> a -> b) -> a -> Mod m b\nl0 f u = Mod (f m' u)\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n\n\ninstance Show t => Show (Mod n t)\n where\n show = show . unMod\n\ninstance (Integral t, KnownNat n) => Num (Mod n t)\n where\n (+) = l2 (\\m a b -> (a + b) `mod` (fromIntegral m))\n (*) = l2 (\\m a b -> (a * b) `mod` (fromIntegral m))\n (-) = l2 (\\m a b -> (a - b) `mod` (fromIntegral m))\n abs = l1 (const abs)\n signum = l1 (const signum)\n fromInteger = l0 (\\m x -> fromInteger x `mod` (fromIntegral m))\n\n\ninstance KnownNat m => Element (Mod m I)\n where\n constantD x n = i2f (constantD (unMod x) n)\n extractR ord m mi is mj js = i2fM <$> extractR ord (f2iM m) mi is mj js\n setRect i j m x = setRect i j (f2iM m) (f2iM x)\n sortI = sortI . f2i\n sortV = i2f . sortV . f2i\n compareV u v = compareV (f2i u) (f2i v)\n selectV c l e g = i2f (selectV c (f2i l) (f2i e) (f2i g))\n remapM i j m = i2fM (remap i j (f2iM m))\n rowOp c a i1 i2 j1 j2 x = rowOpAux (c_rowOpMI m') c (unMod a) i1 i2 j1 j2 (f2iM x)\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n gemm u a b c = gemmg (c_gemmMI m') (f2i u) (f2iM a) (f2iM b) (f2iM c)\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n\ninstance KnownNat m => Element (Mod m Z)\n where\n constantD x n = i2f (constantD (unMod x) n)\n extractR ord m mi is mj js = i2fM <$> extractR ord (f2iM m) mi is mj js\n setRect i j m x = setRect i j (f2iM m) (f2iM x)\n sortI = sortI . f2i\n sortV = i2f . sortV . f2i\n compareV u v = compareV (f2i u) (f2i v)\n selectV c l e g = i2f (selectV c (f2i l) (f2i e) (f2i g))\n remapM i j m = i2fM (remap i j (f2iM m))\n rowOp c a i1 i2 j1 j2 x = rowOpAux (c_rowOpML m') c (unMod a) i1 i2 j1 j2 (f2iM x)\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n gemm u a b c = gemmg (c_gemmML m') (f2i u) (f2iM a) (f2iM b) (f2iM c)\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n\n\ninstance KnownNat m => CTrans (Mod m I)\ninstance KnownNat m => CTrans (Mod m Z)\n\n\ninstance KnownNat m => Container Vector (Mod m I)\n where\n conj' = id\n size' = dim\n scale' s x = vmod (scale (unMod s) (f2i x))\n addConstant c x = vmod (addConstant (unMod c) (f2i x))\n add' a b = vmod (add' (f2i a) (f2i b))\n sub a b = vmod (sub (f2i a) (f2i b))\n mul a b = vmod (mul (f2i a) (f2i b))\n equal u v = equal (f2i u) (f2i v)\n scalar' x = fromList [x]\n konst' x = i2f . konst (unMod x)\n build' n f = build n (fromIntegral . f)\n cmap' = mapVector\n atIndex' x k = fromIntegral (atIndex (f2i x) k)\n minIndex' = minIndex . f2i\n maxIndex' = maxIndex . f2i\n minElement' = Mod . minElement . f2i\n maxElement' = Mod . maxElement . f2i\n sumElements' = fromIntegral . sumI m' . f2i\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n prodElements' = fromIntegral . prodI m' . f2i\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n step' = i2f . step . f2i\n find' = findV\n assoc' = assocV\n accum' = accumV\n ccompare' a b = ccompare (f2i a) (f2i b)\n cselect' c l e g = i2f $ cselect c (f2i l) (f2i e) (f2i g)\n scaleRecip s x = scale' s (cmap recip x)\n divide x y = mul x (cmap recip y)\n arctan2' = undefined\n cmod' m = vmod . cmod' (unMod m) . f2i\n fromInt' = vmod\n toInt' = f2i\n fromZ' = vmod . fromZ'\n toZ' = toZ' . f2i\n\ninstance KnownNat m => Container Vector (Mod m Z)\n where\n conj' = id\n size' = dim\n scale' s x = vmod (scale (unMod s) (f2i x))\n addConstant c x = vmod (addConstant (unMod c) (f2i x))\n add' a b = vmod (add' (f2i a) (f2i b))\n sub a b = vmod (sub (f2i a) (f2i b))\n mul a b = vmod (mul (f2i a) (f2i b))\n equal u v = equal (f2i u) (f2i v)\n scalar' x = fromList [x]\n konst' x = i2f . konst (unMod x)\n build' n f = build n (fromIntegral . f)\n cmap' = mapVector\n atIndex' x k = fromIntegral (atIndex (f2i x) k)\n minIndex' = minIndex . f2i\n maxIndex' = maxIndex . f2i\n minElement' = Mod . minElement . f2i\n maxElement' = Mod . maxElement . f2i\n sumElements' = fromIntegral . sumL m' . f2i\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n prodElements' = fromIntegral . prodL m' . f2i\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n step' = i2f . step . f2i\n find' = findV\n assoc' = assocV\n accum' = accumV\n ccompare' a b = ccompare (f2i a) (f2i b)\n cselect' c l e g = i2f $ cselect c (f2i l) (f2i e) (f2i g)\n scaleRecip s x = scale' s (cmap recip x)\n divide x y = mul x (cmap recip y)\n arctan2' = undefined\n cmod' m = vmod . cmod' (unMod m) . f2i\n fromInt' = vmod . fromInt'\n toInt' = toInt . f2i\n fromZ' = vmod\n toZ' = f2i\n\n\ninstance (Storable t, Indexable (Vector t) t) => Indexable (Vector (Mod m t)) (Mod m t)\n where\n (!) = (@>)\n\ntype instance RealOf (Mod n I) = I\ntype instance RealOf (Mod n Z) = Z\n\ninstance KnownNat m => Product (Mod m I) where\n norm2 = undefined\n absSum = undefined\n norm1 = undefined\n normInf = undefined\n multiply = lift2m (multiplyI m')\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n\ninstance KnownNat m => Product (Mod m Z) where\n norm2 = undefined\n absSum = undefined\n norm1 = undefined\n normInf = undefined\n multiply = lift2m (multiplyL m')\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n\ninstance KnownNat m => Normed (Vector (Mod m I))\n where\n norm_0 = norm_0 . toInt\n norm_1 = norm_1 . toInt\n norm_2 = norm_2 . toInt\n norm_Inf = norm_Inf . toInt\n\ninstance KnownNat m => Normed (Vector (Mod m Z))\n where\n norm_0 = norm_0 . toZ\n norm_1 = norm_1 . toZ\n norm_2 = norm_2 . toZ\n norm_Inf = norm_Inf . toZ\n\n\ninstance KnownNat m => Numeric (Mod m I)\ninstance KnownNat m => Numeric (Mod m Z)\n\ni2f :: Storable t => Vector t -> Vector (Mod n t)\ni2f v = unsafeFromForeignPtr (castForeignPtr fp) (i) (n)\n where (fp,i,n) = unsafeToForeignPtr v\n\nf2i :: Storable t => Vector (Mod n t) -> Vector t\nf2i v = unsafeFromForeignPtr (castForeignPtr fp) (i) (n)\n where (fp,i,n) = unsafeToForeignPtr v\n\nf2iM :: (Element t, Element (Mod n t)) => Matrix (Mod n t) -> Matrix t\nf2iM m = m { xdat = f2i (xdat m) }\n\ni2fM :: (Element t, Element (Mod n t)) => Matrix t -> Matrix (Mod n t)\ni2fM m = m { xdat = i2f (xdat m) }\n\nvmod :: forall m t. (KnownNat m, Storable t, Integral t, Numeric t) => Vector t -> Vector (Mod m t)\nvmod = i2f . cmod' m'\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m)\n\nlift1 f a = vmod (f (f2i a))\nlift2 f a b = vmod (f (f2i a) (f2i b))\n\nlift2m f a b = liftMatrix vmod (f (f2iM a) (f2iM b))\n\ninstance KnownNat m => Num (Vector (Mod m I))\n where\n (+) = lift2 (+)\n (*) = lift2 (*)\n (-) = lift2 (-)\n abs = lift1 abs\n signum = lift1 signum\n negate = lift1 negate\n fromInteger x = fromInt (fromInteger x)\n\ninstance KnownNat m => Num (Vector (Mod m Z))\n where\n (+) = lift2 (+)\n (*) = lift2 (*)\n (-) = lift2 (-)\n abs = lift1 abs\n signum = lift1 signum\n negate = lift1 negate\n fromInteger x = fromZ (fromInteger x)\n\n--------------------------------------------------------------------------------\n\ninstance (KnownNat m) => Testable (Matrix (Mod m I))\n where\n checkT _ = test\n\ntest = (ok, info)\n where\n v = fromList [3,-5,75] :: Vector (Mod 11 I)\n m = (3><3) [1..] :: Matrix (Mod 11 I)\n\n a = (3><3) [1,2 , 3\n ,4,5 , 6\n ,0,10,-3] :: Matrix I\n\n b = (3><2) [0..] :: Matrix I\n\n am = fromInt a :: Matrix (Mod 13 I)\n bm = fromInt b :: Matrix (Mod 13 I)\n ad = fromInt a :: Matrix Float\n bd = fromInt b :: Matrix Float\n\n g = (3><3) (repeat (40000)) :: Matrix I\n gm = fromInt g :: Matrix (Mod 100000 I)\n\n lg = (3><3) (repeat (3*10^(9::Int))) :: Matrix Z\n lgm = fromZ lg :: Matrix (Mod 10000000000 Z)\n\n gen n = diagRect 1 (konst 5 n) n n :: Numeric t => Matrix t\n \n rgen n = gen n :: Matrix R\n cgen n = complex (rgen n) + fliprl (complex (rgen n)) * scalar (0:+1) :: Matrix C\n sgen n = single (cgen n)\n \n checkGen x = norm_Inf $ flatten $ invg x <> x - ident (rows x)\n \n invg t = gaussElim t (ident (rows t))\n\n checkLU okf t = norm_Inf $ flatten (l <> u <> p - t)\n where\n (l,u,p,_) = luFact (LU x' p')\n where\n (x',p') = mutable (luST okf) t\n\n checkSolve aa = norm_Inf $ flatten (aa <> x - bb)\n where\n bb = flipud aa\n x = luSolve' (luPacked' aa) bb\n\n tmm = diagRect 1 (fromList [2..6]) 5 5 :: Matrix (Mod 19 I)\n\n info = do\n print v\n print m\n print (tr m)\n print $ v+v\n print $ m+m\n print $ m <> m\n print $ m #> v\n\n print $ am <> gaussElim am bm - bm\n print $ ad <> gaussElim ad bd - bd\n\n print g\n print $ g <> g\n print gm\n print $ gm <> gm\n\n print lg\n print $ lg <> lg\n print lgm\n print $ lgm <> lgm\n \n putStrLn \"checkGen\"\n print (checkGen (gen 5 :: Matrix R))\n print (checkGen (gen 5 :: Matrix Float))\n print (checkGen (cgen 5 :: Matrix C))\n print (checkGen (sgen 5 :: Matrix (Complex Float)))\n print (invg (gen 5) :: Matrix (Mod 7 I))\n print (invg (gen 5) :: Matrix (Mod 7 Z))\n \n print $ mutable (luST (const True)) (gen 5 :: Matrix R)\n print $ mutable (luST (const True)) (gen 5 :: Matrix (Mod 11 Z))\n\n putStrLn \"checkLU\"\n print $ checkLU (magnit 0) (gen 5 :: Matrix R)\n print $ checkLU (magnit 0) (gen 5 :: Matrix Float)\n print $ checkLU (magnit 0) (cgen 5 :: Matrix C)\n print $ checkLU (magnit 0) (sgen 5 :: Matrix (Complex Float))\n print $ checkLU (magnit 0) (gen 5 :: Matrix (Mod 7 I))\n print $ checkLU (magnit 0) (gen 5 :: Matrix (Mod 7 Z))\n\n putStrLn \"checkSolve\"\n print $ checkSolve (gen 5 :: Matrix R)\n print $ checkSolve (gen 5 :: Matrix Float)\n print $ checkSolve (cgen 5 :: Matrix C)\n print $ checkSolve (sgen 5 :: Matrix (Complex Float))\n print $ checkSolve (gen 5 :: Matrix (Mod 7 I))\n print $ checkSolve (gen 5 :: Matrix (Mod 7 Z))\n \n putStrLn \"luSolve'\"\n print $ luSolve' (luPacked' tmm) (ident (rows tmm))\n print $ invershur tmm\n\n\n ok = and\n [ toInt (m #> v) == cmod 11 (toInt m #> toInt v )\n , am <> gaussElim_1 am bm == bm\n , am <> gaussElim_2 am bm == bm\n , am <> gaussElim am bm == bm\n , (checkGen (gen 5 :: Matrix R)) < 1E-15\n , (checkGen (gen 5 :: Matrix Float)) < 2E-7\n , (checkGen (cgen 5 :: Matrix C)) < 1E-15\n , (checkGen (sgen 5 :: Matrix (Complex Float))) < 3E-7\n , (checkGen (gen 5 :: Matrix (Mod 7 I))) == 0\n , (checkGen (gen 5 :: Matrix (Mod 7 Z))) == 0\n , (checkLU (magnit 1E-10) (gen 5 :: Matrix R)) < 2E-15\n , (checkLU (magnit 1E-5) (gen 5 :: Matrix Float)) < 1E-6\n , (checkLU (magnit 1E-10) (cgen 5 :: Matrix C)) < 5E-15\n , (checkLU (magnit 1E-5) (sgen 5 :: Matrix (Complex Float))) < 1E-6\n , (checkLU (magnit 0) (gen 5 :: Matrix (Mod 7 I))) == 0\n , (checkLU (magnit 0) (gen 5 :: Matrix (Mod 7 Z))) == 0\n , checkSolve (gen 5 :: Matrix R) < 2E-15\n , checkSolve (gen 5 :: Matrix Float) < 1E-6\n , checkSolve (cgen 5 :: Matrix C) < 4E-15\n , checkSolve (sgen 5 :: Matrix (Complex Float)) < 1E-6\n , checkSolve (gen 5 :: Matrix (Mod 7 I)) == 0\n , checkSolve (gen 5 :: Matrix (Mod 7 Z)) == 0\n , prodElements (konst (9:: Mod 10 I) (12::Int)) == product (replicate 12 (9:: Mod 10 I))\n , gm <> gm == konst 0 (3,3)\n , lgm <> lgm == konst 0 (3,3)\n , invershur tmm == luSolve' (luPacked' tmm) (ident (rows tmm))\n , luSolve' (luPacked' (tr $ ident 5 :: Matrix (I ./. 2))) (ident 5) == ident 5\n ]\n\n\n", "meta": {"hexsha": "41cbd5cdb2c00ef206a7595b72b6ccf154c6a3fe", "size": 15443, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Internal/Modular.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/Modular.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/Modular.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": 32.1729166667, "max_line_length": 99, "alphanum_fraction": 0.5679595933, "num_tokens": 5441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.525777734576895}} {"text": "{- |\nModule : Numeric.GSL.Root\nCopyright : (c) Alberto Ruiz 2009\nLicense : GPL\n\nMaintainer : Alberto Ruiz (aruiz at um dot es)\nStability : provisional\nPortability : uses ffi\n\nMultidimensional root finding.\n\n\n\nThe example in the GSL manual:\n\n@import Numeric.GSL\nimport Numeric.LinearAlgebra(format)\nimport Text.Printf(printf)\n\nrosenbrock a b [x,y] = [ a*(1-x), b*(y-x^2) ]\n\ndisp = putStrLn . format \\\" \\\" (printf \\\"%.3f\\\")\n\nmain = do\n let (sol,path) = root Hybrids 1E-7 30 (rosenbrock 1 10) [-10,-5]\n print sol\n disp path\n\n\\> main\n[1.0,1.0]\n 0.000 -10.000 -5.000 11.000 -1050.000\n 1.000 -3.976 24.827 4.976 90.203\n 2.000 -3.976 24.827 4.976 90.203\n 3.000 -3.976 24.827 4.976 90.203\n 4.000 -1.274 -5.680 2.274 -73.018\n 5.000 -1.274 -5.680 2.274 -73.018\n 6.000 0.249 0.298 0.751 2.359\n 7.000 0.249 0.298 0.751 2.359\n 8.000 1.000 0.878 -0.000 -1.218\n 9.000 1.000 0.989 -0.000 -0.108\n10.000 1.000 1.000 0.000 0.000\n@\n\n-}\n-----------------------------------------------------------------------------\n\nmodule Numeric.GSL.Root (\n uniRoot, UniRootMethod(..),\n uniRootJ, UniRootMethodJ(..),\n root, RootMethod(..),\n rootJ, RootMethodJ(..),\n) where\n\nimport Data.Packed.Internal\nimport Data.Packed.Matrix\nimport Numeric.GSL.Internal\nimport Foreign.Ptr(FunPtr, freeHaskellFunPtr)\nimport Foreign.C.Types\nimport System.IO.Unsafe(unsafePerformIO)\n\n-------------------------------------------------------------------------\n\ndata UniRootMethod = Bisection\n | FalsePos\n | Brent\n deriving (Enum, Eq, Show, Bounded)\n\nuniRoot :: UniRootMethod\n -> Double\n -> Int\n -> (Double -> Double)\n -> Double\n -> Double\n -> (Double, Matrix Double)\nuniRoot method epsrel maxit fun xl xu = uniRootGen (fi (fromEnum method)) fun xl xu epsrel maxit\n\nuniRootGen m f xl xu epsrel maxit = unsafePerformIO $ do\n fp <- mkDoublefun f\n rawpath <- createMIO maxit 4\n (c_root m fp epsrel (fi maxit) xl xu)\n \"root\"\n let it = round (rawpath @@> (maxit-1,0))\n path = takeRows it rawpath\n [sol] = toLists $ dropRows (it-1) path\n freeHaskellFunPtr fp\n return (sol !! 1, path)\n\nforeign import ccall safe \"root\"\n c_root:: CInt -> FunPtr (Double -> Double) -> Double -> CInt -> Double -> Double -> TM\n\n-------------------------------------------------------------------------\ndata UniRootMethodJ = UNewton\n | Secant\n | Steffenson\n deriving (Enum, Eq, Show, Bounded)\n\nuniRootJ :: UniRootMethodJ\n -> Double\n -> Int\n -> (Double -> Double)\n -> (Double -> Double)\n -> Double\n -> (Double, Matrix Double)\nuniRootJ method epsrel maxit fun dfun x = uniRootJGen (fi (fromEnum method)) fun\n dfun x epsrel maxit\n\nuniRootJGen m f df x epsrel maxit = unsafePerformIO $ do\n fp <- mkDoublefun f\n dfp <- mkDoublefun df\n rawpath <- createMIO maxit 2\n (c_rootj m fp dfp epsrel (fi maxit) x)\n \"rootj\"\n let it = round (rawpath @@> (maxit-1,0))\n path = takeRows it rawpath\n [sol] = toLists $ dropRows (it-1) path\n freeHaskellFunPtr fp\n return (sol !! 1, path)\n\nforeign import ccall safe \"rootj\"\n c_rootj :: CInt -> FunPtr (Double -> Double) -> FunPtr (Double -> Double)\n -> Double -> CInt -> Double -> TM\n\n-------------------------------------------------------------------------\n\ndata RootMethod = Hybrids\n | Hybrid\n | DNewton\n | Broyden\n deriving (Enum,Eq,Show,Bounded)\n\n-- | Nonlinear multidimensional root finding using algorithms that do not require \n-- any derivative information to be supplied by the user.\n-- Any derivatives needed are approximated by finite differences.\nroot :: RootMethod\n -> Double -- ^ maximum residual\n -> Int -- ^ maximum number of iterations allowed\n -> ([Double] -> [Double]) -- ^ function to minimize\n -> [Double] -- ^ starting point\n -> ([Double], Matrix Double) -- ^ solution vector and optimization path\n\nroot method epsabs maxit fun xinit = rootGen (fi (fromEnum method)) fun xinit epsabs maxit\n\nrootGen m f xi epsabs maxit = unsafePerformIO $ do\n let xiv = fromList xi\n n = dim xiv\n fp <- mkVecVecfun (aux_vTov (checkdim1 n . fromList . f . toList))\n rawpath <- vec xiv $ \\xiv' ->\n createMIO maxit (2*n+1)\n (c_multiroot m fp epsabs (fi maxit) // xiv')\n \"multiroot\"\n let it = round (rawpath @@> (maxit-1,0))\n path = takeRows it rawpath\n [sol] = toLists $ dropRows (it-1) path\n freeHaskellFunPtr fp\n return (take n $ drop 1 sol, path)\n\n\nforeign import ccall safe \"multiroot\"\n c_multiroot:: CInt -> FunPtr TVV -> Double -> CInt -> TVM\n\n-------------------------------------------------------------------------\n\ndata RootMethodJ = HybridsJ\n | HybridJ\n | Newton\n | GNewton\n deriving (Enum,Eq,Show,Bounded)\n\n-- | Nonlinear multidimensional root finding using both the function and its derivatives.\nrootJ :: RootMethodJ\n -> Double -- ^ maximum residual\n -> Int -- ^ maximum number of iterations allowed\n -> ([Double] -> [Double]) -- ^ function to minimize\n -> ([Double] -> [[Double]]) -- ^ Jacobian\n -> [Double] -- ^ starting point\n -> ([Double], Matrix Double) -- ^ solution vector and optimization path\n\nrootJ method epsabs maxit fun jac xinit = rootJGen (fi (fromEnum method)) fun jac xinit epsabs maxit\n\nrootJGen m f jac xi epsabs maxit = unsafePerformIO $ do\n let xiv = fromList xi\n n = dim xiv\n fp <- mkVecVecfun (aux_vTov (checkdim1 n . fromList . f . toList))\n jp <- mkVecMatfun (aux_vTom (checkdim2 n . fromLists . jac . toList))\n rawpath <- vec xiv $ \\xiv' ->\n createMIO maxit (2*n+1)\n (c_multirootj m fp jp epsabs (fi maxit) // xiv')\n \"multiroot\"\n let it = round (rawpath @@> (maxit-1,0))\n path = takeRows it rawpath\n [sol] = toLists $ dropRows (it-1) path\n freeHaskellFunPtr fp\n freeHaskellFunPtr jp\n return (take n $ drop 1 sol, path)\n\nforeign import ccall safe \"multirootj\"\n c_multirootj:: CInt -> FunPtr TVV -> FunPtr TVM -> Double -> CInt -> TVM\n\n-------------------------------------------------------\n\ncheckdim1 n v\n | dim v == n = v\n | otherwise = error $ \"Error: \"++ show n\n ++ \" components expected in the result of the function supplied to root\"\n\ncheckdim2 n m\n | rows m == n && cols m == n = m\n | otherwise = error $ \"Error: \"++ show n ++ \"x\" ++ show n\n ++ \" Jacobian expected in rootJ\"\n", "meta": {"hexsha": "6da15e5f002524265dde4c79276aa63f84a7b141", "size": 7160, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/Root.hs", "max_stars_repo_name": "curiousleo/liquidhaskell", "max_stars_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 941, "max_stars_repo_stars_event_min_datetime": "2015-01-13T10:51:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:32:32.000Z", "max_issues_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/Root.hs", "max_issues_repo_name": "curiousleo/liquidhaskell", "max_issues_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 1300, "max_issues_repo_issues_event_min_datetime": "2015-01-01T05:41:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:11:03.000Z", "max_forks_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/Root.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": 34.0952380952, "max_line_length": 100, "alphanum_fraction": 0.5377094972, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5256387117707382}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeInType #-}\n{-# LANGUAGE TypeOperators #-}\n\n-- |\n-- Module : Numeric.Hamilton\n-- Description : Hamiltonian dynamics for physical systems on generalized\n-- coordinates using automatic differentiation\n-- Copyright : (c) Justin Le 2016\n-- License : BSD-3\n-- Maintainer : justin@jle.im\n-- Stability : unstable\n-- Portability : portable\n--\n-- Simulate physical systems on generalized/arbitrary coordinates using\n-- Hamiltonian mechanics and automatic differentiation!\n--\n-- See the for more\n-- information on usage!\n--\n\nmodule Numeric.Hamilton\n ( -- * Systems and states\n -- ** Systems\n System\n , mkSystem\n , mkSystem'\n , underlyingPos\n -- ** States\n , Config(..)\n , Phase(..)\n , toPhase\n , fromPhase\n -- * State functions\n , momenta\n , velocities\n , keC\n , keP\n , pe\n , lagrangian\n , hamiltonian\n , hamEqs\n -- * Simulating hamiltonian dynamics\n -- ** Over phase space\n , stepHam\n , evolveHam\n , evolveHam'\n -- ** Over configuration space\n -- | Convenience wrappers over the normal phase-space\n -- steppers/simulators that allow you to provide input and expect\n -- output in configuration space instead of in phase space. Note that\n -- the simulation itself still runs in phase space, so these all\n -- require conversions to and from phase space under the hood.\n , stepHamC\n , evolveHamC\n , evolveHamC'\n ) where\n\nimport Control.Monad\nimport Data.Bifunctor\nimport Data.Foldable\nimport Data.Kind\nimport Data.Maybe\nimport Data.Proxy\nimport Data.Type.Equality\nimport GHC.Generics (Generic)\nimport GHC.TypeLits\nimport GHC.TypeLits.Compare\nimport Numeric.AD\nimport Numeric.GSL.ODE\nimport Numeric.LinearAlgebra.Static as H\nimport Numeric.LinearAlgebra.Static.Vector\nimport qualified Data.Vector.Generic.Sized as VG\nimport qualified Data.Vector.Sized as V\nimport qualified Numeric.LinearAlgebra as LA\n\n-- | Represents the full state of a system of @n@ generalized coordinates\n-- in configuration space (informally, \"positions and velocities\")\n--\n-- A configuration space representaiton is more directly \"physically\n-- meaningful\" and intuitive/understandable to humans than a phase space\n-- representation. However, it's much less mathematically ideal to work\n-- with because of the lack of some neat underlying symmetries.\n--\n-- You can convert a @'Config' n@ into a @'Phase' n@ (convert from\n-- configuration space to phase space) for a given system with 'toPhase'.\n-- This allows you to state your system in configuration space and then\n-- convert it to phase space before handing it off to the hamiltonian\n-- machinery.\ndata Config :: Nat -> Type where\n Cfg :: { -- | The current values (\"positions\") of each of the @n@\n -- generalized coordinates\n cfgPositions :: !(R n)\n -- | The current rate of changes (\"velocities\") of each of the\n -- @n@ generalized coordinates\n , cfgVelocities :: !(R n)\n }\n -> Config n\n deriving (Generic)\n\nderiving instance KnownNat n => Show (Config n)\n\n-- | Represents the full state of a system of @n@ generalized coordinates\n-- in phase space (informally, \"positions and momentums\").\n--\n-- Phase space representations are much nicer to work with mathematically\n-- because of some neat underlying symmetries. For one, positions and\n-- momentums are \"interchangeable\" in a system; if you swap every\n-- coordinate's positions with their momentums, and also swap them in the\n-- equations of motions, you get the same system back. This isn't the case\n-- with configuration space representations.\n--\n-- A hamiltonian simulation basically describes the trajectory of each\n-- coordinate through phase space, so this is the /state/ of the\n-- simulation. However, configuration space representations are much more\n-- understandable to humans, so it might be useful to give an initial state\n-- in configuration space using 'Config', and then convert it to a 'Phase'\n-- with 'toPhase'.\ndata Phase :: Nat -> Type where\n Phs :: { -- | The current values (\"positions\") of each of the @n@\n -- generalized coordinates.\n phsPositions :: !(R n)\n -- | The current conjugate momenta (\"momentums\") to each of\n -- the @n@ generalized coordinates\n , phsMomenta :: !(R n)\n }\n -> Phase n\n deriving (Generic)\n\nderiving instance KnownNat n => Show (Phase n)\n\n-- | Represents a physical system in which physics happens. A @'System'\n-- m n@ is a system whose state described using @n@ generalized coordinates\n-- (an \"@n@-dimensional\" system), where the underlying cartesian coordinate\n-- space is @m@-dimensional.\n--\n-- For the most part, you are supposed to be able to ignore @m@. @m@ is\n-- only provided because it's useful when plotting/drawing the system with\n-- a given state back in rectangular coordinates. (The only function that\n-- use the @m@ at the moment is 'underlyingPos')\n--\n-- A @'System' m n@'s state is described using a @'Config' n@ (which\n-- describes the system in configuration space) or a @'Phase' n@ (which\n-- describes the system in phase space).\ndata System :: Nat -> Nat -> Type where\n Sys :: { _sysInertia :: R m\n , _sysCoords :: R n -> R m\n , _sysJacobian :: R n -> L m n\n , _sysHessian :: R n -> V.Vector n (L m n)\n , _sysPotential :: R n -> Double\n , _sysPotentialGrad :: R n -> R n\n }\n -> System m n\n\n-- | Converts the position of generalized coordinates of a system to the\n-- coordinates of the system's underlying cartesian coordinate system.\n-- Useful for plotting/drawing the system in cartesian space.\nunderlyingPos\n :: System m n\n -> R n\n -> R m\nunderlyingPos = _sysCoords\n\n-- | The potential energy of a system, given the position in the\n-- generalized coordinates of the system.\npe :: System m n\n -> R n\n -> Double\npe = _sysPotential\n\nvec2l\n :: (KnownNat m, KnownNat n)\n => V.Vector m (V.Vector n Double)\n -> L m n\nvec2l = rowsL . fmap gvecR\n\n-- | Create a system with @n@ generalized coordinates by describing its\n-- coordinate space (by a function from the generalized coordinates to the\n-- underlying cartesian coordinates), the inertia of each of those\n-- underlying coordinates, and the pontential energy function.\n--\n-- The potential energy function is expressed in terms of the genearlized\n-- coordinate space's positions.\nmkSystem\n :: forall m n. (KnownNat m, KnownNat n)\n => R m -- ^ The \"inertia\" of each of the @m@ coordinates\n -- in the underlying cartesian space of the system. This\n -- should be mass for linear coordinates and rotational\n -- inertia for angular coordinates.\n -> (forall a. RealFloat a => V.Vector n a -> V.Vector m a)\n -- ^ Conversion function to convert points in the\n -- generalized coordinate space to the underlying cartesian\n -- space of the system.\n -> (forall a. RealFloat a => V.Vector n a -> a)\n -- ^ The potential energy of the system as a function of\n -- the generalized coordinate space's positions.\n -> System m n\nmkSystem m f u = Sys\n { _sysInertia = m\n , _sysCoords = gvecR . f . grVec\n , _sysJacobian = tr . vec2l . jacobianT f . grVec\n , _sysHessian = tr2 . fmap vec2l . hessianF f . grVec\n , _sysPotential = u . grVec\n , _sysPotentialGrad = gvecR . grad u . grVec\n }\n where\n tr2 :: forall o. (KnownNat n, KnownNat o)\n => V.Vector m (L n o)\n -> V.Vector n (L m o)\n tr2 = fmap rowsL . traverse lRows\n {-# INLINE tr2 #-}\n\n\n-- | Convenience wrapper over 'mkSystem' that allows you to specify the\n-- potential energy function in terms of the underlying cartesian\n-- coordinate space.\nmkSystem'\n :: forall m n. (KnownNat m, KnownNat n)\n => R m -- ^ The \"inertia\" of each of the @m@ coordinates\n -- in the underlying cartesian space of the system. This\n -- should be mass for linear coordinates and rotational\n -- inertia for angular coordinates.\n -> (forall a. RealFloat a => V.Vector n a -> V.Vector m a)\n -- ^ Conversion function to convert points in the\n -- generalized coordinate space to the underlying cartesian\n -- space of the system.\n -> (forall a. RealFloat a => V.Vector m a -> a)\n -- ^ The potential energy of the system as a function of\n -- the underlying cartesian coordinate space's positions.\n -> System m n\nmkSystem' m f u = mkSystem m f (u . f)\n\n\n-- | Compute the generalized momenta conjugate to each generalized\n-- coordinate of a system by giving the configuration-space state of the\n-- system.\n--\n-- Note that getting the momenta from a @'Phase' n@ involves just using\n-- 'phsMomenta'.\nmomenta\n :: (KnownNat m, KnownNat n)\n => System m n\n -> Config n\n -> R n\nmomenta Sys{..} Cfg{..} = tr j #> diag _sysInertia #> j #> cfgVelocities\n where\n j = _sysJacobian cfgPositions\n\n-- | Convert a configuration-space representaiton of the state of the\n-- system to a phase-space representation.\n--\n-- Useful because the hamiltonian simulations use 'Phase' as its working\n-- state, but 'Config' is a much more human-understandable and intuitive\n-- representation. This allows you to state your starting state in\n-- configuration space and convert to phase space for your simulation to\n-- use.\ntoPhase\n :: (KnownNat m, KnownNat n)\n => System m n\n -> Config n\n -> Phase n\ntoPhase s = Phs <$> cfgPositions <*> momenta s\n\n-- | The kinetic energy of a system, given the system's state in\n-- configuration space.\nkeC :: (KnownNat m, KnownNat n)\n => System m n\n -> Config n\n -> Double\nkeC s = do\n vs <- cfgVelocities\n ps <- momenta s\n return $ (vs <.> ps) / 2\n\n-- | The Lagrangian of a system (the difference between the kinetic energy\n-- and the potential energy), given the system's state in configuration\n-- space.\nlagrangian\n :: (KnownNat m, KnownNat n)\n => System m n\n -> Config n\n -> Double\nlagrangian s = do\n t <- keC s\n u <- pe s . cfgPositions\n return (t - u)\n\n-- | Compute the rate of change of each generalized coordinate by giving\n-- the state of the system in phase space.\n--\n-- Note that getting the velocities from a @'Config' n@ involves just using\n-- 'cfgVelocities'.\nvelocities\n :: (KnownNat m, KnownNat n)\n => System m n\n -> Phase n\n -> R n\nvelocities Sys{..} Phs{..} = inv jmj #> phsMomenta\n where\n j = _sysJacobian phsPositions\n jmj = tr j H.<> diag _sysInertia H.<> j\n\n-- | Invert 'toPhase' and convert a description of a system's state in\n-- phase space to a description of the system's state in configuration\n-- space.\n--\n-- Possibly useful for showing the phase space representation of a system's\n-- state in a more human-readable/human-understandable way.\nfromPhase\n :: (KnownNat m, KnownNat n)\n => System m n\n -> Phase n\n -> Config n\nfromPhase s = Cfg <$> phsPositions <*> velocities s\n\n-- | The kinetic energy of a system, given the system's state in\n-- phase space.\nkeP :: (KnownNat m, KnownNat n)\n => System m n\n -> Phase n\n -> Double\nkeP s = do\n ps <- phsMomenta\n vs <- velocities s\n return $ (vs <.> ps) / 2\n\n-- | The Hamiltonian of a system (the sum of kinetic energy and the\n-- potential energy), given the system's state in phase space.\nhamiltonian\n :: (KnownNat m, KnownNat n)\n => System m n\n -> Phase n\n -> Double\nhamiltonian s = do\n t <- keP s\n u <- pe s . phsPositions\n return (t + u)\n\n-- | The \"hamiltonian equations\" for a given system at a given state in\n-- phase space. Returns the rate of change of the positions and\n-- conjugate momenta, which can be used to progress the simulation through\n-- time.\n--\n-- Computed using the maths derived in\n-- .\nhamEqs\n :: (KnownNat m, KnownNat n)\n => System m n\n -> Phase n\n -> (R n, R n)\nhamEqs Sys{..} Phs{..} = (dHdp, -dHdq)\n where\n mm = diag _sysInertia\n j = _sysJacobian phsPositions\n trj = tr j\n jmj = trj H.<> mm H.<> j\n ijmj = inv jmj\n dTdq = gvecR\n . flip fmap (_sysHessian phsPositions) $ \\djdq ->\n -phsMomenta <.> ijmj #> trj #> mm #> djdq #> ijmj #> phsMomenta\n dHdp = ijmj #> phsMomenta\n dHdq = dTdq + _sysPotentialGrad phsPositions\n\n-- | Step a system through phase space over over a single timestep.\nstepHam\n :: forall m n. (KnownNat m, KnownNat n)\n => Double -- ^ timestep to step through\n -> System m n -- ^ system to simulate\n -> Phase n -- ^ initial state, in phase space\n -> Phase n\nstepHam r s p = evolveHam @m @n @2 s p (V.fromTuple (0, r))\n `V.unsafeIndex` 1\n\n-- | Evolve a system using a hamiltonian stepper, with the given initial\n-- phase space state.\n--\n-- Desired solution times provided as a list instead of a sized 'V.Vector'.\n-- The output list should be the same length as the input list.\nevolveHam'\n :: forall m n. (KnownNat m, KnownNat n)\n => System m n -- ^ system to simulate\n -> Phase n -- ^ initial state, in phase space\n -> [Double] -- ^ desired solution times\n -> [Phase n]\nevolveHam' _ _ [] = []\nevolveHam' s p0 ts = V.withSizedList (toList ts') $ \\(v :: V.Vector s Double) ->\n case Proxy @2 %<=? Proxy @s of\n LE Refl -> (if l1 then tail else id)\n . toList\n $ evolveHam s p0 v\n NLE{} -> error \"evolveHam': Internal error\"\n where\n (l1, ts') = case ts of\n [x] -> (True , [0,x])\n _ -> (False, ts )\n\n-- | Evolve a system using a hamiltonian stepper, with the given initial\n-- phase space state.\nevolveHam\n :: forall m n s. (KnownNat m, KnownNat n, KnownNat s, 2 <= s)\n => System m n -- ^ system to simulate\n -> Phase n -- ^ initial state, in phase space\n -> V.Vector s Double -- ^ desired solution times\n -> V.Vector s (Phase n)\nevolveHam s p0 ts = fmap toPs . fromJust . V.fromList . LA.toRows\n $ odeSolveV RKf45 hi eps eps (const f) (fromPs p0) ts'\n where\n hi = (V.unsafeIndex ts 1 - V.unsafeIndex ts 0) / 100\n eps = 1.49012e-08\n f :: LA.Vector Double -> LA.Vector Double\n f = uncurry (\\p m -> LA.vjoin [p,m])\n . join bimap extract . hamEqs s . toPs\n ts' = VG.fromSized . VG.convert $ ts\n n = fromInteger $ natVal (Proxy @n)\n fromPs :: Phase n -> LA.Vector Double\n fromPs p = LA.vjoin . map extract $ [phsPositions p, phsMomenta p]\n toPs :: LA.Vector Double -> Phase n\n toPs v = Phs pP pM\n where\n Just [pP, pM] = traverse create . LA.takesV [n, n] $ v\n\n-- | A convenience wrapper for 'evolveHam'' that works on configuration\n-- space states instead of phase space states.\n--\n-- Note that the simulation itself still runs in phase space; this function\n-- just abstracts over converting to and from phase space for the inputs\n-- and outputs.\nevolveHamC'\n :: forall m n. (KnownNat m, KnownNat n)\n => System m n -- ^ system to simulate\n -> Config n -- ^ initial state, in configuration space\n -> [Double] -- ^ desired solution times\n -> [Config n]\nevolveHamC' s c0 = fmap (fromPhase s) . evolveHam' s (toPhase s c0)\n\n-- | A convenience wrapper for 'evolveHam' that works on configuration\n-- space states instead of phase space states.\n--\n-- Note that the simulation itself still runs in phase space; this function\n-- just abstracts over converting to and from phase space for the inputs\n-- and outputs.\nevolveHamC\n :: forall m n s. (KnownNat m, KnownNat n, KnownNat s, 2 <= s)\n => System m n -- ^ system to simulate\n -> Config n -- ^ initial state, in configuration space\n -> V.Vector s Double -- ^ desired solution times\n -> V.Vector s (Config n)\nevolveHamC s c0 = fmap (fromPhase s) . evolveHam s (toPhase s c0)\n\n-- | Step a system through configuration space over over a single timestep.\n--\n-- Note that the simulation itself still runs in phase space; this function\n-- just abstracts over converting to and from phase space for the input\n-- and output.\nstepHamC\n :: forall m n. (KnownNat m, KnownNat n)\n => Double -- ^ timestep to step through\n -> System m n -- ^ system to simulate\n -> Config n -- ^ initial state, in phase space\n -> Config n\nstepHamC r s = fromPhase s . stepHam r s . toPhase s\n\n", "meta": {"hexsha": "c08e23c34def8a8f1ea2215b93823d5b2dbb92cb", "size": 17376, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Hamilton.hs", "max_stars_repo_name": "mstksg/hamilton", "max_stars_repo_head_hexsha": "3ba45860466a25de2933c61dd6f3eefa84725c29", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 136, "max_stars_repo_stars_event_min_datetime": "2016-11-22T15:07:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T22:08:07.000Z", "max_issues_repo_path": "src/Numeric/Hamilton.hs", "max_issues_repo_name": "mstksg/hamilton", "max_issues_repo_head_hexsha": "3ba45860466a25de2933c61dd6f3eefa84725c29", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2016-12-05T09:41:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-06T03:24:53.000Z", "max_forks_repo_path": "src/Numeric/Hamilton.hs", "max_forks_repo_name": "mstksg/hamilton", "max_forks_repo_head_hexsha": "3ba45860466a25de2933c61dd6f3eefa84725c29", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-11-24T21:59:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:15.000Z", "avg_line_length": 36.8917197452, "max_line_length": 80, "alphanum_fraction": 0.6298342541, "num_tokens": 4507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5253365743053078}} {"text": "-- |\n-- = Nonlinear transient computing\n--\n-- This module was developed as a part of author's PhD project:\n-- https://www.researchgate.net/project/Theory-and-Modeling-of-Complex-Nonlinear-Delay-Dynamics-Applied-to-Neuromorphic-Computing\n--\n\n{-# LANGUAGE BangPatterns #-}\n\nmodule RC.NTC\n ( new\n , learn\n , learnClassifier\n , predict\n , par0\n , NTCParameters (..)\n ) where\n\nimport Numeric.LinearAlgebra\nimport System.Random ( StdGen\n , split\n )\nimport qualified Data.List as List\nimport qualified Data.Vector.Storable as V\nimport qualified Data.Vector.Storable.Mutable as VM\nimport System.IO.Unsafe ( unsafePerformIO )\nimport qualified Learning\nimport qualified Numeric.DDE.Model as DDEModel\n\nimport RC.NTC.Types\nimport qualified RC.NTC.Reservoir as Reservoir\nimport qualified RC.Helpers as H\n\n-- | An untrained NTC network\nnew\n :: StdGen\n -> NTCParameters\n -> (Int, Int, Int)\n -- ^ Input dimension, network nodes, and output dimension\n -> NTC\nnew g par (ind, nodes, out) =\n let iwgen = _inputWeightsGenerator par\n iw = iwgen g (nodes, ind) (_inputWeightsRange par)\n ntc = NTC { _inputWeights = iw\n , _reservoir = _reservoirModel par\n , _outputWeights = Nothing\n , _par = par\n }\n in ntc\n\n-- | Default NTC parameters\npar0 :: NTCParameters\npar0 = Par\n { _preprocess = id\n , _inputWeightsGenerator = H.randMatrix\n , _postprocess = H.addBiases -- Usually `id` will work\n , _inputWeightsRange = undefined -- To be manually set, e.g. (-1, 1)\n , _reservoirModel = Reservoir.genReservoir p\n }\n where\n filt' = DDEModel.BandpassFiltering {\n DDEModel._tau = 7.8125e-3\n , DDEModel._theta = recip 0.34375\n }\n\n p = DDEModel.RC { DDEModel._filt = filt'\n , DDEModel._rho = 3.25\n , DDEModel._fnl = H.hsigmoid (1.09375, 1.5, 0.0)\n }\n\n-- | Nonlinear transformation performed by an NTC network\nforwardPass :: NTC -- ^ NTC network\n -> Matrix Double -- ^ Input information\n -> Matrix Double\nforwardPass NTC { _par = Par { _preprocess = prep, _postprocess = post }\n , _inputWeights = iw\n , _reservoir = Reservoir res\n } !sample =\n let pipeline = post. res. (iw <>). prep\n in pipeline sample\n\n-- | NTC training: learn the readout weights offline\nlearn\n :: NTC\n -> Int\n -- ^ Discard the first N points\n -> Matrix Double\n -- ^ Input matrix of features rows and observations columns\n -> Matrix Double\n -- ^ Desired output matrix of observations columns\n -> Either String NTC\nlearn ntc forgetPts inp out = ntc'\n where\n state' = forwardPass ntc inp ?? (All, Drop forgetPts)\n teacher' = out ?? (All, Drop forgetPts)\n ntc' = case Learning.learn' state' teacher' of\n Nothing -> Left \"Cannot create a readout matrix\"\n w -> Right $ ntc { _outputWeights = w }\n\n_concatForwardPass :: NTC\n -> Int\n -- ^ Number of samples in the list (for\n -- memory allocation)\n -> [Matrix Double]\n -- ^ List of samples\n -> Matrix Double\n_concatForwardPass ntc m (state0_:samples') = unsafePerformIO $ do\n -- Detect the postprocessing output dimension `nodes`.\n -- Alternatively, use Static shapes from hmatrix.\n let state0 = forwardPass ntc state0_\n nodes = rows state0\n state0' = H.flatten' state0\n\n -- Allocate memory for a mutable vector\n v <- VM.new (nodes * m)\n\n -- Copy the first computed state0'\n copy state0' v 0 0 nodes\n\n let foldA _ [] = return ()\n foldA f ((y, i):ys) = do\n let v0 = f y\n copy v0 v 0 (i * nodes) ((i + 1) * nodes)\n foldA f ys\n\n -- NB: Does compiler know (H.flatten'. H.unflatten') == id?\n -- If not, consider refactoring genReservoir and forwardPass\n foldA (H.flatten'. forwardPass ntc) $ zip samples' [1..m - 1]\n\n processed' <- V.unsafeFreeze v\n let processed = H.unflatten' nodes processed'\n return processed\n where\n copy !v0 !v !i0 !i !k\n | i < k = do\n VM.unsafeWrite v i (v0 V.! i0)\n copy v0 v (i0 + 1) (i + 1) k\n | otherwise = return ()\n\n-- | NTC training specific to classification task.\n-- The readout weights are learned offline.\n--\n-- Alternatively, one could use `learn` function. However,\n-- to make sure the training samples do not mix in the reservoir RNN,\n-- a significant padding of zeros would be needed. Although that\n-- way directly corresponds to a physical experiment, that would be not\n-- memory-efficient on a computer.\nlearnClassifier\n :: NTC\n -- ^ NTC network\n -> [Int]\n -- ^ Target labels\n -> Int\n -- ^ Number of inputs (for memory allocation)\n -> [Matrix Double]\n -- ^ Training inputs\n -> Either String (Learning.Classifier Int)\nlearnClassifier ntc labels m samples =\n case Learning.learn' state teacher' of\n Nothing -> Left \"Cannot create a readout matrix\"\n Just w -> let clf = Learning.winnerTakesAll w klasses. forwardPass ntc\n in Right (Learning.Classifier clf)\n where\n klasses = fromList. List.sort. List.nub $ labels\n klassesNo = V.length klasses\n teacher' = concatHor. map (flip (Learning.teacher klassesNo) 1) $ labels\n\n -- Alternatively, a streaming interface might be a solution\n -- https://hackage.haskell.org/package/pipes-4.3.7/docs/Pipes-Tutorial.html\n state = _concatForwardPass ntc m samples\n\n-- | Horizontal matrix concatenation, alternative to fromBlocks\nconcatHor :: Element a => [Matrix a] -> Matrix a\nconcatHor ms@(m:_) = foldr (|||) (zeroCols (rows m)) ms\n-- concatHor = concatMapHor id\n{-# SPECIALIZE concatHor :: [Matrix Double] -> Matrix Double #-}\n\nconcatMapHor\n :: Element b =>\n (Matrix a -> Matrix b) -> [Matrix a] -> Matrix b\nconcatMapHor f ms@(m:_) = foldr (\\a b -> f a ||| b) (zeroCols (rows m)) ms\n{-# SPECIALIZE concatMapHor :: (Matrix Double -> Matrix Double) -> [Matrix Double] -> Matrix Double #-}\n\n-- | Matrix with zero elements\nzeroCols :: V.Storable a => Int -> Matrix a\nzeroCols rows' = (rows'><0) []\n{-# SPECIALIZE zeroCols :: Int -> Matrix Double #-}\n\n-- | Run prediction using a \"clean\" (uninitialized) reservoir and then\n-- forget the reservoir's state.\n-- This can be used for both forecasting and classification tasks.\npredict :: NTC -- ^ Trained network\n -> Int -- ^ Washout (forget) points\n -> Matrix Double\n -- ^ Input matrix where measurements are columns and features are rows\n -> Either String (Matrix Double)\n -- ^ Either error string or predicted output\npredict ntc@NTC { _outputWeights = ow\n } forgetPts inp =\n case ow of\n Nothing -> Left \"Please train the NTC first\"\n Just w -> let y = forwardPass ntc inp\n y2 = y ?? (All, Drop forgetPts)\n prediction = w <> y2\n in Right prediction\n", "meta": {"hexsha": "1d4fdecc0c05d1e5559729225b83dd8219a82a4a", "size": 7048, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "rc/RC/NTC.hs", "max_stars_repo_name": "masterdezign/rc", "max_stars_repo_head_hexsha": "0a37c27aff70a096d010d2043ef6eab33dee2dc8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-02-24T22:31:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T11:44:32.000Z", "max_issues_repo_path": "rc/RC/NTC.hs", "max_issues_repo_name": "masterdezign/rc", "max_issues_repo_head_hexsha": "0a37c27aff70a096d010d2043ef6eab33dee2dc8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rc/RC/NTC.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": 34.213592233, "max_line_length": 129, "alphanum_fraction": 0.6223041998, "num_tokens": 1846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5252903738092137}} {"text": "module Q.Options.ImpliedVol.Normal where\nimport Data.Default.Class (Default (..))\nimport Numeric.IEEE (epsilon)\nimport Numeric.Natural (Natural)\nimport Numeric.RootFinding as R (RiddersParam (RiddersParam),\n Root (NotBracketed, Root, SearchFailed), Tolerance,\n ridders)\nimport Q.Options.Bachelier (Bachelier (Bachelier), euOption)\n\nimport Statistics.Distribution (cumulative, density)\nimport Statistics.Distribution.Normal (standard)\nimport Q.Options\n\n\n-- | Method to use to calculate the normal implied vol.\ndata Method =\n Jackel -- ^ Jackel analytical formula approximation.\n | ChoKimKwak -- ^ J. Choi, K kim, and M. Kwak (2009)\n -- | Numerical root finding. Currently Ridders is used.\n | RootFinding\n Natural -- ^ Maximum number of iterations.\n R.Tolerance -- ^ Tolerance (relative or absolute)\n (Double, Double, Double) -- ^ Triple of @(low bound, initial\n -- guess, upper bound)@. If initial\n -- guess if out of bracket middle\n -- of bracket is taken as.\n\ninstance Default Method where\n def = Jackel\n\n-- | Default method implementation of 'euImpliedVolWith' using 'Jackel'.\neuImpliedVol :: OptionType -> Forward -> Strike -> YearFrac -> Rate -> Premium -> Vol\neuImpliedVol = euImpliedVolWith def\n\n-- | Calcualte the bachelier option implied vol of a european option.\n--\n-- If the options premium does not have time value @'hasTimeValue'@ return 0.\neuImpliedVolWith :: Method -> OptionType -> Forward -> Strike -> YearFrac -> Rate -> Premium -> Vol\neuImpliedVolWith m cp f k t r p\n | hasTimeValue cp f k p df = euImpliedVolWith' m cp f k t r p\n | otherwise = Vol $ 0\n where df = discountFactor t r\n\neuImpliedVolWith' :: Method-> OptionType-> Forward-> Strike-> YearFrac-> Rate-> Premium-> Vol\neuImpliedVolWith' Jackel cp (Forward f) (Strike k) (YearFrac t) (Rate r) (Premium p)\n -- Case where interest rate is not 0 we need undiscount. The paper is written\n -- for the undiscounted Bachelier option prices.\n | r /= 0\n = euImpliedVol cp (Forward f) (Strike k) (YearFrac t) (Rate 0) (Premium (p/df))\n -- Case of ATM. Solve directly.\n | abs (k - f) <= epsilon = Vol $ p * sqrt2Pi / (sqrt t)\n -- Case of ITM option. Calcualte vol of the out of the money option with Put-Call-Parity.\n | phiStarTilde >= 0\n = euImpliedVol (succ cp) (Forward f) (Strike k) (YearFrac t) (Rate r) (Premium p')\n -- General case for an out of the money option.\n | otherwise = let\n ẋ = if phiStarTilde < c then\n let g = 1 / (phiStarTilde - 0.5)\n ξ = (0.032114372355 - (g**2)*(0.016969777977 - (g**2)*(2.6207332461E-3-(9.6066952861E-5)*g**2)))\n /\n (1-(g**2)*(0.6635646938 - (g**2)*(0.14528712196 - 0.010472855461*g**2)))\n in g * (1 / sqrt2Pi + ξ*g**2)\n else\n let h = sqrt $ (-log (-phiStarTilde))\n in (9.4883409779-h*(9.6320903635-h*(0.58556997323 + 2.1464093351*h)))\n /\n (1-h*(0.65174820867 + h*(1.5120247828 + 6.6437847132E-5*h)))\n c = (-0.001882039271)\n x = ẋ + (3*q * ẋ * ẋ * (2 - q * ẋ * (2 + ẋ*ẋ)))\n /\n (6 + q*ẋ * ((-12) + ẋ *(6*q + ẋ * ((-6)*q*ẋ*(3+ẋ*ẋ)))))\n phiXBarTilde = (cumulative standard ẋ) + (density standard ẋ)/ẋ\n q = (phiXBarTilde-phiStarTilde)/ (density standard ẋ)\n in Vol $ (abs (k - f)) / (abs (x * sqrt t))\n where phiStarTilde = negate $ (abs (p - (max (theta * (f - k)) 0))) / (abs (k - f))\n theta = if cp == Call then 1 else -1\n phiTilde = (-theta) * p / (k - f)\n p' = cpi * df * (f - k) + p\n cpi = fromIntegral $ fromEnum cp --call put indicartor.\n df = exp $ (-r) * t\n sqrt2Pi = 2.506628274631000\n\n\neuImpliedVolWith' ChoKimKwak cp (Forward f) (Strike k) (YearFrac t) (Rate r) (Premium p) =\n let df = exp $ (-r) * t\n forwardPremium = p / df\n straddlePremium = case cp of Call -> 2 * forwardPremium - (f - k)\n Put -> 2 * forwardPremium + (f - k)\n nu' = (f - k) / straddlePremium\n nu = max (-1 + epsilon) (min nu' (1 - epsilon))\n eta | abs nu < sqrtEpsilon = 1\n | otherwise = nu / (atanh nu)\n heta = h eta\n in Vol $ sqrt (pi / (2 * t)) * straddlePremium * heta\n\n\neuImpliedVolWith' (RootFinding maxIter tol bracket) cp (Forward forward) k t r (Premium p) =\n let f vol = p' - p where\n (Premium p') = vPremium $ euOption b cp k\n b = Bachelier t (Forward forward) r (Vol vol)\n (lb, _, ub) = bracket\n root = ridders (RiddersParam (fromEnum maxIter) tol) (lb, ub) f\n in case root of (Root vol) -> Vol vol\n NotBracketed -> error \"not bracketed\"\n SearchFailed -> error \"search failed\"\n\nsqrtEpsilon :: Double\nsqrtEpsilon = sqrt epsilon\n\nh :: Floating p => p -> p\nh eta = sqrt(eta) * (num / den) where\n a0 = 3.994961687345134e-1\n a1 = 2.100960795068497e+1\n a2 = 4.980340217855084e+1\n a3 = 5.988761102690991e+2\n a4 = 1.848489695437094e+3\n a5 = 6.106322407867059e+3\n a6 = 2.493415285349361e+4\n a7 = 1.266458051348246e+4\n\n b0 = 1.000000000000000e+0\n b1 = 4.990534153589422e+1\n b2 = 3.093573936743112e+1\n b3 = 1.495105008310999e+3\n b4 = 1.323614537899738e+3\n b5 = 1.598919697679745e+4\n b6 = 2.392008891720782e+4\n b7 = 3.608817108375034e+3\n b8 = -2.067719486400926e+2\n b9 = 1.174240599306013e+1\n\n num = a0 + eta * (a1 + eta * (a2 + eta * (a3 + eta * (a4 + eta * (a5 + eta * (a6 + eta * a7))))))\n den = b0 + eta * (b1 + eta * (b2 + eta * (b3 + eta * (b4 + eta * (b5 + eta * (b6 + eta * (b7 + eta * (b8 + eta * b9))))))))\n", "meta": {"hexsha": "c08650bdfba217dc83f9ee68ad17759ec019f756", "size": 6248, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Q/Options/ImpliedVol/Normal.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/ImpliedVol/Normal.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/ImpliedVol/Normal.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": 46.6268656716, "max_line_length": 125, "alphanum_fraction": 0.5387323944, "num_tokens": 1992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503682, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5252903713654111}} {"text": "module STCR2Z2T0S0 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\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:radialFlagStr: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 radialFlag = read radialFlagStr :: Bool\n numThread = read numThreadStr :: Int\n sourceDist = L.take 1 initDist\n sinkDist = L.drop 1 initDist\n folderPath = \"output/test/STCR2Z2T0S0\"\n dirName = takeDirectory histFilePath\n fileName = takeFileName histFilePath\n newHistFilePath =\n if radialFlag\n then dirName (\"Radial_\" L.++ fileName)\n else histFilePath\n (R2S1RPPoint (_, _, _, s)) = L.head sourceDist\n createDirectoryIfMissing True folderPath\n arrR2Z2T0S0 <-\n if radialFlag\n then do\n flag <- doesFileExist newHistFilePath\n radialArr <-\n if flag\n then R.map magnitude . getNormalizedHistogramArr <$>\n decodeFile newHistFilePath\n else do\n putStrLn\n \"Couldn't find a Green's function data. Start simulation...\"\n solveMonteCarloR2Z2T0S0Radial\n numThread\n numTrail\n maxTrail\n numPoint\n numPoint\n thetaSigma\n scaleSigma\n maxScale\n tao\n theta0Freqs\n thetaFreqs\n scale0Freqs\n scaleFreqs\n newHistFilePath\n (emptyHistogram\n [ if maxScale >= 2\n then round maxScale + 1\n else (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 computeUnboxedP $\n computeR2Z2T0S0ArrayRadial\n Pinwheel\n radialArr\n numPoint\n numPoint\n 1\n maxScale\n thetaFreqs\n scaleFreqs\n theta0Freqs\n scale0Freqs\n else do\n flag <- doesFileExist newHistFilePath\n hist <-\n if flag\n then decodeFile newHistFilePath\n else return $\n emptyHistogram\n [ numPoint\n , numPoint\n , L.length scale0Freqs\n , L.length theta0Freqs\n , L.length scaleFreqs\n , L.length thetaFreqs\n ]\n 0\n solveMonteCarloR2Z2T0S0\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 newHistFilePath\n hist\n plan <- makeR2Z2T0S0Plan emptyPlan False \"\" arrR2Z2T0S0\n sourceDistArr <-\n computeInitialDistributionR2T0S0\n plan\n numPoint\n numPoint\n theta0Freqs\n scale0Freqs\n maxScale\n -- initDist\n sourceDist\n sinkDistArr <-\n computeInitialDistributionR2T0S0\n plan\n numPoint\n numPoint\n theta0Freqs\n scale0Freqs\n maxScale\n sinkDist\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 rotate4D2 .\n r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs maxScale $\n sourceR2Z2\n plotImageRepaComplex (folderPath printf \"Source%.0f.png\" s) . ImageRepa 8 $\n sourceField\n -- Sink field\n sinkArr' <- convolveR2T0S0 plan arrR2Z2T0S0F sinkDistArr\n let sinkArr = computeSinkFromSourceR2Z2T0S0 thetaFreqs theta0Freqs sinkArr'\n sinkR2Z2 <- R.sumP . R.sumS . rotateR2Z2T0S0Array $ sinkArr\n sinkField <-\n fmap (computeS . R.extend (Z :. (1 :: Int) :. All :. All)) .\n R.sumP .\n R.sumS .\n rotate4D2 .\n r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs maxScale $\n sinkR2Z2\n plotImageRepaComplex (folderPath printf \"Sink%.0f.png\" s) . ImageRepa 8 $\n sinkField\n -- Completion Filed\n completionFiled <- convolveR2Z2 plan sourceR2Z2 sinkR2Z2\n completionFiledR2 <-\n R.sumP .\n R.sumS .\n rotate4D2 .\n r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs maxScale $\n completionFiled\n plotImageRepaComplex (folderPath printf \"Completion%.0f.png\" s) .\n ImageRepa 8 . computeS . R.extend (Z :. (1 :: Int) :. All :. All) $\n completionFiledR2\n plotImageRepa (folderPath printf \"CompletionMagnitude%.0f.png\" s) .\n ImageRepa 8 .\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.map magnitude $\n completionFiledR2\n", "meta": {"hexsha": "dae87a63c62b3ff4b63ce5f8c8c6c81064932a11", "size": 6649, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2Z2T0S0/STCR2Z2T0S0.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/STCR2Z2T0S0/STCR2Z2T0S0.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/STCR2Z2T0S0/STCR2Z2T0S0.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.4120603015, "max_line_length": 245, "alphanum_fraction": 0.587607159, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5244540885327681}} {"text": "module Proginduction where\n\nimport MHMonad\nimport Distr\nimport Data.Monoid \nimport Statistics.Distribution\nimport Statistics.Distribution.Normal (normalDistr)\nimport Graphics.Rendering.Chart\nimport Graphics.Rendering.Chart.Backend.Diagrams\nimport Graphics.Rendering.Chart.State\nimport Data.Colour\nimport Data.Colour.Names\nimport Data.Default.Class\nimport Control.Lens\n\n-- A grammar for a simple expression language\ndata BinOp = Add | Multiply\ndata UnOp = Neg\ndata Expr = BinOp BinOp Expr Expr\n | UnOp UnOp Expr\n | Number Double\n | Var\n | Cond BoolExpr Expr Expr\ndata BoolExpr = Leq Expr Expr\n\n-- Simple evaluation function for expressions\neval :: Expr -> Double -> Double\neval (BinOp Add e1 e2) x = (eval e1 x) + (eval e2 x)\neval (BinOp Multiply e1 e2) x = (eval e1 x) * (eval e2 x)\neval (UnOp Neg e ) x = - (eval e x)\neval (Number r) x = r\neval (Cond (Leq e1 e2) e3 e4) x = if (eval e1 x) <= (eval e2 x) then (eval e3 x) else (eval e4 x)\neval Var x = x\n\n-- a probabilistic context free grammar\npcfgbinop :: Meas BinOp\npcfgbinop = do n <- categorical [0.5,0.5]\n case n of 0 -> return Add\n 1 -> return Multiply\n\npcfgexpr :: Meas Expr\npcfgexpr = do n <- categorical [0.2,0.1,0.3,0.39,0.01]\n case n of 0 -> do {o <- pcfgbinop ; e1 <- pcfgexpr ; e2 <- pcfgexpr ; return $ BinOp o e1 e2 }\n 1 -> do {e <- pcfgexpr ; return $ UnOp Neg e }\n 2 -> do {r <- normal 0 3 ; return $ Number r }\n 3 -> return $ Var\n 4 -> do {e1 <- return Var ; r <- normal 0 4 ; e3 <- pcfgexpr ; e4 <- pcfgexpr ; return $ Cond (Leq e1 (Number r)) e3 e4 }\n\n-- length of an expression\nlen :: Expr -> Integer\nlen (BinOp _ e1 e2) = len e1 + len e2 + 1\nlen (UnOp _ e1) = len e1 + 1\nlen (Number r) = 1\nlen Var = 1\nlen (Cond (Leq e1 e2) e3 e4) = len e1 + len e2 + len e3 + len e4 + 1\n\n-- a random expression is drawn from the context free grammar,\n-- but then we weight to get a more reasonable length\nrandexpr :: Meas (Double -> Double)\nrandexpr = do { e <- pcfgexpr ;\n score ((normalPdf 25 5) (fromIntegral $ len e)) ;\n return $ \\x -> eval e x }\n\n\n-- functions for plotting a histogram\ntotalweight :: [(Integer,Double)] -> Double\ntotalweight rxs = sum $ map (\\(_,r) -> r) rxs\n\ntoHistogram :: [(Integer,Double)] -> Integer -> Integer -> [Double]\ntoHistogram rxs from to = if from > to then [] else \n ((sum $ map (\\(x,r) -> if x == from then r else 0) rxs) / (totalweight rxs)) : (toHistogram rxs (from + 1) to)\n\nchart :: [Double] -> Renderable ()\nchart rs = toRenderable layout\n where\n layout =\n layout_title .~ \"Sample Bars\" ++ btitle\n $ layout_title_style . font_size .~ 10\n $ layout_x_axis . laxis_generate .~ autoIndexAxis alabels\n $ layout_y_axis . laxis_override .~ axisGridHide\n $ layout_left_axis_visibility . axis_show_ticks .~ False\n $ layout_plots .~ [ plotBars bars2 ]\n $ def :: Layout PlotIndex Double\n\n bars2 = plot_bars_titles .~ [\"\"]\n $ plot_bars_values .~ addIndexes (map (\\x -> [x]) rs) -- [45,30],[30,20],[70,25]]\n-- $ plot_bars_style .~ BarsClustered\n $ plot_bars_spacing .~ BarsFixGap 30 5\n $ plot_bars_item_styles .~ map mkstyle (cycle defaultColorSeq)\n $ def\n\n alabels = map show [0 .. ((length rs)-1)]\n\n btitle = \"\" \n bstyle = Just (solidLine 1.0 $ opaque black) \n mkstyle c = (solidFillStyle c, bstyle)\n\n-- plot a histogram of lengths when the weighted pcfg grammar is used\ntest1 =\n let test =\n do\n e <- pcfgexpr\n -- score ((density $ normalDistr 25 5) (fromIntegral $ len e))\n return $ len e\n in\n do\n rxs' <- weightedsamples test\n let rxs = map (\\(x,r) -> (x,r)) rxs'\n _ <- renderableToFile def \"histogram.svg\" (chart (toHistogram (take 100000 rxs) 0 40))\n return ()\n\nsample_fun f = \n [ (x, f x) | x <- [(-0.25),(-0.25+0.1)..6.2]]\n\nplot_funs :: String -> [(Double,Double)] -> [Double -> Double] -> IO ()\nplot_funs filename dataset funs =\n let graphs = map sample_fun funs in\n let my_lines = plot_lines_style . line_color .~ blue `withOpacity` 0.1\n $ plot_lines_values .~ graphs $ def in\n let my_dots = plot_points_style .~ filledCircles 4 (opaque black)\n $ plot_points_values .~ dataset\n $ def in \n let my_layout = layout_plots .~ [toPlot my_lines , toPlot my_dots]\n $ layout_x_axis .\n laxis_generate .~ scaledAxis def (0,6)\n $ layout_y_axis . laxis_generate .~ scaledAxis def (-2,10)\n $ def in\n let graphic = toRenderable my_layout in\n do\n putStr (\"Generating \" ++ filename ++ \"...\")\n renderableToFile def filename graphic;\n putStrLn (\" Done!\")\n return ()\n\n\ndataset :: [(Double, Double)]\ndataset = [(0,0.6), (1, 0.7), (2,1.2), (3,3.2), (4,6.8), (5, 8.2), (6,8.4)]\n\nfit prior dataset = do f <- prior\n mapM (\\(x,y) -> score $ (density $ normalDistr (f x) 0.3) y) dataset\n return f\n \nevery n xs = case drop (n-1) xs of\n (y:ys) -> y : every n ys\n [] -> []\n\n-- Plot some fitted expressions\ntest3 =\n do\n fs' <- mh $ fit randexpr dataset\n let fs = map (\\(f,_)->f) $ take 10 $ every 1000 $ drop 1000000 $ fs'\n plot_funs \"prog-ind.svg\" dataset fs\n return ()\n\n-- Histogram of the posterior length\ntest4 =\n do\n let posteriorLength =\n do e <- pcfgexpr\n mapM (\\(x,y) -> score $ (density $ normalDistr (eval e x) 0.3) y) dataset\n return (len e)\n ls <- mh $ posteriorLength\n let rxs = map (\\(x,r) -> (x,getProduct r)) ls\n _ <- renderableToFile def \"histogram.svg\" (chart (toHistogram (take 100000 $ drop 100000 rxs) 0 40))\n return ()\n", "meta": {"hexsha": "445cc4f19ecf2c6583bf3e2696a08c8494688a96", "size": 5829, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Proginduction.hs", "max_stars_repo_name": "PiotrJander/oplss-staton", "max_stars_repo_head_hexsha": "6357a1026f11dddde3f90e4ebea3ab3220018a0f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-20T04:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-20T04:44:45.000Z", "max_issues_repo_path": "src/Proginduction.hs", "max_issues_repo_name": "PiotrJander/oplss-staton", "max_issues_repo_head_hexsha": "6357a1026f11dddde3f90e4ebea3ab3220018a0f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Proginduction.hs", "max_forks_repo_name": "PiotrJander/oplss-staton", "max_forks_repo_head_hexsha": "6357a1026f11dddde3f90e4ebea3ab3220018a0f", "max_forks_repo_licenses": ["BSD-3-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.1144578313, "max_line_length": 145, "alphanum_fraction": 0.5928975811, "num_tokens": 1776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5242196607125458}} {"text": "{-# LANGUAGE CPP #-}\n{- MatInv.hs\n - 4x4 Matrix invert function.\n - Direct implementation obtained from Maple's CodeGeneration\n -\n - Timothy A. Chagnon\n - CS 636 - Spring 2009\n -}\nmodule MatInv where\n\n#ifdef USING_HMATRIX\nimport MathHmatrix\nimport Numeric.LinearAlgebra\ninverse4f :: Mat4f -> Mat4f\ninverse4f = inv\n\n#else\nimport MathDirect\n\n-- Analytical solution via Maple (see minv.mw)\ninverse4f :: Mat4f -> Mat4f\ninverse4f (Mat4f (Vec4f m11 m12 m13 m14)\n (Vec4f m21 m22 m23 m24)\n (Vec4f m31 m32 m33 m34)\n (Vec4f m41 m42 m43 m44)) =\n let t1 = m22 * m43 in\n let t3 = m22 * m44 in\n let t5 = m42 * m24 in\n let t7 = m44 * m32 in\n let t9 = m43 * m32 in\n let t11 = m42 * m23 in\n let t14 = m11 * m22 in\n let t15 = m43 * m34 in\n let t17 = m44 * m33 in\n let t19 = m11 * m42 in\n let t20 = m24 * m33 in\n let t22 = m11 * m44 in\n let t23 = m32 * m23 in\n let t25 = m11 * m43 in\n let t26 = m32 * m24 in\n let t28 = m23 * m34 in\n let t30 = m31 * m14 in\n let t32 = m22 * m41 in\n let t33 = m13 * m34 in\n let t35 = m14 * m33 in\n let t37 = m31 * m13 in\n let t39 = m43 * m31 in\n let t40 = m12 * m24 in\n let t42 = m21 * m12 in\n let t44 = -t14 * t15 + t14 * t17 - t19 * t20 - t22 * t23 + t25 * t26 + t19 * t28 + t1 * t30 + t32 * t33 - t32 * t35 - t3 * t37 - t39 * t40 - t17 * t42 in\n let t46 = m42 * m21 in\n let t50 = m41 * m12 in\n let t52 = m21 * m13 in\n let t54 = m41 * m14 in\n let t57 = m44 * m31 in\n let t58 = m12 * m23 in\n let t60 = m41 * m13 in\n let t62 = m21 * m14 in\n let t65 = t5 * t37 - t46 * t33 + t46 * t35 + t15 * t42 + t50 * t20 + t7 * t52 + t54 * t23 - t50 * t28 + t57 * t58 - t60 * t26 - t9 * t62 - t11 * t30 in\n let t67 = 1.0 / (t44 + t65) in\n let t121 = m44 * m21 in\n let t125 = m43 * m21 in\n let t146 = m41 * m32 in\n let t152 = m42 * m31 in\n let t172 = m32 * m11 in\n let t174 = m32 * m21 in\n let t176 = m31 * m12 in\n let r00 = (-t1 * m34 + t3 * m33 - t5 * m33 - t7 * m23 + t9 * m24 + t11 * m34) * t67 in\n let r01 = -(t17 * m12 + m42 * m13 * m34 - m42 * m14 * m33 - t15 * m12 - t7 * m13 + t9 * m14) * t67 in\n let r02 = (t1 * m14 - t3 * m13 - m43 * m12 * m24 + t5 * m13 + m44 * m12 * m23 - t11 * m14) * t67 in\n let r03 = -(-m22 * m13 * m34 + m22 * m14 * m33 - t40 * m33 - m14 * m32 * m23 + t58 * m34 + m13 * m32 * m24) * t67 in\n let r10 = -(t17 * m21 + m41 * m23 * m34 - t15 * m21 - t57 * m23 + t39 * m24 - m41 * m24 * m33) * t67 in\n let r11 = (-t25 * m34 + t22 * m33 + t39 * m14 + t60 * m34 - t54 * m33 - t57 * m13) * t67 in\n let r12 = -(t22 * m23 - t25 * m24 - t121 * m13 - t54 * m23 + t60 * m24 + t125 * m14) * t67 in\n let r13 = (-m11 * m24 * m33 + m11 * m23 * m34 + m24 * m31 * m13 - t52 * m34 + t62 * m33 - m23 * m31 * m14) * t67 in\n let r20 = (t32 * m34 - t3 * m31 + t5 * m31 - t46 * m34 + t7 * m21 - t146 * m24) * t67 in\n let r21 = -(t22 * m32 - t19 * m34 + t152 * m14 + t50 * m34 - t54 * m32 - t57 * m12) * t67 in\n let r22 = (t22 * m22 - t121 * m12 - t54 * m22 - t19 * m24 + t46 * m14 + t50 * m24) * t67 in\n let r23 = -(m34 * m11 * m22 - m34 * m21 * m12 - t30 * m22 - t172 * m24 + t174 * m14 + t176 * m24) * t67 in\n let r30 = -(-t1 * m31 + t32 * m33 - t46 * m33 + t11 * m31 - t146 * m23 + t9 * m21) * t67 in\n let r31 = (-t19 * m33 + t25 * m32 - t39 * m12 + t152 * m13 + t50 * m33 - t60 * m32) * t67 in\n let r32 = -(t25 * m22 - t125 * m12 - t60 * m22 - t19 * m23 + t46 * m13 + t50 * m23) * t67 in\n let r33 = t67 * (m33 * m11 * m22 - m33 * m21 * m12 - t37 * m22 - t172 * m23 + t174 * m13 + t176 * m23) in\n Mat4f (Vec4f r00 r01 r02 r03)\n (Vec4f r10 r11 r12 r13)\n (Vec4f r20 r21 r22 r23)\n (Vec4f r30 r31 r32 r33)\n\n#endif\n", "meta": {"hexsha": "48bdd857bb5f74c90a5ad86614645f3b07b14ac2", "size": 3791, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "a1/MatInv.hs", "max_stars_repo_name": "tchagnon/cs636-raytracer", "max_stars_repo_head_hexsha": "9c297a862822f6ff279b4fbb50ce237b6e24303f", "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": "a1/MatInv.hs", "max_issues_repo_name": "tchagnon/cs636-raytracer", "max_issues_repo_head_hexsha": "9c297a862822f6ff279b4fbb50ce237b6e24303f", "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": "a1/MatInv.hs", "max_forks_repo_name": "tchagnon/cs636-raytracer", "max_forks_repo_head_hexsha": "9c297a862822f6ff279b4fbb50ce237b6e24303f", "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": 42.1222222222, "max_line_length": 157, "alphanum_fraction": 0.5251912424, "num_tokens": 1698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.523940553527574}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\nmodule Main where\n\nimport Lib\nimport Numeric.Vector.Sized\nimport Numeric.Layer.Affine\nimport Numeric.Network\nimport Numeric.Layer.Affine\nimport Numeric.Layer.Sigmoid\nimport Numeric.Loss.MeanSquaredError\nimport qualified Data.Array.Accelerate.Interpreter as AI\nimport qualified Data.Array.Accelerate.LLVM.Native as Native\n\nv :: SizedVector 3\nv = use (fromList [1, 2, 3]) .+. use (fromList [2, 3, 4])\n\nxs :: SizedMatrix 2 3\nxs = use (fromList [1 .. 6])\n-- 1 2 3\n-- 4 5 6\n\nys :: SizedMatrix 3 4\nys = use (fromList [1 .. 12])\n-- 1 2 3 4\n-- 5 6 7 8\n-- 9 10 11 12\n--\nu = use (fromList [1, 2]) :: SizedVector 2\nzs = use (fromList [1, 2, 3, 4]) :: SizedMatrix 2 2\n\naff = affine xs v u\n\nnet :: Network '[Affine 3 2, Sigmoid 2, Affine 2 2, Sigmoid 2]\nnet = Affine ws b :~> Sigmoid () :~> Affine ws' b' :~> Last (Sigmoid ())\n where\n ws = fromList [1, 2, 3, 4, 5, 6]\n b = fromList [1, 2]\n ws' = fromList [-2, 2, 0, 1]\n b' = fromList [0, 1]\n\nmain :: IO ()\nmain = do\n print net'\n where\n net' = train\n net\n (MeanSquaredError () :: MeanSquaredError 2)\n (use $ fromList [-1, -2, -3])\n (use $ fromList [1, 2])\n\n -- print (runUsing Native.run v)\n -- print (runUsing Native.run (xs >< ys))\n -- print (runUsing Native.run (xs #> v))\n -- print (runUsing Native.run (u <# zs))\n -- print (runUsing Native.run aff)\n", "meta": {"hexsha": "146fd244b3fad9377f4e33ce68072d04da077c27", "size": 1398, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "mixed-signals/mixed-signals", "max_stars_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "mixed-signals/mixed-signals", "max_issues_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "mixed-signals/mixed-signals", "max_forks_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5263157895, "max_line_length": 72, "alphanum_fraction": 0.6201716738, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.5234526282800924}} {"text": "\n-- | Hamiltonian Monte Carlo. See, ex: Neal (2012)\n-- http://arxiv.org/pdf/1206.1901.pdf.\n\nmodule Strategy.Hamiltonian (hamiltonian) where\n\nimport Control.Monad.State.Strict\nimport Data.Maybe\nimport qualified Data.Vector.Storable as V\nimport Math.Probably.Sampler\nimport Math.Probably.Types\nimport Math.Probably.Utils\nimport Numeric.LinearAlgebra\n\n-- | A Hamiltonian transition with step size and leapfrog increment tunables.\nhamiltonian :: Maybe Double -> Maybe Int -> Transition (Double, Int)\nhamiltonian e l = do\n Chain (ds, q0) target _ (te, tl) <- get\n let stepSize = fromMaybe te e\n nDisc = fromMaybe tl l\n lTarget = curry (logObjective target) ds\n glTarget = handleGradient $ gradient target\n\n r0 <- V.replicateM (dim q0) (lift unormal)\n zc <- lift unit\n let (q, r) = leapfrogIntegrator glTarget (q0, r0) stepSize nDisc\n next = (ds, nextState lTarget (q0, q) (r0, r) zc)\n\n put $ Chain next target (logObjective target next) (stepSize, nDisc)\n return next\n\n-- | The leapfrog or Stormer-Verlet integrator.\nleapfrogIntegrator :: Gradient -> Particle -> Double -> Int -> Particle\nleapfrogIntegrator glTarget (q0, r0) e = go q0 r0 where\n go q r 0 = (q, r)\n go q r n = let (q1, r1) = leapfrog glTarget (q, r) e\n in go q1 r1 (pred n)\n\n-- | The acceptance probability of a move.\nacceptProb :: (Vector Double -> Double) -> Particle -> Particle -> Double\nacceptProb lTarget (q0, q1) (r0, r1) = exp . min 0 $\n auxilliaryTarget lTarget (q1, r1) - auxilliaryTarget lTarget (q0, r0)\n\n-- | The next state, given a proposal and random value from (0, 1).\nnextState\n :: (Vector Double -> Double)\n -> Particle\n -> Particle\n -> Double\n -> ContinuousParams\nnextState lTarget position momentum z\n | z < pAccept = snd position\n | otherwise = fst position\n where\n pAccept = acceptProb lTarget position momentum\n\n", "meta": {"hexsha": "76f2c6e1149598035561086e3e32829990f1553e", "size": 1865, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Strategy/Hamiltonian.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/Hamiltonian.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/Hamiltonian.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": 32.7192982456, "max_line_length": 77, "alphanum_fraction": 0.691689008, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5234526234734642}} {"text": "{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n{-# LANGUAGE DataKinds, FlexibleContexts, FlexibleInstances, GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses, NoMonomorphismRestriction #-}\n{-# LANGUAGE OverloadedStrings, PolyKinds, TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults -fno-warn-orphans -Wall #-}\nmodule Main where\nimport Algebra.Bridge.Singular\nimport Algebra.Prelude.Core\nimport Control.Monad (void)\nimport Control.Parallel.Strategies\nimport qualified Data.Text as T\nimport qualified Data.Vector.Unboxed as V\nimport Numeric.Field.Fraction (Fraction)\nimport Prelude (read)\nimport Statistics.Resampling\nimport Statistics.Resampling.Bootstrap\nimport Statistics.Types\nimport qualified System.Random.MWC as Rand\n\n\ni2 :: [OrderedPolynomial (Fraction Integer) Grevlex 5]\ni2 = [35 * y^4 - 30*x*y^2 - 210*y^2*z + 3*x^2 + 30*x*z - 105*z^2 +140*y*t - 21*u\n ,5*x*y^3 - 140*y^3*z - 3*x^2*y + 45*x*y*z - 420*y*z^2 + 210*y^2*t -25*x*t + 70*z*t + 126*y*u\n ]\n where [t,u,x,y,z] = vars\n\ni3 :: [OrderedPolynomial (Fraction Integer) Grevlex 4]\ni3 = [ x^31 - x^6 - x- y, x^8 - z, x^10 -t]\n where\n [t,x,y,z] = vars\n\ni4 :: [OrderedPolynomial (Fraction Integer) Grevlex 4]\ni4 = [ w+x+y+z, w*x+x*y+y*z+z*w, w*x*y + x*y*z + y*z*w + z*w*x, w*x*y*z - 1]\n where\n [x,y,z,w] = vars\n\nbenchIdeal :: IsSingularPolynomial poly => Text -> Ideal poly -> IO Double\nbenchIdeal fun i = fmap ((/1000) . read . T.unpack) $ singular $\n toProg fun i\n\ntoProg :: (SingularOrder (Arity poly) (MOrder poly), SingularCoeff (Coefficient poly), IsOrderedPolynomial poly) => Text -> Ideal poly -> Text\ntoProg fun i =\n let expr = funE fun [idealE' i]\n in prettySingular $ do\n directC \"system(\\\"--ticks-per-sec\\\", 1000000)\"\n void $ ringC \"R\" expr\n declOnlyC IdealT \"G\"\n directC \"timer=1\"\n directC \"int t=rtimer\"\n letC \"G\" expr\n directC \"print(rtimer-t)\"\n directC \"exit\"\n\nanalyse :: (IsSingularPolynomial poly) => String -> Text -> Ideal poly -> IO ()\nanalyse lab fun ideal = do\n gen <- Rand.create\n i2Gr <- V.replicateM 200 $ benchIdeal fun ideal\n res <- resample gen [Mean, StdDev] 1000 i2Gr\n let [Estimate mn (ConfInt lbmn ubmn _) ,Estimate dv _]\n = bootstrapBCA cl95 i2Gr res\n putStrLn lab\n putStrLn $ unlines $ map ('\\t':)\n [\"Mean:\\t\" ++ show mn ++ \"(ms)\"\n ,\"MeanLB:\\t\" ++ show lbmn\n ,\"MeanUB:\\t\" ++ show ubmn\n ,\"StdDev:\\t\" ++ show dv\n ]\n\nrunTestCases :: (IsMonomialOrder n o, SingularCoeff k, KnownNat n)\n => String -> Ideal (OrderedPolynomial k o n) -> IO ()\nrunTestCases lab i = do\n analyse (lab ++ \" (Lex, Sing(gr))\") \"groebner\" $ fmap (changeOrder Lex) i\n analyse (lab ++ \" (Lex, Sing(sba))\") \"sba\" $ fmap (changeOrder Lex) i\n analyse (lab ++ \" (Grevlex, Sing(gr))\") \"groebner\" $ fmap (changeOrder Grevlex) i\n analyse (lab ++ \" (Grevlex, Sing(sba))\") \"sba\" $ fmap (changeOrder Grevlex) i\n\nmain :: IO ()\nmain = do\n ideal2 <- return $! (toIdeal i2 `using` rdeepseq)\n ideal3 <- return $! (toIdeal i3 `using` rdeepseq)\n ideal4 <- return $! (toIdeal i4 `using` rdeepseq)\n\n runTestCases \"I1\" ideal2\n runTestCases \"Cyclic4\" ideal4\n analyse \"I3 (Grevlex, Sing(gr))\" \"groebner\" ideal3\n analyse \"I3 (Grevlex, Sing(sba))\" \"sba\" ideal3\n -- analyse \"groebner\" ideal4\n -- analyse \"sba\" ideal4\n -- analyse \"groebner\" ideal3\n -- analyse \"sba\" ideal3\n -- defaultMainWith defaultConfig $\n -- mkTestCases (Left 1) ideal2\n -- ++ mkTestCases (Right \"Cyclic-4\") ideal4\n -- ++ [mkTC \"grevlex03\" ideal3]\n", "meta": {"hexsha": "e502973a9d7653508bcd7ae6b1f5b2136d2b4387", "size": 3744, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "halg-algorithms/bench/singular-bench.hs", "max_stars_repo_name": "hangingman/computational-algebra", "max_stars_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2015-02-09T01:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T04:37:09.000Z", "max_issues_repo_path": "halg-algorithms/bench/singular-bench.hs", "max_issues_repo_name": "hangingman/computational-algebra", "max_issues_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-09-18T16:31:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T08:28:37.000Z", "max_forks_repo_path": "halg-algorithms/bench/singular-bench.hs", "max_forks_repo_name": "hangingman/computational-algebra", "max_forks_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-12-22T16:04:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T19:35:53.000Z", "avg_line_length": 39.0, "max_line_length": 142, "alphanum_fraction": 0.6119123932, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5230519185657001}} {"text": "#!/usr/bin/env stack\n-- stack runghc --resolver lts-16 --package ad --package hmatrix-vector-sized-0.1.3.0 --package vector-sized --package hmatrix --package comonad --package free\n\n-- | Source file accompanying\n-- https://blog.jle.im/entry/hamiltonian-dynamics-in-haskell.html\n\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ViewPatterns #-}\n\nimport Data.Foldable\nimport Data.Maybe\nimport GHC.TypeLits\nimport Numeric.AD\nimport Numeric.LinearAlgebra.Static\nimport Numeric.LinearAlgebra.Static.Vector\nimport qualified Control.Comonad as C\nimport qualified Control.Comonad.Cofree as C\nimport qualified Data.Vector.Sized as V\n\n-- | A @'System' m n@ represents a system parameterized by @n@ generalized\n-- coordinates, moving in an \"underlying\" @m@-dimensional cartesian\n-- coordinate system.\ndata System m n = System\n { sysInertia :: R m -- ^ 'm' vector\n , sysCoords :: R n -> R m -- ^ f\n , sysJacobian :: R n -> L m n -- ^ J_f\n , sysHessian :: R n -> V.Vector n (L m n) -- ^ H_f\n , sysPotential :: R n -> Double -- ^ U\n , sysPotentialGrad :: R n -> R n -- ^ grad U\n }\n\n-- | A system's position in configuration space\ndata Config n = Config\n { confPositions :: R n\n , confVelocities :: R n\n }\n deriving Show\n\n-- | A system's position in phase space\ndata Phase n = Phase\n { phasePositions :: R n\n , phaseMomenta :: R n\n }\n deriving Show\n\n-- | Given a position in @n@-dimensional generalized coordinates, return\n-- the position in the underlying @m@-dimensional cartesian coordinate\n-- system.\nunderlyingPosition\n :: System m n\n -> R n\n -> R m\nunderlyingPosition = sysCoords\n\n-- | Give the system's generalized momenum, given its position in\n-- configuration space.\nmomenta\n :: (KnownNat n, KnownNat m)\n => System m n\n -> Config n\n -> R n\nmomenta s (Config q v) = tr j #> mHat #> j #> v\n where\n j = sysJacobian s q\n mHat = diag (sysInertia s)\n\n-- | Convert a position in configuration space to a position in phase space\ntoPhase\n :: (KnownNat n, KnownNat m)\n => System m n\n -> Config n\n -> Phase n\ntoPhase s c = Phase (confPositions c) (momenta s c)\n\n-- | Shift around the Hessian into the shape expected\ntr2 :: (KnownNat m, KnownNat n)\n => V.Vector m (L n n)\n -> V.Vector n (L m n)\ntr2 = fmap rowsL . traverse lRows\n{-# INLINE tr2 #-}\n\n-- | Vector of vectors to matrix\nvec2l\n :: KnownNat n\n => V.Vector m (V.Vector n Double)\n -> L m n\nvec2l = rowsL . fmap gvecR\n{-# INLINE vec2l #-}\n\n-- | Make a system given its inertias, coordinate functions, and potential\n-- energy function\nmkSystem\n :: (KnownNat m, KnownNat n)\n => R m\n -> (forall a. RealFloat a => V.Vector n a -> V.Vector m a)\n -> (forall a. RealFloat a => V.Vector n a -> a)\n -> System m n\nmkSystem m f u = System\n -- < convert from | actual thing | convert to >\n { sysInertia = m\n , sysCoords = gvecR . f . grVec\n , sysJacobian = tr . vec2l . jacobianT f . grVec\n , sysHessian = tr2 . fmap vec2l . hessianF f . grVec\n , sysPotential = u . grVec\n , sysPotentialGrad = gvecR . grad u . grVec\n }\n\n\n-- | Equations of motion for a system at a given position in phase space\nhamilEqns\n :: (KnownNat n, KnownNat m)\n => System m n\n -> Phase n\n -> (R n, R n) -- dq/dt and dp/dt\nhamilEqns s (Phase q p) = (dqdt, dpdt)\n where\n j = sysJacobian s q\n trj = tr j\n mHat = diag (sysInertia s)\n kHat = trj `mul` mHat `mul` j\n kHatInv = inv kHat\n dqdt = kHatInv #> p\n dpdt = gvecR bigUglyThing - sysPotentialGrad s q\n where\n bigUglyThing =\n fmap (\\j2 -> -p <.> kHatInv #> trj #> mHat #> j2 #> kHatInv #> p)\n (sysHessian s q)\n\n-- | Step a system's position through phase space using Euler integration\nstepEuler\n :: (KnownNat n, KnownNat m)\n => System m n -- ^ the system\n -> Double -- ^ dt\n -> Phase n -- ^ q(t) and p(t)\n -> Phase n -- ^ q(t + dt) and p(t + dt)\nstepEuler s dt ph@(Phase q p) = Phase (q + konst dt * dq) (p + konst dt * dp)\n where\n (dq, dp) = hamilEqns s ph\n\n-- | Iterate Euler's method to repeatedly step a system through phase space\nrunSystem\n :: (KnownNat n, KnownNat m)\n => System m n -- ^ the system\n -> Double -- ^ dt\n -> Phase n -- ^ initial phase\n -> [Phase n] -- ^ progression of the system using Euler integration\nrunSystem s dt = go\n where\n go p0 = p0 : go (stepEuler s dt p0)\n\n-- | A simple particle in 2D cartesian space under gravity\nsimpleSystem :: System 2 2\nsimpleSystem = mkSystem (vec2 5 5) id pot\n where\n -- potential energy of a gravity field\n -- U(x,y) = 9.8 * y\n pot :: RealFloat a => V.Vector 2 a -> a\n pot xy = 9.8 * (xy `V.index` 1)\n\n-- | An initial position in configuration space, representing a particle\n-- at <0,0> with initial velocity <1,3>\nsimpleConfig0 :: Config 2\nsimpleConfig0 = Config\n { confPositions = vec2 0 0\n , confVelocities = vec2 1 3\n }\n\nsimpleMain :: IO ()\nsimpleMain =\n mapM_ (disp 2 . phasePositions) -- position with 2 digits of precision\n . take 25 -- 25 steps\n $ runSystem simpleSystem 0.1 (toPhase simpleSystem simpleConfig0)\n\n\n-- | A pendulum system, parameterized by its angle clockwise from\n-- equilibrium\npendulum :: System 2 1\npendulum = mkSystem (vec2 5 5) coords pot -- 5kg particle\n where\n -- = <-0.5 sin(theta), -0.5 cos(theta)>\n -- pendulum of length 0.25\n coords :: RealFloat a => V.Vector 1 a -> V.Vector 2 a\n coords (V.head->theta) = V.fromTuple (- 0.25 * sin theta, - 0.25 * cos theta)\n -- potential energy of gravity field\n -- U(x,y) = 9.8 * y\n pot :: RealFloat a => V.Vector 1 a -> a\n pot q = 9.8 * (coords q `V.index` 1)\n\n-- | An initial pendulum position in configuration space, representing\n-- a pendulum at equilibrium with initial angular velocity 0.1 rad/sec\n-- clockwise\npendulumConfig0 :: Config 1\npendulumConfig0 = Config\n { confPositions = 0\n , confVelocities = 0.1\n }\n\npendulumMain :: IO ()\npendulumMain =\n mapM_ (disp 3 . phasePositions) -- position with 2 digits of precision\n . take 25 -- 25 steps\n $ runSystem pendulum 0.1 (toPhase pendulum pendulumConfig0)\n\nmain :: IO ()\nmain = pendulumMain\n\n", "meta": {"hexsha": "04b237558d157ea44f4504a5d3479930ec0b2336", "size": 6763, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "code-samples/hamilton1/Hamilton.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/hamilton1/Hamilton.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/hamilton1/Hamilton.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": 32.3588516746, "max_line_length": 159, "alphanum_fraction": 0.5845039184, "num_tokens": 1978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427857178614, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5229855178188046}} {"text": "{-# LANGUAGE BangPatterns, 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 , normalFromSample\n , standard\n ) where\n\nimport Data.Aeson (FromJSON, ToJSON)\nimport Control.Applicative ((<$>), (<*>))\nimport Data.Binary (Binary)\nimport Data.Binary (put, get)\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.MathFunctions.Constants (m_sqrt_2, m_sqrt_2_pi)\nimport Numeric.SpecFunctions (erfc, invErfc)\nimport qualified Statistics.Distribution as D\nimport qualified Statistics.Sample as S\nimport qualified System.Random.MWC.Distributions as MWC\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, Read, Show, Typeable, Data, Generic)\n\ninstance FromJSON NormalDistribution\ninstance ToJSON NormalDistribution\n\ninstance Binary NormalDistribution where\n put (ND w x y z) = put w >> put x >> put y >> put z\n get = ND <$> get <*> get <*> get <*> get\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\ninstance D.MaybeMean NormalDistribution where\n maybeMean = Just . D.mean\n\ninstance D.Mean NormalDistribution where\n mean = mean\n\ninstance D.MaybeVariance NormalDistribution where\n maybeStdDev = Just . D.stdDev\n maybeVariance = Just . D.variance\n\ninstance D.Variance NormalDistribution where\n stdDev = stdDev\n\ninstance D.Entropy NormalDistribution where\n entropy d = 0.5 * log (2 * pi * exp 1 * D.variance d)\n\ninstance D.MaybeEntropy NormalDistribution where\n maybeEntropy = Just . D.entropy\n\ninstance D.ContGen NormalDistribution where\n genContVar d = MWC.normal (mean d) (stdDev d)\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.\nnormalDistr :: Double -- ^ Mean of distribution\n -> Double -- ^ Standard deviation of distribution\n -> NormalDistribution\nnormalDistr m sd\n | sd > 0 = ND { mean = m\n , stdDev = sd\n , ndPdfDenom = log $ m_sqrt_2_pi * sd\n , ndCdfDenom = m_sqrt_2 * sd\n }\n | otherwise =\n error $ \"Statistics.Distribution.Normal.normalDistr: standard deviation must be positive. Got \" ++ show sd\n\n-- | Create distribution using parameters estimated from\n-- sample. Variance is estimated using maximum likelihood method\n-- (biased estimation).\nnormalFromSample :: S.Sample -> NormalDistribution\nnormalFromSample xs\n = normalDistr m (sqrt v)\n where\n (m,v) = S.meanVariance xs\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", "meta": {"hexsha": "f4a444e8a1ea9627ee090ccb0c6f04b86ffec4ff", "size": 4330, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Normal.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/Normal.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/Normal.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3134328358, "max_line_length": 110, "alphanum_fraction": 0.6595842956, "num_tokens": 1131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.522806943010531}} {"text": "module Chapter08 where\n\nimport Numeric.LinearAlgebra.Data\n--import Numeric.LinearAlgebra.Algorithms\nimport Numeric.LinearAlgebra.HMatrix\nimport Data.List as L \n\nimport Chapter04\nimport Chapter06\nimport Chapter07\n\nstopWords :: [String]\nstopWords = [\"a\", \"about\", \"above\", \"above\", \"across\", \"after\",\n \"afterwards\", \"again\", \"against\", \"all\", \"almost\", \"alone\", \"along\",\n \"already\", \"also\", \"although\", \"always\", \"am\", \"among\", \"amongst\",\n \"amoungst\", \"amount\", \"an\", \"and\", \"another\", \"any\", \"anyhow\",\n \"anyone\", \"anything\", \"anyway\", \"anywhere\", \"are\", \"around\", \"as\",\n \"at\", \"back\", \"be\", \"became\", \"because\", \"become\", \"becomes\",\n \"becoming\", \"been\", \"before\", \"beforehand\", \"behind\", \"being\",\n \"below\", \"beside\", \"besides\", \"between\", \"beyond\", \"bill\", \"both\",\n \"bottom\", \"but\", \"by\", \"call\", \"can\", \"cannot\", \"cant\", \"co\", \"con\",\n \"could\", \"couldnt\", \"cry\", \"de\", \"describe\", \"detail\", \"do\", \"done\",\n \"dont\", \"down\", \"due\", \"during\", \"each\", \"eg\", \"eight\", \"either\",\n \"eleven\", \"else\", \"elsewhere\", \"empty\", \"enough\", \"etc\", \"even\",\n \"ever\", \"every\", \"everyone\", \"everything\", \"everywhere\", \"except\",\n \"few\", \"fifteen\", \"fifty\", \"fill\", \"find\", \"fire\", \"first\", \"five\",\n \"for\", \"former\", \"formerly\", \"forty\", \"found\", \"four\", \"from\",\n \"front\", \"full\", \"further\", \"get\", \"give\", \"go\", \"got\", \"had\", \"has\",\n \"hasnt\", \"have\", \"he\", \"hence\", \"her\", \"here\", \"hereafter\", \"hereby\",\n \"herein\", \"hereupon\", \"hers\", \"herself\", \"him\", \"himself\", \"his\",\n \"how\", \"however\", \"hundred\", \"i\", \"ie\", \"if\", \"im\", \"in\", \"inc\",\n \"indeed\", \"interest\", \"into\", \"is\", \"it\", \"its\", \"itself\", \"just\",\n \"keep\", \"last\", \"latter\", \"latterly\", \"least\", \"less\", \"ltd\", \"made\",\n \"many\", \"may\", \"me\", \"meanwhile\", \"might\", \"mill\", \"mine\", \"more\",\n \"moreover\", \"most\", \"mostly\", \"move\", \"much\", \"must\", \"my\", \"myself\",\n \"name\", \"namely\", \"neither\", \"need\", \"never\", \"nevertheless\",\n \"next\", \"nine\", \"no\", \"nobody\", \"none\", \"noone\", \"nor\", \"not\",\n \"nothing\", \"now\", \"nowhere\", \"of\", \"off\", \"often\", \"on\", \"once\",\n \"one\", \"only\", \"onto\", \"or\", \"other\", \"others\", \"otherwise\", \"our\",\n \"ours\", \"ourselves\", \"out\", \"over\", \"own\", \"part\", \"per\", \"perhaps\",\n \"please\", \"put\", \"rather\", \"re\", \"same\", \"see\", \"seem\", \"seemed\",\n \"seeming\", \"seems\", \"serious\", \"several\", \"she\", \"should\", \"show\",\n \"side\", \"since\", \"sincere\", \"six\", \"sixty\", \"so\", \"some\", \"somehow\",\n \"someone\", \"something\", \"sometime\", \"sometimes\", \"somewhere\", \"still\",\n \"such\", \"system\", \"take\", \"ten\", \"than\", \"that\", \"the\", \"their\",\n \"them\", \"themselves\", \"then\", \"thence\", \"there\", \"thereafter\",\n \"thereby\", \"therefore\", \"therein\", \"thereupon\", \"these\", \"they\",\n \"thick\", \"thin\", \"third\", \"this\", \"those\", \"though\", \"three\",\n \"through\", \"throughout\", \"thru\", \"thus\", \"to\", \"together\", \"too\",\n \"top\", \"toward\", \"towards\", \"twelve\", \"twenty\", \"two\", \"un\", \"under\",\n \"until\", \"up\", \"upon\", \"us\", \"very\", \"via\", \"want\", \"was\", \"we\",\n \"well\", \"were\", \"what\", \"whatever\", \"when\", \"whence\", \"whenever\",\n \"where\", \"whereafter\", \"whereas\", \"whereby\", \"wherein\", \"whereupon\",\n \"wherever\", \"whether\", \"which\", \"while\", \"whither\", \"who\", \"whoever\",\n \"whole\", \"whom\", \"whose\", \"why\", \"will\", \"with\", \"within\", \"without\",\n \"would\", \"yet\", \"you\", \"your\", \"youre\", \"yours\", \"yourself\",\n \"yourselves\", \"rt\", \"mt\", \"u\"]\n\nprincipalComponentAnalysis :: [[Double]] -> Integer -> Matrix Double\nprincipalComponentAnalysis records top =\n tr $ mul (tr topOrderedEvectors) (tr featureVectors)\n where featureVectors = fromLists records\n (_, covMatrix) = meanCov featureVectors\n (_, evectors) = eigSH covMatrix\n topOrderedEvectors = takeColumns (fromInteger top) evectors\n\neuclidianDistanceSqrdFromRow :: Matrix Double -> Integer -> Vector Double\neuclidianDistanceSqrdFromRow records row = \n sumOfSquaresVector\n where d = cols records\n copyMatrix = repmat (subMatrix (fromIntegral row, 0) (1,d) records) (rows records) 1\n diffMatrix = records - copyMatrix\n diffSqrdMatrix = diffMatrix * diffMatrix\n sumOfSquaresVector = sum $ toColumns diffSqrdMatrix\n\norder :: Eq a => [a] -> [a] -> [Integer]\norder unsorted nubSorted = \n concatMap \n (\\x -> L.map toInteger $ L.elemIndices x unsorted)\n nubSorted\n\nfindClosestFeaturesToRow :: Matrix Double -> Integer -> Integer -> [Integer]\nfindClosestFeaturesToRow records row knn =\n take (fromIntegral knn) orderOfFeatures\n where sumOfSquares = toList $ euclidianDistanceSqrdFromRow records row \n orderOfFeatures = order sumOfSquares . nub $ sort sumOfSquares", "meta": {"hexsha": "8a1248adae28fbc517cf9e1b699997296c8c04ca", "size": 4617, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Chapter08.hs", "max_stars_repo_name": "ulmalana/haskell-data-analysis", "max_stars_repo_head_hexsha": "2474f756c7a51f7a74e725e67d899e3f737dea3d", "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/Chapter08.hs", "max_issues_repo_name": "ulmalana/haskell-data-analysis", "max_issues_repo_head_hexsha": "2474f756c7a51f7a74e725e67d899e3f737dea3d", "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/Chapter08.hs", "max_forks_repo_name": "ulmalana/haskell-data-analysis", "max_forks_repo_head_hexsha": "2474f756c7a51f7a74e725e67d899e3f737dea3d", "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": 53.6860465116, "max_line_length": 92, "alphanum_fraction": 0.5917262292, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505964, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5227002389115953}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE NoImplicitPrelude #-}\nmodule Main where\n\nimport qualified Prelude as P\nimport Data.Array.Accelerate.Data.Complex as A\nimport Data.Array.Accelerate as A\n-- import qualified Data.Array.Accelerate.Fourier.Adhoc as A\nimport qualified Data.Array.Accelerate.Interpreter as I\nimport Data.Array.Accelerate.Interpreter as I\nimport Data.Array.Accelerate.Data.Fold\nimport Data.Array.Accelerate.Data.Monoid\nimport qualified Data.List as L\nimport qualified Data.Array.Accelerate.LLVM.PTX as PTX\n\nimport qualified Data.Csv as CSV\nimport qualified Data.ByteString.Lazy as BS\nimport qualified Statistics.Sample as S\nimport qualified Data.Vector as V\n\ntype Arr a = Acc (Vector a)\n\nmean :: (Floating a, FromIntegral Int a) => Arr a -> Acc (Scalar a)\nmean xs = unit $ the (fold (+) 0 xs) / (fromIntegral $ length xs)\n\nsmooth :: (Floating a, FromIntegral Int a) => Arr a -> Exp Int -> Arr a\nsmooth xs res = error \"LOL\"\n\nsumF :: (Elt a, Lift Exp a, P.Num (Exp a)) => Fold (Exp a) (Exp a)\nsumF = Fold (lift . Sum) (getSum . unlift)\n\nlengthF :: (Elt a, Lift Exp a, P.Num (Exp a)) => Fold (Exp a) (Exp a)\nlengthF = Fold (\\_ -> 1) (getSum . unlift)\n\nmeanF :: (Elt a, Lift Exp a, P.Fractional (Exp a)) => Fold (Exp a) (Exp a)\nmeanF = sumF / lengthF\n\nvalF :: (Elt a, Monoid (Exp a)) => Fold (Exp a) (Exp a)\nvalF = Fold P.id P.id\n\n-- | E(X^2)\nsumOfSquaresF :: (Elt a, Lift Exp a, P.Num (Exp a)) => Fold (Exp a) (Exp a)\nsumOfSquaresF = Fold (lift . Sum . (^(2 :: Exp Int))) (getSum . unlift)\n\n-- | sqrt (E(X^2) - E(X) ^ 2)\nstandardDeviationF :: (Elt a, Lift Exp a, P.Floating (Exp a)) => Fold (Exp a) (Exp a)\nstandardDeviationF = sqrt $ (sumOfSquaresF / lengthF) - (meanF * meanF)\n\n-- | E(X - mu) ^ 4\n-- differenceQuadsF :: (Elt a, Lift Exp a, P.Fractional (Exp a), Monoid (Exp a)) => Fold (Exp a) (Exp a)\n-- differenceQuadsF = (\\m -> Fold (\\x -> lift $ Sum ((x - m) ^ e)) (getSum . unlift)) P.<$> meanF\n-- where\n-- e = 4 :: Exp Int\n\n-- | E((X - u)^2)^2\n-- otherThing :: (Elt a, Lift Exp a, P.Fractional (Exp a), Monoid (Exp a)) => Fold (Exp a) (Exp a)\n-- otherThing = Fold (lift . Sum . (^(2 :: Exp Int))) (getSum . unlift)\n\n-- kurtosisF :: (Elt a, Lift Exp a, P.Fractional (Exp a), Monoid (Exp a)) => Fold (Exp a) (Exp a)\n-- kurtosisF = (valF - meanF)\n\n-- | Kurt(X) = E(X - u)^4/(E((X - u)^2)^2)\n-- (mean (map (\\x -> x - u) xs)) ^ four / ((mean (map (\\x -> (x - u) ^ two) xs))^two)\nkurtosis :: (Floating a, Elt a, FromIntegral Int a) => Arr a -> Exp a\nkurtosis xs = (u4 / (variance P.^ 2))\n where\n u4 = the $ compute $ mean $ map (\\x -> (x - u) ^ (4 :: Exp Int)) xs\n variance = the $ compute $ mean $ map (\\x -> (x - u) ^ (2 :: Exp Int)) xs\n u = the $ compute $ mean xs\n\ndiffs :: (Elt a, P.Num (Exp a)) => Arr a -> Arr a\ndiffs xs = zipWith (-) (tail xs) xs\n\nroughness :: (Elt a, P.Floating (Exp a), FromIntegral Int a, Lift Exp a) => Arr a -> Acc (Scalar a)\nroughness xs = compute $ runFold standardDeviationF $ diffs xs\n\n-- smoothSimple :: (Elt a, Floating a, FromIntegral Int a, Ord a) => Arr a -> Exp Int -> Arr a\n-- smoothSimple xs resolution =\n-- ifThenElse (resolution < length xs)\n-- smaLargeResolution\n-- (sma bestWindowSize 1 xs)\n-- where\n-- -- THIS IS WRONG. IT NEEDS TO MINIMIZE THE ROUGHNESS\n-- bestWindowSize = the $ minimum $ map fst $ afst $ filter acceptableWindow $ map (go xs) ws\n-- acceptableWindow b =\n-- (r < originalRoughness) && (k >= originalKurt)\n-- where\n-- r = fst $ snd b\n-- k = snd $ snd b\n-- smaLargeResolution = sma (length xs `div` resolution) (length xs `div` resolution) xs\n-- originalKurt = kurtosis xs\n-- originalRoughness = the $ roughness xs\n-- end :: Exp Int\n-- end = length xs `div` 10\n-- ws :: Arr Int\n-- ws = enumFromN (index1 $ end - 2) 2\n\n-- smoothSimple' :: (Elt a, Floating a, FromIntegral Int a, Ord a) => Arr a -> Exp Int -> Arr a\n-- smoothSimple' xs resolution = sma bestWindowSize 1 xs\n-- where\n-- bestWindowSize =\n-- fst $ while (\\a -> fst a >= 2) godude $ lift ((length xs `div` resolution), (originalRoughness, 1 :: Exp Int))\n-- originalKurt = kurtosis xs\n-- originalRoughness = the $ roughness xs\n-- godude a =\n-- let\n-- w = fst a\n-- minObj = fst $ snd a\n-- smoothed = sma w 1 xs\n-- r = the $ roughness smoothed\n-- kurt = kurtosis smoothed\n-- in ifThenElse (r < minObj && kurt >= originalKurt) (lift (w-1, (r, w))) (lift (w-1, snd a))\n\n-- go :: (Elt a, P.Floating (Exp a), FromIntegral Int a) => Arr a -> Exp Int -> Exp (Int, (a, a))\n-- go xs w = lift (w,(the $ roughness smoothed, kurtosis smoothed))\n-- where\n-- smoothed = sma w 1 xs\n\nsma :: (Floating a, FromIntegral Int a) => Exp Int -> Exp Int -> Arr a -> Arr a\nsma range slide xs = mavg range xs\n where\n skip ys =\n map snd. afst\n $ filter (\\y -> fst y `mod` slide == 0)\n $ imap (\\i y -> lift (unindex1 i, y)) ys\n\ncomputeStuff :: (Floating a, FromIntegral Int a, Lift Exp a) => Exp Int -> Exp Int -> Arr a -> Exp (a, a)\ncomputeStuff resolution window xs = lift (the $ roughness smoothed, kurtosis smoothed)\n where\n smoothed = sma window resolution xs\n\nkurtAndRoughness :: (Floating a, FromIntegral Int a, Lift Exp a) => Arr a -> Exp (a, a)\nkurtAndRoughness xs = lift (the $ roughness xs, kurtosis xs)\n\nmavg :: (Floating a, FromIntegral Int a) => Exp Int -> Arr a -> Arr a\nmavg k xs =\n map (/ fromIntegral k)\n $ scanl (+) (the $ sum h)\n $ zipWith (-) t xs\n where\n h = take k xs\n t = drop k xs\n\n-- transform :: Arr (Complex Double) -> Arr (Complex Double)\n-- transform = A.transform A.forward\n\n-- inverseTransform :: Arr (Complex Double) -> Arr (Complex Double)\n-- inverseTransform = A.transform A.inverse\n\nbinarySearch :: Int -> Int -> Arr (Complex Double) -> a -> a -> a -> ()\nbinarySearch h t xs minObj originalKurt windowSize = ()\n\nmain :: P.IO ()\nmain = do\n P.Right xs <- CSV.decode CSV.HasHeader P.<$> BS.readFile \"data.csv\" :: P.IO (P.Either P.String (V.Vector (P.String, Double)))\n\n let\n -- use accelerate-io\n v = V.toList $ P.snd P.<$> xs :: [Double]\n vec = use $ fromList (Z :. (V.length xs)) v\n ws = P.reverse [2..V.length xs `div` 10]\n [(minObj, originalKurt)] = toList $ PTX.runN $ unit $ kurtAndRoughness vec\n runOnWindow w = P.head $ toList $ PTX.runN $ unit $ computeStuff 1 (constant w) vec\n roughsAndKurts = (\\w -> (w, runOnWindow w)) P.<$> ws\n bestWindow@(_, w) = L.foldl' goman (minObj, 1) roughsAndKurts\n goman old@(obj, _) (w,(r, k)) = if (r P.< obj P.&& k P.>= originalKurt) then (r,w) else old\n smoothed = PTX.run $ sma (constant w) 1 vec\n P.print $ L.take 100 roughsAndKurts\n P.print $ (minObj, originalKurt)\n P.print $ V.length xs\n P.print smoothed\n -- P.print $ S.kurtosis $ (V.fromList v :: V.Vector Double)\n -- bestWindowSize = the $ minimum $ map fst $ afst $ filter acceptableWindow $ map (go xs) ws\n -- acceptableWindow b =\n -- (r < originalRoughness) && (k >= originalKurt)\n -- where\n -- r = fst $ snd b\n -- k = snd $ snd b\n -- smaLargeResolution = sma (length xs `div` resolution) (length xs `div` resolution) xs\n -- originalKurt = kurtosis xs\n -- originalRoughness = the $ roughness xs\n -- end :: Exp Int\n -- end = length xs `div` 10\n -- ws :: Arr Int\n -- ws = enumFromN (index1 $ end - 2) 2\n\nmavg' :: P.Fractional b => Int -> [b] -> [b]\nmavg' k lst = P.map (/ P.fromIntegral k) $ L.scanl' (+) (P.sum h) $ P.zipWith (-) t lst\n where (h, t) = L.splitAt k lst", "meta": {"hexsha": "3cbf2306ee16d955fccb5911b4bd50f08eaca0a3", "size": 7570, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "cotrone/hs-asap", "max_stars_repo_head_hexsha": "f1a6679d4a1cc8556d6d4cc0a32993ff631a3820", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-09T15:54:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T15:54:02.000Z", "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "cotrone/hs-asap", "max_issues_repo_head_hexsha": "f1a6679d4a1cc8556d6d4cc0a32993ff631a3820", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "cotrone/hs-asap", "max_forks_repo_head_hexsha": "f1a6679d4a1cc8556d6d4cc0a32993ff631a3820", "max_forks_repo_licenses": ["BSD-3-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.8421052632, "max_line_length": 127, "alphanum_fraction": 0.6062087186, "num_tokens": 2491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5222671738961201}} {"text": "{-# LANGUAGE Strict, StrictData #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE TypeFamilies, TypeFamilyDependencies #-}\n\n------------------------------------------------\n-- |\n-- Module : Numeric.Algebra.Homology\n-- Copyright : (c) Jun Yoshida 2019\n-- License : BSD3\n--\n-- Chain complexes over integers\n--\n------------------------------------------------\n\nmodule Numeric.Algebra.Homology\n (ChainEliminable, Homology(..), homology) where\n\nimport GHC.Generics (Generic, Generic1)\nimport Control.DeepSeq (NFData, force, deepseq)\n\nimport Control.Parallel.Strategies\n\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Control.Applicative\n\nimport Data.STRef\n\nimport Data.Bifunctor\nimport Data.Traversable\nimport Data.Tuple (swap)\nimport Data.Maybe\nimport Data.List\n\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Numeric.LinearAlgebra.Devel as LA\n\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Mutable as MV\n\nimport Numeric.Algebra.FreeModule\nimport Numeric.Algebra.Presentation\nimport Numeric.Matrix.Integral\nimport Numeric.Matrix.Integral.NormalForms\nimport Numeric.F2 (F2)\nimport qualified Numeric.Matrix.F2 as F2\nimport qualified Numeric.Matrix.F2.Mutable as F2\n\n{-- for Debug\nimport Debug.Trace\n\ntraceCond :: Bool -> String -> a -> a\ntraceCond False _ = id\ntraceCond True msg = trace msg\n--}\n\n--------------\n-- * Classes\n--------------\nclass (Normalized a) => ChainEliminable a where\n elimChainHead :: Mat a -> Mat a -> (NormalForm a, Mat a)\n -- ^ If\n -- @ let (a',v) = elimChainHead u a @\n -- Then\n -- @ a' == toNF (a <> u^{-1}) @\n -- and the vectors of v (i.e. toVecs v) induces a basis for the cokernel of a⊗ℚ.\n\n\n-------------------------------------\n-- * Computation of homology groups\n-------------------------------------\ndata Homology a = Homology {\n freeCycs :: [Vec a],\n torsions :: [(a,Vec a)],\n bndries :: [Vec a]\n } deriving (Generic)\n\nderiving instance (Coefficient a, Show a, Show (Vec a)) => Show (Homology a)\nderiving instance (Coefficient a) => NFData (Homology a)\n\n-- | Compute the kernel and the image of a matrix from its normal form.\nhomologyOfNF :: (Normalized a) => NormalForm a -> (Homology a, Homology a)\nhomologyOfNF nf\n = let invs = invariants nf ++ repeat 0\n cycs = map snd $ filter ((==0) . fst) $ zip invs (toVecs (basisDom nf))\n img = filter ((/=0) . fst) $ zip invs (toVecs (basisCod nf))\n (tors,bnds') = partition ((/=1) . fst) img\n bnds = map (uncurry scale) bnds'\n in (Homology [] tors bnds, Homology cycs [] [])\n\n-- | Decompose complexes into two-term complexes with differential in a Smith normal form.\nchainToNormals :: (ChainEliminable a, Traversable t) => t (Mat a) -> (Mat a,t (NormalForm a))\nchainToNormals = first (maybe (ident 0) id) . mapAccumL chainToNormals' Nothing\n where\n chainToNormals' mayU mat\n = let (u,mat') = case mayU of\n Just u -> (u, mat <> u)\n Nothing -> (ident (rankDom mat), mat)\n !(!matNF, !coker) = force (elimChainHead u mat')\n in (Just coker, matNF)\n\n-- | Compute homology group with integral coefficient.\nhomology :: (ChainEliminable a, Traversable t, Alternative t, NFData (t (NormalForm a)), NFData (t (Homology a, Homology a))) => t (Mat a) -> t (Homology a)\nhomology diffs =\n let !(!coker, !nfs) = force (chainToNormals diffs)\n !hs = force (fmap homologyOfNF nfs `using` parTraversable (rparWith rdeepseq))\n in (uncurry ((<|>) . pure)) (mapAccumR pile (Homology (toVecs coker) [] []) hs)\n where\n pile (Homology cycs _ _) (thisH, nextCycH) =\n (nextCycH, thisH {freeCycs = cycs})\n\n-----------------\n-- * Instances\n-----------------\n-- | Enables chain-level Gaussian eliminations on integer matrices.\ninstance ChainEliminable LA.Z where\n elimChainHead basis matA = runST $ do\n stMatA <- LA.thawMatrix matA\n stBasis <- LA.thawMatrix basis\n stU <- LA.thawMatrix (LA.ident (LA.rows matA))\n -- Compute the Smith normal form\n smithRepST stU stMatA stBasis\n -- Write the new basis of the source\n resBasis <- LA.unsafeFreezeMatrix stBasis\n -- Take the invariant factor.\n invFs <- LA.takeDiag <$!> LA.unsafeFreezeMatrix stMatA\n let rkQ = length (takeWhile (/=0) (LA.toList invFs)) -- rank over the field of fractions; e.g. Q for Z\n -- Free closure of the image of matA & its orthogonal.\n fimage <- if LA.rows matA > 0 && rkQ > 0\n then LA.extractMatrix stU LA.AllRows (LA.ColRange 0 (rkQ-1))\n else return $ (LA.rows matA LA.>< 0) []\n fcoker <- if LA.rows matA > 0 && rkQ < LA.rows matA\n then LA.extractMatrix stU LA.AllRows (LA.FromCol rkQ)\n else return $ (LA.rows matA LA.>< 0) []\n return (SmithNF invFs resBasis fimage, fcoker)\n\ninstance ChainEliminable F2 where\n elimChainHead basis matA = runST $ do\n stMatA <- F2.thawMatrixF2 matA\n stBasis <- F2.thawMatrixF2 basis\n stU <- F2.newIdentF2 (F2.rows matA)\n -- Compute the Smith normal form\n rk <- F2.mdiagRepF2 stU stMatA stBasis\n -- Write the new basis of the source\n resBasis <- F2.unsafeFreezeMatrixF2 stBasis\n (fimage,fcoker) <- F2.splitColumnsAt rk <$> F2.unsafeFreezeMatrixF2 stU\n return (DiagNF rk resBasis fimage, fcoker)\n", "meta": {"hexsha": "4b78225e8e09003d196c6a6ee04855408180a38e", "size": 5432, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Algebra/Homology.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/Homology.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/Homology.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": 35.2727272727, "max_line_length": 156, "alphanum_fraction": 0.6461708395, "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5212340900786956}} {"text": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Mutable as VM\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\nimport qualified Data.Vector.Generic as VG\nimport qualified Data.Vector.Generic.Mutable as VGM\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport qualified Data.ByteString.Builder as BSB\nimport Data.Char ( isSpace )\nimport Data.List ( unfoldr )\nimport Data.Function\nimport Data.Complex\nimport Control.Monad\nimport Control.Monad.Primitive\nimport Control.Monad.ST\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n abs <-\n VU.replicateM n\n $ (\\v -> (v VU.! 0, v VU.! 1))\n . VU.unfoldr (BS.readInt . BS.dropWhile isSpace)\n <$> BS.getLine\n let v = uncurry multiplyCT $ VU.unzip abs\n print 0\n VU.mapM_ print v\n\n-- O(n^2) multiply polynomials\nnaiveMultiply :: VU.Vector Int -> VU.Vector Int -> VU.Vector Int\nnaiveMultiply f g = VU.create $ do\n let len = VU.length f + VU.length g - 1\n h <- VUM.new len\n flip VU.imapM_ f $ \\i x ->\n flip VU.imapM_ g $ \\j y -> VUM.modify h (\\z -> z + x * y) (i + j)\n return h\n\n-- O(n log n) multiply polynomials by FFT (Immutable Vector)\n-- 859 ms in atc001-c\n-- c.f. https://qiita.com/ageprocpp/items/0d63d4ed80de4a35fe79\nmultiply :: VU.Vector Int -> VU.Vector Int -> VU.Vector Int\n{-# INLINE multiply #-}\nmultiply !f !g =\n let !len = VU.length f + VU.length g - 1\n !sz = fix (\\rec !k -> if k >= len then k else rec (k * 2)) 1\n !f' = VU.map fromIntegral f\n VU.++ VU.replicate (sz - VU.length f) (0 :: Complex Double)\n !g' = VU.map fromIntegral g\n VU.++ VU.replicate (sz - VU.length g) (0 :: Complex Double)\n in VU.map (round . magnitude . (/ fromIntegral sz))\n . VU.take len\n . dft (-1)\n $ VU.zipWith (*) (dft 1 f') (dft 1 g')\n\n-- DFT algorithm\n-- if sign == 1 then DFT\n-- if sign == -1 then inverse DFT\ndft :: Double -> VU.Vector (Complex Double) -> VU.Vector (Complex Double)\n{-# INLINE dft #-}\ndft !sign !f\n | VU.length f == 1\n = f\n | otherwise\n = let !n = VU.length f\n !nd2 = n `div` 2\n !f0 = dft sign $ VU.map (f VU.!) $ VU.enumFromStepN 0 2 nd2\n !f1 = dft sign $ VU.map (f VU.!) $ VU.enumFromStepN 1 2 nd2\n -- f0 = dft sign $ VU.ifilter (\\i _ -> i `mod` 2 == 0) f\n -- f1 = dft sign $ VU.ifilter (\\i _ -> i `mod` 2 == 1) f\n !zeta = cis (sign * 2 * acos (-1) / fromIntegral n) :: Complex Double\n in VU.imap (\\i z -> (f0 VU.! (i `mod` nd2)) + z * (f1 VU.! (i `mod` nd2)))\n $ VU.iterateN n (* zeta) 1\n\n-- O(n log n) multiply polynomials by FFT \n-- c.f. https://qiita.com/ageprocpp/items/0d63d4ed80de4a35fe79\n-- multiply :: VU.Vector Int -> VU.Vector Int -> VU.Vector Int\n-- multiply 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-- dft nf 1 sz\n-- dft ng 1 sz\n-- forM_ [0..sz-1] $ \\i -> do\n-- y <- VUM.read ng i\n-- VUM.modify nf (* y) i\n-- dft nf (-1) sz\n-- ret <- VU.freeze nf\n-- return $ VU.map ((`div` sz) . round . realPart) $ VU.take len ret\n\n-- DFT algorithm\n-- if sign == 1 then DFT\n-- if sign == -1 then inverse DFT\n-- dft :: PrimMonad m => VUM.MVector (PrimState m) (Complex Double) -> Double -> Int -> m ()\n-- {-# INLINE dft #-}\n-- dft f sign 1 = return ()\n-- dft f sign n = do\n-- let nd2 = n `div` 2\n-- f0 <- VUM.new nd2\n-- f1 <- VUM.new nd2\n-- forM_ [0..nd2-1] $ \\i -> do\n-- x0 <- VUM.read f (2*i)\n-- VUM.write f0 i x0\n-- x1 <- VUM.read f (2*i+1)\n-- VUM.write f1 i x1\n-- dft f0 sign nd2\n-- dft f1 sign nd2\n-- let zeta = cis (sign * 2 * acos (-1) / fromIntegral n)\n-- let zetas = VU.iterateN n (*zeta) 1\n-- flip VU.imapM_ zetas $ \\i z -> do\n-- x0 <- VUM.read f0 (i `mod` nd2)\n-- x1 <- VUM.read f1 (i `mod` nd2)\n-- VUM.write f i (x0 + z * x1)\n\n\n-- O(n log n) multiply polynomials by Cooley-Tukey FFT (Mutable Vector)\n-- 448 ms in atc001-c\n-- c.f. http://wwwa.pikara.ne.jp/okojisan/stockham/cooley-tukey.html\n\n-- This function computes polynomial coefficient of (f * g)(x)\n-- f & g are polynomial coefficient array of f(x) & g(x)\nmultiplyCT :: VU.Vector Int -> VU.Vector Int -> VU.Vector Int\nmultiplyCT 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 multiplyCT #-}\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 θ0 = 2 * pi / fromIntegral n\n forM_ [0 .. m - 1] $ \\p -> do\n let wp = cos (fromIntegral p * θ0) :+ (-sin (fromIntegral p * θ0))\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": "53bc2b03d7e8df23d9594ee182033e761358c817", "size": 6528, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "atc001/c/Main.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": "atc001/c/Main.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": "atc001/c/Main.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": 34.9090909091, "max_line_length": 92, "alphanum_fraction": 0.5706188725, "num_tokens": 2332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5206420955474566}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeInType #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE ViewPatterns #-}\n\nmodule Backprop.Learn.Model.Function (\n -- * Types\n ParamFunc(..)\n , ParamFuncP, pattern PFP, runParamFuncP\n , FixedFunc, pattern FF, runFixedFunc\n , paramMap, learnParam\n , idLearn\n -- ** Combinators\n , dimapPF, lmapPF, rmapPF, compPF, parPF\n -- *** Chain\n , (.-), nilPF, onlyPF\n -- * Activation functions\n -- | See \n --\n -- ** Maps\n -- *** Unparameterized\n , step\n , logistic\n , softsign\n , reLU\n , softPlus\n , bentIdentity\n , siLU\n , softExponential\n , sinc\n , gaussian\n , tanh\n , atan\n , sin\n , vmap\n , vmap'\n -- *** Parameterized\n , liftUniform\n , isru\n , preLU\n , sreLU\n , sreLUPFP\n , eLU\n , isrLU\n , apl\n , aplPFP\n -- ** Mixing\n , softMax\n , maxout\n , kSparse\n ) where\n\nimport Backprop.Learn.Model.Class\nimport Control.Category\nimport Data.Foldable\nimport Data.Proxy\nimport Data.Type.Length\nimport Data.Type.Mayb hiding (type (<$>))\nimport Data.Type.Tuple hiding (T2(..), T3(..))\nimport Data.Typeable\nimport GHC.TypeNats\nimport Numeric.Backprop\nimport Numeric.LinearAlgebra.Static.Backprop hiding (tr)\nimport Prelude hiding ((.), id)\nimport Type.Class.Known\nimport Type.Family.List\nimport qualified Data.Type.Tuple as T\nimport qualified Data.Vector.Sized as SV\nimport qualified Data.Vector.Storable.Sized as SVS\nimport qualified Numeric.LinearAlgebra as HU\nimport qualified Numeric.LinearAlgebra.Static as H\nimport qualified Numeric.LinearAlgebra.Static.Vector as H\n\n-- | An unparameterized function. Has a 'Category' instance.\n--\n-- A @'FixedFunc' a b@ essentially the same as a:\n--\n-- @\n-- forall s. 'Reifies' s 'W' => 'BVar' s a -> 'BVar' s b\n-- @\n--\n-- And the 'FF' pattern (and 'runFixedFunc' extractor) witness this.\n--\n-- It is usually better to just use the functions directly, with\n-- combinators like 'Dimap', 'LMap', 'RMap', 'dimapPF', 'lmapPF', 'rmapPF',\n-- etc. This is just provided to let you work nicely with 'ParamFunc'\n-- combinators.\ntype FixedFunc = ParamFunc 'Nothing\n\n-- | 'FF' and 'runFixedFunc' witness the fact that a @'FixedFunc' a b@ is\n-- just a function from @'BVar' s a@ to @'BVar' s b@.\npattern FF :: (forall s. Reifies s W => BVar s a -> BVar s b) -> FixedFunc a b\npattern FF { runFixedFunc } <- (getFF->runFixedFunc) where\n FF f = PF (const f)\n{-# COMPLETE FF #-}\n\ngetFF :: forall a b. FixedFunc a b -> (forall s. Reifies s W => BVar s a -> BVar s b)\ngetFF ff = runParamFunc ff N_\n\n-- | Identity model, useful for using with other combinators.\nidLearn :: FixedFunc a a\nidLearn = FF id\n\n-- | A @'ParamFunc' p a b@ is a parameterized function from @a@ to @b@,\n-- potentially with trainable parameter @p@.\n--\n-- A utility wrapper for a deterministic and stateless model.\nnewtype ParamFunc p a b =\n PF { runParamFunc :: forall s. Reifies s W => Mayb (BVar s) p -> BVar s a -> BVar s b\n }\n deriving (Typeable)\n\ninstance ( Num a, Num b, MaybeC Num p, KnownMayb p)\n => Learn a b (ParamFunc p a b) where\n type LParamMaybe (ParamFunc p a b) = p\n\n runLearn p = stateless . runParamFunc p\n\ninstance Category (ParamFunc p) where\n id = PF (const id)\n f . g = PF $ \\p -> runParamFunc f p\n . runParamFunc g p\n\n-- | Convenient type synonym for a 'ParamFunc' with parameters.\n--\n-- Mostly made to be easy to construct/deconstruct with 'PFP' and\n-- 'runParamFuncP'.\ntype ParamFuncP p = ParamFunc ('Just p)\n\npattern PFP :: (forall s. Reifies s W => BVar s p -> BVar s a -> BVar s b)\n -> ParamFuncP p a b\npattern PFP { runParamFuncP } <- (getPFP->(getWF->runParamFuncP))\n where\n PFP f = PF $ \\(J_ p) -> f p\n{-# COMPLETE PFP #-}\n\nnewtype WrapFun p a b = WF { getWF :: forall s. Reifies s W => BVar s p -> BVar s a -> BVar s b }\n\ngetPFP :: ParamFuncP p a b -> WrapFun p a b\ngetPFP pf = WF (\\case p -> runParamFunc pf (J_ p))\n\n-- | Create a 'ParamFunc' from any instance of 'Learn' that does not have\n-- state.\nlearnParam\n :: forall l a b. (Learn a b l, NoState l)\n => l\n -> ParamFunc (LParamMaybe l) a b\nlearnParam l = PF (runLearnStateless l)\n\n-- | 'ParamFuncP' taking a singleton list; meant to be used with '.-'\nonlyPF\n :: forall p a b. (KnownMayb p, MaybeC Backprop p)\n => ParamFunc p a b\n -> ParamFuncP (T (MaybeToList p)) a b\nonlyPF f = PFP $ \\ps -> case knownMayb @p of\n N_ -> runParamFunc f N_\n J_ _ -> runParamFunc f (J_ (isoVar tOnly onlyT ps))\n\n\n-- | Compose two 'ParamFuncP's on lists.\n(.-)\n :: forall ps qs a b c. (ListC (Backprop <$> ps), ListC (Backprop <$> qs), Known Length ps)\n => ParamFuncP (T ps) b c\n -> ParamFuncP (T qs) a b\n -> ParamFuncP (T (ps ++ qs)) a c\nf .- g = PFP $ \\ps -> runParamFuncP f (ps ^^. tTake @ps @qs known)\n . runParamFuncP g (ps ^^. tDrop @ps @qs known)\ninfixr 9 .-\n\n-- | The identity of '.-'\nnilPF :: ParamFuncP (T '[]) a a\nnilPF = id\n\n-- | Pre- and post-compose a 'ParamFunc'\ndimapPF\n :: (forall s. Reifies s W => BVar s a -> BVar s b)\n -> (forall s. Reifies s W => BVar s c -> BVar s d)\n -> ParamFunc p b c\n -> ParamFunc p a d\ndimapPF f g h = PF $ \\p -> g . runParamFunc h p . f\n\n-- | Precompose a 'ParamFunc'\nlmapPF\n :: (forall s. Reifies s W => BVar s a -> BVar s b)\n -> ParamFunc p b c\n -> ParamFunc p a c\nlmapPF f = dimapPF f id\n\n-- | Postcompose a 'ParamFunc'\nrmapPF\n :: (forall s. Reifies s W => BVar s b -> BVar s c)\n -> ParamFunc p a b\n -> ParamFunc p a c\nrmapPF = dimapPF id\n\n-- | Compose two 'ParamFunc's sequentially\ncompPF\n :: forall p q a b c. (MaybeC Backprop p, MaybeC Backprop q, KnownMayb p, KnownMayb q)\n => ParamFunc p a b\n -> ParamFunc q b c\n -> ParamFunc (TupMaybe p q) a c\ncompPF f g = PF $ \\pq ->\n let (p, q) = splitTupMaybe @_ @p @q (\\(T2B p' q') -> (p', q')) pq\n in runParamFunc g q . runParamFunc f p\n\n-- | Compose two 'ParamFunc's in parallel\nparPF\n :: forall p q a b c d.\n ( MaybeC Backprop p\n , MaybeC Backprop q\n , KnownMayb p\n , KnownMayb q\n , Backprop a\n , Backprop b\n , Backprop c\n , Backprop d\n )\n => ParamFunc p a c\n -> ParamFunc q b d\n -> ParamFunc (TupMaybe p q) (T.T2 a b) (T.T2 c d)\nparPF f g = PF $ \\pq (T2B x y) ->\n let (p, q) = splitTupMaybe @_ @p @q (\\(T2B p' q') -> (p', q')) pq\n in T2B (runParamFunc f p x)\n (runParamFunc g q y)\n\n-- TODO: replace all of these with manual ops?\n\n-- | Softmax normalizer\nsoftMax\n :: (KnownNat i, Reifies s W)\n => BVar s (R i)\n -> BVar s (R i)\nsoftMax x = expx / konst (norm_1V expx)\n where\n expx = exp x\n\n-- | Logistic function\n--\n-- \\[\n-- \\sigma(x) = \\frac{1}{1 + e^{-x}}\n-- \\]\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n\n-- | Binary step / heaviside step\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n-- \\[\n-- \\begin{cases}\n-- 0 & \\text{for } x < 0 \\\\\n-- 1 & \\text{for } x \\ge 0\n-- \\end{cases}\n-- \\]\nstep :: (Ord a, Num a) => a -> a\nstep x | x < 0 = 0\n | otherwise = 1\n\n-- | Softsign activation function\n--\n-- \\[\n-- \\frac{x}{1 + \\lvert x \\rvert}\n-- \\]\nsoftsign :: Fractional a => a -> a\nsoftsign x = x / (1 + abs x)\n\n-- | Inverse square root unit\n--\n-- \\[\n-- \\frac{x}{\\sqrt{1 + \\alpha x^2}}\n-- \\]\n--\n-- See 'liftUniform' to make this compatible with 'PFP'.\n--\n-- You can also just use this after partially applying it, to fix the\n-- parameter (and not have it trained).\nisru\n :: Floating a\n => a -- ^ α (scaling parameter)\n -> a -- ^ x\n -> a\nisru α x = x / sqrt (1 + α * x * x)\n\n-- | Rectified linear unit.\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n--\n-- \\[\n-- \\max(0,x)\n-- \\]\n--\n-- @\n-- 'reLU' = 'preLU' 0\n-- @\n--\nreLU :: (Num a, Ord a) => a -> a\nreLU x | x < 0 = 0\n | otherwise = x\n\n-- | Parametric rectified linear unit\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n-- If scaling parameter is a fixed (and not learned) parameter, this is\n-- typically called a leaky recitified linear unit (typically with\n-- α = 0.01).\n--\n-- To use as a learned parameter:\n--\n-- @\n-- 'vmap' . 'preLU' :: 'BVar' s Double -> 'BVar' s ('R' n) -> BVar s (R n)\n-- @\n--\n-- This can be give directly to 'PFP'.\n--\n-- To fix the paramater (\"leaky\"), just partially apply a parameter:\n--\n-- @\n-- 'preLU' 0.01 :: 'BVar' s ('R' n) -> BVar s (R n)\n-- preLU ('realToFrac' α) :: BVar s (R n) -> BVar s (R n)\n-- @\n--\n-- See also 'rreLU'.\n--\n-- \\[\n-- \\begin{cases}\n-- \\alpha x & \\text{for } x < 0 \\\\\n-- x & \\text{for } x \\ge 0\n-- \\end{cases}\n-- \\]\npreLU\n :: (Num a, Ord a)\n => a -- ^ α (scaling parameter)\n -> a -- ^ x\n -> a\npreLU α x | x < 0 = α * x\n | otherwise = x\n\n-- | Exponential linear unit\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n-- To use as a learned parameter:\n--\n-- @\n-- 'vmap' . 'eLU' :: 'BVar' s Double -> 'BVar' s ('R' n) -> BVar s (R n)\n-- @\n--\n-- This can be give directly to 'PFP'.\n--\n-- To fix the paramater, just partially apply a parameter:\n--\n-- @\n-- 'vmap'' ('eLU' 0.01) :: 'BVar' s ('R' n) -> BVar s (R n)\n-- @\n--\n-- \\[\n-- \\begin{cases}\n-- \\alpha (e^x - 1) & \\text{for } x < 0 \\\\\n-- x & \\text{for } x \\ge 0\n-- \\end{cases}\n-- \\]\neLU :: (Floating a, Ord a)\n => a -- ^ α (scaling parameter)\n -> a -- ^ x\n -> a\neLU α x | x < 0 = α * (exp x - 1)\n | otherwise = x\n\n-- | S-shaped rectified linear activiation unit\n--\n-- See 'sreLUPFP' for an uncurried and uniformly lifted version usable with\n-- 'PFP'.\n--\n-- \\[\n-- \\begin{cases}\n-- t_l + a_l (x - t_l) & \\text{for } x \\le t_l \\\\\n-- x & \\text{for } t_l < x < t_r \\\\\n-- t_r + a_r (x - t_r) & \\text{for } x \\ge t_r\n-- \\end{cases}\n-- \\]\nsreLU\n :: (Num a, Ord a)\n => a -- ^ @t_l@\n -> a -- ^ @a_l@\n -> a -- ^ @t_r@\n -> a -- ^ @a_l@\n -> a -- ^ @x@\n -> a\nsreLU tl al tr ar x\n | x < tl = tl + al * (x - tl)\n | x > tr = tr + ar * (x - tr)\n | otherwise = x\n\n-- | An uncurried and uniformly lifted version of 'sreLU' directly usable\n-- with 'PFP'.\nsreLUPFP\n :: (KnownNat n, Reifies s W)\n => BVar s (T.T2 (T.T2 Double Double) (T.T2 Double Double))\n -> BVar s (R n)\n -> BVar s (R n)\nsreLUPFP (T2B (T2B tl al) (T2B tr ar)) = vmap (sreLU tl al tr ar)\n\n-- | Inverse square root linear unit\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n-- \\[\n-- \\begin{cases}\n-- \\frac{x}{1 + \\alpha x^2} & \\text{for } x < 0 \\\\\n-- x & \\text{for } x \\ge 0\n-- \\end{cases}\n-- \\]\nisrLU\n :: (Floating a, Ord a)\n => a -- ^ α\n -> a -- ^ x\n -> a\nisrLU α x\n | x < 0 = x / sqrt (1 + α * x * x)\n | otherwise = x\n\n-- | Adaptive piecewise linear activation unit\n--\n-- See 'aplPFP' for an uncurried version usable with 'PFP'.\n--\n-- \\[\n-- \\max(0, x_i) + \\sum_j^M a_i^j \\max(0, -x_i + b_i^j)\n-- \\]\napl :: (KnownNat n, KnownNat m, Reifies s W)\n => BVar s (L n m) -- ^ a\n -> BVar s (L n m) -- ^ b\n -> BVar s (R m) -- ^ x\n -> BVar s (R m)\napl as bs x = vmap' (max 0) x\n + sum (toRows (as * (bs - fromRows (SV.replicate x))))\n\n-- | 'apl' uncurried, to be directly usable with 'PFP'.\naplPFP\n :: (KnownNat n, KnownNat m, Reifies s W)\n => BVar s (T.T2 (L n m) (L n m))\n -> BVar s (R m)\n -> BVar s (R m)\naplPFP (T2B a b) = apl a b\n\n-- | SoftPlus\n--\n-- \\[\n-- \\ln(1 + e^x)\n-- \\]\nsoftPlus :: Floating a => a -> a\nsoftPlus x = log (1 + exp x)\n\n-- | Bent identity\n--\n-- \\[\n-- \\frac{\\sqrt{x^2 + 1} - 1}{2} + x\n-- \\]\nbentIdentity :: Floating a => a -> a\nbentIdentity x = (sqrt (x * x + 1) - 1) / 2 + x\n\n-- | Sigmoid-weighted linear unit. Multiply 'logistic' by its input.\n--\n-- \\[\n-- x \\sigma(x)\n-- \\]\nsiLU :: Floating a => a -> a\nsiLU x = x * logistic x\n\n-- | SoftExponential\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n-- \\[\n-- \\begin{cases}\n-- - \\frac{\\ln(1 - \\alpha (x + \\alpha))}{\\alpha} & \\text{for } \\alpha < 0 \\\\\n-- x & \\text{for } \\alpha = 0 \\\\\n-- \\frac{e^{\\alpha x} - 1}{\\alpha} + \\alpha & \\text{for } \\alpha > 0\n-- \\end{cases}\n-- \\]\nsoftExponential\n :: (Floating a, Ord a)\n => a -- ^ α\n -> a -- ^ x\n -> a\nsoftExponential α x = case compare α x of\n LT -> - log (1 - α * (x + α)) / α\n EQ -> x\n GT -> (exp (α * x) - 1) / α + α\n\n-- | Sinc\n--\n-- \\[\n-- \\begin{cases}\n-- 1 & \\text{for } x = 0 \\\\\n-- \\frac{\\sin(x)}{x} & \\text{for } x \\ne 0\n-- \\end{cases}\n-- \\]\nsinc :: (Floating a, Eq a) => a -> a\nsinc 0 = 1\nsinc x = sin x / x\n\n-- | Gaussian\n--\n-- \\[\n-- e^{-x^2}\n-- \\]\ngaussian :: Floating a => a -> a\ngaussian x = exp (- (x * x))\n\n-- | Maximum of vector.\n--\n-- Compare to 'norm_InfV', which gives the maximum absolute value.\nmaxout :: (KnownNat n, Reifies s W) => BVar s (R n) -> BVar s Double\nmaxout = liftOp1 . op1 $ \\x ->\n let n = HU.maxElement . H.extract $ x\n in ( n\n , \\d -> H.vecR . SVS.map (\\e -> if e == n then d else 0) . H.rVec $ x\n )\n\n-- | Usable with functions like '*', 'isru', etc. to turn them into a form\n-- usable with 'PFP':\n--\n-- @\n-- 'liftUniform' ('*') :: 'BVar' s 'Double' -> BVar s ('R' n) -> BVar s (R n)\n-- liftUniform 'isru' :: BVar s Double -> BVar s (R n) -> BVar s (R n)\n-- @\n--\n-- Basically turns a parmaeterized function on individual elements of\n-- into one that shares the same parameter across all elements of the\n-- vector.\nliftUniform\n :: (Reifies s W, KnownNat n)\n => (BVar s (R n) -> r)\n -> BVar s Double\n -> r\nliftUniform f = f . konst\n\n-- | Utility function to make a 'ParamFunc' that maps a parameterized\n-- function over every item in the 'R'. The parameter is shared across the\n-- entire map, and trained.\nparamMap\n :: KnownNat i\n => (forall s. Reifies s W => Mayb (BVar s) p -> BVar s Double -> BVar s Double)\n -> ParamFunc p (R i) (R i)\nparamMap f = PF (vmap . f)\n\n-- -- TODO: vmap can do better.\n\n-- | Keep only the top @k@ values, and zero out all of the rest.\n--\n-- Useful for postcomposing in between layers (with a logistic function\n-- before) to encourage the number of \"activated\" neurons is kept to be\n-- around @k@. Used in k-Sprase autoencoders (see 'KAutoencoder').\n--\n-- \nkSparse\n :: forall n s. (Reifies s W, KnownNat n)\n => Int -- ^ number of items to keep\n -> BVar s (R n)\n -> BVar s (R n)\nkSparse k = liftOp1 . op1 $ \\xs ->\n let xsSort = HU.sortVector (H.extract xs)\n thresh = xsSort `HU.atIndex` (n - k)\n mask = H.dvmap (\\x -> if x >= thresh then 1 else 0) xs\n in ( H.dvmap (\\x -> if x >= thresh then x else 0) xs\n , (* mask)\n )\n where\n n = fromIntegral $ natVal (Proxy @n)\n", "meta": {"hexsha": "6449a702f320523174756710261922ea4105b952", "size": 15635, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "old2/src/Backprop/Learn/Model/Function.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "old2/src/Backprop/Learn/Model/Function.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "old2/src/Backprop/Learn/Model/Function.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": 26.772260274, "max_line_length": 97, "alphanum_fraction": 0.5430764311, "num_tokens": 5252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5203289268210451}} {"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule FourierPinwheel.Filtering 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 Numeric.GSL.Special.Bessel\nimport Utils.List\n\n{-# INLINE idealLowPassFilter #-}\nidealLowPassFilter ::\n (VG.Vector vector (Complex Double))\n => Double\n -> Double\n -> Int\n -> Int\n -> vector (Complex Double)\nidealLowPassFilter radius period numRhoFreqs numRFreqs =\n let centerRhoFreq = div numRhoFreqs 2\n centerRFreq = div numRFreqs 2\n sinc x =\n if x == 0\n then 1\n else sin (pi * x) / (pi * x)\n in VG.convert .\n toUnboxed . computeS . fromFunction (Z :. numRFreqs :. numRhoFreqs) $ \\(Z :. i' :. j') ->\n let i = i' - centerRFreq\n j = j' - centerRhoFreq\n in -- if i == (j)\n -- then\n (2 * radius) / period *\n sinc (fromIntegral j / period * (2 * radius)) :+\n 0\n -- else 0\n\n{-# INLINE applyFilterRho #-}\napplyFilterRho ::\n DFTPlan\n -> VU.Vector (Complex Double)\n -> R.Array U DIM4 (Complex Double)\n -> IO (R.Array U DIM4 (Complex Double))\napplyFilterRho plan filterF arr' = do\n let (Z :. numRFreqs :. numThetaFreqs :. numRhoFreqs :. numPhiFreqs) =\n extent arr'\n arr =\n computeUnboxedS $\n R.backpermute\n (Z :. numRFreqs :. numRhoFreqs :. numThetaFreqs :. numPhiFreqs)\n (\\(Z :. r :. rho :. theta :. phi) -> (Z :. r :. theta :. rho :. phi))\n arr'\n arrF <-\n fmap (fromUnboxed (extent arr) . VG.convert) .\n dftExecute\n plan\n (DFTPlanID\n DFT1DG\n [numRFreqs, numRhoFreqs, numThetaFreqs, numPhiFreqs]\n [0, 1]) .\n VG.convert . toUnboxed $\n arr\n let convolvedArrF =\n computeUnboxedS .\n R.traverse2\n arrF\n (fromUnboxed (Z :. numRFreqs :. numRhoFreqs) filterF)\n const $ \\fArr fFilter idx@(Z :. r :. rho :. theta :. phi) ->\n fArr idx * fFilter (Z :. r :. rho)\n fmap\n (computeS .\n R.backpermute\n (Z :. numRFreqs :. numThetaFreqs :. numRhoFreqs :. numPhiFreqs)\n (\\(Z :. r :. theta :. rho :. phi) -> (Z :. r :. rho :. theta :. phi)) .\n fromUnboxed (extent arr) . VG.convert) .\n dftExecute\n plan\n (DFTPlanID\n IDFT1DG\n [numRFreqs, numRhoFreqs, numThetaFreqs, numPhiFreqs]\n [0, 1]) .\n VG.convert . toUnboxed $\n convolvedArrF\n\nhollowCoefficients ::\n DFTPlan\n -> Double\n -> Double\n -> R.Array U DIM4 (Complex Double)\n -> IO (R.Array U DIM4 (Complex Double))\nhollowCoefficients plan radius period coefficients = do\n let (Z :. numRFreqs :. _ :. numRhoFreqs :. _) = extent coefficients\n lpf = idealLowPassFilter (log radius) (log period) numRhoFreqs numRFreqs\n filter =\n VG.convert .\n toUnboxed .\n computeS . makeFilter2D . fromUnboxed (Z :. numRFreqs :. numRhoFreqs) $\n lpf\n filterF <-\n VG.convert <$>\n dftExecute plan (DFTPlanID DFT1DG [numRFreqs, numRhoFreqs] [0, 1]) filter\n -- computeS . R.zipWith (-) coefficients <$>\n applyFilterRho plan filterF coefficients\n", "meta": {"hexsha": "536fab4d42842e506222183d78790e86ea62870b", "size": 3402, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FourierPinwheel/Filtering.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/Filtering.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/Filtering.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.7943925234, "max_line_length": 95, "alphanum_fraction": 0.5643738977, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.5202968972325649}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n\nmodule Neural(\n Example,\n initNetwork,\n train,\n predict\n ) where\n\n import Numeric.LinearAlgebra\n import System.Random\n import Debug.Trace\n import Data.List\n\n import Tool\n\n type Example = (Vector Double, Vector Double)\n\n -- Fully connected neural network described in ADT\n data Network where\n -- Start layer : data layer. consists of just one data vector. (homogeneous)\n StartLayer :: Vector Double -> Network\n -- Hidden layer : consists of three elements\n -- 1. network subset that comes before this layer\n -- 2. weight matrix of size ((curr hidden layer dimension), (prev layer output dimension+1)).\n -- 3. current forward values (homogeneous)\n HiddenLayer :: Network -> Matrix Double -> Vector Double -> Network\n -- End layer : softmax layer. consists of three elements\n -- 1. network subset that comes before this layer\n -- 2. current softmax value\n -- 3. current loss of training (not used)\n EndLayer :: Network -> Vector Double -> Double -> Network\n deriving (Show)\n\n {- Activations and loss -}\n\n softmax :: Vector Double -> Vector Double\n softmax v = normalizer `seq` ((\\val -> val / normalizer) `cmap` (exp v))\n where normalizer = sumElements (exp v)\n\n crossEntropy :: Vector Double -> Vector Double -> Double\n crossEntropy t y = -(sumElements $ (t * (log y)))\n\n activation x = tanh x\n\n {- Derivation computations -}\n\n {-\n - jaNodeHidden is a matrix of derivatives\n -\n - dy1/dx1 dy1/dx2 ... dy1/dxr\n - ...\n - dyk/dx1 dyk/dx2 ... dyk/dxr\n -\n - where yi = activation (sum (weight * xj)), dimension of x is r, dimension of y is k.\n -}\n jaNodeHidden :: Matrix Double -> Vector Double -> Matrix Double\n jaNodeHidden weights y = weights * (repeatCols (cols weights) jaActivation)\n where\n jaActivation = 1 - (y^2)\n\n {-\n - jaWeightHidden is a matrix of derivatives\n -\n - dy1/dw11 dy1/dw12 ... dy1/dw1r\n - ...\n - dyk/dwk1 dyk/dwk2 ... dyk/dwkr\n -\n - where yi = activation (sum (wij * xj)), dimension of x is r, dimension of y is k.\n -}\n jaWeightHidden :: Vector Double -> Vector Double -> Matrix Double\n jaWeightHidden x y = jaActivation `outer` jaLinear\n where\n jaActivation = 1 - (y^2)\n jaLinear = x\n\n -- Derivatives of softmax-crossentropy loss function\n jaLoss t y = y - t\n\n {- Network handling -}\n\n -- Initialize network with random weights and zero values\n -- The first argument is dimension of hidden layers.\n -- 0th element represents dimension of the last hidden layer.\n -- 0th element should be equal to the number of classes\n -- The second argument is dimension of input layer.\n -- length of hiddenDims should be larger than or equal to 1\n initNetwork :: [Int] -> Int -> IO Network\n initNetwork hiddenDims inputDim = do\n inner <- initInnerNetwork hiddenDims inputDim\n return $ EndLayer\n inner\n (zeros $ head hiddenDims)\n 0.0\n where\n initInnerNetwork :: [Int] -> Int -> IO Network\n initInnerNetwork hiddenDims inputDim =\n if 1 == length hiddenDims then do\n randWeight <- randmat (-0.5, 0.5) (head hiddenDims) (inputDim+1) -- col+1 for bias\n return $ HiddenLayer\n (StartLayer (homo $ ones inputDim))\n randWeight\n (homo $ zeros (head hiddenDims)) -- append 1 for bias\n else do\n randWeight <- randmat (-0.5, 0.5) (head hiddenDims) (head (tail hiddenDims) + 1) -- col+1 for bias\n prevLayer <- (initInnerNetwork (tail hiddenDims) inputDim)\n return $ HiddenLayer\n prevLayer\n randWeight\n (homo $ zeros (last hiddenDims)) -- append 1 for bias\n\n -- Get a vector value of the last layer of the network\n lastLayerOf :: Network -> Vector Double\n lastLayerOf network = case network of\n StartLayer d -> d\n HiddenLayer _ _ value -> value\n EndLayer _ value _ -> value\n\n -- Train FC neural network 'epoch' times using given examples\n train :: Int -> Double -> [Example] -> Network -> Network\n train epoch learningRate examples network = examples `seq` ((iterate (trainEpoch learningRate examples) network)!!epoch)\n\n -- Train FC neural network with examples\n trainEpoch :: Double -> [Example] -> Network -> Network\n trainEpoch learningRate examples network =\n foldl' (\\acc (input, gt) ->\n ((backward learningRate gt) . forward . (feedData input)) acc\n ) network examples\n\n -- Predict softmax values of network\n predict :: Network -> Vector Double -> Vector Double\n predict network input = (lastLayerOf . forward . (feedData input)) network\n\n -- Prepare Network with input\n feedData :: Vector Double -> Network -> Network\n feedData input network = input `seq` case network of\n StartLayer d -> StartLayer $ homo input\n HiddenLayer prevLayer weights value -> HiddenLayer (feedData input prevLayer) weights value\n EndLayer prevLayer value loss -> EndLayer (feedData input prevLayer) value loss\n\n -- Forward data to update values of Network. Leaves weights of layers unchanged.\n -- Use this for prediction\n forward :: Network -> Network\n forward network = case network of\n StartLayer d -> StartLayer d\n HiddenLayer prevLayer weights _ ->\n value `seq` HiddenLayer prevResult weights value\n where prevResult = forward prevLayer\n value = (homo (activation (weights #> lastLayerOf prevResult)))\n EndLayer prevLayer _ loss ->\n lastVector `seq` EndLayer prevResult (softmax $ invhomo lastVector) loss -- remove the last element since it is meaningless\n where prevResult = forward prevLayer\n lastVector = lastLayerOf prevResult\n\n -- Backpropagate errors to update weights of Network. Leaves values of layers unchanged\n -- Uses stochastic gradient descent\n backward :: Double -> Vector Double -> Network -> Network\n backward learningRate gt (EndLayer prevLayer value _) =\n EndLayer (innerBackward prevLayer lastDiff) value loss\n where\n {-\n - lastDiff is a vector of partial derivatives\n -\n - [dL/dY1 ... dL/dYk]\n -\n - where last softmax layer is k-dimension.\n -}\n lastDiff = jaLoss gt value\n loss = crossEntropy gt value\n\n innerBackward :: Network -> Vector Double -> Network\n innerBackward network nextDiffs = case network of\n StartLayer d -> StartLayer d\n HiddenLayer prevLayer weights values -> newWeights `seq` HiddenLayer (innerBackward prevLayer currDiff) newWeights values\n where\n {-\n - currDiff is a vector of partial derivatives\n -\n - [dL/dX1 ... dL/dXr]\n -\n - where X is the output of previous layer\n -}\n currDiff = (invhomo . flatten) $ ((jaNodeHidden weights (invhomo values)) * (repeatCols (cols weights) nextDiffs)) ? [0]\n newWeights = weightDiff `seq` (weights - ((\\w -> w*learningRate) `cmap` weightDiff))\n where\n {-\n - weightDiff is a matrix filled with partial derivatives\n -\n - dL/dW11 dL/dW12 ... dL/dW1r\n - ...\n - dL/dWk1 dL/dWk2 ... dL/dWkr\n -\n - where this hidden layer have 'k' nodes and previous layer has 'r' nodes\n -}\n weightDiff = pjacobian `seq` (pjacobian * (repeatCols (cols pjacobian) nextDiffs))\n where\n {-\n - pjacobian is a matrix filled with partial derivatives (p is for pseudo)\n -\n - dY1/dW11 dY1/dW12 ... dY1/dW1r\n - ...\n - dYk/dWk1 dYk/dWk2 ... dYk/dWkr\n -\n - where this hidden layer have 'k' nodes and previous layer has 'r' nodes\n -}\n pjacobian = let x = lastLayerOf prevLayer in x `seq` jaWeightHidden x (invhomo values)\n\n", "meta": {"hexsha": "b9d84cdc591745fb77b20781453b23426adc5c3b", "size": 8218, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Neural.hs", "max_stars_repo_name": "ycjungSubhuman/hskmlp", "max_stars_repo_head_hexsha": "e30a8f5ffab52b373090be7b7d2990670bc177e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Neural.hs", "max_issues_repo_name": "ycjungSubhuman/hskmlp", "max_issues_repo_head_hexsha": "e30a8f5ffab52b373090be7b7d2990670bc177e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Neural.hs", "max_forks_repo_name": "ycjungSubhuman/hskmlp", "max_forks_repo_head_hexsha": "e30a8f5ffab52b373090be7b7d2990670bc177e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3205741627, "max_line_length": 134, "alphanum_fraction": 0.6097590655, "num_tokens": 2008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5200137976046815}} {"text": "{-# LANGUAGE TemplateHaskell #-}\nmodule NewTTRS.Law where\n\nimport Control.Lens\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Monoid\nimport Statistics.Distribution (complCumulative, cumulative)\nimport Statistics.Distribution.Normal (normalDistr)\n\nimport NewTTRS.Outcome\n\ndata Law = Law { lawRaw :: !(UArray Int Double)\n , lawMean, lawStddev :: !Double }\n\ndata LawUpdate = LawUpdate\n { playerLaw , opponentLaw :: Law\n , updateOutcome :: Outcome\n }\n\n-- | Law assigned to unrated players\ndefaultLaw :: Law\ndefaultLaw = normalLaw 1800 450\n\n-- | The list of discrete scores characterized by a law\nomega :: [Int]\nomega = [0,10..3600]\n\n-- | The parameter used to characterize upset probability.\nalpha :: Double\nalpha = 0.0148540595817432\n\n-- | Generate a normalized law from a list of probabilities\n-- which correspond to the elements of 'omega'.\nlawFromList :: [Double] -> Law\nlawFromList xs = Law (listArray (0,360) normalized) mean (sqrt variance)\n where\n normalized = fmap (/ sum xs) xs\n mean = sum [ fromIntegral p * x | (p,x) <- zip omega normalized ]\n variance = sum [ fromIntegral (p * p) * x | (p,x) <- zip omega normalized ]\n - mean * mean\n\n-- | Find the probability that the score is in the range of\n-- [i-5,i+5] given a law.\nlawAt :: Law -> Int -> Double\nlawAt law i = lawRaw law ! (i `div` 10)\n{-# INLINE lawAt #-}\n\n-- | Probability of an upset given the difference in two ratings.\nupsetProbability :: Int -> Double\nupsetProbability d = recip (1 + exp (alpha * fromIntegral d))\n\n-- | Perform a bayesian inference given a player's law, the opponent's law\n-- and the outcome of the matches between the two.\nlawUpdate ::\n Law {- ^ Player's law to be updated -} ->\n Law {- ^ Opponent's law -} ->\n Outcome {- ^ Player's outcome against opponent -} ->\n Law\nlawUpdate lp lq outcome\n = lawFromList\n [ sum [ upsetProbability (q - p) ^ w\n * upsetProbability (p - q) ^ l\n * lawAt lq q\n | q <- omega ]\n * lawAt lp p\n | p <- omega\n ]\n where\n w = view outcomeWins outcome\n l = view outcomeLosses outcome\n\n-- | Perform the inverse computation of 'lawUpdate'\nlawUnupdate ::\n Law {- ^ Player's law to be updated -} ->\n Law {- ^ Opponent's law -} ->\n Outcome {- ^ Player's outcome against opponent -} ->\n Law\nlawUnupdate lp lq outcome\n = lawFromList\n [ lawAt lp p\n / sum [ upsetProbability (q - p) ^ w\n * upsetProbability (p - q) ^ l\n * lawAt lq q\n | q <- omega ]\n | p <- omega\n ]\n where\n w = view outcomeWins outcome\n l = view outcomeLosses outcome\n\n-- | Chance that a player with the first law will defeat a player with the second law\nchanceToWin :: Law -> Law -> Double\nchanceToWin lp lq =\n sum [ upsetProbability (q - p)\n * lawAt lp p\n * lawAt lq q\n | q <- omega\n , p <- omega\n ]\n\n-- | Generate a discretized normal law given a mean and standard deviation.\nnormalLaw ::\n Double {- ^ mean -} ->\n Double {- ^ standard deviation -} ->\n Law\nnormalLaw mean stddev = lawFromList $ mkNormal 0 3600 mean stddev\n\n-- | Generate a discrete approximation of a normal distribution.\nmkNormal ::\n Int {- ^ lower bound -} ->\n Int {- ^ upper bound -} ->\n Double {- ^ mean -} ->\n Double {- ^ standard deviation -} ->\n [Double]\nmkNormal lo hi mean stddev =\n [ c (lo + 5) ]\n ++ [ c (p+10) - c p | p <- [lo+5, lo+15 .. hi - 15]]\n ++ [ c' (hi - 5) ]\n where\n distr = normalDistr mean stddev\n c = cumulative distr . fromIntegral\n c' = complCumulative distr . fromIntegral\n\n-- | Degrade a law given a certain number of days. When days is\n-- less than 1, no degrading is done.\ntimeEffect :: Int -> Law -> Law\ntimeEffect days law\n | days <= 0 = law\n | otherwise = lawFromList\n $ sum [ lawAt law x * timeAt y | x <- omega, y <- [-3600,-3590.. -x]]\n : [ sum [ lawAt law x * timeAt (r - x) | x <- omega ]\n | r <- omega \\\\ [0,3600] ]\n ++ [ sum [lawAt law x * timeAt y | x <- omega, y <- [3600-x,3610-x..3600]] ]\n where\n timeArray :: UArray Int Double\n timeArray = listArray (-360,360) $ mkNormal (-3600) 3600 0 (70 * sqrt (fromIntegral days / 365))\n timeAt y = timeArray ! (y `div` 10)\n\n-- | Compute a metric of the law used to order players\nlawScore :: Law -> Double\nlawScore law = lawMean law - 2 * lawStddev law\n\n-- | Return the raw law discrete approximations\nlawElems :: Law -> [Double]\nlawElems = elems . lawRaw\n", "meta": {"hexsha": "2292593bcf4ab7184f37d549c87d6ebc329ff0a0", "size": 4476, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NewTTRS/Law.hs", "max_stars_repo_name": "glguy/newttrs", "max_stars_repo_head_hexsha": "c35c1bbf5344c349607e75df649e71d43b40a71e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T07:32:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T07:32:35.000Z", "max_issues_repo_path": "src/NewTTRS/Law.hs", "max_issues_repo_name": "glguy/newttrs", "max_issues_repo_head_hexsha": "c35c1bbf5344c349607e75df649e71d43b40a71e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewTTRS/Law.hs", "max_forks_repo_name": "glguy/newttrs", "max_forks_repo_head_hexsha": "c35c1bbf5344c349607e75df649e71d43b40a71e", "max_forks_repo_licenses": ["BSD-3-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.4489795918, "max_line_length": 98, "alphanum_fraction": 0.6210902592, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.52001379243276}} {"text": "{-# LANGUAGE NoImplicitPrelude #-}\nmodule Algebra.Additive (\n -- * Class\n C,\n zero,\n (+), (-),\n negate, subtract,\n\n -- * Complex functions\n sum, sum1,\n sumNestedAssociative,\n sumNestedCommutative,\n\n -- * Instance definition helpers\n elementAdd, elementSub, elementNeg,\n (<*>.+), (<*>.-), (<*>.-$),\n\n -- * Instances for atomic types\n propAssociative,\n propCommutative,\n propIdentity,\n propInverse,\n ) where\n\nimport qualified Algebra.Laws as Laws\n\nimport Data.Int (Int, Int8, Int16, Int32, Int64, )\nimport Data.Word (Word, Word8, Word16, Word32, Word64, )\n\nimport qualified NumericPrelude.Elementwise as Elem\nimport Control.Applicative (Applicative(pure, (<*>)), )\nimport Data.Tuple.HT (fst3, snd3, thd3, )\nimport qualified Data.List.Match as Match\n\nimport qualified Data.Complex as Complex98\nimport qualified Data.Ratio as Ratio98\nimport qualified Prelude as P\nimport Prelude (Integer, Float, Double, fromInteger, )\nimport NumericPrelude.Base\n\n\ninfixl 6 +, -\n\n{- |\nAdditive a encapsulates the notion of a commutative group, specified\nby the following laws:\n\n@\n a + b === b + a\n (a + b) + c === a + (b + c)\n zero + a === a\n a + negate a === 0\n@\n\nTypical examples include integers, dollars, and vectors.\n\nMinimal definition: '+', 'zero', and ('negate' or '(-)')\n-}\n\nclass C a where\n {-# MINIMAL zero, (+), ((-) | negate) #-}\n -- | zero element of the vector space\n zero :: a\n -- | add and subtract elements\n (+), (-) :: a -> a -> a\n -- | inverse with respect to '+'\n negate :: a -> a\n\n {-# INLINE negate #-}\n negate a = zero - a\n {-# INLINE (-) #-}\n a - b = a + negate b\n\n{- |\n'subtract' is @(-)@ with swapped operand order.\nThis is the operand order which will be needed in most cases\nof partial application.\n-}\nsubtract :: C a => a -> a -> a\nsubtract = flip (-)\n\n\n\n\n{- |\nSum up all elements of a list.\nAn empty list yields zero.\n\nThis function is inappropriate for number types like Peano.\nMaybe we should make 'sum' a method of Additive.\nThis would also make 'lengthLeft' and 'lengthRight' superfluous.\n-}\nsum :: (C a) => [a] -> a\nsum = foldl (+) zero\n\n{- |\nSum up all elements of a non-empty list.\nThis avoids including a zero which is useful for types\nwhere no universal zero is available.\n-}\nsum1 :: (C a) => [a] -> a\nsum1 = foldl1 (+)\n\n\n{- |\nSum the operands in an order,\nsuch that the dependencies are minimized.\nDoes this have a measurably effect on speed?\n\nRequires associativity.\n-}\nsumNestedAssociative :: (C a) => [a] -> a\nsumNestedAssociative [] = zero\nsumNestedAssociative [x] = x\nsumNestedAssociative xs = sumNestedAssociative (sum2 xs)\n\n{-\nMake sure that the last entries in the list\nare equally often part of an addition.\nMaybe this can reduce rounding errors.\nThe list that sum2 computes is a breadth-first-flattened binary tree.\n\nRequires associativity and commutativity.\n-}\nsumNestedCommutative :: (C a) => [a] -> a\nsumNestedCommutative [] = zero\nsumNestedCommutative xs@(_:rs) =\n let ys = xs ++ Match.take rs (sum2 ys)\n in last ys\n\n_sumNestedCommutative :: (C a) => [a] -> a\n_sumNestedCommutative [] = zero\n_sumNestedCommutative xs@(_:rs) =\n let ys = xs ++ take (length rs) (sum2 ys)\n in last ys\n\n{-\n[a,b,c, a+b,c+(a+b)]\n[a,b,c,d, a+b,c+d,(a+b)+(c+d)]\n[a,b,c,d,e, a+b,c+d,e+(a+b),(c+d)+e+(a+b)]\n[a,b,c,d,e,f, a+b,c+d,e+f,(a+b)+(c+d),(e+f)+((a+b)+(c+d))]\n-}\n\nsum2 :: (C a) => [a] -> [a]\nsum2 (x:y:rest) = (x+y) : sum2 rest\nsum2 xs = xs\n\n\n\n{- |\nInstead of baking the add operation into the element function,\nwe could use higher rank types\nand pass a generic @uncurry (+)@ to the run function.\nWe do not do so in order to stay Haskell 98\nat least for parts of NumericPrelude.\n-}\n{-# INLINE elementAdd #-}\nelementAdd ::\n (C x) =>\n (v -> x) -> Elem.T (v,v) x\nelementAdd f =\n Elem.element (\\(x,y) -> f x + f y)\n\n{-# INLINE elementSub #-}\nelementSub ::\n (C x) =>\n (v -> x) -> Elem.T (v,v) x\nelementSub f =\n Elem.element (\\(x,y) -> f x - f y)\n\n{-# INLINE elementNeg #-}\nelementNeg ::\n (C x) =>\n (v -> x) -> Elem.T v x\nelementNeg f =\n Elem.element (negate . f)\n\n\n-- like <*>\ninfixl 4 <*>.+, <*>.-, <*>.-$\n\n{- |\n> addPair :: (Additive.C a, Additive.C b) => (a,b) -> (a,b) -> (a,b)\n> addPair = Elem.run2 $ Elem.with (,) <*>.+ fst <*>.+ snd\n-}\n{-# INLINE (<*>.+) #-}\n(<*>.+) ::\n (C x) =>\n Elem.T (v,v) (x -> a) -> (v -> x) -> Elem.T (v,v) a\n(<*>.+) f acc =\n f <*> elementAdd acc\n\n{-# INLINE (<*>.-) #-}\n(<*>.-) ::\n (C x) =>\n Elem.T (v,v) (x -> a) -> (v -> x) -> Elem.T (v,v) a\n(<*>.-) f acc =\n f <*> elementSub acc\n\n{-# INLINE (<*>.-$) #-}\n(<*>.-$) ::\n (C x) =>\n Elem.T v (x -> a) -> (v -> x) -> Elem.T v a\n(<*>.-$) f acc =\n f <*> elementNeg acc\n\n\n-- * Instances for atomic types\n\ninstance C Integer where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\ninstance C Float where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\ninstance C Double where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\n\ninstance C Int where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\ninstance C Int8 where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\ninstance C Int16 where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\ninstance C Int32 where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\ninstance C Int64 where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\n\ninstance C Word where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\ninstance C Word8 where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\ninstance C Word16 where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\ninstance C Word32 where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\ninstance C Word64 where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n negate = P.negate\n (+) = (P.+)\n (-) = (P.-)\n\n\n\n\n-- * Instances for composed types\n\ninstance (C v0, C v1) => C (v0, v1) where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = (,) zero zero\n (+) = Elem.run2 $ pure (,) <*>.+ fst <*>.+ snd\n (-) = Elem.run2 $ pure (,) <*>.- fst <*>.- snd\n negate = Elem.run $ pure (,) <*>.-$ fst <*>.-$ snd\n\ninstance (C v0, C v1, C v2) => C (v0, v1, v2) where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = (,,) zero zero zero\n (+) = Elem.run2 $ pure (,,) <*>.+ fst3 <*>.+ snd3 <*>.+ thd3\n (-) = Elem.run2 $ pure (,,) <*>.- fst3 <*>.- snd3 <*>.- thd3\n negate = Elem.run $ pure (,,) <*>.-$ fst3 <*>.-$ snd3 <*>.-$ thd3\n\n\ninstance (C v) => C [v] where\n zero = []\n negate = map negate\n (+) (x:xs) (y:ys) = (+) x y : (+) xs ys\n (+) xs [] = xs\n (+) [] ys = ys\n (-) (x:xs) (y:ys) = (-) x y : (-) xs ys\n (-) xs [] = xs\n (-) [] ys = negate ys\n\n\ninstance (C v) => C (b -> v) where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero _ = zero\n (+) f g x = (+) (f x) (g x)\n (-) f g x = (-) (f x) (g x)\n negate f x = negate (f x)\n\n-- * Properties\n\npropAssociative :: (Eq a, C a) => a -> a -> a -> Bool\npropCommutative :: (Eq a, C a) => a -> a -> Bool\npropIdentity :: (Eq a, C a) => a -> Bool\npropInverse :: (Eq a, C a) => a -> Bool\n\npropCommutative = Laws.commutative (+)\npropAssociative = Laws.associative (+)\npropIdentity = Laws.identity (+) zero\npropInverse = Laws.inverse (+) negate zero\n\n\n\n-- legacy\n\ninstance (P.Integral a) => C (Ratio98.Ratio a) where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n (+) = (P.+)\n (-) = (P.-)\n negate = P.negate\n\ninstance (P.RealFloat a) => C (Complex98.Complex a) where\n {-# INLINE zero #-}\n {-# INLINE negate #-}\n {-# INLINE (+) #-}\n {-# INLINE (-) #-}\n zero = P.fromInteger 0\n (+) = (P.+)\n (-) = (P.-)\n negate = P.negate\n", "meta": {"hexsha": "c16e0bfbae03e12664823dbf10ea3d7f81539070", "size": 9642, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/examples/ghc710/Undefined11.hs", "max_stars_repo_name": "expipiplus1/ghc-exactprint", "max_stars_repo_head_hexsha": "91f54d7a7a1d8d2131c5e83d13dee6c9e8b57831", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2015-01-10T23:15:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T19:53:04.000Z", "max_issues_repo_path": "tests/examples/ghc710/Undefined11.hs", "max_issues_repo_name": "expipiplus1/ghc-exactprint", "max_issues_repo_head_hexsha": "91f54d7a7a1d8d2131c5e83d13dee6c9e8b57831", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 296, "max_issues_repo_issues_event_min_datetime": "2017-07-05T14:35:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T13:23:00.000Z", "max_forks_repo_path": "tests/examples/ghc710/Undefined11.hs", "max_forks_repo_name": "expipiplus1/ghc-exactprint", "max_forks_repo_head_hexsha": "91f54d7a7a1d8d2131c5e83d13dee6c9e8b57831", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2015-02-05T10:08:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T00:59:27.000Z", "avg_line_length": 22.7405660377, "max_line_length": 69, "alphanum_fraction": 0.5035262394, "num_tokens": 3137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5193282003781251}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702\n{-# LANGUAGE Trustworthy #-}\n#endif\n\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.Matrix\n ( (!*!), (!+!), (!-!), (!*), (*!), (!!*), (*!!), (!!/)\n , column\n , adjoint\n , M22, M23, M24, M32, M33, M34, M42, M43, M44\n , m33_to_m44, m43_to_m44\n , det22, det33, det44, inv22, inv33, inv44\n , identity\n , Trace(..)\n , translation\n , transpose\n , fromQuaternion\n , mkTransformation\n , mkTransformationMat\n , _m22, _m23, _m24\n , _m32, _m33, _m34\n , _m42, _m43, _m44\n#if MIN_VERSION_base(4,8,0)\n , lu\n , luFinite\n , forwardSub\n , forwardSubFinite\n , backwardSub\n , backwardSubFinite\n , luSolve\n , luSolveFinite\n , luInv\n , luInvFinite\n , luDet\n , luDetFinite\n#endif\n ) where\n\n#if __GLASGOW_HASKELL__ < 710\nimport Control.Applicative\n#endif\nimport Control.Lens hiding (index)\nimport Control.Lens.Internal.Context\nimport Data.Distributive\nimport Data.Foldable as Foldable\nimport Data.Functor.Rep\nimport Linear.Quaternion\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport Linear.Vector\nimport Linear.Conjugate\nimport Linear.Trace\n\n#if MIN_VERSION_base(4,8,0)\nimport GHC.TypeLits\nimport Linear.V\n#endif\n\n-- $setup\n-- >>> import Control.Lens hiding (index)\n-- >>> import Data.Complex (Complex (..))\n-- >>> import Linear.V2\n-- >>> import Linear.V3\n-- >>> import Linear.V\n-- >>> import Data.IntMap\n-- >>> import Debug.SimpleReflect.Vars\n\n-- | This is a generalization of 'Control.Lens.inside' to work over any corepresentable 'Functor'.\n--\n-- @\n-- 'column' :: 'Representable' f => 'Lens' s t a b -> 'Lens' (f s) (f t) (f a) (f b)\n-- @\n--\n-- In practice it is used to access a column of a matrix.\n--\n-- >>> V2 (V3 1 2 3) (V3 4 5 6) ^._x\n-- V3 1 2 3\n--\n-- >>> V2 (V3 1 2 3) (V3 4 5 6) ^.column _x\n-- V2 1 4\ncolumn :: Representable f => LensLike (Context a b) s t a b -> Lens (f s) (f t) (f a) (f b)\ncolumn l f es = o <$> f i where\n go = l (Context id)\n i = tabulate $ \\ e -> ipos $ go (index es e)\n o eb = tabulate $ \\ e -> ipeek (index eb e) (go (index es e))\n\ninfixl 7 !*!\n-- | Matrix product. This can compute any combination of sparse and dense multiplication.\n--\n-- >>> V2 (V3 1 2 3) (V3 4 5 6) !*! V3 (V2 1 2) (V2 3 4) (V2 4 5)\n-- V2 (V2 19 25) (V2 43 58)\n--\n-- >>> V2 (fromList [(1,2)]) (fromList [(2,3)]) !*! fromList [(1,V3 0 0 1), (2, V3 0 0 5)]\n-- V2 (V3 0 0 2) (V3 0 0 15)\n(!*!) :: (Functor m, Foldable t, Additive t, Additive n, Num a) => m (t a) -> t (n a) -> m (n a)\nf !*! g = fmap (\\ f' -> Foldable.foldl' (^+^) zero $ liftI2 (*^) f' g) f\n\ninfixl 6 !+!\n-- | Entry-wise matrix addition.\n--\n-- >>> V2 (V3 1 2 3) (V3 4 5 6) !+! V2 (V3 7 8 9) (V3 1 2 3)\n-- V2 (V3 8 10 12) (V3 5 7 9)\n(!+!) :: (Additive m, Additive n, Num a) => m (n a) -> m (n a) -> m (n a)\nas !+! bs = liftU2 (^+^) as bs\n\ninfixl 6 !-!\n-- | Entry-wise matrix subtraction.\n--\n-- >>> V2 (V3 1 2 3) (V3 4 5 6) !-! V2 (V3 7 8 9) (V3 1 2 3)\n-- V2 (V3 (-6) (-6) (-6)) (V3 3 3 3)\n(!-!) :: (Additive m, Additive n, Num a) => m (n a) -> m (n a) -> m (n a)\nas !-! bs = liftU2 (^-^) as bs\n\ninfixl 7 !*\n-- | Matrix * column vector\n--\n-- >>> V2 (V3 1 2 3) (V3 4 5 6) !* V3 7 8 9\n-- V2 50 122\n(!*) :: (Functor m, Foldable r, Additive r, Num a) => m (r a) -> r a -> m a\nm !* v = fmap (\\r -> Foldable.sum $ liftI2 (*) r v) m\n\ninfixl 7 *!\n-- | Row vector * matrix\n--\n-- >>> V2 1 2 *! V2 (V3 3 4 5) (V3 6 7 8)\n-- V3 15 18 21\n\n-- (*!) :: (Metric r, Additive n, Num a) => r a -> r (n a) -> n a\n-- f *! g = dot f <$> distribute g\n\n(*!) :: (Num a, Foldable t, Additive f, Additive t) => t a -> t (f a) -> f a\nf *! g = sumV $ liftI2 (*^) f g\n\ninfixl 7 *!!\n-- | Scalar-matrix product\n--\n-- >>> 5 *!! V2 (V2 1 2) (V2 3 4)\n-- V2 (V2 5 10) (V2 15 20)\n(*!!) :: (Functor m, Functor r, Num a) => a -> m (r a) -> m (r a)\ns *!! m = fmap (s *^) m\n{-# INLINE (*!!) #-}\n\ninfixl 7 !!*\n-- | Matrix-scalar product\n--\n-- >>> V2 (V2 1 2) (V2 3 4) !!* 5\n-- V2 (V2 5 10) (V2 15 20)\n(!!*) :: (Functor m, Functor r, Num a) => m (r a) -> a -> m (r a)\n(!!*) = flip (*!!)\n{-# INLINE (!!*) #-}\n\ninfixl 7 !!/\n-- | Matrix-scalar division\n(!!/) :: (Functor m, Functor r, Fractional a) => m (r a) -> a -> m (r a)\nm !!/ s = fmap (^/ s) m\n{-# INLINE (!!/) #-}\n\n-- | Hermitian conjugate or conjugate transpose\n--\n-- >>> adjoint (V2 (V2 (1 :+ 2) (3 :+ 4)) (V2 (5 :+ 6) (7 :+ 8)))\n-- V2 (V2 (1.0 :+ (-2.0)) (5.0 :+ (-6.0))) (V2 (3.0 :+ (-4.0)) (7.0 :+ (-8.0)))\nadjoint :: (Functor m, Distributive n, Conjugate a) => m (n a) -> n (m a)\nadjoint = collect (fmap conjugate)\n{-# INLINE adjoint #-}\n\n-- * Matrices\n--\n-- Matrices use a row-major representation.\n\n-- | A 2x2 matrix with row-major representation\ntype M22 a = V2 (V2 a)\n-- | A 2x3 matrix with row-major representation\ntype M23 a = V2 (V3 a)\n-- | A 2x4 matrix with row-major representation\ntype M24 a = V2 (V4 a)\n-- | A 3x2 matrix with row-major representation\ntype M32 a = V3 (V2 a)\n-- | A 3x3 matrix with row-major representation\ntype M33 a = V3 (V3 a)\n-- | A 3x4 matrix with row-major representation\ntype M34 a = V3 (V4 a)\n-- | A 4x2 matrix with row-major representation\ntype M42 a = V4 (V2 a)\n-- | A 4x3 matrix with row-major representation\ntype M43 a = V4 (V3 a)\n-- | A 4x4 matrix with row-major representation\ntype M44 a = V4 (V4 a)\n\n-- | Build a rotation matrix from a unit 'Quaternion'.\nfromQuaternion :: Num a => Quaternion a -> M33 a\nfromQuaternion (Quaternion w (V3 x y z)) =\n V3 (V3 (1-2*(y2+z2)) (2*(xy-zw)) (2*(xz+yw)))\n (V3 (2*(xy+zw)) (1-2*(x2+z2)) (2*(yz-xw)))\n (V3 (2*(xz-yw)) (2*(yz+xw)) (1-2*(x2+y2)))\n where x2 = x*x\n y2 = y*y\n z2 = z*z\n xy = x*y\n xz = x*z\n xw = x*w\n yz = y*z\n yw = y*w\n zw = z*w\n{-# INLINE fromQuaternion #-}\n\n-- | Build a transformation matrix from a rotation matrix and a\n-- translation vector.\nmkTransformationMat :: Num a => M33 a -> V3 a -> M44 a\nmkTransformationMat (V3 r1 r2 r3) (V3 tx ty tz) =\n V4 (snoc3 r1 tx) (snoc3 r2 ty) (snoc3 r3 tz) (V4 0 0 0 1)\n where snoc3 (V3 x y z) = V4 x y z\n{-# INLINE mkTransformationMat #-}\n\n-- |Build a transformation matrix from a rotation expressed as a\n-- 'Quaternion' and a translation vector.\nmkTransformation :: Num a => Quaternion a -> V3 a -> M44 a\nmkTransformation = mkTransformationMat . fromQuaternion\n{-# INLINE mkTransformation #-}\n\n-- | Convert from a 4x3 matrix to a 4x4 matrix, extending it with the @[ 0 0 0 1 ]@ column vector\nm43_to_m44 :: Num a => M43 a -> M44 a\nm43_to_m44\n (V4 (V3 a b c)\n (V3 d e f)\n (V3 g h i)\n (V3 j k l)) =\n V4 (V4 a b c 0)\n (V4 d e f 0)\n (V4 g h i 0)\n (V4 j k l 1)\n\n-- | Convert a 3x3 matrix to a 4x4 matrix extending it with 0's in the new row and column.\nm33_to_m44 :: Num a => M33 a -> M44 a\nm33_to_m44 (V3 r1 r2 r3) = V4 (vector r1) (vector r2) (vector r3) (point 0)\n\n-- |The identity matrix for any dimension vector.\n--\n-- >>> identity :: M44 Int\n-- V4 (V4 1 0 0 0) (V4 0 1 0 0) (V4 0 0 1 0) (V4 0 0 0 1)\n-- >>> identity :: V3 (V3 Int)\n-- V3 (V3 1 0 0) (V3 0 1 0) (V3 0 0 1)\nidentity :: (Num a, Traversable t, Applicative t) => t (t a)\nidentity = scaled (pure 1)\n\n-- |Extract the translation vector (first three entries of the last\n-- column) from a 3x4 or 4x4 matrix.\ntranslation :: (Representable t, R3 t, R4 v) => Lens' (t (v a)) (V3 a)\ntranslation = column _w._xyz\n{-\ntranslation f rs = aux <$> f (view _w <$> view _xyz rs)\n where aux (V3 x y z) = (_x._w .~ x) . (_y._w .~ y) . (_z._w .~ z) $ rs\n\n-- translation :: (R3 t, R4 v, Functor f, Functor t) => (V3 a -> f (V3 a)) -> t (v a) -> f (t a)\n-- translation = (. fmap (^._w)) . _xyz where\n-- x ^. l = getConst (l Const x)\n-}\n\n-- |Extract a 2x2 matrix from a matrix of higher dimensions by dropping excess\n-- rows and columns.\n_m22 :: (Representable t, R2 t, R2 v) => Lens' (t (v a)) (M22 a)\n_m22 = column _xy._xy\n\n-- |Extract a 2x3 matrix from a matrix of higher dimensions by dropping excess\n-- rows and columns.\n_m23 :: (Representable t, R2 t, R3 v) => Lens' (t (v a)) (M23 a)\n_m23 = column _xyz._xy\n\n-- |Extract a 2x4 matrix from a matrix of higher dimensions by dropping excess\n-- rows and columns.\n_m24 :: (Representable t, R2 t, R4 v) => Lens' (t (v a)) (M24 a)\n_m24 = column _xyzw._xy\n\n-- |Extract a 3x2 matrix from a matrix of higher dimensions by dropping excess\n-- rows and columns.\n_m32 :: (Representable t, R3 t, R2 v) => Lens' (t (v a)) (M32 a)\n_m32 = column _xy._xyz\n\n-- |Extract a 3x3 matrix from a matrix of higher dimensions by dropping excess\n-- rows and columns.\n_m33 :: (Representable t, R3 t, R3 v) => Lens' (t (v a)) (M33 a)\n_m33 = column _xyz._xyz\n\n-- |Extract a 3x4 matrix from a matrix of higher dimensions by dropping excess\n-- rows and columns.\n_m34 :: (Representable t, R3 t, R4 v) => Lens' (t (v a)) (M34 a)\n_m34 = column _xyzw._xyz\n\n-- |Extract a 4x2 matrix from a matrix of higher dimensions by dropping excess\n-- rows and columns.\n_m42 :: (Representable t, R4 t, R2 v) => Lens' (t (v a)) (M42 a)\n_m42 = column _xy._xyzw\n\n-- |Extract a 4x3 matrix from a matrix of higher dimensions by dropping excess\n-- rows and columns.\n_m43 :: (Representable t, R4 t, R3 v) => Lens' (t (v a)) (M43 a)\n_m43 = column _xyz._xyzw\n\n-- |Extract a 4x4 matrix from a matrix of higher dimensions by dropping excess\n-- rows and columns.\n_m44 :: (Representable t, R4 t, R4 v) => Lens' (t (v a)) (M44 a)\n_m44 = column _xyzw._xyzw\n\n-- |2x2 matrix determinant.\n--\n-- >>> det22 (V2 (V2 a b) (V2 c d))\n-- a * d - b * c\ndet22 :: Num a => M22 a -> a\ndet22 (V2 (V2 a b) (V2 c d)) = a * d - b * c\n{-# INLINE det22 #-}\n\n-- |3x3 matrix determinant.\n--\n-- >>> det33 (V3 (V3 a b c) (V3 d e f) (V3 g h i))\n-- a * (e * i - f * h) - d * (b * i - c * h) + g * (b * f - c * e)\ndet33 :: Num a => M33 a -> a\ndet33 (V3 (V3 a b c)\n (V3 d e f)\n (V3 g h i)) = a * (e*i-f*h) - d * (b*i-c*h) + g * (b*f-c*e)\n{-# INLINE det33 #-}\n\n-- |4x4 matrix determinant.\ndet44 :: Num a => M44 a -> a\ndet44 (V4 (V4 i00 i01 i02 i03)\n (V4 i10 i11 i12 i13)\n (V4 i20 i21 i22 i23)\n (V4 i30 i31 i32 i33)) =\n let\n s0 = i00 * i11 - i10 * i01\n s1 = i00 * i12 - i10 * i02\n s2 = i00 * i13 - i10 * i03\n s3 = i01 * i12 - i11 * i02\n s4 = i01 * i13 - i11 * i03\n s5 = i02 * i13 - i12 * i03\n\n c5 = i22 * i33 - i32 * i23\n c4 = i21 * i33 - i31 * i23\n c3 = i21 * i32 - i31 * i22\n c2 = i20 * i33 - i30 * i23\n c1 = i20 * i32 - i30 * i22\n c0 = i20 * i31 - i30 * i21\n in s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0\n{-# INLINE det44 #-}\n\n-- |2x2 matrix inverse.\n--\n-- >>> inv22 $ V2 (V2 1 2) (V2 3 4)\n-- V2 (V2 (-2.0) 1.0) (V2 1.5 (-0.5))\ninv22 :: Fractional a => M22 a -> M22 a\ninv22 m@(V2 (V2 a b) (V2 c d)) = (1 / det) *!! V2 (V2 d (-b)) (V2 (-c) a)\n where det = det22 m\n{-# INLINE inv22 #-}\n\n-- |3x3 matrix inverse.\n--\n-- >>> inv33 $ V3 (V3 1 2 4) (V3 4 2 2) (V3 1 1 1)\n-- V3 (V3 0.0 0.5 (-1.0)) (V3 (-0.5) (-0.75) 3.5) (V3 0.5 0.25 (-1.5))\ninv33 :: Fractional a => M33 a -> M33 a\ninv33 m@(V3 (V3 a b c)\n (V3 d e f)\n (V3 g h i))\n = (1 / det) *!! V3 (V3 a' b' c')\n (V3 d' e' f')\n (V3 g' h' i')\n where a' = cofactor (e,f,h,i)\n b' = cofactor (c,b,i,h)\n c' = cofactor (b,c,e,f)\n d' = cofactor (f,d,i,g)\n e' = cofactor (a,c,g,i)\n f' = cofactor (c,a,f,d)\n g' = cofactor (d,e,g,h)\n h' = cofactor (b,a,h,g)\n i' = cofactor (a,b,d,e)\n cofactor (q,r,s,t) = det22 (V2 (V2 q r) (V2 s t))\n det = det33 m\n{-# INLINE inv33 #-}\n\n\n-- | 'transpose' is just an alias for 'distribute'\n--\n-- > transpose (V3 (V2 1 2) (V2 3 4) (V2 5 6))\n-- V2 (V3 1 3 5) (V3 2 4 6)\ntranspose :: (Distributive g, Functor f) => f (g a) -> g (f a)\ntranspose = distribute\n{-# INLINE transpose #-}\n\n-- |4x4 matrix inverse.\ninv44 :: Fractional a => M44 a -> M44 a\ninv44 (V4 (V4 i00 i01 i02 i03)\n (V4 i10 i11 i12 i13)\n (V4 i20 i21 i22 i23)\n (V4 i30 i31 i32 i33)) =\n let s0 = i00 * i11 - i10 * i01\n s1 = i00 * i12 - i10 * i02\n s2 = i00 * i13 - i10 * i03\n s3 = i01 * i12 - i11 * i02\n s4 = i01 * i13 - i11 * i03\n s5 = i02 * i13 - i12 * i03\n c5 = i22 * i33 - i32 * i23\n c4 = i21 * i33 - i31 * i23\n c3 = i21 * i32 - i31 * i22\n c2 = i20 * i33 - i30 * i23\n c1 = i20 * i32 - i30 * i22\n c0 = i20 * i31 - i30 * i21\n det = s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0\n invDet = recip det\n in invDet *!! V4 (V4 (i11 * c5 - i12 * c4 + i13 * c3)\n (-i01 * c5 + i02 * c4 - i03 * c3)\n (i31 * s5 - i32 * s4 + i33 * s3)\n (-i21 * s5 + i22 * s4 - i23 * s3))\n (V4 (-i10 * c5 + i12 * c2 - i13 * c1)\n (i00 * c5 - i02 * c2 + i03 * c1)\n (-i30 * s5 + i32 * s2 - i33 * s1)\n (i20 * s5 - i22 * s2 + i23 * s1))\n (V4 (i10 * c4 - i11 * c2 + i13 * c0)\n (-i00 * c4 + i01 * c2 - i03 * c0)\n (i30 * s4 - i31 * s2 + i33 * s0)\n (-i20 * s4 + i21 * s2 - i23 * s0))\n (V4 (-i10 * c3 + i11 * c1 - i12 * c0)\n (i00 * c3 - i01 * c1 + i02 * c0)\n (-i30 * s3 + i31 * s1 - i32 * s0)\n (i20 * s3 - i21 * s1 + i22 * s0))\n{-# INLINE inv44 #-}\n\n#if MIN_VERSION_base(4,8,0)\n-- | Compute the (L, U) decomposition of a square matrix using Crout's\n-- algorithm. The 'Index' of the vectors must be 'Integral'.\nlu :: ( Num a\n , Fractional a\n , Foldable m\n , Traversable m\n , Applicative m\n , Additive m\n , Ixed (m a)\n , Ixed (m (m a))\n , i ~ Index (m a)\n , i ~ Index (m (m a))\n , Eq i\n , Integral i\n , a ~ IxValue (m a)\n , m a ~ IxValue (m (m a))\n , Num (m a)\n )\n => m (m a)\n -> (m (m a), m (m a))\nlu a =\n let n = fromIntegral (length a)\n initU = identity\n initL = zero\n buildLVal !i !j !l !u =\n let go !k !s\n | k == j = s\n | otherwise = go (k+1)\n ( s\n + ( (l ^?! ix i ^?! ix k)\n * (u ^?! ix k ^?! ix j)\n )\n )\n s' = go 0 0\n in l & (ix i . ix j) .~ ((a ^?! ix i ^?! ix j) - s')\n buildL !i !j !l !u\n | i == n = l\n | otherwise = buildL (i+1) j (buildLVal i j l u) u\n buildUVal !i !j !l !u =\n let go !k !s\n | k == j = s\n | otherwise = go (k+1)\n ( s\n + ( (l ^?! ix j ^?! ix k)\n * (u ^?! ix k ^?! ix i)\n )\n )\n s' = go 0 0\n in u & (ix j . ix i) .~ ( ((a ^?! ix j ^?! ix i) - s')\n / (l ^?! ix j ^?! ix j)\n )\n buildU !i !j !l !u\n | i == n = u\n | otherwise = buildU (i+1) j l (buildUVal i j l u)\n buildLU !j !l !u\n | j == n = (l, u)\n | otherwise =\n let l' = buildL j j l u\n u' = buildU j j l' u\n in buildLU (j+1) l' u'\n in buildLU 0 initL initU\n\n-- | Compute the (L, U) decomposition of a square matrix using Crout's\n-- algorithm, using the vector's 'Finite' instance to provide an index.\nluFinite :: ( Num a\n , Fractional a\n , Functor m\n , Finite m\n , n ~ Size m\n , KnownNat n\n , Num (m a)\n )\n => m (m a)\n -> (m (m a), m (m a))\nluFinite a =\n bimap (fmap fromV . fromV)\n (fmap fromV . fromV)\n (lu (fmap toV (toV a)))\n\n-- | Solve a linear system with a lower-triangular matrix of coefficients with\n-- forwards substitution.\nforwardSub :: ( Num a\n , Fractional a\n , Foldable m\n , Additive m\n , Ixed (m a)\n , Ixed (m (m a))\n , i ~ Index (m a)\n , i ~ Index (m (m a))\n , Eq i\n , Ord i\n , Integral i\n , a ~ IxValue (m a)\n , m a ~ IxValue (m (m a))\n )\n => m (m a)\n -> m a\n -> m a\nforwardSub a b =\n let n = fromIntegral (length b)\n initX = zero\n coeff !i !j !s !x\n | j == i = s\n | otherwise = coeff i (j+1) (s + ((a ^?! ix i ^?! ix j) * (x ^?! ix j))) x\n go !i !x\n | i == n = x\n | otherwise = go (i + 1) (x & ix i .~ ( ((b ^?! ix i) - coeff i 0 0 x)\n / (a ^?! ix i ^?! ix i)\n ))\n in go 0 initX\n\n-- | Solve a linear system with a lower-triangular matrix of coefficients with\n-- forwards substitution, using the vector's 'Finite' instance to provide an\n-- index.\nforwardSubFinite :: ( Num a\n , Fractional a\n , Foldable m\n , n ~ Size m\n , KnownNat n\n , Additive m\n , Finite m\n )\n => m (m a)\n -> m a\n -> m a\nforwardSubFinite a b = fromV (forwardSub (fmap toV (toV a)) (toV b))\n\n-- | Solve a linear system with an upper-triangular matrix of coefficients with\n-- backwards substitution.\nbackwardSub :: ( Num a\n , Fractional a\n , Foldable m\n , Additive m\n , Ixed (m a)\n , Ixed (m (m a))\n , i ~ Index (m a)\n , i ~ Index (m (m a))\n , Eq i\n , Ord i\n , Integral i\n , a ~ IxValue (m a)\n , m a ~ IxValue (m (m a))\n )\n => m (m a)\n -> m a\n -> m a\nbackwardSub a b =\n let n = fromIntegral (length b)\n initX = zero\n coeff !i !j !s !x\n | j == n = s\n | otherwise = coeff i\n (j+1)\n (s + ((a ^?! ix i ^?! ix j) * (x ^?! ix j)))\n x\n go !i !x\n | i < 0 = x\n | otherwise = go (i-1)\n (x & ix i .~ ( ((b ^?! ix i) - coeff i (i+1) 0 x)\n / (a ^?! ix i ^?! ix i)\n ))\n in go (n-1) initX\n\n-- | Solve a linear system with an upper-triangular matrix of coefficients with\n-- backwards substitution, using the vector's 'Finite' instance to provide an\n-- index.\nbackwardSubFinite :: ( Num a\n , Fractional a\n , Foldable m\n , n ~ Size m\n , KnownNat n\n , Additive m\n , Finite m\n )\n => m (m a)\n -> m a\n -> m a\nbackwardSubFinite a b = fromV (backwardSub (fmap toV (toV a)) (toV b))\n\n-- | Solve a linear system with LU decomposition.\nluSolve :: ( Num a\n , Fractional a\n , Foldable m\n , Traversable m\n , Applicative m\n , Additive m\n , Ixed (m a)\n , Ixed (m (m a))\n , i ~ Index (m a)\n , i ~ Index (m (m a))\n , Eq i\n , Integral i\n , a ~ IxValue (m a)\n , m a ~ IxValue (m (m a))\n , Num (m a)\n )\n => m (m a)\n -> m a\n -> m a\nluSolve a b =\n let (l, u) = lu a\n in backwardSub u (forwardSub l b)\n\n-- | Solve a linear system with LU decomposition, using the vector's 'Finite'\n-- instance to provide an index.\nluSolveFinite :: ( Num a\n , Fractional a\n , Functor m\n , Finite m\n , n ~ Size m\n , KnownNat n\n , Num (m a)\n )\n => m (m a)\n -> m a\n -> m a\nluSolveFinite a b = fromV (luSolve (fmap toV (toV a)) (toV b))\n\n-- | Invert a matrix with LU decomposition.\nluInv :: ( Num a\n , Fractional a\n , Foldable m\n , Traversable m\n , Applicative m\n , Additive m\n , Distributive m\n , Ixed (m a)\n , Ixed (m (m a))\n , i ~ Index (m a)\n , i ~ Index (m (m a))\n , Eq i\n , Integral i\n , a ~ IxValue (m a)\n , m a ~ IxValue (m (m a))\n , Num (m a)\n )\n => m (m a)\n -> m (m a)\nluInv a =\n let n = fromIntegral (length a)\n initA' = zero\n (l, u) = lu a\n go !i !a'\n | i == n = a'\n | otherwise = let e = zero & ix i .~ 1\n a'r = backwardSub u (forwardSub l e)\n in go (i+1) (a' & ix i .~ a'r)\n in transpose (go 0 initA')\n\n-- | Invert a matrix with LU decomposition, using the vector's 'Finite' instance\n-- to provide an index.\nluInvFinite :: ( Num a\n , Fractional a\n , Functor m\n , Finite m\n , n ~ Size m\n , KnownNat n\n , Num (m a)\n )\n => m (m a)\n -> m (m a)\nluInvFinite a = fmap fromV (fromV (luInv (fmap toV (toV a))))\n\n-- | Compute the determinant of a matrix using LU decomposition.\nluDet :: ( Num a\n , Fractional a\n , Foldable m\n , Traversable m\n , Applicative m\n , Additive m\n , Trace m\n , Ixed (m a)\n , Ixed (m (m a))\n , i ~ Index (m a)\n , i ~ Index (m (m a))\n , Eq i\n , Integral i\n , a ~ IxValue (m a)\n , m a ~ IxValue (m (m a))\n , Num (m a)\n )\n => m (m a)\n -> a\nluDet a =\n let (l, u) = lu a\n p = Foldable.foldl (*) 1\n in (p (diagonal l)) * (p (diagonal u))\n\n-- | Compute the determinant of a matrix using LU decomposition, using the\n-- vector's 'Finite' instance to provide an index.\nluDetFinite :: ( Num a\n , Fractional a\n , Functor m\n , Finite m\n , n ~ Size m\n , KnownNat n\n , Num (m a)\n )\n => m (m a)\n -> a\nluDetFinite = luDet . fmap toV . toV\n#endif\n", "meta": {"hexsha": "87bbc5d9f863f462e95d29bd14d87a5d8f99da57", "size": 23115, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Linear/Matrix.hs", "max_stars_repo_name": "TravisWhitaker/linear", "max_stars_repo_head_hexsha": "9bb5d69d25f96dd338769f81927d5101b90663af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Linear/Matrix.hs", "max_issues_repo_name": "TravisWhitaker/linear", "max_issues_repo_head_hexsha": "9bb5d69d25f96dd338769f81927d5101b90663af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Linear/Matrix.hs", "max_forks_repo_name": "TravisWhitaker/linear", "max_forks_repo_head_hexsha": "9bb5d69d25f96dd338769f81927d5101b90663af", "max_forks_repo_licenses": ["BSD-3-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.1103633917, "max_line_length": 98, "alphanum_fraction": 0.4669262384, "num_tokens": 8079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.519328194760383}} {"text": "{-# LANGUAGE BangPatterns , RankNTypes, GADTs, DataKinds #-}\n\n{- | The 'Numerical.HBLAS.BLAS.Level2' module provides a fully general\nyet type safe Level2 BLAS API.\n\nWhen in doubt about the semantics of an operation,\nconsult your system's BLAS api documentation, or just read the documentation\nfor\n\n\nA few basic notes about how to invoke BLAS routines.\n\nMany BLAS operations take one or more arguments of type 'Transpose'.\n'Tranpose' has the following different constructors, which tell BLAS\nroutines what transformation to implicitly apply to an input matrix @mat@ with dimension @n x m@.\n\n* 'NoTranspose' leaves the matrix @mat@ as is.\n\n* 'Transpose' treats the @mat@ as being implicitly transposed, with dimension\n @m x n@. Entry @mat(i,j)@ being treated as actually being the entry\n @mat(j,i)@. For Real matrices this is also the matrix adjoint operation.\n ie @Tranpose(mat)(i,j)=mat(j,i)@\n\n* 'ConjNoTranspose' will implicitly conjugate @mat@, which is a no op for Real ('Float' or 'Double') matrices, but for\n'Complex Float' and 'Complex Double' matrices, a given matrix entry @mat(i,j)==x':+'y@\nwill be treated as actually being @conjugate(mat)(i,j)=y':+'x@.\n\n* 'ConjTranpose' will implicitly transpose and conjugate the input matrix.\nConjugateTranpose acts as matrix adjoint for both real and complex matrices.\n\n\n\nThe *gemm operations work as follows (using 'sgemm' as an example):\n\n* @'sgemm trLeft trRight alpha beta left right result'@, where @trLeft@ and @trRight@\nare values of type 'Transpose' that respectively act on the matrices @left@ and @right@.\n\n* the generalized matrix computation thusly formed can be viewed as being\n@result = alpha * trLeft(left) * trRight(right) + beta * result@\n\n\nthe *gemv operations are akin to the *gemm operations, but with @right@ and @result@\nbeing vectors rather than matrices.\n\n\nthe *trsv operations solve for @x@ in the equation @A x = y@ given @A@ and @y@.\nThe 'MatUpLo' argument determines if the matrix should be treated as upper or\nlower triangular and 'MatDiag' determines if the triangular solver should treat\nthe diagonal of the matrix as being all 1's or not. A general pattern of invocation\nwould be @'strsv' matuplo tranposeMatA matdiag matrixA xVector@.\nA key detail to note is that the input vector is ALSO the result vector,\nie 'strsv' and friends updates the vector place.\n\n-}\n\nmodule Numerical.HBLAS.BLAS.Level2(\n sgbmv\n ,dgbmv\n ,cgbmv\n ,zgbmv\n\n ,sgemv\n ,dgemv\n ,cgemv\n ,zgemv\n\n ,sger\n ,dger\n ,cgerc\n ,zgerc\n ,cgeru\n ,zgeru\n\n ,chbmv\n ,zhbmv\n\n ,chemv\n ,zhemv\n\n ,cher\n ,zher\n ,cher2\n ,zher2\n\n ,chpmv\n ,zhpmv\n\n ,chpr\n ,zhpr\n ,chpr2\n ,zhpr2\n\n ,ssbmv\n ,dsbmv\n\n ,sspmv\n ,dspmv\n\n ,sspr\n ,dspr\n ,sspr2\n ,dspr2\n\n ,ssymv\n ,dsymv\n\n ,ssyr\n ,dsyr\n ,ssyr2\n ,dsyr2\n\n ,stbmv\n ,dtbmv\n ,ctbmv\n ,ztbmv\n\n ,stbsv\n ,dtbsv\n ,ctbsv\n ,ztbsv\n\n ,stpmv\n ,dtpmv\n ,ctpmv\n ,ztpmv\n\n ,stpsv\n ,dtpsv\n ,ctpsv\n ,ztpsv\n\n ,strmv\n ,dtrmv\n ,ctrmv\n ,ztrmv\n\n ,strsv\n ,dtrsv\n ,ctrsv\n ,ztrsv\n ) where\n\n\nimport Numerical.HBLAS.UtilsFFI\nimport Numerical.HBLAS.BLAS.FFI.Level2\nimport Numerical.HBLAS.BLAS.Internal.Level2\nimport Control.Monad.Primitive\nimport Data.Complex\n\nsgbmv :: PrimMonad m => GbmvFun Float orient (PrimState m) m\nsgbmv = gbmvAbstraction \"sgbmv\" cblas_sgbmv_safe cblas_sgbmv_unsafe (\\x f -> f x)\n\ndgbmv :: PrimMonad m => GbmvFun Double orient (PrimState m) m\ndgbmv = gbmvAbstraction \"dgbmv\" cblas_dgbmv_safe cblas_dgbmv_unsafe (\\x f -> f x)\n\ncgbmv :: PrimMonad m => GbmvFun (Complex Float) orient (PrimState m) m\ncgbmv = gbmvAbstraction \"cgbmv\" cblas_cgbmv_safe cblas_cgbmv_unsafe withRStorable_\n\nzgbmv :: PrimMonad m => GbmvFun (Complex Double) orient (PrimState m) m\nzgbmv = gbmvAbstraction \"zgbmv\" cblas_zgbmv_safe cblas_zgbmv_unsafe withRStorable_\n\nsgemv :: PrimMonad m => GemvFun Float orient (PrimState m) m\nsgemv = gemvAbstraction \"sgemv\" cblas_sgemv_safe cblas_sgemv_unsafe (flip ($))\n\ndgemv :: PrimMonad m => GemvFun Double orient (PrimState m) m\ndgemv = gemvAbstraction \"dgemv\" cblas_dgemv_safe cblas_dgemv_unsafe (flip ($))\n\ncgemv :: PrimMonad m => GemvFun (Complex Float) orient (PrimState m) m\ncgemv = gemvAbstraction \"cgemv\" cblas_cgemv_safe cblas_cgemv_unsafe withRStorable_\n\nzgemv :: PrimMonad m => GemvFun (Complex Double) orient (PrimState m) m\nzgemv = gemvAbstraction \"zgemv\" cblas_zgemv_safe cblas_zgemv_unsafe withRStorable_\n\nsger :: PrimMonad m => GerFun Float orient (PrimState m) m\nsger = gerAbstraction \"sger\" cblas_sger_safe cblas_sger_unsafe (\\x f -> f x)\n\ndger :: PrimMonad m => GerFun Double orient (PrimState m) m\ndger = gerAbstraction \"dger\" cblas_dger_safe cblas_dger_unsafe (\\x f -> f x)\n\ncgerc :: PrimMonad m => GerFun (Complex Float) orient (PrimState m) m\ncgerc = gerAbstraction \"cgerc\" cblas_cgerc_safe cblas_cgerc_unsafe withRStorable_\n\nzgerc :: PrimMonad m => GerFun (Complex Double) orient (PrimState m) m\nzgerc = gerAbstraction \"zgerc\" cblas_zgerc_safe cblas_zgerc_unsafe withRStorable_\n\ncgeru :: PrimMonad m => GerFun (Complex Float) orient (PrimState m) m\ncgeru = gerAbstraction \"cgeru\" cblas_cgeru_safe cblas_cgeru_unsafe withRStorable_\n\nzgeru :: PrimMonad m => GerFun (Complex Double) orient (PrimState m) m\nzgeru = gerAbstraction \"zgeru\" cblas_zgeru_safe cblas_zgeru_unsafe withRStorable_\n\nchbmv :: PrimMonad m => HbmvFun (Complex Float) orient (PrimState m) m\nchbmv = hbmvAbstraction \"chbmv\" cblas_chbmv_safe cblas_chbmv_unsafe withRStorable_\n\nzhbmv :: PrimMonad m => HbmvFun (Complex Double) orient (PrimState m) m\nzhbmv = hbmvAbstraction \"zhbmv\" cblas_zhbmv_safe cblas_zhbmv_unsafe withRStorable_\n\nchemv :: PrimMonad m => HemvFun (Complex Float) orient (PrimState m) m\nchemv = hemvAbstraction \"chemv\" cblas_chemv_safe cblas_chemv_unsafe withRStorable_\n\nzhemv :: PrimMonad m => HemvFun (Complex Double) orient (PrimState m) m\nzhemv = hemvAbstraction \"zhemv\" cblas_zhemv_safe cblas_zhemv_unsafe withRStorable_\n\ncher :: PrimMonad m => HerFun Float (Complex Float) orient (PrimState m) m\ncher = herAbstraction \"cher\" cblas_cher_safe cblas_cher_unsafe (\\x f -> f x)\n\nzher :: PrimMonad m => HerFun Double (Complex Double) orient (PrimState m) m\nzher = herAbstraction \"zher\" cblas_zher_safe cblas_zher_unsafe (\\x f -> f x)\n\ncher2 :: PrimMonad m => Her2Fun (Complex Float) orient (PrimState m) m\ncher2 = her2Abstraction \"cher2\" cblas_cher2_safe cblas_cher2_unsafe withRStorable_\n\nzher2 :: PrimMonad m => Her2Fun (Complex Double) orient (PrimState m) m\nzher2 = her2Abstraction \"zher2\" cblas_zher2_safe cblas_zher2_unsafe withRStorable_\n\nchpmv :: PrimMonad m => HpmvFun (Complex Float) orient (PrimState m) m\nchpmv = hpmvAbstraction \"chpmv\" cblas_chpmv_safe cblas_chpmv_unsafe withRStorable_\n\nzhpmv :: PrimMonad m => HpmvFun (Complex Double) orient (PrimState m) m\nzhpmv = hpmvAbstraction \"zhpmv\" cblas_zhpmv_safe cblas_zhpmv_unsafe withRStorable_\n\nchpr :: PrimMonad m => HprFun Float (Complex Float) orient (PrimState m) m\nchpr = hprAbstraction \"chpr\" cblas_chpr_safe cblas_chpr_unsafe (\\x f -> f x)\n\nzhpr :: PrimMonad m => HprFun Double (Complex Double) orient (PrimState m) m\nzhpr = hprAbstraction \"zhpr\" cblas_zhpr_safe cblas_zhpr_unsafe (\\x f -> f x)\n\nchpr2 :: PrimMonad m => Hpr2Fun (Complex Float) orient (PrimState m) m\nchpr2 = hpr2Abstraction \"chpr2\" cblas_chpr2_safe cblas_chpr2_unsafe withRStorable_\n\nzhpr2 :: PrimMonad m => Hpr2Fun (Complex Double) orient (PrimState m) m\nzhpr2 = hpr2Abstraction \"zhpr2\" cblas_zhpr2_safe cblas_zhpr2_unsafe withRStorable_\n\nssbmv :: PrimMonad m => SbmvFun Float orient (PrimState m) m\nssbmv = sbmvAbstraction \"ssbmv\" cblas_ssbmv_safe cblas_ssbmv_unsafe (\\x f -> f x)\n\ndsbmv :: PrimMonad m => SbmvFun Double orient (PrimState m) m\ndsbmv = sbmvAbstraction \"dsbmv\" cblas_dsbmv_safe cblas_dsbmv_unsafe (\\x f -> f x)\n\nsspmv :: PrimMonad m => SpmvFun Float orient (PrimState m) m\nsspmv = spmvAbstraction \"sspmv\" cblas_sspmv_safe cblas_sspmv_unsafe (\\x f -> f x)\n\ndspmv :: PrimMonad m => SpmvFun Double orient (PrimState m) m\ndspmv = spmvAbstraction \"dspmv\" cblas_dspmv_safe cblas_dspmv_unsafe (\\x f -> f x)\n\nsspr :: PrimMonad m => SprFun Float orient (PrimState m) m\nsspr = sprAbstraction \"sspr\" cblas_sspr_safe cblas_sspr_unsafe (\\x f -> f x)\n\ndspr :: PrimMonad m => SprFun Double orient (PrimState m) m\ndspr = sprAbstraction \"dspr\" cblas_dspr_safe cblas_dspr_unsafe (\\x f -> f x)\n\nsspr2 :: PrimMonad m => Spr2Fun Float orient (PrimState m) m\nsspr2 = spr2Abstraction \"sspr2\" cblas_sspr2_safe cblas_sspr2_unsafe (\\x f -> f x)\n\ndspr2 :: PrimMonad m => Spr2Fun Double orient (PrimState m) m\ndspr2 = spr2Abstraction \"dspr2\" cblas_dspr2_safe cblas_dspr2_unsafe (\\x f -> f x)\n\nssymv :: PrimMonad m => SymvFun Float orient (PrimState m) m\nssymv = symvAbstraction \"ssymv\" cblas_ssymv_safe cblas_ssymv_unsafe (\\x f -> f x)\n\ndsymv :: PrimMonad m => SymvFun Double orient (PrimState m) m\ndsymv = symvAbstraction \"dsymv\" cblas_dsymv_safe cblas_dsymv_unsafe (\\x f -> f x)\n\nssyr :: PrimMonad m => SyrFun Float orient (PrimState m) m\nssyr = syrAbstraction \"ssyr\" cblas_ssyr_safe cblas_ssyr_unsafe (\\x f -> f x)\n\ndsyr :: PrimMonad m => SyrFun Double orient (PrimState m) m\ndsyr = syrAbstraction \"dsyr\" cblas_dsyr_safe cblas_dsyr_unsafe (\\x f -> f x)\n\nssyr2 :: PrimMonad m => Syr2Fun Float orient (PrimState m) m\nssyr2 = syr2Abstraction \"ssyr2\" cblas_ssyr2_safe cblas_ssyr2_unsafe (\\x f -> f x)\n\ndsyr2 :: PrimMonad m => Syr2Fun Double orient (PrimState m) m\ndsyr2 = syr2Abstraction \"dsyr2\" cblas_dsyr2_safe cblas_dsyr2_unsafe (\\x f -> f x)\n\nstbmv :: PrimMonad m => TbmvFun Float orient (PrimState m) m\nstbmv = tbmvAbstraction \"stbmv\" cblas_stbmv_safe cblas_stbmv_unsafe\n\ndtbmv :: PrimMonad m => TbmvFun Double orient (PrimState m) m\ndtbmv = tbmvAbstraction \"dtbmv\" cblas_dtbmv_safe cblas_dtbmv_unsafe\n\nctbmv :: PrimMonad m => TbmvFun (Complex Float) orient (PrimState m) m\nctbmv = tbmvAbstraction \"ctbmv\" cblas_ctbmv_safe cblas_ctbmv_unsafe\n\nztbmv :: PrimMonad m => TbmvFun (Complex Double) orient (PrimState m) m\nztbmv = tbmvAbstraction \"ztbmv\" cblas_ztbmv_safe cblas_ztbmv_unsafe\n\nstbsv :: PrimMonad m => TbsvFun Float orient (PrimState m) m\nstbsv = tbsvAbstraction \"stbsv\" cblas_stbsv_safe cblas_stbsv_unsafe\n\ndtbsv :: PrimMonad m => TbsvFun Double orient (PrimState m) m\ndtbsv = tbsvAbstraction \"dtbsv\" cblas_dtbsv_safe cblas_dtbsv_unsafe\n\nctbsv :: PrimMonad m => TbsvFun (Complex Float) orient (PrimState m) m\nctbsv = tbsvAbstraction \"ctbsv\" cblas_ctbsv_safe cblas_ctbsv_unsafe\n\nztbsv :: PrimMonad m => TbsvFun (Complex Double) orient (PrimState m) m\nztbsv = tbsvAbstraction \"ztbsv\" cblas_ztbsv_safe cblas_ztbsv_unsafe\n\nstpmv :: PrimMonad m => TpmvFun Float orient (PrimState m) m\nstpmv = tpmvAbstraction \"stpmv\" cblas_stpmv_safe cblas_stpmv_unsafe\n\ndtpmv :: PrimMonad m => TpmvFun Double orient (PrimState m) m\ndtpmv = tpmvAbstraction \"dtpmv\" cblas_dtpmv_safe cblas_dtpmv_unsafe\n\nctpmv :: PrimMonad m => TpmvFun (Complex Float) orient (PrimState m) m\nctpmv = tpmvAbstraction \"ctpmv\" cblas_ctpmv_safe cblas_ctpmv_unsafe\n\nztpmv :: PrimMonad m => TpmvFun (Complex Double) orient (PrimState m) m\nztpmv = tpmvAbstraction \"ztpmv\" cblas_ztpmv_safe cblas_ztpmv_unsafe\n\nstpsv :: PrimMonad m => TpsvFun Float orient (PrimState m) m\nstpsv = tpsvAbstraction \"stpsv\" cblas_stpsv_safe cblas_stpsv_unsafe\n\ndtpsv :: PrimMonad m => TpsvFun Double orient (PrimState m) m\ndtpsv = tpsvAbstraction \"dtpsv\" cblas_dtpsv_safe cblas_dtpsv_unsafe\n\nctpsv :: PrimMonad m => TpsvFun (Complex Float) orient (PrimState m) m\nctpsv = tpsvAbstraction \"ctpsv\" cblas_ctpsv_safe cblas_ctpsv_unsafe\n\nztpsv :: PrimMonad m => TpsvFun (Complex Double) orient (PrimState m) m\nztpsv = tpsvAbstraction \"ztpsv\" cblas_ztpsv_safe cblas_ztpsv_unsafe\n\nstrmv :: PrimMonad m => TrmvFun Float orient (PrimState m) m\nstrmv = trmvAbstraction \"strmv\" cblas_strmv_safe cblas_strmv_unsafe\n\ndtrmv :: PrimMonad m => TrmvFun Double orient (PrimState m) m\ndtrmv = trmvAbstraction \"dtrmv\" cblas_dtrmv_safe cblas_dtrmv_unsafe\n\nctrmv :: PrimMonad m => TrmvFun (Complex Float) orient (PrimState m) m\nctrmv = trmvAbstraction \"ctrmv\" cblas_ctrmv_safe cblas_ctrmv_unsafe\n\nztrmv :: PrimMonad m => TrmvFun (Complex Double) orient (PrimState m) m\nztrmv = trmvAbstraction \"ztrmv\" cblas_ztrmv_safe cblas_ztrmv_unsafe\n\nstrsv :: PrimMonad m => TrsvFun Float orient (PrimState m) m\nstrsv = trsvAbstraction \"strsv\" cblas_strsv_safe cblas_strsv_unsafe\n\ndtrsv :: PrimMonad m => TrsvFun Double orient (PrimState m) m\ndtrsv = trsvAbstraction \"dtrsv\" cblas_dtrsv_safe cblas_dtrsv_unsafe\n\nctrsv :: PrimMonad m => TrsvFun (Complex Float) orient (PrimState m) m\nctrsv = trsvAbstraction \"ctrsv\" cblas_ctrsv_safe cblas_ctrsv_unsafe\n\nztrsv :: PrimMonad m => TrsvFun (Complex Double) orient (PrimState m) m\nztrsv = trsvAbstraction \"ztrsv\" cblas_ztrsv_safe cblas_ztrsv_unsafe\n", "meta": {"hexsha": "42cfd76e56f5f46973a4bbd84dade657c3a97728", "size": 13197, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numerical/HBLAS/BLAS/Level2.hs", "max_stars_repo_name": "schnecki/hblas", "max_stars_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-05-03T23:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-17T22:58:54.000Z", "max_issues_repo_path": "src/Numerical/HBLAS/BLAS/Level2.hs", "max_issues_repo_name": "schnecki/hblas", "max_issues_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-01-24T13:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T22:15:09.000Z", "max_forks_repo_path": "src/Numerical/HBLAS/BLAS/Level2.hs", "max_forks_repo_name": "schnecki/hblas", "max_forks_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-01-09T12:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:37:37.000Z", "avg_line_length": 38.0317002882, "max_line_length": 119, "alphanum_fraction": 0.7367583542, "num_tokens": 4453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.5185895891151057}} {"text": "{-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Test.QuickCheck.LinearAlgebra\n-- Copyright : Copyright (c) , Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n--\n-- Test generators for linear algebra types.\n--\n\nmodule Test.QuickCheck.LinearAlgebra (\n -- Testable element types\n TestElem(..),\n \n -- * Generating random objects\n -- ** Dimensions\n dim,\n dim2,\n Dim(..),\n Dim2(..),\n \n -- ** Indices\n index,\n index2, \n Index(..),\n Index2(..), \n \n -- ** Elements\n elem,\n elems,\n -- realElem,\n -- realElems,\n \n -- ** Association lists\n assocs,\n assocs2,\n Assocs(..), \n Assocs2(..),\n -- bandedAssocs,\n \n -- ** Vectors\n vector,\n VectorPair(..),\n VectorTriple(..),\n VectorList(..),\n WeightedVectorList(..),\n NonEmptyVectorList(..),\n NonEmptyWeightedVectorList(..),\n \n -- ** Matrices\n matrix,\n MatrixPair(..),\n MatrixTriple(..),\n -- hermMatrix,\n -- triMatrix,\n\n -- Banded matrices\n -- bandwidths,\n -- banded,\n -- bandedWith,\n -- hermBanded,\n -- triBanded,\n \n -- BandedAssocs(..),\n\n ) where\n\nimport Prelude hiding ( elem )\n\n-- import BLAS.Types( UpLoEnum(..), DiagEnum(..) )\nimport Control.Monad\nimport Data.Complex( magnitude )\nimport Data.Maybe( fromJust )\n\nimport Test.QuickCheck hiding ( vector )\nimport qualified Test.QuickCheck as QC\n\nimport Numeric.LinearAlgebra.Types\nimport Numeric.LinearAlgebra.Vector( Vector )\nimport qualified Numeric.LinearAlgebra.Vector as V\nimport Numeric.LinearAlgebra.Matrix( Matrix )\nimport qualified Numeric.LinearAlgebra.Matrix as M\n-- import Data.Matrix.Banded( Banded, maybeBandedFromMatrixStorage )\n-- import Data.Matrix.Banded.ST( runSTBanded, unsafeThawBanded, \n-- diagViewBanded )\n\n\nclass TestElem e where\n maybeToReal :: e -> Maybe Double\n toReal :: e -> Double\n norm1 :: e -> Double\n norm :: e -> Double\n conjugate :: e -> e\n \n toReal = fromJust . maybeToReal\n \ninstance (TestElem Double) where\n maybeToReal = Just\n toReal = id\n norm1 = abs\n norm = abs\n conjugate = id\n \ninstance (TestElem (Complex Double)) where\n maybeToReal (x :+ y) | y == 0 = Just x\n | otherwise = Nothing\n norm1 (x :+ y) = abs x + abs y\n norm z = magnitude z\n conjugate (x :+ y) = x :+ (-y)\n\n{-\n-- | Element types that can be tested with QuickCheck properties.\nclass (Storable e, Arbitrary e, CoArbitrary e) => TestElem e where\n -- | Inicates whether or not the value should be used in tests. For\n -- 'Double's, @isTestElem e@ is defined as \n -- @not (isNaN e || isInfinite e || isDenormalized e)@.\n isTestElem :: e -> Bool\n\ninstance TestElem Double where\n isTestElem e = not (isNaN e || isInfinite e || isDenormalized e)\n {-# INLINE isTestElem #-}\n\ninstance TestElem (Complex Double) where\n isTestElem (x :+ y) = isTestElem x && isTestElem y\n {-# INLINE isTestElem #-}\n-}\n\nminit:: Int ->Int\nminit n= n `mod` 20\n\n-- | Generate a random element.\nelem :: (Arbitrary e) => Gen e\nelem = arbitrary\n\n-- | Generate a list of elements suitable for testing with.\nelems :: (Arbitrary e) => Int -> Gen [e]\nelems n = replicateM n elem\n\n-- Generate a random element that has no imaginary part.\n-- realElem :: (TestElem e) => Gen e\n-- realElem = liftM fromReal elem\n\n-- Generate a list of elements for testing that have no imaginary part.\n-- realElems :: (TestElem e) => Int -> Gen [e]\n-- realElems n = replicateM n realElem\n\n-- | Get an appropriate dimension for a random vector\ndim :: Gen Int\ndim = sized $ \\s -> do\n (NonNegative n) <- resize (s `div` 4) $ arbitrary\n return (minit n)\n \n-- | Get an appropriate dimension for a random matrix\ndim2 :: Gen (Int,Int)\ndim2 = sized $ \\s -> do\n m <- resize (s `div` 2) $ dim\n n <- resize (s `div` 2) $ dim\n return (m,n)\n \n-- | A vector dimension. \nnewtype Dim = Dim Int\n deriving (Eq, Ord, Num, Integral, Real, Enum, Show, Read)\n\ninstance Arbitrary Dim where\n arbitrary = sized $ \\s -> do\n (NonNegative n) <- resize (s `div` 4) $ arbitrary\n return $ Dim n\n \n shrink (Dim a) = \n [ Dim a' | (NonNegative a') <- shrink (NonNegative a) ]\n\n-- | A matrix dimension. \nnewtype Dim2 = Dim2 (Int,Int)\n deriving (Eq, Show, Read)\n\ninstance Arbitrary Dim2 where\n arbitrary = do\n mn <- dim2\n return $ Dim2 mn\n\n\n-- | Given a dimension generate a valid index. The dimension must be positive.\nindex :: Int -> Gen Int\nindex n | n <= 0 = \n error $ \"index \" ++ (show n) ++ \":\"\n ++ \" dimension must be positive (QuickCheck error)\"\n | otherwise =\n choose (0,n-1)\n\n-- | Given a matrix dimension generate a valid index.\nindex2 :: (Int,Int) -> Gen (Int,Int)\nindex2 (m,n) = do\n i <- index m\n j <- index n\n return (i,j)\n\n-- | A dimension and a valid index for it.\ndata Index = Index Int Int deriving (Eq,Show)\ninstance Arbitrary Index where\n arbitrary = do\n n <- (1+) `fmap` dim\n i <- index n\n return $ Index n i\n\n-- | A matrix dimension and a valid index for it.\ndata Index2 = Index2 (Int,Int) (Int,Int) deriving (Eq,Show)\ninstance Arbitrary Index2 where\n arbitrary = do\n (m',n') <- dim2\n let mn = (m' + 1, n' + 1)\n ij <- index2 mn\n return $ Index2 mn ij\n \n \n-- | Generate an associations list for a vector of the given dimension.\nassocs :: (Arbitrary e) => Int -> Gen [(Int,e)]\nassocs n | n == 0 = return []\n | otherwise = do\n l <- choose(0, 2*n)\n is <- replicateM l $ index n\n es <- elems l\n return $ zip is es\n\n-- | Generate an associations list for a matrix of the given shape.\nassocs2 :: (Arbitrary e) => (Int,Int) -> Gen [((Int,Int),e)]\nassocs2 (m,n) | m*n == 0 = return []\n | otherwise = do\n l <- choose(0, 2*m*n)\n is <- replicateM l $ index2 (m,n)\n es <- elems l\n return $ zip is es\n\n\n-- | A dimension and an associations list.\ndata Assocs e = Assocs Int [(Int,e)] deriving (Eq,Show)\n\ninstance (Arbitrary e) => Arbitrary (Assocs e) where\n arbitrary = do\n n <- dim\n ies <- assocs n\n return $ Assocs n ies\n \n shrink (Assocs n ies) =\n [ Assocs n' $ filter ((< n') . fst) ies\n | n' <- shrink n\n ] ++\n [ Assocs n ies'\n | ies' <- shrink ies\n ]\n\n-- | A shape and an associations list.\ndata Assocs2 e = Assocs2 (Int,Int) [((Int,Int),e)] deriving (Eq,Show)\ninstance (Arbitrary e) => Arbitrary (Assocs2 e) where\n arbitrary = do\n mn <- dim2\n ies <- assocs2 mn\n return $ Assocs2 mn ies\n\n\n-- | Generate a random vector of the given size.\nvector :: (Arbitrary e, Storable e) => Int -> Gen (Vector e)\nvector n = do\n es <- elems n\n return $ V.fromList n es\n\ninstance (Arbitrary e, Storable e) => Arbitrary (Vector e) where\n arbitrary = dim >>= vector\n \n shrink x =\n [ V.slice 0 n x\n | (NonNegative n) <- shrink (NonNegative $ V.dim x)\n ]\n\n-- | Two vectors with the same dimension.\ndata VectorPair e f = \n VectorPair (Vector e) (Vector f) deriving (Eq, Show)\ninstance (Arbitrary e, Storable e, Arbitrary f, Storable f) =>\n Arbitrary (VectorPair e f) where\n arbitrary = do\n x <- arbitrary\n y <- vector (V.dim x)\n return $ VectorPair x y\n \n shrink (VectorPair x y) =\n [ VectorPair (V.slice 0 n' x) (V.slice 0 n' y)\n | n' <- shrink (V.dim x)\n ]\n\n-- | Three vectors with the same dimension.\ndata VectorTriple e f g =\n VectorTriple (Vector e) (Vector f) (Vector g) deriving (Eq, Show)\ninstance (Arbitrary e, Storable e, Arbitrary f, Storable f,\n Arbitrary g, Storable g) =>\n Arbitrary (VectorTriple e f g) where\n arbitrary = do\n x <- arbitrary\n y <- vector (V.dim x)\n z <- vector (V.dim x)\n return $ VectorTriple x y z\n\n-- | A nonempty list of vectors with the same dimension.\ndata NonEmptyVectorList e = NonEmptyVectorList Int [Vector e] deriving (Eq, Show)\ninstance (Arbitrary e, Storable e) => Arbitrary (NonEmptyVectorList e) where\n arbitrary = do\n x <- arbitrary\n n <- choose (0,20)\n let p = V.dim x\n xs <- replicateM n $ vector p\n return $ NonEmptyVectorList p $ x:xs\n\n-- | A nonempty list of (weight, vector) pairs, with the weights all non-negative\n-- and the vectors all having the same dimension.\ndata NonEmptyWeightedVectorList e = NonEmptyWeightedVectorList Int [(e, Vector e)]\n deriving (Eq, Show)\ninstance (Arbitrary e, Storable e, Num e) => Arbitrary (NonEmptyWeightedVectorList e) where\n arbitrary = do\n (NonEmptyVectorList p xs) <- arbitrary\n ws <- replicateM (length xs) $ fmap abs arbitrary\n return $ NonEmptyWeightedVectorList p $ zip ws xs\n \n-- | A list of vectors with the same dimension.\ndata VectorList e = VectorList Int [Vector e] deriving (Eq, Show)\ninstance (Arbitrary e, Storable e) => Arbitrary (VectorList e) where\n arbitrary = do\n (NonEmptyVectorList p (_:xs)) <- arbitrary\n return $ VectorList p xs\n\n-- | A list of (weight, vector) pairs, with the weights all non-negative\n-- and the vectors all having the same dimension.\ndata WeightedVectorList e = WeightedVectorList Int [(e, Vector e)]\n deriving (Eq, Show)\ninstance (Arbitrary e, Storable e, Num e) => Arbitrary (WeightedVectorList e) where\n arbitrary = do\n (NonEmptyWeightedVectorList p (_:wxs)) <- arbitrary\n return $ WeightedVectorList p wxs\n\n-- | Generate a random matrix of the given size.\nmatrix :: (Arbitrary e, Storable e) => (Int,Int) -> Gen (Matrix e)\nmatrix (m,n) = \n oneof [ raw, sub ]\n where\n raw = do\n es <- elems $ m * n\n return $ M.fromList (m,n) es\n sub = do\n m' <- choose (m, 2*m)\n es <- elems $ m' * n\n return $ M.slice (0,0) (m,n) (M.fromList (m',n) es)\n\ninstance (Arbitrary e, Storable e) => Arbitrary (Matrix e) where\n arbitrary = dim2 >>= matrix\n \n-- | Two matrices with the same dimension.\ndata MatrixPair e f = \n MatrixPair (Matrix e) (Matrix f) deriving (Eq, Show)\ninstance (Arbitrary e, Storable e, Arbitrary f, Storable f) =>\n Arbitrary (MatrixPair e f) where\n arbitrary = do\n x <- arbitrary\n y <- matrix (M.dim x)\n return $ MatrixPair x y\n\n-- | Three matrices with the same dimension.\ndata MatrixTriple e f g =\n MatrixTriple (Matrix e) (Matrix f) (Matrix g) deriving (Eq, Show)\ninstance (Arbitrary e, Storable e, Arbitrary f, Storable f,\n Arbitrary g, Storable g) =>\n Arbitrary (MatrixTriple e f g) where\n arbitrary = do\n x <- arbitrary\n y <- matrix (M.dim x)\n z <- matrix (M.dim x)\n return $ MatrixTriple x y z\n\ninstance Arbitrary Trans where\n arbitrary = elements [ NoTrans, Trans, ConjTrans ]\n{-\n\n-- | Generate a triangular dense matrix.\ntriMatrix :: (TestElem e) => (Int,Int) -> Gen (Tri Matrix e)\ntriMatrix (m,n) = do\n a <- matrix (m,n)\n u <- QC.elements [ Lower, Upper ]\n d <- QC.elements [ Unit, NonUnit ]\n return $ Tri u d a\n \n-- | Generate a Hermitian dense matrix.\nhermMatrix :: (TestElem e) => Int -> Gen (Herm Matrix e)\nhermMatrix n = do\n a <- matrix (n,n)\n d <- realElems n\n let a' = runSTMatrix $ do\n ma <- unsafeThawMatrix a\n setElems (diagView ma 0) d\n return ma\n u <- QC.elements [ Lower, Upper ]\n return $ Herm u a'\n\nrawMatrix :: (TestElem e) => (Int,Int) -> Gen (Matrix e)\nrawMatrix (m,n) = do\n es <- elems (m*n)\n return $ M.fromList (m,n) es\n\n\nsubMatrix :: (TestElem e) => (Int,Int) -> Gen (SubMatrix e)\nsubMatrix (m,n) = \n oneof [ rawSubMatrix (m,n)\n , rawSubMatrix (n,m) >>= \\(SubMatrix a (i,j) (m',n')) ->\n return $ SubMatrix (herm a) (j,i) (n',m')\n ]\n\nrawSubMatrix :: (TestElem e) => (Int,Int) -> Gen (SubMatrix e)\nrawSubMatrix (m,n) = do\n i <- choose (0,5)\n j <- choose (0,5)\n e <- choose (0,5)\n f <- choose (0,5)\n x <- rawMatrix (i+m+e, j+n+f)\n return $ SubMatrix x (i,j) (m,n)\n\ninstance (TestElem e) => Arbitrary (SubMatrix e) where\n arbitrary = do\n (m,n) <- shape\n (SubMatrix a ij mn) <- subMatrix (m,n)\n return $ SubMatrix a ij mn\n\n-- | Generate valid bandwidth for a given matrix dimension size\nbandwidth :: Int -> Gen Int\nbandwidth n = if n == 0 then return 0 else choose (0,n-1)\n \n-- | Generate valid bandwidths for the given matrix shape.\nbandwidths :: (Int,Int) -> Gen (Int,Int)\nbandwidths (m,n) = liftM2 (,) (bandwidth m) (bandwidth n)\n\n-- | Generate a random banded matrix of the given shape.\nbanded :: (TestElem e) => (Int,Int) -> Gen (Banded e)\nbanded mn = do\n lu <- bandwidths mn\n bandedWith lu mn\n\n-- | Generate a random banded matrix with the given bandwidths.\nbandedWith :: (TestElem e) \n => (Int,Int) -> (Int,Int) -> Gen (Banded e)\nbandedWith lu mn = frequency [ (3, rawBanded mn lu) \n , (2, hermedBanded mn lu)\n ]\n\n-- | Generate a triangular banded matrix.\ntriBanded :: (TestElem e) => Int -> Gen (Tri Banded e)\ntriBanded n = do\n a <- banded (n,n)\n u <- QC.elements [ Lower, Upper ]\n d <- QC.elements [ Unit, NonUnit ]\n return $ Tri u d a\n \n-- | Generate a Hermitian banded matrix.\nhermBanded :: (TestElem e) => Int -> Gen (Herm Banded e)\nhermBanded n = do\n a <- banded (n,n)\n d <- realElems n\n let a' = runSTBanded $ do\n ma <- unsafeThawBanded a\n setElems (diagViewBanded ma 0) d\n return ma\n u <- QC.elements [ Lower, Upper ]\n return $ Herm u a' \n\nrawBanded :: (TestElem e) => \n (Int,Int) -> (Int,Int) -> Gen (Banded e)\nrawBanded (m,n) (kl,ku) = \n let bw = kl+ku+1\n in do\n a <- frequency [ (2, rawMatrix (bw,n))\n , (1, rawSubMatrix (bw,n) >>= \\(SubMatrix b ij _) ->\n return $ submatrix b ij (bw,n)) \n ]\n return $ fromJust (maybeBandedFromMatrixStorage (m,n) (kl,ku) a)\n\nhermedBanded :: (TestElem e) => \n (Int,Int) -> (Int,Int) -> Gen (Banded e)\nhermedBanded (m,n) (kl,ku) = do\n x <- rawBanded (n,m) (ku,kl)\n return $ herm x\n\n-- | Generate an associations list for a banded matrix of the given shape\n-- and bandwidths.\nbandedAssocs :: (TestElem e) => (Int,Int) -> (Int,Int) -> Gen [((Int,Int),e)]\nbandedAssocs (m,n) (kl,ku) | m*n == 0 = return []\n | otherwise = do\n (Nat l) <- arbitrary\n ijs <- replicateM l $ index2 (kl+1+ku,n)\n let ijs' = mapMaybe (\\(i,j) -> let i' = i - j - ku in\n if 0 <= i' && i' < m then Just (i',j)\n else Nothing ) ijs\n es <- replicateM l elem\n return $ zip ijs' es\n\n\n-- | A shape, bandwidths, and an associations list.\ndata BandedAssocs e = BandedAssocs (Int,Int) (Int,Int) [((Int,Int),e)] deriving (Eq,Show)\ninstance (TestElem e) => Arbitrary (BandedAssocs e) where\n arbitrary = do\n mn <- shape\n bw <- bandwidths mn\n ies <- bandedAssocs mn bw\n return $ BandedAssocs mn bw ies\n-}\n", "meta": {"hexsha": "36f8a4d85d78d5d80842c41ee8656a549ca4955e", "size": 15510, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Test/QuickCheck/LinearAlgebra.hs", "max_stars_repo_name": "cartazio/hs-cblas", "max_stars_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-01-19T00:43:25.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-14T16:18:59.000Z", "max_issues_repo_path": "lib/Test/QuickCheck/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/Test/QuickCheck/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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.29296875, "max_line_length": 91, "alphanum_fraction": 0.5839458414, "num_tokens": 4456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834732, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5185895809027381}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\nimport Control.DeepSeq\nimport Criterion.Main\nimport Criterion.Types\nimport Data.Char\nimport Data.Functor.Identity\nimport Data.Time\nimport GHC.Generics (Generic)\nimport GHC.TypeLits\nimport Lens.Micro\nimport Lens.Micro.TH\nimport Numeric.Backprop\nimport Numeric.Backprop.Class\nimport Numeric.LinearAlgebra.Static\nimport System.Directory\nimport qualified Data.Vector as V\nimport qualified Numeric.LinearAlgebra as HM\nimport qualified System.Random.MWC as MWC\n\ntype family HKD f a where\n HKD Identity a = a\n HKD f a = f a\n\ndata Layer' i o f =\n Layer { _lWeights :: !(HKD f (L o i))\n , _lBiases :: !(HKD f (R o))\n }\n deriving (Generic)\n\ntype Layer i o = Layer' i o Identity\n\nderiving instance (KnownNat i, KnownNat o) => Show (Layer i o)\ninstance NFData (Layer i o)\n\nmakeLenses ''Layer'\n\ndata Network' i h1 h2 o f =\n Net { _nLayer1 :: !(HKD f (Layer i h1))\n , _nLayer2 :: !(HKD f (Layer h1 h2))\n , _nLayer3 :: !(HKD f (Layer h2 o ))\n }\n deriving (Generic)\n\ntype Network i h1 h2 o = Network' i h1 h2 o Identity\n\nderiving instance (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o) => Show (Network i h1 h2 o)\ninstance NFData (Network i h1 h2 o)\n\nmakeLenses ''Network'\n\nmain :: IO ()\nmain = do\n g <- MWC.initialize\n . V.fromList\n . map (fromIntegral . ord)\n $ \"hello world\"\n test0 <- MWC.uniformR @(R 784, R 10) ((0,0),(1,1)) g\n net0 <- MWC.uniformR @(Network 784 300 100 10) (-0.5, 0.5) g\n t <- getZonedTime\n let tstr = formatTime defaultTimeLocale \"%Y%m%d-%H%M%S\" t\n createDirectoryIfMissing True \"bench-results\"\n defaultMainWith defaultConfig\n { reportFile = Just $ \"bench-results/mnist-bench_\" ++ tstr ++ \".html\"\n , timeLimit = 10\n } [\n bgroup \"gradient\"\n [ let runTest x y = gradNetManual x y net0\n in bench \"manual\" $ nf (uncurry runTest) test0\n , let runTest x y = gradBP (netErr x y) net0\n in bench \"bp-lens\" $ nf (uncurry runTest) test0\n , let runTest x y = gradBP (netErrHKD x y) net0\n in bench \"bp-hkd\" $ nf (uncurry runTest) test0\n , let runTest x y = gradBP (\\n' -> netErrHybrid n' y x) net0\n in bench \"hybrid\" $ nf (uncurry runTest) test0\n ]\n , bgroup \"descent\"\n [ let runTest x y = trainStepManual 0.02 x y net0\n in bench \"manual\" $ nf (uncurry runTest) test0\n , let runTest x y = trainStep 0.02 x y net0\n in bench \"bp-lens\" $ nf (uncurry runTest) test0\n , let runTest x y = trainStepHKD 0.02 x y net0\n in bench \"bp-hkd\" $ nf (uncurry runTest) test0\n , let runTest x y = trainStepHybrid 0.02 x y net0\n in bench \"hybrid\" $ nf (uncurry runTest) test0\n ]\n , bgroup \"run\"\n [ let runTest = runNetManual net0\n in bench \"manual\" $ nf runTest (fst test0)\n , let runTest x = evalBP (`runNetwork` x) net0\n in bench \"bp-lens\" $ nf runTest (fst test0)\n , let runTest x = evalBP (`runNetworkHKD` x) net0\n in bench \"bp-hkd\" $ nf runTest (fst test0)\n , let runTest x = evalBP (`runNetHybrid` x) net0\n in bench \"hybrid\" $ nf runTest (fst test0)\n ]\n ]\n\n-- ------------------------------\n-- - \"Backprop\" Lens Mode -\n-- ------------------------------\n\nrunLayer\n :: (KnownNat i, KnownNat o, Reifies s W)\n => BVar s (Layer i o)\n -> BVar s (R i)\n -> BVar s (R o)\nrunLayer l x = (l ^^. lWeights) #>! x + (l ^^. lBiases)\n{-# INLINE runLayer #-}\n\nsoftMax :: (KnownNat n, Reifies s W) => BVar s (R n) -> BVar s (R n)\nsoftMax x = konst' (1 / sumElements' expx) * expx\n where\n expx = exp x\n{-# INLINE softMax #-}\n\nrunNetwork\n :: (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o, Reifies s W)\n => BVar s (Network i h1 h2 o)\n -> R i\n -> BVar s (R o)\nrunNetwork n = softMax\n . runLayer (n ^^. nLayer3)\n . logistic\n . runLayer (n ^^. nLayer2)\n . logistic\n . runLayer (n ^^. nLayer1)\n . auto\n{-# INLINE runNetwork #-}\n\ncrossEntropy\n :: (KnownNat n, Reifies s W)\n => R n\n -> BVar s (R n)\n -> BVar s Double\ncrossEntropy t r = negate $ log r <.>! auto t\n{-# INLINE crossEntropy #-}\n\nnetErr\n :: (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o, Reifies s W)\n => R i\n -> R o\n -> BVar s (Network i h1 h2 o)\n -> BVar s Double\nnetErr x t n = crossEntropy t (runNetwork n x)\n{-# INLINE netErr #-}\n\ntrainStep\n :: forall i h1 h2 o. (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o)\n => Double\n -> R i\n -> R o\n -> Network i h1 h2 o\n -> Network i h1 h2 o\ntrainStep r !x !t !n = n - realToFrac r * gradBP (netErr x t) n\n{-# INLINE trainStep #-}\n\n-- ------------------------------\n-- - \"Backprop\" HKD Mode -\n-- ------------------------------\n\nrunLayerHKD\n :: (KnownNat i, KnownNat o, Reifies s W)\n => BVar s (Layer i o)\n -> BVar s (R i)\n -> BVar s (R o)\nrunLayerHKD (splitBV->Layer w b) x = w #>! x + b\n{-# INLINE runLayerHKD #-}\n\nrunNetworkHKD\n :: (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o, Reifies s W)\n => BVar s (Network i h1 h2 o)\n -> R i\n -> BVar s (R o)\nrunNetworkHKD (splitBV->Net l1 l2 l3) = softMax\n . runLayerHKD l3\n . logistic\n . runLayerHKD l2\n . logistic\n . runLayerHKD l1\n . auto\n{-# INLINE runNetworkHKD #-}\n\nnetErrHKD\n :: (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o, Reifies s W)\n => R i\n -> R o\n -> BVar s (Network i h1 h2 o)\n -> BVar s Double\nnetErrHKD x t n = crossEntropy t (runNetworkHKD n x)\n{-# INLINE netErrHKD #-}\n\ntrainStepHKD\n :: forall i h1 h2 o. (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o)\n => Double\n -> R i\n -> R o\n -> Network i h1 h2 o\n -> Network i h1 h2 o\ntrainStepHKD r !x !t !n = n - realToFrac r * gradBP (netErrHKD x t) n\n{-# INLINE trainStepHKD #-}\n\n-- ------------------------------\n-- - \"Manual\" Mode -\n-- ------------------------------\n\nrunLayerManual\n :: (KnownNat i, KnownNat o)\n => Layer i o\n -> R i\n -> R o\nrunLayerManual l x = (l ^. lWeights) #> x + (l ^. lBiases)\n{-# INLINE runLayerManual #-}\n\nsoftMaxManual :: KnownNat n => R n -> R n\nsoftMaxManual x = konst (1 / sumElements expx) * expx\n where\n expx = exp x\n{-# INLINE softMaxManual #-}\n\nrunNetManual\n :: (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o)\n => Network i h1 h2 o\n -> R i\n -> R o\nrunNetManual n = softMaxManual\n . runLayerManual (n ^. nLayer3)\n . logistic\n . runLayerManual (n ^. nLayer2)\n . logistic\n . runLayerManual (n ^. nLayer1)\n{-# INLINE runNetManual #-}\n\ngradNetManual\n :: forall i h1 h2 o. (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o)\n => R i\n -> R o\n -> Network i h1 h2 o\n -> Network i h1 h2 o\ngradNetManual x t (Net (Layer w1 b1) (Layer w2 b2) (Layer w3 b3)) =\n let y1 = w1 #> x\n z1 = y1 + b1\n x2 = logistic z1\n y2 = w2 #> x2\n z2 = y2 + b2\n x3 = logistic z2\n y3 = w3 #> x3\n z3 = y3 + b3\n o0 = exp z3\n o1 = HM.sumElements (extract o0)\n o2 = o0 / konst o1\n -- o3 = - (log o2 <.> t)\n dEdO3 = 1\n dEdO2 = dEdO3 * (- t / o2)\n dEdO1 = - (dEdO2 <.> o0) / (o1 ** 2)\n dEdO0 = konst dEdO1 + dEdO2 / konst o1\n dEdZ3 = dEdO0 * o0\n dEdY3 = dEdZ3\n dEdX3 = tr w3 #> dEdY3\n dEdZ2 = dEdX3 * (x3 * (1 - x3))\n dEdY2 = dEdZ2\n dEdX2 = tr w2 #> dEdY2\n dEdZ1 = dEdX2 * (x2 * (1 - x2))\n dEdY1 = dEdZ1\n dEdB3 = dEdZ3\n dEdW3 = dEdY3 `outer` x3\n dEdB2 = dEdZ2\n dEdW2 = dEdY2 `outer` x2\n dEdB1 = dEdZ1\n dEdW1 = dEdY1 `outer` x\n in Net (Layer dEdW1 dEdB1) (Layer dEdW2 dEdB2) (Layer dEdW3 dEdB3)\n{-# INLINE gradNetManual #-}\n\ntrainStepManual\n :: forall i h1 h2 o. (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o)\n => Double\n -> R i\n -> R o\n -> Network i h1 h2 o\n -> Network i h1 h2 o\ntrainStepManual r !x !t !n =\n let gN = gradNetManual x t n\n in n - (realToFrac r * gN)\n\n-- ------------------------------\n-- - \"Hybrid\" Mode -\n-- ------------------------------\n\nlayerOp :: (KnownNat i, KnownNat o) => Op '[Layer i o, R i] (R o)\nlayerOp = op2 $ \\(Layer w b) x ->\n ( w #> x + b\n , \\g -> (Layer (g `outer` x) g, tr w #> g)\n )\n{-# INLINE layerOp #-}\n\nlogisticOp\n :: Floating a\n => Op '[a] a\nlogisticOp = op1 $ \\x ->\n let lx = logistic x\n in (lx, \\g -> lx * (1 - lx) * g)\n{-# INLINE logisticOp #-}\n\nsoftMaxOp\n :: KnownNat n\n => Op '[R n] (R n)\nsoftMaxOp = op1 $ \\x ->\n let expx = exp x\n tot = sumElements expx\n invtot = 1 / tot\n res = konst invtot * expx\n in ( res\n , \\g -> res - konst (invtot ** 2) * exp (2 * x) * g\n )\n{-# INLINE softMaxOp #-}\n\nsoftMaxCrossEntropyOp\n :: KnownNat n\n => R n\n -> Op '[R n] Double\nsoftMaxCrossEntropyOp targ = op1 $ \\x ->\n let expx = exp x\n sm = konst (1 / sumElements expx) * expx\n ce = negate $ log sm <.> targ\n in ( ce\n , \\g -> (sm - targ) * konst g\n )\n{-# INLINE softMaxCrossEntropyOp #-}\n\nrunNetHybrid\n :: (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o, Reifies s W)\n => BVar s (Network i h1 h2 o)\n -> R i\n -> BVar s (R o)\nrunNetHybrid n = liftOp1 softMaxOp\n . liftOp2 layerOp (n ^^. nLayer3)\n . liftOp1 logisticOp\n . liftOp2 layerOp (n ^^. nLayer2)\n . liftOp1 logisticOp\n . liftOp2 layerOp (n ^^. nLayer1)\n . auto\n{-# INLINE runNetHybrid #-}\n\nnetErrHybrid\n :: (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o, Reifies s W)\n => BVar s (Network i h1 h2 o)\n -> R o\n -> R i\n -> BVar s Double\nnetErrHybrid n t = liftOp1 (softMaxCrossEntropyOp t)\n . liftOp2 layerOp (n ^^. nLayer3)\n . liftOp1 logisticOp\n . liftOp2 layerOp (n ^^. nLayer2)\n . liftOp1 logisticOp\n . liftOp2 layerOp (n ^^. nLayer1)\n . auto\n{-# INLINE netErrHybrid #-}\n\ntrainStepHybrid\n :: forall i h1 h2 o. (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o)\n => Double\n -> R i\n -> R o\n -> Network i h1 h2 o\n -> Network i h1 h2 o\ntrainStepHybrid r !x !t !n =\n let gN = gradBP (\\n' -> netErrHybrid n' t x) n\n in n - (realToFrac r * gN)\n{-# INLINE trainStepHybrid #-}\n\n-- ------------------------------\n-- - Operations -\n-- ------------------------------\n\ninfixr 8 #>!\n(#>!)\n :: (KnownNat m, KnownNat n, Reifies s W)\n => BVar s (L m n)\n -> BVar s (R n)\n -> BVar s (R m)\n(#>!) = liftOp2 . op2 $ \\m v ->\n ( m #> v, \\g -> (g `outer` v, tr m #> g) )\n{-# INLINE (#>!) #-}\n\ninfixr 8 <.>!\n(<.>!)\n :: (KnownNat n, Reifies s W)\n => BVar s (R n)\n -> BVar s (R n)\n -> BVar s Double\n(<.>!) = liftOp2 . op2 $ \\x y ->\n ( x <.> y, \\g -> (konst g * y, x * konst g)\n )\n{-# INLINE (<.>!) #-}\n\nkonst'\n :: (KnownNat n, Reifies s W)\n => BVar s Double\n -> BVar s (R n)\nkonst' = liftOp1 . op1 $ \\c -> (konst c, HM.sumElements . extract)\n{-# INLINE konst' #-}\n\nsumElements :: KnownNat n => R n -> Double\nsumElements = HM.sumElements . extract\n{-# INLINE sumElements #-}\n\nsumElements'\n :: (KnownNat n, Reifies s W)\n => BVar s (R n)\n -> BVar s Double\nsumElements' = liftOp1 . op1 $ \\x -> (sumElements x, konst)\n{-# INLINE sumElements' #-}\n\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n{-# INLINE logistic #-}\n\n-- ------------------------------\n-- - Instances -\n-- ------------------------------\n\ninstance (KnownNat i, KnownNat o) => Num (Layer i o) where\n Layer w1 b1 + Layer w2 b2 = Layer (w1 + w2) (b1 + b2)\n Layer w1 b1 - Layer w2 b2 = Layer (w1 - w2) (b1 - b2)\n Layer w1 b1 * Layer w2 b2 = Layer (w1 * w2) (b1 * b2)\n abs (Layer w b) = Layer (abs w) (abs b)\n signum (Layer w b) = Layer (signum w) (signum b)\n negate (Layer w b) = Layer (negate w) (negate b)\n fromInteger x = Layer (fromInteger x) (fromInteger x)\n\ninstance (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o) => Num (Network i h1 h2 o) where\n Net a b c + Net d e f = Net (a + d) (b + e) (c + f)\n Net a b c - Net d e f = Net (a - d) (b - e) (c - f)\n Net a b c * Net d e f = Net (a * d) (b * e) (c * f)\n abs (Net a b c) = Net (abs a) (abs b) (abs c)\n signum (Net a b c) = Net (signum a) (signum b) (signum c)\n negate (Net a b c) = Net (negate a) (negate b) (negate c)\n fromInteger x = Net (fromInteger x) (fromInteger x) (fromInteger x)\n\ninstance (KnownNat i, KnownNat o) => Fractional (Layer i o) where\n Layer w1 b1 / Layer w2 b2 = Layer (w1 / w2) (b1 / b2)\n recip (Layer w b) = Layer (recip w) (recip b)\n fromRational x = Layer (fromRational x) (fromRational x)\n\ninstance (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o) => Fractional (Network i h1 h2 o) where\n Net a b c / Net d e f = Net (a / d) (b / e) (c / f)\n recip (Net a b c) = Net (recip a) (recip b) (recip c)\n fromRational x = Net (fromRational x) (fromRational x) (fromRational x)\n\ninstance KnownNat n => MWC.Variate (R n) where\n uniform g = randomVector <$> MWC.uniform g <*> pure Uniform\n uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance (KnownNat m, KnownNat n) => MWC.Variate (L m n) where\n uniform g = uniformSample <$> MWC.uniform g <*> pure 0 <*> pure 1\n uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance (KnownNat i, KnownNat o) => MWC.Variate (Layer i o) where\n uniform g = Layer <$> MWC.uniform g <*> MWC.uniform g\n uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o) => MWC.Variate (Network i h1 h2 o) where\n uniform g = Net <$> MWC.uniform g <*> MWC.uniform g <*> MWC.uniform g\n uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance Backprop (R n) where\n zero = zeroNum\n add = addNum\n one = oneNum\n\ninstance (KnownNat n, KnownNat m) => Backprop (L m n) where\n zero = zeroNum\n add = addNum\n one = oneNum\n\ninstance (KnownNat i, KnownNat o) => Backprop (Layer i o)\ninstance (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o) => Backprop (Network i h1 h2 o)\n", "meta": {"hexsha": "db3d787beae2403607eeed17ba81d27d9a4a4ed2", "size": 15584, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/bench.hs", "max_stars_repo_name": "tonyday567/backprop", "max_stars_repo_head_hexsha": "3b3abc7f16297f096d1bb0b5b6ef13f3c7432344", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 166, "max_stars_repo_stars_event_min_datetime": "2017-02-22T08:46:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T14:38:43.000Z", "max_issues_repo_path": "bench/bench.hs", "max_issues_repo_name": "tonyday567/backprop", "max_issues_repo_head_hexsha": "3b3abc7f16297f096d1bb0b5b6ef13f3c7432344", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2017-05-25T05:35:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T09:18:58.000Z", "max_forks_repo_path": "bench/bench.hs", "max_forks_repo_name": "tonyday567/backprop", "max_forks_repo_head_hexsha": "3b3abc7f16297f096d1bb0b5b6ef13f3c7432344", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2017-03-10T17:29:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T10:43:24.000Z", "avg_line_length": 31.6105476673, "max_line_length": 100, "alphanum_fraction": 0.519699692, "num_tokens": 5159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5184322084537677}} {"text": "{-# LANGUAGE RankNTypes, BangPatterns, GADTs #-}\n{-# OPTIONS -Wall #-}\n\nmodule Language.Hakaru.Distribution where\n\nimport System.Random\nimport Language.Hakaru.Mixture\nimport Language.Hakaru.Types\nimport Data.Ix\nimport Data.Maybe (fromMaybe)\nimport Data.List (findIndex, foldl')\nimport Numeric.SpecFunctions\nimport qualified Data.Map.Strict as M\nimport qualified Data.Number.LogFloat as LF\n\nmapFst :: (t -> s) -> (t, u) -> (s, u)\nmapFst f (a,b) = (f a, b)\n\ndirac :: (Eq a) => a -> Dist a\ndirac theta = Dist {logDensity = (\\ (Discrete x) -> if x == theta then 0 else log 0),\n distSample = (\\ g -> (Discrete theta,g))}\n\nbern :: Double -> Dist Bool\nbern p = Dist {logDensity = (\\ (Discrete x) -> log (if x then p else 1 - p)),\n distSample = (\\ g -> case randomR (0, 1) g of\n (t, g') -> (Discrete $ t <= p, g'))}\n\nuniform :: Double -> Double -> Dist Double\nuniform lo hi =\n let uniformLogDensity lo' hi' x | lo' <= x && x <= hi' = log (recip (hi' - lo'))\n uniformLogDensity _ _ _ = log 0\n in Dist {logDensity = (\\ (Lebesgue x) -> uniformLogDensity lo hi x),\n distSample = (\\ g -> mapFst Lebesgue $ randomR (lo, hi) g)}\n\nuniformD :: (Ix a, Random a) => a -> a -> Dist a\nuniformD lo hi =\n let uniformLogDensity lo' hi' x | lo' <= x && x <= hi' = log density\n uniformLogDensity _ _ _ = log 0\n density = recip (fromInteger (toInteger (rangeSize (lo,hi))))\n in Dist {logDensity = (\\ (Discrete x) -> uniformLogDensity lo hi x),\n distSample = (\\ g -> mapFst Discrete $ randomR (lo, hi) g)}\n\nmarsaglia :: (RandomGen g, Random a, Ord a, Floating a) => g -> ((a, a), g)\nmarsaglia g0 = -- \"Marsaglia polar method\"\n let (x, g1) = randomR (-1,1) g0\n (y, g ) = randomR (-1,1) g1\n s = x * x + y * y\n q = sqrt ((-2) * log s / s)\n in if 1 >= s && s > 0 then ((x * q, y * q), g) else marsaglia g\n\nchoose :: (RandomGen g) => Mixture k -> g -> (k, Prob, g)\nchoose (Mixture m) g0 =\n let peak = maximum (M.elems m)\n unMix = M.map (LF.fromLogFloat . (/peak)) m\n total = M.foldl' (+) (0::Double) unMix\n (p, g) = randomR (0, total) g0\n f !k !v b !p0 = let p1 = p0 + v in if p <= p1 then k else b p1\n err p0 = error (\"choose: failure p0=\" ++ show p0 ++\n \" total=\" ++ show total ++\n \" size=\" ++ show (M.size m))\n in (M.foldrWithKey f err unMix 0, LF.logFloat total * peak, g)\n\nchooseIndex :: (RandomGen g) => [Double] -> g -> (Int, g)\nchooseIndex probs g0 =\n let (p, g) = random g0\n k = fromMaybe (error (\"chooseIndex: failure p=\" ++ show p))\n (findIndex (p <=) (scanl1 (+) probs))\n in (k, g)\n\nnormal_rng :: (Real a, Floating a, Random a, RandomGen g) =>\n a -> a -> g -> (a, g)\nnormal_rng mu sd g | sd > 0 = case marsaglia g of\n ((x, _), g1) -> (mu + sd * x, g1)\nnormal_rng _ _ _ = error \"normal: invalid parameters\"\n\nnormalLogDensity :: Floating a => a -> a -> a -> a\nnormalLogDensity mu sd x = (-tau * square (x - mu)\n + log (tau / pi / 2)) / 2\n where square y = y * y\n tau = 1 / square sd\n\nnormal :: Double -> Double -> Dist Double \nnormal mu sd = Dist {logDensity = normalLogDensity mu sd . fromLebesgue,\n distSample = mapFst Lebesgue . normal_rng mu sd}\n\ncategoricalLogDensity :: (Eq b, Floating a) => [(b, a)] -> b -> a\ncategoricalLogDensity list x = log $ fromMaybe 0 (lookup x list)\ncategoricalSample :: (Num b, Ord b, RandomGen g, Random b) =>\n [(t,b)] -> g -> (t, g)\ncategoricalSample list g = (elem', g1)\n where\n (p, g1) = randomR (0, total) g\n elem' = fst $ head $ filter (\\(_,p0) -> p <= p0) sumList\n sumList = scanl1 (\\acc (a, b) -> (a, b + snd(acc))) list\n total = sum $ map snd list\n\ncategorical :: Eq a => [(a,Double)] -> Dist a\ncategorical list = Dist {logDensity = categoricalLogDensity list . fromDiscrete,\n distSample = mapFst Discrete . categoricalSample list}\n\nlnFact :: Integer -> Double\nlnFact = logFactorial\n\n-- Makes use of Atkinson's algorithm as described in:\n-- Monte Carlo Statistical Methods pg. 55\n--\n-- Further discussion at:\n-- http://www.johndcook.com/blog/2010/06/14/generating-poisson-random-values/\npoisson_rng :: (RandomGen g) => Double -> g -> (Integer, g)\npoisson_rng lambda g0 = make_poisson g0\n where smu = sqrt lambda\n b = 0.931 + 2.53*smu\n a = -0.059 + 0.02483*b\n vr = 0.9277 - 3.6224/(b - 2)\n arep = 1.1239 + 1.1368/(b-3.4)\n lnlam = log lambda\n\n make_poisson :: (RandomGen g) => g -> (Integer,g)\n make_poisson g = let (u, g1) = randomR (-0.5,0.5) g\n (v, g2) = randomR (0,1) g1\n us = 0.5 - abs u\n k = floor $ (2*a / us + b)*u + lambda + 0.43 in\n case () of\n () | us >= 0.07 && v <= vr -> (k, g2)\n () | k < 0 -> make_poisson g2\n () | us <= 0.013 && v > us -> make_poisson g2\n () | accept_region us v k -> (k, g2)\n _ -> make_poisson g2\n\n accept_region :: Double -> Double -> Integer -> Bool\n accept_region us v k = log (v * arep / (a/(us*us)+b)) <=\n -lambda + (fromIntegral k)*lnlam - lnFact k\n\npoisson :: Double -> Dist Integer\npoisson l =\n let poissonLogDensity l' x | l' > 0 && x> 0 = (fromIntegral x)*(log l') - lnFact x - l'\n poissonLogDensity l' x | x==0 = -l'\n poissonLogDensity _ _ = log 0\n in Dist {logDensity = poissonLogDensity l . fromDiscrete,\n distSample = mapFst Discrete . poisson_rng l}\n\n-- Direct implementation of \"A Simple Method for Generating Gamma Variables\"\n-- by George Marsaglia and Wai Wan Tsang.\ngamma_rng :: (RandomGen g) => Double -> Double -> g -> (Double, g)\ngamma_rng shape _ _ | shape <= 0.0 = error \"gamma: got a negative shape paramater\"\ngamma_rng _ scl _ | scl <= 0.0 = error \"gamma: got a negative scale paramater\"\ngamma_rng shape scl g | shape < 1.0 = (gvar2, g2)\n where (gvar1, g1) = gamma_rng (shape + 1) scl g\n (w, g2) = randomR (0,1) g1\n gvar2 = scl * gvar1 * (w ** recip shape) \ngamma_rng shape scl g = \n let d = shape - 1/3\n c = recip $ sqrt $ 9*d\n -- Algorithm recommends inlining normal generator\n n = normal_rng 1 c\n (v, g2) = until (\\y -> fst y > 0.0) (\\ (_, g') -> normal_rng 1 c g') (n g)\n x = (v - 1) / c\n sqr = x * x\n v3 = v * v * v\n (u, g3) = randomR (0.0, 1.0) g2\n accept = u < 1.0 - 0.0331*(sqr*sqr) || log u < 0.5*sqr + d*(1.0 - v3 + log v3)\n in case accept of\n True -> (scl*d*v3, g3)\n False -> gamma_rng shape scl g3\n\ngammaLogDensity :: Double -> Double -> Double -> Double\ngammaLogDensity shape scl x | x>= 0 && shape > 0 && scl > 0 =\n scl * log shape - scl * x + (shape - 1) * log x - logGamma shape\ngammaLogDensity _ _ _ = log 0\n\ngamma :: Double -> Double -> Dist Double\ngamma shape scl = Dist {logDensity = gammaLogDensity shape scl . fromLebesgue,\n distSample = mapFst Lebesgue . gamma_rng shape scl}\n\nbeta_rng :: (RandomGen g) => Double -> Double -> g -> (Double, g)\nbeta_rng a b g | a <= 1.0 && b <= 1.0 =\n let (u, g1) = randomR (0.0, 1.0) g\n (v, g2) = randomR (0.0, 1.0) g1\n x = u ** (recip a)\n y = v ** (recip b)\n in case (x+y) <= 1.0 of\n True -> (x / (x + y), g2)\n False -> beta_rng a b g2\nbeta_rng a b g = let (ga, g1) = gamma_rng a 1 g\n (gb, g2) = gamma_rng b 1 g1\n in (ga / (ga + gb), g2)\n\nbetaLogDensity :: Double -> Double -> Double -> Double\nbetaLogDensity _ _ x | x < 0 || x > 1 = error \"beta: value must be between 0 and 1\"\nbetaLogDensity a b _ | a <= 0 || b <= 0 = error \"beta: parameters must be positve\" \nbetaLogDensity a b x = (logGamma (a + b)\n - logGamma a\n - logGamma b\n + (a - 1) * log x\n + (b - 1) * log (1 - x))\n\nbeta :: Double -> Double -> Dist Double\nbeta a b = Dist {logDensity = betaLogDensity a b . fromLebesgue,\n distSample = mapFst Lebesgue . beta_rng a b}\n\nlaplace_rng :: (RandomGen g) => Double -> Double -> g -> (Double, g)\nlaplace_rng mu sd g = sample (randomR (0.0, 1.0) g)\n where sample (u, g1) = case u < 0.5 of\n True -> (mu + sd * log (u + u), g1)\n False -> (mu - sd * log (2.0 - u - u), g1)\n\nlaplaceLogDensity :: Floating a => a -> a -> a -> a\nlaplaceLogDensity mu sd x = - log (2 * sd) - abs (x - mu) / sd\n\nlaplace :: Double -> Double -> Dist Double\nlaplace mu sd = Dist {logDensity = laplaceLogDensity mu sd . fromLebesgue,\n distSample = mapFst Lebesgue . laplace_rng mu sd}\n\n-- Consider having dirichlet return Vector\n-- Note: This is acutally symmetric dirichlet\ndirichlet_rng :: (RandomGen g) => Int -> Double -> g -> ([Double], g)\ndirichlet_rng n' a g' = normalize (gammas g' n')\n where gammas g 0 = ([], 0, g)\n gammas g n = let (xs, total, g1) = gammas g (n-1)\n ( x, g2) = gamma_rng a 1 g1 \n in ((x : xs), x+total, g2)\n normalize (b, total, h) = (map (/ total) b, h)\n\ndirichletLogDensity :: [Double] -> [Double] -> Double\ndirichletLogDensity a x | all (> 0) x = sum' (zipWith logTerm a x) + logGamma (sum a)\n where sum' = foldl' (+) 0\n logTerm b y = (b-1) * log y - logGamma b\ndirichletLogDensity _ _ = error \"dirichlet: all values must be between 0 and 1\"\n", "meta": {"hexsha": "22eefa1ee9ee8ac23a1fadd14fb5de1b86893f24", "size": 9891, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Language/Hakaru/Distribution.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/Distribution.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/Distribution.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": 43.192139738, "max_line_length": 91, "alphanum_fraction": 0.5291679304, "num_tokens": 3128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5182557740870856}} {"text": "module Main where\n\nimport Numeric.GSL.Integration\nimport Complex\nimport System.IO\nimport Data.Fixed\nimport Data.Array\nimport Data.Maybe\nimport Control.Monad\nimport Data.Packed.Matrix\nimport Data.Packed.Vector\nimport Numeric.LinearAlgebra.Algorithms\nimport qualified Data.IntMap as M\n\ndata Ctree a b = End (a,b)\n | Branche (a,b) [Ctree a b]\n deriving (Show)\n\n-- Given N boxes, return all possible combinations of P particles in these boxes.\n\nc n p = g 1 0 \n where g i a | i == n = [ End (n, p - a) ]\n | a == p - 1 = [ End (i, 1) ] ++ g (i + 1) a \n | otherwise = [ if r == p - a \n then End (i,r) \n else Branche (i,r) $ g (i+1) (a + r) | \n i <- [i..n-1], \n r <- [1..p-a] ] \n ++ [ End (n, p-a) ]\n\n-- Convert combinations of Ctree do list format\n\ncl [] = []\ncl ((End p):l) = [p]:cl l\ncl ((Branche p b):l) = (map (p:) $ cl b) ++ cl l\n\n-- Create newstates aplying A+(i)A+(j)A(k)A(l) operator on state 'a'\n\nnewState i j k l n a = do cp i =<< cp j =<< dp k =<< dp l a \n where\n cp i a = if a!i < n \n then Just $ a//[(i,a!i + 1)]\n else Nothing\n\n dp i a = if a!i > 0\n then Just $ a//[(i,a!i - 1)]\n else Nothing\n\n-- List all states that can have operator A+(i)A+(j)A(k)A(l) applied\n \npossibleStates i j k l nb np = filter (isJust . newState i j k l np) . aStates nb\n\n-- Autovalue of operator A+(i)A+(j)A(k)A(l) \n\nvalue i j k l n a = sqrt $ ((a!i + 1)*(a!j + 1)*a!k*a!l) / ((prod $ elems a')*(prod $ elems a))\n where a' = fromJust $ newState i j k l n a\n prod x = prod' x 1\n prod' [] a = a\n prod' (x:xs) a | x == 0 = prod' xs a\n | otherwise = prod' xs a*x\n\nsumValues i j k l n = sum . map (value i j k l n) \n\n-- Convert state from List to Array type\n\naStates nb = map (listArray (1,nb) (repeat 0) //) \n\n-- Total quasi-momentum of base state 'a'\n\nqt a = qt' a 0 (min + 1) \n where qt' a t i | i == max = mod (t + (max - 1)*a!max) max\n | otherwise = qt' a (t + (i-1)*a!i) (i + 1)\n (min,max) = bounds a\n\n-- Group states by quasi-momentum\n\ngroupQt states = M.fromListWith (++) $ map (\\x -> (qt x, [x])) states\n\n-- Print grouped states\n\nprintGroups states = do mapM_ printG states\n where printG (n,s) = do putStrLn $ (show n) ++ \":\"\n mapM_ (putStrLn.show.elems) s\n putStrLn \"\"\n\nna = array (0, 4) [ (0, 1.81772),\n (1, 1.75048),\n (2, 0.998368),\n (3, 0.111417),\n (4, 1.19828) ]\n\na = array (0,4) [ (0, 1.94699),\n (1, 1.98301),\n (2, 2.29932),\n (3, 2.49687),\n (4, 2.22725) ]\n\nn = 5 :: Int\nnd = 5 :: Double\n\nbloch phi w a b = exp(0 :+ a*phi)*exp(0 :+ (-wa*phy))*(cos(b*phy)*sin(b*pi/nd)*cos(wa*pi/nd) :+ sin(b*phy)*cos(b*pi/nd)*sin(wa*pi/nd))\n where phy = -pi/nd + mod' (phi + pi/nd) (2*pi/nd)\n wa = a - w\n\ncbloch phi w a b = conjugate $ bloch phi w a b\n\ntoInt phi w i j k l = 1/((na!i)*(na!j)*(na!k)*(na!l))* \n cbloch phi w (fi i) (a!i) * cbloch phi w (fi j) (a!j) * \n bloch phi w (fi k) (a!k) * bloch phi w (fi l) (a!l) \n where fi = fromIntegral \n\n-- Calculate matrix for each quasi-momentum\n\nmatFrom :: Int -> Int -> Array Int (Array Int Int) -> Double -> Array (Int,Int) Double\nmatFrom nb np gs c = matrix \n where matrix = array ((1,1),(size,size)) [((i,j), f i j) | i <- [1..size], j <- [1..size]] \n f i j | i > j = matrix!(j,i)\n | otherwise = energy i j + c*(sum $ map (\\x -> sq x (gs!j)*(im!x)) [ (oi,oj,ok,ol) | oi <- [1..nb], \n oj <- [1..nb], \n ok <- [1..nb], ol <- [1..nb], \n newState oi oj ok ol np (gs!j) == Just (gs!i) ])\n sq (i,j,k,l) s = sqrt $ (fi $ (s!i) + 1)*(fi $ (s!j) + 1)*(fi $ s!k)*(fi $ s!l)\n energy i j | i == j = e (gs!j) 1 0 \n | otherwise = 0\n e s i t | i == nb = t*(fi $ s!i)\n | otherwise = e s (i+1) (t + (a!(i-1))*(fi $ s!i))\n size = snd $ bounds gs \n im = intMatrix nb\n fi = fromIntegral\n\nintMatrix n = array ((1,1,1,1),(n,n,n,n)) [ ((i,j,k,l), integrate (i,j,k,l) n) | i <- [1..n], j <- [1..n], k <- [1..n], l <- [1..n] ]\n\nintegrate (i,j,k,l) n | mod (i+j-k-l) n == 0 = fst $ integrateQAGS 1E-6 1000 (\\x -> realPart $ toInt x 0.4 (i-1) (j-1) (k-1) (l-1)) 0 (2*pi)\n | otherwise = 0\n\n-- Create Matrix\n\ngenMatrix nb np k cst = matFrom nb np (listArray (1,length $ qmGroup M.! k) $ qmGroup M.! k) cst\n where qmGroup = groupQt $ aStates nb $ cl $ c nb np\n qmKeys = M.keys qmGroup \n\n-- Print eigenvalues and eigenstates to all states, group by quasi-momentum\n\nprintStates nb np cst file = do\n let qmGroup = groupQt $ aStates nb $ cl $ c nb np\n qmKeys = M.keys qmGroup \n \n calEig n x = eig $ (n> do\n hPutStrLn file $ \"Eigenvalue: \" ++ (show e) ++ \"\\n\"\n mapM_ (\\n -> hPutStrLn file $ (show n) ++ \" \") v\n hPutStrLn file \"\\n\"\n\n forM_ qmKeys $ \\k -> do\n let kSize = length $ qmGroup M.! k\n hPutStrLn file $ \"quasi-momentum: \" ++ (show k) ++ \"\\n\"\n printEig $ calEig (kSize) $ matFrom nb np (listArray (1, kSize) $ qmGroup M.! k) cst\n\nmain = do\n file <- openFile \"output\" WriteMode\n printStates 5 10 1 file\n hClose file\n\n", "meta": {"hexsha": "f8d07051cfa7c86f53013ce10d308126a9b17aeb", "size": 6141, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "eigenvalues_calculation.hs", "max_stars_repo_name": "aivuk/quantum-haskell", "max_stars_repo_head_hexsha": "ee089b379229dc15dc8ed42a8840ee5c9b03e068", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-11T02:31:22.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-11T02:31:22.000Z", "max_issues_repo_path": "eigenvalues_calculation.hs", "max_issues_repo_name": "aivuk/quantum-haskell", "max_issues_repo_head_hexsha": "ee089b379229dc15dc8ed42a8840ee5c9b03e068", "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": "eigenvalues_calculation.hs", "max_forks_repo_name": "aivuk/quantum-haskell", "max_forks_repo_head_hexsha": "ee089b379229dc15dc8ed42a8840ee5c9b03e068", "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.4451219512, "max_line_length": 149, "alphanum_fraction": 0.4450415242, "num_tokens": 1979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891348788759, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5177938282042823}} {"text": "{-# LANGUAGE QuantifiedConstraints, \n TupleSections,\n DefaultSignatures,\n FlexibleInstances,\n FlexibleContexts,\n UndecidableInstances,\n ConstraintKinds,\n MultiParamTypeClasses,\n TypeFamilies #-}\n\nmodule Tensor where\nimport Data.Complex\nimport Helper\nimport EitherTrans\nimport Control.Monad.Trans.State\nimport Data.Monoid\nimport Data.List\nimport Data.Function\nimport System.Random\nimport System.Random.Stateful\n\n-- orphan instance\n-- sort complex numbers by their magnitudes\ninstance RealFloat a => Ord (Complex a) where\n compare a b = compare (magnitude a) (magnitude b)\n\ninstance (UniformRange a) => UniformRange (Complex a) where\n uniformRM (lr :+ li, hr :+ hi) g = do\n mr <- uniformRM (lr, hr) g \n mi <- uniformRM (li, hi) g\n return $ mr :+ mi\n\ninstance (Uniform a) => Uniform (Complex a) where\n uniformM g = do\n r <- uniformM g\n i <- uniformM g\n return $ r :+ i\n \n\n{-\n The definition of tensor product should follow conventional tensor product properties.\n Tensor product should form a monoid upto isomorphism\n-}\n\n-- higer-kinded definition\n-- Polymorphic constraints\n\nclass Cmplx c where\n conj :: c -> c\n conj = error \"please define conjugate function\"\n\ninstance (Num a) => Cmplx (Complex a) where\n conj = conjugate\n\nclass (Monoid (t a), Cmplx a) => Tensor t a where\n (|*|) :: t a -> t a -> t a\n (|*|) = (<>)\n tconcat :: [t a] -> t a\n tconcat = mconcat\n norm :: Floating a => t a -> t a\n fromList :: Integral b => [a] -> b -> t a\n rank :: Integral b => t a -> b\n isSquare :: t a -> Bool\n conjTr :: t a -> t a\n inner :: t a -> t a -> t a\n\nclass (Tensor q a, Num (q a)) => QuantumRegister q a where\n\n densityOp :: q a\n -> q a\n\n densityOp x = x * conjTr x\n\n -- Builds a transformation tensor to apply input gate to selected qubit\n build :: (Integral b, Integral d) => b -- ^ Number of qubits this tensor applies to\n -> [(d, q a)]-- ^ Index / Gate pair (Pre-sorted)\n -> q a -- ^ Default Gate\n -> q a\n build i xs d = tconcat $ go i (sortOnFst xs) d 0\n where\n go i2 [] d2 n = replicate (fromIntegral i2 - n) d2\n go i2 (x:xs) d2 n = replicate (fromIntegral (fst x) - n) d2 ++ (snd x : go i2 xs d2 (fromIntegral $ fst x + 1))\n\n getProb :: Int -- ^ Index of the qubit\n -> q a -- ^ Qubits\n -> Either String (a, a) -- ^ Resulting Probability\n default getProb :: (Foldable q, Floating a) => Int -> q a -> Either String (a, a) -- ^ Resulting Probability\n getProb i q\n | i < 0 || i >= rank q = Left \"Index out of bounds\"\n | not (isSquare q) = Left \"Invalid Quantum Register\"\n | otherwise = do\n a <- applyGate mask0 i q\n b <- applyGate mask1 i q\n return (f a, f b)\n where\n f = getSum . foldMap (Sum . (\\x -> conj x * x))\n\n initQubit :: a -- ^ Constant for |0>\n -> a -- ^ Constant for |1>\n -> Either String (q a) -- ^ Resulting Qubit\n\n initQubit0 :: q a -- ^ Initialize |0> qubit at z-direction\n\n initNumQubit0 :: (Integral b) => b -- ^ Number of qubits to initialize\n -> Either String (q a) -- ^ Initialized quantum register\n\n toQuantumRegister :: [a] -- ^ State vector array to convert\n -> Either String (q a) -- ^ Converted Quantum Register\n\n collapse :: Int -- ^ Index of the qubit\n -> Bool -- ^ Collapsed State\n -> q a -- ^ Qubits to collapse\n -> Either String (q a) -- ^ Resulting Tensor\n\n default collapse :: (Floating a) => Int -> Bool -> q a -> Either String (q a)\n collapse i s q\n | i < 0 || i >= rank q = Left \"Index out of bounds\"\n | not (isSquare q) = Left \"Invalid state vector\"\n | s = norm <$> applyGate mask1 i q\n | otherwise = norm <$> applyGate mask0 i q\n\n measure :: (Monad m, StatefulGen g m, UniformRange a) => Int -- ^ Index of the qubit\n -> g -- ^ generator\n -> StateT (q a) (EitherT String m) Bool -- ^ Resulting State Transformer\n\n default measure :: (Monad m, Num a, Ord a, StatefulGen g m, UniformRange a) => Int -- ^ Index of the qubit\n -> g -- ^ generator\n -> StateT (q a) (EitherT String m) Bool -- ^ Resulting State Transformer\n measure i g = StateT go\n where\n go q\n | i < 0 || i >= rank q = EitherT $ return $ Left \"Index out of bounds\"\n | not (isSquare q) = EitherT $ return $ Left \"Invalid state vector\"\n | otherwise = EitherT $ do\n p <- uniformRM (0, 1) g\n return $ do\n t <- getProb i q\n if p < fst t\n then (False, ) <$> collapse i False q\n else (True, ) <$> collapse i True q\n\n\n applyGate :: q a -- ^ Gate tensor\n -> Int -- ^ Index\n -> q a -- ^ Quantum Registers\n -> Either String (q a)\n applyGate a i b\n | not (isSquare a) = Left \"Invalid Gate Tensor\"\n | not (isSquare b) = Left \"Invalid Statevector\"\n | i < 0 || i >= rank b = Left \"Index out of bounds\"\n | otherwise = Right $ build (rank b) [(i, a)] pauliId * b\n\n\n applyGateAll :: q a -- ^ Gate tensor\n -> q a -- ^ Quantum Registers\n -> Either String (q a)\n\n applyGateAll a b\n | not (isSquare a) = Left \"Invalid Gate Tensor\"\n | not (isSquare b) = Left \"Invalid Statevector\"\n | otherwise = Right $ build (rank b) [] a * b\n\n applyControl :: q a -- ^ Gate tensor\n -> Int -- ^ Control qubit index\n -> Int -- ^ Apply qubit index\n -> q a -- ^ Quantum Registers\n -> Either String (q a)\n\n applyControl a ctl i b\n | not (isSquare a) = Left \"Invalid gate tensor\"\n | not (isSquare b) = Left \"Invalid state vector\"\n | i < 0 || i >= rank b = Left \"Application qubit index out of bounds\"\n | ctl < 0 || ctl >= rank b = Left \"Control qubit index out of bounds\"\n | ctl == i = Left \"Control and application qubit cannot be the same\"\n | otherwise = Right $ (build (rank b) [(ctl, mask0)] pauliId\n + build (rank b) (sortBy (compare `on` fst) [(ctl, mask1), (i, a)]) pauliId) * b\n\n illegalPeek :: q a\n -> String\n\n subSystem :: [Int] -> q a -> Either String (q a)\n\n isEntangled :: [Int] -> q a -> Either String Bool\n\n mask0 :: q a\n mask1 :: q a\n pauliId :: q a\n\nclass (QuantumRegister q a) => Gates q a where\n pauliX :: q a\n pauliY :: q a\n pauliZ :: q a\n hadamard :: q a\n\n\n\n-- Num-only declaration\n\n-- class (forall a. Num a => Monoid (t a)) => Tensor t where\n-- (|*|) :: (Num a) => t a -> t a -> t a\n-- (|*|) = (<>)\n-- norm :: Floating a => t a -> t a\n-- fromList :: Integral b => [a] -> b -> t a\n-- rank :: Integral b => t a -> b\n-- isSquare :: t a -> Bool\n\n-- class (Tensor q, forall a. Num a => Num (q a)) => QuantumRegister q where\n-- -- Builds a transformation tensor to apply input gate to selected qubit\n-- build :: (RealFloat a, Integral b, Integral c) => b -- ^ Number of qubits this tensor applies to\n-- -> [(c, q (Complex a))]-- ^ Index / Gate pair (Pre-sorted)\n-- -> q (Complex a) -- ^ Default Gate\n-- -> q (Complex a)\n-- build i xs d = mconcat $ go i (sortOnFst xs) d 0\n-- where\n-- go i2 [] d2 n = replicate (fromIntegral i2 - n) d2\n-- go i2 (x:xs) d2 n = replicate (fromIntegral (fst x) - n) d2 ++ (snd x : go i2 xs d2 (fromIntegral $ fst x + 1))\n\n-- getProb :: (RealFloat a) => Int -- ^ Index of the qubit\n-- -> q (Complex a) -- ^ Qubits\n-- -> Either String (a, a) -- ^ Resulting Probability\n\n-- initQubit :: (RealFloat a) => Complex a -- ^ Constant for |0>\n-- -> Complex a -- ^ Constant for |1>\n-- -> Either String (q (Complex a)) -- ^ Resulting Qubit\n\n-- initQubit0 :: (RealFloat a) => q (Complex a) -- ^ Initialize |0> qubit at z-direction\n\n-- initNumQubit0 :: (RealFloat a, Integral b) => b -- ^ Number of qubits to initialize\n-- -> Either String (q (Complex a)) -- ^ Initialized quantum register\n\n-- toQuantumRegister :: (RealFloat a) => [Complex a] -- ^ State vector array to convert\n-- -> Either String (q (Complex a)) -- ^ Converted Quantum Register\n\n-- collapse :: (RealFloat a) => Int -- ^ Index of the qubit\n-- -> Complex a -- ^ Collapsed State\n-- -> q (Complex a) -- ^ Qubits to collapse\n-- -> EitherT String IO (q (Complex a)) -- ^ Resulting Tensor\n\n-- measure :: (RealFloat a, Monad m) => Int -- ^ Index of the qubit\n-- -> StateT (q (Complex a)) (EitherT String m) (Complex a)\n-- -- -> q (Complex a) -- ^ Qubits\n-- -- -> Either String ( m (Complex a, q (Complex a))) -- ^ Resulting measurement and the collapsed qubits\n\n\n-- pauliX :: (RealFloat a) => q (Complex a)\n-- pauliY :: (RealFloat a) => q (Complex a)\n-- pauliZ :: (RealFloat a) => q (Complex a)\n-- pauliId :: (RealFloat a) => q (Complex a)\n-- hadamard :: (RealFloat a) => q (Complex a)\n-- mask0 :: (RealFloat a) => q (Complex a)\n-- mask1 :: (RealFloat a) => q (Complex a)", "meta": {"hexsha": "457e5e9d59b6217d0562da1e60dceca88ee289de", "size": 9260, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Tensor.hs", "max_stars_repo_name": "w41g87/Qaskell", "max_stars_repo_head_hexsha": "40bfa73d1e4b6ab59921129cd84190d7440eba7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Tensor.hs", "max_issues_repo_name": "w41g87/Qaskell", "max_issues_repo_head_hexsha": "40bfa73d1e4b6ab59921129cd84190d7440eba7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Tensor.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": 36.8924302789, "max_line_length": 126, "alphanum_fraction": 0.5476241901, "num_tokens": 2647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5170111525293933}} {"text": "{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, GeneralizedNewtypeDeriving #-}\n\n-- | This module defines the Syntax of the Quantum IO Monad, which is an embedded\n-- language for writing quantum computations.\nmodule QIO.QioSyn where\n\nimport Data.Monoid as Monoid\nimport Data.Complex\nimport Control.Applicative (Applicative(..))\nimport Control.Monad (liftM, ap)\n\n-- | For Real numbers, we simply use the built in Double type\ntype RR = Double\n\n-- | For Complex numbers, we use the built in Complex numbers, over our Real\n-- number type (i.e. Double)\ntype CC = Complex RR\n\n-- | The amplitude of a complex number is the magnitude squared.\namp :: CC -> RR\namp k = (magnitude k)*(magnitude k)\n\n-- | The type of Qubits in QIO are simply integer references.\nnewtype Qbit = Qbit Int deriving (Num, Enum, Eq, Ord)\n\n\n-- | A rotation is in essence a two-by-two complex valued matrix\ntype Rotation = ((Bool,Bool) -> CC)\n\n-- | The underlying data type of a U unitary operation\ndata U = UReturn | Rot Qbit Rotation U\n | Swap Qbit Qbit U | Cond Qbit (Bool -> U) U | Ulet Bool (Qbit -> U) U\n\n-- | The underlying data type of a QIO Computation\ndata QIO a = QReturn a | MkQbit Bool (Qbit -> QIO a) | ApplyU U (QIO a)\n | Meas Qbit (Bool -> QIO a)\n\n\n-- | The type \"U\" forms a Monoid\ninstance Semigroup U where\n --mempty = UReturn\n UReturn <> u = u\n (Rot x a u) <> u' = Rot x a (u <> u')\n (Swap x y u) <> u' = Swap x y (u <> u')\n (Cond x br u') <> u'' = Cond x br (u' <> u'')\n (Ulet b f u) <> u' = Ulet b f (u <> u')\n\ninstance Monoid U where\n mempty = UReturn\n\n\n-- | Apply the given rotation to the given qubit\nrot :: Qbit -> Rotation -> U\nrot x r = Rot x r UReturn\n\n-- | Swap the state of the two given qubits\nswap :: Qbit -> Qbit -> U\nswap x y = Swap x y UReturn\n\n-- | Apply the conditional unitary, depending on the value of the given qubit\ncond :: Qbit -> (Bool -> U) -> U\ncond x br = Cond x br UReturn\n\n-- | Introduce an Ancilla qubit in the given state, for use in the sub-unitary\nulet :: Bool -> (Qbit -> U) -> U\nulet b ux = Ulet b ux UReturn\n\n-- | Returns the inverse (or reverse) of the given unitary operation\nurev :: U -> U\nurev UReturn = UReturn\nurev (Rot x r u) = urev u <> rot x (rrev r)\nurev (Swap x y u) = urev u <> swap x y\nurev (Cond x br u) = urev u <> cond x (urev.br)\nurev (Ulet b xu u) = urev u <> ulet b (urev.xu)\n\n-- | Apply a not rotation to the given qubit\nunot :: Qbit -> U\nunot x = rot x rnot\n\n-- | Apply a hadamard rotation to the given qubit\nuhad :: Qbit -> U\nuhad x = rot x rhad\n\n-- | Apply a phase rotation (of the given angle) to the given qubit\nuphase :: Qbit -> RR -> U\nuphase x r = rot x (rphase r)\n\ninstance Functor QIO where\n fmap = liftM\n\ninstance Applicative QIO where\n pure = QReturn\n (<*>) = ap\n\n-- | The \"QIO\" type forms a Monad\ninstance Monad QIO where\n return = pure\n (QReturn a) >>= f = f a\n (MkQbit b g) >>= f = MkQbit b (\\ x -> g x >>= f)\n (ApplyU u q) >>= f = ApplyU u (q >>= f)\n (Meas x g) >>= f = Meas x (\\ b -> g b >>= f)\n\n-- | Initialise a qubit in the given state (adding it to the overall quantum state)\nmkQbit :: Bool -> QIO Qbit\nmkQbit b = MkQbit b return\n\n-- | Apply the given unitary operation to the current quantum state\napplyU :: U -> QIO ()\napplyU u = ApplyU u (return ())\n\n-- | Measure the given qubit, and return the measurement outcome (note that this\n-- operation may affect the overall quantum state, as a measurement is destructive)\nmeasQbit :: Qbit -> QIO Bool\nmeasQbit x = Meas x return\n\n\n-- | The identity rotation\nrid :: Rotation\nrid (x,y) = if x==y then 1 else 0\n\n-- | The not rotation\nrnot :: Rotation\nrnot (x,y) = if x==y then 0 else 1\n\n-- | The hadamard rotation\nrhad :: Rotation\nrhad (x,y) = if x && y then -h else h where h = (1/sqrt 2)\n\n-- | The phase rotation\nrphase :: RR -> Rotation\nrphase _ (False,False) = 1\nrphase r (True,True) = exp(0:+r)\nrphase _ (_,_) = 0\n\n-- | Returns the inverse (or reverse) of the given rotation\nrrev :: Rotation -> Rotation\nrrev r (False,True) = conjugate (r (True,False))\nrrev r (True,False) = conjugate (r (False,True))\nrrev r xy = conjugate (r xy)\n\n-- | Rotations can be compared for equality.\n-- They are equal if the define the same matrix.\ninstance Eq Rotation where\n f == g = (f (False,False) == g (False,False))\n && (f (False,True) == g (False,True))\n && (f (True,False) == g (True,False))\n && (f (True,True) == g (True,True))\n f /= g = (f (False,False) /= g (False,False))\n || (f (False,True) /= g (False,True))\n || (f (True,False) /= g (True,False))\n || (f (True,True) /= g (True,True))\n\n\n-- | We can display a qubit reference\ninstance Show Qbit where\n show (Qbit q) = \"(Qbit:\" ++ show q ++ \")\"\n\n-- | We can display the matrix representation of a rotation\ninstance Show Rotation where\n show f = \"(\" ++ (show (f (False,False))) ++ \",\" ++ (show (f (False,True))) ++ \",\" ++ (show (f (True,False))) ++ \",\" ++ (show (f (True,True))) ++ \")\"\n\n-- | We can display a representation of a unitary\ninstance Show U where\n show u = show' u 0 (-1)\n\n-- | A helper function for the show instance of U\nshow' :: U -> Int -> Int -> String\nshow' (UReturn) x fv = \"\"\nshow' (Rot q a u) x fv = spaces x ++ \"Rotate \" ++ show q ++ \" by \" ++ show a ++ \".\\n\" ++ show' u x fv\nshow' (Swap q1 q2 u) x fv = spaces x ++ \"Swap \" ++ show q1 ++ \" and \" ++ show q2 ++ \".\\n\" ++ show' u x fv\nshow' (Cond q f u) x fv = spaces x ++ \"Cond (if \" ++ show q ++ \" then \\n\" ++ spaces (x+1) ++ \"(\\n\" ++ show' (f True) (x+1) fv ++ spaces (x+1) ++ \")\\n\" ++ spaces x ++ \"else \\n\" ++ spaces (x+1) ++ \"(\\n\" ++ show' (f False) (x+1) fv ++ spaces (x+1) ++ \")\\n\" ++ show' u x fv\nshow' (Ulet b f u) x fv = spaces x ++ \"Ulet \" ++ show b ++ \" (\\\\\" ++ show (Qbit fv) ++ \"->\\n \" ++ show' (f (Qbit fv)) x (fv-1) ++ \")\\n\" ++ show' u x fv\n\n-- | A helper function that returns a string of 4\\x\\ spaces.\nspaces :: Int -> String\nspaces 0 = \"\"\nspaces n = if (n < 0) then error \"spaces: negative argument\"\n else \" \" ++ spaces (n-1)\n", "meta": {"hexsha": "86268a8d649b67a4d186ec72fd35bfd84bbd98b2", "size": 6097, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "QIO/QioSyn.hs", "max_stars_repo_name": "karlti/qio-haskell", "max_stars_repo_head_hexsha": "c08ee61802446eb793a81082a9c31c995831da3e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-11T15:26:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-11T15:26:05.000Z", "max_issues_repo_path": "QIO/QioSyn.hs", "max_issues_repo_name": "karlti/qio-haskell", "max_issues_repo_head_hexsha": "c08ee61802446eb793a81082a9c31c995831da3e", "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": "QIO/QioSyn.hs", "max_forks_repo_name": "karlti/qio-haskell", "max_forks_repo_head_hexsha": "c08ee61802446eb793a81082a9c31c995831da3e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-12T22:41:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T09:25:43.000Z", "avg_line_length": 34.061452514, "max_line_length": 269, "alphanum_fraction": 0.5991471215, "num_tokens": 1940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.5169808435886629}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeFamilies #-}\n-- |\n-- Monoids for calculating various statistics in constant space. This\n-- module contains algorithms that should be generally avoided unless\n-- there's specific reason to use them.\nmodule Statistics.Monoid.Extra (\n -- * Mean\n WelfordMean(..)\n , asWelfordMean\n , MeanKahan(..)\n , asMeanKahan\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-- Mean\n----------------------------------------------------------------\n\n-- | Incremental calculation of mean. Sum of elements is calculated\n-- using compensated Kahan summation. It's provided only for sake of\n-- completeness. 'Statistics.Monoid.Numeric.KBNSum' should be used\n-- instead.\ndata MeanKahan = MeanKahan !Int !KahanSum\n deriving (Show,Eq,Typeable,Data,Generic)\n\nasMeanKahan :: MeanKahan -> MeanKahan\nasMeanKahan = id\n\n\ninstance Semigroup MeanKahan where\n (<>) = mappend\n {-# INLINE (<>) #-}\n\ninstance Monoid MeanKahan where\n mempty = MeanKahan 0 mempty\n MeanKahan 0 _ `mappend` m = m\n m `mappend` MeanKahan 0 _ = m\n MeanKahan n1 s1 `mappend` MeanKahan n2 s2 = MeanKahan (n1+n2) (s1 `mappend` s2)\n\ninstance Real a => StatMonoid MeanKahan a where\n addValue (MeanKahan n m) x = MeanKahan (n+1) (addValue m x)\n\ninstance CalcCount MeanKahan where\n calcCount (MeanKahan n _) = n\ninstance CalcMean MeanKahan where\n calcMean (MeanKahan 0 _) = Nothing\n calcMean (MeanKahan n s) = Just (kahan s / fromIntegral n)\n\n\n-- | Incremental calculation of mean. Note that this algorithm doesn't\n-- offer better numeric precision than plain summation. Its only\n-- advantage is protection against double overflow:\n--\n-- > λ> calcMean $ asMeanKBN $ reduceSample (replicate 100 1e308)\n-- > Just NaN\n-- > λ> calcMean $ asWelfordMean $ reduceSample (replicate 100 1e308)\n-- > Just 1.0e308\n--\n-- Unless this feature is needed 'Statistics.Monoid.Numeric.KBNSum'\n-- should be used. Algorithm is due to Welford [Welford1962]\ndata WelfordMean = WelfordMean !Int -- Number of entries\n !Double -- Current mean\n deriving (Show,Eq,Typeable,Data,Generic)\n\n-- | Type restricted 'id'\nasWelfordMean :: WelfordMean -> WelfordMean\nasWelfordMean = id\n\ninstance Semigroup WelfordMean where\n (<>) = mappend\n {-# INLINE (<>) #-}\n\ninstance Monoid WelfordMean where\n mempty = WelfordMean 0 0\n mappend (WelfordMean 0 _) m = m\n mappend m (WelfordMean 0 _) = m\n mappend (WelfordMean n x) (WelfordMean k y)\n = WelfordMean (n + k) ((x*n' + y*k') / (n' + k'))\n where\n n' = fromIntegral n\n k' = fromIntegral k\n {-# INLINE mempty #-}\n {-# INLINE mappend #-}\n\n-- | \\[ s_n = s_{n-1} + \\frac{x_n - s_{n-1}}{n} \\]\ninstance Real a => StatMonoid WelfordMean a where\n addValue (WelfordMean n m) !x\n = WelfordMean n' (m + (realToFrac x - m) / fromIntegral n')\n where\n n' = n+1\n {-# INLINE addValue #-}\n\ninstance CalcCount WelfordMean where\n calcCount (WelfordMean n _) = n\ninstance CalcMean WelfordMean where\n calcMean (WelfordMean 0 _) = Nothing\n calcMean (WelfordMean _ m) = Just m\n\n\n\n----------------------------------------------------------------\n-- Unboxed instances\n----------------------------------------------------------------\n\nderivingUnbox \"MeanKahan\"\n [t| MeanKahan -> (Int,Double,Double) |]\n [| \\(MeanKahan a (KahanSum b c)) -> (a,b,c) |]\n [| \\(a,b,c) -> MeanKahan a (KahanSum b c) |]\n\nderivingUnbox \"WelfordMean\"\n [t| WelfordMean -> (Int,Double) |]\n [| \\(WelfordMean a b) -> (a,b) |]\n [| \\(a,b) -> WelfordMean a b |]\n\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", "meta": {"hexsha": "989cbf214604ce1d8a8a1abf2aec84bd95305279", "size": 4569, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Monoid/Extra.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/Extra.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/Extra.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": 31.7291666667, "max_line_length": 81, "alphanum_fraction": 0.6180783541, "num_tokens": 1317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5165101703135304}} {"text": "module Solve where\n\nimport Data.List\nimport Control.Applicative ((<|>), many)\nimport Control.Monad (void)\nimport Data.Char (isLetter, isDigit)\nimport qualified Debug.Trace as DT\nimport Numeric.LinearAlgebra.Data\nimport Data.Int\n\nimport Text.ParserCombinators.Parsec\nimport qualified Text.ParserCombinators.Parsec.Token as P\nimport Text.ParserCombinators.Parsec.Language\n\n\n-- TYPE DEFINITIONS\ndata Point = MkPoint {\n x :: Int,\n y :: Int\n} deriving (Show, Eq)\n\ndata Dimensions = MkDimensions {\n width :: Int,\n height :: Int\n} deriving (Show, Eq)\n\ndata Rectangle = MkRectangle {\n upperLeft :: Point,\n dimensions :: Dimensions\n} deriving (Show, Eq)\n \ndata Claim = MkClaim {\n index :: Int,\n rectangle :: Rectangle\n} deriving (Show, Eq)\n\n-- PARSING\n-- of course, we could simply use a regular expression, but I've always wanted to play \n-- around with the Parsec library for generating parsers, so bear with me :-)\nnumParser :: Parser Int\nnumParser = do\n n <- many1 digit\n return (read n)\n\npointParser :: Parser Point\npointParser = do\n x <- numParser\n void $ char ','\n y <- numParser\n return (MkPoint x y) \n\ndimensionsParser :: Parser Dimensions\ndimensionsParser = do\n width <- numParser\n void $ char 'x'\n height <- numParser\n return (MkDimensions width height)\n\nrectangleParser :: Parser Rectangle\nrectangleParser = do\n p <- pointParser\n void $ char ':'\n void $ char ' '\n dim <- dimensionsParser\n return (MkRectangle p dim)\n \nclaimParser :: Parser Claim\nclaimParser = do\n void $ char '#'\n idx <- numParser\n void $ char ' '\n void $ char '@'\n void $ char ' '\n rect <- rectangleParser\n return (MkClaim idx rect)\n\n-- helper function to apply a parser\nregularParse :: Parser a -> String -> Either ParseError a\nregularParse p = parse p \"\"\n\n\n-- MAIN routines\n--\n-- create an association list for the given claim\n-- the association list contains a list of (x,y) coordinates plus the value (which equals the claim's index)\ntoAssocList :: Claim -> [((Int, Int), Int64)]\ntoAssocList c = map (\\(i,j) -> ((i,j), (fromIntegral idx))) indices \n where idx = index c \n r = rectangle c\n x' = x $ upperLeft r\n y' = y $ upperLeft r\n width' = width $ dimensions r\n height' = height $ dimensions r\n indices = [(i,j) | i <- [(x'+1) .. (x' + width')],\n j <- [(y'+1) .. (y' + height')]]\n\n\n-- apply the given claim to the given matrix\napplyClaim :: Claim -> Matrix Int64 -> Matrix Int64\napplyClaim c m = accum m (\\new old -> if old == 0 then new else -1) (toAssocList c)\n\n-- apply the given list of claims to the given matrix\napplyClaims :: [Either ParseError Claim ] -> Matrix Int64 -> Matrix Int64\napplyClaims [] m = m\napplyClaims (x:xs) m = \n case x of\n Right x' -> applyClaims xs (applyClaim x' m)\n Left _ -> applyClaims xs m -- leave m unchanged for erroneous claim\n\n-- count the elements in the given matrix that are equal to the given value\ncountElems :: Matrix Int64 -> Int64 -> Int\ncountElems m val = length $ filter (\\x -> x == val) $ toList $ flatten m \n\n-- count the clashes (squares with overlapping claims)\ncountClashes :: Matrix Int64 -> Int\ncountClashes m = countElems m (-1)\n\n-- prepare solution: parse input, build a 1001x1001 matrix, and apply all claims to it\nprepSolution:: String -> ([Claim], Matrix Int64)\nprepSolution input = (validClaims, applyClaims claims m)\n where claims = map (\\line -> regularParse claimParser line) $ lines input\n m = (1001><1001) (repeat 0) -- 1001x1001, all elements are 0\n m2 = applyClaims claims m\n validClaims = map (\\(Right x) -> x) $ filter (\\x -> case x of Right _ -> True) claims\n\n-- find the single claim that is intact\n-- our approach is kind of brute force - for n claims, we check all matrix elements n times\nfindIntactClaim :: ([Claim], Matrix Int64) -> Claim\nfindIntactClaim (claims, m) = head $ filter (\\c -> area c == countElems m (fromIntegral (index c))) claims\n where area c' = width (dimensions (rectangle c')) * height (dimensions (rectangle c'))\n\nsolveI :: String -> Int\nsolveI = countClashes . snd . prepSolution\n\nsolveII :: String -> Int\nsolveII = index . findIntactClaim . prepSolution \n\n#if defined(STANDALONE)\nmain = do\n input <- readFile \"input.txt\"\n putStrLn $ show $ solveI input \n putStrLn $ show $ solveII input \n#endif\n", "meta": {"hexsha": "d87d9a80fa452adb2ac0238144c854ec799ece6c", "size": 4358, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "2018/03-no_matter_how_you_slice_it/Solve.hs", "max_stars_repo_name": "frankschmitt/advent_of_code", "max_stars_repo_head_hexsha": "812c8f744c7eb99c9819b0f4bb3727122d0ff515", "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": "2018/03-no_matter_how_you_slice_it/Solve.hs", "max_issues_repo_name": "frankschmitt/advent_of_code", "max_issues_repo_head_hexsha": "812c8f744c7eb99c9819b0f4bb3727122d0ff515", "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": "2018/03-no_matter_how_you_slice_it/Solve.hs", "max_forks_repo_name": "frankschmitt/advent_of_code", "max_forks_repo_head_hexsha": "812c8f744c7eb99c9819b0f4bb3727122d0ff515", "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.2638888889, "max_line_length": 108, "alphanum_fraction": 0.6681964204, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5163500186810395}} {"text": "{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeFamilies #-}\n\n-- |\n-- Module : Spiral.SPL\n-- Copyright : (c) 2016-2017 Drexel University\n-- License : BSD-style\n-- Maintainer : mainland@drexel.edu\n\nmodule Spiral.SPL (\n module Spiral.Permutation,\n\n SPL(..),\n matrix,\n fromLists,\n fromFunction,\n\n diag,\n circ,\n skew,\n toep,\n permute,\n backpermute,\n\n extent,\n\n mXv,\n (#>),\n\n toMatrix,\n col,\n row,\n\n transpose,\n\n inverse,\n\n (<->),\n (<|>),\n block,\n\n (⊗),\n (×),\n (⊕),\n\n Z(..),\n (:.)(..),\n\n DIM0,\n DIM1,\n DIM2,\n ix1,\n ix2\n ) where\n\nimport Data.Complex\nimport Data.Monoid ((<>))\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector as V\nimport Text.PrettyPrint.Mainland hiding ((<|>))\nimport Text.PrettyPrint.Mainland.Class\n\nimport qualified Spiral.Array as A\nimport Spiral.Array (D,\n IArray,\n M,\n Matrix,\n Vector,\n manifest)\nimport qualified Spiral.Array.Operators.Mapping as A\nimport qualified Spiral.Array.Operators.Matrix as A\nimport Spiral.Array.Repr.Complex\nimport Spiral.Array.Shape\nimport Spiral.Exp\nimport Spiral.Permutation hiding (Inv)\nimport Spiral.RootOfUnity\nimport Spiral.Util.Pretty\n\n-- | Wrap an array to ensure it is unconditionally Show-able.\nnewtype ShowArray r sh e = ShowArray { unShowArray :: Array r sh e }\n\ninstance (Show sh, Show e, IArray r sh e) => Show (ShowArray r sh e) where\n show arr = show (manifest (unShowArray arr))\n\n-- | An SPL transform. The type index is the type of the scalar values in the\n-- transformed vector.\ndata SPL a where\n -- | An \"embedded\" array with an unknown representation.\n E :: IArray r DIM2 e => ShowArray r DIM2 e -> SPL e\n\n -- | The $n \\times n$ identity matrix.\n I :: Num e => Int -> SPL e\n\n -- | Transpose\n T :: SPL e -> SPL e\n\n -- | Inverse\n Inv :: (Eq e, Fractional e) => SPL e -> SPL e\n\n -- | A permutation\n Pi :: Permutation -> SPL e\n\n -- | The rotation matrix\n Rot :: Floating a => a -> SPL a\n\n -- | A diagonal matrix\n Diag :: V.Vector e -> SPL e\n\n -- | The $n \\times n$ diagonal matrix with constant diagonal elements.\n KDiag :: Int -> e -> SPL e\n\n -- | Vertical stacking of transforms\n Above :: SPL e -> SPL e -> SPL e\n\n -- | Horizontal stacking of transforms\n Beside :: SPL e -> SPL e -> SPL e\n\n -- | Kronecker product\n Kron :: SPL e -> SPL e -> SPL e\n\n -- | Direct sum\n DSum :: SPL e -> SPL e -> SPL e\n\n -- | Matrix product\n Prod :: SPL e -> SPL e -> SPL e\n\n -- | Circulant matrix given first column\n Circ :: V.Vector e -> SPL e\n\n -- | Skew-Circulant matrix given first column\n Skew :: V.Vector e -> SPL e\n\n -- | Toeplitz matrix\n Toep :: V.Vector e -> SPL e\n\n -- | Make a complex transform into a real transform.\n Re :: RealFloatConst a => SPL (Exp (Complex a)) -> SPL (Exp a)\n\n -- | The 2x2 DFT\n F2 :: SPL e\n\n -- | The nxn DFT matrix\n DFT :: RootOfUnity a => Int -> SPL a\n\n -- | The nxn Inverse DFT matrix\n DFT' :: RootOfUnity a => Int -> SPL a\n\n -- | The nxn \"rotated\" DFT matrix\n F :: RootOfUnity a => Int -> a -> SPL a\n\n -- | The nxn \"rotated\" inverse DFT matrix\n F' :: RootOfUnity a => Int -> a -> SPL a\n\nderiving instance Show e => Show (SPL e)\nderiving instance Typeable e => Typeable (SPL e)\n\n-- | Embed any 'Matrix' as an SPL term.\nmatrix :: IArray r DIM2 e\n => Array r DIM2 e\n -> SPL e\nmatrix = E . ShowArray\n\n-- | Embed a matrix created from a list of lists of values.\nfromLists :: [[e]] -> SPL e\nfromLists = matrix . A.fromLists\n\n-- | Embed a matrix created from a function mapping indices to elements.\nfromFunction :: DIM2 -> (DIM2 -> e) -> SPL e\nfromFunction sh = matrix . A.fromFunction sh\n\n-- | Create a diagonal matrix\ndiag :: [a] -> SPL a\ndiag = Diag . V.fromList\n\n-- | Create a circulant matrix from the first column\ncirc :: [a] -> SPL a\ncirc = Circ . V.fromList\n\n-- | Create a skew circulant matrix from the first column\nskew :: [a] -> SPL a\nskew = Skew . V.fromList\n\n-- | Create a Toeplitz matrix\ntoep :: [a] -> SPL a\ntoep = Toep . V.fromList\n\n-- | Permute (scatter).\npermute :: Permutation -> SPL e\npermute = Pi\n\n-- | Backpermute (gather).\nbackpermute :: Permutation -> SPL e\nbackpermute = Pi . invert\n\n-- | Return the extent of an SPL transform.\nextent :: SPL a -> DIM2\nextent (E a) = A.extent (unShowArray a)\nextent (I n) = ix2 n n\nextent (T e) = ix2 n m\n where\n Z :. m :. n = extent e\nextent (Inv e) = ix2 n n\n where\n Z :. n :. _ = extent e\nextent (Pi p) = ix2 (dim p) (dim p)\nextent (Rot _) = ix2 2 2\nextent (Diag xs) = ix2 n n\n where\n n = length xs\nextent (KDiag n _) = ix2 n n\n\nextent (Above a b) = ix2 (ra+rb) c\n where\n Z :. ra :. c = extent a\n Z :. rb :. _c = extent b\n\nextent (Beside a b) = ix2 r (ca+cb)\n where\n Z :. r :. ca = extent a\n Z :. _r :. cb = extent b\n\nextent (Kron a b) = ix2 (m*p) (n*q)\n where\n Z :. m :. n = extent a\n Z :. p :. q = extent b\n\nextent (DSum a b) = ix2 (m+p) (n+q)\n where\n Z :. m :. n = extent a\n Z :. p :. q = extent b\n\nextent (Prod a b) = ix2 m q\n where\n Z :. m :. _n = extent a\n Z :. _p :. q = extent b\n\nextent (Circ xs) = ix2 n n\n where\n n = length xs\n\nextent (Skew xs) = ix2 n n\n where\n n = length xs\n\nextent (Toep xs) = ix2 n n\n where\n n = (length xs + 1) `quot` 2\n\nextent (Re a) = ix2 (2*m) (2*n)\n where\n Z :. m :. n = extent a\n\nextent F2 = ix2 2 2\n\nextent (DFT n) = ix2 n n\nextent (DFT' n) = ix2 n n\nextent (F n _) = ix2 n n\nextent (F' n _) = ix2 n n\n\n-- | Transpose an SPL expression\ntranspose :: forall a . (Show a, Num a) => SPL a -> SPL a\n-- transpose (E m) = (matrix . A.transpose . unShowArray) m\ntranspose a@I{} = a\ntranspose (T a) = a\ntranspose (Inv a) = Inv (transpose a)\ntranspose (Pi p) = backpermute p\ntranspose (Rot alpha) = Rot (-alpha)\ntranspose a@Diag{} = a\ntranspose a@KDiag{} = a\ntranspose (Above a b) = Beside (transpose a) (transpose b)\ntranspose (Beside a b) = Above (transpose a) (transpose b)\ntranspose (Kron a b) = Kron (transpose a) (transpose b)\ntranspose (DSum a b) = DSum (transpose a) (transpose b)\ntranspose (Prod a b) = Prod (transpose b) (transpose a)\ntranspose (Circ cs) = circ (x:reverse xs)\n where\n x:xs = V.toList cs\ntranspose a@Skew{} = a\ntranspose (Toep cs) = Toep (V.reverse cs)\ntranspose (Re a) = Re (transpose a)\ntranspose F2 = F2\ntranspose a@DFT{} = a\ntranspose a@DFT'{} = a\ntranspose a@F{} = a\ntranspose a@F'{} = a\ntranspose a = T a\n\n-- | Inverse of an SPL expression\ninverse :: forall a . (Eq a, Fractional a) => SPL a -> SPL a\ninverse a@I{} = a\ninverse (T a) = T (inverse a)\ninverse (Inv a) = a\ninverse (Pi p) = backpermute p\ninverse (Rot alpha) = Rot (-alpha)\ninverse (Diag xs) = Diag (fmap (1/) xs)\ninverse (KDiag n k) = KDiag n (1/k)\ninverse (Kron a b) = Kron (inverse a) (inverse b)\ninverse (Prod a b) = Prod (inverse b) (inverse a)\ninverse (Re a) = Re (inverse a)\ninverse F2 = F2\ninverse (DFT n) = DFT' n\ninverse (DFT' n) = DFT n\ninverse (F n w) = F' n w\ninverse (F' n w) = F n w\ninverse a = Inv a\n\n-- | Compute the product, @A x@.\nmXv :: forall r a .\n ( Num a\n , IArray r DIM1 a\n )\n => SPL a -- ^ The SPL transform, @A@\n -> Vector r a -- ^ The vector, @x@\n -> Vector D a\nmXv I{} x =\n A.delay x\n\nmXv (Pi p) x =\n A.fromFunction (ix1 n) f\n where\n Z :. n = A.extent x\n\n f (Z :. i) = x A.! reindex i\n where\n reindex = toIdxMapping (invert p)\n\nmXv (Diag d) x =\n A.fromVector d A..* x\n\nmXv (KDiag n k) x =\n A.fromFunction (ix1 n) f\n where\n f (Z :. i) = k * x A.! i\n\nmXv (Kron (I m) a) x =\n A.delay $\n A.concat [a #> A.slice (i*n') 1 n' x | i <- [0..m-1]]\n where\n Z :. _n :. n' = extent a\n\nmXv (Kron a (I n)) x =\n permute (L (m*n) m) #> Kron (I n) a #> permute (L (m'*n) n) #> x\n where\n Z :. m :. m' = extent a\n\nmXv (Kron a b) x =\n (I m ⊗ b) #> (a ⊗ I n') #> x\n where\n Z :. m :. _ = extent a\n Z :. _ :. n' = extent b\n\nmXv (DSum a b) x =\n A.delay $\n (a #> A.slice 0 1 m x) A.++ (b #> A.slice m 1 n x)\n where\n Z :. _ :. m = extent a\n Z :. _ :. n = extent b\n\nmXv (Prod a b) x =\n a #> b #> x\n\nmXv a x =\n toMatrix a `A.mXv` x\n\n-- | Compute the matrix-vector product, @A x@.\ninfixr 8 #>\n(#>) :: forall r a .\n ( Num a\n , IArray r DIM1 a\n )\n => SPL a\n -> Vector r a\n -> Vector D a\n(#>) = mXv\n\n-- | Convert an SPL transform to an explicit matrix.\ntoMatrix :: forall e . Num e => SPL e -> Matrix M e\ntoMatrix (E a) =\n manifest (unShowArray a)\n\ntoMatrix (T e) = manifest $ A.transpose $ toMatrix e\n\ntoMatrix (Inv e) =\n case A.inverse $ toMatrix e of\n Nothing -> error \"Matrix has no inverse\"\n Just a -> A.manifest a\n\ntoMatrix (Diag xs) =\n manifest $ A.fromFunction (ix2 n n) f\n where\n n = length xs\n\n f (Z :. i :. j) | i == j = xs V.! i\n | otherwise = 0\n\ntoMatrix (KDiag n e) =\n manifest $ A.fromFunction (ix2 n n) f\n where\n f (Z :. i :. j) | i == j = e\n | otherwise = 0\n\ntoMatrix (Above a b) =\n A.manifest $ toMatrix a A.<-> toMatrix b\n\ntoMatrix (Beside a b) =\n A.manifest $ toMatrix a A.<|> toMatrix b\n\ntoMatrix (Kron a b) =\n A.manifest $ A.kronecker (toMatrix a) (toMatrix b)\n\ntoMatrix (DSum a b) =\n A.manifest $ A.directSum (toMatrix a) (toMatrix b)\n\ntoMatrix (Prod a b) =\n A.manifest $ A.mXm (toMatrix a) (toMatrix b)\n\ntoMatrix (Circ xs) =\n manifest $ A.fromFunction (ix2 n n) f\n where\n n = length xs\n\n f (Z :. i :. j) = xs V.! ((i-j) `mod` n)\n\ntoMatrix (Skew xs) =\n manifest $ A.fromFunction (ix2 n n) f\n where\n n = length xs\n\n f (Z :. i :. j) = xs V.! ((i+j) `mod` n)\n\ntoMatrix (Toep xs) =\n manifest $ A.fromFunction (ix2 n n) f\n where\n n = (length xs + 1) `quot` 2\n\n f (Z :. i :. j) = xs V.! (i-j+n-1)\n\ntoMatrix (I n) =\n manifest $ A.fromFunction (ix2 n n) f\n where\n f (Z :. i :. j) | i == j = 1\n | otherwise = 0\n\ntoMatrix (Rot alpha) =\n A.matrix [[cos alpha, -(sin alpha)],\n [sin alpha, cos alpha]]\n\ntoMatrix (Pi p) =\n manifest $ A.fromFunction (ix2 (dim p) (dim p)) f\n where\n f (Z :. i :. j) | g j == i = 1\n | otherwise = 0\n\n g = toIdxMapping p\n\ntoMatrix (Re a) = manifest (RE (toMatrix a))\n\ntoMatrix F2 =\n A.matrix [[1, 1],\n [1, -1]]\n\ntoMatrix (DFT n) = toMatrix (F n (omega n))\ntoMatrix (DFT' n) = toMatrix (F' n (omega n))\n\ntoMatrix (F n w) = manifest $ A.fromFunction (ix2 n n) f\n where\n f (Z :. i :. j) = w ^ (i*j)\n\ntoMatrix (F' n w) = toMatrix (KDiag n (1/fromIntegral n) × F n (1/w))\n\npprArgs :: Pretty a => [a] -> Doc\npprArgs = parens . commasep . map ppr\n\ninstance (Num e, Pretty e) => Pretty (SPL e) where\n pprPrec p (E a) = pprPrec p (manifest (unShowArray a))\n pprPrec _ (I n) = text \"I_\" <> ppr n\n pprPrec _ (T e) = pprPrec 10 e <> text \"^T\"\n pprPrec _ (Inv e) = pprPrec 10 e <> text \"^-1\"\n pprPrec _ (Pi p) = ppr p\n pprPrec _ (Rot alpha) = text \"R_\" <> ppr alpha\n pprPrec _ (Diag xs) = text \"diag\" <> pprArgs (V.toList xs)\n pprPrec _ (KDiag n e) = text \"kdiag\" <> parens (commasep [ppr n, ppr e])\n pprPrec p (Above a b) = infixop p AboveOp a b\n pprPrec p (Beside a b) = infixop p BesideOp a b\n pprPrec p (Kron a b) = infixop p KOp a b\n pprPrec p (DSum a b) = infixop p DSOp a b\n pprPrec p (Prod a b) = infixop p POp a b\n pprPrec _ (Circ xs) = text \"circ\" <> pprArgs (V.toList xs)\n pprPrec _ (Skew xs) = text \"skew\" <> pprArgs (V.toList xs)\n pprPrec _ (Toep xs) = text \"toep\" <> pprArgs (V.toList xs)\n pprPrec _ (Re a) = text \"Re\" <> parens (ppr a)\n pprPrec _ F2 = text \"F_2\"\n pprPrec _ (DFT n) = text \"DFT_\" <> ppr n\n pprPrec _ (DFT' n) = text \"DFT'_\" <> ppr n\n pprPrec _ (F n w) = text \"F_\" <> ppr n <> parens (ppr w)\n pprPrec _ (F' n w) = text \"F'_\" <> ppr n <> parens (ppr w)\n\ndata MatrixBinop = AboveOp\n | BesideOp\n | KOp\n | DSOp\n | POp\n deriving (Eq, Ord, Show)\n\ninstance HasFixity MatrixBinop where\n fixity AboveOp = infixl_ 7\n fixity BesideOp = infixl_ 7\n fixity KOp = infixl_ 7\n fixity DSOp = infixl_ 6\n fixity POp = infixl_ 7\n\ninstance Pretty MatrixBinop where\n ppr AboveOp = text \"<->\"\n ppr BesideOp = text \"<|>\"\n ppr KOp = char '⊗'\n ppr DSOp = char '⊕'\n ppr POp = char '×'\n\n-- | Extract a row of a matrix\nrow :: Matrix M e -> Int -> V.Vector e\nrow e i = V.slice (i*n) n xs\n where\n M (Z :. _m :. n) xs = manifest e\n\n-- | Extract a column of a matrix\ncol :: forall e . Matrix M e -> Int -> V.Vector e\ncol e j = V.generate m f\n where\n M (Z :. m :. n) xs = manifest e\n\n f :: Int -> e\n f i = xs V.! (i*n + j)\n\n-- | Vertical stacking of transforms\ninfixr 7 <->\n(<->) :: SPL e -> SPL e -> SPL e\n(<->) = Above\n\n-- | Horizontal stacking of transforms\ninfixr 7 <|>\n(<|>) :: SPL e -> SPL e -> SPL e\n(<|>) = Beside\n\n-- | Create a block matrix\nblock :: SPL e -> SPL e -> SPL e -> SPL e -> SPL e\nblock tl tr bl br = (tl <|> tr) <-> (bl <|> br)\n\n-- | Alias for Kronecker product.\ninfixl 7 ⊗\n(⊗) :: SPL e -> SPL e -> SPL e\nI m ⊗ (Kron (I n) y) = I (m*n) ⊗ y\nI 1 ⊗ y = y\nx ⊗ I 1 = x\nx ⊗ y = Kron x y\n\n-- | Alias for matrix direct sum.\ninfixl 6 ⊕\n(⊕) :: SPL e -> SPL e -> SPL e\nI m ⊕ I n = I (n + m)\nDiag xs ⊕ Diag ys = Diag (xs <> ys)\nx ⊕ y = DSum x y\n\n-- | Alias for matrix product.\ninfixl 7 ×\n(×) :: SPL e -> SPL e -> SPL e\n(×) = Prod\n", "meta": {"hexsha": "1f408b70d753c043bcab4604807d0f2655ce1c32", "size": 14266, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Spiral/SPL.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/SPL.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/SPL.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": 24.8970331588, "max_line_length": 77, "alphanum_fraction": 0.540515912, "num_tokens": 4907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5163480092815377}} {"text": "#!/usr/bin/env stack\n-- stack --install-ghc runghc --resolver lts-11.9 --package backprop-0.2.2.0 --package random --package hmatrix-backprop-0.1.2.1 --package statistics --package lens --package one-liner-instances --package split --package ghc-typelits-natnormalise --package ghc-typelits-knownnat --package hmatrix --package hmatrix-vector-sized --package microlens --package vector-sized --package transformers --package type-combinators -- -O2\n\n-- | Replace the second line with this one to have \"./model.hs\" open a ghci session\n-- stack --install-ghc ghci --resolver lts-11.9 --package backprop-0.2.2.0 --package random --package hmatrix-backprop-0.1.2.1 --package statistics --package lens --package one-liner-instances --package split --package ghc-typelits-natnormalise --package ghc-typelits-knownnat --package hmatrix --package hmatrix-vector-sized --package microlens --package vector-sized --package transformers --package type-combinators\n\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeInType #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n{-# OPTIONS_GHC -fwarn-redundant-constraints #-}\n\nimport Control.Monad.Trans.State\nimport Data.Bifunctor\nimport Data.Foldable\nimport Data.List\nimport Data.List.Split\nimport Data.Tuple\nimport Data.Type.Option\nimport GHC.Generics (Generic)\nimport GHC.TypeNats\nimport Lens.Micro hiding ((&))\nimport Numeric.Backprop\nimport Numeric.LinearAlgebra.Static.Backprop\nimport Numeric.LinearAlgebra.Static.Vector\nimport Numeric.OneLiner\nimport System.Random\nimport qualified Data.Vector.Storable.Sized as SVS\nimport qualified Numeric.LinearAlgebra as HU\nimport qualified Numeric.LinearAlgebra.Static as H\nimport qualified Prelude.Backprop as B\n\ndata a :& b = !a :& !b\n deriving (Show, Generic)\ninfixr 2 :&\n\ntype Model p a b = forall z. Reifies z W\n => BVar z p\n -> BVar z a\n -> BVar z b\n\nlinReg :: Model (Double :& Double) Double Double\nlinReg (a :&& b) x = b * x + a\n\nsquaredErrorGrad\n :: (Backprop p, Backprop b, Num b)\n => Model p a b -- ^ Model\n -> a -- ^ Observed input\n -> b -- ^ Observed output\n -> p -- ^ Parameter guess\n -> p -- ^ Gradient\nsquaredErrorGrad f x targ = gradBP $ \\p ->\n (f p (auto x) - auto targ) ^ 2\n\ntrainModel\n :: (Fractional p, Backprop p, Num b, Backprop b)\n => Model p a b -- ^ model to train\n -> p -- ^ initial parameter guess\n -> [(a,b)] -- ^ list of observations\n -> p -- ^ updated parameter guess\ntrainModel f = foldl' $ \\p (x,y) -> p - 0.1 * squaredErrorGrad f x y p\n\ntrainModelIO\n :: (Fractional p, Backprop p, Num b, Backprop b, Random p)\n => Model p a b -- ^ model to train\n -> [(a,b)] -- ^ list of observations\n -> IO p -- ^ parameter guess\ntrainModelIO m xs = do\n p0 <- (/ 10) . subtract 0.5 <$> randomIO\n return $ trainModel m p0 xs\n\ntestTrainLinReg :: IO (Double :& Double)\ntestTrainLinReg = trainModelIO linReg (concat (replicate 1000 samps))\n where\n samps = [(1,1),(2,3),(3,5),(4,7),(5,9)]\n\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n\nfeedForward\n :: (KnownNat i, KnownNat o)\n => Model (L o i :& R o) (R i) (R o)\nfeedForward (w :&& b) x = w #> x + b\n\nfeedForwardLog\n :: (KnownNat i, KnownNat o)\n => Model (L o i :& R o) (R i) (R o)\nfeedForwardLog (w :&& b) x = logistic (w #> x + b)\n\ntestTrainPerceptron :: IO [R 1]\ntestTrainPerceptron = do\n trained <- trainModelIO feedForwardLog $ take 10000 (cycle samps)\n print trained\n return [ evalBP2 feedForwardLog trained r | (r, _) <- samps ]\n where\n samps = [ (H.vec2 0 0, 0)\n , (H.vec2 1 0, 0)\n , (H.vec2 0 1, 0)\n , (H.vec2 1 1, 1)\n ]\n\nlogReg :: Model (Double :& Double) Double Double\nlogReg ab = logistic . linReg ab\n\nfeedForwardLog'\n :: (KnownNat i, KnownNat o)\n => Model (L o i :& R o) (R i) (R o)\nfeedForwardLog' wb = logistic . feedForward wb\n\nsoftMax :: (Reifies z W, KnownNat n) => BVar z (R n) -> BVar z (R n)\nsoftMax x = konst (1 / sumElements expx) * expx\n where\n expx = exp x\n\nfeedForwardSoftMax\n :: (KnownNat i, KnownNat o)\n => Model (L o i :& R o) (R i) (R o)\nfeedForwardSoftMax wb = softMax . feedForward wb\n\n(<~)\n :: (Backprop p, Backprop q)\n => Model p b c\n -> Model q a b\n -> Model (p :& q) a c\n(f <~ g) (p :&& q) = f p . g q\ninfixr 8 <~\n\ntestTrainTwoLayer :: IO [R 1]\ntestTrainTwoLayer = do\n trained <- trainModelIO model (take 10000 (cycle samps))\n print trained\n return [ evalBP2 model trained r | (r, _) <- samps ]\n where\n model :: Model _ (R 2) (R 1)\n model = feedForwardLog' @4 @1 <~ feedForwardLog' @2 @4\n samps = [ (H.vec2 0 0, 0)\n , (H.vec2 1 0, 1)\n , (H.vec2 0 1, 1)\n , (H.vec2 1 1, 0)\n ]\n\ntype ModelS p s a b = forall z. Reifies z W\n => BVar z p\n -> BVar z a\n -> BVar z s\n -> (BVar z b, BVar z s)\n\nar2 :: ModelS (Double :& (Double :& Double)) Double Double Double\nar2 (c :&& (φ1 :&& φ2)) yLast yLastLast =\n ( c + φ1 * yLast + φ2 * yLastLast, yLast )\n\nfcrnn\n :: (KnownNat i, KnownNat o)\n => ModelS ((L o i :& L o o) :& R o) (R o) (R i) (R o)\nfcrnn ((wX :&& wS) :&& b) x s = ( y, logistic y )\n where\n y = (wX #> x) + (wS #> s) + b\n\n(<*~*)\n :: (Backprop p, Backprop q, Backprop s, Backprop t)\n => ModelS p s b c\n -> ModelS q t a b\n -> ModelS (p :& q) (s :& t) a c\n(f <*~* g) (p :&& q) x (s :&& t) = (z, s' :&& t')\n where\n (y, t') = g q x t\n (z, s') = f p y s\ninfixr 8 <*~*\n\nmapS\n :: (forall z. Reifies z W => BVar z b -> BVar z c)\n -> ModelS p s a b\n -> ModelS p s a c\nmapS f g p x = first f . g p x\n\ntoS :: Model p a b\n -> ModelS p s a b\ntoS f p x s = (f p x, s)\n\n(<*~)\n :: (Backprop p, Backprop q)\n => Model p b c\n -> ModelS q s a b\n -> ModelS (p :& q) s a c\n(f <*~ g) (p :&& q) x = first (f p) . g q x\ninfixr 8 <*~\n\nunroll\n :: (Backprop a, Backprop b)\n => ModelS p s a b\n -> ModelS p s [a] [b]\nunroll f p xs s0 = swap $ B.mapAccumL f' s0 xs\n where\n -- we have to re-arrange the order of arguments and tuple a bit to\n -- match what `mapAccumL` expects\n f' s x = swap (f p x s)\n\nunrollLast\n :: (Backprop a, Backprop b)\n => ModelS p s a b\n -> ModelS p s [a] b\nunrollLast f = mapS (last . sequenceVar) (unroll f)\n\nunrollLast'\n :: Backprop a\n => ModelS p s a b\n -> ModelS p s [a] b\nunrollLast' f p xs s0 = foldl' go (undefined, s0) (sequenceVar xs)\n where\n go (_, s) x = f p x s\n\n\nfixState\n :: s\n -> ModelS p s a b\n -> Model p a b\nfixState s0 f p x = fst $ f p x (auto s0)\n\nzeroState\n :: Num s\n => ModelS p s a b\n -> Model p a b\nzeroState = fixState 0\n\ntrainState\n :: (Backprop p, Backprop s)\n => ModelS p s a b\n -> Model (p :& s) a b\ntrainState f (p :&& s) x = fst $ f p x s\n\nprime\n :: Foldable t\n => ModelS p s a b -- ^ model\n -> p -- ^ parameterization\n -> s -- ^ initial state\n -> t a -- ^ priming input\n -> s -- ^ primed state\nprime f p = foldl' $ evalBP2 (\\s x -> snd $ f (auto p) x s)\n\nfeedback\n :: (Backprop a, Backprop s)\n => ModelS p s a a -- ^ model\n -> p -- ^ parameterization\n -> s -- ^ initial state\n -> a -- ^ initial input\n -> [a] -- ^ inifinite feedback loop\nfeedback f p s0 x0 = unfoldr go (x0, s0)\n where\n go (x, s) = Just (x, (y, s'))\n where\n -- 'T2' tuples up a pair of 'BVar's into a 'BVar' of a tuple\n (y, s') = evalBP (uncurry T2 . f (auto p) (auto x)) s\n\ntestAR2 :: IO [Double]\ntestAR2 = do\n trained <- trainModelIO model $ take 10000 samps\n let primed = prime model0 trained 0 (take 19 series)\n output = feedback model0 trained primed (series !! 19)\n print trained\n return $ take 200 output\n where\n -- sine wave with period 25\n series :: [Double]\n series = [ sin (2 * pi * t / 25) | t <- [0..] ]\n samps = [ (init c, last c) | c <- chunksOf 19 series ]\n model0 :: ModelS _ _ Double Double\n model0 = ar2\n model :: Model _ [Double] Double\n model = zeroState $ unrollLast model0\n\ntestRNN :: IO [R 1]\ntestRNN = do\n trained <- trainModelIO model $ take 100000 samps\n let primed = prime model0 trained 0 (take 19 series)\n output = feedback model0 trained primed (series !! 19)\n return $ take 200 output\n where\n -- sine wave with period 25\n series :: [H.R 1]\n series = [ H.konst (sin (2 * pi * t / 25)) | t <- [0..] ]\n samps = [ (init c, last c) | c <- chunksOf 19 series ]\n model0 :: ModelS _ _ (R 1) (R 1)\n model0 = feedForward @30 @1\n <*~ mapS logistic (fcrnn @1 @30)\n model :: Model _ [R 1] (R 1)\n model = zeroState $ unrollLast model0\n\nrecurrently\n :: (Backprop a, Backprop b)\n => Model p (a :& b) b\n -> ModelS p b a b\nrecurrently f p x yLast = (y, y)\n where\n y = f p (x :&& yLast)\n\nrecurrentlyWith\n :: (Backprop a, Backprop b)\n => (forall z. Reifies z W => BVar z c -> BVar z b)\n -> Model p (a :& b) c\n -> ModelS p b a c\nrecurrentlyWith store f p x yLast = (y, store y)\n where\n y = f p (x :&& yLast)\n\nffOnSplit\n :: forall i o. (KnownNat i, KnownNat o)\n => Model _ (R i :& R o) (R o)\nffOnSplit p (rI :&& rO) = feedForward p (rI # rO)\n\nfcrnn'\n :: (KnownNat i, KnownNat o)\n => ModelS _ (R o) (R i) (R o)\nfcrnn' = recurrentlyWith logistic (\\p -> feedForward p . uncurryT (#))\n\nlagged\n :: (KnownNat n, 1 <= n)\n => Model p (R (n + 1)) b\n -> ModelS p (R n) Double b\nlagged f p x xLasts = (y, xLasts')\n where\n fullLasts = xLasts & x\n y = f p fullLasts\n (_, xLasts') = headTail fullLasts\n\nar :: (KnownNat n, 1 <= n)\n => ModelS _ (R n) Double Double\nar = lagged (\\p -> fst . headTail . feedForward @_ @1 p)\n\nar2' :: ModelS _ (R 2) Double Double\nar2' = ar @2\n\nmain :: IO ()\nmain = do\n putStrLn \"Linear regression\"\n print =<< testTrainLinReg\n\n putStrLn \"Single layer perceptron learning AND\"\n mapM_ print =<< testTrainPerceptron\n\n putStrLn \"Two-layer ANN learning XOR\"\n mapM_ print =<< testTrainTwoLayer\n\n putStrLn \"Sine (AR2)\"\n ar2Test <- testAR2\n mapM_ print (take 30 ar2Test)\n writeFile \"ar2sin.dat\" $ unlines (show <$> ar2Test)\n\n putStrLn \"Sine (RNN)\"\n rnnTest <- testRNN\n mapM_ print (take 30 rnnTest)\n writeFile \"rnnsin.dat\" $ unlines (show . HU.sumElements . H.extract <$> rnnTest)\n\npattern (:&&) :: (Backprop a, Backprop b, Reifies z W)\n => BVar z a -> BVar z b -> BVar z (a :& b)\npattern x :&& y <- (\\xy -> (xy ^^. t1, xy ^^. t2)->(x, y))\n where\n (:&&) = isoVar2 (:&) (\\case x :& y -> (x, y))\n{-# COMPLETE (:&&) #-}\n\nt1 :: Lens (a :& b) (a' :& b) a a'\nt1 f (x :& y) = (:& y) <$> f x\n\nt2 :: Lens (a :& b) (a :& b') b b'\nt2 f (x :& y) = (x :&) <$> f y\n\ninstance (Num a, Num b) => Num (a :& b) where\n (+) = gPlus\n (-) = gMinus\n (*) = gTimes\n negate = gNegate\n abs = gAbs\n signum = gSignum\n fromInteger = gFromInteger\n\ninstance (Fractional a, Fractional b) => Fractional (a :& b) where\n (/) = gDivide\n recip = gRecip\n fromRational = gFromRational\n\ninstance (Random a, Random b) => Random (a :& b) where\n random g0 = (x :& y, g2)\n where\n (x, g1) = random g0\n (y, g2) = random g1\n randomR (x0 :& y0, x1 :& y1) g0 = (x :& y, g2)\n where\n (x, g1) = randomR (x0, x1) g0\n (y, g2) = randomR (y0, y1) g1\n\ninstance (Backprop a, Backprop b) => Backprop (a :& b)\n\nuncurryT\n :: (Backprop a, Backprop b, Reifies z W)\n => (BVar z a -> BVar z b -> BVar z c)\n -> BVar z (a :& b)\n -> BVar z c\nuncurryT f x = f (x ^^. t1) (x ^^. t2)\n\ninstance (KnownNat n, KnownNat m) => Random (L n m) where\n random = runState . fmap vecL $ SVS.replicateM (state random)\n randomR (xs,ys) = runState . fmap vecL $ SVS.zipWithM (curry (state . randomR))\n (lVec xs) (lVec ys)\n\ninstance (KnownNat n) => Random (R n) where\n random = runState $ vecR <$> SVS.replicateM (state random)\n randomR (xs,ys) = runState . fmap vecR $ SVS.zipWithM (curry (state . randomR))\n (rVec xs) (rVec ys)\n\n", "meta": {"hexsha": "45e98d2c2450b851014497894b3f777abb8a8f8d", "size": 13761, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "code-samples/functional-models/model.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/functional-models/model.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/functional-models/model.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": 32.4551886792, "max_line_length": 427, "alphanum_fraction": 0.5312840637, "num_tokens": 4493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126791, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.516348000966894}} {"text": "import Data.Complex\nimport Data.Either\nimport Data.Maybe\n--import System.Random\nimport Text.Read\n\nmain = do\n putStrLn \"Compiled.\"\n center defaultGD [\"0\", \"0\"]\n\n--Datatypes/typeclasses/etc.\n\ndata Vector2 = V2 Double Double deriving (Show, Read, Eq)\n\ndata Transformation = Transformation Matrix Vector2 deriving (Show, Read, Eq)\n\ndata GlobalData = GD\n { getWindowSize :: (Int, Int),\n getTickSizes :: (Double, Double),\n getPlotLoc :: (Vector2, Vector2),\n getIters :: Int,\n getAxesShown :: Bool,\n getVectToChar :: VectToChar\n }\n\ntype Matrix = (Double, Double, Double, Double)\n\ntype Args = [String]\n\ntype StrCommand = String\n\ntype ArgDescription = String\n\ntype CmdDescription = String\n\ntype Command = GlobalData -> Args -> IO ()\n\ntype PlotCommand = GlobalData -> Args -> Either (IO ()) VectToChar\n\ntype VectToChar = GlobalData -> Vector2 -> Char\n\n--Constants\n\ndefaultGD :: GlobalData\ndefaultGD = GD (100, 30) (1.0, 1.0) (V2 (-1.5) (-1), V2 1.5 1) 50 True vtcMBSet\n\ncharWidth :: Double\ncharWidth = 0.3\n\ncursorChar = 'o'\n\noriginChar = '+'\n\nhAxisMinChar = '<'\n\nhAxisMaxChar = '>'\n\nhAxisChar = '-'\n\nhAxisTickChar = '|'\n\nvAxisMinChar = 'V'\n\nvAxisMaxChar = '^'\n\nvAxisChar = '|'\n\nvAxisTickChar = '~'\n\nmaxShadeChar = '#'\n\nminShadeChar = ' '\n\nvBounderyChar = '|'\n\nhBounderyChar = '~'\n\nshadeChars :: [Char]\nshadeChars = \" `.*+&$@#\"\n\ncommandList :: [(StrCommand, (Command, ArgDescription, CmdDescription))]\ncommandList =\n [ (\"draw\", (draw, \"draw\", \"Redraws the plot to the screen.\")),\n (\"plot\", (plot, \"plot (args)\", \"Sets the function defining which points to plot.\\nPossible arguments:\\n\" ++ show (map (sndTriple . snd) plotList))),\n ( \"zoom\",\n ( zoom,\n \"zoom [Double c]\",\n \"Zooms in by the specified factor.\"\n ++ \"Requires c > 0. Omitting arguments sets zoom level.\"\n )\n ),\n (\"shift\", (shift, \"shift (Double dx) (Double dy)\", \"Translates the plot by the specified amount.\")),\n (\"center\", (center, \"center (Double x) (Double y)\", \"Centers the plot on the point (x,y). Defaults to the origin.\")),\n ( \"resize\",\n ( resize,\n \"resize (Int width) (Int height)\",\n \"Resizes the window. Omitting arguments defaults to 100x30.\"\n ++ \"\\nRequires width, height > 0. Tag -square ignores second argument and calculates height based on given width.\"\n )\n ),\n (\"toggleAxes\", (toggleAxes, \"toggleAxes\", \"Toggles the visibility of the axes.\")),\n ( \"cutoff\",\n ( cutoff,\n \"cutoff (Int n)\",\n \"Sets the cutoff point for iterations. Generally, a higher cutoff point means greater precision.\\n\"\n ++ \"Requires n > 0. Omitting arguments defaults to 50.\"\n )\n ),\n (\"reload\", (reload, \"reload\", \"Restores all data (center, scale factor, etc.) to their default values.\")),\n (\"info\", (info, \"info\", \"Prints information about the current plot.\")),\n (\"quit\", (quit, \"quit\", \"Ends execution. Current data will be lost.\")),\n (\"help\", (help, \"help [command]\", \"Prints a description of the specified command and its arguments. Omitting the arguments lists available commands.\"))\n ]\n\nplotList :: [(StrCommand, (PlotCommand, ArgDescription, CmdDescription))]\nplotList =\n [ (\"mandelbrot\", (plotMBSet, \"plot mandelbrot\", \"Plots the Mandelbrot set over the complex plane.\\nTag -shade adds shading based on time to diverge.\")),\n (\"sierpinski\", (plotSierpinski, \"plot sierpinski\", \"Work in progress. Plots the Sierpinski triangle within the unit square, calculated as an iterated function system.\\n\")),\n ( \"juliaset\",\n ( plotJuliaSet,\n \"plot juliaset (Complex c)\",\n \"Given a complex value (using a:+b notation), plots the filled julia set of z^2+c over the complex plane.\\n\"\n ++ \"Omitting arguments defaults to 0:+0. Tag -shade adds shading based on time to diverge.\\n\"\n )\n )\n ]\n\n--Triple commands\n\nfstTriple (x, _, _) = x\n\nsndTriple (_, y, _) = y\n\nthrdTriple (_, _, z) = z\n\n--IO commands\n\ngetCommand :: Command\ngetCommand gd _ = do\n putStr \"\\nMBSet>> \"\n line <- getLine\n if line == \"\"\n then do getCommand gd []\n else do\n let (strCmd : args) = words line\n let mCommand = lookup strCmd commandList\n case mCommand of\n Nothing -> rejectCommand gd [strCmd]\n Just (command, argDesc, cmdDesc) -> command gd args\n return ()\n\nrejectCommand :: Command\nrejectCommand gd [strCmd] = do\n putStrLn $ \"No such command: \" ++ strCmd\n putStrLn \"Use the command \\\"help\\\" to see a list of available commands.\"\n getCommand gd []\nrejectCommand gd args = do\n putStrLn \"No such command.\\nUse the command \\\"help\\\" to see a list of available commands.\"\n getCommand gd []\n\nrejectArgs :: Command\nrejectArgs gd args = do\n putStrLn $ \"Invalid arguments: \" ++ unwords args ++ \"\\nUse the command \\\"help [command]\\\" for command syntax.\"\n getCommand gd []\n\n--Input Commands\n\ndraw :: Command\ndraw gd _ = do\n putStr . unlines . asciiArray $ gd\n getCommand gd []\n\nplot :: Command\nplot gd args@(strPlot : args') = do\n let mPlotTriple = lookup strPlot plotList\n if isNothing mPlotTriple\n then do\n rejectArgs gd args\n else do\n let Just (plotCmd, _, _) = mPlotTriple\n if isLeft $ plotCmd gd args'\n then do\n let Left failureAction = plotCmd gd args\n failureAction ---------\n else do\n let Right command = plotCmd gd args'\n draw (setVectToChar gd command) [\"\"]\nplot gd args = help gd $ \"plot\" : args\n\nzoom :: Command\nzoom gd [] = draw (setPlotLoc gd $ getPlotLoc defaultGD) []\nzoom gd args\n | head args == \"in\" = zoom gd $ \"2\" : tail args\n | head args == \"out\" = zoom gd $ \"0.5\" : tail args\n | otherwise = do\n let mDouble = readMaybe (head args) :: Maybe Double\n case mDouble of\n Nothing -> rejectArgs gd args\n Just x ->\n if x <= 0\n then rejectArgs gd args\n else draw (zoomGD gd x) $ tail args\n return ()\n\nshift :: Command\nshift gd@GD {getPlotLoc = (v1, v2)} args@(dxStr : dyStr : args')\n | isNothing (readMaybe dxStr :: Maybe Double) = rejectArgs gd args\n | isNothing (readMaybe dyStr :: Maybe Double) = rejectArgs gd args\n | otherwise = draw (setPlotLoc gd (v1 `vPlus` d, v2 `vPlus` d)) args'\n where\n d = V2 (read dxStr :: Double) (read dyStr :: Double)\nshift gd args = rejectArgs gd args\n\ncenter :: Command\ncenter gd [] = center gd [\"0\", \"0\"]\ncenter gd@GD {getPlotLoc = (v1, v2)} args@(xStr : yStr : args')\n | isNothing (readMaybe xStr :: Maybe Double) = rejectArgs gd args\n | isNothing (readMaybe yStr :: Maybe Double) = rejectArgs gd args\n | otherwise = shift gd $ [show dx, show dy] ++ args'\n where\n (V2 dx dy) = newCenter `vMinus` currentCenter\n currentCenter = midPt v1 v2\n newCenter = V2 (read xStr :: Double) (read yStr :: Double)\ncenter gd args = rejectArgs gd args\n\nresize :: Command\nresize gd [] = draw (setWindowSize gd $ getWindowSize defaultGD) []\nresize gd args@(wStr : hStr : args')\n | isNothing (readMaybe wStr :: Maybe Int) = rejectArgs gd args\n | width <= 0 = rejectArgs gd args\n | \"square\" `elem` args = resize gd sqrArgs\n | isNothing (readMaybe hStr :: Maybe Int) = rejectArgs gd args\n | height <= 0 = rejectArgs gd args\n | otherwise = draw (setWindowSize gd (width, height)) args'\n where\n width = read wStr :: Int\n height = read hStr :: Int\n sqrHeight = round . (* charWidth) . fromIntegral $ width\n sqrArgs = wStr : show sqrHeight : filter (/= \"square\") args'\nresize gd args = rejectArgs gd args\n\ncutoff :: Command\ncutoff gd [] = draw (setIters gd $ getIters defaultGD) []\ncutoff gd args@(strIters : args')\n | isNothing (readMaybe strIters :: Maybe Int) = rejectArgs gd args\n | iters <= 0 = rejectArgs gd args\n | otherwise = draw (setIters gd iters) args'\n where\n iters = read strIters :: Int\n\ntoggleAxes :: Command\ntoggleAxes gd@GD {getAxesShown = axesShown} = draw (setAxesShown gd (not axesShown))\n\nreload :: Command\nreload _ = draw defaultGD\n\ninfo :: Command\ninfo gd args = do\n putStrLn \"\\n -- Current plot information --\"\n putStrLn $ \"Window size: \" ++ (show . fst . getWindowSize $ gd) ++ \"x\" ++ (show . snd . getWindowSize $ gd)\n let (xMin, yMin) = (getX . fst . getPlotLoc $ gd, getY . fst . getPlotLoc $ gd)\n let (xMax, yMax) = (getX . snd . getPlotLoc $ gd, getY . snd . getPlotLoc $ gd)\n putStrLn $ \"Plot location (bounds): \" ++ show xMin ++ \" < x < \" ++ show xMax ++ \", \" ++ show yMin ++ \" < y < \" ++ show yMax\n putStrLn $ \"Cutoff point (number of iterations): \" ++ show (getIters gd)\n putStrLn $ \"Axes shown: \" ++ show (getAxesShown gd)\n getCommand gd []\n\nquit :: Command\nquit gd args = do\n putStrLn \"Quitting.\\n\\n\"\n return ()\n\nhelp :: Command\nhelp gd (\"plot\" : strPlot : args) = do\n let output = case lookup strPlot plotList of\n Just (f, argDesc, cmdDesc) -> argDesc ++ \" -- \" ++ cmdDesc\n Nothing -> \"No such plot: \" ++ strPlot\n putStrLn output\n getCommand gd []\nhelp gd [] = do\n putStrLn \"Available commands: \"\n print $ map fst commandList\n getCommand gd []\nhelp gd args = do\n let strCmd = head args\n let output = case lookup strCmd commandList of\n Just (f, argDesc, cmdDesc) -> argDesc ++ \" -- \" ++ cmdDesc\n Nothing -> \"No such command: \" ++ strCmd\n putStrLn output\n getCommand gd []\n\n--GlobalData functions\n\nsetWindowSize :: GlobalData -> (Int, Int) -> GlobalData\nsetWindowSize (GD _ tickSizes plotLoc iters axesShown vectToChar) windowSize = GD windowSize tickSizes plotLoc iters axesShown vectToChar\n\nsetTickSizes :: GlobalData -> (Double, Double) -> GlobalData\nsetTickSizes (GD windowSize _ plotLoc iters axesShown vectToChar) tickSizes = GD windowSize tickSizes plotLoc iters axesShown vectToChar\n\nsetPlotLoc :: GlobalData -> (Vector2, Vector2) -> GlobalData\nsetPlotLoc (GD windowSize tickSizes _ iters axesShown vectToChar) plotLoc = GD windowSize tickSizes plotLoc iters axesShown vectToChar\n\nsetIters :: GlobalData -> Int -> GlobalData\nsetIters (GD windowSize tickSizes plotLoc _ axesShown vectToChar) iters = GD windowSize tickSizes plotLoc iters axesShown vectToChar\n\nsetAxesShown :: GlobalData -> Bool -> GlobalData\nsetAxesShown (GD windowSize tickSizes plotLoc iters _ vectToChar) axesShown = GD windowSize tickSizes plotLoc iters axesShown vectToChar\n\nsetVectToChar :: GlobalData -> VectToChar -> GlobalData\nsetVectToChar (GD windowSize tickSizes plotLoc iters axesShown _) = GD windowSize tickSizes plotLoc iters axesShown\n\npxlW :: GlobalData -> Double\npxlW gd = (getX vMax - getX vMin) / fromIntegral screenWidth\n where\n (screenWidth, _) = getWindowSize gd\n (vMin, vMax) = getPlotLoc gd\n\npxlH :: GlobalData -> Double\npxlH gd = (getY vMax - getY vMin) / fromIntegral screenHeight\n where\n (_, screenHeight) = getWindowSize gd\n (vMin, vMax) = getPlotLoc gd\n\nzoomGD :: GlobalData -> Double -> GlobalData\nzoomGD gd@GD {getPlotLoc = (v1, v2)} c = setPlotLoc gd (v1', v2')\n where\n v1' = vPlus (midPt v1 v2) . vScale (1 / c) $ v1 `vMinus` midPt v1 v2\n v2' = vPlus (midPt v1 v2) . vScale (1 / c) $ v2 `vMinus` midPt v1 v2\n\n--Vector2 functions\n\ngetX :: Vector2 -> Double\ngetX (V2 x _) = x\n\ngetY :: Vector2 -> Double\ngetY (V2 _ y) = y\n\nmag :: Vector2 -> Double\nmag (V2 x y) = sqrt (x ^ 2 + y ^ 2)\n\nvPlus :: Vector2 -> Vector2 -> Vector2\nvPlus (V2 a b) (V2 x y) = V2 (a + x) (b + y)\n\nvMinus :: Vector2 -> Vector2 -> Vector2\nvMinus (V2 a b) (V2 x y) = V2 (a - x) (b - y)\n\nvScale :: Double -> Vector2 -> Vector2\nvScale c (V2 x y) = V2 (x * c) (y * c)\n\nmidPt :: Vector2 -> Vector2 -> Vector2\nmidPt v1 v2 = vScale 0.5 (v1 `vPlus` v2)\n\napplyTransformation :: Transformation -> Vector2 -> Vector2\napplyTransformation (Transformation (a11, a21, a12, a22) (V2 bx by)) v@(V2 x y) =\n V2 (a11 * x + a12 * y + bx) (a21 * x + a22 * y + by)\n\n-- Printing\n\nhRange :: GlobalData -> [Double]\nhRange gd = [xMin + i * dx | i <- [0 .. width]]\n where\n dx = (xMax - xMin) / width\n width = fromIntegral . fst . getWindowSize $ gd\n xMin = getX . fst . getPlotLoc $ gd\n xMax = getX . snd . getPlotLoc $ gd\n\nvectRow :: GlobalData -> Double -> [Vector2]\nvectRow gd y = map (`V2` y) $ hRange gd\n\nvRange :: GlobalData -> [Double]\nvRange gd = reverse [yMin + i * dy | i <- [0 .. height]]\n where\n dy = (yMax - yMin) / height\n height = fromIntegral . snd . getWindowSize $ gd\n yMin = getY . fst . getPlotLoc $ gd\n yMax = getY . snd . getPlotLoc $ gd\n\nvectArray :: GlobalData -> [[Vector2]]\nvectArray gd = map (vectRow gd) $ vRange gd\n\nasciiArray :: GlobalData -> [[Char]]\nasciiArray gd = addBoundery . map (map (vectToAscii gd)) $ vectArray gd\n\naddBoundery :: [[Char]] -> [[Char]]\naddBoundery array = [hBoundery] ++ addVBoundery array ++ [hBoundery]\n where\n hBoundery = minShadeChar : replicate (length . head $ array) hBounderyChar ++ [minShadeChar]\n addVBoundery array = map (\\row -> vBounderyChar : row ++ [vBounderyChar]) array\n\nvectToAscii :: GlobalData -> Vector2 -> Char\nvectToAscii gd v@(V2 x y)\n | onCursor = cursorChar\n | onXAxis && onYAxis = originChar\n -- x-axis\n | onXAxis && abs (x - xMin) <= pxlW gd / 2 = hAxisMinChar\n | onXAxis && abs (x - xMax) <= pxlW gd / 2 = hAxisMaxChar\n | onXTick = hAxisTickChar\n | onXAxis = hAxisChar\n -- y-axis\n | onYAxis && abs (y - yMin) <= pxlH gd / 2 = vAxisMinChar\n | onYAxis && abs (y - yMax) <= pxlH gd / 2 = vAxisMaxChar\n | onYTick = vAxisTickChar\n | onYAxis = vAxisChar\n | otherwise = getVectToChar gd gd v\n where\n (scrnW, scrnH) = getWindowSize gd\n (vMin, vMax) = getPlotLoc gd\n onXAxis = getAxesShown gd && abs y < pxlH gd / 2\n onYAxis = getAxesShown gd && abs x < pxlW gd / 2\n onXTick = onXAxis && abs (x - rndX) < pxlW gd / 2 --WIP\n onYTick = onYAxis && abs (y - rndY) < pxlH gd / 2 --WIP\n [rndX, rndY] = map (fromIntegral . round) [x, y] --WIP rewrite as nearest tick\n (xMin, yMin) = (getX vMin, getY vMin)\n (xMax, yMax) = (getX vMax, getY vMax)\n onCursor = mag (v `vMinus` midPt vMin vMax) <= pxlW gd / 2\n\n--Mandelbrot set\n\nplotMBSet :: PlotCommand\nplotMBSet gd args\n | \"-shade\" `elem` args = Right vtcMBSetShaded\n | otherwise = Right vtcMBSet\n\nvtcMBSet :: VectToChar\nvtcMBSet gd@GD {getIters = iters} (V2 x y)\n | isInSet = maxShadeChar\n | otherwise = minShadeChar\n where\n isInSet = all (\\z -> magnitude z < 2) . take iters $ mSequence c (0 :+ 0)\n c = x :+ y\n mSequence c z = z : mSequence c (mFunc c z)\n mFunc c z = z ^ 2 + c\n\nvtcMBSetShaded :: VectToChar\nvtcMBSetShaded gd@GD {getIters = maxIters} (V2 x y)\n | itersToEscape >= maxIters = maxShadeChar\n | itersToEscape >= (49 * maxIters) `div` 8 = shadeChars !! 7\n | itersToEscape >= (36 * maxIters) `div` 8 = shadeChars !! 6\n | itersToEscape >= (25 * maxIters) `div` 8 = shadeChars !! 5\n | itersToEscape >= (16 * maxIters) `div` 8 = shadeChars !! 4\n | itersToEscape >= (9 * maxIters) `div` 8 = shadeChars !! 3\n | itersToEscape >= (4 * maxIters) `div` 8 = shadeChars !! 2\n | itersToEscape >= (1 * maxIters) `div` 8 = shadeChars !! 1\n | otherwise = minShadeChar\n where\n itersToEscape = length . takeWhile (\\z -> magnitude z < 2) . take maxIters $ mSequence c (0 :+ 0)\n c = x :+ y\n mSequence c z = z : mSequence c (z ^ 2 + c)\n\n--Julia Sets\n\nplotJuliaSet :: PlotCommand\nplotJuliaSet gd args@(cStr : args')\n | isNothing mc = Left (rejectArgs gd args)\n | \"-shade\" `elem` args = Right (vtcJuliaSetShaded c)\n | otherwise = Right (vtcJuliaSet c)\n where\n mc = readMaybe cStr :: Maybe (Complex Double)\n Just c = mc\nplotJuliaSet gd args = plotJuliaSet gd (\"0\" : \"0\" : args)\n\nvtcJuliaSet :: Complex Double -> VectToChar\nvtcJuliaSet c gd@GD {getIters = iters} (V2 x y)\n | isInSet = maxShadeChar\n | otherwise = minShadeChar\n where\n isInSet = all (\\z -> magnitude z < 2) . take iters $ jSequence c (x :+ y)\n jSequence c z = z : jSequence c (z ^ 2 + c)\n\nvtcJuliaSetShaded :: Complex Double -> VectToChar\nvtcJuliaSetShaded c gd@GD {getIters = maxIters} (V2 x y)\n | itersToEscape >= maxIters = maxShadeChar\n | itersToEscape >= (7 * maxIters) `div` 8 = shadeChars !! 7\n | itersToEscape >= (6 * maxIters) `div` 8 = shadeChars !! 6\n | itersToEscape >= (5 * maxIters) `div` 8 = shadeChars !! 5\n | itersToEscape >= (4 * maxIters) `div` 8 = shadeChars !! 4\n | itersToEscape >= (3 * maxIters) `div` 8 = shadeChars !! 3\n | itersToEscape >= (2 * maxIters) `div` 8 = shadeChars !! 2\n | itersToEscape >= (1 * maxIters) `div` 8 = shadeChars !! 1\n | otherwise = minShadeChar\n where\n itersToEscape = length . takeWhile (\\z -> magnitude z < 2) . take maxIters $ jSequence c (x :+ y)\n jSequence c z = z : jSequence c (z ^ 2 + c)\n\n--Sierpinski triangle (WIP - random)\n\nplotSierpinski :: PlotCommand\nplotSierpinski gd args = Right vtcSierpinski\n\nvtcSierpinski :: VectToChar\nvtcSierpinski gd v@(V2 x y)\n | x < 0 || x > 1 || y < 0 || y > 1 = minShadeChar\n | any (withinRange gd v) $ truncatedList gd = maxShadeChar\n | otherwise = minShadeChar\n\ntruncatedList gd = take iters' $ drop iters' sierpinskiList' --Hardcoded parameter\n where\n iters' = 10 * getIters gd\n\nwithinRange gd (V2 x1 y1) (V2 x2 y2) = abs (x2 - x1) <= width && abs (y2 - y1) <= height\n where\n (width, height) = (0.75 * pxlW gd, 0.75 * pxlH gd) --Hardcoded parameter\n\nsierpinskiList :: (Vector2, Int) -> [Vector2]\nsierpinskiList (v, n) = v : sierpinskiList (nextSierpinski (v, n))\n\nsierpinskiList' = sierpinskiList (V2 0.5 0.5, 0) --Initial values\n\nnextSierpinski :: (Vector2, Int) -> (Vector2, Int)\nnextSierpinski (v@(V2 x y), n)\n | rand n `mod` 3 == 0 = (applyTransformation trans0 v, n + 1)\n | rand n `mod` 3 == 1 = (applyTransformation trans1 v, n + 1)\n | rand n `mod` 3 == 2 = (applyTransformation trans2 v, n + 1)\nnextSierpinski _ = (V2 0 0, 0)\n\ntrans0 = Transformation (0.5, 0.0, 0.0, 0.5) (V2 0 0)\n\ntrans1 = Transformation (0.5, 0.0, 0.0, 0.5) (V2 0.5 0)\n\ntrans2 = Transformation (0.5, 0.0, 0.0, 0.5) (V2 0.25 (sqrt 3 / 4))\n\n--Generates a pseudorandom digit\nrand :: Int -> Int\nrand n = randList !! (n `mod` length randList)\n\nrandList =\n [ 3,\n 1,\n 4,\n 1,\n 5,\n 9,\n 2,\n 6,\n 5,\n 3,\n 5,\n 8,\n 9,\n 7,\n 9,\n 3,\n 2,\n 3,\n 8,\n 4,\n 6,\n 2,\n 6,\n 4,\n 3,\n 3,\n 8,\n 3,\n 2,\n 7,\n 9,\n 5,\n 0,\n 2,\n 8,\n 8,\n 4,\n 1,\n 9,\n 7,\n 1,\n 6,\n 9,\n 3,\n 9,\n 9,\n 3,\n 7,\n 5,\n 1,\n 0,\n 5,\n 8,\n 2,\n 0,\n 9,\n 7,\n 4,\n 9,\n 4,\n 4,\n 5,\n 9,\n 2,\n 3,\n 0,\n 7,\n 8,\n 1,\n 6,\n 4,\n 0,\n 6,\n 2,\n 8,\n 6,\n 2,\n 0,\n 8,\n 9,\n 9,\n 8,\n 6,\n 2,\n 8,\n 0,\n 3,\n 4,\n 8,\n 2,\n 5,\n 3,\n 4,\n 2,\n 1,\n 1,\n 7,\n 0,\n 6,\n 7,\n 9,\n 8,\n 2,\n 1,\n 4,\n 8,\n 0,\n 8,\n 6,\n 5,\n 1,\n 3,\n 2,\n 8,\n 2,\n 3,\n 0,\n 6,\n 6,\n 4,\n 7,\n 0,\n 9,\n 3,\n 8,\n 4,\n 4,\n 6,\n 0,\n 9,\n 5,\n 5,\n 0,\n 5,\n 8,\n 2,\n 2,\n 3,\n 1,\n 7,\n 2,\n 5,\n 3,\n 5,\n 9,\n 4,\n 0,\n 8,\n 1,\n 2,\n 8,\n 4,\n 8,\n 1,\n 1,\n 1,\n 7,\n 4,\n 5,\n 0,\n 2,\n 8,\n 4,\n 1,\n 0,\n 2,\n 7,\n 0,\n 1,\n 9,\n 3,\n 8,\n 5,\n 2,\n 1,\n 1,\n 0,\n 5,\n 5,\n 5,\n 9,\n 6,\n 4,\n 4,\n 6,\n 2,\n 2,\n 9,\n 4,\n 8,\n 9,\n 5,\n 4,\n 9,\n 3,\n 0,\n 3,\n 8,\n 1,\n 9,\n 6,\n 4,\n 4,\n 2,\n 8,\n 8,\n 1,\n 0,\n 9,\n 7,\n 5,\n 6,\n 6,\n 5,\n 9,\n 3,\n 3,\n 4,\n 4,\n 6,\n 1,\n 2,\n 8,\n 4,\n 7,\n 5,\n 6,\n 4,\n 8,\n 2,\n 3,\n 3,\n 7,\n 8,\n 6,\n 7,\n 8,\n 3,\n 1,\n 6,\n 5,\n 2,\n 7,\n 1,\n 2,\n 0,\n 1,\n 9,\n 0,\n 9,\n 1,\n 4,\n 5,\n 6,\n 4,\n 8,\n 5,\n 6,\n 6,\n 9,\n 2,\n 3,\n 4,\n 6,\n 0,\n 3,\n 4,\n 8,\n 6,\n 1,\n 0,\n 4,\n 5,\n 4,\n 3,\n 2,\n 6,\n 6,\n 4,\n 8,\n 2,\n 1,\n 3,\n 3,\n 9,\n 3,\n 6,\n 0,\n 7,\n 2,\n 6,\n 0,\n 2,\n 4,\n 9,\n 1,\n 4,\n 1,\n 2,\n 7,\n 3,\n 7,\n 2,\n 4,\n 5,\n 8,\n 7,\n 0,\n 0,\n 6,\n 6,\n 0,\n 6,\n 3,\n 1,\n 5,\n 5,\n 8,\n 8,\n 1,\n 7,\n 4,\n 8,\n 8,\n 1,\n 5,\n 2,\n 0,\n 9,\n 2,\n 0,\n 9,\n 6,\n 2,\n 8,\n 2,\n 9,\n 2,\n 5,\n 4,\n 0,\n 9,\n 1,\n 7,\n 1,\n 5,\n 3,\n 6,\n 4,\n 3,\n 6,\n 7,\n 8,\n 9,\n 2,\n 5,\n 9,\n 0,\n 3,\n 6,\n 0,\n 0,\n 1,\n 1,\n 3,\n 3,\n 0,\n 5,\n 3,\n 0,\n 5,\n 4,\n 8,\n 8,\n 2,\n 0,\n 4,\n 6,\n 6,\n 5,\n 2,\n 1,\n 3,\n 8,\n 4,\n 1,\n 4,\n 6,\n 9,\n 5,\n 1,\n 9,\n 4,\n 1,\n 5,\n 1,\n 1,\n 6,\n 0,\n 9,\n 4,\n 3,\n 3,\n 0,\n 5,\n 7,\n 2,\n 7,\n 0,\n 3,\n 6,\n 5,\n 7,\n 5,\n 9,\n 5,\n 9,\n 1,\n 9,\n 5,\n 3,\n 0,\n 9,\n 2,\n 1,\n 8,\n 6,\n 1,\n 1,\n 7,\n 3,\n 8,\n 1,\n 9,\n 3,\n 2,\n 6,\n 1,\n 1,\n 7,\n 9,\n 3,\n 1,\n 0,\n 5,\n 1,\n 1,\n 8,\n 5,\n 4,\n 8,\n 0,\n 7,\n 4,\n 4,\n 6,\n 2,\n 3,\n 7,\n 9,\n 9,\n 6,\n 2,\n 7,\n 4,\n 9\n ]\n", "meta": {"hexsha": "db2e88fd21e5c27291cb6695782463403ac4284d", "size": 21112, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "AsciiFractal.hs", "max_stars_repo_name": "Than2000/ASCIIFractal", "max_stars_repo_head_hexsha": "889bcd10ab9ee6ba26625619550d519b05ff0a6e", "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": "AsciiFractal.hs", "max_issues_repo_name": "Than2000/ASCIIFractal", "max_issues_repo_head_hexsha": "889bcd10ab9ee6ba26625619550d519b05ff0a6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AsciiFractal.hs", "max_forks_repo_name": "Than2000/ASCIIFractal", "max_forks_repo_head_hexsha": "889bcd10ab9ee6ba26625619550d519b05ff0a6e", "max_forks_repo_licenses": ["BSD-3-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.2394366197, "max_line_length": 176, "alphanum_fraction": 0.5697707465, "num_tokens": 7680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5162155399074886}} {"text": "module STCR2Z2T0S0ReversalCornerPointSet where\n\nimport Data.Array.Repa as R\nimport Data.Binary (decodeFile)\nimport Data.Complex\nimport Data.List as L\nimport DFT.Plan\nimport FokkerPlanck.MonteCarlo\nimport FokkerPlanck.Pinwheel\nimport Image.IO\nimport STC.PowerMethod\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Text.Printf\nimport Types\n\n\nmain = do\n args@(numPointStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:taoDecayStr:taoReversalStr:taoCornerStr:numTrailStr:maxTrailStr:theta0FreqsStr:thetaFreqsStr:scale0FreqsStr:scaleFreqsStr:histFilePath:numIterationStr:writeSourceFlagStr:rStr: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 taoDecay = read taoDecayStr :: Double\n taoReversal = read taoReversalStr :: Double\n taoCorner = read taoCornerStr :: Double\n numTrail = read numTrailStr :: Int\n maxTrail = read maxTrailStr :: Int\n theta0Freq = read theta0FreqsStr :: Double\n theta0Freqs = [-theta0Freq .. theta0Freq]\n thetaFreq = read thetaFreqsStr :: Double\n thetaFreqs = [-thetaFreq .. thetaFreq]\n scale0Freq = read scale0FreqsStr :: Double\n scaleFreq = read scaleFreqsStr :: Double\n scale0Freqs = [-scale0Freq .. scale0Freq]\n scaleFreqs = [-scaleFreq .. scaleFreq]\n numIteration = read numIterationStr :: Int\n writeSourceFlag = read writeSourceFlagStr :: Bool\n numThread = read numThreadStr :: Int\n folderPath = \"output/test/STCR2Z2T0S0ReversalCornerPointSet\"\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 solveMonteCarloR2Z2T0S0ReversalCornerRadial\n numThread\n numTrail\n maxTrail\n numPoint\n numPoint\n thetaSigma\n scaleSigma\n maxScale\n taoDecay\n taoReversal\n taoCorner\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 plan <- makeR2Z2T0S0Plan emptyPlan arrR2Z2T0S0\n let n = 30\n m = round $ (fromIntegral n) * (sqrt 2) / 2\n a = 10\n b = -10\n c = 10\n a' = round $ (fromIntegral a) * (sqrt 2) / 2\n b' = round $ (fromIntegral b) * (sqrt 2) / 2\n c' = round $ (fromIntegral c) * (sqrt 2) / 2\n r = read rStr :: Double\n rr = round r :: Int\n shift = 15\n numTheta = 45\n deltaTheta = 1 * pi / numTheta\n xs =\n -- [ R2S1RPPoint (rr, shift, 0, 1)\n -- , R2S1RPPoint (rr, -shift, 0, 1)\n -- , R2S1RPPoint (-rr, shift, 0, 1)\n -- , R2S1RPPoint (-rr, -shift, 0, 1)\n -- , R2S1RPPoint (shift, rr, 0, 1)\n -- , R2S1RPPoint (-shift, rr, 0, 1)\n -- , R2S1RPPoint (shift, -rr, 0, 1)\n -- , R2S1RPPoint (-shift, -rr, 0, 1)\n -- ]\n -- [R2S1RPPoint (i, -i, 0, 1) | i <- [-2,0 .. 20]] L.++\n [R2S1RPPoint (-i, -i, 0, 1) | i <- [-10,-8 .. 10]]\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]\n -- ]) -- L.++\n -- -- (L.map\n -- -- (\\(i, j) -> R2S1RPPoint (round i, round j, 0, 1))\n -- -- [ ((r + 2) * cos (k * deltaTheta), (r + 2) * sin (k * deltaTheta))\n -- -- | k <- [0 .. numTheta - 1]\n -- -- ]) L.++\n -- -- (L.map\n -- -- (\\(i, j) -> R2S1RPPoint (round i, round j, 0, 1))\n -- -- [ ( (r + 5) * cos (k * deltaTheta)\n -- -- , (r + 5) * sin (k * deltaTheta))\n -- -- | k <- [0 .. numTheta - 1]\n -- -- ])\n -- -- L.++ [R2S1RPPoint (3, 5, 0, 1)]\n -- )\n -- ([R2S1RPPoint (i, i, 0, 1) | i <- [a',a' + b' .. c']] L.++\n -- [R2S1RPPoint (i, -i, 0, 1) | i <- [-a',-(a' + b') .. -c']] L.++\n -- [R2S1RPPoint (i, i, 0, 1) | i <- [-a',-(a' + b') .. -c']] L.++\n -- [R2S1RPPoint (i, -i, 0, 1) | i <- [a',a' + b' .. c']] L.++\n -- [R2S1RPPoint (i, 0, 0, 1) | i <- [a,a + b .. c]] L.++\n -- [R2S1RPPoint (0, i, 0, 1) | i <- [-a,-(a + b) .. -c]] L.++\n -- [R2S1RPPoint (i, 0, 0, 1) | i <- [-a,-(a + b) .. -c]] L.++\n -- [R2S1RPPoint (0, i, 0, 1) | i <- [a,a + b .. c]] L.++\n -- [R2S1RPPoint (3, 5, 0, 1)])\n -- [ R2S1RPPoint (n, 0, 0, 1)\n -- , R2S1RPPoint (0, n, 0, 1)\n -- , R2S1RPPoint (-n, 0, 0, 1)\n -- , R2S1RPPoint (0, -n, 0, 1)\n -- , R2S1RPPoint (m, m, 0, 1)\n -- , R2S1RPPoint (-m, m, 0, 1)\n -- , R2S1RPPoint (m, -m, 0, 1)\n -- , R2S1RPPoint (-m, -m, 0, 1)\n -- ]\n let bias = computeBiasR2T0S0 numPoint numPoint theta0Freqs scale0Freqs xs\n eigenVec =\n computeInitialEigenVectorR2T0S0\n numPoint\n numPoint\n theta0Freqs\n scale0Freqs\n thetaFreqs\n scaleFreqs\n xs\n powerMethodR2Z2T0S0\n plan\n folderPath\n numPoint\n numPoint\n numOrientation\n thetaFreqs\n theta0Freqs\n numScale\n scaleFreqs\n scale0Freqs\n arrR2Z2T0S0\n numIteration\n writeSourceFlag\n -- (printf \"_%d\" (round r :: Int))\n (printf\n \"_%d_%d_%d_%d_%.2f_%.2f\"\n (round maxScale :: Int)\n (round taoDecay :: Int)\n (round taoReversal :: Int)\n (round taoCorner :: Int)\n thetaSigma\n scaleSigma)\n 0.5\n bias\n eigenVec\n", "meta": {"hexsha": "dcbf76cdf119006b41cace5ffeb2daeef8c4b7b7", "size": 6674, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2Z2T0S0ReversalCornerPointSet/STCR2Z2T0S0ReversalCornerPointSet.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/STCR2Z2T0S0ReversalCornerPointSet/STCR2Z2T0S0ReversalCornerPointSet.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/STCR2Z2T0S0ReversalCornerPointSet/STCR2Z2T0S0ReversalCornerPointSet.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.3121693122, "max_line_length": 283, "alphanum_fraction": 0.5094396164, "num_tokens": 2295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357569, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5152787736372774}} {"text": "{-# OPTIONS_GHC -Wall #-}\n{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nmodule Main where\n\nimport Control.Monad ( zipWithM_ )\nimport Data.Foldable ( toList )\nimport Data.Monoid ( Monoid(..) )\nimport Data.SBV\nimport Data.SBV.Tools.CodeGen\nimport Data.SBV.Internals ( SolverContext )\nimport Data.Semigroup ( Semigroup(..) )\n\nimport qualified Numeric.GSL.ODE as ODE\nimport qualified Numeric.LinearAlgebra as LA\n\nimport Graphics.Rendering.Chart.Easy hiding ( (.>) )\nimport Graphics.Rendering.Chart.Backend.Cairo\n\ndata Pendulum a = Pendulum\n { pendulumLength :: a\n , pendulumDampingConstant :: a\n , pendulumMass :: a\n , pendulumGravity :: a\n } deriving (Eq, Show, Functor, Foldable, Traversable)\n\ndata State a = State\n { stateθ :: a\n , stateω :: a\n } deriving (Eq, Show, Functor, Foldable, Traversable)\n\nnewtype Controller a = Controller\n { controllerDamping :: a\n } deriving (Eq, Show, Functor, Foldable, Traversable)\n\ninstance EqSymbolic a => EqSymbolic (State a) where\n (State x a) .== (State y b) = x .== y &&& a .== b\n\nstateLabels :: State String\nstateLabels = State \"θ\" \"ω\"\n\npendulum :: Fractional a => Pendulum a -> a -> State a -> State a\npendulum sys@(Pendulum len damping _ grav) τ (State θ ω) =\n State ω $\n (grav * taylorSin θ) / len + (damping * ω) / inertia + τ / inertia\n where\n inertia = pendulumInertia sys\n\npendulumInertia :: Fractional a => Pendulum a -> a\npendulumInertia (Pendulum len _ mass _) = mass * len * len\n\nkineticEnergy :: Fractional a => Pendulum a -> State a -> a\nkineticEnergy system (State _ ω) =\n 0.5 * pendulumInertia system * ω * ω\n\ndkedt ::\n Fractional a => Controller a -> Pendulum a -> State a -> a\ndkedt ctrl system state@(State _ ω) =\n pendulumInertia system * ω * stateω (closedLoop ctrl system state)\n\n-- | Potential energy spans [-2, 0] * mg.\npotentialEnergy :: Fractional a => Pendulum a -> State a -> a\npotentialEnergy (Pendulum len _ mass grav) (State θ _) =\n len * mass * grav * (taylorCos θ - 1)\n\ndpedt :: Fractional a => Pendulum a -> State a -> a\ndpedt (Pendulum len _ mass grav) (State θ ω) =\n len * mass * grav * (- taylorSin θ) * ω\n\nlyapunovController :: Fractional a => Controller a -> Pendulum a -> State a -> a\nlyapunovController (Controller kd) (Pendulum len _ mass grav) (State θ ω) =\n (-2) * mass * grav * len * taylorSin θ - kd * ω\n\nclosedLoop ::\n Fractional a => Controller a -> Pendulum a -> State a -> State a\nclosedLoop ctrl system initialState =\n pendulum system torque initialState\n where\n torque = lyapunovController ctrl system initialState\n\n{- Proofs -}\n\nv :: Fractional a => Pendulum a -> State a -> a\nv system st =\n kineticEnergy system st - potentialEnergy system st\n\ndvdt :: Fractional a => Controller a -> Pendulum a -> State a -> a\ndvdt ctrl system st =\n dkedt ctrl system st - dpedt system st\n\nnewtype SAll a = SAll { getSAll :: a }\n\ninstance Boolean a => Semigroup (SAll a) where\n (SAll x) <> (SAll y) = SAll $ x &&& y\n\ninstance Boolean a => Monoid (SAll a) where\n mempty = SAll true\n mappend = (<>)\n\nallIsPoint :: (IEEEFloating a, Foldable t) => t (SBV a) -> SBool\nallIsPoint = getSAll . foldMap (SAll . fpIsPoint)\n\nnanFree ::\n (IEEEFloating a, SolverContext m, Monad m) =>\n (String -> m (SBV a)) -> (State (SBV a) -> SBV a) -> m SBool\nnanFree gen f = do\n st <- traverse gen stateLabels\n constrainPi st\n constrainFP st\n pure . fpIsPoint $ f st\n where\n constrainFP = constrain . allIsPoint\n constrainPi (State θ _) = constrain $ θ .<= π &&& θ .> -π\n π = 3.1415926535897932384626433832795028841971693993751\n\nlyapunov'sTheorem ::\n ( SymWord a, Fractional a\n , SolverContext m, Monad m) =>\n (String -> m (SBV a)) -> (State (SBV a) -> SBV a) -> (State (SBV a) -> SBV a) -> m SBool\nlyapunov'sTheorem gen f dfdt = do\n st <- traverse gen stateLabels\n constrainPi st\n-- constrainFP st\n-- constrainFP [f st, dfdt st]\n eq <- lyapunovEquilibrium st\n nn <- lyapunovNonNegative st\n gn <- lyapunovGradNegative st\n pure $ eq &&& nn &&& gn\n where\n constrainPi (State θ _) = constrain $ θ .<= π &&& θ .> -π\n π = 3.1415926535897932384626433832795028841971693993751\n lyapunovEquilibrium _ = pure $\n f (State 0 0) .== 0.0\n\n lyapunovNonNegative st = do\n constrain $ st ./= State 0 0\n pure $ f st .> 0.0\n\n lyapunovGradNegative st = pure $\n dfdt st .<= 0.0 &&& dfdt (State 0 0) .<= 0.0\n\nnominalController :: Fractional a => Controller a\nnominalController = Controller 0.3\n\nnominalSystem :: Fractional a => Pendulum a\nnominalSystem = Pendulum 0.5 (-0.03) 0.1 9.81\n\nsystemLabels :: Pendulum String\nsystemLabels = Pendulum \"length\" \"damping\" \"mass\" \"gravity\"\n\ncontrollerLabels :: Controller String\ncontrollerLabels = Controller \"kd\"\n\nproveStability :: IO ThmResult\nproveStability =\n prove $ lyapunov'sTheorem sReal v' dvdt'\n where\n v' = v nominalSystem\n dvdt' = dvdt nominalController nominalSystem\n\nproveNanSafety :: IO ThmResult\nproveNanSafety =\n prove $ nanFree sFloat controller\n where\n controller = lyapunovController nominalController nominalSystem\n\n-- Simulation\n\ndxdt :: Floating a => p -> [a] -> [a]\ndxdt _ [θ, ω] = toList $\n closedLoop nominalController nominalSystem\n (State θ ω)\ndxdt _ _ = error \"Invalid arguments to 'dxdt'\"\n\ndxdtOpenLoop :: Fractional a => p -> [a] -> [a]\ndxdtOpenLoop _ [θ, ω] =\n toList $ pendulum nominalSystem 0 (State θ ω)\ndxdtOpenLoop _ _ = error \"Invalid arguments to 'dxdtOpenLoop'\"\n\nsolution :: State Double\n -> (Double -> [Double] -> [Double])\n -> LA.Vector Double\n -> LA.Matrix Double\nsolution state0 f = ODE.odeSolve f $ toList state0\n\nlistSolution :: State Double\n -> (Double -> [Double] -> [Double])\n -> [Double]\n -> [(Double, Double)]\nlistSolution state0 f =\n fmap assoc . LA.toRows . solution state0 f . LA.fromList\n where\n assoc vec = let [t, x] = LA.toList vec in (t, x)\n\ninitialStates :: Fractional a => [State a]\ninitialStates = zipWith State [1e-3, -0.5, 0.3] [1e-3, 0.1, 0.3]\n\nsampleTs :: (Enum a, Fractional a) => [a]\nsampleTs = [0, 0.01 .. 7]\n\nmakePlot :: PlotValue a\n => String -> String -> String -> [[(a, a)]] -> IO ()\nmakePlot nm title lbl trajectories =\n toFile opts (nm <> \".png\") $ do\n layout_title .= title\n setColors $ fmap opaque [red, blue, green]\n zipWithM_ mkPlot [0 :: Int ..] trajectories\n where\n mkPlot num = plot . line (lbl <> show num) . pure\n opts = def { _fo_size = (1280, 720) }\n\nplotStates :: String -> (Double -> [Double] -> [Double]) -> IO ()\nplotStates prefix dynamics = do\n makePlot (prefix <> \"_theta\") (prefix <> \" pendulum angle\") \"θ\" thetas\n makePlot (prefix <> \"_omega\") (prefix <> \" pendulum velocity\") \"ω\" omegas\n where\n trajs = fmap (\\st -> listSolution st dynamics sampleTs) initialStates\n withTime sel = zip sampleTs . fmap sel\n thetas, omegas :: [[(Double, Double)]]\n thetas = fmap (withTime fst) trajs\n omegas = fmap (withTime snd) trajs\n\nunstabilized :: IO ()\nunstabilized = plotStates \"Unstabilized\" dxdtOpenLoop\n\nstabilized :: IO ()\nstabilized = plotStates \"Stabilized\" dxdt\n\nmain :: IO ()\nmain = do\n unstabilized\n stabilized\n genCCode\n\n-- Trigonometry\n\ntaylorCos :: Fractional a => a -> a\ntaylorCos x = 1 + sum (take 10 series)\n where\n inc num old =\n let new = old * x * x / (num * (num + 1))\n in new : inc (num + 2) new\n signs = cycle [negate, id]\n series = zipWith ($) signs (inc 1 1)\n\ntaylorSin :: Fractional a => a -> a\ntaylorSin x = x + sum (take 10 series)\n where\n inc num old =\n let new = old * x * x / (num * (num + 1))\n in new : inc (num + 2) new\n signs = cycle [negate, id]\n series = zipWith ($) signs (inc 2 x)\n\n-- C code generation\n\nemitController ::\n (Fractional a, SymWord a) =>\n (String -> SBVCodeGen (SBV a)) -> IO ()\nemitController gen = compileToC Nothing \"lyapunovController\" $ do\n system <- traverse gen systemLabels\n controller <- traverse gen controllerLabels\n state <- traverse gen stateLabels\n cgReturn $ lyapunovController controller system state\n\ngenCCode :: IO ()\ngenCCode = do\n emitController cgGen\n emitTaylor taylorSin \"taylorSin\" cgGen\n emitTaylor taylorCos \"taylorCos\" cgGen\n emitCalloutController cgGen\n where\n cgGen :: String -> SBVCodeGen SDouble\n cgGen = cgInput\n\nemitTaylor\n :: (Fractional a, SymWord a)\n => (SBV a -> SBV a)\n -> String\n -> (String -> SBVCodeGen (SBV a))\n -> IO ()\nemitTaylor f funName gen = compileToC Nothing funName $\n gen \"x\" >>= cgReturn . f\n\ntaylorSin' :: (Fractional a, SymWord a) => SBV a -> SBV a\ntaylorSin' = cgUninterpret \"taylorSin\" mempty taylorSin\n\ntaylorCos' :: (Fractional a, SymWord a) => SBV a -> SBV a\ntaylorCos' = cgUninterpret \"taylorCos\" mempty taylorCos\n\nlyapunovController'\n :: (SymWord a, Fractional a) =>\n Controller (SBV a)\n -> Pendulum (SBV a) -> State (SBV a) -> SBV a\nlyapunovController' (Controller kd) (Pendulum len _ mass grav) (State θ ω) =\n -2 * mass * grav * len * taylorSin' θ + kd * (-ω)\n\nemitCalloutController\n :: (SymWord a, Fractional a) =>\n (String -> SBVCodeGen (SBV a)) -> IO ()\nemitCalloutController gen = compileToC Nothing \"lyapunovController2\" $ do\n system <- traverse gen systemLabels\n controller <- traverse gen controllerLabels\n state <- traverse gen stateLabels\n cgReturn $ lyapunovController' controller system state\n", "meta": {"hexsha": "7b30d51312d0dbd3873eb106f85240b9966a6cf6", "size": 9396, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Pendulum.hs", "max_stars_repo_name": "peddie/smt-solving", "max_stars_repo_head_hexsha": "8f523a85a817cf4b1b63671f20b09d4674263a31", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-10T23:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T17:18:12.000Z", "max_issues_repo_path": "Pendulum.hs", "max_issues_repo_name": "peddie/smt-solving", "max_issues_repo_head_hexsha": "8f523a85a817cf4b1b63671f20b09d4674263a31", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pendulum.hs", "max_forks_repo_name": "peddie/smt-solving", "max_forks_repo_head_hexsha": "8f523a85a817cf4b1b63671f20b09d4674263a31", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-09T23:22:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-09T23:22:07.000Z", "avg_line_length": 30.3096774194, "max_line_length": 90, "alphanum_fraction": 0.6625159642, "num_tokens": 2962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5149157794318959}} {"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 MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE DataKinds #-}\n\n\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n\nmodule Particle ( main ) where\n\nimport Data.Random hiding ( StdNormal, Normal )\nimport Data.Random.Source.PureMT ( pureMT )\nimport Control.Monad.State ( evalState, replicateM )\nimport Numeric.LinearAlgebra.Static\n ( R, vector, Sym,\n headTail, matrix, sym,\n diag\n )\nimport GHC.TypeLits ( KnownNat )\nimport Data.Random.Distribution.Static.MultivariateNormal ( Normal(..) )\nimport qualified Data.Vector as V\nimport Data.Vector ( Vector )\nimport Data.List ( transpose )\nimport Control.Parallel.Strategies\nimport GHC.Generics (Generic)\n\nimport Numeric.Particle\n\nimport qualified Graphics.Rendering.Chart as C\nimport Graphics.Rendering.Chart.Backend.Diagrams\nimport Data.Colour\nimport Data.Colour.Names\nimport Data.Default.Class\nimport Control.Lens\n\nimport Diagrams.Backend.Cairo.CmdLine\nimport Diagrams.Prelude hiding ( render, Renderable, trace, Vector, sample )\nimport Diagrams.Backend.CmdLine\n\nimport Data.Csv\nimport System.IO hiding ( hGetContents )\nimport Data.ByteString.Lazy ( hGetContents )\n\nnParticles :: Int\nnParticles = 1000 -- 500\n\ndata SystemState a = SystemState { x1 :: a, x2 :: a }\n deriving (Show, Generic)\n\ninstance NFData a => NFData (SystemState a)\n\nnewtype SystemObs a = SystemObs { y1 :: a }\n deriving Show\n\n(.+), (.*), (.-) :: (Num a) => V.Vector a -> V.Vector a -> V.Vector a\n(.+) = V.zipWith (+)\n(.*) = V.zipWith (*)\n(.-) = V.zipWith (-)\n\ndeltaT, g :: Double\ndeltaT = 0.01\ng = 9.81\n\ntype PendulumState = R 2\n\nstateUpdate :: Particles (SystemState Double) ->\n Particles (SystemState Double)\nstateUpdate xPrevs = V.zipWith SystemState x1s x2s\n where\n ix = V.length xPrevs\n\n x1Prevs = V.map x1 xPrevs\n x2Prevs = V.map x2 xPrevs\n\n deltaTs = V.replicate ix deltaT\n gs = V.replicate ix g\n x1s = x1Prevs .+ (x2Prevs .* deltaTs)\n x2s = x2Prevs .- (gs .* (V.map sin x1Prevs) .* deltaTs)\n\nstateUpdateNoisy :: MonadRandom m =>\n Sym 2 ->\n Particles (SystemState Double) ->\n m (Particles (SystemState Double))\nstateUpdateNoisy bigQ xPrevs = do\n let xs = stateUpdate xPrevs\n\n x1s = V.map x1 xs\n x2s = V.map x2 xs\n\n let ix = V.length xPrevs\n etas <- replicateM ix $ sample $ rvar (Normal 0.0 bigQ)\n\n let eta1s, eta2s :: V.Vector Double\n eta1s = V.fromList $ map (fst . headTail) etas\n eta2s = V.fromList $ map (fst . headTail . snd . headTail) etas\n\n return (V.zipWith SystemState (x1s .+ eta1s) (x2s .+ eta2s))\n\nobsUpdate :: Particles (SystemState Double) ->\n Particles (SystemObs Double)\nobsUpdate xs = V.map (SystemObs . sin . x1) xs\n\nweight :: forall a n . KnownNat n =>\n (a -> R n) ->\n Sym n ->\n a -> a -> Double\nweight f bigR obs obsNew = pdf (Normal (f obsNew) bigR) (f obs)\n\nbigP :: Sym 2\nbigP = sym $ diag 0.1\n\ninitParticles :: MonadRandom m =>\n m (Particles (SystemState Double))\ninitParticles = V.replicateM nParticles $ do\n r <- sample $ rvar (Normal m0 bigP)\n let x1 = fst $ headTail r\n x2 = fst $ headTail $ snd $ headTail r\n return $ SystemState { x1 = x1, x2 = x2}\n\nrunFilter :: Particles (SystemObs Double) -> Vector (Particles (SystemState Double))\nrunFilter pendulumSamples = evalState action (pureMT 19)\n where\n action = do\n xs <- initParticles\n scanMapM\n (runPF (stateUpdateNoisy bigQ) obsUpdate (weight f bigR))\n return\n xs\n pendulumSamples\n\nf :: SystemObs Double -> R 1\nf = vector . pure . y1\n\nh :: SystemState Double -> R 2\nh u = vector [x1 u , x2 u]\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\nm0 :: PendulumState\nm0 = vector [1.6, 0]\n\ntestSmoothing :: Particles (SystemObs Double) -> Int -> [Double]\ntestSmoothing ss n = V.toList $ evalState action (pureMT 23)\n where\n action = do\n xss <- V.replicateM n $ oneSmoothingPath (stateUpdateNoisy bigQ) (weight h bigQ) nParticles (runFilter ss)\n let yss = V.fromList $ map V.fromList $\n transpose $\n V.toList $ V.map (V.toList) $\n xss\n return $ V.map (/ (fromIntegral n)) $ V.map V.sum $ V.map (V.map x1) yss\n\nchartEstimated :: String ->\n [(Double, Double)] ->\n [(Double, Double)] ->\n [(Double, Double)] ->\n C.Renderable ()\nchartEstimated title acts obs ests = C.toRenderable layout\n where\n\n actuals = C.plot_lines_values .~ [acts]\n $ C.plot_lines_style . C.line_color .~ opaque red\n $ C.plot_lines_title .~ \"Actual Trajectory\"\n $ C.plot_lines_style . C.line_width .~ 1.0\n $ def\n\n measurements = C.plot_points_values .~ obs\n $ C.plot_points_style . C.point_color .~ opaque blue\n $ C.plot_points_title .~ \"Measurements\"\n $ def\n\n estimas = C.plot_lines_values .~ [ests]\n $ C.plot_lines_style . C.line_color .~ opaque black\n $ C.plot_lines_title .~ \"Inferred Trajectory\"\n $ C.plot_lines_style . C.line_width .~ 1.0\n $ def\n\n layout = C.layout_title .~ title\n $ C.layout_plots .~ [C.toPlot actuals, C.toPlot measurements, C.toPlot estimas]\n $ C.layout_y_axis . C.laxis_title .~ \"Angle / Horizontal Displacement\"\n $ C.layout_y_axis . C.laxis_override .~ C.axisGridHide\n $ C.layout_x_axis . C.laxis_title .~ \"Time\"\n $ C.layout_x_axis . C.laxis_override .~ C.axisGridHide\n $ def\n\nnObs :: Int\nnObs = 200\n\ndiagU :: IO (Diagram Cairo)\ndiagU = 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 preObs = V.take nObs $ V.map fst generatedSamples\n let obs = V.toList preObs\n let acts = V.toList $ V.take nObs $ V.map snd generatedSamples\n let nus = take nObs (testSmoothing (V.map SystemObs preObs) 50)\n denv <- defaultEnv C.vectorAlignmentFns 600 500\n let charte = chartEstimated \"Particle Smoother\"\n (zip [0,1..] acts)\n (zip [0,1..] obs)\n (zip [0,1..] nus)\n return $ fst $ runBackend denv (C.render charte (600, 500))\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 du <- diagU\n displayHeader \"diagrams/Smooth3.png\" du\n", "meta": {"hexsha": "f9e5bd86d9707ff7fb87431ec75c79d04bcf1ace", "size": 7811, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/ParticleTest.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/ParticleTest.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/ParticleTest.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": 31.7520325203, "max_line_length": 112, "alphanum_fraction": 0.5937780054, "num_tokens": 2130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5148784908762686}} {"text": "{-# LANGUAGE ScopedTypeVariables #-}\n\n\nmodule Math.Probably.Unscented where\n\nimport Math.Probably.Sampler\nimport Math.Probably.FoldingStats\nimport Math.Probably.MCMC (empiricalMean, empiricalCovariance)\nimport Debug.Trace\n\nimport Numeric.LinearAlgebra hiding (find)\n\n-- smells because it is inefficient. For testing.\nsmellyTransform :: Sampler a -> Int -> (a -> Vector Double) -> Sampler (Vector Double, Matrix Double)\nsmellyTransform dist n f = do\n ys <- sequence $ replicate n $ fmap f dist\n let n = dim $ head ys\n return (empiricalMean ys, empiricalCovariance ys)\n \nalphaUT = 1e-1\nkappaUT = 0\nbetaUT = 2\n\nunscentedTransform :: (Vector Double, Matrix Double) -- ^ random variable\n -> (Vector Double -> Vector Double) -- ^ nonlinear transformation\n -> (Vector Double, Matrix Double, [Vector Double])\nunscentedTransform (xmean, xcov) f = (ymean, ycov, xs) where\n l = dim xmean\n lr = (realToFrac l) :: Double\n lambda = traceit \"lambda \" $alphaUT * alphaUT * (lr + kappaUT) - lr\n matSqrt = traceit \"SQRT \" $ toRows $ chol $ scale (lr+lambda) xcov\n xs = concat [[xmean], \n [xmean + (matSqrt!!i)| i <- [0..(l-1)]],\n [xmean - (matSqrt!!i)| i <- [0..(l-1)]]]\n wm = traceit \"wm \" $ (lambda / (lr+lambda)) : replicate (2*l) (1/(2*(lr+lambda)))\n wc = traceit \"wc \" $ ((lambda / (lr+lambda)) + 1 - alphaUT*alphaUT +betaUT) : replicate (2*l) (1/(2*(lr+lambda)))\n ys = map f xs\n ymean = sum $ zipWith (scale) wm ys \n ycov = sum [scale wi $ (yi - ymean) `outer` (yi - ymean) | (wi,yi) <- zip wc ys]\n\n\nunscentedKalmanFilterAdditive :: (Vector Double -> Vector Double) -- ^ processes nonlinearity\n -> (Vector Double -> Vector Double) -- ^ observation nonlinearity\n -> Matrix Double -- ^ process noise\n -> Matrix Double -- ^ observation noise\n -> (Vector Double, Matrix Double) -- ^ initial state estimate\n -> [Vector Double] -- ^ observations\n -> [(Vector Double, Matrix Double)] \nunscentedKalmanFilterAdditive procF obsF procCov obsCov (xmn0, xcov0) [] = []\nunscentedKalmanFilterAdditive procF obsF procCov obsCov (xmn0, xcov0) (yobs:yobss) =\n (xmn1, xcov1) : unscentedKalmanFilterAdditive procF obsF procCov obsCov (xmn1, xcov1) (yobss) where\n nx = dim xmn0\n nrx = realToFrac $ nx\n kx = 3-nrx\n l = dim xmn0\n lr = (realToFrac l) :: Double\n lambda = alphaUT * alphaUT * (lr + kappaUT) - lr\n\n --xmn1zz = ymn1pred\n --xcov1zz = ycov1pred\n\n (xmn1pred, xcov1pred', _) = unscentedTransform (xmn0, xcov0) procF \n xcov1pred = xcov1pred' + procCov\n\n (ymn1pred, ycov1pred', chis) = unscentedTransform (xmn1pred, xcov1pred) obsF \n ycov1pred = ycov1pred' + obsCov\n\n ny = dim ymn1pred\n nry = realToFrac $ ny\n ky = 3-nry\n\n wc = ((lambda / (lr+lambda)) + 1 - alphaUT*alphaUT +betaUT) : replicate (2*l) (1/(2*(lr+lambda)))\n\n ws = (ky / (nry+ky)) : replicate (2*ny) (1/(2*(nry+ky)))\n-- $ trace (show $ map dim [chii,xmn1pred, obsF chii, ymn1pred])\n crossCov = traceit \"cross \" $ sum [scale wi \n $ (chii - xmn1pred) `outer` \n (obsF chii - ymn1pred) \n | (wi,chii) <- zip ws chis]\n\n gain = crossCov `multiply` inv ycov1pred\n\n xmn1 = xmn1pred + gain `mXv` (yobs - ymn1pred)\n xcov1 = traceit \"newxcov \" $ xcov1pred - gain `multiply` ycov1pred `multiply` trans gain \n\n\ntraceit s x = trace (s++\" : \"++show x) x\n\n\nsimDynamical :: Int \n -> (Vector Double -> Vector Double) -- ^ processes nonlinearity\n -> (Vector Double -> Vector Double) -- ^ observation nonlinearity\n -> Matrix Double -- ^ process noise\n -> Matrix Double -- ^ observation noise\n -> Vector Double -- ^ initial state\n -> Sampler [(Vector Double, Vector Double)]\n\nsimDynamical 0 procF obsF procCov obsCov x0 = return []\nsimDynamical n procF obsF procCov obsCov x0 = do\n xnoise <- multiNormal (constant 0$ dim x0) procCov\n let x1 = procF $ join [ x0, xnoise]\n ynoise <- multiNormal (constant 0$ rows obsCov) obsCov\n let y1 = obsF $ join [ x1, ynoise]\n rest <- simDynamical (n-1) procF obsF procCov obsCov x1 \n return $ (x1, y1) : rest\n\n\nunscentedKalmanFilter :: (Vector Double -> Vector Double) -- ^ processes nonlinearity\n -> (Vector Double -> Vector Double) -- ^ observation nonlinearity\n -> Matrix Double -- ^ process noise\n -> Matrix Double -- ^ observation noise\n -> (Vector Double, Matrix Double) -- ^ initial state estimate\n -> [Vector Double] -- ^ observations\n -> [(Vector Double, Matrix Double)] \nunscentedKalmanFilter procF obsF procCov obsCov (xmn0, xcov0) [] = []\nunscentedKalmanFilter procF obsF procCov obsCov (xmn0, xcov0) (yobs:yobss) =\n (xmn1, xcov1) : unscentedKalmanFilter procF obsF procCov obsCov (xmn1, xcov1) (yobss) where\n nx = dim xmn0\n nrx = realToFrac $ nx\n kx = 3-nrx\n\n xmn1zz = ymn1pred\n xcov1zz = ycov1pred\n\n xmn0aug = traceit \"xm0aug\" $ join [xmn0, constant 0 nx]\n xcov0aug = fromBlocks [[xcov0, 0], \n [0, procCov]]\n (xmn1pred, xcov1pred, _) = unscentedTransform (xmn0aug, xcov0aug) procF \n\n xmn1aug = traceit \"xm1aug\"$ join [xmn1pred, constant 0 nx]\n xcov1aug = fromBlocks [[xcov1pred, 0], \n [0, obsCov]]\n\n\n (ymn1pred, ycov1pred, chis) = unscentedTransform (xmn1aug, xcov1aug) obsF \n\n ny = dim ymn1pred\n nry = realToFrac $ ny\n ky = 3-nry\n\n ws = (ky / (nry+ky)) : replicate (2*ny) (1/(2*(nry+ky)))\n-- $ trace (show $ map dim [chii,xmn1pred, obsF chii, ymn1pred])\n crossCov = traceit \"cross \" $ sum [scale wi \n $ (subVector 0 nx chii - xmn1pred) `outer` \n (obsF chii - ymn1pred) \n | (wi,chii) <- zip ws chis]\n\n gain = crossCov `multiply` inv ycov1pred\n\n xmn1 = xmn1pred + gain `mXv` (yobs - ymn1pred)\n xcov1 = traceit \"newxcov \" $ xcov1pred - gain `multiply` ycov1pred `multiply` trans gain \n", "meta": {"hexsha": "3d7da24f41964778b77c334650749bce1d52c4e6", "size": 6221, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/Probably/Unscented.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/Unscented.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/Unscented.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": 40.9276315789, "max_line_length": 116, "alphanum_fraction": 0.5947596849, "num_tokens": 2004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5140480676713242}} {"text": "module Numeric.FFT.Special.PowersOfTwo\n ( special2, special4, special8, special16, special32, special64\n ) where\n\nimport Control.Monad.ST\nimport Data.Complex\nimport qualified Data.Vector.Unboxed.Mutable as MV\n\nimport Numeric.FFT.Types\n\n\n-- | Length 2 hard-coded FFT.\nspecial2 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial2 _ xsin xsout = do\n a <- MV.unsafeRead xsin 0\n b <- MV.unsafeRead xsin 1\n MV.unsafeWrite xsout 0 $ a + b\n MV.unsafeWrite xsout 1 $ a - b\n\n-- | Length 4 hard-coded FFT.\nspecial4 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial4 sign xsin xsout = do\n xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n let tb = xr0 - xr2 ; t3 = xr0 + xr2 ; tf = xi0 + xi2 ; t9 = xi0 - xi2\n t6 = xr1 + xr3 ; ta = xr1 - xr3 ; te = xi1 - xi3 ; tg = xi1 + xi3\n r3 = (tb + te) :+ (t9 - ta)\n r2 = (t3 - t6) :+ (tf - tg)\n r1 = (tb - te) :+ (ta + t9)\n MV.unsafeWrite xsout 0 $ (t3 + t6) :+ (tf + tg)\n MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r3\n MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r2\n MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r1\n\n-- | Length 8 hard-coded FFT.\nkp707106781 :: Double\nkp707106781 = 0.707106781186547524400844362104849039284835938\nspecial8 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial8 sign xsin xsout = do\n xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n xr4 :+ xi4 <- MV.unsafeRead xsin 4 ; xr5 :+ xi5 <- MV.unsafeRead xsin 5\n xr6 :+ xi6 <- MV.unsafeRead xsin 6 ; xr7 :+ xi7 <- MV.unsafeRead xsin 7\n let tn = xr0 - xr4 ; t3 = xr0 + xr4 ; tC = xi0 - xi4 ; ti = xi0 + xi4\n tB = xr2 - xr6 ; t6 = xr2 + xr6 ; to = xi2 - xi6 ; tl = xi2 + xi6\n td = xr7 + xr3 ; tv = xr7 - xr3 ; tN = xi7 + xi3 ; ty = xi7 - xi3\n tz = tv - ty ; tH = tv + ty ; ta = xr1 + xr5 ; tq = xr1 - xr5\n tt = xi1 - xi5 ; tM = xi1 + xi5 ; tL = t3 - t6 ; t7 = t3 + t6\n tG = tt - tq ; tu = tq + tt ; te = ta + td ; tf = td - ta\n tm = ti - tl ; tP = ti + tl ; tQ = tM + tN ; tO = tM - tN\n tF = tn - to ; tp = tn + to ; tA = tu + tz ; tE = tz - tu\n tD = tB + tC ; tJ = tC - tB ; tK = tG + tH ; tI = tG - tH\n r7 = (tp + kp707106781 * tA) :+ (tJ + kp707106781 * tK)\n r6 = (tL + tO) :+ (tf + tm)\n r5 = (tF + kp707106781 * tI) :+ (tD + kp707106781 * tE)\n r4 = (t7 - te) :+ (tP - tQ)\n r3 = (tp - kp707106781 * tA) :+ (tJ - kp707106781 * tK)\n r2 = (tL - tO) :+ (tm - tf)\n r1 = (tF - kp707106781 * tI) :+ (tD - kp707106781 * tE)\n MV.unsafeWrite xsout 0 $ (t7 + te) :+ (tP + tQ)\n MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r7\n MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r6\n MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r5\n MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r4\n MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r3\n MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r2\n MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r1\n\n-- | Length 16 hard-coded FFT.\nkp923879532, kp414213562 :: Double\n--kp707106781 :: Double\nkp923879532 = 0.923879532511286756128183189396788286822416626\nkp414213562 = 0.414213562373095048801688724209698078569671875\n--kp707106781 = 0.707106781186547524400844362104849039284835938\nspecial16 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial16 sign xsin xsout = do\n xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n xr4 :+ xi4 <- MV.unsafeRead xsin 4 ; xr5 :+ xi5 <- MV.unsafeRead xsin 5\n xr6 :+ xi6 <- MV.unsafeRead xsin 6 ; xr7 :+ xi7 <- MV.unsafeRead xsin 7\n xr8 :+ xi8 <- MV.unsafeRead xsin 8 ; xr9 :+ xi9 <- MV.unsafeRead xsin 9\n xr10 :+ xi10 <- MV.unsafeRead xsin 10 ; xr11 :+ xi11 <- MV.unsafeRead xsin 11\n xr12 :+ xi12 <- MV.unsafeRead xsin 12 ; xr13 :+ xi13 <- MV.unsafeRead xsin 13\n xr14 :+ xi14 <- MV.unsafeRead xsin 14 ; xr15 :+ xi15 <- MV.unsafeRead xsin 15\n let tL = xr0 - xr8 ; t3 = xr0 + xr8 ; t1k = xi0 - xi8 ; ty = xi0 + xi8\n t1j = xr4 - xr12 ; t6 = xr4 + xr12 ; tM = xi4 - xi12 ; tB = xi4 + xi12\n t1l = t1j + t1k ; t1H = t1k - t1j ; t1R = t3 - t6 ; t7 = t3 + t6\n t1x = tL + tM ; tN = tL - tM ; tC = ty + tB ; t25 = ty - tB\n t1c = xr15 - xr7 ; tp = xr15 + xr7 ; t20 = xi15 + xi7 ; t1a = xi15 - xi7\n t17 = xr3 - xr11 ; ts = xr3 + xr11 ; t21 = xi3 + xi11 ; t1f = xi3 - xi11\n t1E = t1a - t17 ; t1b = t17 + t1a ; t1Z = tp - ts ; tt = tp + ts\n t2h = t20 + t21 ; t22 = t20 - t21 ; t1D = t1c + t1f ; t1g = t1c - t1f\n tP = xr2 - xr10 ; ta = xr2 + xr10 ; tO = xi2 - xi10 ; tF = xi2 + xi10\n t1n = tP + tO ; tQ = tO - tP ; tR = xr14 - xr6 ; td = xr14 + xr6\n tS = xi14 - xi6 ; tI = xi14 + xi6 ; te = ta + td ; t26 = td - ta\n tT = tR + tS ; t1m = tR - tS ; tJ = tF + tI ; t1S = tF - tI\n t11 = xr1 - xr9 ; ti = xr1 + xr9 ; t1V = xi1 + xi9 ; tZ = xi1 - xi9\n t2f = t7 - te ; tf = t7 + te ; tW = xr5 - xr13 ; tl = xr5 + xr13\n t1W = xi5 + xi13 ; t14 = xi5 - xi13 ; t1B = tZ - tW ; t10 = tW + tZ\n t1U = ti - tl ; tm = ti + tl ; t2g = t1V + t1W ; t1X = t1V - t1W\n t1A = t11 + t14 ; t15 = t11 - t14 ; tu = tm + tt ; tv = tt - tm\n tK = tC - tJ ; t2j = tC + tJ ; t2k = t2g + t2h ; t2i = t2g - t2h\n t29 = t1R - t1S ; t1T = t1R + t1S ; t27 = t25 - t26 ; t2d = t26 + t25\n t2a = t1X - t1U ; t1Y = t1U + t1X ; t23 = t1Z - t22 ; t2b = t1Z + t22\n t28 = t23 - t1Y ; t24 = t1Y + t23 ; t1I = tQ + tT ; tU = tQ - tT\n t2e = t2a + t2b ; t2c = t2a - t2b\n tV = tN + kp707106781 * tU ; t1v = tN - kp707106781 * tU\n t1o = t1m - t1n ; t1y = t1n + t1m\n t1t = t15 - kp414213562 * t10 ; t16 = t10 + kp414213562 * t15\n t1h = t1b - kp414213562 * t1g ; t1s = t1g + kp414213562 * t1b\n t1r = t1l + kp707106781 * t1o ; t1p = t1l - kp707106781 * t1o\n t1q = t16 + t1h ; t1i = t16 - t1h ; t1w = t1t + t1s ; t1u = t1s - t1t\n t1z = t1x + kp707106781 * t1y ; t1L = t1x - kp707106781 * t1y\n t1M = t1B - kp414213562 * t1A ; t1C = t1A + kp414213562 * t1B\n t1F = t1D - kp414213562 * t1E ; t1N = t1E + kp414213562 * t1D\n t1P = t1H + kp707106781 * t1I ; t1J = t1H - kp707106781 * t1I\n t1K = t1F - t1C ; t1G = t1C + t1F ; t1O = t1M - t1N ; t1Q = t1M + t1N\n r15 = (t1z + kp923879532 * t1G) :+ (t1P + kp923879532 * t1Q)\n r14 = (t1T + kp707106781 * t24) :+ (t2d + kp707106781 * t2e)\n r13 = (tV + kp923879532 * t1i) :+ (t1r + kp923879532 * t1u)\n r12 = (t2f + t2i) :+ (tv + tK)\n r11 = (t1L + kp923879532 * t1O) :+ (t1J + kp923879532 * t1K)\n r10 = (t29 + kp707106781 * t2c) :+ (t27 + kp707106781 * t28)\n r9 = (t1v - kp923879532 * t1w) :+ (t1p - kp923879532 * t1q)\n r8 = (tf - tu) :+ (t2j - t2k)\n r7 = (t1z - kp923879532 * t1G) :+ (t1P - kp923879532 * t1Q)\n r6 = (t1T - kp707106781 * t24) :+ (t2d - kp707106781 * t2e)\n r5 = (tV - kp923879532 * t1i) :+ (t1r - kp923879532 * t1u)\n r4 = (t2f - t2i) :+ (tK - tv)\n r3 = (t1L - kp923879532 * t1O) :+ (t1J - kp923879532 * t1K)\n r2 = (t29 - kp707106781 * t2c) :+ (t27 - kp707106781 * t28)\n r1 = (t1v + kp923879532 * t1w) :+ (t1p + kp923879532 * t1q)\n MV.unsafeWrite xsout 0 $ (tf + tu) :+ (t2j + t2k)\n MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r15\n MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r14\n MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r13\n MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r12\n MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r11\n MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r10\n MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r9\n MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r8\n MV.unsafeWrite xsout 9 $ if sign == 1 then r9 else r7\n MV.unsafeWrite xsout 10 $ if sign == 1 then r10 else r6\n MV.unsafeWrite xsout 11 $ if sign == 1 then r11 else r5\n MV.unsafeWrite xsout 12 $ if sign == 1 then r12 else r4\n MV.unsafeWrite xsout 13 $ if sign == 1 then r13 else r3\n MV.unsafeWrite xsout 14 $ if sign == 1 then r14 else r2\n MV.unsafeWrite xsout 15 $ if sign == 1 then r15 else r1\n\n-- | Length 32 hard-coded FFT.\nkp980785280, kp198912367, kp831469612, kp668178637 :: Double\n--kp923879532, kp707106781, kp414213562 :: Double\nkp980785280 = 0.980785280403230449126182236134239036973933731\nkp198912367 = 0.198912367379658006911597622644676228597850501\nkp831469612 = 0.831469612302545237078788377617905756738560812\nkp668178637 = 0.668178637919298919997757686523080761552472251\n--kp923879532 = 0.923879532511286756128183189396788286822416626\n--kp707106781 = 0.707106781186547524400844362104849039284835938\n--kp414213562 = 0.414213562373095048801688724209698078569671875\nspecial32 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial32 sign xsin xsout = do\n xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n xr4 :+ xi4 <- MV.unsafeRead xsin 4 ; xr5 :+ xi5 <- MV.unsafeRead xsin 5\n xr6 :+ xi6 <- MV.unsafeRead xsin 6 ; xr7 :+ xi7 <- MV.unsafeRead xsin 7\n xr8 :+ xi8 <- MV.unsafeRead xsin 8 ; xr9 :+ xi9 <- MV.unsafeRead xsin 9\n xr10 :+ xi10 <- MV.unsafeRead xsin 10 ; xr11 :+ xi11 <- MV.unsafeRead xsin 11\n xr12 :+ xi12 <- MV.unsafeRead xsin 12 ; xr13 :+ xi13 <- MV.unsafeRead xsin 13\n xr14 :+ xi14 <- MV.unsafeRead xsin 14 ; xr15 :+ xi15 <- MV.unsafeRead xsin 15\n xr16 :+ xi16 <- MV.unsafeRead xsin 16 ; xr17 :+ xi17 <- MV.unsafeRead xsin 17\n xr18 :+ xi18 <- MV.unsafeRead xsin 18 ; xr19 :+ xi19 <- MV.unsafeRead xsin 19\n xr20 :+ xi20 <- MV.unsafeRead xsin 20 ; xr21 :+ xi21 <- MV.unsafeRead xsin 21\n xr22 :+ xi22 <- MV.unsafeRead xsin 22 ; xr23 :+ xi23 <- MV.unsafeRead xsin 23\n xr24 :+ xi24 <- MV.unsafeRead xsin 24 ; xr25 :+ xi25 <- MV.unsafeRead xsin 25\n xr26 :+ xi26 <- MV.unsafeRead xsin 26 ; xr27 :+ xi27 <- MV.unsafeRead xsin 27\n xr28 :+ xi28 <- MV.unsafeRead xsin 28 ; xr29 :+ xi29 <- MV.unsafeRead xsin 29\n xr30 :+ xi30 <- MV.unsafeRead xsin 30 ; xr31 :+ xi31 <- MV.unsafeRead xsin 31\n let t1x = xr0-xr16 ; t3 = xr0+xr16 ; t2R = xi0-xi16 ; t14 = xi0+xi16\n t2S = xr8-xr24 ; t6 = xr8+xr24 ; t1y = xi8-xi24 ; t17 = xi8+xi24\n t2T = t2R-t2S ; t3T = t2S+t2R ; t4r = t3-t6 ; t7 = t3+t6\n t3t = t1x-t1y ; t1z = t1x+t1y ; t18 = t14+t17 ; t4Z = t14-t17\n t1A = xr4-xr20 ; ta = xr4+xr20 ; t1B = xi4-xi20 ; t1b = xi4+xi20\n t1C = t1A+t1B ; t2U = t1B-t1A ; t1D = xr28-xr12 ; td = xr28+xr12\n t1E = xi28-xi12 ; t1e = xi28+xi12 ; te = ta+td ; t50 = td-ta\n t1F = t1D-t1E ; t2V = t1D+t1E ; t4s = t1b-t1e ; t1f = t1b+t1e\n t2W = t2U+t2V ; t3u = t2U-t2V ; t3U = t1F-t1C ; t1G = t1C+t1F\n t1L = xr2-xr18 ; ti = xr2+xr18 ; t1I = xi2-xi18 ; t1j = xi2+xi18\n t1J = xr10-xr26 ; tl = xr10+xr26 ; t1M = xi10-xi26 ; t1m = xi10+xi26\n t3w = t1J+t1I ; t1K = t1I-t1J ; t4v = ti-tl ; tm = ti+tl\n t3x = t1L-t1M ; t1N = t1L+t1M ; t4u = t1j-t1m ; t1n = t1j+t1m\n t3X = t3x - kp414213562 * t3w ; t3y = t3w + kp414213562 * t3x\n t2Z = t1N + kp414213562 * t1K ; t1O = t1K - kp414213562 * t1N\n t53 = t4v+t4u ; t4w = t4u-t4v ; t1S = xr30-xr14 ; tp = xr30+xr14\n t1P = xi30-xi14 ; t1q = xi30+xi14 ; t1Q = xr6-xr22 ; ts = xr6+xr22\n t1T = xi6-xi22 ; t1t = xi6+xi22 ; t3z = t1Q+t1P ; t1R = t1P-t1Q\n t4x = tp-ts ; tt = tp+ts ; t3A = t1S-t1T ; t1U = t1S+t1T\n t4y = t1q-t1t ; t1u = t1q+t1t\n t3W = t3A + kp414213562 * t3z ; t3B = t3z - kp414213562 * t3A\n t2Y = t1U - kp414213562 * t1R ; t1V = t1R + kp414213562 * t1U\n t52 = t4x-t4y ; t4z = t4x+t4y ; t2G = xr31-xr15 ; tN = xr31+xr15\n t4N = xi31+xi15 ; t2r = xi31-xi15 ; t2s = xr7-xr23 ; tQ = xr7+xr23\n t4O = xi7+xi23 ; t2J = xi7-xi23 ; t2x = xr3-xr19 ; tU = xr3+xr19\n t4T = xi3+xi19 ; t2w = xi3-xi19 ; t3O = t2s+t2r ; t2t = t2r-t2s\n t2z = xr27-xr11 ; tX = xr27+xr11 ; t4U = xi27+xi11 ; t2C = xi27-xi11\n t3L = t2G-t2J ; t2K = t2G+t2J ; t4S = tN-tQ ; tR = tN+tQ\n tY = tU+tX ; t4Q = tX-tU ; t4P = t4N-t4O ; t5G = t4N+t4O\n t5H = t4T+t4U ; t4V = t4T-t4U ; t5F = tR-tY ; tZ = tR+tY\n t5I = t5G-t5H ; t5X = t5G+t5H ; t2L = t2x+t2w ; t2y = t2w-t2x\n t2D = t2z+t2C ; t2M = t2z-t2C ; t4R = t4P-t4Q ; t5k = t4Q+t4P\n t3M = t2D-t2y ; t2E = t2y+t2D ; t5j = t4S+t4V ; t4W = t4S-t4V\n t3P = t2L-t2M ; t2N = t2L+t2M ; t2f = xr1-xr17 ; ty = xr1+xr17\n t4C = xi1+xi17 ; t20 = xi1-xi17 ; t21 = xr9-xr25 ; tB = xr9+xr25\n t4D = xi9+xi25 ; t2i = xi9-xi25 ; t26 = xr5-xr21 ; tF = xr5+xr21\n t4I = xi5+xi21 ; t25 = xi5-xi21 ; t3H = t21+t20 ; t22 = t20-t21\n t28 = xr29-xr13 ; tI = xr29+xr13 ; t4J = xi29+xi13 ; t2b = xi29-xi13\n t3E = t2f-t2i ; t2j = t2f+t2i ; t4H = ty-tB ; tC = ty+tB\n tJ = tF+tI ; t4F = tI-tF ; t4E = t4C-t4D ; t5B = t4C+t4D\n t5C = t4I+t4J ; t4K = t4I-t4J ; t5A = tC-tJ ; tK = tC+tJ\n t5D = t5B-t5C ; t5W = t5B+t5C ; t2k = t26+t25 ; t27 = t25-t26\n t2c = t28+t2b ; t2l = t28-t2b ; t4G = t4E-t4F ; t5h = t4F+t4E\n t3F = t2c-t27 ; t2d = t27+t2c ; t5d = t4r+t4s ; t4t = t4r-t4s\n t5g = t4H+t4K ; t4L = t4H-t4K ; t3I = t2k-t2l ; t2m = t2k+t2l\n t4A = t4w-t4z ; t5o = t4w+t4z\n t4X = t4R - kp414213562 * t4W ; t58 = t4W + kp414213562 * t4R\n t59 = t4L - kp414213562 * t4G ; t4M = t4G + kp414213562 * t4L\n t5b = t4t - kp707106781 * t4A ; t4B = t4t + kp707106781 * t4A\n t5c = t59+t58 ; t5a = t58-t59 ; t5n = t50+t4Z ; t51 = t4Z-t50\n t54 = t52-t53 ; t5e = t53+t52 ; t56 = t4M+t4X ; t4Y = t4M-t4X\n t57 = t51 + kp707106781 * t54 ; t55 = t51 - kp707106781 * t54\n t5i = t5g + kp414213562 * t5h ; t5s = t5h - kp414213562 * t5g\n t5t = t5k + kp414213562 * t5j ; t5l = t5j - kp414213562 * t5k\n t5r = t5d - kp707106781 * t5e ; t5f = t5d + kp707106781 * t5e\n t5w = t5s+t5t ; t5u = t5s-t5t ; t5q = t5l-t5i ; t5m = t5i+t5l\n t5v = t5n + kp707106781 * t5o ; t5p = t5n - kp707106781 * t5o\n tf = t7+te ; t5x = t7-te ; t5y = t1n-t1u ; t1v = t1n+t1u\n t5E = t5A+t5D ; t5Q = t5D-t5A ; t5R = t5F+t5I ; t5J = t5F-t5I\n t5P = t5x-t5y ; t5z = t5x+t5y ; t5U = t5Q+t5R ; t5S = t5Q-t5R\n t1g = t18+t1f ; t5L = t18-t1f ; t5M = tt-tm ; tu = tm+tt\n t5O = t5J-t5E ; t5K = t5E+t5J ; t5T = t5M+t5L ; t5N = t5L-t5M\n t5V = tf-tu ; tv = tf+tu ; t60 = t5W+t5X ; t5Y = t5W-t5X\n t11 = tZ-tK ; t10 = tK+tZ ; t5Z = t1g+t1v ; t1w = t1g-t1v\n t39 = t1z + kp707106781 * t1G ; t1H = t1z - kp707106781 * t1G\n t1W = t1O-t1V ; t3k = t1O+t1V\n t3j = t2T + kp707106781 * t2W ; t2X = t2T - kp707106781 * t2W\n t30 = t2Y-t2Z ; t3a = t2Z+t2Y\n t3d = t22 + kp707106781 * t2d ; t2e = t22 - kp707106781 * t2d\n t37 = t1H - kp923879532 * t1W ; t1X = t1H + kp923879532 * t1W\n t33 = t2X + kp923879532 * t30 ; t31 = t2X - kp923879532 * t30\n t2n = t2j - kp707106781 * t2m ; t3c = t2j + kp707106781 * t2m\n t3g = t2t + kp707106781 * t2E ; t2F = t2t - kp707106781 * t2E\n t2O = t2K - kp707106781 * t2N ; t3f = t2K + kp707106781 * t2N\n t47 = t3t - kp707106781 * t3u ; t3v = t3t + kp707106781 * t3u\n t35 = t2n - kp668178637 * t2e ; t2o = t2e + kp668178637 * t2n\n t34 = t2O + kp668178637 * t2F ; t2P = t2F - kp668178637 * t2O\n t3C = t3y-t3B ; t4i = t3y+t3B\n t4h = t3T - kp707106781 * t3U ; t3V = t3T + kp707106781 * t3U\n t38 = t35+t34 ; t36 = t34-t35 ; t32 = t2o+t2P ; t2Q = t2o-t2P\n t41 = t3v - kp923879532 * t3C ; t3D = t3v + kp923879532 * t3C\n t3Y = t3W-t3X ; t48 = t3X+t3W\n t4b = t3E + kp707106781 * t3F ; t3G = t3E - kp707106781 * t3F\n t3J = t3H - kp707106781 * t3I ; t4a = t3H + kp707106781 * t3I\n t4e = t3L + kp707106781 * t3M ; t3N = t3L - kp707106781 * t3M\n t45 = t3V + kp923879532 * t3Y ; t3Z = t3V - kp923879532 * t3Y\n t42 = t3J - kp668178637 * t3G ; t3K = t3G + kp668178637 * t3J\n t3Q = t3O - kp707106781 * t3P ; t4d = t3O + kp707106781 * t3P\n t43 = t3Q + kp668178637 * t3N ; t3R = t3N - kp668178637 * t3Q\n t4p = t47 + kp923879532 * t48 ; t49 = t47 - kp923879532 * t48\n t44 = t42-t43 ; t46 = t42+t43 ; t40 = t3R-t3K ; t3S = t3K+t3R\n t4l = t4h - kp923879532 * t4i ; t4j = t4h + kp923879532 * t4i\n t4n = t4b - kp198912367 * t4a ; t4c = t4a + kp198912367 * t4b\n t4m = t4e + kp198912367 * t4d ; t4f = t4d - kp198912367 * t4e\n t3n = t39 - kp923879532 * t3a ; t3b = t39 + kp923879532 * t3a\n t4q = t4n+t4m ; t4o = t4m-t4n ; t4k = t4c+t4f ; t4g = t4c-t4f\n t3r = t3j + kp923879532 * t3k ; t3l = t3j - kp923879532 * t3k\n t3o = t3d - kp198912367 * t3c ; t3e = t3c + kp198912367 * t3d\n t3h = t3f - kp198912367 * t3g ; t3p = t3g + kp198912367 * t3f\n t3s = t3o+t3p ; t3q = t3o-t3p ; t3i = t3e+t3h ; t3m = t3h-t3e\n r31 = (t3b + kp980785280 * t3i) :+ (t3r + kp980785280 * t3s)\n r30 = (t5f + kp923879532 * t5m) :+ (t5v + kp923879532 * t5w)\n r29 = (t3D + kp831469612 * t3S) :+ (t45 + kp831469612 * t46)\n r28 = (t5z + kp707106781 * t5K) :+ (t5T + kp707106781 * t5U)\n r27 = (t1X + kp831469612 * t2Q) :+ (t33 + kp831469612 * t36)\n r26 = (t4B + kp923879532 * t4Y) :+ (t57 + kp923879532 * t5a)\n r25 = (t49 + kp980785280 * t4g) :+ (t4l + kp980785280 * t4o)\n r24 = (t5V+t5Y) :+ (t11+t1w)\n r23 = (t3n + kp980785280 * t3q) :+ (t3l + kp980785280 * t3m)\n r22 = (t5r + kp923879532 * t5u) :+ (t5p + kp923879532 * t5q)\n r21 = (t41 + kp831469612 * t44) :+ (t3Z + kp831469612 * t40)\n r20 = (t5P + kp707106781 * t5S) :+ (t5N + kp707106781 * t5O)\n r19 = (t37 - kp831469612 * t38) :+ (t31 - kp831469612 * t32)\n r18 = (t5b - kp923879532 * t5c) :+ (t55 - kp923879532 * t56)\n r17 = (t4p - kp980785280 * t4q) :+ (t4j - kp980785280 * t4k)\n r16 = (tv-t10) :+ (t5Z-t60)\n r15 = (t3b - kp980785280 * t3i) :+ (t3r - kp980785280 * t3s)\n r14 = (t5f - kp923879532 * t5m) :+ (t5v - kp923879532 * t5w)\n r13 = (t3D - kp831469612 * t3S) :+ (t45 - kp831469612 * t46)\n r12 = (t5z - kp707106781 * t5K) :+ (t5T - kp707106781 * t5U)\n r11 = (t1X - kp831469612 * t2Q) :+ (t33 - kp831469612 * t36)\n r10 = (t4B - kp923879532 * t4Y) :+ (t57 - kp923879532 * t5a)\n r9 = (t49 - kp980785280 * t4g) :+ (t4l - kp980785280 * t4o)\n r8 = (t5V-t5Y) :+ (t1w-t11)\n r7 = (t3n - kp980785280 * t3q) :+ (t3l - kp980785280 * t3m)\n r6 = (t5r - kp923879532 * t5u) :+ (t5p - kp923879532 * t5q)\n r5 = (t41 - kp831469612 * t44) :+ (t3Z - kp831469612 * t40)\n r4 = (t5P - kp707106781 * t5S) :+ (t5N - kp707106781 * t5O)\n r3 = (t37 + kp831469612 * t38) :+ (t31 + kp831469612 * t32)\n r2 = (t5b + kp923879532 * t5c) :+ (t55 + kp923879532 * t56)\n r1 = (t4p + kp980785280 * t4q) :+ (t4j + kp980785280 * t4k)\n MV.unsafeWrite xsout 0 $ (tv+t10) :+ (t5Z+t60)\n MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r31\n MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r30\n MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r29\n MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r28\n MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r27\n MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r26\n MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r25\n MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r24\n MV.unsafeWrite xsout 9 $ if sign == 1 then r9 else r23\n MV.unsafeWrite xsout 10 $ if sign == 1 then r10 else r22\n MV.unsafeWrite xsout 11 $ if sign == 1 then r11 else r21\n MV.unsafeWrite xsout 12 $ if sign == 1 then r12 else r20\n MV.unsafeWrite xsout 13 $ if sign == 1 then r13 else r19\n MV.unsafeWrite xsout 14 $ if sign == 1 then r14 else r18\n MV.unsafeWrite xsout 15 $ if sign == 1 then r15 else r17\n MV.unsafeWrite xsout 16 $ if sign == 1 then r16 else r16\n MV.unsafeWrite xsout 17 $ if sign == 1 then r17 else r15\n MV.unsafeWrite xsout 18 $ if sign == 1 then r18 else r14\n MV.unsafeWrite xsout 19 $ if sign == 1 then r19 else r13\n MV.unsafeWrite xsout 20 $ if sign == 1 then r20 else r12\n MV.unsafeWrite xsout 21 $ if sign == 1 then r21 else r11\n MV.unsafeWrite xsout 22 $ if sign == 1 then r22 else r10\n MV.unsafeWrite xsout 23 $ if sign == 1 then r23 else r9\n MV.unsafeWrite xsout 24 $ if sign == 1 then r24 else r8\n MV.unsafeWrite xsout 25 $ if sign == 1 then r25 else r7\n MV.unsafeWrite xsout 26 $ if sign == 1 then r26 else r6\n MV.unsafeWrite xsout 27 $ if sign == 1 then r27 else r5\n MV.unsafeWrite xsout 28 $ if sign == 1 then r28 else r4\n MV.unsafeWrite xsout 29 $ if sign == 1 then r29 else r3\n MV.unsafeWrite xsout 30 $ if sign == 1 then r30 else r2\n MV.unsafeWrite xsout 31 $ if sign == 1 then r31 else r1\n\n-- | Length 64 hard-coded FFT.\nkp956940335, kp881921264, kp534511135, kp303346683 :: Double\nkp995184726, kp773010453, kp820678790, kp098491403 :: Double\n--kp980785280, kp831469612, kp668178637, kp198912367 :: Double\n--kp923879532, kp707106781, kp414213562 :: Double\nkp956940335 = 0.956940335732208864935797886980269969482849206\nkp881921264 = 0.881921264348355029712756863660388349508442621\nkp534511135 = 0.534511135950791641089685961295362908582039528\nkp303346683 = 0.303346683607342391675883946941299872384187453\nkp995184726 = 0.995184726672196886244836953109479921575474869\nkp773010453 = 0.773010453362736960810906609758469800971041293\nkp820678790 = 0.820678790828660330972281985331011598767386482\nkp098491403 = 0.098491403357164253077197521291327432293052451\n--kp980785280 = 0.980785280403230449126182236134239036973933731\n--kp831469612 = 0.831469612302545237078788377617905756738560812\n--kp668178637 = 0.668178637919298919997757686523080761552472251\n--kp198912367 = 0.198912367379658006911597622644676228597850501\n--kp923879532 = 0.923879532511286756128183189396788286822416626\n--kp707106781 = 0.707106781186547524400844362104849039284835938\n--kp414213562 = 0.414213562373095048801688724209698078569671875\nspecial64 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial64 sign xsin xsout = do\n xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n xr4 :+ xi4 <- MV.unsafeRead xsin 4 ; xr5 :+ xi5 <- MV.unsafeRead xsin 5\n xr6 :+ xi6 <- MV.unsafeRead xsin 6 ; xr7 :+ xi7 <- MV.unsafeRead xsin 7\n xr8 :+ xi8 <- MV.unsafeRead xsin 8 ; xr9 :+ xi9 <- MV.unsafeRead xsin 9\n xr10 :+ xi10 <- MV.unsafeRead xsin 10 ; xr11 :+ xi11 <- MV.unsafeRead xsin 11\n xr12 :+ xi12 <- MV.unsafeRead xsin 12 ; xr13 :+ xi13 <- MV.unsafeRead xsin 13\n xr14 :+ xi14 <- MV.unsafeRead xsin 14 ; xr15 :+ xi15 <- MV.unsafeRead xsin 15\n xr16 :+ xi16 <- MV.unsafeRead xsin 16 ; xr17 :+ xi17 <- MV.unsafeRead xsin 17\n xr18 :+ xi18 <- MV.unsafeRead xsin 18 ; xr19 :+ xi19 <- MV.unsafeRead xsin 19\n xr20 :+ xi20 <- MV.unsafeRead xsin 20 ; xr21 :+ xi21 <- MV.unsafeRead xsin 21\n xr22 :+ xi22 <- MV.unsafeRead xsin 22 ; xr23 :+ xi23 <- MV.unsafeRead xsin 23\n xr24 :+ xi24 <- MV.unsafeRead xsin 24 ; xr25 :+ xi25 <- MV.unsafeRead xsin 25\n xr26 :+ xi26 <- MV.unsafeRead xsin 26 ; xr27 :+ xi27 <- MV.unsafeRead xsin 27\n xr28 :+ xi28 <- MV.unsafeRead xsin 28 ; xr29 :+ xi29 <- MV.unsafeRead xsin 29\n xr30 :+ xi30 <- MV.unsafeRead xsin 30 ; xr31 :+ xi31 <- MV.unsafeRead xsin 31\n xr32 :+ xi32 <- MV.unsafeRead xsin 32 ; xr33 :+ xi33 <- MV.unsafeRead xsin 33\n xr34 :+ xi34 <- MV.unsafeRead xsin 34 ; xr35 :+ xi35 <- MV.unsafeRead xsin 35\n xr36 :+ xi36 <- MV.unsafeRead xsin 36 ; xr37 :+ xi37 <- MV.unsafeRead xsin 37\n xr38 :+ xi38 <- MV.unsafeRead xsin 38 ; xr39 :+ xi39 <- MV.unsafeRead xsin 39\n xr40 :+ xi40 <- MV.unsafeRead xsin 40 ; xr41 :+ xi41 <- MV.unsafeRead xsin 41\n xr42 :+ xi42 <- MV.unsafeRead xsin 42 ; xr43 :+ xi43 <- MV.unsafeRead xsin 43\n xr44 :+ xi44 <- MV.unsafeRead xsin 44 ; xr45 :+ xi45 <- MV.unsafeRead xsin 45\n xr46 :+ xi46 <- MV.unsafeRead xsin 46 ; xr47 :+ xi47 <- MV.unsafeRead xsin 47\n xr48 :+ xi48 <- MV.unsafeRead xsin 48 ; xr49 :+ xi49 <- MV.unsafeRead xsin 49\n xr50 :+ xi50 <- MV.unsafeRead xsin 50 ; xr51 :+ xi51 <- MV.unsafeRead xsin 51\n xr52 :+ xi52 <- MV.unsafeRead xsin 52 ; xr53 :+ xi53 <- MV.unsafeRead xsin 53\n xr54 :+ xi54 <- MV.unsafeRead xsin 54 ; xr55 :+ xi55 <- MV.unsafeRead xsin 55\n xr56 :+ xi56 <- MV.unsafeRead xsin 56 ; xr57 :+ xi57 <- MV.unsafeRead xsin 57\n xr58 :+ xi58 <- MV.unsafeRead xsin 58 ; xr59 :+ xi59 <- MV.unsafeRead xsin 59\n xr60 :+ xi60 <- MV.unsafeRead xsin 60 ; xr61 :+ xi61 <- MV.unsafeRead xsin 61\n xr62 :+ xi62 <- MV.unsafeRead xsin 62 ; xr63 :+ xi63 <- MV.unsafeRead xsin 63\n let t35 = xr0-xr32 ; t3 = xr0+xr32 ; t5Y = xi0-xi32 ; t26 = xi0+xi32\n t5X = xr16-xr48 ; t6 = xr16+xr48 ; t36 = xi16-xi48 ; t29 = xi16+xi48\n t39 = xr8-xr40 ; ta = xr8+xr40 ; t38 = xi8-xi40 ; t2d = xi8+xi40\n t7B = t35+t36 ; t37 = t35-t36 ; t3b = xr56-xr24 ; td = xr56+xr24\n t3c = xi56-xi24 ; t2g = xi56+xi24 ; t5Z = t5X+t5Y ; t8F = t5Y-t5X\n taf = t3-t6 ; t7 = t3+t6 ; te = ta+td ; tbz = td-ta\n tbA = t26-t29 ; t2a = t26+t29 ; t3d = t3b+t3c ; t60 = t3b-t3c\n td9 = t7-te ; tf = t7+te ; tcB = tbA-tbz ; tbB = tbz+tbA\n t61 = t39+t38 ; t3a = t38-t39 ; t2h = t2d+t2g ; tag = t2d-t2g\n t7C = t61+t60 ; t62 = t60-t61 ; tdH = t2a-t2h ; t2i = t2a+t2h\n tcb = taf-tag ; tah = taf+tag ; t8G = t3a+t3d ; t3e = t3a-t3d\n t3j = xr4-xr36 ; ti = xr4+xr36 ; t3h = xi4-xi36 ; t2l = xi4+xi36\n t3g = xr20-xr52 ; tl = xr20+xr52 ; t3k = xi20-xi52 ; t2o = xi20+xi52\n t3q = xr60-xr28 ; tp = xr60+xr28 ; t3o = xi60-xi28 ; t2s = xi60+xi28\n tai = ti-tl ; tm = ti+tl ; t3n = xr12-xr44 ; ts = xr12+xr44\n t3r = xi12-xi44 ; t2v = xi12+xi44 ; tal = tp-ts ; tt = tp+ts\n taj = t2l-t2o ; t2p = t2l+t2o ; tam = t2s-t2v ; t2w = t2s+t2v\n tu = tm+tt ; tdI = tt-tm ; tak = tai+taj ; tbC = taj-tai\n tbD = tal+tam ; tan = tal-tam ; t7F = t3h-t3g ; t3i = t3g+t3h\n t3l = t3j-t3k ; t7E = t3j+t3k ; tda = t2p-t2w ; t2x = t2p+t2w\n t65 = t3l-kp414213562*t3i ; t3m = t3i+kp414213562*t3l\n t3s = t3q-t3r ; t7H = t3q+t3r ; t7I = t3o-t3n ; t3p = t3n+t3o\n t8I = t7F-kp414213562*t7E ; t7G = t7E+kp414213562*t7F\n t8J = t7I+kp414213562*t7H ; t7J = t7H-kp414213562*t7I\n t64 = t3s+kp414213562*t3p ; t3t = t3p-kp414213562*t3s\n t3H = xr2-xr34 ; ty = xr2+xr34 ; t3x = xi2-xi34 ; t2B = xi2+xi34\n t3w = xr18-xr50 ; tB = xr18+xr50 ; t3I = xi18-xi50 ; t2E = xi18+xi50\n t3C = xr58-xr26 ; tI = xr58+xr26 ; t3D = xi58-xi26 ; t2L = xi58+xi26\n t3z = xr10-xr42 ; tF = xr10+xr42 ; t3E = t3C-t3D ; t3K = t3C+t3D\n t2I = xi10+xi42 ; t3A = xi10-xi42 ; tat = ty-tB ; tC = ty+tB\n tJ = tF+tI ; taq = tI-tF ; t3L = t3A-t3z ; t3B = t3z+t3A\n tdd = tC-tJ ; tK = tC+tJ ; tar = t2B-t2E ; t2F = t2B+t2E\n tau = t2I-t2L ; t2M = t2I+t2L ; tce = tar-taq ; tas = taq+tar\n tcf = tat-tau ; tav = tat+tau ; t7M = t3x-t3w ; t3y = t3w+t3x\n t3F = t3B-t3E ; t7Q = t3B+t3E ; tdc = t2F-t2M ; t2N = t2F+t2M\n t6G = t3y+kp707106781*t3F ; t3G = t3y-kp707106781*t3F\n t7N = t3L+t3K ; t3M = t3K-t3L ; t3J = t3H-t3I ; t7P = t3H+t3I\n t9k = t7M-kp707106781*t7N ; t7O = t7M+kp707106781*t7N\n t9l = t7P-kp707106781*t7Q ; t7R = t7P+kp707106781*t7Q\n t6H = t3J+kp707106781*t3M ; t3N = t3J-kp707106781*t3M\n t5I = xr63-xr31 ; t1z = xr63+xr31 ; tb8 = xi63+xi31 ; t56 = xi63-xi31\n t53 = xr15-xr47 ; t1C = xr15+xr47 ; tb9 = xi15+xi47 ; t5L = xi15-xi47\n t5d = xr55-xr23 ; t1J = xr55+xr23 ; t5g = xi55-xi23 ; tbq = xi55+xi23\n t58 = xr7-xr39 ; t1G = xr7+xr39 ; t5N = t5d+t5g ; t5h = t5d-t5g\n tbp = xi7+xi39 ; t5b = xi7-xi39 ; tbo = t1z-t1C ; t1D = t1z+t1C\n t1K = t1G+t1J ; tb7 = t1J-t1G ; t5c = t58+t5b ; t5O = t5b-t58\n tdA = t1D-t1K ; t1L = t1D+t1K ; tbr = tbp-tbq ; tdw = tbp+tbq\n tba = tb8-tb9 ; tdv = tb8+tb9 ; t8l = t56-t53 ; t57 = t53+t56\n tct = tbo-tbr ; tbs = tbo+tbr ; teo = tdv+tdw ; tdx = tdv-tdw\n t5i = t5c-t5h ; t8x = t5c+t5h ; t8w = t5I+t5L ; t5M = t5I-t5L\n t5P = t5N-t5O ; t8m = t5O+t5N\n t6Y = t57+kp707106781*t5i ; t5j = t57-kp707106781*t5i\n t6V = t5M+kp707106781*t5P ; t5Q = t5M-kp707106781*t5P\n t9z = t8w-kp707106781*t8x ; t8y = t8w+kp707106781*t8x\n tcw = tba-tb7 ; tbb = tb7+tba\n t9C = t8l-kp707106781*t8m ; t8n = t8l+kp707106781*t8m\n t40 = xr62-xr30 ; tN = xr62+xr30 ; t3Q = xi62-xi30 ; t2Q = xi62+xi30\n t3P = xr14-xr46 ; tQ = xr14+xr46 ; t41 = xi14-xi46 ; t2T = xi14+xi46\n t3V = xr54-xr22 ; tX = xr54+xr22 ; t3W = xi54-xi22 ; t30 = xi54+xi22\n t3S = xr6-xr38 ; tU = xr6+xr38 ; t3X = t3V-t3W ; t43 = t3V+t3W\n t2X = xi6+xi38 ; t3T = xi6-xi38 ; taA = tN-tQ ; tR = tN+tQ\n tY = tU+tX ; tax = tX-tU ; t44 = t3T-t3S ; t3U = t3S+t3T\n tdf = tR-tY ; tZ = tR+tY ; tay = t2Q-t2T ; t2U = t2Q+t2T\n taB = t2X-t30 ; t31 = t2X+t30 ; tch = tay-tax ; taz = tax+tay\n tci = taA-taB ; taC = taA+taB ; t7T = t3Q-t3P ; t3R = t3P+t3Q\n t3Y = t3U-t3X ; t7X = t3U+t3X ; tdg = t2U-t31 ; t32 = t2U+t31\n t6J = t3R+kp707106781*t3Y ; t3Z = t3R-kp707106781*t3Y\n t7U = t44+t43 ; t45 = t43-t44 ; t42 = t40-t41 ; t7W = t40+t41\n t9n = t7T-kp707106781*t7U ; t7V = t7T+kp707106781*t7U\n t9o = t7W-kp707106781*t7X ; t7Y = t7W+kp707106781*t7X\n t6K = t42+kp707106781*t45 ; t46 = t42-kp707106781*t45\n t4P = xr1-xr33 ; t14 = xr1+xr33 ; taH = xi1+xi33 ; t4d = xi1-xi33\n t4a = xr17-xr49 ; t17 = xr17+xr49 ; taI = xi17+xi49 ; t4S = xi17-xi49\n t4k = xr57-xr25 ; t1e = xr57+xr25 ; t4n = xi57-xi25 ; taZ = xi57+xi25\n t4f = xr9-xr41 ; t1b = xr9+xr41 ; t4U = t4k+t4n ; t4o = t4k-t4n\n taY = xi9+xi41 ; t4i = xi9-xi41 ; taX = t14-t17 ; t18 = t14+t17\n t1f = t1b+t1e ; taG = t1e-t1b ; t4j = t4f+t4i ; t4V = t4i-t4f\n tdp = t18-t1f ; t1g = t18+t1f ; tb0 = taY-taZ ; tdl = taY+taZ\n taJ = taH-taI ; tdk = taH+taI ; t82 = t4d-t4a ; t4e = t4a+t4d\n tcm = taX-tb0 ; tb1 = taX+tb0 ; tej = tdk+tdl ; tdm = tdk-tdl\n t4p = t4j-t4o ; t8e = t4j+t4o ; t8d = t4P+t4S ; t4T = t4P-t4S\n t4W = t4U-t4V ; t83 = t4V+t4U\n t6R = t4e+kp707106781*t4p ; t4q = t4e-kp707106781*t4p\n t6O = t4T+kp707106781*t4W ; t4X = t4T-kp707106781*t4W\n t9s = t8d-kp707106781*t8e ; t8f = t8d+kp707106781*t8e\n tcp = taJ-taG ; taK = taG+taJ\n t9v = t82-kp707106781*t83 ; t84 = t82+kp707106781*t83\n t4C = xr5-xr37 ; t1j = xr5+xr37 ; taL = xi5+xi37 ; t4K = xi5-xi37\n t4H = xr21-xr53 ; t1m = xr21+xr53 ; t85 = t4K-t4H ; t4L = t4H+t4K\n taO = t1j-t1m ; t1n = t1j+t1m ; t4F = xi21-xi53 ; taM = xi21+xi53\n tdq = taL+taM ; taN = taL-taM ; t86 = t4C+t4F ; t4G = t4C-t4F\n t4r = xr61-xr29 ; t1q = xr61+xr29 ; taR = xi61+xi29 ; t4z = xi61-xi29\n t4w = xr13-xr45 ; t1t = xr13+xr45 ; t88 = t4z-t4w ; t4A = t4w+t4z\n taQ = t1q-t1t ; t1u = t1q+t1t ; t4u = xi13-xi45 ; taS = xi13+xi45\n tb2 = taO+taN ; taP = taN-taO ; tdr = taR+taS ; taT = taR-taS\n t89 = t4r+t4u ; t4v = t4r-t4u ; tdn = t1u-t1n ; t1v = t1n+t1u\n tb3 = taQ-taT ; taU = taQ+taT\n t4Z = t4A-kp414213562*t4v ; t4B = t4v+kp414213562*t4A\n tcq = tb2-tb3 ; tb4 = tb2+tb3 ; tek = tdq+tdr ; tds = tdq-tdr\n t4M = t4G-kp414213562*t4L ; t4Y = t4L+kp414213562*t4G\n t87 = t85-kp414213562*t86 ; t8g = t86+kp414213562*t85\n t6P = t4M+t4B ; t4N = t4B-t4M ; t6S = t4Y+t4Z ; t50 = t4Y-t4Z\n t8h = t89-kp414213562*t88 ; t8a = t88+kp414213562*t89\n t9w = t8g-t8h ; t8i = t8g+t8h ; tcn = taU-taP ; taV = taP+taU\n t9t = t8a-t87 ; t8b = t87+t8a ; t5v = xr3-xr35 ; t1O = xr3+xr35\n tbc = xi3+xi35 ; t5D = xi3-xi35 ; t5A = xr19-xr51 ; t1R = xr19+xr51\n t8o = t5D-t5A ; t5E = t5A+t5D ; tbf = t1O-t1R ; t1S = t1O+t1R\n t5y = xi19-xi51 ; tbd = xi19+xi51 ; tdB = tbc+tbd ; tbe = tbc-tbd\n t8p = t5v+t5y ; t5z = t5v-t5y ; t5k = xr59-xr27 ; t1V = xr59+xr27\n tbi = xi59+xi27 ; t5s = xi59-xi27 ; t5p = xr11-xr43 ; t1Y = xr11+xr43\n t8r = t5s-t5p ; t5t = t5p+t5s ; tbh = t1V-t1Y ; t1Z = t1V+t1Y\n t5n = xi11-xi43 ; tbj = xi11+xi43 ; tbt = tbf+tbe ; tbg = tbe-tbf\n tdC = tbi+tbj ; tbk = tbi-tbj ; t8s = t5k+t5n ; t5o = t5k-t5n\n tdy = t1Z-t1S ; t20 = t1S+t1Z ; tbu = tbh-tbk ; tbl = tbh+tbk\n t5S = t5t-kp414213562*t5o ; t5u = t5o+kp414213562*t5t\n tcx = tbt-tbu ; tbv = tbt+tbu ; tep = tdB+tdC ; tdD = tdB-tdC\n t5F = t5z-kp414213562*t5E ; t5R = t5E+kp414213562*t5z\n t8q = t8o-kp414213562*t8p ; t8z = t8p+kp414213562*t8o\n t6W = t5F+t5u ; t5G = t5u-t5F ; t6Z = t5R+t5S ; t5T = t5R-t5S\n t8A = t8s-kp414213562*t8r ; t8t = t8r+kp414213562*t8s\n t9D = t8z-t8A ; t8B = t8z+t8A ; tcu = tbl-tbg ; tbm = tbg+tbl\n tef = tf-tu ; tv = tf+tu ; t10 = tK+tZ ; teu = tZ-tK\n tel = tej-tek ; teE = tej+tek ; t9A = t8t-t8q ; t8u = t8q+t8t\n teD = tv-t10 ; t11 = tv+t10 ; teF = teo+tep ; teq = teo-tep\n tei = t1g-t1v ; t1w = t1g+t1v ; t21 = t1L+t20 ; ten = t1L-t20\n tet = t2i-t2x ; t2y = t2i+t2x ; teI = teE+teF ; teG = teE-teF\n t23 = t21-t1w ; t22 = t1w+t21 ; t33 = t2N+t32 ; teg = t2N-t32\n t34 = t2y-t33 ; teH = t2y+t33 ; tex = tef-teg ; teh = tef+teg\n teB = teu+tet ; tev = tet-teu ; tey = tel-tei ; tem = tei+tel\n tdV = td9+tda ; tdb = td9-tda ; tdJ = tdH-tdI ; te5 = tdI+tdH\n tez = ten+teq ; ter = ten-teq ; tdL = tdd+tdc ; tde = tdc-tdd\n teA = tey-tez ; teC = tey+tez ; tew = ter-tem ; tes = tem+ter\n tdh = tdf+tdg ; tdK = tdf-tdg ; tdE = tdA-tdD ; te1 = tdA+tdD\n te2 = tdy+tdx ; tdz = tdx-tdy ; te6 = tde+tdh ; tdi = tde-tdh\n teb = te2+kp414213562*te1 ; te3 = te1-kp414213562*te2\n tdZ = tdn+tdm ; tdo = tdm-tdn ; tdt = tdp-tds ; tdY = tdp+tds\n tdW = tdL+tdK ; tdM = tdK-tdL\n tdR = tdt-kp414213562*tdo ; tdu = tdo+kp414213562*tdt\n tdT = tdb-kp707106781*tdi ; tdj = tdb+kp707106781*tdi\n tea = tdZ-kp414213562*tdY ; te0 = tdY+kp414213562*tdZ\n tdQ = tdE+kp414213562*tdz ; tdF = tdz-kp414213562*tdE\n tdP = tdJ+kp707106781*tdM ; tdN = tdJ-kp707106781*tdM\n tdS = tdQ-tdR ; tdU = tdR+tdQ ; tdO = tdu+tdF ; tdG = tdu-tdF\n te9 = tdV-kp707106781*tdW ; tdX = tdV+kp707106781*tdW\n te4 = te0+te3 ; te8 = te3-te0\n te7 = te5-kp707106781*te6 ; ted = te5+kp707106781*te6\n tee = tea+teb ; tec = tea-teb ; tbE = tbC+tbD ; tcc = tbC-tbD\n tcC = tan-tak ; tao = tak+tan\n tcF = tcf-kp414213562*tce ; tcg = tce+kp414213562*tcf\n tcP = tcb-kp707106781*tcc ; tcd = tcb+kp707106781*tcc\n tcZ = tcB-kp707106781*tcC ; tcD = tcB+kp707106781*tcC\n tcj = tch-kp414213562*tci ; tcE = tci+kp414213562*tch\n tcy = tcw-kp707106781*tcx ; tcV = tcw+kp707106781*tcx\n tcW = tct+kp707106781*tcu ; tcv = tct-kp707106781*tcu\n tcT = tcm+kp707106781*tcn ; tco = tcm-kp707106781*tcn\n td0 = tcg+tcj ; tck = tcg-tcj\n td4 = tcW+kp198912367*tcV ; tcX = tcV-kp198912367*tcW\n tcr = tcp-kp707106781*tcq ; tcS = tcp+kp707106781*tcq\n tcK = tcr-kp668178637*tco ; tcs = tco+kp668178637*tcr\n tcQ = tcF+tcE ; tcG = tcE-tcF\n tcJ = tcd-kp923879532*tck ; tcl = tcd+kp923879532*tck\n td5 = tcT-kp198912367*tcS ; tcU = tcS+kp198912367*tcT\n tcL = tcy+kp668178637*tcv ; tcz = tcv-kp668178637*tcy\n tcN = tcD+kp923879532*tcG ; tcH = tcD-kp923879532*tcG\n tcO = tcK+tcL ; tcM = tcK-tcL ; tcI = tcz-tcs ; tcA = tcs+tcz\n td7 = tcP+kp923879532*tcQ ; tcR = tcP-kp923879532*tcQ\n tcY = tcU-tcX ; td2 = tcU+tcX\n td1 = tcZ+kp923879532*td0 ; td3 = tcZ-kp923879532*td0\n td6 = td4-td5 ; td8 = td5+td4\n tbH = tav+kp414213562*tas ; taw = tas-kp414213562*tav\n tbR = tah+kp707106781*tao ; tap = tah-kp707106781*tao\n tc1 = tbB+kp707106781*tbE ; tbF = tbB-kp707106781*tbE\n taD = taz+kp414213562*taC ; tbG = taC-kp414213562*taz\n tbw = tbs-kp707106781*tbv ; tbX = tbs+kp707106781*tbv\n tbY = tbb+kp707106781*tbm ; tbn = tbb-kp707106781*tbm\n tbV = taK+kp707106781*taV ; taW = taK-kp707106781*taV\n tc2 = taw+taD ; taE = taw-taD\n tc7 = tbY+kp198912367*tbX ; tbZ = tbX-kp198912367*tbY\n tb5 = tb1-kp707106781*tb4 ; tbU = tb1+kp707106781*tb4\n tbN = tb5-kp668178637*taW ; tb6 = taW+kp668178637*tb5\n tbS = tbH+tbG ; tbI = tbG-tbH\n tbP = tap-kp923879532*taE ; taF = tap+kp923879532*taE\n tc6 = tbV-kp198912367*tbU ; tbW = tbU+kp198912367*tbV\n tbM = tbw+kp668178637*tbn ; tbx = tbn-kp668178637*tbw\n tbL = tbF+kp923879532*tbI ; tbJ = tbF-kp923879532*tbI\n tbO = tbM-tbN ; tbQ = tbN+tbM ; tbK = tb6+tbx ; tby = tb6-tbx\n tc5 = tbR-kp923879532*tbS ; tbT = tbR+kp923879532*tbS\n tc0 = tbW+tbZ ; tc4 = tbZ-tbW\n tc3 = tc1-kp923879532*tc2 ; tc9 = tc1+kp923879532*tc2\n tca = tc6+tc7 ; tc8 = tc6-tc7\n t3f = t37+kp707106781*t3e ; t6D = t37-kp707106781*t3e\n t6E = t65+t64 ; t66 = t64-t65\n t6T = t6R-kp923879532*t6S ; t7k = t6R+kp923879532*t6S\n t7h = t6D+kp923879532*t6E ; t6F = t6D-kp923879532*t6E\n t7l = t6O+kp923879532*t6P ; t6Q = t6O-kp923879532*t6P\n t70 = t6Y-kp923879532*t6Z ; t7n = t6Y+kp923879532*t6Z\n t7o = t6V+kp923879532*t6W ; t6X = t6V-kp923879532*t6W\n t77 = t6H-kp198912367*t6G ; t6I = t6G+kp198912367*t6H\n t7x = t7l-kp098491403*t7k ; t7m = t7k+kp098491403*t7l\n t7w = t7o+kp098491403*t7n ; t7p = t7n-kp098491403*t7o\n t6L = t6J-kp198912367*t6K ; t76 = t6K+kp198912367*t6J\n t63 = t5Z+kp707106781*t62 ; t73 = t5Z-kp707106781*t62\n t7s = t6I+t6L ; t6M = t6I-t6L\n t7c = t6T-kp820678790*t6Q ; t6U = t6Q+kp820678790*t6T\n t74 = t3m+t3t ; t3u = t3m-t3t\n t7r = t73+kp923879532*t74 ; t75 = t73-kp923879532*t74\n t7i = t77+t76 ; t78 = t76-t77\n t7b = t6F-kp980785280*t6M ; t6N = t6F+kp980785280*t6M\n t7f = t75+kp980785280*t78 ; t79 = t75-kp980785280*t78\n t71 = t6X-kp820678790*t70 ; t7d = t70+kp820678790*t6X\n t7z = t7h+kp980785280*t7i ; t7j = t7h-kp980785280*t7i\n t7q = t7m-t7p ; t7u = t7m+t7p ; t7g = t7c+t7d ; t7e = t7c-t7d\n t72 = t6U+t71 ; t7a = t71-t6U\n t7t = t7r+kp980785280*t7s ; t7v = t7r-kp980785280*t7s\n t7y = t7w-t7x ; t7A = t7x+t7w\n t7D = t7B+kp707106781*t7C ; t9h = t7B-kp707106781*t7C\n t9i = t8I-t8J ; t8K = t8I+t8J\n t9x = t9v-kp923879532*t9w ; t9Y = t9v+kp923879532*t9w\n t9V = t9h-kp923879532*t9i ; t9j = t9h+kp923879532*t9i\n t9Z = t9s+kp923879532*t9t ; t9u = t9s-kp923879532*t9t\n t9E = t9C-kp923879532*t9D ; ta1 = t9C+kp923879532*t9D\n ta2 = t9z+kp923879532*t9A ; t9B = t9z-kp923879532*t9A\n t9L = t9l-kp668178637*t9k ; t9m = t9k+kp668178637*t9l\n tab = t9Z-kp303346683*t9Y ; ta0 = t9Y+kp303346683*t9Z\n taa = ta2+kp303346683*ta1 ; ta3 = ta1-kp303346683*ta2\n t9p = t9n-kp668178637*t9o ; t9K = t9o+kp668178637*t9n\n t8H = t8F+kp707106781*t8G ; t9H = t8F-kp707106781*t8G\n ta6 = t9m+t9p ; t9q = t9m-t9p\n t9Q = t9x-kp534511135*t9u ; t9y = t9u+kp534511135*t9x\n t9I = t7J-t7G ; t7K = t7G+t7J\n ta5 = t9H-kp923879532*t9I ; t9J = t9H+kp923879532*t9I\n t9W = t9L+t9K ; t9M = t9K-t9L\n t9P = t9j-kp831469612*t9q ; t9r = t9j+kp831469612*t9q\n t9T = t9J+kp831469612*t9M ; t9N = t9J-kp831469612*t9M\n t9F = t9B-kp534511135*t9E ; t9R = t9E+kp534511135*t9B\n tad = t9V+kp831469612*t9W ; t9X = t9V-kp831469612*t9W\n ta4 = ta0-ta3 ; ta8 = ta0+ta3 ; t9U = t9Q+t9R ; t9S = t9Q-t9R\n t9G = t9y+t9F ; t9O = t9F-t9y\n ta7 = ta5+kp831469612*ta6 ; ta9 = ta5-kp831469612*ta6\n tac = taa-tab ; tae = tab+taa\n t51 = t4X-kp923879532*t50 ; t6m = t4X+kp923879532*t50\n t6j = t3f+kp923879532*t3u ; t3v = t3f-kp923879532*t3u\n t6n = t4q+kp923879532*t4N ; t4O = t4q-kp923879532*t4N\n t5U = t5Q-kp923879532*t5T ; t6p = t5Q+kp923879532*t5T\n t6q = t5j+kp923879532*t5G ; t5H = t5j-kp923879532*t5G\n t69 = t3N+kp668178637*t3G ; t3O = t3G-kp668178637*t3N\n t6y = t6n-kp303346683*t6m ; t6o = t6m+kp303346683*t6n\n t6z = t6q+kp303346683*t6p ; t6r = t6p-kp303346683*t6q\n t47 = t3Z+kp668178637*t46 ; t68 = t46-kp668178637*t3Z\n t6u = t3O+t47 ; t48 = t3O-t47\n t6f = t51-kp534511135*t4O ; t52 = t4O+kp534511135*t51\n t6t = t63+kp923879532*t66 ; t67 = t63-kp923879532*t66\n t6k = t69+t68 ; t6a = t68-t69\n t6h = t3v-kp831469612*t48 ; t49 = t3v+kp831469612*t48\n t6d = t67+kp831469612*t6a ; t6b = t67-kp831469612*t6a\n t5V = t5H-kp534511135*t5U ; t6e = t5U+kp534511135*t5H\n t6x = t6j-kp831469612*t6k ; t6l = t6j+kp831469612*t6k\n t6s = t6o+t6r ; t6w = t6r-t6o ; t6g = t6e-t6f ; t6i = t6f+t6e\n t5W = t52-t5V ; t6c = t52+t5V\n t6v = t6t-kp831469612*t6u ; t6B = t6t+kp831469612*t6u\n t6C = t6y+t6z ; t6A = t6y-t6z\n t8j = t8f-kp923879532*t8i ; t90 = t8f+kp923879532*t8i\n t8X = t7D+kp923879532*t7K ; t7L = t7D-kp923879532*t7K\n t91 = t84+kp923879532*t8b ; t8c = t84-kp923879532*t8b\n t8C = t8y-kp923879532*t8B ; t93 = t8y+kp923879532*t8B\n t94 = t8n+kp923879532*t8u ; t8v = t8n-kp923879532*t8u\n t8N = t7R+kp198912367*t7O ; t7S = t7O-kp198912367*t7R\n t9c = t91-kp098491403*t90 ; t92 = t90+kp098491403*t91\n t9d = t94+kp098491403*t93 ; t95 = t93-kp098491403*t94\n t7Z = t7V+kp198912367*t7Y ; t8M = t7Y-kp198912367*t7V\n t98 = t7S+t7Z ; t80 = t7S-t7Z\n t8T = t8j-kp820678790*t8c ; t8k = t8c+kp820678790*t8j\n t97 = t8H+kp923879532*t8K ; t8L = t8H-kp923879532*t8K\n t8Y = t8N+t8M ; t8O = t8M-t8N\n t8V = t7L-kp980785280*t80 ; t81 = t7L+kp980785280*t80\n t8R = t8L+kp980785280*t8O ; t8P = t8L-kp980785280*t8O\n t8D = t8v-kp820678790*t8C ; t8S = t8C+kp820678790*t8v\n t9b = t8X-kp980785280*t8Y ; t8Z = t8X+kp980785280*t8Y\n t96 = t92+t95 ; t9a = t95-t92 ; t8U = t8S-t8T ; t8W = t8T+t8S\n t8E = t8k-t8D ; t8Q = t8k+t8D\n t99 = t97-kp980785280*t98 ; t9f = t97+kp980785280*t98\n t9g = t9c+t9d ; t9e = t9c-t9d\n r63 = (t8Z+kp995184726*t96) :+ (t9f+kp995184726*t9g)\n r62 = (tbT+kp980785280*tc0) :+ (tc9+kp980785280*tca)\n r61 = (t6l+kp956940335*t6s) :+ (t6B+kp956940335*t6C)\n r60 = (tdX+kp923879532*te4) :+ (ted+kp923879532*tee)\n r59 = (t9r+kp881921264*t9G) :+ (t9T+kp881921264*t9U)\n r58 = (tcl+kp831469612*tcA) :+ (tcN+kp831469612*tcO)\n r57 = (t6N+kp773010453*t72) :+ (t7f+kp773010453*t7g)\n r56 = (teh+kp707106781*tes) :+ (teB+kp707106781*teC)\n r55 = (t81+kp773010453*t8E) :+ (t8R+kp773010453*t8U)\n r54 = (taF+kp831469612*tby) :+ (tbL+kp831469612*tbO)\n r53 = (t49+kp881921264*t5W) :+ (t6d+kp881921264*t6g)\n r52 = (tdj+kp923879532*tdG) :+ (tdP+kp923879532*tdS)\n r51 = (t9X+kp956940335*ta4) :+ (ta9+kp956940335*tac)\n r50 = (tcR+kp980785280*tcY) :+ (td3+kp980785280*td6)\n r49 = (t7j+kp995184726*t7q) :+ (t7v+kp995184726*t7y)\n r48 = (teD+teG) :+ (t23+t34)\n r47 = (t9b+kp995184726*t9e) :+ (t99+kp995184726*t9a)\n r46 = (tc5+kp980785280*tc8) :+ (tc3+kp980785280*tc4)\n r45 = (t6x+kp956940335*t6A) :+ (t6v+kp956940335*t6w)\n r44 = (te9+kp923879532*tec) :+ (te7+kp923879532*te8)\n r43 = (t9P+kp881921264*t9S) :+ (t9N+kp881921264*t9O)\n r42 = (tcJ+kp831469612*tcM) :+ (tcH+kp831469612*tcI)\n r41 = (t7b+kp773010453*t7e) :+ (t79+kp773010453*t7a)\n r40 = (tex+kp707106781*teA) :+ (tev+kp707106781*tew)\n r39 = (t8V-kp773010453*t8W) :+ (t8P-kp773010453*t8Q)\n r38 = (tbP-kp831469612*tbQ) :+ (tbJ-kp831469612*tbK)\n r37 = (t6h-kp881921264*t6i) :+ (t6b-kp881921264*t6c)\n r36 = (tdT-kp923879532*tdU) :+ (tdN-kp923879532*tdO)\n r35 = (tad-kp956940335*tae) :+ (ta7-kp956940335*ta8)\n r34 = (td7-kp980785280*td8) :+ (td1-kp980785280*td2)\n r33 = (t7z-kp995184726*t7A) :+ (t7t-kp995184726*t7u)\n r32 = (t11-t22) :+ (teH-teI)\n r31 = (t8Z-kp995184726*t96) :+ (t9f-kp995184726*t9g)\n r30 = (tbT-kp980785280*tc0) :+ (tc9-kp980785280*tca)\n r29 = (t6l-kp956940335*t6s) :+ (t6B-kp956940335*t6C)\n r28 = (tdX-kp923879532*te4) :+ (ted-kp923879532*tee)\n r27 = (t9r-kp881921264*t9G) :+ (t9T-kp881921264*t9U)\n r26 = (tcl-kp831469612*tcA) :+ (tcN-kp831469612*tcO)\n r25 = (t6N-kp773010453*t72) :+ (t7f-kp773010453*t7g)\n r24 = (teh-kp707106781*tes) :+ (teB-kp707106781*teC)\n r23 = (t81-kp773010453*t8E) :+ (t8R-kp773010453*t8U)\n r22 = (taF-kp831469612*tby) :+ (tbL-kp831469612*tbO)\n r21 = (t49-kp881921264*t5W) :+ (t6d-kp881921264*t6g)\n r20 = (tdj-kp923879532*tdG) :+ (tdP-kp923879532*tdS)\n r19 = (t9X-kp956940335*ta4) :+ (ta9-kp956940335*tac)\n r18 = (tcR-kp980785280*tcY) :+ (td3-kp980785280*td6)\n r17 = (t7j-kp995184726*t7q) :+ (t7v-kp995184726*t7y)\n r16 = (teD-teG) :+ (t34-t23)\n r15 = (t9b-kp995184726*t9e) :+ (t99-kp995184726*t9a)\n r14 = (tc5-kp980785280*tc8) :+ (tc3-kp980785280*tc4)\n r13 = (t6x-kp956940335*t6A) :+ (t6v-kp956940335*t6w)\n r12 = (te9-kp923879532*tec) :+ (te7-kp923879532*te8)\n r11 = (t9P-kp881921264*t9S) :+ (t9N-kp881921264*t9O)\n r10 = (tcJ-kp831469612*tcM) :+ (tcH-kp831469612*tcI)\n r9 = (t7b-kp773010453*t7e) :+ (t79-kp773010453*t7a)\n r8 = (tex-kp707106781*teA) :+ (tev-kp707106781*tew)\n r7 = (t8V+kp773010453*t8W) :+ (t8P+kp773010453*t8Q)\n r6 = (tbP+kp831469612*tbQ) :+ (tbJ+kp831469612*tbK)\n r5 = (t6h+kp881921264*t6i) :+ (t6b+kp881921264*t6c)\n r4 = (tdT+kp923879532*tdU) :+ (tdN+kp923879532*tdO)\n r3 = (tad+kp956940335*tae) :+ (ta7+kp956940335*ta8)\n r2 = (td7+kp980785280*td8) :+ (td1+kp980785280*td2)\n r1 = (t7z+kp995184726*t7A) :+ (t7t+kp995184726*t7u)\n MV.unsafeWrite xsout 0 $ (t11+t22) :+ (teH+teI)\n MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r63\n MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r62\n MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r61\n MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r60\n MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r59\n MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r58\n MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r57\n MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r56\n MV.unsafeWrite xsout 9 $ if sign == 1 then r9 else r55\n MV.unsafeWrite xsout 10 $ if sign == 1 then r10 else r54\n MV.unsafeWrite xsout 11 $ if sign == 1 then r11 else r53\n MV.unsafeWrite xsout 12 $ if sign == 1 then r12 else r52\n MV.unsafeWrite xsout 13 $ if sign == 1 then r13 else r51\n MV.unsafeWrite xsout 14 $ if sign == 1 then r14 else r50\n MV.unsafeWrite xsout 15 $ if sign == 1 then r15 else r49\n MV.unsafeWrite xsout 16 $ if sign == 1 then r16 else r48\n MV.unsafeWrite xsout 17 $ if sign == 1 then r17 else r47\n MV.unsafeWrite xsout 18 $ if sign == 1 then r18 else r46\n MV.unsafeWrite xsout 19 $ if sign == 1 then r19 else r45\n MV.unsafeWrite xsout 20 $ if sign == 1 then r20 else r44\n MV.unsafeWrite xsout 21 $ if sign == 1 then r21 else r43\n MV.unsafeWrite xsout 22 $ if sign == 1 then r22 else r42\n MV.unsafeWrite xsout 23 $ if sign == 1 then r23 else r41\n MV.unsafeWrite xsout 24 $ if sign == 1 then r24 else r40\n MV.unsafeWrite xsout 25 $ if sign == 1 then r25 else r39\n MV.unsafeWrite xsout 26 $ if sign == 1 then r26 else r38\n MV.unsafeWrite xsout 27 $ if sign == 1 then r27 else r37\n MV.unsafeWrite xsout 28 $ if sign == 1 then r28 else r36\n MV.unsafeWrite xsout 29 $ if sign == 1 then r29 else r35\n MV.unsafeWrite xsout 30 $ if sign == 1 then r30 else r34\n MV.unsafeWrite xsout 31 $ if sign == 1 then r31 else r33\n MV.unsafeWrite xsout 32 $ if sign == 1 then r32 else r32\n MV.unsafeWrite xsout 33 $ if sign == 1 then r33 else r31\n MV.unsafeWrite xsout 34 $ if sign == 1 then r34 else r30\n MV.unsafeWrite xsout 35 $ if sign == 1 then r35 else r29\n MV.unsafeWrite xsout 36 $ if sign == 1 then r36 else r28\n MV.unsafeWrite xsout 37 $ if sign == 1 then r37 else r27\n MV.unsafeWrite xsout 38 $ if sign == 1 then r38 else r26\n MV.unsafeWrite xsout 39 $ if sign == 1 then r39 else r25\n MV.unsafeWrite xsout 40 $ if sign == 1 then r40 else r24\n MV.unsafeWrite xsout 41 $ if sign == 1 then r41 else r23\n MV.unsafeWrite xsout 42 $ if sign == 1 then r42 else r22\n MV.unsafeWrite xsout 43 $ if sign == 1 then r43 else r21\n MV.unsafeWrite xsout 44 $ if sign == 1 then r44 else r20\n MV.unsafeWrite xsout 45 $ if sign == 1 then r45 else r19\n MV.unsafeWrite xsout 46 $ if sign == 1 then r46 else r18\n MV.unsafeWrite xsout 47 $ if sign == 1 then r47 else r17\n MV.unsafeWrite xsout 48 $ if sign == 1 then r48 else r16\n MV.unsafeWrite xsout 49 $ if sign == 1 then r49 else r15\n MV.unsafeWrite xsout 50 $ if sign == 1 then r50 else r14\n MV.unsafeWrite xsout 51 $ if sign == 1 then r51 else r13\n MV.unsafeWrite xsout 52 $ if sign == 1 then r52 else r12\n MV.unsafeWrite xsout 53 $ if sign == 1 then r53 else r11\n MV.unsafeWrite xsout 54 $ if sign == 1 then r54 else r10\n MV.unsafeWrite xsout 55 $ if sign == 1 then r55 else r9\n MV.unsafeWrite xsout 56 $ if sign == 1 then r56 else r8\n MV.unsafeWrite xsout 57 $ if sign == 1 then r57 else r7\n MV.unsafeWrite xsout 58 $ if sign == 1 then r58 else r6\n MV.unsafeWrite xsout 59 $ if sign == 1 then r59 else r5\n MV.unsafeWrite xsout 60 $ if sign == 1 then r60 else r4\n MV.unsafeWrite xsout 61 $ if sign == 1 then r61 else r3\n MV.unsafeWrite xsout 62 $ if sign == 1 then r62 else r2\n MV.unsafeWrite xsout 63 $ if sign == 1 then r63 else r1\n", "meta": {"hexsha": "e871494845b5a2f142d01fcd07e440c83a4f29fb", "size": 48992, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/FFT/Special/PowersOfTwo.hs", "max_stars_repo_name": "ian-ross/arb-fft", "max_stars_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-06-15T09:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-08T13:14:27.000Z", "max_issues_repo_path": "Numeric/FFT/Special/PowersOfTwo.hs", "max_issues_repo_name": "ian-ross/arb-fft", "max_issues_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-03-08T20:31:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T20:32:09.000Z", "max_forks_repo_path": "Numeric/FFT/Special/PowersOfTwo.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": 60.8596273292, "max_line_length": 79, "alphanum_fraction": 0.6074869366, "num_tokens": 24002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5138631358005461}} {"text": "import Data.Complex\nimport Data.Ratio\n\nn0 :: Int\nn0 = 5\n\nn1 :: Double\nn1 = 5.0\n\nn2 :: Complex Double\nn2 = 2 :+ 3\n\nn3 :: Ratio Int\nn3 = 2 % 3\n\nmain :: IO ()\nmain = do\n print n0\n print n1\n print n2\n print n3", "meta": {"hexsha": "4d094ef825355b29965328b3030d73078516fdb3", "size": 209, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Nums.hs", "max_stars_repo_name": "dashalary/hs-nums", "max_stars_repo_head_hexsha": "a48ef247f7f892db2281995c1550acf04b75fc89", "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": "Nums.hs", "max_issues_repo_name": "dashalary/hs-nums", "max_issues_repo_head_hexsha": "a48ef247f7f892db2281995c1550acf04b75fc89", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nums.hs", "max_forks_repo_name": "dashalary/hs-nums", "max_forks_repo_head_hexsha": "a48ef247f7f892db2281995c1550acf04b75fc89", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 9.9523809524, "max_line_length": 20, "alphanum_fraction": 0.5980861244, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289535, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5133982003890049}} {"text": "-- Bicubic interpolation algorithm from http://books.google.fi/books?id=1aAOdzK3FegC&pg=PA136&dq=bicubic+interpolation&hl=fi&sa=X&ei=japrUaWaH8Tcsga5hYHoCg&redir_esc=y#v=onepage&q=bicubic%20interpolation&f=false\n\nmodule Gradient (gradientStepper) where\n\nimport Prelude hiding ((<>))\nimport Numeric.LinearAlgebra\nimport Types\n\nbcuMatrix = (16><16) \n [\n 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,\n -3, 0, 0, 3, 0, 0, 0, 0,-2, 0, 0,-1, 0, 0, 0, 0,\n 2, 0, 0,-2, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0,\n 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,\n 0, 0, 0, 0,-3, 0, 0, 3, 0, 0, 0, 0,-2, 0, 0,-1,\n 0, 0, 0, 0, 2, 0, 0,-2, 0, 0, 0, 0, 1, 0, 0, 1,\n -3, 3, 0, 0,-2,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,-3, 3, 0, 0,-2,-1, 0, 0,\n 9,-9, 9,-9, 6, 3,-3,-6, 6,-6,-3, 3, 4, 2, 1, 2,\n -6, 6,-6, 6,-4,-2, 2, 4,-3, 3, 3,-3,-2,-1,-1,-2,\n 2,-2, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 2,-2, 0, 0, 1, 1, 0, 0,\n -6, 6,-6, 6,-3,-3, 3, 3,-4, 4, 2,-2,-2,-2,-1,-1,\n 4,-4, 4,-4, 2, 2,-2,-2, 2,-2,-2, 2, 1, 1, 1, 1::Double\n ]\n\n-- 0 1 2 3\n-- 4 5 6 7\n-- 8 9 10 11\n-- 12 13 14 15\n--\n-- 01 (0,0) --> (0,1) f, dx, dy, cross\n-- 32 | y=x1, x=x2 \n-- v\n-- (1,0)\ncenteredDifferencing = (16><16) [ \n-- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0,-1/2, 0, 1/2, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,-1/2, 0, 1/2, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0,-1/2, 0, 1/2, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,-1/2, 0, 1/2, 0, 0, 0, 0, 0,\n 0,-1/2, 0, 0, 0, 0, 0, 0, 0, 1/2, 0, 0, 0, 0, 0, 0,\n 0, 0,-1/2, 0, 0, 0, 0, 0, 0, 0, 1/2, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0,-1/2, 0, 0, 0, 0, 0, 0, 0, 1/2, 0,\n 0, 0, 0, 0, 0,-1/2, 0, 0, 0, 0, 0, 0, 0, 1/2, 0, 0,\n 1/4, 0,-1/4, 0, 0, 0, 0, 0,-1/4, 0, 1/4, 0, 0, 0, 0, 0,\n 0, 1/4, 0,-1/4, 0, 0, 0, 0, 0,-1/4, 0, 1/4, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 1/4, 0,-1/4, 0, 0, 0, 0, 0,-1/4, 0, 1/4,\n 0, 0, 0, 0, 1/4, 0,-1/4, 0, 0, 0, 0, 0,-1/4, 0, 1/4, 0::Double\n ]\n\ncombinedMatrix = bcuMatrix <> centeredDifferencing\n\n-- bicubic interpolation \n-- returns (value, d/dx, d/dy) at (y,x)@m\nbicubicInterpolation :: Matrix Double -> (Double, Double) -> (Double, Double, Double)\nbicubicInterpolation m (y, x) = (val, g1, g2)\n where\n (x_, dx) = properFraction x --u\n (y_, dy) = properFraction y --t\n ls = tr $ reshape 4 $ combinedMatrix #> flatten sub\n us = 4 |> [1.0, dx, dx*dx, dx*dx*dx]\n ts = 4 |> [1.0, dy, dy*dy, dy*dy*dy]\n us2 = 4 |> [0.0, 1.0, 2.0*dx, 3.0*dx*dx]\n ts2 = 4 |> [0.0, 1.0, 2.0*dy, 3.0*dy*dy]\n val = ts `dot` (ls #> us) --f\n g1 = ts2 `dot` (ls #> us) --d/dy\n g2 = ts `dot` (ls #> us2) --d/dx\n sub = subMatrix (y_-1,x_-1) (4,4) m\n\ngradientStepper:: Direction -> Double -> Matrix Double -> (Double, Double) -> [(Double, Double, Double)]\ngradientStepper dir delta mat (y0, x0) = (x0, y0, z0) : ga x0 y0 z0 dy0 dx0\n where\n (z0, dy0, dx0) = bicubicInterpolation mat (y0, x0)\n ga x y z dy dx\n | x' < 2 || y' < 2 || x' > fromIntegral (cols mat - 3) || y' > fromIntegral (rows mat - 3) = []\n | z' > z = (x', y', z') : ga x' y' z' dy' dx'\n | otherwise = []\n where\n l \n | dy == 00 && dx == 0.0 = 1\n | otherwise = 1.0 / sqrt (dy*dy+dx*dx)\n (dyn, dxn) = (dy*l, dx*l)\n directionOp = if dir == Descent then subtract else (+)\n (y',x') = (y `directionOp` delta*dyn, x `directionOp` delta*dxn)\n (z',dy',dx') = bicubicInterpolation mat (y', x') \n\n", "meta": {"hexsha": "2eb58d6bf3c44ba2a283f15bc9f12cbe3d281ae1", "size": 4251, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Gradient.hs", "max_stars_repo_name": "angs/Hachure-map", "max_stars_repo_head_hexsha": "1d06afe230e9321271c9d12a257bc9254b3d68f8", "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": "Gradient.hs", "max_issues_repo_name": "angs/Hachure-map", "max_issues_repo_head_hexsha": "1d06afe230e9321271c9d12a257bc9254b3d68f8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gradient.hs", "max_forks_repo_name": "angs/Hachure-map", "max_forks_repo_head_hexsha": "1d06afe230e9321271c9d12a257bc9254b3d68f8", "max_forks_repo_licenses": ["BSD-3-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.2234042553, "max_line_length": 211, "alphanum_fraction": 0.4055516349, "num_tokens": 2678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.5129501679785995}} {"text": "{- |\nModule : Numeric.Information.Model.IT\nDescription : Information quantities on models\nCopyright : (c) Malte Harder\nLicense : MIT\n\nMaintainer : malte.harder@gmail.com\nStability : experimental\nPortability : portable\n\n-}\n\nmodule Numeric.Information.Model.IT\n (\n -- * Entropy & Mutual Information\n nodeEntropy\n , nodeCondEntropy\n , nodeMutualInfo\n , nodeCondMutualInfo\n -- * Specific Information\n , nodeSpecificInformation\n , nodeMinimalInformation\n -- * Partial Information Decomposition\n -- ** Data Types\n , PINode (..)\n , PILattice\n -- ** Functions\n , piDecomp\n -- ** Helper Functions\n , piLattice\n , piSet\n , (-<<)\n , (-<=)\n , subset\n -- * Information Flow\n , nodeInformationFlow\n ) where\n\nimport Numeric.Information.Model\n\nimport Numeric.Information.Distribution\nimport Numeric.Information.IT\n\nimport Data.Graph.Inductive\nimport Data.List\n\n--import Statistics.Math hiding(log2)\nimport Numeric.SpecFunctions hiding(log2)\n\n\nnodeEntropy :: (Floating prob, Ord prob, Ord a)\n => [String]\n -> ModelDistribution prob a\n -> prob\nnodeEntropy v m = (entropy . extract) (marginalize v m)\n\nnodeCondEntropy :: (Floating prob, Ord prob, Ord a)\n => [String]\n -> [String]\n -> ModelDistribution prob a\n -> prob\nnodeCondEntropy yv xv m =\n let p_ygx = extractC $ conditionalize yv xv m\n p_x = extract $ marginalize xv m\n in condEntropy p_ygx p_x\n\nnodeMutualInfo :: (Floating prob, Ord prob, Ord a)\n => [String]\n -> [String]\n -> ModelDistribution prob a\n -> prob\nnodeMutualInfo yv xv m =\n let p_ygx = extractC $ conditionalize yv xv m\n p_x = extract $ marginalize xv m\n in mutualInfo p_ygx p_x\n\nnodeCondMutualInfo :: (Floating prob, Ord prob, Ord a)\n => [String]\n -> [String]\n -> [String]\n -> ModelDistribution prob a\n -> prob\nnodeCondMutualInfo yv xv zv m =\n let p_xgz = extractC $ conditionalize xv zv m\n p_xgyz = \\(y,z) -> (extractC $ conditionalize xv (yv++zv) m) $ y ++ z\n p_z = extract $ marginalize zv m\n p_ygz = extractC $ conditionalize yv zv m\n in condMutualInfo p_xgz p_xgyz p_z (p_ygz -|- p_z)\n\nnodeSpecificInformation :: (Floating prob, Ord prob, Ord a)\n => [String]\n -> [a]\n -> [String]\n -> ModelDistribution prob a\n -> prob\nnodeSpecificInformation sv s av m =\n let p_s = (extract $ marginalize sv m) ?= s\n p_ags = (extractC $ conditionalize av sv m) s\n p_sga = (extractC $ conditionalize sv av m)\n in expected p_ags (\\a-> log2 ((p_sga a) ?= s / p_s))\n\nnodeMinimalInformation :: (Floating prob, Ord prob, Ord a)\n => [String]\n -> [[String]]\n -> ModelDistribution prob a\n -> prob\nnodeMinimalInformation sv avs m =\n let p_s = (extract $ marginalize sv m)\n in expected p_s (\\s -> minimum $\n map (\\av -> nodeSpecificInformation sv s av m) avs)\n\nnodeMaxMinimalInformation :: (Floating prob, Ord prob, Ord a)\n => [String]\n -> [[[String]]]\n -> ModelDistribution prob a\n -> prob\nnodeMaxMinimalInformation sv avss m =\n let p_s = (extract $ marginalize sv m)\n in expected p_s (\\s -> maximum' $\n map (\\avs -> minimum $\n map (\\av -> nodeSpecificInformation sv s av m)\n avs) avss)\n\n\nnodeInformationFlow :: (Floating prob, Ord prob, Ord a)\n => [String]\n -> [String]\n -> Model prob a\n -> prob\nnodeInformationFlow as bs m = undefined\n\n\nmaximum' [] = 0\nmaximum' xs = maximum xs\n\ndata PINode prob a = PINode { partial :: [[a]]\n , value :: prob\n } deriving (Eq)\n\ninstance (Show a, Show prob) => Show (PINode prob a) where\n show n = (intercalate \",\" $\n map (\\xs -> (intercalate \" & \" (map (trim . show . show) xs))) $ partial n)\n ++ \" = \"++ (show $ value n)\n\ntrim = reverse . tail . reverse . tail\n\ntype PILattice prob a = Gr (PINode prob a) ()\n\npiDecomp :: (Floating prob, Ord prob, Ord a)\n => [String]\n -> [String]\n -> ModelDistribution prob a\n -> PILattice prob String\npiDecomp s as m =\n let g = piLattice as\n g' = nmap minimalInformation g\n in gmap (subtractLower g') g'\n where minimalInformation piN =\n piN { value = (nodeMinimalInformation s (partial piN) m)}\n subtractLower g' (inA, n, piN, outA) =\n (inA,\n n,\n piN { value = (value piN) -\n (nodeMaxMinimalInformation s\n (map (partial . snd) $ filter\n (\\(n',piN') -> (n',n) `elem` (edges g') ) $ labNodes g')\n m )} ,\n outA)\n\npiLattice :: (Eq a, Fractional prob) => [a] -> PILattice prob a\npiLattice modelNodes =\n let nodes = autoLabel $ map (\\n -> PINode { partial = n, value = 0 })\n $ piSet modelNodes\n size = (length nodes)-1\n edges = [ (i,j,()) | i <- [0..size], j <- [0..size],\n i /= j && -- Reflexive reduction\n (partial $ snd $ nodes !! i) -<= (partial $ snd $ nodes !! j) ]\n compositionEdges = [ (i,k,()) | (i,j,()) <- edges, k <- [0..size],\n (j,k,()) `elem` edges]\n reducedEdges = edges \\\\ compositionEdges\n in mkGraph nodes reducedEdges\n\npiSet :: (Eq a) => [a] -> [[[a]]]\npiSet r = [ a | a <- (powerset' . powerset') r,\n (null [ a | x <- a, y <- a,\n x /= y &&\n (length x <= length y) && (subset x y)])]\n\nmuSet :: (Eq a) => Int -> [a] -> [([[a]], Double)]\nmuSet k ls =\n let r = piSet ls\n p = powerset' ls\n n = length ls\n in map (\\beta -> (beta, (fromIntegral n)/(fromIntegral k) * (esoohc n k) * (fromIntegral $ length $\n filter (\\a -> length a == k && beta -<= [a]) p) - 1 ) ) r\n\n\nmuSet' :: (Eq a) => [a] -> [([[a]], Double)]\nmuSet' ls =\n let r = piSet ls\n p = powerset' ls\n n = length ls\n in map (\\beta ->\n (beta,\n (sum [ (esoohc n k) * ( fromIntegral\n $ (length $ filter\n (\\a -> length a == k && beta -<= [a]) p)) - (fromIntegral k)/(fromIntegral n)\n | k <- [1 .. (n-1)] ] ) ) ) r\n\nesoohc :: Int -> Int -> Double\nesoohc n k = 1.0 / (n `choose` k)\n\n(-<<) :: (Eq a) => [[a]] -> [[a]] -> Bool\n(-<<) a b = (a -<= b) && (a /= b)\n\n(-<=) :: (Eq a) => [[a]] -> [[a]] -> Bool\n(-<=) a b = foldr q True b\n where q bel cur = cur && (not . null $ filter (\\ael -> subset ael bel) a )\n\nsubset :: (Eq a) => [a] -> [a] -> Bool\nsubset a b = foldr q True a\n where q el cur = cur && (elem el b)\n\npowerset' :: [a] -> [[a]]\npowerset' = tail . powerset\n\npowerset :: [a] -> [[a]]\npowerset [] = [[]]\npowerset (x:xs) = xss /\\/ map (x:) xss\n where xss = powerset xs\n\n(/\\/) :: [a] -> [a] -> [a]\n[] /\\/ ys = ys\n(x:xs) /\\/ ys = x : (ys /\\/ xs)", "meta": {"hexsha": "e102f5842fd29fa95c1b594e1cf22a889ab4ebcc", "size": 7597, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Information/Model/IT.hs", "max_stars_repo_name": "mahrz24/hit", "max_stars_repo_head_hexsha": "ea9d27ea4f9b8ae65d71959e14ca847d54347f35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-28T04:26:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-28T04:26:13.000Z", "max_issues_repo_path": "src/Numeric/Information/Model/IT.hs", "max_issues_repo_name": "mahrz24/hit", "max_issues_repo_head_hexsha": "ea9d27ea4f9b8ae65d71959e14ca847d54347f35", "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/Information/Model/IT.hs", "max_forks_repo_name": "mahrz24/hit", "max_forks_repo_head_hexsha": "ea9d27ea4f9b8ae65d71959e14ca847d54347f35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-21T22:24:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-21T22:24:11.000Z", "avg_line_length": 32.4658119658, "max_line_length": 101, "alphanum_fraction": 0.4871659866, "num_tokens": 2027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.5128070324727494}} {"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n\n{-|\nStability: alpha\n\nNote that this is an __internal__ module. Use it at your own risk.\n-}\nmodule Isumi.Math.FFT.Internal.Polynomial\n (\n -- * Public APIs\n Polynomial(..)\n , polyToVecRep\n , polyFromVecRep\n , polyFromExpCoefRep\n , polyDegree\n , mapPoly\n , UnboxFloatingAppxEq\n , modPoly\n , RealOrComplexPolynomial(..)\n , modPolyG\n , BruunDivisor(..)\n , factorDivisor\n , divToPoly\n , divDegree\n -- * Internal APIs\n , polyMultiply'\n ) where\n\nimport Control.Exception\nimport Control.Monad.Loops\nimport Control.Monad.ST\nimport Data.Complex\nimport Data.Foldable (for_)\nimport Data.STRef\nimport qualified Data.Vector.Unboxed as UV\nimport qualified Data.Vector.Unboxed.Mutable as MUV\nimport Isumi.Math.AppxEq\nimport Isumi.Math.FFT.Internal.Utils (findM, isSorted, realToComplex)\n\n-- | A finite polynomial, represented in either vector or list of (exponent,\n-- coefficient). Using these constructors implys no check for pre-conditions.\ndata Polynomial a = PolyVecRep (UV.Vector a)\n | PolyExpCoefRep [(Int, a)]\n deriving Show\n\ninstance (UV.Unbox a, AppxEq a) => AppxEq (Polynomial a) where\n PolyVecRep v1 ~= PolyVecRep v2 = v1 ~= v2\n PolyExpCoefRep xs ~= PolyExpCoefRep ys = xs ~= ys\n _ ~= _ = False\n\n-- | Construct a polynomial from a vector of coefficients.\n--\n-- Coefficients of higher degree entries are stored first.\npolyFromVecRep :: (UV.Unbox a, Floating a, Eq a)\n => UV.Vector a -> Maybe (Polynomial a)\npolyFromVecRep cs = Just . PolyVecRep $ UV.dropWhile (== 0) cs\n\n-- | Construct a polynomial from a list of (exponent, coefficient) pairs\n--\n-- Higher degree entries are stored first. Unlike vector representation, this\n-- representation doesn't need to store every entry, only those have a non-zero\n-- coefficient.\npolyFromExpCoefRep :: [(Int, a)] -> Maybe (Polynomial a)\npolyFromExpCoefRep dcs = if isSorted False (fmap fst dcs)\n then Just $ PolyExpCoefRep dcs\n else Nothing\n\npolyToVecRep :: Polynomial a -> Maybe (UV.Vector a)\npolyToVecRep (PolyVecRep xs) = Just xs\npolyToVecRep _ = Nothing\n\nmapPoly :: (UV.Unbox a, UV.Unbox b)\n => (a -> b)\n -> Polynomial a\n -> Polynomial b\nmapPoly f (PolyVecRep v) = PolyVecRep (UV.map f v)\nmapPoly f (PolyExpCoefRep ecs) = PolyExpCoefRep $ fmap (\\(e, c) -> (e, f c)) ecs\n\n{-| Divisor in the Bruun's FFT algorithm.\n'a' is some floating type, such as 'Double'\n\nThere are three types of divisors, each of them is represented by a constructor.\n-}\ndata BruunDivisor a =\n -- | \\( x^n - 1 \\)\n BruunDivisorMinus Int\n -- | \\( x^n + cx^{\\frac{n}{2}} + 1 \\)\n | BruunDivisorPlus Int a\n -- | \\( x + c \\)\n | BruunDivisorComplex (Complex a)\n deriving Show\n\ninstance (RealFloat a, AppxEq a) => AppxEq (BruunDivisor a) where\n (BruunDivisorMinus n1) ~= (BruunDivisorMinus n2) = n1 ~= n2\n (BruunDivisorPlus n1 c1) ~= (BruunDivisorPlus n2 c2) = n1 ~= n2 && c1 ~= c2\n (BruunDivisorComplex c1) ~= (BruunDivisorComplex c2) = c1 ~= c2\n (BruunDivisorComplex c1) ~= (BruunDivisorMinus n) = n == 1 && c1 ~= (-1)\n x@(BruunDivisorMinus _) ~= y@(BruunDivisorComplex _) = y ~= x\n _ ~= _ = False\n\ndivDegree :: BruunDivisor a -> Int\ndivDegree (BruunDivisorComplex _) = 1\ndivDegree (BruunDivisorPlus n _) = n\ndivDegree (BruunDivisorMinus n) = n\n\ndata RealOrComplexPolynomial a = RealPolynomial (Polynomial a)\n | ComplexPolynomial (Polynomial (Complex a))\n\ninstance (UV.Unbox a, Show a) => Show (RealOrComplexPolynomial a) where\n show (RealPolynomial p) = show p\n show (ComplexPolynomial p) = show p\n\n{-|\n Convert 'BruunDivisor' to 'Polynomial'\n-}\ndivToPoly :: forall a . (UV.Unbox a, RealFloat a)\n => BruunDivisor a\n -> RealOrComplexPolynomial a\ndivToPoly = \\case\n BruunDivisorMinus deg -> RealPolynomial $\n PolyExpCoefRep [(deg, 1), (0, -1)]\n BruunDivisorPlus deg c -> RealPolynomial $\n PolyExpCoefRep [(deg, 1), (deg `div` 2, c), (0, 1)]\n BruunDivisorComplex c -> ComplexPolynomial $\n PolyExpCoefRep [(1, 1), (0, c)]\n\ntype UnboxFloatingAppxEq a = (UV.Unbox a, Floating a, AppxEq a)\n\nmodPolyG :: (UnboxFloatingAppxEq a, RealFloat a)\n => RealOrComplexPolynomial a\n -> RealOrComplexPolynomial a\n -> Maybe (RealOrComplexPolynomial a)\nmodPolyG (RealPolynomial p) (RealPolynomial d) = RealPolynomial <$> modPoly p d\nmodPolyG (ComplexPolynomial p) (ComplexPolynomial d) =\n ComplexPolynomial <$> modPoly p d\nmodPolyG (RealPolynomial p) (ComplexPolynomial d) = ComplexPolynomial <$>\n mapPoly realToComplex p `modPoly` d\nmodPolyG (ComplexPolynomial p) (RealPolynomial d) = ComplexPolynomial <$>\n p `modPoly` mapPoly realToComplex d\n\n{-|\nCompute polynomial modulo. Only supports the situation where the first\npolynomial is represented by vector,and the second polynomial is represented by\ndegree-coefficient\n-}\nmodPoly :: UnboxFloatingAppxEq a\n => Polynomial a\n -> Polynomial a\n -> Maybe (Polynomial a)\nmodPoly _ (PolyExpCoefRep []) = Nothing\nmodPoly (PolyVecRep cs) (PolyExpCoefRep ic) = Just . PolyVecRep $ modPoly' cs ic\nmodPoly _ _ = Nothing\n\n{-|\nBasically follows the pseudo code from Wikipedia:\n > function n / d:\n > require d ≠ 0\n > q ← 0\n > r ← n # At each step n = d × q + r\n > while r ≠ 0 AND degree(r) ≥ degree(d):\n > t ← lead(r)/lead(d) # Divide the leading terms\n > q ← q + t\n > r ← r − t * d\n > return (q, r)\n-}\nmodPoly' :: forall a. UnboxFloatingAppxEq a\n => UV.Vector a\n -> [(Int, a)]\n -> UV.Vector a\nmodPoly' n d = UV.create $ do\n let dDeg = polyDegree . PolyExpCoefRep $ d\n let dHeadCoef :: a = snd . head $ d\n r <- UV.thaw n\n rDeg <- newSTRef (polyDegree . PolyVecRep $ n)\n rIsZero <- ((==0) <$> readSTRef rDeg) >>= newSTRef\n\n whileM_ ((&&) <$> (not <$> readSTRef rIsZero)\n <*> ((>=dDeg) <$> readSTRef rDeg))\n $ do\n rc <- readSTRef rDeg >>= readCoefAtDeg r\n let tc = rc / dHeadCoef\n tDeg <- (\\rDeg' -> rDeg' - dDeg) <$> readSTRef rDeg\n polySubtract' (r, rDeg, rIsZero) (polyMultiply' (tDeg, tc) d)\n\n rDeg_ <- readSTRef rDeg\n pure $ MUV.drop (MUV.length r - 1 - rDeg_) r\n\npolyDegree :: UV.Unbox a\n => Polynomial a\n -> Int\npolyDegree (PolyVecRep v) =\n let len = UV.length v\n in if len == 0\n then 0\n else len - 1\npolyDegree (PolyExpCoefRep ic) =\n case ic of\n [] -> 0\n (x:_) -> fst x\n\nreadCoefAtDeg :: UV.Unbox a => UV.MVector s a -> Int -> ST s a\nreadCoefAtDeg v d = MUV.read v (MUV.length v - 1 - d)\n\nupdateCoefAtDeg :: UV.Unbox a => UV.MVector s a -> Int -> a -> ST s ()\nupdateCoefAtDeg v d = MUV.write v (MUV.length v - 1 - d)\n\npolyMultiply' :: Num a => (Int, a) -> [(Int, a)] -> [(Int, a)]\npolyMultiply' (d, c) = fmap (\\(d', c') -> (d + d', c * c'))\n\npolySubtract' :: UnboxFloatingAppxEq a\n => (UV.MVector s a, STRef s Int, STRef s Bool)\n -> [(Int, a)]\n -> ST s ()\npolySubtract' (r, rDeg, rIsZero) dcs = do\n for_ dcs $ \\(d, c) -> do\n c' <- (\\x -> x - c) <$> readCoefAtDeg r d\n updateCoefAtDeg r d c'\n -- update 'rDeg' and 'rIsZero'\n -- search from rDeg to lower degrees, until a non-zero coefficient is found.\n rDeg_ <- readSTRef rDeg\n degM <- findM (fmap (~/= 0) . readCoefAtDeg r)\n [rDeg_, (rDeg_-1) .. 0]\n case degM of\n Nothing -> do\n writeSTRef rDeg 0\n writeSTRef rIsZero True\n Just d -> writeSTRef rDeg d\n\n-- | Factor a divisor into two divisors.\n--\n-- If current divisor is of degree 1, it can not be factored again,\n-- then 'Nothing' will be returned.\nfactorDivisor :: RealFloat a\n => BruunDivisor a\n -> Maybe (BruunDivisor a, BruunDivisor a)\nfactorDivisor (BruunDivisorComplex _) = Nothing\nfactorDivisor (BruunDivisorMinus n) =\n if n == 1\n then Nothing\n else\n let n' = n `div` 2\n in Just (BruunDivisorMinus n', BruunDivisorPlus n' 0)\nfactorDivisor (BruunDivisorPlus n c) =\n if | n == 1 -> Nothing\n | n `rem` 4 == 0 -> Just $ factorDPToDPs n c\n | otherwise -> Just $ factorDPToDCs c\n\n-- | Factor divisor in plus form into two divisors in plus form.\n-- Doesn't check for pre-condition.\nfactorDPToDPs :: Floating a => Int -> a -> (BruunDivisor a, BruunDivisor a)\nfactorDPToDPs n c =\n let n' = n `div` 2\n c' = sqrt (2 - c)\n in assert (n' >= 2)\n (BruunDivisorPlus n' c', BruunDivisorPlus n' (-c'))\n\n-- | Factor divisor in plus form into two divisors in complex form.\n-- Doesn't check for pre-condition.\nfactorDPToDCs :: RealFloat a\n => a\n -> (BruunDivisor a, BruunDivisor a)\nfactorDPToDCs c =\n (BruunDivisorComplex (c' / 2 + d), BruunDivisorComplex (c' / 2 - d))\n where\n c' = realToComplex c\n d = sqrt (c' * c' - 4) / 2\n\n", "meta": {"hexsha": "f124457c51bec8369dd44e317f1ff83f98099ddc", "size": 9380, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/lib/Isumi/Math/FFT/Internal/Polynomial.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/Polynomial.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/Polynomial.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": 34.1090909091, "max_line_length": 80, "alphanum_fraction": 0.6135394456, "num_tokens": 2884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5128039682533224}} {"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DerivingVia #-}\n{-# Language FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# Language MultiParamTypeClasses #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE UndecidableInstances #-}\nmodule Geometry.Intersections\n ( Intersections (..)\n , intersections, isIntersecting\n ) where\n\nimport Data.Complex\nimport Data.List (nub)\n\nimport Geometry.Base\nimport Geometry.Line\nimport Geometry.Circle\nimport Geometry.Polygon\nimport Geometry.Plot\nimport Geometry.Decorations\n\n--------------------------------------------------------------------------------\n-- | Class provides `intersections'` function returning a list (possible empty)\n-- of all potential intersection points (co-dimension 1).\nclass (Manifold a, Manifold b) => Intersections a b where\n intersections' :: a -> b -> [Cmp]\n\n-- | Filters intersection points, keeping ones belonging to given manifolds.\nintersections :: (Figure a, Figure b, Intersections a b)\n => a -> b -> [Cmp]\nintersections a b \n | isTrivial a = filter (isContaining b) [cmp $ refPoint a]\n | isTrivial b = filter (isContaining a) [cmp $ refPoint b]\n | otherwise =\n nub $\n filter (isContaining a) $\n filter (isContaining b) $\n intersections' a b\n\n-- | Returns `True` if tho curves have intersection points.\nisIntersecting :: (Figure a, Figure b, Intersections a b) => a -> b -> Bool\nisIntersecting a b = not . null $ intersections a b\n\ninstance (Figure a, Figure b, Intersections a b) =>\n Intersections a (Maybe b) where\n intersections' a = maybe [] (intersections' a) \n\ninstance (Figure a, Figure b, Intersections b a) =>\n Intersections (Maybe a) b where\n intersections' = flip intersections'\n\ninstance {-# OVERLAPPING #-}\n (Figure a, Figure b, Intersections b a) =>\n Intersections (Maybe a) (Maybe b) where\n intersections' a = maybe [] (intersections' a)\n\ninstance (Figure a, Figure b, Intersections a b) =>\n Intersections a (Decorated b) where\n intersections' a = intersections a . fromDecorated\n\ninstance (Figure a, Figure b, Intersections b a) =>\n Intersections (Decorated a) b where\n intersections' = flip intersections'\n\ninstance {-# OVERLAPPING #-}\n (Figure a, Figure b, Intersections a b) =>\n Intersections (Decorated a) (Decorated b) where\n intersections' = intersections' . fromDecorated\n\n--------------------------------------------------------------------------------\n\nintersectionCC c1 c2 | d == 0 || b < 0 = []\n | b == 0 = [x]\n | b > 0 = [x, conjugate x]\n where\n r1 = radius c1\n r2 = radius c2\n d = magnitude (center c1 - center c2)\n a = r1**2-r2**2+d**2\n b = -(r2-r1-d)*(r2-r1+d)*(r2+r1-d)*(r2+r1+d)\n x = scale (1/(2*d)) $ a :+ sqrt b\n\nintersectionCL c l | b > r = []\n | b == r = [0:+b]\n | b < r = [a:+b, (-a):+b]\n where\n b = getY (refPoint l)\n r = radius c\n a = sqrt (r**2 - b**2)\n\n--------------------------------------------------------------------------------\n\ninstance Intersections Line Line where\n intersections' l1 l2\n | l2 `isContaining` refPoint l1 = [refPoint l1]\n | l1 `isContaining` refPoint l2 = [refPoint l2]\n | otherwise = lineIntersection l1 l2\n\ninstance Intersections Line Circle where\n intersections' l cir =\n invt <$> intersectionCL (t cir) (t l)\n where\n t :: Trans x => x -> x\n t = rotate (-a) . translate' (negate (center cir))\n invt = translate' (center cir) . rotate a\n a = angle l\n\ninstance Intersections Line Polyline where\n intersections' l = foldMap (intersections l) . segments . closePolyline\n\n--------------------------------------------------------------------------------\n\ninstance Intersections Circle Line where\n intersections' = flip intersections'\n\ninstance Intersections Circle Circle where\n intersections' cir1 cir2 =\n invt <$> intersectionCC (t cir1) (t cir2)\n where\n t = rotate (-a) . translate' (negate c1)\n invt = translate' c1 . rotate a\n c1 = center cir1\n c2 = center cir2\n a = azimuth c1 c2\n\ninstance Intersections Circle Polyline where\n intersections' c = foldMap (intersections c) . segments . closePolyline\n\n--------------------------------------------------------------------------------\n\ninstance Intersections Polyline Line where\n intersections' = flip intersections'\n\ninstance Intersections Polyline Circle where\n intersections' = flip intersections'\n \ninstance Intersections Polyline Polyline where\n intersections' p = foldMap (intersections p) . segments . closePolyline\n\n--------------------------------------------------------------------------------\n\nderiving via Line instance\n (Manifold a, Intersections a Line) => Intersections a Ray\n\ninstance Intersections Ray Line where\n intersections' = intersections' . asLine \n\ninstance Intersections Ray Polyline where\n intersections' = intersections' . asLine \n\ninstance Intersections Ray Circle where\n intersections' = intersections' . asLine \n\n--------------------------------------------------------------------------------\n\nderiving via Line instance\n (Manifold a, Intersections a Line) => Intersections a Segment\n\ninstance Intersections Segment Line where\n intersections' = intersections' . asLine \n\ninstance Intersections Segment Polyline where\n intersections' = intersections' . asLine \n\ninstance Intersections Segment Circle where\n intersections' = intersections' . asLine \n\n--------------------------------------------------------------------------------\n\nderiving via Polyline instance\n (Manifold a, Intersections a Polyline) => Intersections a Polygon\n\ninstance Intersections Polygon Line where\n intersections' = intersections' . asPolyline\n\ninstance Intersections Polygon Polyline where\n intersections' = intersections' . asPolyline\n\ninstance Intersections Polygon Circle where\n intersections' = intersections' . asPolyline\n\n--------------------------------------------------------------------------------\n\nderiving via Polygon instance\n (Manifold a, Intersections a Polyline) => Intersections a Triangle\n\ninstance Intersections Triangle Line where\n intersections' = intersections' . asPolyline\n\ninstance Intersections Triangle Polyline where\n intersections' = intersections' . asPolyline\n\ninstance Intersections Triangle Circle where\n intersections' = intersections' . asPolyline\n\n--------------------------------------------------------------------------------\n\nderiving via Polygon instance\n (Manifold a, Intersections a Polyline) => Intersections a Rectangle\n\ninstance Intersections Rectangle Line where\n intersections' = intersections' . asPolyline\n\ninstance Intersections Rectangle Polyline where\n intersections' = intersections' . asPolyline\n\ninstance Intersections Rectangle Circle where\n intersections' = intersections' . asPolyline\n\n--------------------------------------------------------------------------------\n\ninstance Pnt a => Intersections (Plot a) Line where\n intersections' p l = intersectionsP p l $ intersections (asPolyline p) l\n\ninstance Pnt a => Intersections (Plot a) Circle where\n intersections' p c = intersectionsP p c $ intersections (asPolyline p) c\n \ninstance Pnt a => Intersections (Plot a) Polyline where\n intersections' p pl = intersectionsP p pl $ intersections (asPolyline p) pl\n\ninstance (Pnt a, Manifold b, Intersections (Plot a) b) => Intersections b (Plot a) where\n intersections' = flip intersections'\n\ninstance {-# OVERLAPPING #-}\n (Pnt a, Pnt b) => Intersections (Plot a) (Plot b) where\n intersections' p1 p2 = intersectionsP p1 p2 $\n intersections (asPolyline p1) (asPolyline p2)\n\n--------------------------------------------------------------------------------\n\nderiving via (Plot a) instance\n (Manifold b, Affine a, Trans a, Intersections b (Plot a)) => Intersections b (ClosedPlot a)\n\ninstance Pnt a => Intersections (ClosedPlot a) Line where\n intersections' p l = intersectionsP p l $ intersections (asPolyline p) l\n\ninstance Pnt a => Intersections (ClosedPlot a) Polyline where\n intersections' p pl = intersectionsP p pl $ intersections (asPolyline p) pl\n\ninstance Pnt a => Intersections (ClosedPlot a) Circle where\n intersections' p c = intersectionsP p c $ intersections (asPolyline p) c\n\n\n", "meta": {"hexsha": "41680e72e704f5e507e2162865809d5e889e2552", "size": 8276, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Geometry/Intersections.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/Intersections.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/Intersections.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": 33.7795918367, "max_line_length": 93, "alphanum_fraction": 0.6230062832, "num_tokens": 1899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5127894110999393}} {"text": "\n{-# LANGUAGE CPP #-}\n\n-- | Binary lists are lists whose number of elements is a power of two.\n-- This data structure is efficient for some computations like:\n--\n-- * Splitting a list in half.\n--\n-- * Appending two lists of the same length.\n--\n-- * Extracting an element from the list.\n--\n-- All the functions exported are total except for 'fromListWithDefault'.\n-- It is impossible for the user of this library to create a binary list\n-- whose length is /not/ a power of two.\n--\n-- Since many names in this module clash with the names of some \"Prelude\"\n-- functions, you probably want to import this module this way:\n--\n-- > import Data.BinaryList (BinList,Exponent)\n-- > import qualified Data.BinaryList as BL\n--\n-- Remember that binary lists are an instance of the 'Foldable' and 'Traversable'\n-- classes. If you are missing a function here, look for functions using those\n-- instances.\n--\n-- Note that some functions like 'replicate', 'generate', or 'take', don't use\n-- the length of the list as argument, but the exponent of its length expressed\n-- as a power of two. Throughout this document, this is referred\n-- as the /length exponent/. For example, if the list has length 16, its length exponent\n-- is 4 since 2^4 = 16. Therefore @replicate 4 0@ will create a list with 16 zeroes.\n-- Keep this in mind when using this library. Note as well that this implies that\n-- there is no need to check that the length argument is or is not a power of two.\n--\nmodule Data.BinaryList (\n -- * Type\n BinList\n , Exponent\n -- * Construction\n , singleton\n , append\n , replicate\n , replicateA\n , replicateAR\n , generate\n , generateM\n -- * Queries\n , lengthExponent\n#if !MIN_VERSION_base(4,8,0)\n , length\n#endif\n , lookup\n , head\n , last\n -- * Deconstruction\n , split\n , take\n , takeEnd\n -- * Transformation\n , replace\n , reverse\n -- * Tuples\n , joinPairs\n , disjoinPairs\n -- * Zipping and Unzipping\n , zip , unzip\n , zipWith\n -- * Lists\n -- ** From list\n , fromList\n , fromListWithDefault\n , fromListSplit\n -- ** To list\n , toListFilter\n , toListSegment\n -- * Others\n , traverseSegment\n -- * Example: Radix-2 FFT\n -- $fft\n ) where\n\nimport Prelude hiding\n ( map, head, last\n , reverse, replicate\n , take, lookup\n , zip, unzip, zipWith\n , foldr1, length, foldr\n )\n#if MIN_VERSION_base(4,8,0)\nimport Prelude (length, foldr, foldr1)\n#endif\nimport Data.Foldable (fold,toList)\nimport Foreign.Storable (sizeOf)\nimport Data.List (find)\nimport Data.BinaryList.Internal\nimport Control.Applicative.Backwards\nimport Control.Arrow ((***))\nimport Control.Monad.Trans.State\n ( StateT (..)\n , evalStateT ,evalState\n , runState\n , get ,modify )\nimport Control.Monad.Trans.Class (lift)\nimport Data.Functor.Identity (Identity (..))\nimport Control.Applicative.PhantomState\nimport Data.Word (Word8)\n\n-- GHC-7.8 compatibility\n#if !MIN_VERSION_base(4,8,0)\n\nimport qualified Prelude\nimport Data.Foldable (Foldable (..))\nimport Data.Traversable (Traversable (..))\nimport Control.Applicative (Applicative (..), (<$>))\nimport Data.Monoid (mappend)\n\n-- | /O(1)/. Number of elements in the list.\nlength :: BinList a -> Int\nlength = (2^) . lengthExponent\n\n#endif\n\n\n-- | An exponent.\ntype Exponent = Word8\n\n-- | /O(1)/. Build a list with a single element.\nsingleton :: a -> BinList a\nsingleton = ListEnd\n\n-- | /O(1)/. Given a binary list @l@ with length @2^k@:\n--\n-- > lengthExponent l = k\n--\nlengthExponent :: BinList a -> Exponent\nlengthExponent (ListNode n _ _) = n\nlengthExponent (ListEnd _) = 0\n\n{-# RULES\n \"Data.BinaryList: length equality\"\n forall xs ys . length xs == length ys = lengthExponent xs == lengthExponent ys\n #-}\n\n-- | /O(log n)/. Lookup an element in the list by its index (starting from 0).\n-- If the index is out of range, 'Nothing' is returned.\nlookup :: BinList a -> Int -> Maybe a\nlookup (ListNode n l r) i =\n let m = 2^(n-1) -- Number of elements in a single branch\n in if i < m\n then lookup l i -- Lookup in the left branch\n else lookup r $ i - m -- Lookup in the right branch\nlookup (ListEnd x) 0 = Just x\nlookup _ _ = Nothing\n\n-- | /O(log n)/. Replace a single element in the list. If the index is\n-- out of range, returns the original list.\nreplace :: Int -- ^ Index to look for\n -> a -- ^ Element to insert\n -> BinList a -> BinList a\nreplace i0 y = go i0\n where\n go i (ListNode n l r) =\n let m = 2^(n-1)\n in if i < m\n then ListNode n (go i l) r\n else ListNode n l (go (i-m) r)\n go 0 (ListEnd _) = ListEnd y\n go _ e = e\n\n-- | /O(1)/. Append two binary lists. This is only possible\n-- if both lists have the same length. If this condition\n-- is not hold, 'Nothing' is returned.\nappend :: BinList a -> BinList a -> Maybe (BinList a)\nappend xs ys =\n let i = lengthExponent xs\n in if i == lengthExponent ys\n then Just $ ListNode (i+1) xs ys\n else Nothing\n\n-- | /O(1)/. Split a binary list into two sublists of half the length,\n-- unless the list only contains one element. In that case, it\n-- just returns that element.\nsplit :: BinList a -> Either a (BinList a,BinList a)\nsplit (ListNode _ l r) = Right (l,r)\nsplit (ListEnd x) = Left x\n\n-- | /O(log n)/. Calling @take n xs@ returns the first @min (2^n) (length xs)@ elements of @xs@.\ntake :: Exponent -> BinList a -> BinList a\ntake k xs@(ListNode n l _) = if k >= n then xs else take k l\ntake _ xs = xs\n\n-- | /O(log n)/. Calling @takeEnd n xs@ returns the last @min (2^n) (length xs)@ elements of @xs@.\ntakeEnd :: Exponent -> BinList a -> BinList a\ntakeEnd k xs@(ListNode n _ r) = if k >= n then xs else takeEnd k r\ntakeEnd _ xs = xs\n\n-- | Calling @replicateA n f@ builds a binary list collecting the results of\n-- executing @2^n@ times the applicative action @f@.\nreplicateA :: Applicative f => Exponent -> f a -> f (BinList a)\nreplicateA n f = go n\n where\n go 0 = ListEnd <$> f\n go i = let b = go (i-1)\n in ListNode <$> pure i <*> b <*> b\n\n-- | The same as 'replicateA', but the actions are executed in reversed order.\nreplicateAR :: Applicative f => Exponent -> f a -> f (BinList a)\nreplicateAR n = forwards . replicateA n . Backwards\n\n{-# RULES\n \"Data.BinaryList: map reverse/replicateA\"\n forall i f . map reverse (replicateA i f) = replicateAR i f\n #-}\n\n{-# RULES\n \"Data.BinaryList: map reverse/replicateAR\"\n forall i f . map reverse (replicateAR i f) = replicateA i f\n #-}\n\n-- | /O(log n)/. Calling @replicate n x@ builds a binary list with\n-- @2^n@ occurences of @x@.\nreplicate :: Exponent -> a -> BinList a\nreplicate n = runIdentity . replicateA n . Identity\n\n{-# RULES\n \"Data.BinaryList: map/replicate\"\n forall f n x . map f (replicate n x) = replicate n (f x)\n #-}\n\n-- | /O(n)/. Build a binary list with the given length exponent (see 'lengthExponent')\n-- by applying a function to each index.\ngenerate :: Exponent -> (Int -> a) -> BinList a\ngenerate l f = evalState (replicateA l $ fmap f get <* modify (+1)) 0\n\n-- | Like 'generate', but the generator function returns a value in a 'Monad'.\n-- Therefore, the result is as well contained in a 'Monad'.\ngenerateM :: (Applicative m, Monad m) => Exponent -> (Int -> m a) -> m (BinList a)\ngenerateM l f = evalStateT (replicateA l $ (get >>= lift . f) <* modify (+1)) 0\n\n-- | /O(log n)/. Get the first element of a binary list.\nhead :: BinList a -> a\nhead (ListNode _ l _) = head l\nhead (ListEnd x) = x\n\n-- | /O(log n)/. Get the last element of a binary list.\nlast :: BinList a -> a\nlast (ListNode _ _ r) = last r\nlast (ListEnd x) = x\n\n-- | /O(n)/. Reverse a binary list.\nreverse :: BinList a -> BinList a\n{-# INLINE[2] reverse #-}\nreverse (ListNode n l r) = ListNode n (reverse r) (reverse l)\nreverse xs = xs\n\n{-# RULES\n \"Data.BinaryList: reverse/reverse\"\n forall xs. reverse (reverse xs) = xs\n #-}\n\n------------------------------\n-- Transformations with tuples\n\n-- | /O(n)/. Transform a list of pairs into a flat list. The\n-- resulting list will have twice more elements than the\n-- original.\njoinPairs :: BinList (a,a) -> BinList a\n{-# INLINE[1] joinPairs #-}\njoinPairs (ListEnd (x,y)) = ListNode 1 (ListEnd x) (ListEnd y)\njoinPairs (ListNode n l r) = ListNode (n+1) (joinPairs l) (joinPairs r)\n\n-- | /O(n)/. Opposite transformation of 'joinPairs'. It halves\n-- the number of elements of the input. As a result, when\n-- applied to a binary list with a single element, it returns\n-- 'Nothing'.\ndisjoinPairs :: BinList a -> Maybe (BinList (a,a))\n{-# INLINE [1] disjoinPairs #-}\ndisjoinPairs (ListEnd _) = Nothing\ndisjoinPairs xs = Just $ disjoinPairsNodes xs\n\ndisjoinPairsNodes :: BinList a -> BinList (a,a)\ndisjoinPairsNodes (ListNode _ (ListEnd x) (ListEnd y)) = ListEnd (x,y)\ndisjoinPairsNodes (ListNode n l r) = ListNode (n-1) (disjoinPairsNodes l) (disjoinPairsNodes r)\ndisjoinPairsNodes _ = error \"disjoinPairsNodes: bug. Please, report this with an example input.\"\n\n{-# RULES\n \"Data.BinaryList: disjoinPairs/joinPairs\"\n forall xs . disjoinPairs (joinPairs xs) = Just xs\n #-}\n\n{-# RULES\n \"Data.BinaryList: disjoinPairs/map/joinPairs\"\n forall f xs . disjoinPairs (map f (joinPairs xs)) = Just (map (f *** f) xs)\n #-}\n\n-- | Expression @pairBuilder f xs@ is equivalent to @joinPairs (map f xs)@, but does\n-- not build any intermediate structure. Used for rewriting rules.\npairBuilder :: (a -> (b,b)) -> BinList a -> BinList b\n{-# INLINE[0] pairBuilder #-}\npairBuilder f = go\n where\n go (ListEnd x) = let (a,b) = f x in ListNode 1 (ListEnd a) (ListEnd b)\n go (ListNode n l r) = ListNode (n+1) (go l) (go r)\n\n{-# RULES\n \"Data.BinaryList: joinPairs/map\"\n forall f xs . joinPairs (map f xs) = pairBuilder f xs\n #-}\n\n-- | Expression @zipAndJoing f g xs ys@ is equivalent to @pairBuilder f (zipWith g xs ys)@,\n-- but does not build any intermediate structure. Used for rewriting rules.\nzipAndJoin :: (c -> (d,d)) -> (a -> b -> c) -> BinList a -> BinList b -> BinList d\nzipAndJoin f g = go\n where\n -- Recursion\n go xs@(ListNode n l r) ys@(ListNode n' l' r')\n -- If both lists have the same length, recurse assuming it\n -- to avoid comparisons.\n | n == n' = ListNode (n+1) (goEquals l l') (goEquals r r')\n -- If the first list is larger, the second fits entirely in\n -- the left branch of the first.\n | n > n' = go l ys\n -- If the second list is larger, the first fits entirely in\n -- the left branch of the second.\n | otherwise = go xs l'\n go xs ys = let (x,y) = f $ g (head xs) (head ys)\n in ListNode 1 (ListEnd x) (ListEnd y)\n -- Recursion assuming both lists have the same length\n goEquals (ListNode n l r) (ListNode _ l' r') =\n ListNode (n+1) (goEquals l l') (goEquals r r')\n goEquals (ListEnd x) (ListEnd y) =\n let (x',y') = f $ g x y\n in ListNode 1 (ListEnd x') (ListEnd y')\n goEquals _ _ = undefined -- This can't happen!\n\n{-# RULES\n \"Data.BinaryList: pairBuilder/zipWith\"\n forall f g xs ys . pairBuilder f (zipWith g xs ys) = zipAndJoin f g xs ys\n #-}\n\n------------------------\n-- Zipping and Unzipping\n\n-- | /O(n)/. Zip two binary lists using an operator.\nzipWith :: (a -> b -> c) -> BinList a -> BinList b -> BinList c\n{-# INLINE[1] zipWith #-}\nzipWith f = go\n where\n -- Recursion\n go xs@(ListNode n l r) ys@(ListNode n' l' r')\n -- If both lists have the same length, recurse assuming it\n -- to avoid comparisons.\n | n == n' = ListNode n (goEquals l l') (goEquals r r')\n -- If the first list is larger, the second fits entirely in\n -- the left branch of the first.\n | n > n' = go l ys\n -- If the second list is larger, the first fits entirely in\n -- the left branch of the second.\n | otherwise = go xs l'\n go xs ys = ListEnd $ f (head xs) (head ys)\n -- Recursion assuming both lists have the same length\n goEquals (ListNode n l r) (ListNode _ l' r') =\n ListNode n (goEquals l l') (goEquals r r')\n goEquals (ListEnd x) (ListEnd y) = ListEnd (f x y)\n goEquals _ _ = undefined -- this can't happen\n\n-- | /O(n)/. Zip two binary lists in pairs.\nzip :: BinList a -> BinList b -> BinList (a,b)\n{-# INLINE zip #-}\nzip = zipWith (,)\n\n-- | /O(n)/. Unzip a binary list of pairs.\nunzip :: BinList (a,b) -> (BinList a, BinList b)\n{-# INLINE[1] unzip #-}\nunzip (ListEnd (x,y)) = (ListEnd x, ListEnd y)\nunzip (ListNode n l r) =\n let (la,lb) = unzip l\n (ra,rb) = unzip r\n in (ListNode n la ra, ListNode n lb rb)\n\n-- | Expression @unzipMap f xs@ is equivalent to @unzip (map f xs)@, but\n-- does not create any intermediate structure.\nunzipMap :: ((a,b) -> (c,d)) -> BinList (a,b) -> (BinList c,BinList d)\nunzipMap f = go\n where\n go (ListEnd p) = ListEnd *** ListEnd $ f p\n go (ListNode n l r) =\n let (lc,ld) = go l\n (rc,rd) = go r\n in (ListNode n lc rc, ListNode n ld rd)\n\n{-# RULES\n \"Data.BinaryList: unzip/map\"\n forall f xs . unzip (map f xs) = unzipMap f xs\n #-}\n\n-----------------------------\n-- Transforming from/to lists\n\n-- | /O(log n)/. Calculate the exponent of a positive integer number expressed\n-- as a power of two.\nexponentInBasisTwo :: Int -> Maybe Exponent\nexponentInBasisTwo 1 = Just 0\nexponentInBasisTwo n =\n if even n\n then fmap (+1) $ exponentInBasisTwo $ div n 2\n else Nothing\n\n-- | /O(n)/. Build a binary list from a linked list. If the input list\n-- has length different from a power of two, it returns 'Nothing'.\nfromList :: [a] -> Maybe (BinList a)\nfromList xs = fmap builder . exponentInBasisTwo $ Prelude.length xs\n where\n builder l = evalState (replicateA l $ StateT $ \\(h:t) -> pure (h,t)) xs\n\n-- | /O(1)/. This is the last exponent that has power of two defined in the type 'Int'.\n--\n-- /Note: This value is system dependent, since the type 'Int' varies in size/\n-- /from system to system./\n--\nlastExponentOfTwo :: Exponent\nlastExponentOfTwo = fromIntegral $ 8 * sizeOf (undefined :: Int) - 2\n\n-- | /O(1)/. Calculate the next power of two exponent, if there is any. It is possible\n-- to not find a next one since the type 'Int' is finite. If the input is\n-- already a power of two, its exponent is returned.\nnextExponentOfTwo :: Int -> Maybe Exponent\nnextExponentOfTwo n = find (\\i -> n <= 2^i) [0 .. lastExponentOfTwo]\n\n-- | /O(n)/. Build a binary list from a linked list. If the input list\n-- has length different from a power of two, fill to the next\n-- power of two with a default element.\n--\n-- /Warning: this function crashes if the input list length is larger than any/\n-- /power of two in the type 'Int'. However, this is very unlikely./\nfromListWithDefault :: a -> [a] -> BinList a\nfromListWithDefault e xs =\n let l = Prelude.length xs\n in case nextExponentOfTwo l of\n Just n ->\n evalState (replicateA n $ StateT $\n \\ys -> pure $ case ys of\n (h:t) -> (h,t )\n _ -> (e,[])\n ) xs\n _ -> error \"[binary-list] fromListWithDefault: input list is too big.\"\n\n-- | /O(n)/. Build a binary list from a linked list. It returns a binary list\n-- with length @2 ^ n@ (where @n@ is the supplied 'Int' argument), and\n-- the list of elements of the original list that were not used. If the\n-- input list is shorter than @2 ^ n@, a default element will be used to\n-- complete the binary list. This method for building binary lists is faster\n-- than both 'fromList' and 'fromListWithDefault'.\nfromListSplit :: a -- ^ Default element\n -> Exponent -- ^ Length exponent\n -> [a] -- ^ Input list\n -> (BinList a, [a])\nfromListSplit e n =\n runState $ replicateA n $ StateT $\n \\xs -> pure $ case xs of\n (h:t) -> (h,t )\n _ -> (e,[])\n\n-- | /O(n)/. Create a list from the elements of a binary list matching a given\n-- condition.\ntoListFilter :: (a -> Bool) -> BinList a -> [a]\n{-# INLINE toListFilter #-}\ntoListFilter c = foldr (\\x -> if c x then (x:) else id) []\n\n-- | /O(n)/. Create a list extracting a sublist of elements from a binary list.\ntoListSegment :: Int -> Int -> BinList a -> [a]\n{-# INLINE toListSegment #-}\ntoListSegment s e xs = runPhantomState (traverseSegment (changeState . (:)) s e xs) []\n\n-- | Apply an applicative action to every element in a segment of a binary list, from left to right.\ntraverseSegment :: Applicative f => (a -> f ()) -> Int -> Int -> BinList a -> f ()\n{-# INLINE traverseSegment #-}\ntraverseSegment f s e xs\n | s > e = pure ()\n | e < 0 = pure ()\n | s >= length xs = pure ()\n | otherwise = traverseSegmentFromTo f (max 0 s) e xs\n\ntraverseSegmentFromTo :: Applicative f => (a -> f ()) -> Int -> Int -> BinList a -> f ()\n{-# INLINE traverseSegmentFromTo #-}\ntraverseSegmentFromTo f = go\n where\n go s e (ListNode n l r) =\n let k = 2^(n-1)\n in if s >= k\n -- Sublist is contained in right portion\n then go (s - k) (e - k) r\n else if e < k\n -- Sublist is contained in left portion\n then go s e l\n -- Sublist is divided in both portions\n else traverseSegmentFrom f s l *> traverseSegmentTo f (e - k) r\n go _ _ (ListEnd x) = f x\n\ntraverseSegmentFrom :: Applicative f => (a -> f ()) -> Int -> BinList a -> f ()\n{-# INLINE traverseSegmentFrom #-}\ntraverseSegmentFrom f = go\n where\n go s (ListNode n l r) =\n let k = 2^(n-1)\n in if s >= k\n -- Sublist is contained in right portion\n then go (s - k) r\n -- Sublist is divided in both portions, but right\n -- portion is taken entirely\n else go s l *> traverseFull f r\n go _ (ListEnd x) = f x\n\ntraverseSegmentTo :: Applicative f => (a -> f ()) -> Int -> BinList a -> f ()\n{-# INLINE traverseSegmentTo #-}\ntraverseSegmentTo f = go\n where\n go e (ListNode n l r) =\n let k = 2^(n-1)\n in if e < k\n -- Sublist is contained in left portion\n then go e l\n -- Sublist is divided in both portions, but left\n -- portion is taken entirely\n else traverseFull f l *> go (e - k) r\n go _ (ListEnd x) = f x\n\ntraverseFull :: Applicative f => (a -> f ()) -> BinList a -> f ()\n{-# INLINE traverseFull #-}\ntraverseFull f = go\n where\n go (ListEnd x) = f x\n go (ListNode _ l r) = go l *> go r\n\n------------------------------------------------\n------------------------------------------------\n\n-----------------------------\n-- Show and Functor instances\n\ninstance Show a => Show (BinList a) where\n show = show . toList\n\n{- Internal map\n\nAlthough we encourage the use of 'fmap', we define fmap as a custom 'map'\nfunction and inline 'fmap' to make them equivalent, so writing 'fmap' is\nactually writing 'map'. We do this to use 'map' in rewriting rules.\n\n-}\n\nmap :: (a -> b) -> BinList a -> BinList b\n{-# INLINE[1] map #-}\nmap f = go\n where\n go (ListEnd x) = ListEnd (f x)\n go (ListNode n l r) = ListNode n (go l) (go r)\n\ninstance Functor BinList where\n {-# INLINE fmap #-}\n fmap = map\n\ninstance Foldable BinList where\n -- Folding\n foldr1 f = go\n where\n go (ListEnd x) = x\n go (ListNode _ l r) = f (go l) (go r)\n --\n fold = foldr1 mappend\n foldl1 = foldr1\n foldMap f = fold . fmap f\n#if MIN_VERSION_base(4,8,0)\n length = (2^) . lengthExponent\n#endif\n\ninstance Traversable BinList where\n sequenceA (ListEnd f) = ListEnd <$> f\n sequenceA (ListNode n l r) = ListNode <$> pure n <*> sequenceA l <*> sequenceA r\n\n-----------------------------\n-- Example: Radix-2 FFT\n\n{- $fft\n\nThis is an example demonstrating the use of binary lists to calculate the Discrete\nFourier Transform of complex vectors with the Radix-2 Fast Fourier Transform algorithm.\n\n> import Data.BinaryList (BinList)\n> import qualified Data.BinaryList as BL\n> \n> import Data.Complex\n> import Data.Maybe (fromJust)\n> \n> i :: Complex Double\n> i = 0 :+ 1\n> \n> fft :: BinList (Complex Double) -> BinList (Complex Double)\n> fft xs =\n> case BL.disjoinPairs xs of\n> Nothing -> xs\n> Just ps ->\n> let (evens,odds) = BL.unzip ps\n> n = BL.lengthExponent xs - 1\n> q = negate $ pi * i / fromIntegral (2^n)\n> twiddles = BL.generate n $ \\k -> exp $ q * fromIntegral k\n> oddsfft = BL.zipWith (*) twiddles $ fft odds\n> evensfft = fft evens\n> in fromJust $\n> BL.append (BL.zipWith (+) evensfft oddsfft)\n> (BL.zipWith (-) evensfft oddsfft)\n\n-}\n", "meta": {"hexsha": "a33de6775d1ac4d5acda656ffdb648006163ee04", "size": 20734, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/BinaryList.hs", "max_stars_repo_name": "Daniel-Diaz/binary-list", "max_stars_repo_head_hexsha": "d6c9d276134c4bfd0d9497e85e05606f43d8ee97", "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/BinaryList.hs", "max_issues_repo_name": "Daniel-Diaz/binary-list", "max_issues_repo_head_hexsha": "d6c9d276134c4bfd0d9497e85e05606f43d8ee97", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-03-28T18:01:13.000Z", "max_issues_repo_issues_event_max_datetime": "2015-03-28T23:24:27.000Z", "max_forks_repo_path": "Data/BinaryList.hs", "max_forks_repo_name": "Daniel-Diaz/binary-list", "max_forks_repo_head_hexsha": "d6c9d276134c4bfd0d9497e85e05606f43d8ee97", "max_forks_repo_licenses": ["BSD-3-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.7687296417, "max_line_length": 100, "alphanum_fraction": 0.6144014662, "num_tokens": 5990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5125615268136601}} {"text": "{-# LANGUAGE RecordWildCards #-}\nmodule Q.Options.Black76\n (\n module Q.Options\n , Black76(..)\n , atmf\n , euOption\n , eucall\n , euput\n )\n where\n\nimport Q.Options\nimport Q.Types\nimport Statistics.Distribution (cumulative, density)\nimport Statistics.Distribution.Normal (standard)\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 b76@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 | cp == Put = Delta $ putDelta\n\n-- | see 'euOption'\neuput b76 = euOption b76 Put\n\n-- | see 'euOption'\neucall b76 = euOption b76 Call\n\ndPlus (Forward f) (Vol sigma) (Strike k) (YearFrac t) =\n recip (sigma * sqrt t) * (log (f/k) + (0.5 * sigma * sigma) * t)\ndMinus (Forward f) (Vol sigma) (Strike k) (YearFrac t) =\n recip (sigma * sqrt t) * (log (f/k) - (0.5 * sigma * sigma) * t)\n", "meta": {"hexsha": "39e902956c49eefecf473c44be05e0dbc8c841cc", "size": 1803, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Q/Options/Black76.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/Black76.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/Black76.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": 29.5573770492, "max_line_length": 79, "alphanum_fraction": 0.589572934, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5121147278983059}} {"text": "{-# LANGUAGE FlexibleContexts, TypeOperators, RankNTypes, GeneralizedNewtypeDeriving, DeriveFunctor, PolyKinds, GADTs #-}\n\nmodule Qubit where\n\nimport Linear.V2\nimport Linear.V1\nimport Linear.Vector\nimport Vec\nimport Data.Complex\nimport Data.Functor.Compose\nimport Data.Functor.Product\nimport Data.Functor.Identity\nimport Cat\nimport Data.Coerce\n\ntype Kron = Compose\ntype Spin = V2\ntype QuBit = V2\ntype C = Complex Double\n\ntype DSum = Product\n\nnewtype FKron f g a = FKron [(f a, g a)]\n\ntype Fock a = Q [a] -- a \"fock space\" over a. No assumption of anti symmettric or symmettric. \nnewtype Anti a = Anti (Fock a)\n-- for antisymmettric space, keep list sorted (canonical form).\n-- liftAnti1 :: (a -> Q a) -> ([a] -> Q [a])\n-- liftAnti2 :: (a,a) -> Q (a,a) -> ([a] -> Q [a])\n-- \n\n-- this is fock system as a sparse indictaor matrix. We can also do the form of occupation number Q (V Bool)\n\nvac :: Fock a\nvac = pure []\n\ntype SHO = Q Int\n\nshovac :: SHO \nshovac = pure 0\nadag :: Int -> SHO\nadag n = W [(n + 1, sqrt (fromInteger (toInteger n) + 1))]\nagad 0 = mempty\nagad n = W [(n - 1, sqrt n)]\n\n\nraise = LinOp adag\nlower = LinOp agad\n\n-- boson system can be seen as collection of oscillators. Q (V Int). Positive integers really.\n\ntype Boson v = Q (v Int) -- accepts a functor describing all the oscillators. A Vec for example.\n-- bvac = pure zero -- if v is a Vector type, it probably has a zero.\n-- \n\n\n-- traversable ordering. The vector is put into canocnical form with adag appearing first in the traversal coming first.\ntype Fermion v = Q (v Bool) -- fermion needs to prefix count to figure out signs. This means that v has to be traversable? Foldable?\nfvac :: Applicative v => Fermion v\nfvac = pure (pure False)\n{-\n-- what about systems with different types of particles.\nparticle-hole Q ([a], [a])\n\n\nAntiOp a = AntiOp [a] -> Q [a]\n-- indexed linear operators. a -> AntiOp a\npsi :: Ord a => a -> (a -> Anti a)\npsidag :: Ord a => a -> (a -> Anti a)\n\nphi :: Ord a => a -> (a -> Sym a)\nphidag :: Ord a => a -> (a -> Sym a)\n\n-- hmm. Something kind of funny about these.\nlift1 :: (i -> Double) -> (i -> Fock i)\nlift2 :: (i -> i -> Double) -> (i -> Fock i)\nsymlift -- mention that there is implcit symmettrization\n2 natural lifts. cnnected by logarithms. UxUxUxU vs HIII + IHII + IIHI + IIIH\n\n\nsum1 :: (i -> i -> Q i) -> (i -> Q i) -- takes an indexed operator and turns it into an operator\nsum1 :: (i -> AntiOp i) -> (AntiOp i)\nsum2\nsum :: Addable b => (i -> b) -> b\n\n\nturn all of this into a typeclass functions. Then do this form, but also full initial form for manipulation.\n\ndyson\n\n-}\n-- instance (Additive f, Additive g) => Additive (Compose f g) where\n-- instance Num f (g a) => Num (Compose f g a)\n\n-- (Kron (Kron V2 V2) V2) Complex Double  -- a 3 qubit vector space\nswap :: (Traversable f, Applicative g) => Kron f g a -> Kron g f a\nswap = Compose . sequenceA . getCompose\n\n-- kron :: (Num a, Functor f, Functor g) => f a -> g a -> Kron f g a\n-- kron f g = Compose $ fmap (\\amp1 -> fmap (\\amp2 -> amp1 * amp2) g) f\nkron' :: (Num a, Functor f, Functor g) => f a -> g a -> Kron f g a\nkron' x y = Compose (outer x y)\n\ndensify :: (Additive (Kron f g), Num a, Functor f, Functor g) => FKron f g a -> Kron f g a\ndensify (FKron xs) = sumV $ map (uncurry kron') xs\n\n\nkron''' :: (Applicative f', Applicative g', Traversable f, Traversable g') =>\n (f a -> f' a) -> (g a -> g' a) -> (Kron f g a -> Kron f' g' a)\nkron''' lf lg (Compose fga) = Compose $ sequenceA $ (fmap lf) $ sequenceA $ (fmap lg fga)\n\ntype LinOp' f g a = f a -> g a\n-- SVD let's you re free\n-- but also [indicatro vectro, g a]\n-- and perhaps randomize sampling.\n {-\nsigx :: Spin C -> Spin C\nsigx (V2 up down) = V2 down up\n\nsigz :: Spin C -> Spin C\nsigz (V2 (a :+ b) (c :+ d)) = V2 ()\n\nsigz :: Spin C -> Spin C\nsigz (V2 up down) = V2 up (-down) \n-}\n{-\nclass Add a where\n (+++) :: a -> a -> a\n negate' :: a -> a\n\ninstance Num a => Add a where\n +++ = +\ninstance => Additive f\n-}\n\n\nflip' :: Spin a -> Spin a\nflip' (V2 up down) = V2 down up\n\nsigx = flip'\n\nsigz :: Num a => Spin a -> Spin a\nsigz (V2 up down) = V2 up (negate down) \n\n\n\n-- phase :: Complex a => Spin a -> Spin a\ntype f ~> g = forall a. (Functor f, Functor g) => f a -> g a\ntype f *** g = Compose f g\n-- (Functor f, Functor g, Functor h, Functor k)\n-- we only need g to be a functor\n-- see below. If we remove the type signature, this implementation generalizes to another type\npar :: Functor g => (forall a. f a -> g a) -> (forall b. h b -> k b) -> (forall c. (Compose f h c) -> (Compose g k c))\npar f g = Compose . (fmap g) . f . getCompose -- insufficient though. We can't write linear operators this way\n\n-- I should used V1, not Identity\n-- These are all also coerce.\nrightUnitor :: Functor f => Compose f Identity a -> f a \nrightUnitor (Compose f) = fmap runIdentity f\n\nrightUnitor' :: f ~> Compose f Identity\nrightUnitor' = Compose . fmap Identity\n\nleftUnitor' :: f ~> Compose Identity f\nleftUnitor' = Compose . Identity\n\nleftUnitor :: Identity *** f ~> f\nleftUnitor = runIdentity . getCompose\n\n-- should be coerce. Confusing role problems\nassoc :: Functor f => (Kron (Kron f g) h) ~> (Kron f (Kron g h))\nassoc = Compose . (fmap Compose) . getCompose . getCompose\n\nassoc' :: Functor f => (Kron f (Kron g h)) ~> (Kron (Kron f g) h)\nassoc' (Compose x) = Compose $ Compose $ (fmap getCompose x) \n\n\n-- if the functor in question happens to be representable\n -- then we can use our previous defitions of monoidal catgoeries.\n -- Reader Functors\n-- Num c => prod :: Reader a c -> Reader b c -> Reader (a,b) c\n-- Num \n-- newtype ReadCat c a b = ReadCat (Reader a c -> Reader b c)\n-- newtype LinOp c a b = LinOp ((a -> c) -> (b -> c))\n-- par (LinOp f) (LinOp g) = LinOp \\h -> h (\\(a,b) -> )\n-- FMapN\n-- fmapN @n\n{-Compose f g\n\n\n\nassoc :: Compose (Compose f g) h a -> Compose f (Compose g h) a\n\nassoc = Compose . (fmap Compose) . getCompose . getCompose\n\nCompose f Id a -> f a\n\nrightunit = (fmap runIdentity) . getCompose\n\nThe morphisms of the functor category are natural transformations\n\npar :: (f ~> g) -> (h~> k) -> ((Compose f h) ~> (Compose g k))\n\n\n\n\n\n-}\n\n\nnewtype Kron' k l f a = Kron' ((k (l f)) a) deriving Functor\n\n-- deriving via compose\n{-\nnewtype V2' f a = V2' (Compose V2 f a) deriving Functor\nnewtype V1' f a = V1' (Compose V1 f a) deriving Functor\n-}\n{-\nnewtype V2' f a = V2' (V2 (f a)) deriving Functor\nnewtype V1' f a = V1' (f a) deriving Functor\n-}\n\ntype V2' f a = Kron V2 f a\ntype V1' f a = Kron V1 f a\n\nlowerv1 (Compose (V1 f)) = f -- It's a coerce. V1 is assuredly a newtype\n{-\nexvsa :: (Additive f, Num a) => V2' f a \nexvsa = zero\n-}\n\n-- constant vecotrs a morphisms from unit\n-- Using f ~ one = (V1 1) \nexconst :: (a ~ Double, Functor f) => V1' f a -> V2' f a\nexconst x = let x' = lowerv1 x in Compose $ V2 (1.4 *^ x') (7.3 *^ x')\n\none = V1 1\nattemp = exconst (Compose (V1 one))\n\n-- Applicative composes, so Additive probably should too.\n-- Wait is this in the library?\n-- Why is applicative g necessary?\n{-\nOk. There doesn't appear to be a compose\nBut V2 etc have a Num instance\nand liftU2 has a default implementation that uses Applicative\nI probably don't need Applcative g if I define a liftU2 using g's liftU2\n\n-}\n-- I should check to make sure the lift makes sense\n-- Why isn't this in the library? There must be a good reason.\n-- Is there an additive instance for Product?\n\ninstance (Additive g, Additive f) => Additive (Compose f g) where\n (Compose v) ^+^ (Compose w) = Compose (liftU2 (^+^) v w) -- I we might be able to used\n zero = zero -- what?\n liftU2 f (Compose x) (Compose y) = Compose $ liftU2 (liftU2 f) x y\n liftI2 f (Compose x) (Compose y) = Compose $ liftI2 (liftI2 f) x y\n\ntype LinOp1 f g a = forall k. Additive k => Kron f k a -> Kron g k a\n\n-- This feels less right to me. But why?\ntype LinOp1' f g a = forall k. Functor k => Kron k f a -> Kron k g a\n{-\nIt feels less right perhaps because it will change how we do things so little.\nWe just have to fmap.\nNo, but saying we always have direct access to the scalar isn't right.\n-}\n\n\n-- reassoc :: Kron f (Kron g k) a -> Kron (Kron f g) k a\n-- reassoc = coerce\n\n--reassoc' :: Kron (Kron f g) k a -> Kron f (Kron g k) a\n--reassoc' = -- coerce\n\n-- yikes. coerce will help a bit. Quite a bit.\n-- Also Fixing the unnecessary applicative instances.\n-- Additive k' is expected. Applicative is coming from Additve (Kron ) constraint.\n\n{-kron'' :: (Applicative g, Applicative k', Additive k', Functor f', Functor f, Functor g') => \n (forall k. Additive k => Kron f k a -> Kron f' k a) -> (forall k. Additive k => Kron g k a -> Kron g' k a) -> (Kron (Kron f g) k') a -> (Kron (Kron f' g') k') a\n-}\n\ntype Qubit = V2\n\nkron'' :: (Additive f, Additive g, Additive k, Additive f', Additive g') => \n LinOp1 f f' a -> LinOp1 g g' a -> Kron (Kron f g) k a -> Kron (Kron f' g') k a\nkron'' lf lg fgk = let v = (Qubit.assoc fgk) in Qubit.assoc' (Compose $ fmap lg $ getCompose (lf v))\n\nsigx' :: LinOp1 Qubit Qubit C \nsigx' (Compose (V2 up down)) = Compose $ V2 down up \n\nsigz' :: LinOp1 Qubit Qubit C \nsigz' (Compose (V2 up down)) = Compose $ V2 up ((-1) *^ down) \n\nsigy' :: LinOp1 Qubit Qubit C \nsigy' (Compose (V2 up down)) = Compose $ V2 ((-i) *^ down) (i *^ up) where i = 0 :+ 1\n\nswap' :: (Traversable f, Applicative g) => LinOp1 (Kron f g) (Kron g f) a \nswap' (Compose (Compose fgk)) = Compose $ Compose $ sequenceA fgk \n\ncnot :: LinOp1 (Kron Qubit Qubit) (Kron Qubit Qubit) a \ncnot (Compose (Compose (V2 (V2 up1 down1) v))) = Compose $ Compose $ V2 (V2 down1 up1) v\n\nphase :: Double -> LinOp1 Qubit Qubit C\nphase phi (Compose (V2 up down)) = Compose $ V2 up ((cis phi) *^ down)\n\nmtest :: LinOp1 (Kron Qubit Qubit) (Kron Qubit Qubit) C \nmtest = (left sigx') . (left sigy') . (right sigz') . swap'\n\nleft :: (Additive f, Additive k, Additive g) => LinOp1 f g a -> LinOp1 (Kron f k) (Kron g k) a\nleft l = kron'' l id -- Qubit.assoc' . l . Qubit.assoc \n\nright :: (Additive k, Additive f, Additive g) => LinOp1 f g a -> LinOp1 (Kron k f) (Kron k g) a\nright l = kron'' id l -- (Compose (Compose fkk)) = Compose $ Compose $ (fmap (getCompose . l . Compose) fkk)\n\nleftUnit :: Kron V1 (Kron f k) a -> Kron f k a\nleftUnit (Compose (V1 x)) = x\n\n\n{-\n(f a -> g a) is a natural transfromation\n(Fractional a => f a -> g a) is a numerical transfromation\n\nHorizontal composition in Functor land. Sure.\nEven in applicative\nThe issue is that Good linear ops are going to hold numbers. So ti feels wrong to quanitfy over them\nOne option is to add a type class constraint\n(Num a) or (Fractional a)\nThis will work because linear lifts these\n\n\n-- this is the same as par written above.\n\n-- Functor f => (t -> f a) -> (a -> b) -> t -> f b\nThe oppotite ordering\n-- Functor f' => (f' b -> t') -> (a -> b) -> f' a -> t'\nThe more general type as inferred is\nf b ~ t'\n\n(f' a -> f a) -> (a -> b) -> (f' a -> f b)\nvs \n(f' b -> f b) -> (a -> b) -> (f' a -> f b)\nvs.\nforall\n\nkron l l' x = l' (fmap l x)\n\n(forall f. Additive f => Kron V2 f a -> Kron V3 f a) -> () -> (forall p. Kron f (Kron k p) -> Kron f' (Kron k' p) )\nWe want to allow the field a to unify across them all. \nThe scalar is generic in a certain sense, but not in another.\n\nThis is the lifted Kron'\nWe don't want Additive1, something went screwy there.\nAdditive (Kron' ) \n\n\nThe problem with Num based Kron: If we define LinOp\n(LinOp f g = forall Num a => f a -> g a\nWhy Num, Why not Fractional. This is a problem.\nAnd really we want to be threading the scalar a throughout the entire system.\n\nkron\n\nAnd what if we unified the two orderings\n\n\nHmm. These are pretty similar to van Laarhoven lenses. This observation is porbably poison\nSwtich the arguments\n(a -> b) -> Lens \nFunctor f => (t -> f a) -> (t -> f b)\ntype Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t\nLens t a t b\n\nkron :: (Fractional a => f a -> g a) -> (Fractional k) -> LinOp\nkron l l' (Compose fk) = Compose (fmap l' (l fk))\n\n\nConstrained natural transformation\nkron forall const. (const a => f a -> g a) -> (forall b. const (k b) => k b -> l b)\n\n\n\n\n(f Double -> g Double) ->\n(forall f. V2' f Double -> V2' f Double)\n\n\nkron :: LinOp f g -> LinOp k l -> LinOp (Kron f k) (Kron g l)\n\n\n-}\n\n{-\n\n-- can't build. Well we can build vzero\nexv2' :: (Additive f, Num a) => V2' f a\nexv2' = V2' (Compose ( ? )) \n\n\n\n-}\n-- constants are given as morphisms\n-- exv2' :: (Additive f, Num a) => V1' f a -> V2' f a\n-- exv2' (V1' f) = (V2' (V2 )\n\n{-\nThere is no additive instance for Compose?\nHuh.\n\n\nclass (forall f. Additive f => Additive k f) => Additive1 k where\n\nI'm doing something insane.\nYea, The 1 pattern. I've been here before and decided it was insane.\nSomething in purescript. Surely it wasn't Additive1 was it?\n\n\n-}\n{-\nclass Additive1 k where\n vadd :: (Additive f, Num a) => k f a -> k f a -> k f a\n vzero :: (Additive f, Num a) => k f a\ninstance Additive1 V2' where -- (Functor (V2' f)) => \n\n vadd (V2' (V2 v w)) (V2' (V2 x y)) = V2' (V2 (v ^+^ x) (w ^+^ y) )\n vzero = V2' (V2 zero zero)\n\n \n --vadd (V2' v) (V2' w) = V2' (v ^+^ w)\n --vzero = V2' zero\n \ninstance Additive1 V1' where -- (Functor (V2' f)) => \n vadd (V1' v) (V1' w) = V1' (v ^+^ w)\n vzero = V1' zero\n\ninstance (Additive1 k, Additive1 l) => Additive1 (Kron' k l) where\n vadd (Kron' x) (Kron' y) = Kron' (vadd x y)\n vzero = Kron' vzero\n -}\n{-\nDeriv functor for V2'\n-}\n\n\n\n", "meta": {"hexsha": "8ccadb0cba57114c7c104883f76eafc9d7836f50", "size": 13335, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Qubit.hs", "max_stars_repo_name": "philzook58/fib-anyon", "max_stars_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-01-14T10:48:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T08:35:00.000Z", "max_issues_repo_path": "src/Qubit.hs", "max_issues_repo_name": "philzook58/fib-anyon", "max_issues_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Qubit.hs", "max_forks_repo_name": "philzook58/fib-anyon", "max_forks_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-11-15T07:42:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-02T15:15:28.000Z", "avg_line_length": 29.765625, "max_line_length": 162, "alphanum_fraction": 0.6278965129, "num_tokens": 4572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5117878249881307}} {"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{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule TensorHMatrix where\n\nimport Misc.Nats\nimport Numeric.LinearAlgebra as H\nimport Data.Vector.Storable as V\nimport Data.Default\nimport Data.Singletons.Prelude\nimport Generics.SOP.Constraint as C\nimport Misc.Constraints\nimport GenericTensor\n\nimport Prelude hiding (zipWith)\n\n-- the kitchen sink of constraints\ntype Usable a = (Element a, Num a, Numeric a, Num (Vector a), Container Vector a, Floating a, Floating (Vector a))\n\ndata HTensor a (dims :: [k]) where\n Scalar :: !a -> HTensor a '[]\n Vector :: Vector a -> HTensor a '[n]\n Matrix :: Matrix a -> HTensor a '[n, m]\n\nderiving instance (Show a, Element a) => Show (HTensor a dims)\n\ninstance (IntegralL dims, Default a, Usable a) => Default (HTensor a dims) where\n def = fill' def\n\n--type instance IndexOf (HTensor l) = Rec LT l\n--type instance IndexOf (HTensor l) = Rec (Const Int) l\n--type instance IndexOf (HTensor l) = Vec (Length l) Int\n\n{- Fails backwards fundep :(\ninstance Indexable (HTensor (n ': l) a) (HTensor l a) where\n Matrix m ! i = Vector (m ! i)\n Vector v ! i = Scalar (v ! i)\n-}\n\ninstance Usable a => Tensor (HTensor a :: [k] -> *) where\n type N (HTensor a) = a\n \n scalar (Scalar a) = a\n\n transpose (Matrix m) = Matrix (tr' m)\n \n scale (Scalar a) (Vector v) = Vector (H.scale a v)\n\n dot (Vector a) (Vector b) = Scalar (a <.> b)\n \n outer (Vector a) (Vector b) = Matrix (H.outer a b)\n\n mv (Matrix m) (Vector v) = Vector $ m #> v\n\n mm (Matrix m1) (Matrix m2) = Matrix $ m1 <> m2\n\n select i (Vector v) = Scalar (v V.! i)\n\n oneHot :: forall (n :: k). (SingI n, IntegralN n) => Int -> HTensor a '[n]\n oneHot i = Vector $ (konst 0 (natVal' (sing::Sing n))) // [(i, 1)]\n\n --fill :: forall (dims :: [k]). (IntegralL dims) => a -> HTensor a dims\n fill sDims a = case sDims of\n SNil -> Scalar a\n SCons n SNil -> Vector $ konst a (natVal' n)\n SCons m (SCons n SNil) -> Matrix $ konst a (natVal' m, natVal' n)\n _ -> error \"HTensors only go up to dimension 2.\"\n\n-- pretty much all of these instances should be automatically derivable\n-- the only issue is that fromInteger needs to use natVal'\n\ninstance (Usable a, IntegralL dims) => Num (HTensor a dims) where\n Scalar a + Scalar b = Scalar (a + b)\n Vector a + Vector b = Vector (a + b)\n Matrix a + Matrix b = Matrix (a + b)\n\n Scalar a - Scalar b = Scalar (a - b)\n Vector a - Vector b = Vector (a - b)\n Matrix a - Matrix b = Matrix (a - b)\n\n Scalar a * Scalar b = Scalar (a * b)\n Vector a * Vector b = Vector (a * b)\n Matrix a * Matrix b = Matrix (a * b)\n \n negate (Scalar a) = Scalar (negate a)\n negate (Vector a) = Vector (negate a)\n negate (Matrix a) = Matrix (negate a)\n\n abs (Scalar a) = Scalar (abs a)\n abs (Vector a) = Vector (abs a)\n abs (Matrix a) = Matrix (abs a)\n \n signum (Vector a) = Vector (signum a)\n signum (Scalar a) = Scalar (signum a)\n signum (Matrix a) = Matrix (signum a)\n \n \n fromInteger = fill' . fromInteger\n\ninstance (IntegralL dims, Usable a) => Fractional (HTensor a dims) where\n Scalar a / Scalar b = Scalar (a / b)\n Vector a / Vector b = Vector (a / b)\n Matrix a / Matrix b = Matrix (a / b)\n \n recip (Scalar a) = Scalar (recip a)\n recip (Vector a) = Vector (recip a)\n recip (Matrix a) = Matrix (recip a)\n\n fromRational = fill' . fromRational\n\ninstance (IntegralL dims, Usable a) => Floating (HTensor a dims) where\n pi = fill' pi\n\n exp (Scalar a) = Scalar (exp a)\n exp (Vector a) = Vector (exp a)\n exp (Matrix a) = Matrix (exp a)\n \n log (Scalar a) = Scalar (log a)\n log (Vector a) = Vector (log a)\n log (Matrix a) = Matrix (log a)\n\n sqrt (Scalar a) = Scalar (sqrt a)\n sqrt (Vector a) = Vector (sqrt a)\n sqrt (Matrix a) = Matrix (sqrt a)\n\n Scalar a ** Scalar b = Scalar (a ** b)\n Vector a ** Vector b = Vector (a ** b)\n Matrix a ** Matrix b = Matrix (a ** b)\n\n logBase (Scalar a) (Scalar b) = Scalar (logBase a b)\n logBase (Vector a) (Vector b) = Vector (logBase a b)\n logBase (Matrix a) (Matrix b) = Matrix (logBase a b)\n\n sin (Scalar a) = Scalar (sin a)\n sin (Vector a) = Vector (sin a)\n sin (Matrix a) = Matrix (sin a)\n\n cos (Scalar a) = Scalar (cos a)\n cos (Vector a) = Vector (cos a)\n cos (Matrix a) = Matrix (cos a)\n\n tan (Scalar a) = Scalar (tan a)\n tan (Vector a) = Vector (tan a)\n tan (Matrix a) = Matrix (tan a)\n\n asin (Scalar a) = Scalar (asin a)\n asin (Vector a) = Vector (asin a)\n asin (Matrix a) = Matrix (asin a)\n\n acos (Scalar a) = Scalar (acos a)\n acos (Vector a) = Vector (acos a)\n acos (Matrix a) = Matrix (acos a)\n\n atan (Scalar a) = Scalar (atan a)\n atan (Vector a) = Vector (atan a)\n atan (Matrix a) = Matrix (atan a)\n\n sinh (Scalar a) = Scalar (sinh a)\n sinh (Vector a) = Vector (sinh a)\n sinh (Matrix a) = Matrix (sinh a)\n\n cosh (Scalar a) = Scalar (cosh a)\n cosh (Vector a) = Vector (cosh a)\n cosh (Matrix a) = Matrix (cosh a)\n\n tanh (Scalar a) = Scalar (tanh a)\n tanh (Vector a) = Vector (tanh a)\n tanh (Matrix a) = Matrix (tanh a)\n\n asinh (Scalar a) = Scalar (asinh a)\n asinh (Vector a) = Vector (asinh a)\n asinh (Matrix a) = Matrix (asinh a)\n\n acosh (Scalar a) = Scalar (acosh a)\n acosh (Vector a) = Vector (acosh a)\n acosh (Matrix a) = Matrix (acosh a)\n\n atanh (Scalar a) = Scalar (atanh a)\n atanh (Vector a) = Vector (atanh a)\n atanh (Matrix a) = Matrix (atanh a)\n\ninstance Usable a => ImpliesC (IntegralL dims) (CompC Floating (HTensor a) dims) where\n impliesC = Sub Dict\n\ninstance Usable a => ForallC (ImpliesC1 IntegralL (CompC Floating (HTensor a))) where\n forallC = Forall Dict\n\ntmap :: (Container Vector a, Num a, Element b) => (a -> b) -> HTensor a dims -> HTensor b dims\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) -> HTensor a '[n] -> HTensor b '[n] -> HTensor c '[n]\ntZipWith f (Vector a) (Vector b) = Vector (zipWith f a b)\n\n{-\ntranspose :: (Numeric a) => HTensor '[n, m] a -> HTensor '[m, n] a\ntranspose (Matrix m) = Matrix (tr' m)\n\nasCol :: Storable a => HTensor '[n] a -> HTensor '[n, FromInteger 1] a\nasCol (Vector v) = Matrix $ asColumn v\n\nasRow' :: Storable a => HTensor '[n] a -> HTensor '[FromInteger 1, n] a\nasRow' (Vector v) = Matrix $ asRow v\n\ndot :: Numeric a => HTensor '[n] a -> HTensor '[n] a -> a\ndot (Vector a) (Vector b) = a <.> b\n\nmv :: Numeric a => HTensor '[n, m] a -> HTensor '[m] a -> HTensor '[n] a\nmv (Matrix m) (Vector v) = Vector $ m #> v\n\nmm :: Numeric a => HTensor '[n, m] a -> HTensor '[m, k] a -> HTensor '[n, k] a\nmm (Matrix m1) (Matrix m2) = Matrix $ m1 <> m2\n\ngradDot :: Numeric a => HTensor '[n] a -> HTensor '[n] a -> a -> (HTensor '[n] a, HTensor '[n] a)\ngradDot (Vector a) (Vector b) g = (Vector $ scale g b, Vector $ scale g a)\n\ngradMV :: Numeric a => HTensor '[n, m] a -> HTensor '[m] a -> HTensor '[n] a -> (HTensor '[n, m] a, HTensor '[m] a)\ngradMV m v g = (mm (asCol g) (asRow' v), mv (transpose m) g)\n\ngradMM :: Numeric a => HTensor '[n, m] a -> HTensor '[m, k] a -> HTensor '[n, k] a -> (HTensor '[n, m] a, HTensor '[m, k] a)\ngradMM a b g = (mm g (transpose b), mm (transpose a) g)\n\ngradSelect :: forall a n. (SingI n, IntegralN n, Usable a) => Int -> HTensor '[n] a -> a -> HTensor '[n] a\ngradSelect i _ a = Vector $ (konst 0 (natVal' (sing::Sing n))) // [(i, a)]\n-}\n\n", "meta": {"hexsha": "79d04671e863df265a27a9d8652f5282f997838b", "size": 7664, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/TensorHMatrix.hs", "max_stars_repo_name": "vladfi1/hs-nn", "max_stars_repo_head_hexsha": "0b1ee88ed8d02acf723086e12905998ce0f4532c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2016-02-11T16:36:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-23T02:25:19.000Z", "max_issues_repo_path": "src/TensorHMatrix.hs", "max_issues_repo_name": "vladfi1/hs-nn", "max_issues_repo_head_hexsha": "0b1ee88ed8d02acf723086e12905998ce0f4532c", "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/TensorHMatrix.hs", "max_forks_repo_name": "vladfi1/hs-nn", "max_forks_repo_head_hexsha": "0b1ee88ed8d02acf723086e12905998ce0f4532c", "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.2016806723, "max_line_length": 124, "alphanum_fraction": 0.6199112735, "num_tokens": 2549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.511553071948767}} {"text": "{-# OPTIONS_GHC -Wall #-}\n{-# LANGUAGE BangPatterns #-}\n\nmodule Numeric.MCMC.RiemannianLangevin (\n MarkovChain(..)\n , Options, createOptions\n , runChain, localMean, perturb\n ) where\n\nimport Numeric.MCMC.Langevin hiding (Options, runChain)\nimport Numeric.LinearAlgebra \nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.Primitive\nimport Control.Monad.Reader\nimport System.Random.MWC\nimport System.Random.MWC.Distributions \n\n-- | Options for the chain. The target (expected to be a log density), the\n-- right matrix product of its curvature and gradient, the inverse Fisher metric tensor,\n-- its (Cholesky) square root, and the step size.\ndata Options = Options { \n _target :: [Double] -> Double -- Target (log density)\n , _curvatureXgradient :: [Double] -> [Double] -- Curvature right-multiplied by gradient\n , _invFisherMetric :: [Double] -> Matrix Double -- Inverse Fisher metric tensor\n , _sqrtInvFisherMetric :: [Double] -> Matrix Double -- Square root of the tensor\n , _eps :: {-# UNPACK #-} !Double -- Step size\n }\n\n-- | A result with this type has a view of the chain options.\ntype ViewsOptions = ReaderT Options\n\n-- | Construct Options (data constructor not exported).\n-- FIXME sqrtm is not converging; alternatives?\ncreateOptions :: ([Double] -> Double) -- Target (log density)\n -> ([Double] -> [Double]) -- Gradient\n -> ([Double] -> [[Double]]) -- Hessian\n -> Double -- Step size\n -> Options -- Options\ncreateOptions t g h = \n Options t curvatureXgradient invFisherMetric sqrtInvFisherMetric \n where curvatureXgradient xs = \n let mat = invFisherMetric xs <> fromColumns [fromList (g xs)]\n in concat . toLists . trans $ mat\n invFisherMetric = pinv . fromRows . map (fromList . map (* (-1))) . h \n sqrtInvFisherMetric x = let z = schur (invFisherMetric x) \n in fst z <> sqrtm (snd z) <> trans (fst z)\n{-# INLINE createOptions #-}\n\n-- | Non-isotropic Gaussian density.\nnonIsoGauss :: [Double] -> [Double] -> Matrix Double -> Double\nnonIsoGauss xs mu sig = exp val\n where val = -0.5*p*log (2*pi) - 0.5*ldet - 0.5*\n (trans (xsM `sub` muM) <> invSig <> (xsM `sub` muM)) @@> (0, 0)\n (xsM, muM) = (\\f (a, b) -> (f a, f b)) (\\l -> fromColumns [fromList l]) (xs, mu)\n p = fromIntegral $ cols sig\n (invSig, (ldet, _)) = invlndet sig\n{-# INLINE nonIsoGauss #-}\n\n-- | Mean function for the discretized Riemannian Langevin diffusion.\nlocalMean :: Monad m \n => [Double] -- Current state\n -> ViewsOptions m [Double] -- Localized mean of proposal distribution\nlocalMean t = do\n Options _ c _ _ e <- ask\n return $! zipWith (+) t (map (* (0.5 * e^(2 :: Int))) (c t))\n{-# INLINE localMean #-}\n\n-- | Perturb the state, creating a new proposal.\nperturb :: PrimMonad m \n => [Double] -- Current state\n -> Gen (PrimState m) -- MWC PRNG\n -> ViewsOptions m [Double] -- Resulting perturbation.\nperturb t g = do\n Options _ _ _ s _ <- ask\n zs <- replicateM (length t) (lift $ standard g)\n t0 <- localMean t\n let adjustedBrownianMotion = s t <> fromColumns [fromList zs]\n abmList = concat . toLists . trans $ adjustedBrownianMotion\n perturbedState = zipWith (+) t0 t1 \n t1 = map (* eps) abmList\n return $! perturbedState \n{-# INLINE perturb #-}\n\n-- | Perform a Metropolis accept/reject step.\nmetropolisStep :: PrimMonad m \n => MarkovChain -- Current state\n -> Gen (PrimState m) -- MWC PRNG\n -> ViewsOptions m MarkovChain -- New state\nmetropolisStep state g = do\n Options target _ iF _ e <- ask\n let (t0, nacc) = (theta &&& accepts) state\n zc <- lift $ uniformR (0, 1) g\n proposal <- perturb t0 g\n t0Mean <- localMean t0\n proposalMean <- localMean proposal\n let mc = if zc < acceptProb \n then (proposal, 1)\n else (t0, 0)\n\n acceptProb = if isNaN val then 1 else val where val = arRatio \n \n arRatio = exp . min 0 $ \n target proposal + log (nonIsoGauss proposal t0Mean ((e^(2::Int)) `scale` iF t0)) \n - target t0 - log (nonIsoGauss t0 proposalMean ((e^(2::Int)) `scale` iF proposal)) \n\n return $! MarkovChain (fst mc) (nacc + snd mc)\n{-# INLINE metropolisStep #-}\n\n-- | Diffuse through states.\nrunChain :: Options -- Options of the Markov chain.\n -> Int -- Number of epochs to iterate the chain.\n -> Int -- Print every nth iteration\n -> MarkovChain -- Initial state of the Markov chain.\n -> Gen RealWorld -- MWC PRNG\n -> IO MarkovChain -- End state of the Markov chain, wrapped in IO.\nrunChain = go\n where go o n t !c g | n == 0 = return c\n | n `rem` t /= 0 = do\n r <- runReaderT (metropolisStep c g) o\n go o (n - 1) t r g\n | otherwise = do\n r <- runReaderT (metropolisStep c g) o\n print r\n go o (n - 1) t r g\n{-# INLINE runChain #-}\n\n", "meta": {"hexsha": "cbac65efe0a80a820e4598ab1b63677ff115ecf8", "size": 5418, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/MCMC/RiemannianLangevin.hs", "max_stars_repo_name": "jtobin/lazy-langevin", "max_stars_repo_head_hexsha": "147bf3b433d1b7290fda715c7689ecf2b7486eab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-09-05T02:55:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-10T03:12:37.000Z", "max_issues_repo_path": "Numeric/MCMC/RiemannianLangevin.hs", "max_issues_repo_name": "jtobin/lazy-langevin", "max_issues_repo_head_hexsha": "147bf3b433d1b7290fda715c7689ecf2b7486eab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numeric/MCMC/RiemannianLangevin.hs", "max_forks_repo_name": "jtobin/lazy-langevin", "max_forks_repo_head_hexsha": "147bf3b433d1b7290fda715c7689ecf2b7486eab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-22T05:08:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T05:08:38.000Z", "avg_line_length": 42.328125, "max_line_length": 99, "alphanum_fraction": 0.5645994832, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5115464509011574}} {"text": "{-# LANGUAGE AllowAmbiguousTypes, RankNTypes, UnicodeSyntax, NoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns, FlexibleInstances #-}\n\nmodule Optimizer where\n\nimport Utils\nimport Style\nimport GenOptProblem\nimport Numeric.AD\nimport Numeric.AD.Internal.On\nimport Numeric.AD.Internal.Reverse\nimport Numeric.AD.Internal.Sparse\nimport qualified Numeric.LinearAlgebra as L\nimport Debug.Trace\nimport System.Random\nimport System.Console.ANSI\nimport Data.List (foldl')\n\ndefault (Int, Float)\n\n------ Opt types, util functions, and params\n\ntype ObjFn1 a = forall a . (Autofloat a) => [a] -> a\n\n-- used for duf\ntype ObjFn2 a = forall a . (Autofloat a) => [a] -> [a] -> a\n\ntype GradFn a = forall a . (Autofloat a) => [a] -> [a]\n\n----- Various consts\n\nnanSub :: (Autofloat a) => a\nnanSub = 0\n\ninfinity :: Floating a => a\ninfinity = 1/0 -- x/0 == Infinity for any x > 0 (x = 0 -> Nan, x < 0 -> -Infinity)\n-- all numbers are smaller than infinity except infinity, to which it's equal\n\n----- Hyperparameters\n\nweightGrowthFactor :: (Autofloat a) => a -- for EP weight\nweightGrowthFactor = 10\n\nepsUnconstr :: Floating a => a\nepsUnconstr = 10 ** (-2)\n\nepStop :: Floating a => a -- for EP diff\nepStop = 10 ** (-5)\n-- epStop = 60 ** (-3)\n-- epStop = 10 ** (-1)\n-- epStop = 0.05\n\n-- Parameters for Armijo-Wolfe line search\n-- NOTE: must maintain 0 < c1 < c2 < 1\nc1 :: Floating a => a\nc1 = 0.001 -- for Armijo, corresponds to alpha in backtracking line search (see below for explanation)\n-- smaller c1 = shallower slope = less of a decrease in fn value needed = easier to satisfy\n-- turn Armijo off: c1 = 0\n-- Nocedal p38: \"In practice, c1 is chosen to be quite small, say 10−4.\"\n\nc2 :: Floating a => a\nc2 = 0.9 -- for Wolfe, is the factor decrease needed in derivative value\n-- new directional derivative value / old DD value <= c2\n-- smaller c2 = smaller new derivative value = harder to satisfy\n-- turn Wolfe off: c1 = 1 (basically backatracking line search only)\n-- Nocedal p39: \"Typical values of c2 are 0.9 when the search direction pk is chosen by a Newton or quasi-Newton method\"\n\n-- true = force linesearch halt if interval gets too small; false = no forced halt\nintervalMin = True\n\nuseLineSearch :: Bool\nuseLineSearch = True\n\nuseAutodiff :: Bool\nuseAutodiff = True\n\nconstT :: Floating a => a\nconstT = 0.001\n\ndebugOpt = True\ndebugLineSearch = False\ndebugBfgs = True\n\ntrb :: String -> a -> a\ntrb s x = if debugBfgs then trace \"---\" $ trace s x else x -- prints in left to right order\n\ntro :: String -> a -> a\ntro s x = if debugOpt then trace \"---\" $ trace s x else x -- prints in left to right order\n\ntrl :: Show a => String -> a -> a\ntrl s x = if debugLineSearch then trace \"---\" $ trace s $ traceShowId x else x -- prints in left to right order\n\n----- Convergence criteria\n\n-- convergence criterion for EP\n-- if you want to use it for UO, needs a different epsilon\nepStopCond :: (Autofloat a) => [a] -> [a] -> a -> a -> Bool\nepStopCond x x' fx fx' =\n tro (\"EP: \\n||x' - x||: \" ++ (show $ norm (x -. x'))\n ++ \"\\n|f(x') - f(x)|: \" ++ (show $ abs (fx - fx'))) $\n (norm (x -. x') <= epStop) || (abs (fx - fx') <= epStop)\n\nunconstrainedStopCond :: (Autofloat a) => [a] -> Bool\nunconstrainedStopCond gradEval = norm gradEval < epsUnconstr\n\n---------------------------------------\n\n-- Policies\n\nstepPolicy :: State -> (Params, PolicyParams)\nstepPolicy s = \n -- Check overall convergence first \n let epStatus = optStatus $ (paramsr s) in\n let pparams = policyParams s in\n case epStatus of\n\n -- Generate new objective function and replace the optimization and policy params accordingly\n EPConverged -> \n -- TODO: clean up the step incrementing\n let pparams' = pparams { policySteps = 1 + policySteps pparams } in\n let (policyRes, psNew) = (policyFn s) (objFns s) (constrFns s) pparams' in -- See what the policy function wants\n case policyRes of\n Nothing -> (paramsr s, pparams' { policyState = psNew }) -- steps incremented, policy done\n\n Just newFns -> -- Policy keeps going\n let objFnNew = genObjfn (transr s) (filter isObjFn newFns) (filter isConstr newFns) (varyingPaths s) \n -- TODO: check that these inputs are right\n -- Change obj function and restart optimization\n pparamsNew = pparams' { policyState = psNew,\n currFns = newFns }\n paramsNew = Params { weight = initWeight,\n optStatus = NewIter,\n overallObjFn = objFnNew,\n bfgsInfo = defaultBfgsParams }\n in tro (\"Step policy, EP converged, new params:\\n\" ++ show (paramsNew, pparamsNew, newFns)) $ (paramsNew, pparamsNew)\n\n -- If not converged, optimize as usual, don't change policy mid-optimization\n _ -> tro (\"Step policy, EP not converged, new params:\\n\" ++ show (paramsr s, pparams)) $ (paramsr s, pparams)\n\n---------------------------------------\n\n-- Main optimization functions\n\nstep :: State -> State\nstep s = let (state', params') = stepShapes (oConfig s) (paramsr s) (varyingState s) (rng s)\n s' = s { varyingState = state', \n paramsr = params' }\n -- NOTE: we intentionally discard the random generator here because\n -- we want to have consistent computation output in a single\n -- optimization session\n -- For the same reason, all subsequent step* functions such as\n -- stepShapes do not return the new random generator\n (!shapes', _, _) = evalTranslation s'\n\n -- Check the state and see if the overall objective function should be changed\n -- The policy may change EPConverged to a new iteration before the frontend sees it\n (paramsNew, pparamsNew) = stepPolicy s'\n\n -- For debugging\n oldParams = paramsr s\n\n in tro (\"Params: \\n\" ++ show oldParams ++ \"\\n:\") $\n s' { shapesr = shapes',\n paramsr = paramsNew,\n policyParams = pparamsNew } \n -- note: trans is not updated in state\n\n-- Note use of realToFrac to generalize type variables (on the weight and on the varying state)\n\n-- implements exterior point algo as described on page 6 here:\n-- https://www.me.utexas.edu/~jensen/ORMM/supplements/units/nlp_methods/const_opt.pdf\nstepShapes :: OptConfig -> Params -> [Float] -> StdGen -> ([Float], Params)\nstepShapes config params vstate g = -- varying state\n -- if null vstate then error \"empty state in stepshapes\" else\n let (epWeight, epStatus) = (weight params, optStatus params) in\n case epStatus of\n\n -- start the outer EP optimization and the inner unconstrained optimization, recording initial EPstate\n NewIter -> let status' = UnconstrainedRunning (map realToFrac vstate) in\n (vstate', params { weight = initWeight, optStatus = status', bfgsInfo = defaultBfgsParams } )\n -- check *weak* convergence of inner unconstrained opt.\n -- if UO converged, set opt state to converged and update UO state (NOT EP state)\n -- if not, keep running UO (inner state implicitly stored)\n -- note convergence checks are only on the varying part of the state\n UnconstrainedRunning lastEPstate -> -- doesn't use last EP state\n -- let unconstrConverged = unconstrainedStopCond gradEval in\n let unconstrConverged = epStopCond vstate vstate' (objFnApplied vstate) (objFnApplied vstate') in\n -- Two stopping conditions\n -- unconstrainedStopCond gradEval in\n if unconstrConverged then\n let status' = UnconstrainedConverged lastEPstate in -- update UO state only!\n (vstate', params { optStatus = status', bfgsInfo = defaultBfgsParams }) -- note vstate' (UO converged), not vstate\n else (vstate', params { bfgsInfo = bfgs' }) -- update UO state but not EP state; UO still running\n\n -- check EP convergence. if converged then stop, else increase weight, update states, and run UO again\n -- TODO some trickiness about whether unconstrained-converged has updated the correct state\n -- and whether to check WRT the updated state or not\n UnconstrainedConverged lastEPstate ->\n let epConverged = epStopCond lastEPstate (map r2f vstate) -- lastEPstate is last state for converged UO\n (objFnApplied lastEPstate) (objFnApplied (map r2f vstate)) in\n if epConverged then\n let status' = EPConverged in -- no more EP state\n (vstate, params { optStatus = status', bfgsInfo = defaultBfgsParams }) -- do not update UO state\n -- update EP state: to be the converged state from the most recent UO\n else let status' = UnconstrainedRunning (map realToFrac vstate) in -- increase weight\n let epWeight' = weightGrowthFactor * epWeight in\n -- trace (\"Unconstrained converged. New weight: \" ++ show epWeight') $\n (vstate, params { weight = epWeight', optStatus = status', bfgsInfo = defaultBfgsParams })\n\n -- done; don't update obj state or params; user can now manipulate\n EPConverged -> (vstate, params { bfgsInfo = defaultBfgsParams } )\n\n -- TODO: implement EPConvergedOverride (for when the magnitude of the gradient is still large)\n\n -- TODO factor out--only unconstrainedRunning needs to run stepObjective, but EPconverged needs objfn\n where (vstate', gradEval, bfgs') = stepWithObjective config g params vstate\n objFnApplied = (overallObjFn params) g (r2f $ weight params)\n\n-- Given the time, state, and evaluated gradient (or other search direction) at the point,\n-- return the new state\n\nstepT :: Float -> Float -> Float -> Float\nstepT dt x dfdx = x - dt * dfdx\n\n-- Calculates the new state by calculating the directional derivatives (via autodiff)\n-- and timestep (via line search), then using them to step the current state.\n-- Also partially applies the objective function.\nstepWithObjective :: OptConfig -> StdGen -> Params -> [Float] -> ([Float], [Float], BfgsParams)\nstepWithObjective config g params state =\n -- get timestep via line search, and evaluated gradient at the state\n let (t', gradEval, gradToUse, bfgs') = timeAndGrad config params objFnApplied state\n -- step each parameter of the state with the time and gradient\n state' = map (\\(v, dfdv) -> stepT t' v dfdv) (zip state $ gradToUse)\n (fx, fx') = (objFnApplied state, objFnApplied state') \n in -- if fx' > fx then error (\"Error: new energy is greater than old energy: \" ++ show (fx', fx)) else\n tro (\"\\n----------------------------------------\\n\"\n ++ \"\\nopt params: \\n\" ++ (show params)\n ++ \"\\n||x' - x||: \" ++ (show $ norm (state -. state'))\n ++ \"\\n|f(x') - f(x)|: \" ++\n (show $ abs (fx' - fx))\n ++ \"\\nf(x'): \\n\" ++ (show fx')\n ++ \"\\ngradEval: \\n\" ++ (show gradEval)\n ++ \"\\n||gradEval||: \\n\" ++ (show $ norm gradEval)\n ++ \"\\ngradToUse: \\n\" ++ (show gradToUse)\n ++ \"\\n||gradToUse||: \\n\" ++ (show $ norm gradToUse)\n -- ++ \"\\nhessian: \\n\" ++ (show $ h)\n ++ \"\\nbfgs': \\n\" ++ (show bfgs') -- TODO: use trb\n ++ \"\\n timestep: \\n\" ++ (show t')\n ++ \"\\n original state: \\n\" ++ (show state)\n ++ \"\\n new state: \\n\" ++ (show state')\n )\n (state', gradEval, bfgs')\n\n where objFnApplied :: ObjFn1 b\n objFnApplied = (overallObjFn params) g cWeight\n\n cWeight = r2f $ weight params\n -- realToFrac generalizes the type variable `a` to the type variable `b`, which timeAndGrad expects\n\n-- a version of grad with a clearer type signature\nappGrad :: (Autofloat a) => (forall b . (Autofloat b) => [b] -> b) -> [a] -> [a]\nappGrad f l = grad f l\n\ninstance Show (Numeric.AD.Internal.On.On\n (Numeric.AD.Internal.Reverse.Reverse\n s (Numeric.AD.Internal.Sparse.Sparse a))) where\n show a = \"error: not sure how to derive show for hessian element\"\n\nappHess :: (Autofloat a) => (forall b . (Autofloat b) => [b] -> b) -> [a] -> [[a]]\nappHess f l = hessian f l\n\n-- Precondition the gradient\ngradP :: OptConfig -> BfgsParams -> [Double] -> ObjFn1 a -> [Float] -> ([Double], BfgsParams)\ngradP config bfgsParams gradEval f state =\n let x_k = L.vector $ map r2f state\n grad_fx_k = L.vector gradEval\n in case optMethod config of \n GradientDescent -> (gradEval, bfgsParams)\n\n Newton -> -- Precondition gradient with the pseudoinverse of the hessian\n let h = appHess f state\n h_list = (map r2f $ concat h) :: [Double]\n hinv = L.pinv $ L.matrix (length gradEval) $ h_list\n gradPreconditioned = hinv L.#> (L.vector gradEval) in\n (L.toList gradPreconditioned, bfgsParams)\n\n BFGS -> -- Approximate inverse of hessian with the change in gradient (see Nocedal S9.1 p224)\n let grad_val = lastGrad bfgsParams\n h_val = invH bfgsParams\n state_val = lastState bfgsParams\n in case (h_val, grad_val, state_val) of\n (Nothing, Nothing, Nothing) -> -- First step. Initialize the approximation to the identity (not clear how else to approximate it)\n -- k=0 steps from x_0 to x_1: so on the first step, we take a normal gradient descent step\n let h_0 = L.ident $ length gradEval\n in (gradEval, bfgsParams { lastState = Just x_k, lastGrad = Just grad_fx_k, invH = Just h_0 })\n\n (Just h_km1, Just grad_fx_km1, Just x_km1) -> -- For x_{k+1}, to compute H_k, we need the (k-1) info\n -- Our convention is that we are always working \"at\" k to compute k+1\n -- x_0 doesn't require any H; x_1 (the first step) with k = 0 requires H_0\n -- x_2 (the NEXT step) with k=1 requires H_1. For example>\n -- x_2 = x_1 - alpha_1 H_1 grad f(x_1) [GD step]\n -- H_1 = V_0 H_0 V_0 + rho_0 s_0 s_0^T [This is confusing because the book adds an extra +1 to the H index]\n -- V_0 = I - rho_0 y_0 s_0^T\n -- rho_0 = 1 / y_0^T s_0\n -- s_0 = x_1 - x_0\n -- y_0 = grad f(x_1) - grad f(x_0)\n\n let s_km1 = x_k - x_km1\n y_km1 = grad_fx_k - grad_fx_km1\n rho_km1 = 1 / (y_km1 `L.dot` s_km1) -- Scalar\n v_km1 = L.ident (length gradEval) - (rho_km1 `L.scale` y_km1 `L.outer` s_km1) -- Scaling can happen before outer\n h_k = (L.tr (v_km1) L.<> h_km1 L.<> v_km1) + (rho_km1 `L.scale` s_km1 `L.outer` s_km1)\n gradPreconditioned = h_k L.#> grad_fx_k\n in (L.toList gradPreconditioned, \n bfgsParams { lastState = Just x_k, lastGrad = Just grad_fx_k, invH = Just h_k })\n\n _ -> error \"invalid BFGS state\"\n\n LBFGS -> -- Approximate the inverse of the Hessian times the gradient\n -- Only using the last `m` gradient/state difference vectors, not building the full h_k matrix (Nocedal p226)\n let grad_prev = lastGrad bfgsParams\n x_prev = lastState bfgsParams\n ss_val = s_list bfgsParams\n ys_val = y_list bfgsParams\n km1 = numUnconstrSteps bfgsParams -- Our current step is k; the last step is km1 (k_minus_1)\n m = memSize bfgsParams\n in case (grad_prev, x_prev, ss_val, ys_val, km1) of\n\n -- Perform normal gradient descent on first step\n (Nothing, Nothing, [], [], 0) ->\n -- Store x_k, grad f(x_k) so we can compute s_k, y_k on next step\n let bfgsParams' = bfgsParams { lastState = Just x_k, lastGrad = Just grad_fx_k, \n s_list = [], y_list = [], numUnconstrSteps = km1 + 1 } in\n (gradEval, bfgsParams')\n\n (Just grad_fx_km1, Just x_km1, ss, ys, km1) -> \n -- Compute s_{k-1} = x_k - x_{k-1} and y_{k-1} = (analogous with grads)\n -- Unlike Nocedal, compute the difference vectors first instead of last (same result, just a loop rewrite)\n -- Use the updated {s_i} and {y_i}. (If k < m, this reduces to normal BFGS, i.e. we use all the vectors so far)\n let (s_km1, y_km1) = (x_k - x_km1, grad_fx_k - grad_fx_km1) -- Newest vectors added to front\n (ss', ys') = (take m $ s_km1 : ss, take m $ y_km1 : ys) -- The limited-memory part: drop stale vectors\n gradPreconditioned = lbfgs grad_fx_k ss' ys'\n descentDirCheck = -gradPreconditioned `L.dot` grad_fx_k\n\n -- Reset L-BFGS if the result is not a descent direction, and use steepest descent direction\n -- https://github.com/JuliaNLSolvers/Optim.jl/issues/143 https://github.com/JuliaNLSolvers/Optim.jl/pull/144\n\n in if descentDirCheck < epsd \n then (L.toList gradPreconditioned, bfgsParams { lastState = Just x_k, lastGrad = Just grad_fx_k,\n s_list = ss', y_list = ys', numUnconstrSteps = km1 + 1 })\n else tro \"L-BFGS did not find a descent direction. Resetting correction vectors.\" $\n (gradEval, bfgsParams { lastState = Just x_k, lastGrad = Just grad_fx_k,\n s_list = [], y_list = [], numUnconstrSteps = km1 + 1 })\n\n -- TODO: check the curvature condition y_k^T s_k > 0 (8.7) (Nocedal 201)\n -- https://github.com/JuliaNLSolvers/Optim.jl/issues/26\n\n _ -> error \"invalid L-BFGS state\"\n\ntype LVector = L.Vector L.R\ntype LMatrix = L.Matrix L.R\n\n-- See Nocedal p225\n-- expects ys and ss to be in order from most recent to oldest (k-1 ... k-m)\n-- expects length ys == length ss, length ys > 0, length ys > 0\nlbfgs :: LVector -> [LVector] -> [LVector] -> LVector\nlbfgs grad_fx_k ss ys =\n let rhos = map calculate_rho $ zip ss ys -- The length of any list should be the number of stored vectors\n q_k = grad_fx_k\n (q_k_minus_m, alphas) = foldl' pull_q_back (q_k, []) (zip3 rhos ss ys) -- backward: for i = k-1 ... k-m\n -- Note the order of alphas will be from k-m through k-1 for the push_r_forward loop\n h_0_k = estimate_hess (head ys) (head ss)\n r_k_minus_m = h_0_k L.#> q_k_minus_m\n r_k = foldl' push_r_forward r_k_minus_m (zip (zip (reverse rhos) alphas) (zip (reverse ss) (reverse ys)))\n -- forward: for i = k-m .. k-1 (TODO: optimize out the reverses)\n in r_k -- is H_k * grad f(x_k)\n\n where calculate_rho :: (LVector, LVector) -> L.R\n calculate_rho (s, y) = 1 / ((y `L.dot` s) + epsd)\n\n pull_q_back :: (LVector, [L.R]) -> (L.R, LVector, LVector) -> (LVector, [L.R]) -- from i+1 to i\n pull_q_back (q_i_plus_1, alphas) (rho_i, s_i, y_i) =\n let alpha_i = rho_i * (s_i `L.dot` q_i_plus_1) -- scalar\n q_i = q_i_plus_1 - (alpha_i `L.scale` y_i) -- scalar * vector\n in (q_i, alpha_i : alphas) -- Note the order of alphas\n\n -- Scale I by an estimate of the size of the Hessian along the most recent search direction (Nocedal p226)\n estimate_hess :: LVector -> LVector -> LMatrix\n estimate_hess y_km1 s_km1 = \n let gamma_k = (s_km1 `L.dot` y_km1) / ((y_km1 `L.dot` y_km1) + epsd)\n in gamma_k `L.scale` (L.ident (L.size y_km1))\n\n push_r_forward :: LVector -> ((L.R, L.R), (LVector, LVector)) -> LVector -- from i to i+1\n push_r_forward r_i ((rho_i, alpha_i), (s_i, y_i)) =\n let beta_i = rho_i * (y_i `L.dot` r_i) -- scalar\n r_i_plus_1 = r_i + (alpha_i - beta_i) `L.scale` s_i -- scalar * vector\n in r_i_plus_1\n\nestimateGradient :: ObjFn1 a -> [Float] -> [Float]\nestimateGradient f state =\n let len = length state\n h = 0.001 -- Choice of h really matters!!! This is not an accurate estimate.\n fx = f state\n -- time is O(|state|^2)\n dfx i = ((f $ replace i ((state !! i) + h) state) - fx) / h\n dfxs = map dfx [0..(len-1)]\n in dfxs\n where replace pos newVal list = take pos list ++ newVal : drop (pos+1) list\n\n-- Given the objective function, gradient function, timestep, and current state,\n-- return the timestep (found via line search) and evaluated gradient at the current state.\n-- the autodiff library requires that objective functions be polymorphic with Floating a\ntimeAndGrad :: OptConfig -> Params -> ObjFn1 a -> [Float] -> (Float, [Float], [Float], BfgsParams)\ntimeAndGrad config params f state = \n let gradEval = if useAutodiff then gradF state else estimateGradient f state\n (gradToUse_d, bfgs') = gradP config (bfgsInfo params) (map r2f gradEval :: [Double]) f state\n gradToUse = map r2f gradToUse_d\n -- Use line search to find a good timestep. If we use Newton's method, the descent direction uses the preconditioned gradient.\n descentDir = negL $ gradToUse\n timestep = let resT = if useLineSearch && useAutodiff\n then awLineSearch config f (duf descentDir) descentDir state\n else constT in -- hardcoded timestep\n if isNaN resT then error \"returned timestep is NaN\" else resT\n \n in tr \"timeAndGrad: \" (timestep, gradEval, gradToUse, bfgs')\n\n where gradF :: GradFn a\n gradF = appGrad f\n\n -- directional derivative of f at x in the direction of u (descent direction, which may not have unit norm)\n duf :: (Autofloat a) => [a] -> [a] -> a\n duf u x = u `dotL` gradF x\n\nlinesearch_max :: Int\nlinesearch_max = 100 -- TODO what's a reasonable limit (if any)?\n\n-- Implements Armijo-Wolfe line search as specified in Keenan's notes, converges on nonconvex fns as well\n-- based off Lewis & Overton, \"Nonsmooth optimization via quasi-Newton methods\n-- duf = D_u(f), the directional derivative of f at descent direction u\n-- D_u(x) = . If u = -gradF(x) (as it is here), then D_u(x) = -||gradF(x)||^2\n\nawLineSearch :: OptConfig -> ObjFn1 a -> ObjFn1 a -> [Float] -> [Float] -> Float\nawLineSearch config f duf descentDir x0 =\n\n let (a0, b0, t0) = (0, infinity, 1) -- Unit step length should be tried first for quasi-Newton methods. (Nocedal 201)\n\n -- drop while a&w are not satisfied OR the interval is large enough\n (numUpdates, (af, bf, tf)) = head $ dropWhile intervalOK_or_notArmijoAndWolfe\n $ zip [0..] $ iterate update (a0, b0, t0)\n\n in tro (\"Line search # updates: \" ++ show numUpdates) $ tf\n\n where update :: (Float, Float, Float) -> (Float, Float, Float)\n update (a, b, t) =\n let (a', b', sat) | not $ armijo t = trl \"not armijo\" (a, t, False)\n | not $ wolfe t = trl \"not wolfe\" (t, b, False)\n | otherwise = (a, b, True) in\n if sat then (a, b, t) -- if armijo and wolfe, then we use (a, b, t) as-is\n else if b' < infinity then trl \"b' < infinity\" (a', b', (a' + b') / 2)\n else trl \"b' = infinity\" (a', b', 2 * a')\n\n intervalOK_or_notArmijoAndWolfe :: (Int, (Float, Float, Float)) -> Bool\n intervalOK_or_notArmijoAndWolfe (numUpdates, (a, b, t)) =\n not $\n if armijo t && wolfe t then\n trl (\"stop: both sat. |descentDir at x0| = \" ++ show (norm descentDir)) True\n else if abs (b - a) < minInterval then\n trl (\"stop: interval too small. |descentDir at x0| = \" ++ show (norm descentDir)) True\n else if numUpdates > linesearch_max then\n trl (\"stop: number of line search updates exceeded max\") True\n else False\n\n armijo :: Float -> Bool\n armijo t = (f (x0 +. t *. descentDir)) <= (fAtx0 + c1 * t * dufAtx0)\n\n weakWolfe :: Float -> Bool -- Better for nonsmooth functions\n weakWolfe t = (duf (x0 +. t *. descentDir)) >= (c2 * dufAtx0)\n\n strongWolfe :: Float -> Bool\n strongWolfe t = (abs (duf (x0 +. t *. descentDir))) <= (c2 * abs dufAtx0)\n\n -- Descent direction (at x0) must have a negative dot product with the gradient of f at x0.\n dufAtx0 :: Float -- TODO: this is redundant, cache it\n dufAtx0 = let res = duf x0 in\n trl (\": \" ++ show res) $ \n if res > 0 then tro \"WARNING: descent direction doesn't satisfy condition\" res else res\n\n fAtx0 :: Float\n fAtx0 = f x0\n\n minInterval :: Float -- stop if the interval gets too small; might not terminate\n minInterval = if intervalMin then 10 ** (-10) else 0\n -- TODO: the line search is very sensitive to this parameter. Blows up with 10**(-5). Why?\n\n wolfe :: Float -> Bool\n wolfe = weakWolfe\n", "meta": {"hexsha": "6d66e8c4153930ba46fc63855c3d91303c2652ca", "size": 26321, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Optimizer.hs", "max_stars_repo_name": "daodaoliang/penrose", "max_stars_repo_head_hexsha": "1a76b15640f962f4da52c8aab075a633a61885e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-30T07:55:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T07:55:04.000Z", "max_issues_repo_path": "src/Optimizer.hs", "max_issues_repo_name": "daodaoliang/penrose", "max_issues_repo_head_hexsha": "1a76b15640f962f4da52c8aab075a633a61885e1", "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/Optimizer.hs", "max_forks_repo_name": "daodaoliang/penrose", "max_forks_repo_head_hexsha": "1a76b15640f962f4da52c8aab075a633a61885e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.9597585513, "max_line_length": 143, "alphanum_fraction": 0.5763458835, "num_tokens": 6979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5115145537955192}} {"text": "{-# LANGUAGE RankNTypes, FlexibleContexts, TypeFamilies #-}\n\nmodule Numeric.Trainee.Gradee (\n\tGradee(..), gradee, ad,\n\tUnary, Binary,\n\tunary, binary,\n\tdup, vdup, vdupWith,\n\tconjoin, plus, vconjoin, vsum, vfold,\n\tswap,\n\n\tmatMat, matVec, odot,\n\tcorrVec, corrMat,\n\tflattenMat, reshapeVec, concatVecs,\n\ttransposeMat,\n\tvecRow, vecCol,\n\tbiasVec, biasMat,\n\tmaxPoolVec, maxPoolMat,\n\tpadVec, padMat\n\t) where\n\nimport Prelude hiding (id, (.))\nimport Prelude.Unicode\n\nimport Control.Category\nimport Control.Lens (lens)\nimport Data.Reflection (Reifies, reify)\nimport qualified Data.Vector as V\nimport Numeric.AD (grad, auto)\nimport Numeric.AD.Internal.Reverse (Reverse, primal, Tape)\nimport Numeric.LinearAlgebra\n\nimport Numeric.Trainee.Types\n\n-- | Make Gradee like lens\ngradee ∷ (a → b) → (a → b → a) → Gradee a b\ngradee g s = Gradee $ lens g s\n\n-- | Make like lens from binary op\ngradee2 ∷ (a → b → c) → (a → b → c → (a, b)) → Gradee (a, b) c\ngradee2 g s = gradee (uncurry g) (uncurry s)\n\n-- | Make Gradee from any function\nad ∷ (Traversable f, Num a) ⇒ (forall s . Reifies s Tape ⇒ f (Reverse s a) → Reverse s a) → Gradee (f a) a\nad f = gradee f' (\\x dx → fmap (* dx) (grad f x)) where\n\tf' = reify undefined (\\p → primal ∘ spec p f ∘ fmap auto)\n\tspec ∷ Reifies t Tape ⇒ proxy t → (forall s . Reifies s Tape ⇒ g (Reverse s a) → Reverse s a) → g (Reverse t a) → Reverse t a\n\tspec _ h = h\n\ntype Unary a = forall s . Reifies s Tape ⇒ Reverse s a → Reverse s a\ntype Binary a = forall s . Reifies s Tape ⇒ Reverse s a → Reverse s a → Reverse s a\n\n-- | Make Gradee from unary function\nunary ∷ Num a ⇒ Unary a → Gradee a a\nunary f = ad (\\[x] → f x) . gradee return (const head)\n\n-- | Make @Gradee@ from binary function\nbinary ∷ Num a ⇒ Binary a → Gradee (a, a) a\nbinary f = ad (\\[x, y] → f x y) . gradee g s where\n\tg (x, y) = [x, y]\n\ts _ [x, y] = (x, y)\n\ts _ _ = error \"binary\"\n\ndup ∷ Num a ⇒ Gradee a (a, a)\ndup = gradee (\\x → (x, x)) (\\_ (dx', dx'') → dx' + dx'')\n\nvdup ∷ Num a ⇒ Int → Gradee a (V.Vector a)\nvdup n = gradee (V.replicate n) (const V.sum)\n\nvdupWith ∷ (a → a → a) → Int → Gradee a (V.Vector a)\nvdupWith fn n\n\t| n ≤ 0 = error \"vdupWith: negative argument\"\n\t| otherwise = gradee (V.replicate n) (const $ V.foldr1 fn)\n\nconjoin ∷ Num a ⇒ Gradee (a, a) a\nconjoin = binary (+)\n\nplus ∷ Num a ⇒ Gradee (a, a) a\nplus = conjoin\n\nvconjoin ∷ Num a ⇒ Gradee (V.Vector a) a\nvconjoin = ad V.sum\n\nvsum ∷ Num a ⇒ Gradee (V.Vector a) a\nvsum = vconjoin\n\nvfold ∷ (a → a → a) → Gradee (V.Vector a) a\nvfold fn = gradee (V.foldr1 fn) (V.replicate ∘ V.length)\n\nswap ∷ Gradee (a, b) (b, a)\nswap = gradee (\\(x, y) → (y, x)) (\\_ (dy, dx) → (dx, dy))\n\nmatMat ∷ Numeric a ⇒ Gradee (Matrix a, Matrix a) (Matrix a)\nmatMat = gradee2 (<>) backprop where\n\tbackprop a b dc = (dc <> tr b, tr a <> dc)\n\nmatVec ∷ Numeric a ⇒ Gradee (Matrix a, Vector a) (Vector a)\nmatVec = gradee2 (#>) backprop where\n\tbackprop a b dc = (outer dc b, tr a #> dc)\n\nodot ∷ Num (Vector a) ⇒ Gradee (Vector a, Vector a) (Vector a)\nodot = gradee2 (+) backprop where\n\tbackprop _ _ dc = (dc, dc)\n\ncorrVec ∷ Numeric a ⇒ Gradee (Vector a, Vector a) (Vector a)\ncorrVec = gradee2 corr backprop where\n\tbackprop a b dc = (corr dc b, conv a dc)\n\ncorrMat ∷ (Numeric a, Num (Vector a)) ⇒ Gradee (Matrix a, Matrix a) (Matrix a)\ncorrMat = gradee2 corr2 backprop where\n\tbackprop a b dc = (corr2 dc b, conv2 a dc)\n\nflattenMat ∷ Numeric a ⇒ Gradee (Matrix a) (Vector a)\nflattenMat = gradee flatten backprop where\n\tbackprop a = reshape (cols a)\n\nreshapeVec ∷ Numeric a ⇒ Int → Gradee (Vector a) (Matrix a)\nreshapeVec cols' = gradee (reshape cols') (const flatten)\n\nconcatVecs ∷ Numeric a ⇒ Gradee (V.Vector (Vector a)) (Vector a)\nconcatVecs = gradee\n\t(vjoin ∘ V.toList)\n\t(\\vs → V.fromList ∘ takesV (V.toList (V.map size vs)))\n\ntransposeMat ∷ Numeric a ⇒ Gradee (Matrix a) (Matrix a)\ntransposeMat = gradee tr (const tr)\n\nvecRow ∷ Numeric a ⇒ Gradee (Vector a) (Matrix a)\nvecRow = gradee asRow (const flatten)\n\nvecCol ∷ Numeric a ⇒ Gradee (Vector a) (Matrix a)\nvecCol = gradee asColumn (const flatten)\n\nbiasVec ∷ Numeric a ⇒ Gradee (a, Vector a) (Vector a)\nbiasVec = gradee2 (\\b v → cmap (+ b) v) backprop where\n\tbackprop _ _ dv = (sumElements dv, dv)\n\nbiasMat ∷ Numeric a ⇒ Gradee (a, Matrix a) (Matrix a)\nbiasMat = gradee2 (\\b m → cmap (+ b) m) backprop where\n\tbackprop _ _ dm = (sumElements dm, dm)\n\nmaxPoolVec ∷ (RealFrac a, Numeric a) ⇒ Int → Gradee (Vector a) (Vector a)\nmaxPoolVec n = gradee pool' unpool' where\n\tpool' v = build (size v `div` n) $ \\i → maxElement (subVector (round i * n) n v)\n\tunpool' v dv = accum zero (+) (zip maxIndices (toList dv)) where\n\t\tmaxIndices = map (\\i → maxIndex (subVector (i * n) n v) + i * n) [0 .. size dv - 1]\n\t\tzero = build (size v) (const 0)\n\nmaxPoolMat ∷ (RealFrac a, Numeric a) ⇒ Int → Int → Gradee (Matrix a) (Matrix a)\nmaxPoolMat w h = gradee pool' unpool' where\n\tpool' m = build (rows m `div` h, cols m `div` w) $ \\i j → maxElement (subMatrix (round i * h, round j * w) (h, w) m)\n\tunpool' m dm = accum zero (+) (zip maxIndices (toList $ flatten dm)) where\n\t\tmaxIndices = map (\\(i, j) → maxIndex (subMatrix (i * h, j * w) (h, w) m) `biplus` (i * h, j * w)) [(i, j) | i ← [0 .. rows dm - 1], j ← [0 .. cols dm - 1]]\n\t\tzero = build (size m) (const $ const 0)\n\t\tbiplus (lx, ly) (rx, ry) = (lx + rx, ly + ry)\n\npadVec ∷ Numeric a ⇒ Int → Gradee (Vector a) (Vector a)\npadVec n = gradee pad' unpad' where\n\tpad' v = vjoin [zeroes', v, zeroes'] where\n\t\tzeroes' = build n (const 0)\n\tunpad' = subVector n ∘ size\n\npadMat ∷ Numeric a ⇒ Int → Int → Gradee (Matrix a) (Matrix a)\npadMat w h = gradee pad' unpad' where\n\tpad' m = diagBlock [zeroes', m, zeroes'] where\n\t\tzeroes' = build (h, w) (const $ const 0)\n\tunpad' = subMatrix (h, w) ∘ size\n", "meta": {"hexsha": "594d0470ea9edf1b94ad31a0f33dc7a9bf90363f", "size": 5694, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Trainee/Gradee.hs", "max_stars_repo_name": "mvoidex/trainee", "max_stars_repo_head_hexsha": "60a935e53cabcf145736716829ee1be986b0ffc7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-04-25T19:54:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-20T03:03:26.000Z", "max_issues_repo_path": "src/Numeric/Trainee/Gradee.hs", "max_issues_repo_name": "mvoidex/trainee", "max_issues_repo_head_hexsha": "60a935e53cabcf145736716829ee1be986b0ffc7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Trainee/Gradee.hs", "max_forks_repo_name": "mvoidex/trainee", "max_forks_repo_head_hexsha": "60a935e53cabcf145736716829ee1be986b0ffc7", "max_forks_repo_licenses": ["BSD-3-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.0958083832, "max_line_length": 157, "alphanum_fraction": 0.6397962768, "num_tokens": 2032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5109387658565581}} {"text": "-- Copyright (c) 2015 James M. Lawrence\n--\n-- Permission is hereby granted, free of charge, to any person obtaining\n-- a copy of this software and associated documentation files (the\n-- \"Software\"), to deal in the Software without restriction, including\n-- without limitation the rights to use, copy, modify, merge, publish,\n-- distribute, sublicense, and/or sell copies of the Software, and to\n-- permit persons to whom the Software is furnished to do so, subject to\n-- the following conditions:\n--\n-- The above copyright notice and this permission notice shall be included\n-- in all copies or substantial portions of the Software.\n--\n-- THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n-- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n-- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n-- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n-- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n--\n-----------------------------------------------------------------------------\n-- |\n-- Module : Math.CayleyDickson\n-- Copyright : (c) James M. Lawrence\n-- License : MIT\n--\n-- Maintainer : James M. Lawrence \n-- Stability : provisional\n-- Portability : portable\n--\n-- Cayley-Dickson constructions (complex numbers, quaternions,\n-- octonions, sedenions, etc.) over general scalars without limit to\n-- the number of dimensions.\n--\n-- An element of this structure is composed of an m-dimensional\n-- /scalar part/ and an m*(2^n - 1)-dimensional /pure part/ (unrelated\n-- to Haskell's uses of \"pure\"). An element whose scalar part is zero\n-- is called a /pure/. Construction with real scalars yields the\n-- Cayley-Dickson algebras, in which case the scalar part is also\n-- called the /real part/. Other structures may be obtained by\n-- considering general scalars, for instance the quaternions over\n-- complex scalars.\n-----------------------------------------------------------------------------\n\nmodule Math.CayleyDickson (\n -- * Types\n Nion, Complex, Quaternion, Octonion, Sedenion,\n\n -- * Construction\n nion, fromScalar, complex, quaternion, octonion, sedenion,\n\n -- * Operations\n dot, cross, sqnorm, norm, polar,\n -- ** Operations with scalars\n --\n -- | The mnemonic is that the period (\".\") is on the side of the\n -- scalar.\n (**.),\n (.+), (+.), (.-), (-.), (.*), (*.), (/.),\n\n -- * Accessors\n coord, coords, setCoord, scalarPart, purePart,\n\n -- * Constants\n basisElement,\n\n -- * Classes\n Conjugable(..),\n\n -- ** Tags\n Tag(tagVal),\n Tag0, Tag1, Tag2, Tag3, Tag4, Tag5, Tag6, Tag7, Tag8, Tag9,\n Tag10, Tag11, Tag12, Tag13, Tag14, Tag15, Tag16, Tag17, Tag18, Tag19,\n Tag20, Tag21, Tag22, Tag23, Tag24, Tag25, Tag26, Tag27, Tag28, Tag29,\n Tag30,\n\n ) where\n\n----------------------------------------------------------\n-- import\n\nimport Data.List (genericSplitAt, genericTake, genericReplicate, genericLength)\nimport Data.Bits (Bits, testBit)\nimport Data.Proxy (Proxy(Proxy))\nimport qualified Data.Int as Z\nimport qualified Data.Ratio as Q\nimport qualified Data.Complex as C\nimport qualified Data.Fixed as F\nimport qualified Data.Word as W\n\n----------------------------------------------------------\n-- infix\n\ninfix 6 :@\n\ninfix 6 .+\ninfix 6 +.\ninfix 6 .-\ninfix 6 -.\n\ninfix 7 .*\ninfix 7 *.\ninfix 7 /.\n\ninfixr 8 **.\n\n----------------------------------------------------------\n-- Nion\n\n-- | General Cayley-Dickson construction producing \\\"N-ions\\\". The\n-- first parameter is a 'Tag' instance that determines the dimension,\n-- which is 2 raised to 'tagVal'. The second parameter is the scalar\n-- type.\ndata Nion n a = Scalar a | Nion n a :@ Nion n a\n\n----------------------------------------------------------\n-- basic operations\n\n-- | Equivalent to @'coord' x 0@.\nscalarPart :: Nion n a -> a\nscalarPart (Scalar x) = x\nscalarPart (x :@ _) = scalarPart x\n\n-- | Equivalent to @'setCoord' x 0 0@.\npurePart :: Num a => Nion n a -> Nion n a\npurePart (Scalar _) = Scalar 0\npurePart (x :@ y) = purePart x :@ y\n\n-- | Dot product. For real scalars, @(1 \\`dot\\`)@ is equivalent to\n-- @'scalarPart'@.\ndot :: Conjugable a => Nion n a -> Nion n a -> a\n-- (y * conj x + x * conj y) / 2\nScalar x `dot` Scalar y = scalarPart' $ y * conj x\nx@(Scalar _) `dot` (y1 :@ _) = x `dot` y1\n(x1 :@ _) `dot` y@(Scalar _) = x1 `dot` y\n(x1 :@ x2) `dot` (y1 :@ y2) = (x1 `dot` y1) + (x2 `dot` y2)\n\n-- | Cross product. The cross product of two pures yields a pure that\n-- is orthogonal to both operands. For real scalars, @(1 \\`cross\\`)@\n-- is equivalent to @'purePart'@.\ncross :: Conjugable a => Nion n a -> Nion n a -> Nion n a\n-- (y * conj x - x * conj y) / 2\nx `cross` y = y * conj x -. x `dot` y\n\n-- | Squared norm: the dot product of an element with itself.\nsqnorm :: Conjugable a => Nion n a -> a\nsqnorm x = x `dot` x\n\n-- | Square root of @sqnorm@.\nnorm :: (Conjugable a, Floating a) => Nion n a -> a\nnorm = sqrt . sqnorm\n\n-- | Promote a scalar, returning an element whose scalar part is the\n-- argument and whose pure part is zero. The element behaves as if it\n-- were padded with zeros, but no actual padding is done.\nfromScalar :: a -> Nion n a\nfromScalar = Scalar\n\n----------------------------------------------------------\n-- operations with scalars\n\nleftScalarOp :: (Nion n a -> Nion n a -> Nion n a) -> a -> Nion n a -> Nion n a\nleftScalarOp f x y = f (Scalar x) y\n\nrightScalarOp :: (Nion n a -> Nion n a -> Nion n a) -> Nion n a -> a -> Nion n a\nrightScalarOp f x y = f x (Scalar y)\n\n-- | Equivalent to @'fromScalar' x + y@.\n(.+) :: Conjugable a => a -> Nion n a -> Nion n a\n(.+) = leftScalarOp (+)\n\n-- | Equivalent to @'fromScalar' x - y@.\n(.-) :: Conjugable a => a -> Nion n a -> Nion n a\n(.-) = leftScalarOp (-)\n\n-- | Equivalent to @'fromScalar' x * y@.\n(.*) :: Conjugable a => a -> Nion n a -> Nion n a\n(.*) = leftScalarOp (*)\n\n-- | Equivalent to @x + 'fromScalar' y@.\n(+.) :: Conjugable a => Nion n a -> a -> Nion n a\n(+.) = rightScalarOp (+)\n\n-- | Equivalent to @x - 'fromScalar' y@.\n(-.) :: Conjugable a => Nion n a -> a -> Nion n a\n(-.) = rightScalarOp (-)\n\n-- | Equivalent to @x * 'fromScalar' y@.\n(*.) :: Conjugable a => Nion n a -> a -> Nion n a\n(*.) = rightScalarOp (*)\n\n-- | Equivalent to @x / 'fromScalar' y@.\n(/.) :: (Conjugable a, Fractional a) => Nion n a -> a -> Nion n a\n(/.) = rightScalarOp (/)\n\n-- | Raise to a scalar power.\n(**.) :: (Tag n, Conjugable a, RealFloat a) => Nion n a -> a -> Nion n a\nScalar x **. y = Scalar $ x ** y\nx **. y = exp (y .* log x)\n\n----------------------------------------------------------\n-- polar form and complex function application\n\nrealPolar :: RealFloat a => Nion n a -> a -> (a, a, Nion n a)\nrealPolar sqrtMinus1 r\n | r >= 0 = (r, 0, sqrtMinus1)\n | otherwise = (-r, pi, sqrtMinus1)\n\npolarUsing :: (Conjugable a, RealFloat a) =>\n Nion n a -> Nion n a -> (a, a, Nion n a)\npolarUsing sqrtMinus1 (Scalar r) = realPolar sqrtMinus1 r\npolarUsing sqrtMinus1 x\n | sqnormp == 0 = realPolar sqrtMinus1 r\n | otherwise = (normx, acos (r / normx), u)\n where\n p = purePart x\n sqnormp = sqnorm p\n u = p /. sqrt sqnormp\n r = scalarPart x\n normx = sqrt $ sqnormp + r * conj r\n\npolar' :: (Tag n, Conjugable a, RealFloat a) =>\n Proxy n -> Nion n a -> (a, a, Nion n a)\npolar' n x\n | tagVal n == 0 = error \"polar: no polar form in 1 dimension\"\n | otherwise = polarUsing basisElement1 x\n\n-- | Return @(s, t, u)@ such that (approximately)\n--\n-- @x == s .* 'exp' (t .* u)@\n--\n-- where @s@ and @t@ are scalars, @s >= 0@, and @u@ is a unit pure.\n--\n-- If @x@ has no pure part then @u@ is arbitrarily chosen to be the\n-- first pure basis element.\npolar :: (Tag n, Conjugable a, RealFloat a) => Nion n a -> (a, a, Nion n a)\npolar = polar' Proxy\n\napplyUsing' :: (Tag n, Conjugable a, RealFloat a) =>\n Proxy n ->\n Nion n a -> (a -> a) -> (C.Complex a -> C.Complex a) ->\n Nion n a -> Nion n a\napplyUsing' n sqrtMinus1 fr f z\n | tagVal n == 0 = Scalar $ fr $ scalarPart z\n | otherwise = x .+ u *. y\n where (s, t, u) = polarUsing sqrtMinus1 z\n -- handle special cases for a little more accuracy\n x C.:+ y | t == 0 = f $ c s 0\n | t == pi = f $ c (-s) 0\n | otherwise = f $ c s 0 * exp (c t 0 * c 0 1)\n where c = (C.:+)\n\napplyUsing :: (Tag n, Conjugable a, RealFloat a) =>\n Nion n a -> (a -> a) -> (C.Complex a -> C.Complex a) ->\n Nion n a -> Nion n a\napplyUsing = applyUsing' Proxy\n\n----------------------------------------------------------\n-- constants\n\nfill' :: Tag n => Proxy n -> a -> Nion n a\nfill' n s = f $ tagVal n where\n f 0 = Scalar s\n f k = f k' :@ f k' where k' = k - 1\n\nfill :: Tag n => a -> Nion n a\nfill = fill' Proxy\n\npaddedZero :: (Tag n, Num a) => Nion n a\npaddedZero = fill 0\n\nvalidIndex :: (Tag n, Num b, Ord b) => Proxy n -> b -> Bool\nvalidIndex n i = i >= 0 && i < 2 ^ tagVal n\n\nbasisElement' :: (Tag n, Conjugable a, Bits i, Integral i) =>\n Proxy n -> i -> Nion n a\nbasisElement' _ 0 = Scalar 1\nbasisElement' n index\n | validIndex n index = setCoord paddedZero index 1\n | otherwise = error \"basisElement: out of range\"\n\n-- | The nth basis element.\nbasisElement :: (Tag n, Conjugable a, Bits i, Integral i) => i -> Nion n a\nbasisElement = basisElement' Proxy\n\nbasisElement1 :: (Tag n, Conjugable a) => Nion n a\nbasisElement1 = basisElement (1 :: Integer)\n\n----------------------------------------------------------\n-- util\n\n-- Proper Functor and Foldable instances would have to translate\n-- top-level scalars to their equivalent representation with padded\n-- zeros. The machinations needed for this indirection are rather\n-- cumbersome relative to the benefits of having the instances, whose\n-- use would seem uncommon.\n\nsmap :: (a -> a) -> Nion n a -> Nion n a\nsmap f (Scalar s) = Scalar $ f s\nsmap f (x :@ y) = smap f x :@ smap f y\n\nsfoldr :: (a -> b -> b) -> b -> Nion n a -> b\nsfoldr f acc (Scalar x) = f x acc\nsfoldr f acc (x :@ y) = sfoldr f (sfoldr f acc y) x\n\n----------------------------------------------------------\n-- accessors\n\ncoords' :: (Tag n, Num a) => Proxy n -> Nion n a -> [a]\ncoords' n (Scalar x) = x : genericReplicate k 0 where\n k = 2 ^ tagVal n - 1 :: Integer\ncoords' _ x = sfoldr (:) [] x\n\n-- | List of coordinates for this element.\ncoords :: (Tag n, Num a) => Nion n a -> [a]\ncoords = coords' Proxy\n\ncoord' :: (Tag n, Num a, Integral b, Bits b) => Proxy n -> Nion n a -> b -> a\ncoord' _ (Scalar x) 0 = x\ncoord' n elt index\n | validIndex n index = case elt of\n Scalar _ -> 0\n _ -> f elt $ fromInteger $ tagVal n - 1\n | otherwise = error \"coord: out of range\"\n where\n f (Scalar x) _ = x\n f (x :@ y) k = case testBit index k of\n False -> f x k'\n True -> f y k'\n where k' = k - 1\n\n-- | Get the nth coordinate.\ncoord :: (Tag n, Num a, Integral b, Bits b) => Nion n a -> b -> a\ncoord = coord' Proxy\n\nsetCoord' :: (Tag n, Conjugable a, Integral b, Bits b) =>\n Proxy n -> Nion n a -> b -> a -> Nion n a\nsetCoord' _ (Scalar _) 0 value = Scalar value\nsetCoord' n elt index value\n | validIndex n index = case elt of\n Scalar x -> setCoord (x .+ paddedZero) index value\n _ -> f elt $ fromInteger $ tagVal n - 1\n | otherwise = error \"setCoord: out of range\"\n where\n f (Scalar _) _ = Scalar value\n f (x :@ y) k = case testBit index k of\n False -> f x k' :@ y\n True -> x :@ f y k'\n where k' = k - 1\n\n-- | Set the nth coordinate, returning a new element.\nsetCoord :: (Tag n, Conjugable a, Integral b, Bits b) =>\n Nion n a -> b -> a -> Nion n a\nsetCoord = setCoord' Proxy\n\n----------------------------------------------------------\n-- construction\n\nfromList :: Integer -> [a] -> Nion n a\nfromList _ (x:[]) = Scalar x\nfromList k xs = fromList k' l :@ fromList k' r where\n k' = k `div` 2\n (l, r) = genericSplitAt k' xs\n\nnion' :: (Tag n, Num a) => Proxy n -> [a] -> Nion n a\nnion' n elems = fromList d $ taken ++ padding where\n d = 2 ^ tagVal n\n taken = genericTake d elems\n padding = genericReplicate (d - genericLength taken) 0\n\n-- | Construct an element from a list of coordinates. If the list is\n-- too small then the remaining coordinates are padded with zeros. If\n-- the list is too large then the extra values are ignored.\nnion :: (Tag n, Num a) => [a] -> Nion n a\nnion = nion' Proxy\n\n----------------------------------------------------------\n-- instances\n\ninstance (Tag n, Show a, Num a) => Show (Nion n a) where\n show x = \"nion \" ++ show (coords x)\n\ninstance (Conjugable a, Eq a) => Eq (Nion n a) where\n Scalar x == Scalar y = x == y\n x@(Scalar _) == y1 :@ y2 = x == y1 && y2 == 0\n x1 :@ x2 == y@(Scalar _) = x1 == y && x2 == 0\n x1 :@ x2 == y1 :@ y2 = x1 == y1 && x2 == y2\n\ninstance Conjugable a => Num (Nion n a) where\n Scalar x + Scalar y = Scalar $ x + y\n x@(Scalar _) + (y1 :@ y2) = (x + y1) :@ y2\n (x1 :@ x2) + y@(Scalar _) = (x1 + y) :@ x2\n (x1 :@ y1) + (x2 :@ y2) = (x1 + x2) :@ (y1 + y2)\n\n Scalar x - Scalar y = Scalar $ x - y\n x@(Scalar _) - (y1 :@ y2) = (x - y1) :@ negate y2\n (x1 :@ x2) - y@(Scalar _) = (x1 - y) :@ x2\n (x1 :@ y1) - (x2 :@ y2) = (x1 - x2) :@ (y1 - y2)\n\n Scalar x * Scalar y = Scalar $ x * y\n x@(Scalar _) * (y1 :@ y2) = (x * y1) :@ (x * y2)\n (x1 :@ x2) * y@(Scalar _) = (x1 * y) :@ (x2 * y)\n (x1 :@ x2) * (y1 :@ y2) = (x1 * y1 - conj y2 * x2) :@ (y2 * x1 + x2 * conj y1)\n\n negate = smap negate\n fromInteger = fromScalar . fromInteger\n abs = doNotUse\n signum = doNotUse\n\ninstance (Conjugable a, Fractional a) => Fractional (Nion n a) where\n Scalar x / Scalar y = Scalar $ x / y\n x@(_ :@ _) / Scalar y = smap (/ y) x\n x / y = (x * conj y) /. sqnorm y\n\n recip x = conj x /. sqnorm x\n fromRational = fromScalar . fromRational\n\n-- | The first pure basis element is arbitrarily chosen as sqrt (-1).\ninstance (Tag n, Conjugable a, RealFloat a) => Floating (Nion n a) where\n pi = Scalar pi\n exp = applyUsing basisElement1 exp exp\n log = applyUsing basisElement1 log log\n sqrt = applyUsing basisElement1 sqrt sqrt\n sin = applyUsing basisElement1 sin sin\n cos = applyUsing basisElement1 cos cos\n tan = applyUsing basisElement1 tan tan\n asin = applyUsing basisElement1 asin asin\n acos = applyUsing basisElement1 acos acos\n atan = applyUsing basisElement1 atan atan\n sinh = applyUsing basisElement1 sinh sinh\n cosh = applyUsing basisElement1 cosh cosh\n tanh = applyUsing basisElement1 tanh tanh\n asinh = applyUsing basisElement1 asinh asinh\n acosh = applyUsing basisElement1 acosh acosh\n atanh = applyUsing basisElement1 atanh atanh\n\n----------------------------------------------------------\n-- convenience types\n\n-- | Complex numbers, the 2^1-dimensional construction.\ntype Complex a = Nion Tag1 a\n\n-- | Quaternions, the 2^2-dimensional construction.\ntype Quaternion a = Nion Tag2 a\n\n-- | Octonions, the 2^3-dimensional construction.\ntype Octonion a = Nion Tag3 a\n\n-- | Sedenions, the 2^4-dimensional construction.\ntype Sedenion a = Nion Tag4 a\n\n-- | Construct a complex number.\ncomplex :: a -> a -> Complex a\ncomplex x y = (:@) (Scalar x) (Scalar y)\n\n-- | Construct a quaternion.\nquaternion :: a -> a -> a -> a -> Quaternion a\nquaternion w x y z = (:@) ((:@) (Scalar w) (Scalar x))\n ((:@) (Scalar y) (Scalar z))\n\n-- | Construct an octonion.\noctonion :: a -> a -> a -> a ->\n a -> a -> a -> a -> Octonion a\noctonion s t u v\n w x y z = (:@) ((:@) ((:@) (Scalar s) (Scalar t))\n ((:@) (Scalar u) (Scalar v)))\n ((:@) ((:@) (Scalar w) (Scalar x))\n ((:@) (Scalar y) (Scalar z)))\n\n-- | Construct a sedenion.\nsedenion :: a -> a -> a -> a ->\n a -> a -> a -> a ->\n a -> a -> a -> a ->\n a -> a -> a -> a -> Sedenion a\nsedenion k l m n\n o p q r\n s t u v\n w x y z = (:@) ((:@) ((:@) ((:@) (Scalar k) (Scalar l))\n ((:@) (Scalar m) (Scalar n)))\n ((:@) ((:@) (Scalar o) (Scalar p))\n ((:@) (Scalar q) (Scalar r))))\n ((:@) ((:@) ((:@) (Scalar s) (Scalar t))\n ((:@) (Scalar u) (Scalar v)))\n ((:@) ((:@) (Scalar w) (Scalar x))\n ((:@) (Scalar y) (Scalar z))))\n\n----------------------------------------------------------\n-- Conjugable\n\n-- | The /conjugate/ of an element is obtained by negating the pure\n-- part and conjugating the scalar part. The conjugate of a real\n-- number is the identity ('id'), which is the default implementation.\nclass Num a => Conjugable a where\n -- | Conjugate.\n conj :: a -> a\n conj = id\n\n -- | Equivalent to @(x + conj x) / 2@.\n scalarPart' :: a -> a\n scalarPart' = id\n\ninstance Conjugable a => Conjugable (Nion n a) where\n conj (Scalar x) = Scalar $ conj x\n conj (x :@ y) = conj x :@ negate y\n\n scalarPart' (Scalar x) = Scalar $ scalarPart' x\n scalarPart' (x :@ _) = scalarPart' x\n\ninstance (Conjugable a, RealFloat a) => Conjugable (C.Complex a) where\n conj = C.conjugate\n scalarPart' (x C.:+ _) = scalarPart' x C.:+ 0\n\ninstance Conjugable Int\ninstance Conjugable Integer\ninstance Conjugable Float\ninstance Conjugable Double\ninstance Conjugable Z.Int8\ninstance Conjugable Z.Int16\ninstance Conjugable Z.Int32\ninstance Conjugable Z.Int64\ninstance Conjugable W.Word8\ninstance Conjugable W.Word16\ninstance Conjugable W.Word32\ninstance Conjugable W.Word64\ninstance Integral a => Conjugable (Q.Ratio a)\ninstance F.HasResolution a => Conjugable (F.Fixed a)\n\n-----------------------------------------------------------------------------\n-- doNotUse\n\nrant :: String\nrant = unlines $\n [\"\",\n \"The Num class is a bit messed up, having tied (+), (-), and (*) to abs\",\n \"and signum. Number systems that have no appropriate definition for abs\",\n \"or signum must either invent their own operators for addition,\",\n \"subtraction, and multiplication, else break the contract with Num by\",\n \"raising an error such as this one when someone uses abs or signum.\",\n \"\",\n \"For some time I resisted hijacking Num, but eventually the replacement\",\n \"operators became too cumbersome and, coupled with the lack of numeric\",\n \"promotion, significantly detracted from the usability of the package.\",\n \"So here we are. Good luck, and stay away from abs and signum, which\",\n \"officially have cooties.\"]\n\ndoNotUse :: a -> a\ndoNotUse _ = error rant\n\n----------------------------------------------------------\n-- Tag\n\n-- | Tags serve to determine a type's dimension, which is 2 raised to\n-- `tagVal`. Tag instances are included for convenience only, as you\n-- may create your own tag.\nclass Tag n where\n tagVal :: Proxy n -> Integer\n\ndata Tag0\ndata Tag1\ndata Tag2\ndata Tag3\ndata Tag4\ndata Tag5\ndata Tag6\ndata Tag7\ndata Tag8\ndata Tag9\ndata Tag10\ndata Tag11\ndata Tag12\ndata Tag13\ndata Tag14\ndata Tag15\ndata Tag16\ndata Tag17\ndata Tag18\ndata Tag19\ndata Tag20\ndata Tag21\ndata Tag22\ndata Tag23\ndata Tag24\ndata Tag25\ndata Tag26\ndata Tag27\ndata Tag28\ndata Tag29\ndata Tag30\n\ninstance Tag Tag0 where tagVal _ = 0\ninstance Tag Tag1 where tagVal _ = 1\ninstance Tag Tag2 where tagVal _ = 2\ninstance Tag Tag3 where tagVal _ = 3\ninstance Tag Tag4 where tagVal _ = 4\ninstance Tag Tag5 where tagVal _ = 5\ninstance Tag Tag6 where tagVal _ = 6\ninstance Tag Tag7 where tagVal _ = 7\ninstance Tag Tag8 where tagVal _ = 8\ninstance Tag Tag9 where tagVal _ = 9\ninstance Tag Tag10 where tagVal _ = 10\ninstance Tag Tag11 where tagVal _ = 11\ninstance Tag Tag12 where tagVal _ = 12\ninstance Tag Tag13 where tagVal _ = 13\ninstance Tag Tag14 where tagVal _ = 14\ninstance Tag Tag15 where tagVal _ = 15\ninstance Tag Tag16 where tagVal _ = 16\ninstance Tag Tag17 where tagVal _ = 17\ninstance Tag Tag18 where tagVal _ = 18\ninstance Tag Tag19 where tagVal _ = 19\ninstance Tag Tag20 where tagVal _ = 20\ninstance Tag Tag21 where tagVal _ = 21\ninstance Tag Tag22 where tagVal _ = 22\ninstance Tag Tag23 where tagVal _ = 23\ninstance Tag Tag24 where tagVal _ = 24\ninstance Tag Tag25 where tagVal _ = 25\ninstance Tag Tag26 where tagVal _ = 26\ninstance Tag Tag27 where tagVal _ = 27\ninstance Tag Tag28 where tagVal _ = 28\ninstance Tag Tag29 where tagVal _ = 29\ninstance Tag Tag30 where tagVal _ = 30\n", "meta": {"hexsha": "3554f4dfe0336f4732acda7284299477faf02d65", "size": 21043, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/CayleyDickson.hs", "max_stars_repo_name": "lmj/cayley-dickson", "max_stars_repo_head_hexsha": "76bfa107ead61464a5cadee2318feaa13251169b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-11-12T00:50:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-28T22:13:30.000Z", "max_issues_repo_path": "src/Math/CayleyDickson.hs", "max_issues_repo_name": "lmj/cayley-dickson", "max_issues_repo_head_hexsha": "76bfa107ead61464a5cadee2318feaa13251169b", "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/CayleyDickson.hs", "max_forks_repo_name": "lmj/cayley-dickson", "max_forks_repo_head_hexsha": "76bfa107ead61464a5cadee2318feaa13251169b", "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.8311897106, "max_line_length": 80, "alphanum_fraction": 0.5721142423, "num_tokens": 6373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.510900850552776}} {"text": "-- |\n-- Copyright : (c) 2012 Daniël de Kok\n-- License : BSD3\n--\n-- Maintainer : Daniël de Kok \n-- Stability : experimental\n--\n-- This module provides functionality to perform approximate randomization\n-- tests (Noreen, 1989).\n\n\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DoAndIfThenElse #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Statistics.Test.ApproxRand (\n -- * Description\n -- $description\n\n -- * Examples\n -- $examples\n\n -- * Data types\n TestOptions(..),\n TestResult(..),\n Significance(..),\n RandWithError,\n\n -- * Approximate randomization tests\n approxRandTest,\n approxRandStats,\n\n approxRandPairTest,\n approxRandPairStats,\n\n -- * Test statistics\n TestStatistic,\n differenceMean,\n meanDifference,\n varianceRatio\n) where\n\nimport Prelude hiding ((++))\nimport Control.Monad (liftM, replicateM, when)\nimport Control.Monad.Error (ErrorT)\nimport Control.Monad.Error.Class (throwError)\nimport Control.Monad.Mersenne.Random (R(..), Rand(..), getBool)\nimport Control.Monad.ST (runST)\nimport Control.Monad.Trans.Class (lift)\nimport Data.Vector.Generic ((++))\nimport qualified Data.Vector.Generic as VG\nimport qualified Data.Vector.Generic.Mutable as GM\nimport Data.Word (Word)\nimport Statistics.Sample (variance)\nimport Statistics.Test.Types (TestType(..))\nimport Statistics.Types\nimport System.Random.Mersenne.Pure64 (PureMT, randomInt, randomWord)\n\n\n-- $description\n--\n-- Approximate randomization tests rely on a simple premise: given a test\n-- statistic, if the null-hypothesis (the samples do not differ) is true,\n-- we can randomly swap values between samples without an (extreme) impact\n-- on the test statistic. Otherwise, the null-hypothesis must be rejected.\n--\n-- The test works by generating a given number of sample shuffles and computing\n-- the test statistic for each shuffle. If /r/ is the number of shuffled\n-- samples where the test statistic is at least as high as the test statistic\n-- applied on the original samples; and /N/ the number of shuffles, then\n-- the null-hypothesis is rejected iff /(r + 1):(N + 1) < p-value/ (for\n-- one-sided tests).\n--\n-- Two kinds of test are supported:\n--\n-- * /Paired sample/ ('approxRandPairTest'): values from samples are shuffled\n-- pair-wise. This requires the samples to have an equal length.\n--\n-- * /Unpaired sample/ ('approxRandTest'): values from samples are shuffled\n-- among both samples. Consequently the i-th element of one sample does not\n-- bear a relationship with the i-th element of the other sample. The\n-- shuffled samples retain the sizes of the original samples.\n--\n-- Both tests can be performed as a one-tailed or two-tailed test.\n\n-- $examples\n-- Both unpaired and paired sample tests use the 'Rand' monad to obtain\n-- random numbers. We can obtain a pseudo-random number generator that\n-- is seeded using the system clock using the\n-- 'System.Random.Mersenne.Pure64.newPureMT' function (please refer to\n-- the documentation of 'System.Random.Mersenne.Pure64' for more\n-- information):\n--\n-- > prng <- newPureMT\n--\n-- Suppose that we have the samples 's1' and 's2'. We could now perform\n-- a Two-Tailed randomization test with 10,000 shuffles and the mean\n-- difference as the test statistic, by running 'approxRandTest' in the 'Rand'\n-- monad (at the /p = 0.01/ level):\n--\n-- > evalRandom (approxRandTest TwoTailed meanDifference 10000 0.01 s1 s2) prng\n--\n-- It is also possible to obtain the test statistics of the shuffled samples\n-- directly (e.g. to inspect the distribution of test statistics) using the\n-- 'approxRandStats'/'approxRandPiarStats' functions:\n--\n-- > evalRandom (approxRandStats meanDifference 10000 0.01 s1 s2) prng\n\n-- | Computations with random numbers that can fail.\ntype RandWithError a = ErrorT String Rand a\n\n-- | Options for randomization tests\n--\ndata TestOptions = TestOptions {\n toTestType :: TestType, -- ^ Type of test ('OneTailed' or 'TwoTailed')\n toTestStatistic :: TestStatistic, -- ^ Test statistic\n toIterations :: Int, -- ^ Number of shuffled samples to create\n toPValue :: Double -- ^ he p-value at which to test (e.g. 0.05)\n}\n\n-- |\n-- The result of hypothesis testing.\ndata TestResult = TestResult {\n trSignificance :: Significance, -- ^ Significance\n trStat :: Double, -- ^ Test statistic for the samples\n trRandomizedStats :: Sample -- ^ Test statistics for the\n -- randomized samples\n } deriving (Eq, Ord, Show)\n\n-- |\n-- Significance.\ndata Significance =\n Significant Double -- ^ The null hypothesis should be rejected\n | NotSignificant Double -- ^ Data is compatible with the null hypothesis\n deriving (Eq, Ord, Show)\n\n-- |\n-- Apply a pair-wise approximate randomization test.\n--\n-- In pair-wise approximate randomization tests the data points at a given\n-- index are swapped between samples with a probability of 0.5. Since\n-- swapping is pairwise, the samples should have the same length.\napproxRandPairTest ::\n TestOptions -- ^ Options for the test\n -> Sample -- ^ First sample\n -> Sample -- ^ Second sample\n -> RandWithError TestResult -- ^ The test result\napproxRandPairTest (TestOptions testType stat n pTest) s1 s2 = do\n stats <- approxRandPairStats stat n s1 s2\n let tOrig = stat s1 s2\n let sig = significance testType pTest n $ countExtremes tOrig stats\n return $ TestResult sig tOrig stats\n\n-- |\n-- Apply an approximate randomization test.\n--\n-- In approximate randomization tests, the values of two samples are\n-- shuffled among those samples. A test statistic is calculated for\n-- the original samples and the shuffled samples, to detect whether the\n-- difference of the samples is extreme or not.\napproxRandTest ::\n TestOptions -- ^ Options for the test\n -> Sample -- ^ First sample\n -> Sample -- ^ Second sample\n -> Rand TestResult -- ^ The test result\napproxRandTest (TestOptions testType stat n pTest) s1 s2 = do\n stats <- approxRandStats stat n s1 s2\n let tOrig = stat s1 s2\n let sig = significance testType pTest n $ countExtremes tOrig stats\n return $ TestResult sig tOrig stats\n\n-- | Determine the significance.\nsignificance ::\n TestType -- ^ Type of test ('OneTailed' or 'TwoTailed')\n -> Double -- ^ The p-value at which to test (e.g. 0.05)\n -> Int -- ^ Number of sample shuffles\n -> (Int, Int) -- ^ Extreme statistic counts\n -> Significance -- ^ The test result\nsignificance TwoTailed pTest n =\n significant (pTest / 2) . pValue n . uncurry min\nsignificance OneTailed pTest n =\n significant pTest . pValue n . snd\n\n-- | Wrap a p-value in a 'TestResult'.\nsignificant ::\n Double -- ^ The p-value at which to test\n -> Double -- ^ The p-value\n -> Significance -- ^ The test result\nsignificant pTail p =\n if p < pTail then Significant p else NotSignificant p\n\n-- | Calculate a p-value\npValue ::\n Int -- ^ Number of extreme outcomes\n -> Int -- ^ Number of shuffles\n -> Double -- ^ The p-value\npValue n r = (fromIntegral r + 1) / (fromIntegral n + 1)\n\n-- |\n-- Count extreme test statistic values. If the test statistic value of the\n-- original sample is in the right tail, we want to count values equal to\n-- or larger than that value. If the value is in the left tail, we want to\n-- count value smaller than or equal to that value. Since we do not know\n-- the tail (yet), we count both.\n--\n-- Note: we can determine the tail by (1) averaging the test statistics of\n-- the randomized samples, or (2) taking the smaller of the two counts.\ncountExtremes ::\n Double -- ^ Test statistic value of the original samples\n -> Sample -- ^ Test statistic values of the randomized samples.\n -> (Int, Int) -- ^ Count of left- and right-tail extremes.\ncountExtremes tOrig =\n VG.foldl' count (0, 0)\n where\n count (left, right) tPerm =\n let !newLeft = if tPerm <= tOrig then succ left else left in\n let !newRight = if tPerm >= tOrig then succ right else right in\n (newLeft, newRight)\n\n-- |\n-- Generate a given number of pairwise shuffled samples, and calculate\n-- the test statistic for each shuffle.\n--\n-- Since the data points at a given index are swapped (with a probability of\n-- 0.5), the samples should have the same length.\napproxRandPairStats ::\n TestStatistic -- ^ Test statistic\n -> Int -- ^ Number of shuffled samples to create\n -> Sample -- ^ First sample\n -> Sample -- ^ Second sample\n -> RandWithError Sample -- ^ The statistics of the shuffles\napproxRandPairStats stat n s1 s2 = do\n when (VG.length s1 /= VG.length s2) $\n throwError \"Cannot calculate pairwise statistic: samples have different sizes\"\n lift $ liftM VG.fromList $ replicateM n $\n uncurry stat `liftM` shuffleVectorsPairwise s1 s2\n\n-- |\n-- Generate a given number of shuffled samples, and calculate the test\n-- statistic for each shuffle.\n--\n-- This function does not require the samples to have an equal length.\napproxRandStats ::\n TestStatistic -- ^ Test statistic\n -> Int -- ^ Number of shuffled samples to create\n -> Sample -- ^ First sample\n -> Sample -- ^ Second sample\n -> Rand Sample -- ^ The statistics of the shuffles\napproxRandStats stat n s1 s2 =\n liftM VG.fromList $ replicateM n $ uncurry stat `liftM` shuffleVectors s1 s2\n\n-- | Pair-wise shuffle of two vectors.\nshuffleVectorsPairwise :: (VG.Vector v a, VG.Vector v Bool) =>\n v a -> v a -> Rand (v a, v a)\nshuffleVectorsPairwise vec1 vec2 = do\n randomVec <- randomVector (VG.length vec1)\n let pv1 = VG.zipWith3 permute vec1 vec2 randomVec\n let pv2 = VG.zipWith3 permute vec2 vec1 randomVec\n return (pv1, pv2)\n where\n permute val1 val2 coin =\n if coin then val1 else val2\n\nrandomVector :: VG.Vector v Bool => Int -> Rand (v Bool)\nrandomVector len =\n VG.replicateM len getBool\n\n-- Shuffle values amongst two vectors, keeping the original vector lengths.\nshuffleVectors :: VG.Vector v a => v a -> v a -> Rand (v a, v a)\nshuffleVectors v1 v2 = do\n shuffledVectors <- shuffleVector $ v1 ++ v2\n return (VG.slice 0 (VG.length v1) shuffledVectors,\n VG.slice (VG.length v1) (VG.length v2) shuffledVectors)\n\n-- Fisher-Yates shuffle in the Rand monad\nshuffleVector :: VG.Vector v a => v a -> Rand (v a)\nshuffleVector v =\n Rand $ \\s -> case shuffleVector' s v of (sv, s') -> R sv s'\n\n-- Fisher-Yates shuffle\nshuffleVector' :: VG.Vector v a => PureMT -> v a -> (v a, PureMT)\nshuffleVector' gen v = runST $ do\n let maxIdx = VG.length v - 1\n vm <- VG.thaw v\n gen' <- swaps vm 0 maxIdx gen\n vmf <- VG.unsafeFreeze vm\n return (vmf, gen')\n where\n swaps vm idx maxIdx gen'\n | idx < maxIdx = do\n let (newIdx, gen'') = randomIntR gen' (idx, maxIdx)\n GM.unsafeSwap vm idx newIdx\n swaps vm (idx + 1) maxIdx gen''\n | otherwise = return gen'\n\n-- |\n-- A test stastic calculates the difference between two samples. See\n-- 'meanDifference' and 'varianceRatio' for examples.\ntype TestStatistic = Sample -> Sample -> Double\n\n-- |\n-- Calculates the difference mean of two samples (/mean(s1 - s2)/). When the\n-- two samples do not have an equal length, the trailing elements of the\n-- longer vector are ignored.\ndifferenceMean :: TestStatistic\ndifferenceMean v1 v2 =\n VG.sum (subVector v1 v2) / fromIntegral (VG.length v1)\n\n-- | Calculates the mean difference of two samples (/mean(s1) - mean(s2)/).\nmeanDifference :: TestStatistic\nmeanDifference s1 s2 =\n mean s1 - mean s2\n\n-- | Calculate the mean of a sample.\nmean :: Sample -> Double\nmean = do\n t <- VG.sum\n l <- VG.length\n return $ t / fromIntegral l\n\n-- | Calculate the ratio of sample variances (/var(s1) : var(s2)/).\nvarianceRatio :: TestStatistic\nvarianceRatio v1 v2 =\n variance v1 / variance v2\n\n-- | Subtract two vectors.\nsubVector :: (VG.Vector v n, Num n) => v n -> v n -> v n\nsubVector = VG.zipWith (-)\n\nsubIIW :: Int -> Int -> Word\nsubIIW a b = fromIntegral a - fromIntegral b\n{-# INLINE subIIW #-}\n\naddIWI :: Int -> Word -> Int\naddIWI a b = a + fromIntegral b\n{-# INLINE addIWI #-}\n\n-- | Generate Int numbers within a range\nrandomIntR :: PureMT -> (Int, Int) -> (Int, PureMT)\nrandomIntR gen (a, b)\n | n == 0 = randomInt gen\n | otherwise = loop gen\n where\n (a', b') = if a < b then (a, b) else (b, a)\n -- Number of different Ints that should be generated\n n = 1 + subIIW b' a'\n -- The total range of Word can hold x complete n ranges\n x = maxBound `div` n\n -- Pick from a range the is dividable by n without remainders\n s = x * n\n loop gen'\n | r >= s = loop gen'' -- r is outside the range, discard it...\n | otherwise = (addIWI a' (r `div` x), gen'') \n where\n (!r, !gen'') = randomWord gen'\n{-# INLINE randomIntR #-}\n", "meta": {"hexsha": "427d2c9781ca0f99e5364d7e35f464e3ca07af30", "size": 12970, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Test/ApproxRand.hs", "max_stars_repo_name": "danieldk/approx-rand-test", "max_stars_repo_head_hexsha": "0bfc9a3f16381960bb0420264915f2baf2eea175", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-15T18:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-15T18:15:56.000Z", "max_issues_repo_path": "src/Statistics/Test/ApproxRand.hs", "max_issues_repo_name": "danieldk/approx-rand-test", "max_issues_repo_head_hexsha": "0bfc9a3f16381960bb0420264915f2baf2eea175", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Test/ApproxRand.hs", "max_forks_repo_name": "danieldk/approx-rand-test", "max_forks_repo_head_hexsha": "0bfc9a3f16381960bb0420264915f2baf2eea175", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3305322129, "max_line_length": 84, "alphanum_fraction": 0.6723978412, "num_tokens": 3380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5107509042934019}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE Strict #-}\nmodule STC.Convolution where\n\nimport Control.Arrow\nimport Control.Monad as M\nimport Control.Monad.Parallel as MP (bindM2, mapM)\nimport Data.Array.IArray as IA\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.Ix\nimport Data.List as L\nimport Data.Vector.Storable as VS\nimport Data.Vector.Unboxed as VU\nimport Debug.Trace\nimport DFT.Plan\nimport Filter.Utils\nimport FokkerPlanck.FourierSeries\nimport Image.IO\nimport STC.DFTArray\nimport Types\nimport Utils.Parallel\nimport FokkerPlanck.GPUKernel\nimport qualified Data.Array.Accelerate as A\nimport qualified Data.Array.Accelerate.Data.Complex as A\nimport Data.Array.Accelerate.LLVM.PTX\nimport Debug.Trace\nimport Utils.List\nimport Utils.BLAS\n\ndata Field\n = Source\n | Sink\n deriving (Read, Show)\n\n{-# INLINE dftHarmonicsArray #-}\ndftHarmonicsArray ::\n DFTPlan\n -> Int\n -> Double\n -> Int\n -> Double\n -> [Double]\n -> [Double]\n -> [Double]\n -> [Double]\n -> Double\n -> Double\n -> IO (IA.Array (Int, Int) (VS.Vector (Complex Double)))\ndftHarmonicsArray !plan !numRows !deltaRow !numCols !deltaCol !phiFreqs !rhoFreqs !thetaFreqs !rFreqs !halfLogPeriod !cutoff = do\n let !arr =\n computeHarmonicsArray\n numRows\n deltaRow\n numCols\n deltaCol\n phiFreqs\n rhoFreqs\n thetaFreqs\n rFreqs\n halfLogPeriod\n cutoff\n fmap (listArray (bounds arr)) .\n dftExecuteBatchP plan (DFTPlanID DFT1DG [numCols, numRows] [0, 1]) .\n L.map\n (VS.convert .\n toUnboxed .\n computeUnboxedS . makeFilter2D . fromUnboxed (Z :. numCols :. numRows)) .\n IA.elems $\n arr\n \n{-# INLINE dftHarmonicsArrayG #-}\ndftHarmonicsArrayG ::\n DFTPlan\n -> Int\n -> Double\n -> Int\n -> Double\n -> [Double]\n -> [Double]\n -> [Double]\n -> [Double]\n -> Double\n -> Double -> VS.Vector (Complex Double)\n -> IO (IA.Array (Int, Int) (VS.Vector (Complex Double)))\ndftHarmonicsArrayG !plan !numRows !deltaRow !numCols !deltaCol !phiFreqs !rhoFreqs !thetaFreqs !rFreqs !halfLogPeriod !cutoff !gaussian = do\n let !arr =\n computeHarmonicsArray\n numRows\n deltaRow\n numCols\n deltaCol\n phiFreqs\n rhoFreqs\n thetaFreqs\n rFreqs\n halfLogPeriod\n cutoff\n xs <-\n fmap (L.map (VS.zipWith (*) gaussian)) .\n dftExecuteBatchP plan (DFTPlanID DFT1DG [numCols, numRows] [0, 1]) .\n IA.elems $\n arr\n ys <- dftExecuteBatchP plan (DFTPlanID IDFT1DG [numCols, numRows] [0, 1]) xs\n fmap (listArray (bounds arr)) .\n dftExecuteBatchP plan (DFTPlanID DFT1DG [numCols, numRows] [0, 1]) .\n L.map\n (\\vec ->\n let arr = fromUnboxed (Z :. numCols :. numRows) . VS.convert $ vec\n in VS.convert .\n toUnboxed . computeUnboxedS . makeFilter2D . R.traverse arr id $ \\f idx@(Z :. i :. j) ->\n if (i == div numCols 2 && j == div numRows 2)\n then 0\n else f idx) $\n ys\n\n\n{-# INLINE convolve #-}\nconvolve ::\n Field\n -> DFTPlan \n -> R.Array U DIM4 (Complex Double)\n -> IA.Array (Int, Int) (VS.Vector (Complex Double))\n -> DFTArray\n -> IO DFTArray\nconvolve !field !plan !coefficients !harmonicsArray !arr@(DFTArray rows cols thetaFreqs rFreqs vecs) = do\n dftVecs <- dftExecuteBatchP plan (DFTPlanID DFT1DG [cols, rows] [0, 1]) vecs\n let !initVec = VS.replicate (VS.length . L.head $ vecs) 0\n idx = (,) <$> (L.zip [0 ..] rFreqs) <*> (L.zip [0 ..] thetaFreqs)\n fmap (DFTArray rows cols thetaFreqs rFreqs) .\n dftExecuteBatchP plan (DFTPlanID IDFT1DG [cols, rows] [0, 1]) .\n parMap\n rdeepseq\n (\\((!r, !rFreq), (!theta, !thetaFreq)) ->\n L.foldl'\n (\\(!vec) (((!rho, !rhoFreq), (!phi, !phiFreq)), inputVec) ->\n VS.zipWith\n (+)\n vec\n (VS.map (* (coefficients R.! (Z :. r :. theta :. rho :. phi))) .\n VS.zipWith\n (*)\n (getHarmonics harmonicsArray phiFreq rhoFreq thetaFreq rFreq) $\n inputVec))\n initVec .\n L.zip idx $\n dftVecs) $\n idx\n\n{-# INLINE convolve' #-}\nconvolve' ::\n Field\n -> DFTPlan\n -> R.Array U DIM4 (Complex Double)\n -> IA.Array (Int, Int) (VS.Vector (Complex Double))\n -> DFTArray\n -> IO DFTArray\nconvolve' !field !plan !coefficients !harmonicsArray !arr@(DFTArray rows cols thetaFreqs rFreqs vecs) = do\n dftVecs <- dftExecuteBatchP plan (DFTPlanID DFT1DG [cols, rows] [0, 1]) vecs\n let !initVec = VS.replicate (VS.length . L.head $ vecs) 0\n idxTheta = L.zip [0 ..] thetaFreqs\n fmap (DFTArray rows cols thetaFreqs rFreqs) .\n dftExecuteBatchP plan (DFTPlanID IDFT1DG [cols, rows] [0, 1]) .\n parMap\n rdeepseq\n (\\(!theta, !thetaFreq) ->\n VS.map\n (\\x ->\n case field of\n Source -> x\n Sink -> x * cis (pi * thetaFreq)) .\n L.foldl'\n (\\vec1 (rho, rhoFreq) ->\n L.foldl'\n (\\(!vec2) ((!phi, !phiFreq), inputVec) ->\n VS.zipWith\n (+)\n vec2\n (VS.map\n (* (coefficients R.!\n (Z :. (0 :: Int) :. theta :. rho :. phi))) .\n VS.zipWith\n (*)\n (getHarmonics harmonicsArray phiFreq rhoFreq thetaFreq 0) $\n inputVec))\n vec1 .\n L.zip idxTheta $\n dftVecs)\n initVec .\n L.zip [0 ..] $\n rFreqs) $\n idxTheta \n \n \n{-# INLINE convolveG' #-}\nconvolveG' ::\n Field\n -> DFTPlan\n -> R.Array U DIM4 (Complex Double)\n -> IA.Array (Int, Int) (VS.Vector (Complex Double))\n -> VS.Vector (Complex Double)\n -> DFTArray\n -> IO DFTArray\nconvolveG' !field !plan !coefficients !harmonicsArray !gaussianFilter !arr@(DFTArray rows cols thetaFreqs rFreqs vecs) = do\n dftVecs <-\n L.map (VS.zipWith (*) gaussianFilter) <$>\n dftExecuteBatchP plan (DFTPlanID DFT1DG [cols, rows] [0, 1]) vecs\n let !initVec = VS.replicate (VS.length . L.head $ vecs) 0\n idxTheta = L.zip [0 ..] thetaFreqs\n fmap (DFTArray rows cols thetaFreqs rFreqs) .\n dftExecuteBatchP plan (DFTPlanID IDFT1DG [cols, rows] [0, 1]) .\n parMap\n rdeepseq\n (\\(!theta, !thetaFreq) ->\n L.foldl'\n (\\vec1 (rho, rhoFreq) ->\n L.foldl'\n (\\(!vec2) ((!phi, !phiFreq), inputVec) ->\n VS.zipWith\n (+)\n vec2\n (VS.map\n (* (case field of\n Source ->\n coefficients R.!\n (Z :. (0 :: Int) :. theta :. rho :. phi)\n Sink ->\n (coefficients R.!\n (Z :. (0 :: Int) :. theta :. rho :. phi)) *\n (cis $ (-(phiFreq + thetaFreq)) * pi))) .\n VS.zipWith\n (*)\n (getHarmonics harmonicsArray phiFreq rhoFreq thetaFreq 0) $\n inputVec))\n vec1 .\n L.zip idxTheta $\n dftVecs)\n initVec .\n L.zip [0 ..] $\n rFreqs) $\n idxTheta \n\n-- {-# INLINE convolve'' #-}\n-- convolve'' ::\n-- Field\n-- -> DFTPlan\n-- -> R.Array U DIM4 (Complex Double)\n-- -> IA.Array (Int, Int) (VS.Vector (Complex Double))\n-- -> DFTArray\n-- -> IO DFTArray\n-- convolve'' !field !plan !coefficients !harmonicsArray !arr@(DFTArray rows cols phiFreqs rhoFreqs vecs) = do\n-- let !initVec = VS.replicate (VS.length . L.head $ vecs) 0\n-- idx = L.zip [0 ..] phiFreqs\n-- return .\n-- (DFTArray rows cols phiFreqs rhoFreqs) .\n-- parMap\n-- rdeepseq\n-- (\\(theta, thetaFreq) ->\n-- L.foldl'\n-- (\\vec1 (rho, rhoFreq) ->\n-- L.foldl'\n-- (\\vec2 (phi, phiFreq) ->\n-- VS.zipWith (+) vec2 .\n-- VS.map\n-- (* (case field of\n-- Source ->\n-- coefficients R.!\n-- (Z :. (0 :: Int) :. theta :. rho :. phi)\n-- Sink ->\n-- (coefficients R.!\n-- (Z :. (0 :: Int) :. theta :. rho :. phi)) *\n-- (cis $ (-(thetaFreq + phiFreq)) * pi))) $\n-- (getHarmonics harmonicsArray phiFreq rhoFreq 0 0))\n-- vec1\n-- idx)\n-- initVec .\n-- L.zip [0 ..] $\n-- rhoFreqs) $\n-- idx\n\n-- {-# INLINE dftHarmonicsArrayGPU #-}\n-- dftHarmonicsArrayGPU ::\n-- DFTPlan\n-- -> Int\n-- -> Double\n-- -> Int\n-- -> Double\n-- -> [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> Double\n-- -> Double\n-- -> IO (Acc (A.Array A.DIM4 (A.Complex Double)))\n-- dftHarmonicsArrayGPU !plan !numRows !deltaRow !numCols !deltaCol !phiFreqs !rhoFreqs !thetaFreqs !rFreqs !halfLogPeriod !cutoff = do\n-- let !arr =\n-- computeHarmonicsArrayGPU\n-- numRows\n-- deltaRow\n-- numCols\n-- deltaCol\n-- phiFreqs\n-- rhoFreqs\n-- thetaFreqs\n-- rFreqs\n-- halfLogPeriod\n-- cutoff\n-- rangeFunc2 xs ys =\n-- (round (L.head xs - L.last ys), round (L.last xs - L.head ys))\n-- (!tfLB, !tfUB) = rangeFunc2 phiFreqs thetaFreqs\n-- (!rfLB, !rfUB) = rangeFunc2 rhoFreqs rFreqs\n-- fmap\n-- (A.use .\n-- A.fromList\n-- (A.Z A.:. (rfUB - rfLB + 1) A.:. (tfUB - tfLB + 1) A.:. numCols A.:.\n-- numRows) .\n-- VS.toList . VS.concat) .\n-- dftExecuteBatchP plan (DFTPlanID DFT1DG [numCols, numRows] [0, 1]) .\n-- L.map\n-- (VS.convert .\n-- toUnboxed .\n-- computeUnboxedS . makeFilter2D . fromUnboxed (Z :. numCols :. numRows)) .\n-- IA.elems $\n -- arr\n\n-- {-# INLINE convolveGPU #-}\n-- convolveGPU ::\n-- PTX\n-- -> Field\n-- -> DFTPlan\n-- -> Acc (A.Array A.DIM4 (A.Complex Double))\n-- -> Acc (A.Array A.DIM4 (A.Complex Double))\n-- -> Acc (A.Array A.DIM4 (A.Complex Double))\n-- -> DFTArray\n-- -> IO DFTArray\n-- convolveGPU !ptx !field !plan !coefficients !coefficientsSink !harmonics !arr@(DFTArray rows cols thetaFreqs rFreqs vecs) = do\n-- dftVecs <- dftExecuteBatchP plan (DFTPlanID DFT1DG [cols, rows] [0, 1]) vecs\n-- let !numRFreq = L.length rFreqs\n-- !numThetaFreq = L.length thetaFreqs\n-- idx =\n-- [ (r, theta)\n-- | r <- [0 .. (numRFreq - 1)]\n-- , theta <- [0 .. (numThetaFreq - 1)]\n-- ]\n-- case field of\n-- Source ->\n-- fmap (DFTArray rows cols thetaFreqs rFreqs) .\n-- dftExecuteBatchP plan (DFTPlanID IDFT1DG [cols, rows] [0, 1]) .\n-- L.map\n-- (\\(r, theta) ->\n-- VS.fromList . A.toList $\n-- (runNWith ptx (convolveKernel coefficients harmonics))\n-- (A.fromList A.Z [theta])\n-- (A.fromList A.Z [r])\n-- (A.fromList\n-- (A.Z A.:. numRFreq A.:. numThetaFreq A.:. cols A.:. rows) .\n-- VS.toList . VS.concat $\n-- dftVecs)) $\n-- idx\n-- -- Sink ->\n-- -- fmap (DFTArray rows cols thetaFreqs rFreqs) .\n-- -- dftExecuteBatchP plan (DFTPlanID IDFT1DG [cols, rows] [0, 1]) .\n-- -- L.map\n-- -- (\\(r, theta) ->\n-- -- VS.fromList .\n-- -- A.toList .\n-- -- (runNWith ptx (convolveKernel coefficientsSink harmonics))\n-- -- (A.fromList (Z :. (1 :: Int)) theta)\n-- -- (A.fromList (Z :. (1 :: Int)) r)\n-- -- (A.fromList (Z :. numRFreq :. numThetaFreq :. cols :. rows) .\n-- -- VS.toList . VS.concat $\n-- -- dftVecs)) $\n-- -- idx\n\n\n{-# INLINE convolveSingle #-}\nconvolveSingle ::\n Field\n -> R.Array U DIM4 (Complex Double)\n -> IA.Array (Int, Int) (R.Array U DIM2 (Complex Double))\n -> R.Array U DIM1 Double\n -> R.Array U DIM1 Double\n -> Double\n -> Double\n -> R.Array U DIM2 (Complex Double)\n -> VU.Vector (Complex Double)\nconvolveSingle !field !coefficients !harmonicsArray !thetaFreqs !rFreqs !x !y !input =\n let (Z :. cols :. rows) = extent (harmonicsArray IA.! (0, 0))\n rowCenter = div rows 2\n colCenter = div cols 2\n (Z :. _ :. _ :. numRFreq :. numThetaFreq) = extent coefficients\n -- harmonics =\n -- R.traverse2 thetaFreqs rFreqs (\\_ _ -> extent coefficients) $ \\fThetaFreq fRFreq (Z :. r :. theta :. rho :. phi) ->\n -- (harmonicsArray IA.!\n -- ( round (fRFreq (Z :. rho) - fRFreq (Z :. r))\n -- , round $ (fThetaFreq (Z :. phi) - (fThetaFreq (Z :. theta))))) R.!\n -- (Z :. (x + colCenter) :. (y + rowCenter))\n harmonics =\n R.traverse2 thetaFreqs rFreqs (\\_ _ -> extent coefficients) $ \\fPhiFreq fRhoFreq (Z :. r :. theta :. rho :. phi) ->\n let !tf = fPhiFreq (Z :. phi) - fPhiFreq (Z :. theta)\n !rf = fRhoFreq (Z :. rho) - fRhoFreq (Z :. r)\n in (x :+ y) ** (tf :+ 0) *\n ((x ^ 2 + y ^ 2) :+ 0) **\n (((-tf - 1) :+ 2 * pi * rf / (log $ (sqrt 2) * 512)) / 2)\n product =\n R.traverse2 (R.zipWith (*) coefficients harmonics) input const $ \\fCoefficient fInput idx@(Z :. _ :. _ :. rho :. phi) ->\n fCoefficient idx * fInput (Z :. rho :. phi)\n arr =\n case field of\n Source -> product\n Sink ->\n error\n \"convolveSingle: You should not use it to compute a sink field.\"\n in if x == 0 && y == 0\n then VU.replicate (numRFreq * numThetaFreq) 0\n else toUnboxed . sumS . sumS $ arr\n\n-- {-# INLINE convolveSparse #-}\nconvolveSparse ::\n Field\n -> R.Array U DIM4 (Complex Double)\n -> IA.Array (Int, Int) (R.Array U DIM2 (Complex Double))\n -> R.Array U DIM1 Double\n -> R.Array U DIM1 Double\n -> Double\n -> [(Double, Double)]\n -> [R.Array U DIM2 (Complex Double)]\n -> [R.Array U DIM2 (Complex Double)]\nconvolveSparse !field !coefficients !harmonicsArray !thetaFreqs !rFreqs !cutoff !xs !inputs =\n L.map (fromUnboxed (extent . L.head $ inputs)) .\n parMap\n rdeepseq\n (\\(x, y) ->\n L.foldl1' (VU.zipWith (+)) .\n L.zipWith\n (\\(x', y') input ->\n let !x'' = x - x'\n !y'' = y - y'\n (!a, !b) =\n if (x'' ^ 2 + y'' ^ 2) <= cutoff ^ 2\n then (x'', y'')\n else (0, 0)\n in convolveSingle\n field\n coefficients\n harmonicsArray\n thetaFreqs\n rFreqs\n a\n b\n input)\n xs $\n inputs) $\n xs\n\n\n{-# INLINE convolveSingle' #-}\nconvolveSingle' ::\n Field\n -> R.Array U DIM4 (Complex Double)\n -> IA.Array (Int, Int) (R.Array U DIM2 (Complex Double))\n -> R.Array U DIM1 Double\n -> R.Array U DIM1 Double\n -> Double\n -> Double\n -> R.Array U DIM1 (Complex Double)\n -> VU.Vector (Complex Double)\nconvolveSingle' !field !coefficients !harmonicsArray !phiFreqs !rhoFreqs !x !y !input =\n let (Z :. cols :. rows) = extent (harmonicsArray IA.! (0, 0))\n rowCenter = div rows 2\n colCenter = div cols 2\n (Z :. _ :. _ :. numRhoFreq :. numPhiFreq) = extent coefficients\n -- harmonics =\n -- R.traverse2 phiFreqs rhoFreqs (\\_ _ -> extent coefficients) $ \\fPhiFreq fRhoFreq (Z :. _ :. theta :. rho :. phi) ->\n -- (harmonicsArray IA.!\n -- ( round (fRhoFreq (Z :. rho))\n -- , round (fPhiFreq (Z :. phi) - (fPhiFreq (Z :. theta))))) R.!\n -- (Z :. (x + colCenter) :. (y + rowCenter))\n harmonics =\n R.traverse2 phiFreqs rhoFreqs (\\_ _ -> extent coefficients) $ \\fPhiFreq fRhoFreq (Z :. _ :. theta :. rho :. phi) ->\n let !tf = fPhiFreq (Z :. phi) - fPhiFreq (Z :. theta)\n !rf = fRhoFreq (Z :. rho)\n in (x :+ y) ** (tf :+ 0) *\n ((x ^ 2 + y ^ 2) :+ 0) ** (((-tf - 1) :+ rf) / 2)\n product =\n R.traverse2 (R.zipWith (*) coefficients harmonics) input const $ \\fCoefficient fInput idx@(Z :. _ :. _ :. _ :. phi) ->\n fCoefficient idx * fInput (Z :. phi)\n arr =\n case field of\n Source -> product\n Sink ->\n R.traverse2 product phiFreqs const $ \\fProd fPhiFreq idx@(Z :. _ :. theta :. _ :. phi) ->\n fProd idx *\n (cis $ (-(fPhiFreq (Z :. phi) - fPhiFreq (Z :. theta))) * pi)\n in if x == 0 && y == 0\n then VU.replicate (numRhoFreq * numPhiFreq) 0\n else toUnboxed . sumS . sumS $ arr\n\n\nconvolveSparse' ::\n Field\n -> R.Array U DIM4 (Complex Double)\n -> IA.Array (Int, Int) (R.Array U DIM2 (Complex Double))\n -> R.Array U DIM1 Double\n -> R.Array U DIM1 Double\n -> Double\n -> [(Double, Double)]\n -> [R.Array U DIM1 (Complex Double)]\n -> [R.Array U DIM1 (Complex Double)]\nconvolveSparse' !field !coefficients !harmonicsArray !phiFreqs !rhoFreqs !cutoff !xs !inputs =\n L.map (fromUnboxed (extent . L.head $ inputs)) .\n parMap\n rdeepseq\n (\\(x, y) ->\n L.foldl1' (VU.zipWith (+)) .\n L.zipWith\n (\\(x', y') input ->\n let !x'' = x - x'\n !y'' = y - y'\n (!a, !b) =\n if (x'' ^ 2 + y'' ^ 2) <= cutoff ^ 2\n then (x'', y'')\n else (0, 0)\n in convolveSingle'\n field\n coefficients\n harmonicsArray\n phiFreqs\n rhoFreqs\n a\n b\n input)\n xs $\n inputs) $\n xs\n\n{-# INLINE gaussianFilter2D #-}\ngaussianFilter2D :: DFTPlan -> Int -> Double -> IO (VS.Vector (Complex Double))\ngaussianFilter2D plan numPoint stdG =\n dftExecute plan (DFTPlanID DFT1DG [numPoint, numPoint] [0, 1]) .\n VU.convert .\n toUnboxed . computeS . makeFilter2D . fromFunction (Z :. numPoint :. numPoint) $ \\(Z :. i :. j) ->\n let x = fromIntegral $ i - div numPoint 2\n y = fromIntegral $ j - div numPoint 2\n in (exp (-(x ^ 2 + y ^ 2) / (2 * stdG ^ 2))) :+ 0\n \n\n{-# INLINE convoluvePinhweelBasis #-}\nconvoluvePinhweelBasis ::\n R.Array U DIM4 (Complex Double)\n -> IA.Array (Int, Int) (VS.Vector (Complex Double))\n -> DFTArray\n -> DFTArray\nconvoluvePinhweelBasis coefficients harmonicsArray arr@(DFTArray xFreq yFreq thetaFreqs rFreqs vecs) =\n let initVec = VS.replicate (VS.length . L.head $ vecs) 0\n idxs = (,) <$> (L.zip [0 ..] rFreqs) <*> (L.zip [0 ..] thetaFreqs)\n in DFTArray xFreq yFreq thetaFreqs rFreqs .\n parMap\n rdeepseq\n (\\((r, rFreq), (theta, thetaFreq)) ->\n L.foldl'\n (\\vec (((rho, rhoFreq), (phi, phiFreq)), inputVec) ->\n VS.zipWith (+) vec .\n VS.map (* (coefficients R.! (Z :. r :. theta :. rho :. phi))) .\n VS.zipWith\n (*)\n (getHarmonics harmonicsArray phiFreq rhoFreq thetaFreq rFreq) $\n inputVec)\n initVec .\n L.zip idxs $\n vecs) $\n idxs\n\n{-# INLINE convoluvePinhweelBasis' #-}\nconvoluvePinhweelBasis' ::\n R.Array U DIM4 (Complex Double)\n -> IA.Array (Int, Int) (VS.Vector (Complex Double))\n -> DFTArray\n -> DFTArray\nconvoluvePinhweelBasis' coefficients harmonicsArray arr@(DFTArray xFreq yFreq thetaFreqs rFreqs vecs) =\n let idxTheta = L.zip [0 ..] thetaFreqs\n initVec = VS.replicate (VS.length . L.head $ vecs) 0\n in DFTArray xFreq yFreq thetaFreqs rFreqs .\n parMap\n rdeepseq\n (\\(!theta, !thetaFreq) ->\n L.foldl'\n (\\vec1 (rho, rhoFreq) ->\n L.foldl'\n (\\(!vec2) ((!phi, !phiFreq), inputVec) ->\n VS.zipWith\n (+)\n vec2\n (VS.map\n (* (coefficients R.!\n (Z :. (0 :: Int) :. theta :. rho :. phi))) .\n VS.zipWith\n (*)\n (getHarmonics\n harmonicsArray\n phiFreq\n rhoFreq\n thetaFreq\n 0) $\n inputVec))\n vec1 .\n L.zip idxTheta $\n vecs)\n initVec .\n L.zip [0 ..] $\n rFreqs) $\n idxTheta\n \n{-# INLINE convolveFull'' #-}\nconvolveFull'' ::\n R.Array U DIM4 (Complex Double)\n -> IA.Array (Int, Int) (VS.Vector (Complex Double))\n -> DFTArray\n -> DFTArray\nconvolveFull'' !coefficients !harmonicsArray !arr@(DFTArray r2Freq _ thetaFreqs rFreqs vecs) =\n let idxTheta = L.zip [0 ..] thetaFreqs\n !initVec = VS.replicate (VS.length . L.head $ vecs) 0\n in DFTArray r2Freq r2Freq thetaFreqs rFreqs .\n parMap\n rdeepseq\n (\\(!theta, !thetaFreq) ->\n L.foldl'\n (\\vec1 (rho, rhoFreq) ->\n L.foldl'\n (\\(!vec2) ((!phi, !phiFreq), inputVec) ->\n VS.zipWith\n (+)\n vec2\n (VS.map\n (* (coefficients R.!\n (Z :. (0 :: Int) :. theta :. rho :. phi)))\n (getHarmonics\n harmonicsArray\n phiFreq\n rhoFreq\n thetaFreq\n 0)))\n vec1 .\n L.zip idxTheta $\n vecs)\n initVec .\n L.zip [0 ..] $\n rFreqs) $\n idxTheta\n\n\n{-# INLINE convoluvePinhweelBasisTest #-}\nconvoluvePinhweelBasisTest ::\n VS.Vector (Complex Double)\n -> [VS.Vector (Complex Double)]\n -> [VS.Vector (Complex Double)]\n -> DFTArray\n -> IO DFTArray\nconvoluvePinhweelBasisTest coefficients harmonicsArray1 harmonicsArray2 arr@(DFTArray xFreq yFreq thetaFreqs rFreqs vecs) = do\n let vecs1 = parZipWith rdeepseq (VS.zipWith (*)) vecs harmonicsArray1\n m = L.length thetaFreqs * L.length rFreqs\n n = xFreq * yFreq\n vec2 <- gemmBLAS m n m coefficients . VS.concat $ vecs1\n let arr =\n fromUnboxed\n (Z :. (L.length rFreqs) :. (L.length thetaFreqs) :. xFreq :. yFreq) .\n VS.convert $\n vec2\n vecs2 =\n parMap\n rdeepseq\n (\\(i, j) ->\n VS.convert . toUnboxed . computeS . R.slice arr $\n (Z :. i :. j :. All :. All))\n [ (i, j)\n | i <- [0 .. L.length rFreqs - 1]\n , j <- [0 .. L.length thetaFreqs - 1]\n ] :: [VS.Vector (Complex Double)]\n vecs3 = parZipWith rdeepseq (VS.zipWith (*)) vecs2 harmonicsArray2\n return . DFTArray xFreq yFreq thetaFreqs rFreqs $ vecs3\n\n\n{-# INLINE convoluvePinhweelBasisTest' #-}\nconvoluvePinhweelBasisTest' ::\n R.Array U DIM4 (Complex Double)\n -> [VS.Vector (Complex Double)]\n -> [VS.Vector (Complex Double)]\n -> DFTArray\n -> IO DFTArray\nconvoluvePinhweelBasisTest' coefficients harmonicsArray1 harmonicsArray2 arr@(DFTArray xFreq yFreq thetaFreqs rFreqs vecs) = do\n let (Z :. numRFreq :. numThetaFreq :. numRhoFreq :. numPhiFreq) =\n extent coefficients\n coefVec = VU.convert . toUnboxed $ coefficients\n vecs1 =\n parZipWith rdeepseq (VS.zipWith (*)) harmonicsArray1 .\n L.concat . L.replicate numRhoFreq $\n vecs\n m = numRFreq * numThetaFreq\n n = xFreq * yFreq\n k = numRhoFreq * numPhiFreq\n print (m, n, k)\n vec2 <- gemmBLAS m n k coefVec . VS.concat $ vecs1\n let arr =\n fromUnboxed (Z :. numRFreq :. numThetaFreq :. xFreq :. yFreq) .\n VS.convert $\n vec2\n vecs2 =\n parMap\n rdeepseq\n (\\(i, j) ->\n VS.convert . toUnboxed . computeS . R.slice arr $\n (Z :. i :. j :. All :. All))\n [(i, j) | i <- [0 .. numRFreq - 1], j <- [0 .. numThetaFreq - 1]] :: [VS.Vector (Complex Double)]\n vecs3 = parZipWith rdeepseq (VS.zipWith (*)) vecs2 harmonicsArray2\n return . DFTArray xFreq yFreq thetaFreqs rFreqs $ vecs3\n", "meta": {"hexsha": "103321fe81d072d11762d6dd36ff3da142005ca0", "size": 24744, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/STC/Convolution.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/STC/Convolution.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/STC/Convolution.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.510460251, "max_line_length": 140, "alphanum_fraction": 0.5006062076, "num_tokens": 7349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.5105285913791984}} {"text": "{-# LANGUAGE AllowAmbiguousTypes, DataKinds, RankNTypes, TypeFamilies,\n TypeOperators #-}\n{-# OPTIONS_GHC -Wno-missing-export-lists #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n-- | Shaped tensor-based implementation of Recurrent Neural Network\n-- for classification of MNIST digits. Sports 2 hidden layers.\nmodule HordeAd.Tool.MnistRnnShaped where\n\nimport Prelude\n\nimport Control.Monad (foldM)\nimport qualified Data.Array.DynamicS as OT\nimport Data.Array.Internal (valueOf)\nimport qualified Data.Array.Shape\nimport qualified Data.Array.Shaped as OSB\nimport qualified Data.Array.ShapedS as OS\nimport Data.Proxy (Proxy)\nimport qualified Data.Vector.Generic as V\nimport GHC.TypeLits (KnownNat)\nimport Numeric.LinearAlgebra (Vector)\nimport qualified Numeric.LinearAlgebra as HM\n\n-- until stylish-haskell accepts NoStarIsType\nimport qualified GHC.TypeLits\n\nimport HordeAd.Core.DualNumber\nimport HordeAd.Core.Engine\nimport HordeAd.Core.PairOfVectors (DualNumberVariables, varS)\nimport HordeAd.Tool.MnistData\n\nzeroStateS\n :: (IsScalar d r, OS.Shape sh)\n => (DualNumber d (OS.Array sh r) -- state\n -> a)\n -> a\nzeroStateS f = f (konstS 0)\n\nunrollLastS :: forall state c w m d r k rest.\n (DualMonad d r m, KnownNat k, OS.Shape rest)\n => (state -> OS.Array rest r -> w -> m (c, state))\n -> (state -> OS.Array (k : rest) r -> w -> m (c, state))\nunrollLastS f s0 xs w = do\n let g :: (c, state) -> OS.Array rest r -> m (c, state)\n g (_, s) x = f s x w\n foldM g (undefined, s0) $ OSB.toList $ OS.unravel xs\n\ntype LayerWeigthsRNN in_width out_width d r =\n ( DualNumber d (OS.Array '[out_width, in_width] r) -- input weight\n , DualNumber d (OS.Array '[out_width, out_width] r) -- state weight\n , DualNumber d (OS.Array '[out_width] r) ) -- bias\n\nrnnMnistLayerS\n :: forall in_width out_width batch_size d r m.\n ( DualMonad d r m\n , KnownNat in_width, KnownNat out_width, KnownNat batch_size )\n => DualNumber d (OS.Array '[out_width, batch_size] r) -- in state\n -> DualNumber d (OS.Array '[in_width, batch_size] r) -- in\n -> LayerWeigthsRNN in_width out_width d r\n -> m ( DualNumber d (OS.Array '[out_width, batch_size] r) -- out\n , DualNumber d (OS.Array '[out_width, batch_size] r) ) -- out state\nrnnMnistLayerS s x (wX, wS, b) = do\n let y = wX <>$ x + wS <>$ s + asColumnS b\n yTanh <- returnLet $ tanh y\n return (yTanh, yTanh)\n\nrnnMnistTwoS\n :: forall out_width batch_size d r m.\n (DualMonad d r m, KnownNat out_width, KnownNat batch_size)\n => DualNumber d (OS.Array '[2 GHC.TypeLits.* out_width, batch_size] r)\n -- initial state\n -> OS.Array '[SizeMnistWidth, batch_size] r\n -> ( LayerWeigthsRNN SizeMnistWidth out_width d r\n , LayerWeigthsRNN out_width out_width d r )\n -> m ( DualNumber d (OS.Array '[out_width, batch_size] r)\n , DualNumber d (OS.Array '[2 GHC.TypeLits.* out_width, batch_size] r) )\n -- final state\nrnnMnistTwoS s x ((wX, wS, b), (wX2, wS2, b2)) = do\n let s1 = sliceS @0 @out_width s\n s2 = sliceS @out_width @out_width s\n (vec1, s1') <- rnnMnistLayerS s1 (constant x) (wX, wS, b)\n (vec2, s2') <- rnnMnistLayerS s2 vec1 (wX2, wS2, b2)\n s3 <- returnLet $ appendS s1' s2'\n return (vec2, s3)\n\nrnnMnistZeroS\n :: forall out_width batch_size d r m.\n (DualMonad d r m, KnownNat out_width, KnownNat batch_size)\n => OS.Array '[SizeMnistHeight, SizeMnistWidth, batch_size] r\n -- All below is the type of all paramters of this nn. The same is reflected\n -- in the length function below and read from variables further down.\n -> ( LayerWeigthsRNN SizeMnistWidth out_width d r\n , LayerWeigthsRNN out_width out_width d r )\n -> DualNumber d (OS.Array '[SizeMnistLabel, out_width] r)\n -> DualNumber d (OS.Array '[SizeMnistLabel] r)\n -> m (DualNumber d (OS.Array '[SizeMnistLabel, batch_size] r))\nrnnMnistZeroS xs ((wX, wS, b), (wX2, wS2, b2)) w3 b3 = do\n (out, _s) <- zeroStateS (unrollLastS rnnMnistTwoS) xs\n ((wX, wS, b), (wX2, wS2, b2))\n returnLet $ w3 <>$ out + asColumnS b3\n\nrnnMnistLenS\n :: forall out_width. KnownNat out_width\n => Proxy out_width -> (Int, [Int], [(Int, Int)], [OT.ShapeL])\nrnnMnistLenS _ =\n ( 0\n , []\n , []\n , [ Data.Array.Shape.shapeT @'[out_width, SizeMnistWidth]\n , Data.Array.Shape.shapeT @'[out_width, out_width]\n , Data.Array.Shape.shapeT @'[out_width]\n , Data.Array.Shape.shapeT @'[out_width, out_width]\n , Data.Array.Shape.shapeT @'[out_width, out_width]\n , Data.Array.Shape.shapeT @'[out_width]\n , Data.Array.Shape.shapeT @'[SizeMnistLabel, out_width]\n , Data.Array.Shape.shapeT @'[SizeMnistLabel]\n ]\n )\n\nrnnMnistS\n :: forall out_width batch_size d r m.\n (DualMonad d r m, KnownNat out_width, KnownNat batch_size)\n => OS.Array '[SizeMnistHeight, SizeMnistWidth, batch_size] r\n -> DualNumberVariables d r\n -> m (DualNumber d (OS.Array '[SizeMnistLabel, batch_size] r))\nrnnMnistS xs variables = do\n let wX = varS variables 0\n wS = varS variables 1\n b = varS variables 2\n wX2 = varS variables 3\n wS2 = varS variables 4\n b2 = varS variables 5\n w3 = varS variables 6\n b3 = varS variables 7\n rnnMnistZeroS @out_width xs ((wX, wS, b), (wX2, wS2, b2)) w3 b3\n\nrnnMnistLossFusedS\n :: forall out_width batch_size d r m.\n (DualMonad d r m, KnownNat out_width, KnownNat batch_size)\n => Proxy out_width\n -> MnistDataBatchS batch_size r\n -> DualNumberVariables d r\n -> m (DualNumber d r)\nrnnMnistLossFusedS _ (glyphS, labelS) variables = do\n let xs = OS.transpose @'[2, 1, 0] glyphS\n result <- rnnMnistS @out_width xs variables\n let targets2 = HM.tr $ HM.reshape (valueOf @SizeMnistLabel)\n $ OS.toVector labelS\n vec <- lossSoftMaxCrossEntropyL targets2 (fromS2 result)\n returnLet $ scale (recip $ fromIntegral (valueOf @batch_size :: Int))\n $ sumElements0 vec\n\nrnnMnistTestS\n :: forall out_width batch_size r.\n (IsScalar 'DModeGradient r, KnownNat out_width, KnownNat batch_size)\n => Proxy r -> Proxy out_width\n -> MnistDataBatchS batch_size r\n -> Domains r\n -> r\nrnnMnistTestS _ _ (glyphS, labelS) parameters =\n let xs = OS.transpose @'[2, 1, 0] glyphS\n outputS = primalValue (rnnMnistS @out_width xs) parameters\n outputs = map OS.toVector $ OSB.toList $ OS.unravel\n $ OS.transpose @'[1, 0] $ outputS\n labels = map OS.toVector $ OSB.toList $ OS.unravel labelS\n matchesLabels :: Vector r -> Vector r -> Int\n matchesLabels output label | V.maxIndex output == V.maxIndex label = 1\n | otherwise = 0\n in fromIntegral (sum (zipWith matchesLabels outputs labels))\n / fromIntegral (valueOf @batch_size :: Int)\n", "meta": {"hexsha": "a7203c4f4e1e5244d4b645f3274c4abc9d8f16e4", "size": 6832, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Tool/MnistRnnShaped.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HordeAd/Tool/MnistRnnShaped.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "src/HordeAd/Tool/MnistRnnShaped.hs", "max_forks_repo_name": "Mikolaj/horde-ad", "max_forks_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9532163743, "max_line_length": 78, "alphanum_fraction": 0.6675936768, "num_tokens": 2140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5104114635575029}} {"text": "module RayLib where\n\nimport Numeric.LinearAlgebra\nimport qualified Graphics.Image as G\nimport qualified Debug.Trace as Debug\n\ndata Ray = Ray {rayOrigin :: Vector Double,\n rayDirection :: Vector Double}\n deriving (Show, Eq)\n\neps :: Double\neps = 0.000001\n\ndata Isect = Isect {iT :: Double,\n iNormal :: Vector Double,\n iObject :: Geometry,\n iMaterial :: Material}\n\ninstance Eq Isect where\n (Isect iT1 iNormal1 _ _) == (Isect iT2 iNormal2 _ _) = (iT1 == iT2) && (iNormal1 == iNormal2)\n\ninstance Ord Isect where\n compare (Isect iT1 _ _ _) (Isect iT2 _ _ _) = compare iT1 iT2\n\ninstance Show Isect where\n show (Isect t n _ _) = \"time: \" ++ show t ++ \", normal: \" ++ show n\n\nclass At a where\n at :: a -> Ray -> Vector Double\n\ninstance At Double where\n at t (Ray p d) = p + (fromList [t] :: Vector Double) * d\n\ninstance At Isect where \n at (Isect t _ _ _) (Ray p d) = p + (fromList [t] :: Vector Double) * d\n\ntype Color = Vector Double\n\ndata MatParam = MatParam Color\n deriving (Show, Read, Eq)\n\ndata Material = Material {ka :: MatParam,\n ks :: MatParam,\n kd :: MatParam,\n ke :: MatParam,\n kr :: MatParam,\n kt :: MatParam,\n shininess :: Double}\n deriving (Show, Read, Eq)\n\ndata Light = PointLight {lColor :: Color,\n lPosition :: Vector Double,\n constantTerm :: Double,\n linearTerm :: Double,\n quadraticTerm :: Double}\n | DirectionalLight {lColor :: Color,\n lOrientation :: Vector Double}\n deriving (Show, Read, Eq)\n\ntype Lights = [Light]\n\nlightColor :: Light -> Color\nlightColor (PointLight c _ _ _ _) = c\nlightColor (DirectionalLight c _) = c\n\ngetDirection :: Light -> Vector Double -> Vector Double\ngetDirection (PointLight _ pos _ _ _) p = normalize (pos - p)\ngetDirection (DirectionalLight _ o) _ = -o\n\ndistanceAttenuation :: Light -> Vector Double -> Double\ndistanceAttenuation (PointLight _ pos c b a) p = min 1.0 atten\n where atten = (c * dist * dist + b * dist + a) ** (-1.0)\n dist = norm_2 (p - pos)\ndistanceAttenuation (DirectionalLight _ _) p = 1.0\n\nshadowAttenuation :: Scene -> Light -> Vector Double -> Double\nshadowAttenuation scene (PointLight _ pos _ _ _) p = \n let shadowDir = normalize (pos - p) in\n let ray = Ray p shadowDir in\n let isect = intersect scene ray in\n case isect of\n Nothing -> 1\n Just (Isect t _ _ _) ->\n if (t < 0) || (t > norm_2 (pos - p)) then\n 1\n else\n 0\nshadowAttenuation scene dl@(DirectionalLight _ _) p =\n let shadowDir = normalize (getDirection dl p) in\n let ray = Ray p shadowDir in\n let isect = intersect scene ray in\n case isect of\n Nothing -> 1\n Just (Isect t _ _ _) ->\n if t < 0 then\n 1\n else\n 0\n\ndata Geometry = Sphere {sphereCenter :: Vector Double,\n sphereRadius :: Double,\n sphereMaterial :: Material}\n deriving (Show, Read, Eq)\n\ntype Objects = [Geometry]\n\ndata Scene = Scene {scLights :: Lights,\n scObjects :: Objects,\n scAmbient :: Color}\n deriving (Show, Read, Eq)\n\ndata Camera = Camera {eye :: Vector Double,\n viewDir :: Vector Double,\n upDir :: Vector Double,\n aspect :: Double,\n fov :: Double}\n deriving (Show, Read, Eq)\n\nrayThrough :: Camera -> Double -> Double -> Ray\nrayThrough (Camera eye viewDir upDir aspect fov) xx yy =\n let z = -viewDir in\n let y = upDir in\n let x = cross y z in\n let m = fromRows [x,y,z] in\n let fov' = fov * pi / 180.0 in\n let normalizedHeight = 2 * tan (fov' / 2.0) in\n let u = (flatten (m <> (fromColumns [(fromList [1,0,0])]))) * (fromList [normalizedHeight * aspect]) in\n let v = (flatten (m <> (fromColumns [(fromList [0,1,0])]))) * (fromList [normalizedHeight]) in\n let look = (flatten (m <> (fromColumns [(fromList [0,0,-1])]))) in\n let x' = fromList [xx - 0.5] in\n let y' = fromList [yy - 0.5] in\n let dir = normalize (look + x' * u + y' * v) in\n Ray eye dir\n\nintersectObj :: Ray -> Geometry -> Maybe Isect\nintersectObj r@(Ray rayPos rayDir) s@(Sphere center radius material) =\n let v = center - rayPos in\n let b = v <.> rayDir in\n let discriminant = b * b - v <.> v + radius * radius in\n if discriminant < 0.0 then\n Nothing\n else\n let det = sqrt discriminant in\n let (t1,t2) = (b - det, b + det) in\n if t2 < 0.0 then\n Nothing\n else if t1 > 0.0 then\n pure (Isect t1 (normalize (at t1 r)) s material)\n else\n pure (Isect t2 (normalize (at t2 r)) s material)\n\nintersect :: Scene -> Ray -> Maybe Isect\nintersect scene@(Scene _ objects _) r =\n let isects = filter (/= Nothing) . map (intersectObj r) $ objects in\n if length isects == 0 then\n Nothing\n else\n minimum isects\n\nperLightDiffuse :: Light -> Vector Double -> Vector Double -> Vector Double -> Double\nperLightDiffuse light isectPoint rayDir normal = \n let lightDir = getDirection light isectPoint in \n let ddot = lightDir <.> (if (rayDir <.> normal > 0) then -normal else normal) in\n let dmax = max ddot 0.0 in\n dmax\n\nperLightSpecular :: Light -> Vector Double -> Vector Double -> Vector Double -> Double\nperLightSpecular light isectPoint rayDir normal =\n let lightDir = getDirection light isectPoint in \n let reflect = lightDir - (fromList [2 * (lightDir <.> normal)]) * normal in\n if norm_2 reflect == 0 then\n 0\n else\n let reflectNorm = normalize reflect in\n let sdot = rayDir <.> reflect in\n let smax = max sdot 0.0 in\n smax\n\ncombineLightTerms :: Scene -> Vector Double -> Vector Double -> Vector Double -> Double -> Light -> Color\ncombineLightTerms scene isectPoint rayDir normal alpha light =\n let diffuse = perLightDiffuse light isectPoint rayDir normal in\n let specular = perLightSpecular light isectPoint rayDir normal in\n let color = lightColor light in\n let atten = (distanceAttenuation light isectPoint) * (shadowAttenuation scene light isectPoint) in\n color * (fromList [(diffuse + specular) * atten])\n\nshade :: Scene -> Ray -> Isect -> Color\nshade scene@(Scene lights objects ambient) r@(Ray p d) i@(Isect t normal _ material) = \n let (Material kaM ksM kdM keM krM ktM shiny) = material in\n let (MatParam ke) = keM in\n let emissive = ke in\n let (MatParam ka) = kaM in\n let amb = ka * ambient in\n let isectPoint = at t r in\n let alpha = shiny in\n emissive + amb + (sum . map (combineLightTerms scene isectPoint d normal alpha) $ lights)\n\ndata Screen = Screen {screenWidth :: Int,\n screenHeight :: Int}\n deriving (Show, Read, Eq)\n\nclamp :: Double -> Double -> Vector Double -> Vector Double\nclamp a b = fromList . map (\\x -> max a (min b x)) . toList\n\ntrace :: Scene -> Camera -> Double -> Double -> Color\ntrace scene camera x y =\n let ray = rayThrough camera x y in\n let color = traceRay scene ray 0 0 in\n clamp 0 1 color\n\ntracePixel :: Scene -> Screen -> Camera -> Int -> Int -> Color\ntracePixel scene (Screen width height) camera i j =\n let x = (fromIntegral i :: Double) / (fromIntegral width :: Double) in\n let y = (fromIntegral j :: Double) / (fromIntegral height :: Double) in\n let color = trace scene camera x y in \n (fromList [255.0]) * color\n\nreflection :: Scene -> Ray -> Isect -> Int -> Color\nreflection scene ray@(Ray p d) isect@(Isect t n _ mat) depth =\n let reflectR = d - (fromList [2 * d <.> n]) * n in\n if reflectR == 0 then\n fromList ([0,0,0])\n else\n let isectPointApprox = at (t - eps) ray in\n let reflRay = Ray isectPointApprox (normalize reflectR) in\n let (Material _ _ _ _ (MatParam kr) _ _) = mat in \n kr * (traceRay scene reflRay (depth - 1) 0)\n\ntraceRay :: Scene -> Ray -> Int -> Double -> Color\ntraceRay scene ray@(Ray p d) depth t =\n let mIsect = intersect scene ray in\n case mIsect of\n Nothing -> fromList[0,0,0]\n (Just isect) -> let colorC = shade scene ray isect in\n if depth == 0 then\n colorC\n else\n let colorRefl = reflection scene ray isect depth in\n colorC + colorRefl\n\ntype Image = ([[Color]], Int, Int)\n\ntraceImage :: Scene -> Screen -> Camera -> Image\ntraceImage scene screen@(Screen width height) camera =\n let (w, h) = (width - 1, height - 1) in\n let img = [[tracePixel scene screen camera i j | j <- [0..h]] | i <- [0..w]] in\n (img, width, height)\n\nrgbify :: [Double] -> G.Pixel G.RGB Double\nrgbify vec = G.PixelRGB (r / 255.0) (g / 255.0) (b / 255.0)\n where r = vec !! 0\n g = vec !! 1\n b = vec !! 2\n\nrender :: Image -> G.Image G.VU G.RGB Double\nrender (image, width, height) = G.fromLists . format $ image\n where format = map (map rgbify) . map (map toList)\n", "meta": {"hexsha": "71b154eec0b366e4c649b1ff3938c6c7310d54f4", "size": 9352, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/RayLib.hs", "max_stars_repo_name": "0AdityaD/raytracer", "max_stars_repo_head_hexsha": "dbfb66062814f2665a4907d237e97b980171f08d", "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/RayLib.hs", "max_issues_repo_name": "0AdityaD/raytracer", "max_issues_repo_head_hexsha": "dbfb66062814f2665a4907d237e97b980171f08d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RayLib.hs", "max_forks_repo_name": "0AdityaD/raytracer", "max_forks_repo_head_hexsha": "dbfb66062814f2665a4907d237e97b980171f08d", "max_forks_repo_licenses": ["BSD-3-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.2480620155, "max_line_length": 107, "alphanum_fraction": 0.5813729683, "num_tokens": 2560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5089907971080962}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\n------------------------------------------------\n-- |\n-- Module : Numeric.Matrix.Integral.HNFLLL\n-- Copyright : (c) Jun Yoshida 2019\n-- License : BSD3\n--\n-- Compute Hermite normal forms in the LLL-based method.\n-- The original \"pseudo-code\" is found in the paper\n-- George Havas, Bohdan S. Majewski & Keith R. Matthews (1998) Extended GCD and Hermite Normal Form Algorithms via Lattice Basis Reduction, Experimental Mathematics, 7:2, 125-136, DOI: 10.1080/10586458.1998.10504362 \n--\n------------------------------------------------\n\nmodule Numeric.Matrix.Integral.HNFLLL (\n hnfLLLST,\n hnfLLL,\n ) where\n\nimport Control.Monad (when, forM_)\nimport Control.Monad.ST\nimport Control.Monad.Loops (whileM_)\n\nimport Data.STRef\n\nimport qualified Data.Maybe as M\n\nimport Data.Int\n\nimport Numeric.LinearAlgebra ((!))\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Devel\n\n-- | Type class which guarantees the type can be embedded in the real number field\nclass (Num t,Eq t,Ord t) => Realizable t where\n toReal :: t -> Double\n\ninstance Realizable Double where\n toReal = id\n\ninstance Realizable Int64 where\n toReal = fromIntegral\n\n-- | Type class to qualify a type to be used in LLL-based algorithm\nclass (Realizable t, LA.Indexable (LA.Vector t) t, LA.Container LA.Vector t) => LLLQualified t\n\ninstance LLLQualified Double\n\ninstance LLLQualified Int64\n\n-- | Data Type to carry resources in the computation of LLL-based algorithm\ndata HNFLLLResource s t = HNFLLL {\n matA :: STMatrix s t,\n matU :: STMatrix s t,\n lambda :: STMatrix s Double,\n focusC1 :: STRef s (Maybe Int),\n focusC2 :: STRef s (Maybe Int) }\n\n-- | The function which is called Reduce2 in the original \"pseudo-code.\"\nreduceLLL :: (LLLQualified t) => Int -> Int -> HNFLLLResource s t -> ST s ()\nreduceLLL k i resRef = do\n ma <- freezeMatrix (matA resRef)\n case M.listToMaybe (LA.find (/=0) (ma!i)) of\n (Just j) -> do\n writeSTRef (focusC1 resRef) (Just j)\n when ( (ma!i!j) < 0 ) $ do\n rowOper (SCAL (-1) (Row i) AllCols) (matA resRef)\n rowOper (SCAL (-1) (Row i) AllCols) (matU resRef)\n rowOper (SCAL (-1) (Row (j+1)) (ColRange 0 j)) (lambda resRef)\n rowOper (SCAL (-1) (FromRow (j+2)) (Col (j+1))) (lambda resRef)\n Nothing -> writeSTRef (focusC1 resRef) Nothing\n case M.listToMaybe (LA.find (/=0) (ma!k)) of\n (Just j) -> writeSTRef (focusC2 resRef) (Just j)\n Nothing -> writeSTRef (focusC2 resRef) Nothing\n c1 <- readSTRef (focusC1 resRef)\n q <- fromIntegral.floor <$> do\n case c1 of\n (Just j) ->\n (/) <$> (toReal <$> readMatrix (matA resRef) k j) <*> (toReal <$> readMatrix (matA resRef) i j)\n Nothing -> do\n lki <- readMatrix (lambda resRef) (k+1) (i+1)\n di <- readMatrix (lambda resRef) (i+1) (i+1)\n if 2 * abs lki > di\n then return $ fromIntegral (round (lki / di))\n else return 0\n when (q /= 0) $ do\n rowOper (AXPY (negate q) i k AllCols) (matA resRef)\n rowOper (AXPY (negate q) i k AllCols) (matU resRef)\n rowOper (AXPY (toReal $ negate q) (i+1) (k+1) AllCols) (lambda resRef)\n\n-- | The function which is called Swap1 in the original \"pseudo-code.\"\nswapLLL :: (Num t, LA.Element t) => Int -> HNFLLLResource s t -> ST s ()\nswapLLL k resRef = do\n rowOper (SWAP k (k-1) AllCols) (matA resRef)\n rowOper (SWAP k (k-1) AllCols) (matU resRef)\n rowOper (SWAP k (k+1) (ColRange 0 (k-1))) (lambda resRef)\n ml <- freezeMatrix (lambda resRef)\n forM_ [(k+2)..(LA.cols ml-1)] $ \\i -> do\n writeMatrix (lambda resRef) i k $\n ((ml!i!k)*(ml!(k+1)!k) + (ml!i!(k+1))*(ml!(k-1)!(k-1)))/(ml!k!k)\n writeMatrix (lambda resRef) i (k+1) $\n ((ml!i!k)*(ml!(k+1)!(k+1)) + (ml!i!(k+1))*(ml!(k+1)!k))/(ml!k!k)\n writeMatrix (lambda resRef) k k $\n ((ml!(k+1)!k)*(ml!(k+1)!k) + (ml!(k+1)!(k+1))*(ml!(k-1)!(k-1)))/(ml!k!k)\n\n-- | Recognize whether a swap should occur or not.\nshouldSwapST :: (Num t, LA.Element t) => Int -> HNFLLLResource s t -> ST s Bool\nshouldSwapST k resRef = do\n ml <- freezeMatrix $ lambda resRef\n mc1 <- readSTRef $ focusC1 resRef\n mc2 <- readSTRef $ focusC2 resRef\n case (mc1,mc2) of\n (Just c1,Just c2) -> return $ c1 <= c2\n (Just _,Nothing) -> return True\n (Nothing,Just _) -> return False\n (Nothing,Nothing) ->\n return $ (ml!(k+1)!k)*(ml!(k+1)!k) + (ml!(k+1)!(k+1))*(ml!(k-1)!(k-1)) < (ml!k!k)*(ml!k!k)\n\n-- | ST to compute the Hermite normal form for the matrix in stMatA.\n-- The first argument is also subject to the operation that is executed on stMatA, so one gets the transformation unimodular matrix by passing the identity.\n-- See the source of hnfLLL function for an example of usage.\nhnfLLLST :: (LLLQualified t) => STMatrix s t -> STMatrix s t -> ST s ()\nhnfLLLST stMatU stMatA = do\n m <- LA.rows <$> freezeMatrix stMatA\n newLambda <- thawMatrix $ LA.ident (m+1)\n newC1 <- newSTRef Nothing\n newC2 <- newSTRef Nothing\n let resRef = HNFLLL stMatA stMatU newLambda newC1 newC2\n kRef <- newSTRef (1 :: Int)\n whileM_ (( readSTRef kRef) $ do\n k <- readSTRef kRef\n reduceLLL k (k-1) resRef\n shouldSwap <- shouldSwapST k resRef\n if shouldSwap\n then swapLLL k resRef >> when (k>1) (writeSTRef kRef (k-1))\n else (forM_ [0..k-2] $ \\i -> reduceLLL k i resRef) >> writeSTRef kRef (k+1)\n setMatrix stMatA 0 0 =<< (LA.flipud <$> freezeMatrix stMatA)\n setMatrix stMatU 0 0 =<< (LA.flipud <$> freezeMatrix stMatU)\n\n-- | Execute the LLL-based algorithm on a given matrix.\nhnfLLL :: LLLQualified t => LA.Matrix t -> (LA.Matrix t, LA.Matrix t)\nhnfLLL mtx = runST $ do\n stMatA <- thawMatrix mtx\n stMatU <- thawMatrix $ LA.ident (LA.rows mtx)\n hnfLLLST stMatU stMatA\n h <- freezeMatrix stMatA\n u <- freezeMatrix stMatU\n return (u,h)\n\n", "meta": {"hexsha": "f0c515adbc9d20593da3e086e0f2007c0ee2c4a7", "size": 5763, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Matrix/Integral/HNFLLL.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/HNFLLL.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/HNFLLL.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": 38.42, "max_line_length": 218, "alphanum_fraction": 0.6375151831, "num_tokens": 1932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5089558862537106}} {"text": "-- |\n-- Module : Numeric.SpecFunctions.Extra\n-- Copyright : (c) 2009, 2011 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Less common mathematical functions.\nmodule Numeric.SpecFunctions.Extra (\n bd0\n , chooseExact\n , logChooseFast\n , logGammaAS245\n , logGammaCorrection\n ) where\n\nimport Numeric.MathFunctions.Constants (m_NaN,m_pos_inf)\nimport Numeric.SpecFunctions.Internal (chooseExact,logChooseFast,logGammaCorrection)\n\n-- | Evaluate the deviance term @x log(x/np) + np - x@.\nbd0 :: Double -- ^ @x@\n -> Double -- ^ @np@\n -> Double \nbd0 x np \n | isInfinite x || isInfinite np || np == 0 = m_NaN\n | abs x_np >= 0.1*(x+np) = x * log (x/np) - x_np\n | otherwise = loop 1 (ej0*vv) s0\n where \n x_np = x - np\n v = x_np / (x+np)\n s0 = x_np * v\n ej0 = 2*x*v\n vv = v*v\n loop j ej s = case s + ej/(2*j+1) of\n s' | s' == s -> s' -- FIXME: Comparing Doubles for equality!\n | otherwise -> loop (j+1) (ej*vv) s'\n\n\n\n-- | Compute the logarithm of the gamma function Γ(/x/). Uses\n-- Algorithm AS 245 by Macleod.\n--\n-- Gives an accuracy of 10-12 significant decimal digits, except\n-- for small regions around /x/ = 1 and /x/ = 2, where the function\n-- goes to zero. For greater accuracy, use 'logGammaL'.\n--\n-- Returns ∞ if the input is outside of the range (0 < /x/ ≤ 1e305).\nlogGammaAS245 :: Double -> Double\n-- Adapted from http://people.sc.fsu.edu/~burkardt/f_src/asa245/asa245.html\nlogGammaAS245 x\n | x <= 0 = m_pos_inf\n -- Handle positive infinity. logGamma overflows before 1e308 so\n -- it's safe\n | x > 1e308 = m_pos_inf\n -- Normal cases\n | x < 1.5 = a + c *\n ((((r1_4 * b + r1_3) * b + r1_2) * b + r1_1) * b + r1_0) /\n ((((b + r1_8) * b + r1_7) * b + r1_6) * b + r1_5)\n | x < 4 = (x - 2) *\n ((((r2_4 * x + r2_3) * x + r2_2) * x + r2_1) * x + r2_0) /\n ((((x + r2_8) * x + r2_7) * x + r2_6) * x + r2_5)\n | x < 12 = ((((r3_4 * x + r3_3) * x + r3_2) * x + r3_1) * x + r3_0) /\n ((((x + r3_8) * x + r3_7) * x + r3_6) * x + r3_5)\n | x > 3e6 = k\n | otherwise = k + x1 *\n ((r4_2 * x2 + r4_1) * x2 + r4_0) /\n ((x2 + r4_4) * x2 + r4_3)\n where\n (a , b , c)\n | x < 0.5 = (-y , x + 1 , x)\n | otherwise = (0 , x , x - 1)\n\n y = log x\n k = x * (y-1) - 0.5 * y + alr2pi\n alr2pi = 0.918938533204673\n\n x1 = 1 / x\n x2 = x1 * x1\n\n r1_0 = -2.66685511495; r1_1 = -24.4387534237; r1_2 = -21.9698958928\n r1_3 = 11.1667541262; r1_4 = 3.13060547623; r1_5 = 0.607771387771\n r1_6 = 11.9400905721; r1_7 = 31.4690115749; r1_8 = 15.2346874070\n\n r2_0 = -78.3359299449; r2_1 = -142.046296688; r2_2 = 137.519416416\n r2_3 = 78.6994924154; r2_4 = 4.16438922228; r2_5 = 47.0668766060\n r2_6 = 313.399215894; r2_7 = 263.505074721; r2_8 = 43.3400022514\n\n r3_0 = -2.12159572323e5; r3_1 = 2.30661510616e5; r3_2 = 2.74647644705e4\n r3_3 = -4.02621119975e4; r3_4 = -2.29660729780e3; r3_5 = -1.16328495004e5\n r3_6 = -1.46025937511e5; r3_7 = -2.42357409629e4; r3_8 = -5.70691009324e2\n\n r4_0 = 0.279195317918525; r4_1 = 0.4917317610505968;\n r4_2 = 0.0692910599291889; r4_3 = 3.350343815022304\n r4_4 = 6.012459259764103\n", "meta": {"hexsha": "6aa52fc2b1198a3085eca6677ee42cdc47b87c96", "size": 3551, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/SpecFunctions/Extra.hs", "max_stars_repo_name": "Shimuuar/math-functions", "max_stars_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2015-06-05T09:06:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-15T17:18:01.000Z", "max_issues_repo_path": "Numeric/SpecFunctions/Extra.hs", "max_issues_repo_name": "Shimuuar/math-functions", "max_issues_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2015-08-23T21:28:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-31T11:52:32.000Z", "max_forks_repo_path": "Numeric/SpecFunctions/Extra.hs", "max_forks_repo_name": "Shimuuar/math-functions", "max_forks_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-03-29T03:36:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-25T16:40:04.000Z", "avg_line_length": 36.6082474227, "max_line_length": 85, "alphanum_fraction": 0.5344973247, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5085003792925807}} {"text": "{-# LANGUAGE ConstraintKinds, FlexibleContexts, FlexibleInstances, GADTs #-}\n{-# LANGUAGE KindSignatures, MultiParamTypeClasses #-}\n{-# LANGUAGE NoMonomorphismRestriction, TypeFamilies, TypeSynonymInstances #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Algebra.Matrix (Matrix(..), delta, companion,\n gaussReduction, maxNorm, rankWith, det,\n inverse, inverseWith) where\nimport Algebra.Internal\nimport qualified Algebra.LinkedMatrix as LM\nimport Algebra.Prelude.Core hiding (maxNorm, zero)\n\nimport Control.Lens (both, view, (%~), (&), _3)\nimport Control.Monad (when)\nimport qualified Data.Matrix as DM\nimport qualified Data.Vector as V\nimport GHC.Exts (Constraint)\nimport Numeric.Algebra (Additive, DecidableZero)\nimport Numeric.Algebra (Monoidal, Multiplicative)\nimport Numeric.Algebra (Unital)\nimport qualified Numeric.Algebra as NA\nimport qualified Numeric.Decidable.Zero as NA\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Numeric.LinearAlgebra.Devel as LA\nimport qualified Prelude as P\n\n{-# ANN module \"HLint: ignore Redundant bang pattern\" #-}\n\nclass Matrix mat where\n type Elem mat a :: Constraint\n cmap :: (Elem mat a, Elem mat b) => (a -> b) -> mat a -> mat b\n empty :: Elem mat b => mat b\n fromLists :: Elem mat a => [[a]] -> mat a\n fromCols :: Elem mat a => [V.Vector a] -> mat a\n fromCols [] = zero 0 0\n fromCols xs = foldr1 (<||>) $ map colVector xs\n fromRows :: Elem mat a => [V.Vector a] -> mat a\n fromRows [] = zero 0 0\n fromRows xs = foldr1 (<-->) $ map rowVector xs\n toCols :: Elem mat a => mat a -> [V.Vector a]\n toCols m = map (`getCol` m) [1..ncols m]\n toRows :: Elem mat a => mat a -> [V.Vector a]\n toRows m = map (`getRow` m) [1..nrows m]\n ncols :: mat a -> Int\n nrows :: mat a -> Int\n identity :: Elem mat a => Int -> mat a\n diag :: Elem mat a => V.Vector a -> mat a\n getDiag :: Elem mat a => mat a -> V.Vector a\n trace :: Elem mat a => mat a -> a\n diagProd :: Elem mat a => mat a -> a\n zero :: Elem mat a => Int -> Int -> mat a\n colVector :: Elem mat a => V.Vector a -> mat a\n rowVector :: Elem mat a => V.Vector a -> mat a\n getCol :: Elem mat a => Int -> mat a -> V.Vector a\n getRow :: Elem mat a => Int -> mat a -> V.Vector a\n switchRows :: Elem mat a => Int -> Int -> mat a -> mat a\n scaleRow :: Elem mat a => a -> Int -> mat a -> mat a\n combineRows :: Elem mat a => Int -> a -> Int -> mat a -> mat a\n trans :: Elem mat a => mat a -> mat a\n buildMatrix :: Elem mat a => Int -> Int -> ((Int, Int) -> a) -> mat a\n index :: Elem mat a => Int -> Int -> mat a -> Maybe a\n index i j m = if 1 <= i && i <= nrows m && 1 <= j && j <= ncols m\n then Just $ m ! (i, j)\n else Nothing\n (!) :: Elem mat a => mat a -> (Int, Int) -> a\n (<||>) :: Elem mat a => mat a -> mat a -> mat a\n (<-->) :: Elem mat a => mat a -> mat a -> mat a\n nonZeroRows :: (DecidableZero a, Elem mat a) => mat a -> [Int]\n nonZeroRows = map fst . filter (V.any (not . NA.isZero) . snd) . zip [1..] . toRows\n nonZeroCols :: (DecidableZero a, Elem mat a) => mat a -> [Int]\n nonZeroCols = map fst . filter (V.any (not . NA.isZero) . snd) . zip [1..] . toCols\n\ninstance Matrix DM.Matrix where\n type Elem DM.Matrix a = P.Num a\n empty = DM.zero 0 0\n cmap = fmap\n fromLists = DM.fromLists\n ncols = DM.ncols\n nrows = DM.nrows\n trans = DM.transpose\n identity = DM.identity\n diag v = DM.matrix (V.length v) (V.length v) $ \\(i, j) ->\n if i == j then v V.! (i-1) else 0\n getDiag = DM.getDiag\n trace = DM.trace\n diagProd = DM.diagProd\n zero = DM.zero\n colVector = DM.colVector\n rowVector = DM.rowVector\n getCol = DM.getCol\n getRow = DM.getRow\n switchRows = DM.switchRows\n combineRows = DM.combineRows\n scaleRow = DM.scaleRow\n buildMatrix = DM.matrix\n (!) = (DM.!)\n (<||>) = (DM.<|>)\n (<-->) = (DM.<->)\n\nswapIJ :: Eq a => a -> a -> a -> a\nswapIJ i j k\n | k == i = j\n | k == j = i\n | otherwise = k\n\ninstance Matrix LA.Matrix where\n type Elem LA.Matrix a = (P.Num a, LA.Numeric a, LA.Element a, LA.Container LA.Vector a)\n empty = LA.fromLists [[]]\n fromLists = LA.fromLists\n cmap = LA.cmap\n ncols = LA.cols\n nrows = LA.rows\n trans = LA.tr\n identity = LA.ident\n fromCols = LA.fromColumns . map (LA.fromList . V.toList)\n diag = LA.diag . LA.fromList . V.toList\n getDiag = V.fromList . LA.toList . LA.takeDiag\n trace = LA.sumElements . LA.takeDiag\n diagProd = LA.prodElements . LA.takeDiag\n zero i j = LA.konst 0 (i, j)\n colVector = LA.asColumn . LA.fromList . V.toList\n rowVector = LA.asRow . LA.fromList . V.toList\n toCols = map (V.fromList . LA.toList) . LA.toColumns\n toRows = map (V.fromList . LA.toList) . LA.toRows\n getCol i = V.fromList . LA.toList . (!! (i - 1)) . LA.toColumns\n getRow i = V.fromList . LA.toList . (!! (i - 1)) . LA.toRows\n switchRows i j m = m LA.? map (swapIJ (i-1) (j-1)) [0.. nrows m - 1]\n combineRows j s i m = LA.mapMatrixWithIndex (\\(k,l) v -> if k == j - 1 then s P.* (m ! (i,l+1)) P.+ v else v) m\n buildMatrix w h f = LA.build (w, h) (\\i j -> f (toIntLA i+1, toIntLA j+1))\n scaleRow a i = (fst .) $ LA.mutable $ \\(k, l) m -> do\n v <- LA.readMatrix m k l\n when (k == i - 1) $\n LA.writeMatrix m k l (a P.* v)\n m ! (i, j) = m `LA.atIndex` (i - 1, j - 1)\n m <||> n = LA.fromColumns $ LA.toColumns m ++ LA.toColumns n\n m <--> n = LA.fromRows $ LA.toRows m ++ LA.toRows n\n\ntoIntLA :: LA.Container LA.Matrix e => e -> Int\ntoIntLA e = fromIntegral $ LA.toZ ((1 LA.>< 1) [e]) `LA.atIndex` (0, 0)\n\ninstance Matrix LM.Matrix where\n type Elem LM.Matrix a = (CoeffRing a, Unital a, Monoidal a, Multiplicative a, Additive a)\n cmap = LM.cmap\n (!) m pos = m LM.! (pos & both %~ pred)\n index i j = LM.index (i-1) (j-1)\n empty = LM.empty\n buildMatrix h w f = LM.fromList [((i, j), f (i,j)) | j <- [1..w], i <- [1..h]]\n trans = LM.transpose\n combineRows j s i = LM.combineRows s (i-1) (j-1)\n switchRows i j = LM.switchRows (i-1) (j-1)\n scaleRow a i = LM.scaleRow a (pred i)\n zero = LM.zeroMat\n identity = LM.identity\n diag = LM.diag\n getDiag = LM.getDiag\n diagProd = LM.diagProd\n trace = LM.trace\n getRow = LM.getRow . pred\n getCol = LM.getCol . pred\n nrows = LM.nrows\n ncols = LM.ncols\n fromLists = LM.fromLists\n (<||>) = (LM.<||>)\n (<-->) = (LM.<-->)\n rowVector = LM.rowVector\n colVector = LM.colVector\n nonZeroRows = LM.nonZeroRows\n nonZeroCols = LM.nonZeroCols\n\ndelta :: (NA.Monoidal r, NA.Unital r) => Int -> Int -> r\ndelta i j | i == j = NA.one\n | otherwise = NA.zero\n\ncompanion :: (KnownNat n, CoeffRing r, Matrix mat,\n Elem mat r, IsMonomialOrder n ord)\n => Ordinal n -> OrderedPolynomial r ord n -> mat r\ncompanion odn poly =\n let deg = totalDegree' poly\n vx = leadingMonomial (var odn `asTypeOf` poly)\n in buildMatrix deg deg $ \\(j, k) ->\n if 1 <= k && k <= deg - 1\n then delta j (k+1)\n else NA.negate $ coeff (NA.pow vx (fromIntegral $ j-1 :: NA.Natural)) poly\n\n-- | @gaussReduction a = (a', p)@ where @a'@ is row echelon form and @p@ is pivoting matrix.\ngaussReduction :: (Matrix mat, Elem mat a, Normed a, Eq a, NA.Field a)\n => mat a -> (mat a, mat a)\ngaussReduction mat =\n let (a, b, _) = gaussReduction' mat in (a, b)\n\n-- | @gaussReduction a = (a', p)@ where @a'@ is row echelon form and @p@ is pivoting matrix.\ngaussReduction' :: (Matrix mat, Elem mat a, Normed a, Eq a, NA.Field a)\n => mat a -> (mat a, mat a, a)\ngaussReduction' mat = {-# SCC \"gaussRed\" #-} go 1 1 mat (identity $ nrows mat) NA.one\n where\n go i j a p acc\n | i > nrows mat || j > ncols mat = (a, p, acc)\n | otherwise =\n let (k, new) = maximumBy (comparing $ norm . snd) [(l, a ! (l, j)) | l <- [i..nrows mat]]\n in if new == NA.zero\n then go i (j + 1) a p NA.zero\n else let prc l a0 p0\n | l == i = prc (l+1) a0 p0\n | l > nrows mat = (a0, p0)\n | otherwise =\n let coe = NA.negate (a0 ! (l, j))\n a'' = combineRows l coe i a0\n p'' = combineRows l coe i p0\n in prc (l+1) a'' p''\n (a', p') = prc 1 (scaleRow (NA.recip new) i $ switchRows i k a)\n (scaleRow (NA.recip new) i $ switchRows i k p)\n offset = if i == k then id else NA.negate\n in go (i+1) (j+1) a' p' (offset $ acc NA.* new)\n\ndet :: (Elem mat a, Eq a, NA.Field a, Normed a, Matrix mat)\n => mat a -> a\ndet = view _3 . gaussReduction'\n\nmaxNorm :: (Elem mat a, Normed a, Matrix mat) => mat a -> Norm a\nmaxNorm = maximum . concat . map (map norm . V.toList) . toRows\n\nrankWith :: (Elem mat r, CoeffRing r, Matrix mat)\n => (mat r -> mat r) -> mat r -> Int\nrankWith gauss = length . nonZeroRows . gauss\n\ninverse :: (Elem mat a, Eq a, NA.Field a, Normed a, Matrix mat)\n => mat a -> mat a\ninverse = snd . gaussReduction\n\ninverseWith :: (mat a -> (mat a, mat a)) -> mat a -> mat a\ninverseWith = (snd .)\n", "meta": {"hexsha": "ede5bbdd37d7133866ba54ef026b5294b6e117a9", "size": 9305, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "halg-matrices/src/Algebra/Matrix.hs", "max_stars_repo_name": "hangingman/computational-algebra", "max_stars_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2015-02-09T01:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T04:37:09.000Z", "max_issues_repo_path": "halg-matrices/src/Algebra/Matrix.hs", "max_issues_repo_name": "hangingman/computational-algebra", "max_issues_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-09-18T16:31:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T08:28:37.000Z", "max_forks_repo_path": "halg-matrices/src/Algebra/Matrix.hs", "max_forks_repo_name": "hangingman/computational-algebra", "max_forks_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-12-22T16:04:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T19:35:53.000Z", "avg_line_length": 40.2813852814, "max_line_length": 113, "alphanum_fraction": 0.5647501343, "num_tokens": 2972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.50733395402027}} {"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FunctionalDependencies #-}\nmodule VAD(\n vad\n ) where \n\n-- let framed = frameWithWinAndOverlap 256 hann 10 s\n-- sp = mapS (fft . U.map (:+ 0)) framed \n--\n\nimport Prelude hiding(splitAt,(:),foldr1,tail,(++))\nimport Internal\nimport Signal \nimport qualified Data.Vector.Unboxed as U\nimport Data.Vector.Unboxed((!),Unbox(..))\nimport Data.List.Stream\nimport Common \nimport Windows\nimport Data.Complex \nimport Transform\nimport qualified Trace as F\nimport Fixed\nimport GHC.TypeLits\nimport SpecialInt \nimport Data.Int \n\nltseF :: Sample a \n => Int \n -> Signal (U.Vector a) \n -> Signal (U.Vector a) \nltseF n (Signal s) = \n let (before,remaining) = splitAt n s\n _lste b (h:t) = \n let (future,tl) = splitAt n t \n valueMax = U.zipWith max (foldr1 (U.zipWith max) (h:future)) (foldl1' (U.zipWith max) b) \n in \n valueMax:(_lste (tail before ++ [h]) t)\n in \n Signal (_lste before remaining)\n\nlstdD :: Int \n -> U.Vector Double \n -> U.Vector Double\n -> Double\nlstdD winSize noiseEnergy lste = \n let d a b | b == 0 = fromDouble 1e12 \n | otherwise = a / b \n in\n 10 * log(U.sum (U.zipWith (d) lste noiseEnergy) / fromIntegral winSize) / log 10\n\ntheTotal :: (SingI r, SingI s, SingI n)\n => Fixed Int32 n s r \n -> U.Vector (Fixed Int32 n s r) \n -> U.Vector (Fixed Int32 n s r) \n -> Fixed Int40 n s r \ntheTotal m lste noiseEnergy = \n let d a b | b == 0 = convert m \n | otherwise = convert a / convert b\n in\n U.sum (U.zipWith (d) lste noiseEnergy)\n{-# INLINE [0] theTotal #-}\n\nlstdF :: (SingI n, SingI s, SingI r) \n => Int \n -> U.Vector (Fixed Int32 n s r)\n -> U.Vector (Fixed Int32 n s r)\n -> (Fixed Int32 n s r)\nlstdF winSize noiseEnergy lste = 10 * log(convert $ theTotal maxBound lste noiseEnergy/ fromIntegral winSize) / log 10\n\ngetDecisionF :: (SingI n, SingI s, SingI r, SingI (n + n)) \n => Int \n -> U.Vector (Fixed Int32 (n + n) s r) \n -> [(U.Vector (Fixed Int32 (n + n) s r), U.Vector (Fixed Int32 (n + n) s r) )] \n -> [Fixed Int16 n s r]\ngetDecisionF winSize energy ((c,currentE):r) = \n let tv = fromDouble 31.0\n tn = fromDouble 27.0\n l = lstdF winSize energy c \n result | l >= tv = 1 : getDecisionF winSize energy r\n | l <= tn = 0 : getDecisionF winSize currentE r\n | otherwise = 0 : getDecisionF winSize energy r\n in \n result\ngetDecisionF winSize energy [] = 0:getDecisionF winSize energy []\n\ngetDecisionD :: Int \n -> U.Vector Double \n -> [(U.Vector Double, U.Vector Double)]\n -> [Double]\ngetDecisionD winSize energy ((c,currentE):r) = \n let tv = fromDouble 31.0\n tn = fromDouble 27.0\n l = lstdD winSize energy c \n result | l >= tv = 1 : getDecisionD winSize energy r\n | l <= tn = 0 : getDecisionD winSize currentE r\n | otherwise = 0 : getDecisionD winSize energy r\n in \n result\ngetDecisionD winSize energy [] = 0:getDecisionD winSize energy []\n\nbandEnergy :: Complex Double -> Double\nbandEnergy (x :+ y) = x*x + y*y \n\nbandEnergyF :: (SingI n, SingI s, SingI r, SingI (n + n)) => Complex (Fixed Int16 n s r) -> Fixed Int32 (n + n) s r\nbandEnergyF (x :+ y) = amul x x + amul y y\n\nclass VAD a where \n vad :: (Sample a, FFT a) \n => Sampled Time a\n -> Sampled Time a\n\ninstance (SingI n, SingI s, SingI r, SingI (n + n)) => VAD (Fixed Int16 n s r) where \n vad s = \n let winSize = 256 \n overlap = 20\n n = 2\n framed = frameWithWinAndOverlap winSize overlap hann s\n energy = mapS (U.map bandEnergyF . fft . U.map (:+ 0)) (getSignal framed)\n noiseEnergy0 = U.generate winSize (const (fromDouble 0.00001))\n lt = ltseF n energy \n in \n --mapS (lstd winSize noiseEnergy0) lt\n Sampled (period framed) (onSamples (getDecisionF winSize noiseEnergy0) (zipS lt (dropS n energy))) \n\ninstance VAD Double where\n vad s = \n let winSize = 256 \n overlap = 20\n n = 2\n framed = frameWithWinAndOverlap winSize overlap hann s\n energy = mapS (U.map bandEnergy . fft . U.map (:+ 0)) (getSignal framed)\n noiseEnergy0 = U.generate winSize (const (fromDouble 0.00001))\n lt = ltseF n energy \n in \n --mapS (lstd winSize noiseEnergy0) lt\n Sampled (period framed) (onSamples (getDecisionD winSize noiseEnergy0) (zipS lt (dropS n energy))) \n", "meta": {"hexsha": "44897c4792ebe198514dc70e9b7549107cdc9e99", "size": 4879, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "VAD.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": "VAD.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": "VAD.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": 34.3591549296, "max_line_length": 118, "alphanum_fraction": 0.5808567329, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5069509915984216}} {"text": "{-|\nModule : GradientDescent\n|-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies #-}\n\nmodule GradientDescent\n ( sigmoid\n , sigmoidPrime\n , matrixSigmoid\n , matrixSigmoidPrime\n , getOutcomes\n , gradientDescent\n ) where\n\nimport Numeric.LinearAlgebra\nimport qualified Data.List.Split as S\nimport System.Random\nimport Data.Array.IO\nimport Control.Monad\nimport GHC.Float\nimport Network\n\n\n-- | Shuffle list\nshuffle :: [a] -> IO [a]\nshuffle xs = do\n ar <- newArray n xs\n forM [1..n] $ \\i -> do\n j <- randomRIO (i,n)\n vi <- readArray ar i\n vj <- readArray ar j\n writeArray ar j vi\n return vj\n where\n n = length xs\n newArray :: Int -> [a] -> IO (IOArray Int a)\n newArray n = newListArray (1, n)\n\n\n-- | Sigmoid Function\nsigmoid :: Double -> Double\nsigmoid x = 1.0 / (1.0 + exp (-x))\n\n\n-- | Apply Sigmoid Function for every element of matrix\nmatrixSigmoid :: Matrix Double -> Matrix Double\nmatrixSigmoid = cmap sigmoid\n\n\n-- | Sigmoid Prime Function\nsigmoidPrime :: Double -> Double\nsigmoidPrime x = sigmoid x * (1 - sigmoid x)\n\n\n-- | Apply Sigmoid Prime Function for every element of matrix\nmatrixSigmoidPrime :: Matrix Double -> Matrix Double\nmatrixSigmoidPrime = cmap sigmoidPrime\n\n\n-- | Cost function\ncostPrime :: Matrix Double -> Matrix Double -> Matrix Double\ncostPrime outputActivations y = outputActivations - y\n\n\n-- | Feed Forward algorithm\nfeedForward :: Net -- ^ Neural Network\n -> Matrix Double -- ^ Image Matrix\n -> Matrix Double\nfeedForward net x = foldl (\\z (w,b)-> matrixSigmoid ((w <> z) + b)) x (zip (weights net) (biases net))\n\n\n-- | Evaluate Neural Network predictions\nevaluate :: Net -- ^ Neural Network for evaluation\n -> [(Matrix Double, Int)] -- ^ List of Test Images with their corresponding label\n -> Double -- ^ Returns Count of positive predictions\nevaluate net testData = sum $ fmap (\\(x,y) -> if x==y then 1.0 else 0.0) outcomes\n where\n testImages = map fst testData\n testLabels = map snd testData\n outcomes = zip (fmap (head . fmap maxIndex . toColumns . feedForward net) testImages) testLabels\n\n\n-- | Get Neural Network predictions\ngetOutcomes :: Net -- ^ Neural Network\n -> [(Matrix Double, Int)] -- ^ List of Test Images with their corresponding labels\n -> [([Float], (Int, Int))] -- ^ Returns List of Test Images with their corresponding label and predictions\ngetOutcomes net testData = zip listImages outcomes\n where\n testImages = map fst testData\n testLabels = map snd testData\n listImages = head . toLists . tr . cmap double2Float <$> testImages\n outcomes = zip (fmap (head . fmap maxIndex . toColumns . feedForward net) testImages) testLabels\n\n\n-- | Get List of neuron activations\nneuronActivation :: [Matrix Double] -- ^ Weights of Neural Network\n -> [Matrix Double] -- ^ Biases of Neural Network\n -> Matrix Double -- ^ Image Matrix\n -> [Matrix Double]\nneuronActivation [] [] x = []\nneuronActivation (w:ws) (b:bs) x = z : neuronActivation ws bs (matrixSigmoid z)\n where\n z = (w <> x) + b\n\n\n-- | Calculate deltas\ncalDelta :: Net -- ^ Neural Network\n -> [Matrix Double] -- ^ Weights of Neural Network\n -> [Matrix Double] -- ^ List of Neuron Activations\n -> Matrix Double -- ^ delta\n -> Int -- ^ current layer\n -> [Matrix Double]\ncalDelta net w z delta l\n | l == numLayers net = [delta]\n | otherwise = calDelta net (tail w) (tail z) d (l + 1) ++ [delta]\n where\n sp = matrixSigmoidPrime (head z)\n d = tr (head w) <> delta * sp\n\n\n-- | Back Propagation algorithm\nbackProp :: Net -- ^ Neural Network\n -> Matrix Double -- ^ Image Matrix\n -> Matrix Double -- ^ Image vectorized label\n -> ([Matrix Double],[Matrix Double])\nbackProp net x y = (nablaW, nablaB)\n where\n zs = neuronActivation (weights net) (biases net) x\n activations = x : (matrixSigmoid <$> zs)\n delta = (costPrime (last activations) y * matrixSigmoidPrime (last zs)) :: Matrix Double\n lDelta = calDelta net (reverse $ weights net) (tail $ reverse zs) delta 2\n nablaB = lDelta\n nablaW = (\\ (x, y) -> x <> tr y) <$> zip lDelta activations\n\n\n-- | Calculate Nabla for Weights and Biases\ncalNabla :: Net -- ^ Neural Network\n -> [(Matrix Double, Matrix Double)] -- ^ Batch of Images with their corresponding labels\n -> [Matrix Double] -- ^ List of Nabla Matrix's of Weights\n -> [Matrix Double] -- ^ List of Nabla Matrix's of Biases\n -> ([Matrix Double], [Matrix Double])\ncalNabla net [] nW nB = (nW, nB)\ncalNabla net (x:xs) nW nB = calNabla net xs nablaW nablaB\n where\n (deltaNablaW, deltaNablaB) = uncurry (backProp net) x\n nablaB = uncurry (+) <$> zip nB deltaNablaB\n nablaW = uncurry (+) <$> zip nW deltaNablaW\n\n\n-- | Update network's weights and biases for each batch\nupdateMiniBatch :: Net -- ^ Neural Network\n -> [(Matrix Double, Matrix Double)] -- ^ Batch of Images with their corresponding labels\n -> Double -- ^ Alpha\n -> Net\nupdateMiniBatch net miniBatch alpha = newNet\n where\n nB = fmap (\\x -> konst (0 :: Double) ((fst $ size x) :: Int, (snd $ size x) :: Int) :: Matrix Double) (biases net)\n nW = fmap (\\x -> konst (0 :: Double) ((fst $ size x) :: Int, (snd $ size x) :: Int) :: Matrix Double) (weights net)\n (nablaW, nablaB) = calNabla net miniBatch nW nB\n newWeights = (\\(x,y) -> x - cmap (\\ p -> (alpha / fromIntegral (length miniBatch)) * p) y ) <$> zip (weights net) nablaW\n newBiases = (\\(x,y) -> x - cmap (\\ p -> (alpha / fromIntegral (length miniBatch)) * p) y ) <$> zip (biases net) nablaB\n newNet = Net (numLayers net) (sizes net) newBiases newWeights\n\n\n-- | Train Neural Network\ngradientDescent :: Net -- ^ Neural Network to train\n -> [(Matrix Double, Matrix Double)] -- ^ List of Training Images with column vectorized labels\n -> Int -- ^ Number of training iterations\n -> Int -- ^ Size of Image batches\n -> Double -- ^ Alpha\n -> [(Matrix Double, Int)] -- ^ List of Test Images with Labels\n -> IO Net\ngradientDescent net trainingData epochs miniBatchSize alpha testData = loop net 0\n where\n nTest = fromIntegral (length testData)\n loop currentNet epoch = do\n let evaluation = 100.0 * evaluate currentNet testData / nTest\n let evaluationMsg = \"Epoch: \" ++ show epoch ++ \" = \" ++ show evaluation ++ \"% Out Of \" ++ show nTest ++ \" Test Images\"\n print evaluationMsg\n if epoch == epochs then return currentNet\n else do\n shuffledTrainingData <- shuffle trainingData\n let miniBatches = S.chunksOf miniBatchSize shuffledTrainingData\n let newNet = foldl (\\z x-> updateMiniBatch z x alpha) currentNet miniBatches\n loop newNet (epoch + 1)\n\n", "meta": {"hexsha": "1e4e4c9143828ba854720d916a17efc2a5dd1e63", "size": 6928, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/GradientDescent.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": "src/GradientDescent.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": "src/GradientDescent.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": 36.8510638298, "max_line_length": 124, "alphanum_fraction": 0.628608545, "num_tokens": 1835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.5064960217026644}} {"text": "{-# LANGUAGE LambdaCase, BangPatterns #-}\nmodule Stock where\n\nimport Data.Random.Normal\nimport System.Random\nimport Data.Random\nimport Diff\nimport Numeric.SpecFunctions\nimport Numeric.LinearAlgebra\nimport Util\n\nndigits :: Int\nndigits = 4\n\nroundToN :: Int -> Double -> Double\nroundToN n number = (fromInteger (round (number * (10^n)))) / (10.0^n)\n\n-- constants\nr :: Double\nr = 0.06\n\nvariance :: Double\nvariance = 0.2\n\ndays :: Int\ndays = 360\n\nyperiod :: Double\nyperiod = (fromIntegral days) / 360.0\n\ntdiff :: Int\ntdiff = 40\n\ntstep :: Double\ntstep = (fromIntegral tdiff) / 360.0\n\ns0 :: Double\ns0 = 36.0000\n\nk :: Double\nk = 40.000\n\nd1 :: Double\nd1 = (log (s0 / k) + (r + variance / 2) * yperiod) / (sqrt (variance * yperiod))\n\nd2 :: Double\nd2 = d1 - sqrt (variance * yperiod)\n\n-- c = s_0 * N(D_1) - exp (-r * T) * K * N(D_2)\nn :: Double -> Double\nn = cdf StdNormal\n\nc :: Double\nc = s0 * (n d1) - (exp (-r * yperiod)) * k * (n d2)\n\np :: Double\np = c + k * exp (-r * yperiod) - s0\n\n\n\n--- basis functions\nl :: Int -> String -> DiffLang\nl n x\n | n >= 0 = (Exp ((Const (-0.5)) :*: (Var x))) :*: (Exp (Var x)) :*: (Const (1/(factorial n))) :*: (derivN n (laguerre n x) x)\n | otherwise = error \"undefined basis function\"\n\n\nrzs :: Integer -> [Double]\nrzs rand = normals' (0.0,1.0) (mkStdGen (fromIntegral rand))\n\nsRand :: Integer -> Int -> Double\nsRand j n =\n let zs = rzs j\n in s zs n\n\ns :: [Double] -> Int -> R\ns zs 0 = s0\ns zs n\n | n > 0 = roundToN ndigits $ (s zs (n - 1)) * (exp $ (r - variance/2) * tstep + ((sqrt (variance * tstep)) * (zs!!n)))\n\n\ncf :: [R] -> [R]\ncf = map (\\stdj -> max (k - stdj) 0)\n\ncv :: R -> R\ncv = (* (exp (-r * tstep)))\n\neval :: DiffLang -> R -> R\neval (Var _) x = x\neval (Const n) _ = n\neval (e1 :+: e2) x = eval e1 x + eval e2 x\neval (e1 :*: e2) x = eval e1 x * eval e2 x\neval (e1 :^: e2) x = eval e1 x ** eval e2 x\neval (Exp e) x = exp (eval e x)\n\n-- compute coefficients {beta_i} using (n-1)'th day's cash as predicator values,\n-- n'th days cv as ys\nregColN :: ([Vector R], [Vector R]) -> Int -> Matrix R\nregColN (paths, cfs) n\n | length paths > n && n > 1 = regCol n laguerreBasis s t\n | otherwise = error \"too big a N\"\n where st :: ([R], [R], [R])\n st = unzip3 $ filter (\\(a,b,c) -> a /= 0) $ zip3 (toList (cfs!!(n-1))) (toList (paths!!(n-1))) (toList (cfs!!n))\n s :: Vector R\n s = fromList $ sndOf3 st\n t :: Vector R\n t = fromList $ thdOf3 st\n\nlaguerreJ :: Int -> R -> R\nlaguerreJ j = eval (laguerre j \"X\")\n\nlaguerreBasis :: [R -> R]\nlaguerreBasis = map laguerreJ [0..(days `div` tdiff)]\n\nregCol :: Int -> [R -> R] -> Vector R -> Vector R -> Matrix R -- n x 1 result\nregCol n basis s t = linearSolveLS a b\n where a :: Matrix R\n -- a = fromColumns $ map (\\j -> (fromList . map (basis!!j) . toList) s) [0..n-1]\n a = fromRows $ map (\\x -> (fromList . map (\\j -> (basis!!j) x)) [0..n-1]) (toList s)\n b :: Matrix R\n b = (asColumn . fromList . map cv) (toList t)\n\nevalPoly :: R -> [R] -> R\nevalPoly x betas = foldl (\\acc beta -> acc + beta * x) 0 betas\n\nevalPolyL :: [R] -> [R] -> [R]\nevalPolyL xs betas = map (\\x -> evalPoly x betas) xs\n\nepsilon :: Double\nepsilon = 0.00000001\n\ncfP :: ([Vector R], [Vector R]) -> Int -> [Vector R]\ncfP (paths, cfs) n\n | length paths > n && n > 1 = [newCFNP, finalCFN]\n | otherwise = error \"undefined at the date!\"\n where cfn = map (\\p -> if fst p == 0 then 0 else snd p) $ zip oldCFP predCF\n finalCFN = fromList $ map (\\(s,t) -> if s <= epsilon then 0.0 else t) (zip newCFN oldCFN)\n newCFN = map (\\(s,t) -> if t >= s then t else 0.0) (zip oldCFP cfn)\n newCFNP = fromList $ map (\\(s,t) -> if t >= s then 0.0 else s) (zip oldCFP cfn)\n -- newCFNP = fromList $ map (\\(s,t) -> if t <= epsilon then 0.0 else s) (zip oldCFP cfn)\n oldCFN = toList $ cfs!!n\n oldCFP = toList $ cfs!!(n-1)\n predCF = map (\\x -> (foldl (\\acc -> \\case { (n,beta) -> beta * (laguerreBasis!!n) x + acc }) 0 betas)) (toList (paths!!(n-1)))\n betas :: [(Int,R)]\n betas = zip [0..n-1] ((toList . head . toColumns . regColN (paths, cfs)) n)\n\ncfGenRStep :: ([Vector R], [Vector R]) -> Int -> [Vector R]\ncfGenRStep (pathsC, cfsC) n = take (n - 1) cfsC ++ cfP (pathsC, cfsC) n ++ drop (n + 1) cfsC\n\ncfGenD :: (Matrix R, Matrix R) -> [Matrix R]\ncfGenD (paths, cfs) = map (fromColumns) $ foldl (\\cfsCC n ->\n let cfs' = head cfsCC\n in (take (n - 1) cfs' ++ cfP (pathsC, cfs') n ++ drop (n + 1) cfs') : cfsCC)\n [toColumns cfs] (reverse [2..(days `div` tdiff)])\n where pathsC = toColumns paths\n\ncfGenR :: (Matrix R, Matrix R) -> [Vector R]\ncfGenR (paths, cfs) = foldl (\\cfs' n -> take (n - 1) cfs' ++ cfP (pathsC, cfs') n ++ drop (n + 1) cfs') cfsC (reverse [2..(days `div` tdiff)])\n where pathsC = toColumns paths\n cfsC = toColumns cfs\n\ntableaux :: Integer -> Integer -> [[R]]\ntableaux rand size =\n map (\\r -> map (sRand r) [0..(days `div` tdiff)]) ss\n where ss :: [Integer]\n ss = seeds rand size\n\nseeds :: Integer -> Integer -> [Integer]\nseeds rand length = take (fromIntegral length) $ map (\\x -> (ceiling (abs x * 100000000000))) (rzs rand)\n\ntableauxM :: Integer -> Integer -> (Matrix R, Matrix R)\ntableauxM rand size = (matrix (days `div` tdiff + 1) paths, matrix (days `div` tdiff + 1) cfs)\n where paths = concat (tableaux rand size)\n cfs = cf paths\n\ncfGen :: (Matrix R, Matrix R) -> Matrix R\ncfGen = fromColumns . tail . cfGenR\n\nnumNonZ :: Matrix R -> Int\nnumNonZ = sum . map (length . (filter (/= 0)) . toList) . toColumns\n\naOptionValue :: Matrix R -> [R]\naOptionValue m = map (\\lst -> if null lst then 0.0 else (exp (-r * (fromIntegral (fst (last lst))) * tstep)) * (snd (last lst)))\n $ map (filter (\\case {(n,x) -> x /= 0}) . zip [1..(days `div` tdiff)] . toList) (toRows m)\n\neOptionValue :: Matrix R -> [R]\neOptionValue = map (* (exp (-r * (fromIntegral (days `div` tdiff + 1)) * tstep))) . cf . toList . last . toColumns\n\ncStarMin :: Integer -> (Matrix R, Matrix R) -> R\ncStarMin p (cf,m) = (/dist) . sum $ map (\\i -> (vs!!(i-1) - vbar) * (qs!!(i-1) - qbar)) [1..(fromIntegral p)]\n where vs = aOptionValue cf\n qs = eOptionValue m\n vbar = sum vs / (fromIntegral (length vs))\n qbar = sum qs / (fromIntegral (length qs))\n dist = sum $ map (\\i -> (qs!!(i-1) - qbar)**2) [1..(fromIntegral p)]\n\nrbar :: Integer -> (Matrix R, Matrix R) -> R -> R\nrbar pass (cf,m) c = (/(fromIntegral pass)) . sum $ map (\\i -> (vs!!(i-1)) - c * ((qs!!(i-1)) - p)) [1..(fromIntegral pass)]\n where vs = aOptionValue cf\n qs = eOptionValue m\n qbar = sum qs / (fromIntegral (length qs))\n\noutput :: Integer -> Integer -> R\noutput rand size = rbar size (cfs, fst m) (cStarMin size (cfs, fst m))\n where cfs = cfGen m\n m = tableauxM rand size\n\ngenxs :: Integer -> [Double]\ngenxs n = map (\\i -> let x = aOptionValue (cfGen (tableauxM i 100))\n in sum x / (fromIntegral (length x)) ) [100..(100+n)]\n", "meta": {"hexsha": "82b0f4df6a1a24dafdf779dd5ad1daf99e01b869", "size": 7036, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Stock.hs", "max_stars_repo_name": "TxmszLou/lsmc-cv", "max_stars_repo_head_hexsha": "0c7e7b3ab2759c66f3e310c5630ee1d4ae4bba94", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-09T05:37:13.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-09T05:37:13.000Z", "max_issues_repo_path": "src/Stock.hs", "max_issues_repo_name": "TxmszLou/lsmc-cv", "max_issues_repo_head_hexsha": "0c7e7b3ab2759c66f3e310c5630ee1d4ae4bba94", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Stock.hs", "max_forks_repo_name": "TxmszLou/lsmc-cv", "max_forks_repo_head_hexsha": "0c7e7b3ab2759c66f3e310c5630ee1d4ae4bba94", "max_forks_repo_licenses": ["BSD-3-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.345971564, "max_line_length": 142, "alphanum_fraction": 0.5619670267, "num_tokens": 2544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.5062466387903992}} {"text": "module Lib where\n\nimport Codec.Picture\nimport System.Directory\nimport System.IO\nimport Data.Array.Repa as R\nimport Data.Array.Repa.Repr.Vector\nimport Data.Array.Repa.FFTW\nimport Data.Complex (Complex(..), realPart, magnitude)\nimport Prelude as P\nimport Control.Monad\n\nnormalize :: Monad m => Array U DIM2 Double -> m (Array D DIM2 Double)\nnormalize arr = do\n minn <- foldAllP min 1 arr\n let arrmin = R.map (+ (-minn)) arr\n maxx <- foldAllP max 0 arrmin\n let arrnorm = R.map (/maxx) arrmin\n return arrnorm\n\nmyfilter tresh v\n | v < tresh = fromIntegral v * 0.6\n | otherwise = 0\n\nrowFilter :: Monad m => Array D DIM1 Double -> m (Array D DIM1 Double)\nrowFilter row = do\n rowComplex <- computeP $ R.map (\\x -> x :+ 0 ) row\n let fftF = fft $ rowComplex\n (Z :. w) = extent fftF\n barier = round (fromIntegral w/2)\n filtered = fromListUnboxed (Z :. w) $ (P.map (myfilter barier) [1..w])\n fftFilt = R.zipWith (*) fftF filtered\n ifftF <- fmap ifft $ computeP fftFilt\n return $ R.map realPart ifftF\n\ngetRow :: Array D DIM2 Double -> Int -> Array D DIM1 Double\ngetRow array n = slice array (Any :. n :. All)\n\nmapRows :: Monad m => (Array D DIM1 Double -> m (Array D DIM1 Double)) -> Array D DIM2 Double -> m (Array U DIM2 Double)\nmapRows func array = do\n let (Z :. w :. h) = extent array\n rows <- mapM (\\num -> do\n let row = getRow array num\n func row) [0,1..(w-1)]\n let hugeRow = toList $ foldr1 append rows\n return $ fromListUnboxed (Z :. w :. h) hugeRow\n\nreconstruct :: Array D DIM2 Double -> Double -> Int -> IO ()\nreconstruct img p orgW = do\n let (Z :. w :. h) = extent img\n angleStep = pi / fromIntegral h\n anglesList = takeWhile ( round $ (x * sin a + y * cos a)/p + orgWNum/2) anglesList\n list_zip = zip list [0..(h-1)]\n in [(a,b) | (a,b) <- list_zip, a >= 0, a < w]\n\n render (x, y) = let\n list = listOfIndicies (x, y)\n pixelList = P.map (\\(p, h) -> img ! (Z :. p :. h)) list\n pixelSum = sum pixelList\n avg = pixelSum / (fromIntegral $ length pixelList)\n in if avg > 0 then avg else 0\n\n let imageIndicies = [orgWNum/(-2)..orgWNum/2-1]\n img' = fromListUnboxed (Z :. orgW :. orgW) (P.map render [(a,b) | a <- imageIndicies , b <- imageIndicies])\n img <- normalize img'\n writePng \"res/reconstruct.png\" $ generateImage (\\x y -> dToPx (img ! (Z :. x :. y))) orgW orgW\n\n\ngetY a p r x = (x, round ((p - (fromIntegral (x - r) * (cos a))) / (sin a)) + r)\ngetX a p r y = (round ((p - (fromIntegral (y - r) * (sin a))) / (cos a)) + r, y)\n\nfilterCoords r (x, y) = ((fromIntegral x - r)**2 + (fromIntegral y - r)**2) < r**2\n\ngetLineAvg :: Double -> Double -> Int -> (Double -> Double -> Int -> Int -> (Int, Int)) -> Array U DIM2 Double -> Double\ngetLineAvg a p w getCoord img =\n let pixelList = P.map (getCoord a p (div w 2)) [0..w-1]\n r = (fromIntegral w) / 2\n pixelList' = filter (filterCoords r) pixelList\n len = length pixelList'\n ret = (sum $ P.map (\\(x, y) -> img ! (Z :. x :. y)) pixelList') / fromIntegral len\n in if isNaN ret then 0 else ret\n\ngetDetectorValue :: Double -> Double -> Int -> Array U DIM2 Double -> Double\ngetDetectorValue a p w img\n | a < pi/4 || a > (3 * pi)/4 = getLineAvg a p w getX img\n | otherwise = getLineAvg a p w getY img\n\nprocessImage :: String -> Int -> Int -> Int -> IO ()\nprocessImage fname nsteps nrays opening' = do \n (w, h, img) <- imageToArray fname \n putStrLn \"Image loaded\"\n let opening = (fromIntegral opening'/ 180) * pi\n r = fromIntegral w/2\n tresh = sin (opening/2) * r\n p = (sin (opening/2) * r) * 2 / (fromIntegral nrays)\n step = pi / fromIntegral nsteps\n angle = takeWhile ( ((fromIntegral v) * p) - tresh) [0..nrays-1]\n rest = P.map (\\a -> P.map (\\p -> getDetectorValue a p w img) listOfP) angle\n trans = fromListUnboxed (Z :. length rest :. length (head rest)) $ concat $ rest\n trans' = transpose trans\n x <- computeUnboxedP trans'\n nofilter <- normalize x\n arraySaveToImage nofilter \"nofilter\"\n result' <- mapRows rowFilter nofilter\n result <- normalize result'\n arraySaveToImage result \"filter\"\n reconstruct result p w\n\ndToPx x\n | x < 0 = PixelYA8 0 255\n | x > 1 = PixelYA8 255 255\n | otherwise = PixelYA8 (round (x * 255)) 255\n\narraySaveToImage :: Array D DIM2 Double -> String -> IO ()\narraySaveToImage arr fname = do\n let (Z :. w :. h) = extent arr\n writePng (\"res/\" P.++ fname P.++ \".png\") $ generateImage (\\x y -> dToPx $ arr ! (Z :. x :. y)) w h\n\nrgbToGrey :: PixelRGB8 -> Double\nrgbToGrey (PixelRGB8 r g b) =\n let rgb = P.zipWith (*) [0.2126, 0.7152, 0.0722] $ P.map (fromIntegral) [r, g, b] \n in fromInteger . round . sum $ rgb :: Double\n\nimageToArray :: String -> IO (Int, Int, Array U DIM2 Double)\nimageToArray fname = do\n Right imgRGB <- readImage fname\n let (imgGray@(Image w h _)) = convertRGB8 imgRGB\n arr = fromFunction (Z :. w :. h) (\\(Z :. x :. y) -> rgbToGrey $ pixelAt imgGray x y)\n img <- computeUnboxedP arr\n return (w, h, img)\n", "meta": {"hexsha": "7b28493df5161fce8d0414338ff7a062ec5afb41", "size": 5388, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "maciejspychala/haskell_gui", "max_stars_repo_head_hexsha": "01cddd4b7745f45b1dfabecf8eb060b9c25f773d", "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": "maciejspychala/haskell_gui", "max_issues_repo_head_hexsha": "01cddd4b7745f45b1dfabecf8eb060b9c25f773d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "maciejspychala/haskell_gui", "max_forks_repo_head_hexsha": "01cddd4b7745f45b1dfabecf8eb060b9c25f773d", "max_forks_repo_licenses": ["BSD-3-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.3284671533, "max_line_length": 120, "alphanum_fraction": 0.5926132146, "num_tokens": 1738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5062436093602598}} {"text": "{-# LANGUAGE DoAndIfThenElse #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns #-}\n{- # OPTIONS_GHC -ddump-simpl # -}\nmodule Img where\n\nimport Data.Complex\nimport Data.Colour.SRGB\nimport qualified Data.ByteString.Lazy as BS\n\nimport Codec.Picture\n\nimport RNA\n\n-- Functional evaluator\n\n-- more efficient than Data.Fixed.fmod (I believe)\nforeign import ccall unsafe \"math.h fmod\" c_fmod :: Double -> Double -> Double\n\nfmod :: Double -> Double -> Double\nx `fmod` y =\n let z = c_fmod x y in\n if z < 0 then z + y else z\n\ndata C = C {-# UNPACK #-} !Double {-# UNPACK #-} !Double {-# UNPACK #-} !Double\n\ntype Img = Complex Double -> Maybe C\ntype Pattern = Complex Double -> C\n\ntoImg :: RNA -> Img\ntoImg r pos =\n if magnitude pos > 1.0\n then Nothing\n else Just (i pos)\n where\n i = go r\n\ntween :: Double -> C -> C -> C\ntween x (C a1 b1 c1) (C a2 b2 c2) = C\n ((1 - x) * a1 + x * a2)\n ((1 - x) * b1 + x * b2)\n ((1 - x) * c1 + x * c2)\n\ngo :: RNA -> Pattern\ngo _ (!_pos) | False = undefined\n\ngo (Solid color) _pos = C r g b\n where\n RGB r g b = color\n\ngo Blend{} _pos = error \"blend\"\n\ngo (Checker x r1 r2) pos = do\n let !(tmpx :+ tmpy) = realToFrac x * ((1.0 :+ 0.0) + pos)\n if abs ((tmpx + 1) `fmod` 2 - 1) + abs (tmpy `fmod` 2 - 1) < 1\n then i2 pos\n else i1 pos\n where\n i1 = go r1\n i2 = go r2\n\ngo (Rotate x r1) pos = do\n let p' = phase pos + x\n let pos' = mkPolar (magnitude pos) p'\n i1 pos'\n where\n i1 = go r1\n\ngo (Invert r1) pos = do\n let mag = magnitude pos\n let mag' = 1 - mag\n let pos' = mkPolar mag' (phase pos)\n i1 pos'\n where\n i1 = go r1\n\ngo (Swirl x r1) pos = do\n let mag = magnitude pos\n let phase' = phase pos + (1.0 - mag) * x\n let pos' = mkPolar mag phase'\n i1 pos'\n where\n i1 = go r1\n\ngo (Dilated r r1) pos = do\n let p = phase pos\n let mag = magnitude pos\n let phase' = p + 1/fromIntegral r * sin (p * fromIntegral r)\n let pos' = mkPolar mag phase'\n i1 pos'\n where\n i1 = go r1\n\n\ngo (Rays r r1 r2) pos =\n if (phase pos / pi * fromIntegral r + 0.5) `fmod` 2 < 1\n then i2 pos\n else i1 pos\n where\n i1 = go r1\n i2 = go r2\n\ngo (Gradient r1 r2) pos =\n tween (magnitude pos) (i1 pos) (i2 pos)\n where\n i1 = go r1\n i2 = go r2\n\ngo (Ontop x r1 r2) pos = do\n let pos1 = realToFrac (1/x) * pos\n if magnitude pos < x\n then i1 pos1 else i2 pos\n where\n i1 = go r1\n i2 = go r2\n\n\n\nimg2Png :: Img -> BS.ByteString\nimg2Png i = encodePng $ generateImage colorAt w h\n where\n w = 1000\n h = 1000\n colorAt :: Int -> Int -> PixelRGBA8\n colorAt x y = do\n let x' = 2 * fromIntegral x / fromIntegral w - 1\n let y' = 2 * fromIntegral y / fromIntegral h - 1\n case i (y' :+ x') of\n Nothing -> PixelRGBA8 0 0 0 0\n Just (C r g b) -> PixelRGBA8 (clamp r) (clamp g) (clamp b) 255\n\n clamp :: Double -> Pixel8\n clamp = fromIntegral . max (0::Int) . min 255 . round . (* 256)\n", "meta": {"hexsha": "fb301da5738b617c4f1180ee61e7d56e3d63ef48", "size": 2958, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Img.hs", "max_stars_repo_name": "nomeata/kaleidogen", "max_stars_repo_head_hexsha": "eaf4ec0113c1ff7c218e3f3fcd718af0297584db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2018-06-21T03:50:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T15:41:14.000Z", "max_issues_repo_path": "src/Img.hs", "max_issues_repo_name": "nomeata/kaleidogen", "max_issues_repo_head_hexsha": "eaf4ec0113c1ff7c218e3f3fcd718af0297584db", "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/Img.hs", "max_forks_repo_name": "nomeata/kaleidogen", "max_forks_repo_head_hexsha": "eaf4ec0113c1ff7c218e3f3fcd718af0297584db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-05T15:29:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T09:54:10.000Z", "avg_line_length": 22.0746268657, "max_line_length": 79, "alphanum_fraction": 0.5757268425, "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.5062436052934678}} {"text": "{-# LANGUAGE Rank2Types, FlexibleContexts #-}\nmodule Numeric.AD.Lagrangian.Internal where\nimport Numeric.Optimization.Algorithms.HagerZhang05\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Storable as S\nimport Numeric.AD\nimport GHC.IO (unsafePerformIO)\nimport Numeric.AD.Types\nimport Numeric.AD.Internal.Classes\nimport Numeric.LinearAlgebra.Algorithms\nimport qualified Data.Packed.Vector as V\nimport qualified Data.Packed.Matrix as M\nimport Numeric.AD.Internal.Tower\n\ninfixr 1 <=>\n-- | Build a 'Constraint' from a function and a constant\n(<=>) :: (forall s r. (Mode s, Mode r) => [AD2 s r a] -> AD2 s r a) -> a -> Constraint a\ng <=> c = (FU g,c)\n\n-- | A constraint of the form @g(x, y, ...) = c@. See '<=>' for constructing a 'Constraint'.\ntype Constraint a = (FU a, a)\n\ntype AD2 s r a = AD s (AD r a)\n\n-- | A newtype wrapper for working with the rank 2 types constraint functions.\nnewtype FU a = FU {unFU :: forall s r. (Mode s, Mode r) => [AD2 s r a] -> AD2 s r a}\n\n-- | This is the lagrangian multiplier solver. It is assumed that the\n-- objective function and all of the constraints take in the\n-- same amount of arguments.\nminimize :: Double\n -> (forall s r. (Mode s, Mode r) => [AD2 s r Double] -> AD2 s r Double)\n -- ^ The function to minimize\n -> [Constraint Double]\n -- ^ The constraints as pairs @g \\<=\\> c@ which represent equations\n -- of the form @g(x, y, ...) = c@\n -> Int\n -- ^ The arity of the objective function which should equal the arity of\n -- the constraints.\n -> Either (Result, Statistics) (S.Vector Double, S.Vector Double)\n -- ^ Either an explanation of why the gradient descent failed or a pair\n -- containing the arguments at the minimum and the lagrange multipliers\nminimize tolerance toMin constraints argCount = result where\n -- The function to minimize for the langrangian is the squared gradient\n obj argsAndLams =\n squaredGrad (lagrangian toMin constraints argCount) argsAndLams\n\n constraintCount = length constraints\n\n -- perhaps this should be exposed\n guess = U.replicate (argCount + constraintCount) (1.0 :: Double)\n\n result = case unsafePerformIO $\n optimize\n (defaultParameters { printFinal = False })\n tolerance\n guess\n (VFunction (lowerFU obj . U.toList))\n (VGradient (U.fromList . grad obj . U.toList))\n Nothing of\n (vs, ToleranceStatisfied, _) -> Right (S.take argCount vs,\n S.drop argCount vs)\n (_, x, y) -> Left (x, y)\n\n-- | Finding the maximum is the same as the minimum with the objective function inverted\nmaximize :: Double\n -> (forall s r. (Mode s, Mode r) => [AD2 s r Double] -> AD2 s r Double)\n -- ^ The function to maximize\n -> [Constraint Double]\n -- ^ The constraints as pairs @g \\<=\\> c@ which represent equations\n -- of the form @g(x, y, ...) = c@\n -> Int\n -- ^ The arity of the objective function which should equal the arity of\n -- the constraints.\n -> Either (Result, Statistics) (S.Vector Double, S.Vector Double)\n -- ^ Either an explanation of why the gradient descent failed or a pair\n -- containing the arguments at the minimum and the lagrange multipliers\nmaximize tolerance toMax constraints argCount =\n minimize tolerance (negate1 . toMax) constraints argCount\n\nlagrangian :: (Num a, Mode s, Mode r)\n => (forall s r. (Mode s, Mode r) => [AD2 s r a] -> AD2 s r a)\n -> [Constraint a]\n -> Int\n -> [AD2 s r a]\n -> AD2 s r a\nlagrangian f constraints argCount argsAndLams = result where\n args = take argCount argsAndLams\n lams = drop argCount argsAndLams\n\n -- g(x, y, ...) = c <=> g(x, y, ...) - c = 0\n appliedConstraints = fmap (\\(FU f, c) -> f args - (auto . auto) c) constraints\n\n -- L(x, y, ..., lam0, ...) = f(x, y, ...) + lam0 * (g0 - c0) ...\n result = f args + (sum . zipWith (*) lams $ appliedConstraints)\n\nsquaredGrad :: Num a\n => (forall s. Mode s => [AD s a] -> AD s a)\n -> [a] -> a\nsquaredGrad f vs = sum . fmap (\\x -> x*x) . grad f $ vs\n\n-- | WARNING. Experimental.\n-- This is not a true feasibility test for the function. I am not sure\n-- exactly how to implement that. This just checks the feasiblility at a point.\n-- If this ever returns false, 'solve' can fail.\nfeasible :: (forall s r. (Mode s, Mode r) => [AD2 s r Double] -> AD2 s r Double)\n -> [Constraint Double]\n -> [Double]\n -> Bool\nfeasible toMin constraints points = result where\n obj argsAndLams =\n squaredGrad (lagrangian toMin constraints $ length points) argsAndLams\n\n hessianMatrix = M.fromLists . hessian obj $ points\n\n -- make sure all of the eigenvalues are positive\n result = all (>0) . V.toList . eigenvaluesSH $ hessianMatrix\n\n\n", "meta": {"hexsha": "c5be03a462c03d8c76873763c5422a6ef8370a6e", "size": 5029, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/AD/Lagrangian/Internal.hs", "max_stars_repo_name": "ekmett/lagrangian", "max_stars_repo_head_hexsha": "bdda585330687bda9c06d405b70328a215efa5b7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-11-08T11:50:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T02:46:42.000Z", "max_issues_repo_path": "src/Numeric/AD/Lagrangian/Internal.hs", "max_issues_repo_name": "ekmett/lagrangian", "max_issues_repo_head_hexsha": "bdda585330687bda9c06d405b70328a215efa5b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/AD/Lagrangian/Internal.hs", "max_forks_repo_name": "ekmett/lagrangian", "max_forks_repo_head_hexsha": "bdda585330687bda9c06d405b70328a215efa5b7", "max_forks_repo_licenses": ["BSD-3-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.9083333333, "max_line_length": 92, "alphanum_fraction": 0.6172201233, "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5058653653174139}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RebindableSyntax #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n-- |\n-- Module : Data.Array.Accelerate.Data.Complex\n-- Copyright : [2015..2017] Trevor L. McDonell\n-- License : BSD3\n--\n-- Maintainer : Trevor L. McDonell \n-- Stability : experimental\n-- Portability : non-portable (GHC extensions)\n--\n-- Complex numbers, stored in the usual C-style array-of-struct representation,\n-- for easy interoperability.\n--\nmodule Data.Array.Accelerate.Data.Complex (\n\n -- * Rectangular from\n Complex(..),\n real,\n imag,\n\n -- * Polar form\n mkPolar,\n cis,\n polar,\n magnitude,\n phase,\n\n -- * Conjugate\n conjugate,\n\n) where\n\nimport Data.Array.Accelerate.Array.Sugar\nimport Data.Array.Accelerate.Classes\nimport Data.Array.Accelerate.Data.Functor\nimport Data.Array.Accelerate.Prelude\nimport Data.Array.Accelerate.Product\nimport Data.Array.Accelerate.Smart\nimport Data.Array.Accelerate.Type\n\nimport Prelude ( ($) )\nimport Data.Complex ( Complex(..) )\nimport qualified Data.Complex as C\nimport qualified Prelude as P\n\n\n-- Use an array-of-structs representation for complex numbers. This matches the\n-- standard C-style layout, but means that we can define instances only at\n-- specific types (not for any type 'a') as we can only have vectors of\n-- primitive type.\n--\n\ninstance Elt (Complex Half) where\n type EltRepr (Complex Half) = V2 Half\n {-# INLINE eltType #-}\n {-# INLINE [1] toElt #-}\n {-# INLINE [1] fromElt #-}\n eltType = TypeRscalar scalarType\n toElt (V2 r i) = r :+ i\n fromElt (r :+ i) = V2 r i\n\ninstance Elt (Complex Float) where\n type EltRepr (Complex Float) = V2 Float\n {-# INLINE eltType #-}\n {-# INLINE [1] toElt #-}\n {-# INLINE [1] fromElt #-}\n eltType = TypeRscalar scalarType\n toElt (V2 r i) = r :+ i\n fromElt (r :+ i) = V2 r i\n\ninstance Elt (Complex Double) where\n type EltRepr (Complex Double) = V2 Double\n {-# INLINE eltType #-}\n {-# INLINE [1] toElt #-}\n {-# INLINE [1] fromElt #-}\n eltType = TypeRscalar scalarType\n toElt (V2 r i) = r :+ i\n fromElt (r :+ i) = V2 r i\n\ninstance Elt (Complex CFloat) where\n type EltRepr (Complex CFloat) = V2 Float\n {-# INLINE eltType #-}\n {-# INLINE [1] toElt #-}\n {-# INLINE [1] fromElt #-}\n eltType = TypeRscalar scalarType\n toElt (V2 r i) = CFloat r :+ CFloat i\n fromElt (CFloat r :+ CFloat i) = V2 r i\n\ninstance Elt (Complex CDouble) where\n type EltRepr (Complex CDouble) = V2 Double\n {-# INLINE eltType #-}\n {-# INLINE [1] toElt #-}\n {-# INLINE [1] fromElt #-}\n eltType = TypeRscalar scalarType\n toElt (V2 r i) = CDouble r :+ CDouble i\n fromElt (CDouble r :+ CDouble i) = V2 r i\n\ninstance cst a => IsProduct cst (Complex a) where\n type ProdRepr (Complex a) = ProdRepr (a,a)\n fromProd (r :+ i) = fromProd @cst (r,i)\n toProd p = let (r,i) = toProd @cst p in (r :+ i)\n prod = prod @cst @(a,a)\n\ninstance (Lift Exp a, Elt (Plain a), Elt (Complex (Plain a))) => Lift Exp (Complex a) where\n type Plain (Complex a) = Complex (Plain a)\n lift (r :+ i) = Exp $ Tuple (NilTup `SnocTup` lift r `SnocTup` lift i)\n\ninstance (Elt a, Elt (Complex a)) => Unlift Exp (Complex (Exp a)) where\n unlift e\n = let r = Exp $ SuccTupIdx ZeroTupIdx `Prj` e\n i = Exp $ ZeroTupIdx `Prj` e\n in\n r :+ i\n\n\ninstance (Eq a, Elt (Complex a)) => Eq (Complex a) where\n x == y = let r1 :+ c1 = unlift x\n r2 :+ c2 = unlift y\n in r1 == r2 && c1 == c2\n x /= y = let r1 :+ c1 = unlift x\n r2 :+ c2 = unlift y\n in r1 /= r2 || c1 /= c2\n\ninstance (RealFloat a, Elt (Complex a)) => P.Num (Exp (Complex a)) where\n (+) = lift2 ((+) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n (-) = lift2 ((-) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n (*) = lift2 ((*) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n negate = lift1 (negate :: Complex (Exp a) -> Complex (Exp a))\n signum z = if z == 0\n then z\n else let x :+ y = unlift z\n r = magnitude z\n in\n lift (x/r :+ y/r)\n abs z = lift (magnitude z :+ 0)\n fromInteger n = lift (fromInteger n :+ 0)\n\ninstance (RealFloat a, Elt (Complex a)) => P.Fractional (Exp (Complex a)) where\n fromRational x = lift (fromRational x :+ 0)\n z / z' = lift ((x*x''+y*y'') / d :+ (y*x''-x*y'') / d)\n where\n x :+ y = unlift z\n x' :+ y' = unlift z'\n --\n x'' = scaleFloat k x'\n y'' = scaleFloat k y'\n k = - max (exponent x') (exponent y')\n d = x'*x'' + y'*y''\n\ninstance (RealFloat a, Elt (Complex a)) => P.Floating (Exp (Complex a)) where\n pi = lift $ pi :+ 0\n\n exp (unlift -> x :+ y) = let expx = exp x\n in complex $ expx * cos y :+ expx * sin y\n\n log z = lift $ log (magnitude z) :+ phase z\n\n sqrt z@(unlift -> x :+ y) =\n if z == 0\n then 0\n else lift $ u :+ (y < 0 ? (-v, v))\n where\n (u,v) = unlift (x < 0 ? (lift (v',u'), lift (u',v')))\n v' = abs y / (u'*2)\n u' = sqrt ((magnitude z + abs x) / 2)\n\n x ** y =\n if y == 0 then 1 else\n if x == 0 then if exp_r > 0 then 0 else\n if exp_r < 0 then lift (inf :+ 0)\n else lift (nan :+ nan)\n else if isInfinite r || isInfinite i\n then if exp_r > 0 then lift (inf :+ 0) else\n if exp_r < 0 then 0\n else lift (nan :+ nan)\n else exp (log x * y)\n where\n r :+ i = unlift x\n exp_r :+ _ = unlift y\n --\n inf = 1 / 0\n nan = 0 / 0\n\n sin (unlift -> x :+ y) = complex $ sin x * cosh y :+ cos x * sinh y\n cos (unlift -> x :+ y) = complex $ cos x * cosh y :+ (- sin x * sinh y)\n tan (unlift -> x :+ y) = (complex $ sinx*coshy :+ cosx*sinhy) / (complex $ cosx*coshy :+ (-sinx*sinhy))\n where\n sinx = sin x\n cosx = cos x\n sinhy = sinh y\n coshy = cosh y\n\n sinh (unlift -> x :+ y) = complex $ cos y * sinh x :+ sin y * cosh x\n cosh (unlift -> x :+ y) = complex $ cos y * cosh x :+ sin y * sinh x\n tanh (unlift -> x :+ y) = (complex $ cosy*sinhx :+ siny*coshx) / (complex $ cosy*coshx :+ siny*sinhx)\n where\n siny = sin y\n cosy = cos y\n sinhx = sinh x\n coshx = cosh x\n\n asin z@(unlift -> x :+ y) = complex $ y' :+ (-x')\n where\n x' :+ y' = unlift $ log ((complex ((-y):+x)) + sqrt (1 - z*z))\n\n acos z = complex $ y'' :+ (-x'')\n where\n x'' :+ y'' = unlift $ log (z + (complex ((-y') :+ x')))\n x' :+ y' = unlift $ sqrt (1 - z*z)\n\n atan z@(unlift -> x :+ y) = complex $ y' :+ (-x')\n where\n x' :+ y' = unlift $ log ((complex ((1-y):+x)) / sqrt (1+z*z))\n\n asinh z = log (z + sqrt (1+z*z))\n acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1)))\n atanh z = 0.5 * log ((1.0+z) / (1.0-z))\n\n\ninstance (FromIntegral a b, Num b, Elt (Complex b)) => FromIntegral a (Complex b) where\n fromIntegral x = lift (fromIntegral x :+ 0)\n\n-- | @since 1.2.0.0\ninstance Functor Complex where\n fmap f (unlift -> r :+ i) = lift (f r :+ f i)\n\n\n-- Helper function to fix the types for lift (ugh)\n--\ncomplex :: (Elt a, Elt (Complex a)) => Complex (Exp a) -> Exp (Complex a)\ncomplex = lift\n\n-- | The non-negative magnitude of a complex number\n--\nmagnitude :: (RealFloat a, Elt (Complex a)) => Exp (Complex a) -> Exp a\n-- magnitude (unlift -> r :+ i) = sqrt (r*r + i*i)\nmagnitude (unlift -> r :+ i) = scaleFloat k (sqrt (sqr (scaleFloat mk r) + sqr (scaleFloat mk i)))\n where\n k = max (exponent r) (exponent i)\n mk = -k\n sqr z = z * z\n\n-- | The phase of a complex number, in the range @(-'pi', 'pi']@. If the\n-- magnitude is zero, then so is the phase.\n--\nphase :: (RealFloat a, Elt (Complex a)) => Exp (Complex a) -> Exp a\nphase z@(unlift -> r :+ i) =\n if z == 0\n then 0\n else atan2 i r\n\n-- | The function 'polar' takes a complex number and returns a (magnitude,\n-- phase) pair in canonical form: the magnitude is non-negative, and the phase\n-- in the range @(-'pi', 'pi']@; if the magnitude is zero, then so is the phase.\n--\npolar :: (RealFloat a, Elt (Complex a)) => Exp (Complex a) -> Exp (a,a)\npolar z = lift (magnitude z, phase z)\n\n-- | Form a complex number from polar components of magnitude and phase.\n--\n#if __GLASGOW_HASKELL__ <= 708\nmkPolar :: forall a. (RealFloat a, Elt (Complex a)) => Exp a -> Exp a -> Exp (Complex a)\n#else\nmkPolar :: forall a. (Floating a, Elt (Complex a)) => Exp a -> Exp a -> Exp (Complex a)\n#endif\nmkPolar = lift2 (C.mkPolar :: Exp a -> Exp a -> Complex (Exp a))\n\n-- | @'cis' t@ is a complex value with magnitude @1@ and phase @t@ (modulo\n-- @2*'pi'@).\n--\n#if __GLASGOW_HASKELL__ <= 708\ncis :: forall a. (RealFloat a, Elt (Complex a)) => Exp a -> Exp (Complex a)\n#else\ncis :: forall a. (Floating a, Elt (Complex a)) => Exp a -> Exp (Complex a)\n#endif\ncis = lift1 (C.cis :: Exp a -> Complex (Exp a))\n\n-- | Return the real part of a complex number\n--\nreal :: (Elt a, Elt (Complex a)) => Exp (Complex a) -> Exp a\nreal (unlift -> r :+ _) = r\n\n-- | Return the imaginary part of a complex number\n--\nimag :: (Elt a, Elt (Complex a)) => Exp (Complex a) -> Exp a\nimag (unlift -> _ :+ i) = i\n\n-- | Return the complex conjugate of a complex number, defined as\n--\n-- > conjugate(Z) = X - iY\n--\nconjugate :: (Num a, Elt (Complex a)) => Exp (Complex a) -> Exp (Complex a)\nconjugate z = lift $ real z :+ (- imag z)\n\n", "meta": {"hexsha": "8b9ef7930ab87ce3d695748e67376f45e57827a0", "size": 10344, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Array/Accelerate/Data/Complex.hs", "max_stars_repo_name": "ocramz/accelerate", "max_stars_repo_head_hexsha": "0a7cb36a9abaaf1c9b36995519ab2c2f2c7ae32f", "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/Array/Accelerate/Data/Complex.hs", "max_issues_repo_name": "ocramz/accelerate", "max_issues_repo_head_hexsha": "0a7cb36a9abaaf1c9b36995519ab2c2f2c7ae32f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Array/Accelerate/Data/Complex.hs", "max_forks_repo_name": "ocramz/accelerate", "max_forks_repo_head_hexsha": "0a7cb36a9abaaf1c9b36995519ab2c2f2c7ae32f", "max_forks_repo_licenses": ["BSD-3-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.6938110749, "max_line_length": 106, "alphanum_fraction": 0.535962877, "num_tokens": 3335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5055797023177423}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ViewPatterns #-}\n-- |\n-- Module : Statistics.Quantile\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Functions for approximating quantiles, i.e. points taken at regular\n-- intervals from the cumulative distribution function of a random\n-- variable.\n--\n-- The number of quantiles is described below by the variable /q/, so\n-- with /q/=4, a 4-quantile (also known as a /quartile/) has 4\n-- intervals, and contains 5 points. The parameter /k/ describes the\n-- desired point, where 0 ≤ /k/ ≤ /q/.\n\nmodule Statistics.Quantile\n (\n -- * Quantile estimation functions\n -- $cont_quantiles\n ContParam(..)\n , Default(..)\n , quantile\n , quantiles\n , quantilesVec\n -- ** Parameters for the continuous sample method\n , cadpw\n , hazen\n , spss\n , s\n , medianUnbiased\n , normalUnbiased\n -- * Other algorithms\n , weightedAvg\n -- * Median & other specializations\n , median\n , mad\n , midspread\n -- * Deprecated\n , continuousBy\n -- * References\n -- $references\n ) where\n\nimport Data.Binary (Binary)\nimport Data.Aeson (ToJSON,FromJSON)\nimport Data.Data (Data,Typeable)\nimport Data.Default.Class\nimport Data.Functor\nimport qualified Data.Foldable as F\nimport Data.Vector.Generic ((!))\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Storable as S\nimport GHC.Generics (Generic)\n\nimport Statistics.Function (partialSort)\n\n\n----------------------------------------------------------------\n-- Quantile estimation\n----------------------------------------------------------------\n\n-- | O(/n/·log /n/). Estimate the /k/th /q/-quantile of a sample,\n-- using the weighted average method. Up to rounding errors it's same\n-- as @quantile s@.\n--\n-- The following properties should hold otherwise an error will be thrown.\n--\n-- * the length of the input is greater than @0@\n--\n-- * the input does not contain @NaN@\n--\n-- * k ≥ 0 and k ≤ q\nweightedAvg :: G.Vector v Double =>\n Int -- ^ /k/, the desired quantile.\n -> Int -- ^ /q/, the number of quantiles.\n -> v Double -- ^ /x/, the sample data.\n -> Double\nweightedAvg k q x\n | G.any isNaN x = modErr \"weightedAvg\" \"Sample contains NaNs\"\n | n == 0 = modErr \"weightedAvg\" \"Sample is empty\"\n | n == 1 = G.head x\n | q < 2 = modErr \"weightedAvg\" \"At least 2 quantiles is needed\"\n | k == q = G.maximum x\n | k >= 0 || k < q = xj + g * (xj1 - xj)\n | otherwise = modErr \"weightedAvg\" \"Wrong quantile number\"\n where\n j = floor idx\n idx = fromIntegral (n - 1) * fromIntegral k / fromIntegral q\n g = idx - fromIntegral j\n xj = sx ! j\n xj1 = sx ! (j+1)\n sx = partialSort (j+2) x\n n = G.length x\n{-# SPECIALIZE weightedAvg :: Int -> Int -> U.Vector Double -> Double #-}\n{-# SPECIALIZE weightedAvg :: Int -> Int -> V.Vector Double -> Double #-}\n{-# SPECIALIZE weightedAvg :: Int -> Int -> S.Vector Double -> Double #-}\n\n\n----------------------------------------------------------------\n-- Quantiles continuous algorithm\n----------------------------------------------------------------\n\n-- $cont_quantiles\n--\n-- Below is family of functions which use same algorithm for estimation\n-- of sample quantiles. It approximates empirical CDF as continuous\n-- piecewise function which interpolates linearly between points\n-- \\((X_k,p_k)\\) where \\(X_k\\) is k-th order statistics (k-th smallest\n-- element) and \\(p_k\\) is probability corresponding to\n-- it. 'ContParam' determines how \\(p_k\\) is chosen. For more detailed\n-- explanation see [Hyndman1996].\n--\n-- This is the method used by most statistical software, such as R,\n-- Mathematica, SPSS, and S.\n\n\n-- | Parameters /α/ and /β/ to the 'continuousBy' function. Exact\n-- meaning of parameters is described in [Hyndman1996] in section\n-- \\\"Piecewise linear functions\\\"\ndata ContParam = ContParam {-# UNPACK #-} !Double {-# UNPACK #-} !Double\n deriving (Show,Eq,Ord,Data,Typeable,Generic)\n\n-- | We use 's' as default value which is same as R's default.\ninstance Default ContParam where\n def = s\n\ninstance Binary ContParam\ninstance ToJSON ContParam\ninstance FromJSON ContParam\n\n-- | O(/n/·log /n/). Estimate the /k/th /q/-quantile of a sample /x/,\n-- using the continuous sample method with the given parameters.\n--\n-- The following properties should hold, otherwise an error will be thrown.\n--\n-- * input sample must be nonempty\n--\n-- * the input does not contain @NaN@\n--\n-- * 0 ≤ k ≤ q\nquantile :: G.Vector v Double\n => ContParam -- ^ Parameters /α/ and /β/.\n -> Int -- ^ /k/, the desired quantile.\n -> Int -- ^ /q/, the number of quantiles.\n -> v Double -- ^ /x/, the sample data.\n -> Double\nquantile param q nQ xs\n | nQ < 2 = modErr \"continuousBy\" \"At least 2 quantiles is needed\"\n | badQ nQ q = modErr \"continuousBy\" \"Wrong quantile number\"\n | G.any isNaN xs = modErr \"continuousBy\" \"Sample contains NaNs\"\n | otherwise = estimateQuantile sortedXs pk\n where\n pk = toPk param n q nQ\n sortedXs = psort xs $ floor pk + 1\n n = G.length xs\n{-# INLINABLE quantile #-}\n{-# SPECIALIZE\n quantile :: ContParam -> Int -> Int -> U.Vector Double -> Double #-}\n{-# SPECIALIZE\n quantile :: ContParam -> Int -> Int -> V.Vector Double -> Double #-}\n{-# SPECIALIZE\n quantile :: ContParam -> Int -> Int -> S.Vector Double -> Double #-}\n\n-- | O(/k·n/·log /n/). Estimate set of the /k/th /q/-quantile of a\n-- sample /x/, using the continuous sample method with the given\n-- parameters. This is faster than calling quantile repeatedly since\n-- sample should be sorted only once\n--\n-- The following properties should hold, otherwise an error will be thrown.\n--\n-- * input sample must be nonempty\n--\n-- * the input does not contain @NaN@\n--\n-- * for every k in set of quantiles 0 ≤ k ≤ q\nquantiles :: (G.Vector v Double, F.Foldable f, Functor f)\n => ContParam\n -> f Int\n -> Int\n -> v Double\n -> f Double\nquantiles param qs nQ xs\n | nQ < 2 = modErr \"quantiles\" \"At least 2 quantiles is needed\"\n | F.any (badQ nQ) qs = modErr \"quantiles\" \"Wrong quantile number\"\n | G.any isNaN xs = modErr \"quantiles\" \"Sample contains NaNs\"\n -- Doesn't matter what we put into empty container\n | fnull qs = 0 <$ qs\n | otherwise = fmap (estimateQuantile sortedXs) ks'\n where\n ks' = fmap (\\q -> toPk param n q nQ) qs\n sortedXs = psort xs $ floor (F.maximum ks') + 1\n n = G.length xs\n{-# INLINABLE quantiles #-}\n{-# SPECIALIZE quantiles\n :: (Functor f, F.Foldable f) => ContParam -> f Int -> Int -> V.Vector Double -> f Double #-}\n{-# SPECIALIZE quantiles\n :: (Functor f, F.Foldable f) => ContParam -> f Int -> Int -> U.Vector Double -> f Double #-}\n{-# SPECIALIZE quantiles\n :: (Functor f, F.Foldable f) => ContParam -> f Int -> Int -> S.Vector Double -> f Double #-}\n\n-- COMPAT\nfnull :: F.Foldable f => f a -> Bool\n#if !MIN_VERSION_base(4,8,0)\nfnull = F.foldr (\\_ _ -> False) True\n#else\nfnull = null\n#endif\n\n-- | O(/k·n/·log /n/). Same as quantiles but uses 'G.Vector' container\n-- instead of 'Foldable' one.\nquantilesVec :: (G.Vector v Double, G.Vector v Int)\n => ContParam\n -> v Int\n -> Int\n -> v Double\n -> v Double\nquantilesVec param qs nQ xs\n | nQ < 2 = modErr \"quantilesVec\" \"At least 2 quantiles is needed\"\n | G.any (badQ nQ) qs = modErr \"quantilesVec\" \"Wrong quantile number\"\n | G.any isNaN xs = modErr \"quantilesVec\" \"Sample contains NaNs\"\n | G.null qs = G.empty\n | otherwise = G.map (estimateQuantile sortedXs) ks'\n where\n ks' = G.map (\\q -> toPk param n q nQ) qs\n sortedXs = psort xs $ floor (G.maximum ks') + 1\n n = G.length xs\n{-# INLINABLE quantilesVec #-}\n{-# SPECIALIZE quantilesVec\n :: ContParam -> V.Vector Int -> Int -> V.Vector Double -> V.Vector Double #-}\n{-# SPECIALIZE quantilesVec\n :: ContParam -> U.Vector Int -> Int -> U.Vector Double -> U.Vector Double #-}\n{-# SPECIALIZE quantilesVec\n :: ContParam -> S.Vector Int -> Int -> S.Vector Double -> S.Vector Double #-}\n\n\n-- Returns True if quantile number is out of range\nbadQ :: Int -> Int -> Bool\nbadQ nQ q = q < 0 || q > nQ\n\n-- Obtain k from equation for p_k [Hyndman1996] p.363. Note that\n-- equation defines p_k for integer k but we calculate it as real\n-- value and will use fractional part for linear interpolation. This\n-- is correct since equation is linear.\ntoPk\n :: ContParam\n -> Int -- ^ /n/ number of elements\n -> Int -- ^ /k/, the desired quantile.\n -> Int -- ^ /q/, the number of quantiles.\n -> Double\ntoPk (ContParam a b) (fromIntegral -> n) q nQ\n = a + p * (n + 1 - a - b)\n where\n p = fromIntegral q / fromIntegral nQ\n\n-- Estimate quantile for given k (including fractional part)\nestimateQuantile :: G.Vector v Double => v Double -> Double -> Double\n{-# INLINE estimateQuantile #-}\nestimateQuantile sortedXs k'\n = (1-g) * item (k-1) + g * item k\n where\n (k,g) = properFraction k'\n item = (sortedXs !) . clamp\n --\n clamp = max 0 . min (n - 1)\n n = G.length sortedXs\n\npsort :: G.Vector v Double => v Double -> Int -> v Double\npsort xs k = partialSort (max 0 $ min (G.length xs - 1) k) xs\n{-# INLINE psort #-}\n\n\n-- | California Department of Public Works definition, /α/=0, /β/=1.\n-- Gives a linear interpolation of the empirical CDF. This\n-- corresponds to method 4 in R and Mathematica.\ncadpw :: ContParam\ncadpw = ContParam 0 1\n\n-- | Hazen's definition, /α/=0.5, /β/=0.5. This is claimed to be\n-- popular among hydrologists. This corresponds to method 5 in R and\n-- Mathematica.\nhazen :: ContParam\nhazen = ContParam 0.5 0.5\n\n-- | Definition used by the SPSS statistics application, with /α/=0,\n-- /β/=0 (also known as Weibull's definition). This corresponds to\n-- method 6 in R and Mathematica.\nspss :: ContParam\nspss = ContParam 0 0\n\n-- | Definition used by the S statistics application, with /α/=1,\n-- /β/=1. The interpolation points divide the sample range into @n-1@\n-- intervals. This corresponds to method 7 in R and Mathematica and\n-- is default in R.\ns :: ContParam\ns = ContParam 1 1\n\n-- | Median unbiased definition, /α/=1\\/3, /β/=1\\/3. The resulting\n-- quantile estimates are approximately median unbiased regardless of\n-- the distribution of /x/. This corresponds to method 8 in R and\n-- Mathematica.\nmedianUnbiased :: ContParam\nmedianUnbiased = ContParam third third\n where third = 1/3\n\n-- | Normal unbiased definition, /α/=3\\/8, /β/=3\\/8. An approximately\n-- unbiased estimate if the empirical distribution approximates the\n-- normal distribution. This corresponds to method 9 in R and\n-- Mathematica.\nnormalUnbiased :: ContParam\nnormalUnbiased = ContParam ta ta\n where ta = 3/8\n\nmodErr :: String -> String -> a\nmodErr f err = error $ \"Statistics.Quantile.\" ++ f ++ \": \" ++ err\n\n\n----------------------------------------------------------------\n-- Specializations\n----------------------------------------------------------------\n\n-- | O(/n/·log /n/) Estimate median of sample\nmedian :: G.Vector v Double\n => ContParam -- ^ Parameters /α/ and /β/.\n -> v Double -- ^ /x/, the sample data.\n -> Double\n{-# INLINE median #-}\nmedian p = quantile p 1 2\n\n-- | O(/n/·log /n/). Estimate the range between /q/-quantiles 1 and\n-- /q/-1 of a sample /x/, using the continuous sample method with the\n-- given parameters.\n--\n-- For instance, the interquartile range (IQR) can be estimated as\n-- follows:\n--\n-- > midspread medianUnbiased 4 (U.fromList [1,1,2,2,3])\n-- > ==> 1.333333\nmidspread :: G.Vector v Double =>\n ContParam -- ^ Parameters /α/ and /β/.\n -> Int -- ^ /q/, the number of quantiles.\n -> v Double -- ^ /x/, the sample data.\n -> Double\nmidspread param k x\n | G.any isNaN x = modErr \"midspread\" \"Sample contains NaNs\"\n | k <= 0 = modErr \"midspread\" \"Nonpositive number of quantiles\"\n | otherwise = let Pair x1 x2 = quantiles param (Pair 1 (k-1)) k x\n in x2 - x1\n{-# INLINABLE midspread #-}\n{-# SPECIALIZE midspread :: ContParam -> Int -> U.Vector Double -> Double #-}\n{-# SPECIALIZE midspread :: ContParam -> Int -> V.Vector Double -> Double #-}\n{-# SPECIALIZE midspread :: ContParam -> Int -> S.Vector Double -> Double #-}\n\ndata Pair a = Pair !a !a\n deriving (Functor, F.Foldable)\n\n\n-- | O(/n/·log /n/). Estimate the median absolute deviation (MAD) of a\n-- sample /x/ using 'continuousBy'. It's robust estimate of\n-- variability in sample and defined as:\n--\n-- \\[\n-- MAD = \\operatorname{median}(| X_i - \\operatorname{median}(X) |)\n-- \\]\nmad :: G.Vector v Double\n => ContParam -- ^ Parameters /α/ and /β/.\n -> v Double -- ^ /x/, the sample data.\n -> Double\nmad p xs\n = median p $ G.map (abs . subtract med) xs\n where\n med = median p xs\n{-# INLINABLE mad #-}\n{-# SPECIALIZE mad :: ContParam -> U.Vector Double -> Double #-}\n{-# SPECIALIZE mad :: ContParam -> V.Vector Double -> Double #-}\n{-# SPECIALIZE mad :: ContParam -> S.Vector Double -> Double #-}\n\n\n----------------------------------------------------------------\n-- Deprecated\n----------------------------------------------------------------\n\ncontinuousBy :: G.Vector v Double =>\n ContParam -- ^ Parameters /α/ and /β/.\n -> Int -- ^ /k/, the desired quantile.\n -> Int -- ^ /q/, the number of quantiles.\n -> v Double -- ^ /x/, the sample data.\n -> Double\ncontinuousBy = quantile\n{-# DEPRECATED continuousBy \"Use quantile instead\" #-}\n\n-- $references\n--\n-- * Weisstein, E.W. Quantile. /MathWorld/.\n-- \n--\n-- * [Hyndman1996] Hyndman, R.J.; Fan, Y. (1996) Sample quantiles in statistical\n-- packages. /American Statistician/\n-- 50(4):361–365. \n", "meta": {"hexsha": "53cc2a5284c5a28ffb39262dad3f72052ba422f8", "size": 14495, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Quantile.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": "Statistics/Quantile.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": "Statistics/Quantile.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": 35.2676399027, "max_line_length": 98, "alphanum_fraction": 0.5996550535, "num_tokens": 3980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5042108188463422}} {"text": "{-# LANGUAGE DataKinds #-}\n\nimport Math.Tensor\nimport Math.Tensor.LorentzGenerator\nimport Math.Tensor.Examples.Gravity\nimport Math.Tensor.Examples.Gravity.DiffeoSymEqns\nimport Math.Tensor.Examples.Gravity.Schwarzschild\n\nimport Math.Tensor.Internal.LinearAlgebra\n\nimport Numeric.LinearAlgebra (rank)\nimport Numeric.LinearAlgebra.Data (toLists, fromLists, size, cmap, (===), Matrix, Z)\nimport Data.List (nub, nubBy, findIndex, sort)\n\nimport Data.Maybe (mapMaybe)\n\nimport Data.Int (Int64)\nimport Data.Ratio\n\nimport Control.Parallel.Strategies (parList, runEvalIO, rdeepseq)\n\nimport qualified Data.IntMap.Strict as I\n\nmain = do\n\n let ans0 = fromListT6 [((Empty, Empty, Empty, Empty, Empty, Empty), AnsVar $ I.singleton 1 (SField 1))] :: ATens 0 0 0 0 0 0 AnsVarR\n-- let (eta4,eps4,ans4) = mkAnsatzTensorFastAbs 4 symList4 areaList4 :: (AnsatzForestEta, AnsatzForestEpsilon, ATens 1 0 0 0 0 0 AnsVarR)\n let ans4 = ZeroTensor :: ATens 1 0 0 0 0 0 AnsVarR\n let (eta6,eps6,ans6) = mkAnsatzTensorFastAbs 6 symList6 areaList6 :: (AnsatzForestEta, AnsatzForestEpsilon, ATens 1 0 1 0 0 0 AnsVarR)\n let (eta8,eps8,ans8) = mkAnsatzTensorFastAbs 8 symList8 areaList8 :: (AnsatzForestEta, AnsatzForestEpsilon, ATens 2 0 0 0 0 0 AnsVarR)\n let (eta10_1,eps10_1,ans10_1) = mkAnsatzTensorFastAbs 10 symList10_1 areaList10_1 :: (AnsatzForestEta, AnsatzForestEpsilon, ATens 2 0 0 0 2 0 AnsVarR)\n let (eta10_2,eps10_2,ans10_2) = mkAnsatzTensorFastAbs 10 symList10_2 areaList10_2 :: (AnsatzForestEta, AnsatzForestEpsilon, ATens 2 0 1 0 0 0 AnsVarR)\n\n let r0 = tensorRank6' ans0\n let r4 = tensorRank6' ans4\n let r6 = tensorRank6' ans6\n let r8 = tensorRank6' ans8\n let r10_1 = tensorRank6' ans10_1\n let r10_2 = tensorRank6' ans10_2\n\n let ans0' = ans0\n let ans4' = shiftLabels6 r0 ans4\n let ans6' = shiftLabels6 (r0 + r4) ans6\n let ans8' = shiftLabels6 (r0 + r4 + r6) ans8\n let ans10_1' = shiftLabels6 (r0 + r4 + r6 + r8) ans10_1\n let ans10_2' = shiftLabels6 (r0 + r4 + r6 + r8 + r10_1) ans10_2\n\n let ansaetze = ans0' &.&>\n ans4' &.&>\n ans6' &.&>\n ans8' &.&>\n ans10_1' &.&>\n (singletonTList6 ans10_2')\n\n putStrLn $ \"dimension of ansatz space : \" ++ show (tensorRank6 ansaetze)\n\n let two = SField (2 :: Rational)\n\n let e1 = eqn1 ans0' ans4'\n let e2 = eqn3 ans6'\n let e3 = eqn1A ans4' (two &. ans8')\n let e4 = eqn1AI ans6' ans10_2'\n let e5 = eqn2Aa ans6' (two &. ans10_1')\n let e6 = eqn3A ans6' ans10_2'\n\n let system = e1 &.&>\n e2 &.&>\n e3 &.&>\n e4 &.&>\n e5 &.&>\n (singletonTList6 e6)\n\n putStrLn $ \"rank of system : \" ++ show (tensorRank6 system)\n\n let solution = redefineVarsSystem6 $ solveSystem6 system ansaetze\n\n case solution of\n (t1 `AppendTList6` (\n t2 `AppendTList6` (\n t3 `AppendTList6` (\n t4 `AppendTList6` (\n t5 `AppendTList6` (\n t6 `AppendTList6` (\n EmptyTList6)))))))\n -> do\n let Just ans0'' = tryAsATens ans0 t1\n let Just ans4'' = tryAsATens ans4 t2\n let Just ans6'' = tryAsATens ans6 t3\n let Just ans8'' = tryAsATens ans8 t4\n let Just ans10_1'' = tryAsATens ans10_1 t5\n let Just ans10_2'' = tryAsATens ans10_2 t6\n\n let e1' = removeZeros6 $ eqn1 ans0'' ans4''\n let e2' = removeZeros6 $ eqn3 ans6''\n let e3' = removeZeros6 $ eqn1A ans4'' (two &. ans8'')\n let e4' = removeZeros6 $ eqn1AI ans6'' ans10_2''\n let e5' = removeZeros6 $ eqn2Aa ans6'' (two &. ans10_1'')\n let e6' = removeZeros6 $ eqn3A ans6'' ans10_2''\n\n putStrLn $ \"dimension of solution space : \" ++ show (tensorRank6 solution)\n putStrLn \"\"\n putStrLn \"Equations on solution space :\"\n\n print e1'\n print e2'\n print e3'\n print e4'\n print e5'\n print e6'\n\n let kin' = ans10_2'' &- (contrATens3 (0,0) $ contrATens3 (1,1) $ interI2 &* ans10_1'')\n let kin = kin' &+ (tensorTrans1 (0,1) kin')\n\n putStrLn \"\"\n putStrLn $ \"number of parameters in kinetic part of EOM : \" ++ show (tensorRank6' kin)\n putStrLn $ \"number of parameters in mass part of EOM : \" ++ show (tensorRank6' ans8'')\n \n let n1 = removeZeros6 $ (delta3A &* ans4'') &+ (contrATens1 (1,0) $ interArea &* ans4'') &+ (contrATens1 (0,0) $ contrATens1 (1,1) $ two &. flatArea &* interArea &* ans8'')\n\n let n2_1 = contrATens1 (0,0) $ contrATens1 (1,1) $ contrATens2 (0,0) $ flatArea &* interArea &* interJ2 &* ans10_2''\n let n2_2 = contrATens1 (0,0) $ contrATens1 (2,1) $ contrATens2 (0,0) $ flatArea &* interArea &* interJ2 &* ans10_2''\n let n2_3 = contrATens1 (0,0) $ contrATens1 (1,1) $ flatArea &* interArea &* ans10_1''\n\n let n2 = removeZeros6 $ cyclicSymATens5 [0,1,2] $ n2_1 &+ n2_2 &- (two &. n2_3)\n\n putStrLn \"\"\n putStrLn \"Noether identity 1 :\"\n print n1\n\n putStrLn \"\"\n putStrLn \"Noether identity 2 :\"\n print n2\n\n return ()\n", "meta": {"hexsha": "ee669d43e18d210d6dfb0dfbaf868fa881bc4345", "size": 5117, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "calculations/area-density-2nd-derivative/src/Main.hs", "max_stars_repo_name": "nilsalex/HaskellTensor2", "max_stars_repo_head_hexsha": "668ad31d83679066fd64c34b6f29ac910dd59c64", "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": "calculations/area-density-2nd-derivative/src/Main.hs", "max_issues_repo_name": "nilsalex/HaskellTensor2", "max_issues_repo_head_hexsha": "668ad31d83679066fd64c34b6f29ac910dd59c64", "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": "calculations/area-density-2nd-derivative/src/Main.hs", "max_forks_repo_name": "nilsalex/HaskellTensor2", "max_forks_repo_head_hexsha": "668ad31d83679066fd64c34b6f29ac910dd59c64", "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.9037037037, "max_line_length": 182, "alphanum_fraction": 0.6136408052, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.5040105668721423}} {"text": "module Numeric.RBM where\n\nimport Control.Monad\nimport Control.Monad.IO.Class\nimport Math.Probable hiding (vector)\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Data\nimport Numeric.LinearAlgebra.HMatrix (norm_2)\n\ndata RBM = RBM\n { weights :: !(Matrix Double)\n , weightsT :: !(Matrix Double)\n } deriving (Eq, Show)\n\npp :: RBM -> IO ()\npp (RBM w _) = disp 2 w\n\nrandMat :: Int -> Int -> RandT IO Double -> IO (Matrix Double)\nrandMat n p = mwc . fmap fromLists . replicateM n . listOf p\n\nnew :: Int -- ^ nb of visible units\n -> Int -- ^ nb of hidden units\n -> IO RBM\nnew nvisible nhidden = do\n w <- randMat nvisible nhidden (normal 0 0.1)\n let w' = asColumn (konst 0 nvisible) ||| w\n w'' = asRow (konst 0 (nhidden + 1)) === w'\n return $ RBM w'' (tr w'')\n\n\ntrainOnce :: Matrix Double -- ^ training data\n -> Double -- ^ learning rate\n -> RBM\n -> IO RBM\ntrainOnce trainingData learningRate (RBM w wt) = do\n let dat = asColumn (konst 1 n) ||| trainingData\n pos_hidden_act = dat <> w\n pos_hidden_p = cmap logistic pos_hidden_act\n \n pos_hidden_st <- do\n randomM <- randMat n p (uniform 0 1)\n return $ step (pos_hidden_p - randomM)\n\n let pos_assocs = tr dat <> pos_hidden_p\n\n neg_visible_act = pos_hidden_st <> wt\n neg_visible_p = cmap logistic neg_visible_act\n n' = rows neg_visible_p\n neg_visible_p' = asColumn (konst 1 n') ||| dropColumns 1 neg_visible_p\n neg_hidden_act = neg_visible_p' <> w\n neg_hidden_p = cmap logistic neg_hidden_act\n neg_assocs = tr neg_visible_p' <> neg_hidden_p\n\n new_w = (w +) . cmap (\\x -> learningRate * x / fromIntegral n) $\n pos_assocs - neg_assocs\n\n err = norm_2 (dat - neg_visible_p')\n\n putStrLn $ \"Error: \" ++ show err\n return $ RBM new_w (tr new_w)\n\n where n = rows trainingData\n p = cols w\n\nlogistic :: Double -> Double\nlogistic x = 1 / (1 + exp (negate x))\n\ntrainN :: Matrix Double -- ^ training data\n -> Double -- ^ learning rate\n -> Int -- ^ epochs\n -> RBM\n -> IO RBM\ntrainN dat learningRate epochs = go epochs\n\n where go 0 rbm = return rbm\n go n rbm = do\n rbm' <- trainOnce dat learningRate rbm\n go (n - 1) rbm'\n\nrunVisible :: RBM\n -> Matrix Double -- ^ sample rows of values for visible units\n -> IO (Matrix Double) -- ^ values of hidden units for the given visible units\nrunVisible (RBM w wt) inputData = do\n let dat = asColumn (konst 1 n) ||| inputData\n hidden_act = dat <> w\n hidden_p = cmap logistic hidden_act\n\n hidden_st <- do\n randomM <- randMat n p (uniform 0 1)\n return $ step (hidden_p - randomM)\n\n return $ dropColumns 1 hidden_st\n\n where n = rows inputData\n p = cols w\n\nrunHidden :: RBM\n -> Matrix Double -- ^ sample rows of hidden units values\n -> IO (Matrix Double) -- ^ values of visible units for the given hidden ones\nrunHidden (RBM w wt) hiddenData = do\n let dat = asColumn (konst 1 n) ||| hiddenData\n visible_act = dat <> wt\n visible_p = cmap logistic visible_act\n\n visible_st <- do\n randomM <- randMat n p (uniform 0 1)\n return $ step (visible_p - randomM)\n\n return $ dropColumns 1 visible_st\n\n where n = rows hiddenData\n p = cols wt\n\ndaydream :: RBM\n -> Int -- ^ number of samples we want to extract\n -> IO [Vector Double] -- ^ each row is a sample of the visible units\n -- that the RBM has \"daydreamed\"\ndaydream (RBM w wt) nsamples = do\n sample0 <- fmap (fromList . (1:) . tail) . mwc $ listOf n (uniform 0 1)\n\n go sample0 nsamples\n\n where n = rows w\n p = cols w\n\n go :: Vector Double -> Int -> IO [Vector Double]\n go _v 0 = return []\n go v i = do\n let hidden_act = asRow v <> w\n hidden_p = cmap logistic hidden_act\n\n hidden_st <- do\n randomV <- fmap vector . mwc $ listOf p (uniform 0 1)\n return $ step (head (toRows hidden_p) - randomV)\n \n let hidden_st' = asRow . vector . (1:) . tail . toList $ hidden_st\n visible_act = hidden_st' <> wt\n visible_p = cmap logistic visible_act\n\n visible_st <- do\n randomV <- fmap vector . mwc $ listOf n (uniform 0 1)\n return $ step (head (toRows visible_p) - randomV)\n\n let res = vector . tail . toList $ visible_st\n fmap (res:) $ go visible_st (i - 1)\n\n-- EXAMPLE\n\n-- data given in:\n-- http://blog.echen.me/2011/07/18/introduction-to-restricted-boltzmann-machines/\n\n-- Harry Potter, Avatar, LOTR, Gladiator, Titanic, Glitter\nsamples :: Matrix Double\nsamples = fromLists\n [ [ 1, 1, 1, 0, 0, 0 ]\n , [ 1, 0, 1, 0, 0, 0 ]\n , [ 1, 1, 1, 0, 0, 0 ]\n , [ 0, 0, 1, 1, 1, 0 ]\n , [ 0, 0, 1, 1, 0, 0 ]\n , [ 0, 0, 1, 1, 1, 0 ]\n ]\n\nnew_user :: Matrix Double\nnew_user = fromLists [ [ 0, 0, 0, 1, 1, 0 ] ]\n\nhiddens :: Matrix Double\nhiddens = fromLists\n [ [0, 0]\n , [0, 1]\n , [1, 0]\n , [1, 1]\n ]\n\ntest :: Double -> Int -> IO ()\ntest rate k = do\n rbm <- new 6 2\n\n pp rbm\n trained <- trainN samples rate k rbm\n pp trained\n putStrLn \"-------\"\n putStrLn \"VISIBLE\"\n res <- runVisible trained new_user\n disp 2 res\n putStrLn \"-------\"\n putStrLn \"HIDDEN\"\n res' <- runHidden trained hiddens\n disp 2 res'\n \n putStrLn \"-------\"\n putStrLn \"DAYDREAM\"\n daydream trained 10 >>= mapM_ print\n\n\nmain :: IO ()\nmain = test 0.1 10000\n", "meta": {"hexsha": "17518fa3711882174c212f2f36195c2bec894d3d", "size": 5576, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/RBM.hs", "max_stars_repo_name": "alpmestan/rbm", "max_stars_repo_head_hexsha": "48ae0177638d8d79d8b3e00dddebc75f6cc3e174", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-08-13T22:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-13T22:23:48.000Z", "max_issues_repo_path": "src/Numeric/RBM.hs", "max_issues_repo_name": "alpmestan/rbm", "max_issues_repo_head_hexsha": "48ae0177638d8d79d8b3e00dddebc75f6cc3e174", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/RBM.hs", "max_forks_repo_name": "alpmestan/rbm", "max_forks_repo_head_hexsha": "48ae0177638d8d79d8b3e00dddebc75f6cc3e174", "max_forks_repo_licenses": ["BSD-3-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.3045685279, "max_line_length": 88, "alphanum_fraction": 0.5805236729, "num_tokens": 1685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.5037495312406755}} {"text": "{-# LANGUAGE UnicodeSyntax, DataKinds, TypeOperators, KindSignatures,\n TypeInType, GADTs, MultiParamTypeClasses, FunctionalDependencies,\n TypeFamilies, AllowAmbiguousTypes, FlexibleInstances,\n UndecidableInstances, InstanceSigs, TypeApplications, \n ScopedTypeVariables, EmptyCase, FlexibleContexts, \n RankNTypes, LambdaCase\n#-}\n\n-- Implementation of density matrix interpretation of quantum computation\nmodule LinTrans where\n\nimport Prelim\n\nimport qualified Data.Complex as C \nimport Data.Complex (Complex(..))\nimport Control.Monad.State.Lazy\nimport Data.Singletons\nimport Data.Maybe (fromJust)\n--import Data.Tuple hiding (swap)\nimport Unsafe.Coerce\nimport Data.Constraint (Dict(..))\nimport Data.List ( (\\\\) )\nimport qualified Debug.Trace as Tr\n\n\n-- I don't like the show instance for ℂ\nnewtype ℂ = ℂ (Complex Double)\n\nliftC :: (Complex Double -> Complex Double) -> ℂ -> ℂ\nliftC f (ℂ c) = ℂ $ f c\n\ni :: ℂ\ni = ℂ $ 0 :+ 1\nconjugate = liftC C.conjugate\ninstance Num ℂ where\n ℂ m + ℂ n = ℂ $ m + n\n ℂ m - ℂ n = ℂ $ m - n\n ℂ m * ℂ n = ℂ $ m * n\n abs = liftC abs\n signum = liftC signum\n fromInteger = ℂ . fromInteger \ninstance Fractional ℂ where\n fromRational = ℂ . fromRational\n ℂ m / ℂ n = ℂ $ m / n\ninstance Floating ℂ where\n pi = ℂ $ pi\n exp = liftC exp\n log = liftC log\n sin = liftC sin\n cos = liftC cos\n asin = liftC asin\n acos = liftC acos\n atan = liftC atan\n sinh = liftC sinh\n cosh = liftC cosh\n asinh = liftC asinh\n acosh = liftC acosh\n atanh = liftC atanh\ninstance Show ℂ where\n show (ℂ (α :+ β)) = if β == 0 then show α \n else if α == 0 then show β ++ \"i\"\n else show α ++ \" + \" ++ show β ++ \"i\"\n\n\n-- A matrix of dimension m × n is a function from \n-- pairs of nats bounded by m and n respectively.\ntype Matrix m n = (BNat m,BNat n) -> ℂ\ntype Squared n = Matrix (Two `RaiseTo` n) (Two `RaiseTo` n)\n\nmatrix :: forall m n. (SingI m, SingI n) => [ℂ] -> Matrix m n\nmatrix ls (i,j) = ls !! (n * fromIntegral i + fromIntegral j)\n where\n n = toInt (sing :: Sing n)\n\n--------------\n-- Printing --\n--------------\nrows :: forall m n. (SingI m, SingI n) => Matrix m n -> [[ℂ]]\nrows mat = fmap f $ allBNat (sing :: Sing m)\n where\n f i = fmap (\\j -> mat (i,j)) $ allBNat (sing :: Sing n)\n\nshowRows :: (SingI m, SingI n) => Matrix m n -> [String]\nshowRows mat = show <$> rows mat\n\ninstance (SingI m, SingI n) => Show (Matrix m n) where\n show mat = unlines $ showRows mat\n\n---------------------------------------\n-- Primitive matrices and operatoins --\n---------------------------------------\n\nident :: Matrix m m\nident (i,j) = if i==j then 1 else 0\n\ntranspose :: Matrix m n -> Matrix n m\ntranspose mat (i,j) = conjugate $ mat (j,i)\n\n{-\n-- if i : BNat m then raise m n = i : BNat (S m)\n-- so pruneRows mat is just the first m rows of mat\npruneRows :: Sing m -> Matrix (S m) n -> Matrix m n\npruneRows m mat (i,j) = mat (raise m i,j)\n\npruneCols :: Sing n -> Matrix m (S n) -> Matrix m n\npruneCols n mat (i,j) = mat (i,raise n j)\n-}\n\nsumTo :: Sing n -> BNat n -> (BNat n -> ℂ) -> ℂ\nsumTo _ (BNat SZ) _ = 0\nsumTo n (BNat (SS m)) f = f m' + sumTo n m' f \n where\n m' = case succLtTrans m n of Dict -> BNat m -- m < S m < n\n\ndot :: Sing n -> Matrix (S Z) n -> Matrix n (S Z) -> ℂ\ndot n v1 v2 = sumTo n (maxBNat n) (\\x -> v1 (0,x) * v2(x,0))\n\nrow :: BNat m -> Matrix m n -> Matrix (S Z) n\nrow i mat (_,j) = mat (i,j)\n\ncol :: BNat n -> Matrix m n -> Matrix m (S Z)\ncol j mat (i,_) = mat (i,j)\n\nplus :: Matrix m n -> Matrix m n -> Matrix m n\nplus mat1 mat2 (i,j) = mat1(i,j) + mat2(i,j)\n\nmult :: forall m n p. SingI n => Matrix m n -> Matrix n p -> Matrix m p\nmult mat1 mat2 (i,j) = \n-- Tr.trace (\"Composing for intermediate \" ++ show (sing :: Sing n)) $\n dot sing (row i mat1) (col j mat2)\n\nkron :: forall m1 m2 n1 n2. (SingI m1, SingI n1, SingI m2, SingI n2)\n => Matrix m1 n1 -> Matrix m2 n2 -> Matrix (m1 `Times` m2) (n1 `Times` n2)\nkron mat1 mat2 (BNat i,BNat j) = \n-- Tr.trace (\"Computing ⊗ for \" ++ show (m1, n1) ++ \"×\" ++ show (m2, n2)) $\n mat1 (bNat i1, bNat j1) * mat2 (bNat i2,bNat j2)\n where\n i1 = i `divSNat` m2\n i2 = i `modSNat` m2\n j1 = j `divSNat` n2\n j2 = j `modSNat` n2\n m2 = (sing :: Sing m2)\n n2 = (sing :: Sing n2)\n\ntrace :: forall m. SingI m => Matrix m m -> ℂ\ntrace mat = foldr f 0 ls\n where\n ls = allBNat (sing :: Sing m)\n f i x = mat (i,i) + x\n\n----------------------\n-- Quantum Matrices --\n----------------------\n\nsquare :: forall n. SingI n => [ℂ] -> Squared n\nsquare ls = withSingI (two `raiseToSNat` (sing :: Sing n)) $ matrix ls\n\ndensity0 :: Matrix Two Two\ndensity0 = matrix [1,0\n ,0,0]\n\ndensity1 :: Matrix Two Two\ndensity1 = matrix [0,0\n ,0,1]\n\nhadamard = square @One $ [1/sqrt 2, 1/sqrt 2\n ,1/sqrt 2, -1/sqrt 2]\n\n \n\npauliX = square @One $ [0,1,1,0]\npauliY = square @One $ [0,-i,i,0]\npauliZ = square @One $ [1,0,0,-1]\n\ncnotD = square @Two $ [1,0,0,0\n ,0,1,0,0\n ,0,0,0,1\n ,0,0,1,0]\n\nnewD :: Bool -> Squared One\nnewD True = density1\nnewD False = density0 \n\n--------------------------------------------------------------------\n\n\n----------------------\n-- Density Matrices --\n----------------------\n\ndata Density where\n Density :: Sing n -> Squared n -> Density\ninstance Show Density where\n show (Density n m) = withSingI (two `raiseToSNat` n) $ show m\n\n\n\nsize :: forall m. SingI m => Matrix m m -> Int\nsize _ = toInt (sing :: Sing m)\nlogsizeD :: Density -> Int\nlogsizeD (Density n mat) = toInt n\nsizeD :: Density -> Int\nsizeD ρ = 2 ^ logsizeD ρ\n\ntransposeD :: Density -> Density \ntransposeD (Density m ρ) = Density m $ transpose ρ\n\nmultD :: Density -> Density -> Density\nmultD = undefined\n\nkronD :: Density -> Density -> Density\nkronD (Density m mat1) (Density n mat2) = \n withSingI (raiseToSNat two n) $ \n withSingI (raiseToSNat two m) $ \n withSingI (raiseToSNat two (plusSNat m n)) $\n case raiseToPlus two m n of {Dict -> \n Density (m `plusSNat` n) $ mat1 `kron` mat2\n }\n\nidentD :: Int -> Density\nidentD n = case fromIntegral @_ @(SomeSing Nat) n of SomeSing n' -> Density n' ident\n\nnil :: Int -> Density\nnil n = case fromIntegral n of\n SomeSing n' -> withSingI (two `raiseToSNat` n') $\n Density n' . matrix $ fromIntegral <$> repeat 0\n\n\n------------------\n-- Permutations --\n------------------\n\n-- encode and decode modulo a key k\nencode :: Int -> [Int] -> Int\nencode k [] = 0\nencode k (i : ls) = i + k * encode k ls\n\ndecode :: Int -> Int -> [Int]\ndecode k i | i == 0 = []\ndecode k i | otherwise = i `mod` k : decode k (i `div` k)\n\nfromAssocList :: [(Int,Int)] -> Int -> Int\nfromAssocList [] = id\nfromAssocList ((a,b) : ls) = assocFun a b . fromAssocList ls\n where\n assocFun a b i = if i == a then b else i\n\n-- Check if two lists are equal up to the permutation specified, i.e.\n-- if permuting ls1 by f is equal to ls2\nisPermutation :: Eq a => (Int -> Int) -> [a] -> [a] -> Bool\nisPermutation f ls1 ls2 = all (\\i -> ls1 !! i == ls2 !! f i) [0..len]\n where\n len = length ls1\n \n\nswapFun :: forall n. SingI n => (Int -> Int) -> Squared n\nswapFun f (i,j) = if isPermutation f (decode n' i') (decode n' j') then 1 else 0\n where\n n' = toInt (sing :: Sing n)\n i' = toInt i\n j' = toInt j\n\n-- swap takes a list of qubit/bit variables and produces a matrix that permutes\n-- those qubits.\n-- i.e. swap ls |φ_0 ⋯ φ_n⟩ = |φ_f(0) ⋯ ρ_f(n)⟩ \n-- where f = fromAssocList ls\nswap :: forall n. SingI n => [Int] -> Squared n\nswap ls = swapFun @n (fromAssocList $ zip [0..] ls)\n\n-------------------\n-- Density Monad --\n-------------------\n\n-- A density monad is a nondeterminism state monad:\n-- Density -> [Density]\n-- An element op of type DensityMonad corresponds to the superoperator\n-- \\ρ -> ∑ (op ρ)\ntype DensityMonad = StateT Density []\n\nnewM :: Bool -> DensityMonad Int\nnewM b = do\n ρ <- get\n put $ ρ `kronD` (Density one $ newD b)\n return $ sizeD ρ\n\n-- runQ applies the superoperator to the identity density matrix of size 1.\nrunQ :: DensityMonad a -> [(a,Density)]\nrunQ m = runStateT m (Density SZ ident)\n\n-- getDensity combines the result of runQ into a single density matrix\ngetDensity :: DensityMonad a -> Density\ngetDensity m = foldr f (nil n) ls\n where\n ls = runQ m\n n = logsizeD . snd $ head ls\n f (_,ρ) ρ0 = ρ + ρ0\n\n\n-----------------\n-- Application --\n-----------------\n\nsuperM :: forall m n. Matrix (Two `RaiseTo` m) (Two `RaiseTo` n) -> DensityMonad ()\nsuperM mat = do Density _ ρ ← get\n put . Density _ $ mat `mult` ρ `mult` transpose mat\n where\n matD = Density (sing :: Sing m) mat\n\napplyUnitaryM :: forall m. SingI m => Squared m -> [Int] -> DensityMonad ()\napplyUnitaryM u ls = do superM @m σ -- moves the relevant qubits to the front of the density matrix\n superM @m u -- applies operation\n superM @m $ transpose σ -- moves the qubits back\n where\n σ = swap @m ls\n\napplyMatrixM :: Matrix (Two `RaiseTo` m) (Two `RaiseTo` n) \n -> [Int] -> DensityMonad ()\napplyMatrixM mat ls = undefined\n\nmeasM :: Int -> DensityMonad Bool\nmeasM i = do\n ρ <- get\n (b,ρ') <- lift [ (False, applyMatrixD @One density0 [i] ρ)\n , (True, applyMatrixD @One density1 [i] ρ) ]\n put ρ'\n return b\n\n------------------\n-- Num instance --\n------------------\n\ninstance (SingI m, SingI n) => Num (Matrix m n) where\n (+) mat1 mat2 (i,j) = mat1(i,j) + mat2(i,j)\n (-) mat1 mat2 (i,j) = mat1(i,j) - mat2(i,j)\n (*) mat1 mat2 (i,j) = mat1(i,j) * mat2(i,j)\n abs mat (i,j) = abs $ mat(i,j)\n signum mat = undefined -- trace mat\n fromInteger n = matrix . repeat $ fromIntegral n\ninstance Num Density where\n Density n1 mat1 + Density n2 mat2 = \n withSingI (two `raiseToSNat` n1) $\n withSingI (two `raiseToSNat` n2) $\n case eqSNat n1 n2 of \n Left Dict -> Density n1 $ mat1 + mat2\n Right _ -> error $ \"Cannot add mismatched matrices \" \n ++ show mat1 ++ \" and \" ++ show mat2\n _ - _ = undefined\n _ * _ = undefined\n abs _ = undefined\n signum = undefined\n fromInteger n = undefined\n\n\n\ninstance Show (DensityMonad a) where\n show = show . getDensity\n\n-- Debugging help\nm0 = square @Two [1,0,0,0\n ,0,1,0,0\n ,0,0,0,1\n ,0,0,1,0]\nrho = Density three $ \\case\n (0,0) -> -0.5\n (0,2) -> 0.5\n (3,0) -> -0.5\n (3,2) -> 0.5\n (_,_) -> 0\n\n\n{-\n-- produces an association list\nlistToAssoc :: forall n. SingI n => [Int] -> [(BNat n, BNat n)]\nlistToAssoc ls = (fromIntegral <$> [0..n]) `zip` (fromIntegral <$> pad ls)\n where\n n = maxBNat (sing :: Sing n)\n\npad :: [Int] -> [Int]\npad ls = ls ++ ([0..] \\\\ ls)\n\nmkPermutation :: [(BNat n,BNat n)] -> BNat n -> BNat n\nmkPermutation ls i = \n case lookup i ls of\n Just i' -> i'\n Nothing -> error $ \"Permutation \" ++ show ls \n ++ \" not well defined at index \" ++ show i\n\npermute :: forall m. SingI m => [(BNat m, BNat m)] -> Matrix m m -> Matrix m m\npermute ls mat (i,j) = mat (mkPermutation ls i, mkPermutation ls j)\n\nexpand :: forall m n. (SingI m, SingI n) \n => [(BNat (m `Times` n), BNat (m `Times` n))] \n -> Matrix m m -> Matrix (m `Times` n) (m `Times` n)\nexpand ls mat = Tr.trace (\"Expanding...\" ++ show mat) $\n withSingI (timesSNat (sing :: Sing m) (sing :: Sing n)) $ \n permute ls $ mat `kron` ident @n\n\napplyMatrix :: forall m p. (SingI m, SingI p, (p < m) ~ 'False)\n => Squared m -> [Int] -> Squared p -> Squared p\napplyMatrix mat ls ρ = \n Tr.trace (\"Applying \" ++ show ls) $\n case raiseToPlus two m minus of {Dict ->\n case plusMinus m p of {Dict -> \n withSingI (raiseToSNat two m) $\n withSingI (raiseToSNat two minus) $ \n withSingI (raiseToSNat two p) $\n let mat1 = expand @(Two `RaiseTo` m) @(Two `RaiseTo` (p `Minus` m)) \n (swap <$> ls') (transpose mat)\n mat2 = expand @(Two `RaiseTo` m) @(Two `RaiseTo` (p `Minus` m)) ls' mat\n res = Tr.trace \"Middle of application\" $\n mat1 `mult` ρ `mult` mat2\n in mat1 `seq` mat2 `seq` res `seq` Tr.trace \"End of application\" res\n }}\n where\n ls' :: [(BNat (Two `RaiseTo` p), BNat (Two `RaiseTo` p))]\n ls' = withSingI (raiseToSNat two p) $ listToAssoc ls\n m = (sing :: Sing m)\n p = (sing :: Sing p)\n minus :: Sing (p `Minus` m)\n minus = minusSNat p m\n\napplyMatrixD :: forall m. SingI m => Squared m -> [Int] -> Density -> Density\napplyMatrixD mat perm (Density (p :: Sing p) ρ) = \n Tr.trace (\"Applying \" ++ mat' ++ \" to qubits \" ++ show perm ++ \" of \\n\" ++ show (Density p ρ)) $\n case compareSNat p (sing :: Sing m) of\n -- p < m\n Left Dict -> error \"Cannot apply matrix to state: matrix too large\"\n -- m <= p\n Right Dict -> \n let res = withSingI p $ Density p $ applyMatrix @m @p mat perm ρ \n in res `seq` Tr.trace \"Done!\" res\n where\n mat' = withSingI (two `raiseToSNat` (sing :: Sing m)) $ show mat\n\napplyUnitaryM :: forall m. SingI m => Squared m -> [Int] -> DensityMonad ()\napplyUnitaryM mat ls = get >>= \\ρ -> put $ applyMatrixD @m mat ls ρ\n\nmeasM :: Int -> DensityMonad Bool\nmeasM i = do\n ρ <- get\n (b,ρ') <- lift [ (False, applyMatrixD @One density0 [i] ρ)\n , (True, applyMatrixD @One density1 [i] ρ) ]\n put ρ'\n return b\n\n-}\n\n", "meta": {"hexsha": "396ee29573a54012510104ba22dc09574e48d141", "size": 13473, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/examples/LinTrans.hs", "max_stars_repo_name": "jpaykin/LNLHaskell", "max_stars_repo_head_hexsha": "7c3e3880d2702b5456326870ba4863f27a8606b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2016-10-23T18:46:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T06:00:45.000Z", "max_issues_repo_path": "src/examples/LinTrans.hs", "max_issues_repo_name": "jpaykin/LNLHaskell", "max_issues_repo_head_hexsha": "7c3e3880d2702b5456326870ba4863f27a8606b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/LinTrans.hs", "max_forks_repo_name": "jpaykin/LNLHaskell", "max_forks_repo_head_hexsha": "7c3e3880d2702b5456326870ba4863f27a8606b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-29T12:57:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-29T14:22:00.000Z", "avg_line_length": 30.0736607143, "max_line_length": 99, "alphanum_fraction": 0.5668373785, "num_tokens": 4463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.5028538540949463}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -Wcompat #-}\n{-# OPTIONS_GHC -Wincomplete-record-updates #-}\n{-# OPTIONS_GHC -Wincomplete-uni-patterns #-}\n{-# OPTIONS_GHC -Wredundant-constraints #-}\n\nmodule CloudSunlight\n ( cloudSunlightExperiment,\n )\nwhere\n\nimport Control.Monad\nimport qualified Data.ByteString.Lazy as BL\nimport Data.Csv\nimport qualified Data.List as L\nimport qualified Data.Vector.Unboxed as V\nimport qualified Statistics.Regression as R\nimport qualified Statistics.Sample as S\nimport System.Random.MWC\nimport qualified System.Random.MWC.Distributions as D\n\nmeanToa :: Double\nmeanToa = 340.0\n\ntoa :: GenIO -> IO Double\ntoa = D.normal meanToa 30.0\n\n-- | magnitude of aerosol affect on sunlight, between 1.0 and 0.0 (1.0 = max effect)\naerosolAffectSunlight :: Double\naerosolAffectSunlight = 1.0\n\n-- | factor that cloud reduces sunlight, if there is cloud\ncloudAffectSunlight :: Double\ncloudAffectSunlight = 0.6\n\nsunlight ::\n -- | non-dim measure of aerosol\n Double ->\n -- | cloud\n Bool ->\n -- | U_sun (i.e. TOA)\n Double ->\n -- | W/m2\n Double\nsunlight a c toa' = if c then clearSky * cloudAffectSunlight else clearSky\n where\n clearSky = toa' * (1.0 - aerosolAffectSunlight * a)\n\ncloud :: Double -> Double -> Bool\ncloud a u\n | (a + u) > 1.0 = True\n | otherwise = False\n\naerosol :: Double -> Double\naerosol u = u\n\ngenTuple :: GenIO -> IO (Double, String, Double)\ngenTuple gen = do\n uAero <- uniform gen\n uCld <- uniform gen\n uSun <- toa gen\n let a = aerosol uAero\n let c = cloud a uCld\n let s = sunlight a c uSun\n return (a, if c then \"Cloudy\" else \"Clear\", s)\n\ngetCloud :: (a, b, c) -> b\ngetCloud (_a, c, _s) = c\n\ngetSun :: (a, b, c) -> c\ngetSun (_a, _c, s) = s\n\ngetAerosol :: (a, b, c) -> a\ngetAerosol (a, _c, _s) = a\n\ncalcRegression :: V.Vector Double -> Double -> Double\ncalcRegression ols x = x * ols V.! 0 + ols V.! 1\n\ncalcStats ::\n [(Double, String, Double)] ->\n [(Double, String, Double)] ->\n (V.Vector Double, V.Vector Double, Double, Double)\ncalcStats cloud' clear =\n ( olsCloud,\n olsClear,\n avgRegress olsCloud - avgRegress olsClear,\n naiveCloud - naiveClear\n )\n where\n calcAvgs xs = (as, ols, S.mean ss)\n where\n ss = V.fromList (fmap getSun xs)\n as = V.fromList (fmap getAerosol xs)\n ols = fst . R.olsRegress [as] $ ss\n (aCloud, olsCloud, naiveCloud) = calcAvgs cloud'\n (aClear, olsClear, naiveClear) = calcAvgs clear\n totAs = aCloud <> aClear\n avgRegress ols = S.mean $ V.map (calcRegression ols) totAs\n\ncloudSunlightExperiment :: Int -> IO (Double, Double, Double)\ncloudSunlightExperiment n = do\n gen <- create\n xs <- replicateM n (genTuple gen)\n let (cloud', clear) = L.partition ((== \"Cloudy\") . getCloud) xs\n let (olsCloud, olsClear, estDiff, naiveDiff) = calcStats cloud' clear\n let regPoints = [0, 0.1 .. 1]\n f \"dat/cloudy.dat\" cloud'\n f \"dat/clear.dat\" clear\n write\n \"aerosol\\tsunlight\\n\"\n \"dat/olsCloudy.dat\"\n (zip regPoints (fmap (calcRegression olsCloud) regPoints))\n write\n \"aerosol\\tsunlight\\n\"\n \"dat/olsClear.dat\"\n (zip regPoints (fmap (calcRegression olsClear) regPoints))\n return (estDiff, naiveDiff, (0.5 * meanToa * (cloudAffectSunlight - 1.0)))\n where\n f = write \"aerosol\\tcloud\\tsunlight\\n\"\n write header' fpath =\n BL.writeFile fpath . (header' <>)\n . encodeWith\n (defaultEncodeOptions {encDelimiter = 9})\n", "meta": {"hexsha": "e75043726717ea3b90d398ff97052d19e3fc4f9c", "size": 3417, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/CloudSunlight.hs", "max_stars_repo_name": "massma/causality-earth-science", "max_stars_repo_head_hexsha": "67894ba8ef06334c0cd0021031f4601669250088", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-19T09:41:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T14:38:53.000Z", "max_issues_repo_path": "src/CloudSunlight.hs", "max_issues_repo_name": "massma/causality-earth-science", "max_issues_repo_head_hexsha": "67894ba8ef06334c0cd0021031f4601669250088", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CloudSunlight.hs", "max_forks_repo_name": "massma/causality-earth-science", "max_forks_repo_head_hexsha": "67894ba8ef06334c0cd0021031f4601669250088", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-06T10:58:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T10:58:51.000Z", "avg_line_length": 27.336, "max_line_length": 84, "alphanum_fraction": 0.6681299385, "num_tokens": 1106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5026777590400301}} {"text": "{-# LANGUAGE TypeApplications #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n\nmodule ScalarWave where\n\nimport Control.Exception (assert)\nimport Control.Monad.Loops\nimport qualified Data.Vector.Unboxed as U\nimport Data.VectorSpace\nimport Dual\nimport Equations\nimport Foreign\nimport qualified Numeric.LinearAlgebra as L\nimport SSSFN\nimport System.CPUTime\n\ndefault (Int)\n\n--------------------------------------------------------------------------------\n\nbndw :: Floating a => Coord a -> a\nbndw (Coord u v) = swamp * cos (pi / 4 * swk * t) * cos (pi / 4 * swk * r)\n where\n t = v + u\n r = v - u\n swk = 0.1\n swamp = 0.1\n\nguess1 :: Floating a => Coord a -> State a\nguess1 c = State 1 1 0\n\nguess :: (L.Container L.Vector a, Floating a) => Grid (State a)\nguess = gsample (\\(u, v) -> guess1 (Coord u v))\n\n--------------------------------------------------------------------------------\n\neqnInt1 :: Num a => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnInt1 eqn c s r2s r1sr r1su r1sv su sv suv suu svv =\n case eqn of\n EqnG01 -> eqnG01 s r2s r1sr su sv suv\n EqnG22 -> eqnG22 s r2s r1sr su sv suv\n EqnSW2 -> eqnSW2 s r2s r1sr su sv suv\n EqnG00 -> eqnG00 c s r2s r1su su suu\n EqnG11 -> eqnG11 c s r2s r1sv sv svv\n\neqnOrig1 :: Floating a => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnOrig1 eqn c s r2s r1sr r1su r1sv su sv suv suu svv =\n case eqn of\n EqnG01 -> q s - 1\n EqnG22 -> g s - 1\n EqnSW2 -> w s - bndw c\n EqnG00 -> 0\n EqnG11 -> 0\n\n-- i == 0, u == -1\neqnBndU1 :: (Eq a, Floating a) => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnBndU1 eqn c s r2s r1sr r1su r1sv su sv suv suu svv =\n assert (u c == -1) $\n case eqn of\n EqnG01 -> eqnG11 c s r2s r1sv sv svv\n EqnG22 -> g s - 1\n EqnSW2 -> w s - bndw c\n EqnG00 -> 0\n EqnG11 -> 0\n\n-- j == 0, v == -1\neqnBndV1 :: (Eq a, Floating a) => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnBndV1 eqn c s r2s r1sr r1su r1sv su sv suv suu svv =\n assert (v c == -1) $\n case eqn of\n EqnG01 -> eqnG00 c s r2s r1su su suu\n EqnG22 -> g s - 1\n EqnSW2 -> w s - bndw c\n EqnG00 -> 0\n EqnG11 -> 0\n\neqnEndU1 :: Floating a => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnEndU1 eqn c s r2s r1sr r1su r1sv su sv suv suu svv =\n case eqn of\n EqnG01 -> q s - 1\n EqnG22 -> g s - 1\n EqnSW2 -> w s - bndw c\n EqnG00 -> 0\n EqnG11 -> 0\n\neqnEndV1 :: Floating a => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnEndV1 eqn c s r2s r1sr r1su r1sv su sv suv suu svv =\n case eqn of\n EqnG01 -> q s - 1\n EqnG22 -> g s - 1\n EqnSW2 -> w s - bndw c\n EqnG00 -> 0\n EqnG11 -> 0\n\nequation1 :: (Eq a, Floating a) => Coord Int -> Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> State a -> a\nequation1 (Coord i j) =\n if\n | i == 0 && j == 0 -> eqnOrig1\n | i == 0 && j == np - 1 -> eqnEndU1\n | i == np - 1 && j == 0 -> eqnEndV1\n | i == 0 -> eqnBndU1\n | j == 0 -> eqnBndV1\n | True -> eqnInt1\n\n--------------------------------------------------------------------------------\n\ng2s :: Storable a => Grid a -> State (Grid a)\ng2s (Grid xs) =\n let [g, q, w] = L.takesV (replicate 3 (np * np)) xs\n in State (Grid g) (Grid q) (Grid w)\n\ns2g :: Storable a => State (Grid a) -> Grid a\ns2g (State (Grid g) (Grid q) (Grid w)) = Grid (L.vjoin [g, q, w])\n\neqn1 ::\n forall a.\n (L.Field a, RealFloat a, U.Unbox a) =>\n Eqn ->\n Coord (Grid a) ->\n State (Grid a) ->\n Grid a\neqn1 eqn c s =\n Grid $\n L.fromList\n [ eqnRow i j\n | i <- [0 .. np - 1],\n j <- [0 .. np - 1]\n ]\n where\n r2s = (r2project #>) <$> s\n r1sr = (r1derivR #>) <$> s\n r1su = (r1derivU #>) <$> s\n r1sv = (r1derivV #>) <$> s\n su = (derivU #>) <$> s\n sv = (derivV #>) <$> s\n suv = (derivUV #>) <$> s\n suu = (derivUU #>) <$> s\n svv = (derivVV #>) <$> s\n eqnRow :: Int -> Int -> a\n eqnRow i j =\n let at :: Grid a -> a\n at x = x ! (i, j)\n in equation1\n (Coord i j)\n eqn\n (at <$> c)\n (at <$> s)\n (at <$> r2s)\n (at <$> r1sr)\n (at <$> r1su)\n (at <$> r1sv)\n (at <$> su)\n (at <$> sv)\n (at <$> suv)\n (at <$> suu)\n (at <$> svv)\n\neqns ::\n forall a.\n (L.Field a, RealFloat a, U.Unbox a) =>\n Coord (Grid a) ->\n State (Grid a) ->\n Grid a\neqns c s =\n Grid $\n L.fromList\n [ eqnRow (i, j, eqn)\n | eqn <- [EqnG01, EqnG22, EqnSW2],\n i <- [0 .. np - 1],\n j <- [0 .. np - 1]\n ]\n where\n r2s = (r2project #>) <$> s\n r1sr = (r1derivR #>) <$> s\n r1su = (r1derivU #>) <$> s\n r1sv = (r1derivV #>) <$> s\n su = (derivU #>) <$> s\n sv = (derivV #>) <$> s\n suv = (derivUV #>) <$> s\n suu = (derivUU #>) <$> s\n svv = (derivVV #>) <$> s\n eqnRow :: (Int, Int, Eqn) -> a\n eqnRow (i, j, eqn) =\n let at :: Grid a -> a\n at x = x ! (i, j)\n in equation1\n (Coord i j)\n eqn\n (at <$> c)\n (at <$> s)\n (at <$> r2s)\n (at <$> r1sr)\n (at <$> r1su)\n (at <$> r1sv)\n (at <$> su)\n (at <$> sv)\n (at <$> suv)\n (at <$> suu)\n (at <$> svv)\n\neqns5 ::\n forall a.\n (L.Field a, RealFloat a, U.Unbox a) =>\n Coord (Grid a) ->\n State (Grid a) ->\n Grid a\neqns5 c s =\n Grid $\n L.fromList\n [ eqnRow (i, j, eqn)\n | eqn <- [EqnG01, EqnG22, EqnSW2, EqnG00, EqnG11],\n i <- [0 .. np - 1],\n j <- [0 .. np - 1]\n ]\n where\n r2s = (r2project #>) <$> s\n r1sr = (r1derivR #>) <$> s\n r1su = (r1derivU #>) <$> s\n r1sv = (r1derivV #>) <$> s\n su = (derivU #>) <$> s\n sv = (derivV #>) <$> s\n suv = (derivUV #>) <$> s\n suu = (derivUU #>) <$> s\n svv = (derivVV #>) <$> s\n eqnRow :: (Int, Int, Eqn) -> a\n eqnRow (i, j, eqn) =\n let at :: Grid a -> a\n at x = x ! (i, j)\n in equation1\n (Coord i j)\n eqn\n (at <$> c)\n (at <$> s)\n (at <$> r2s)\n (at <$> r1sr)\n (at <$> r1su)\n (at <$> r1sv)\n (at <$> su)\n (at <$> sv)\n (at <$> suv)\n (at <$> suu)\n (at <$> svv)\n\nop ::\n forall a.\n (L.Container L.Vector a, L.Field a, RealFloat a, U.Unbox a) =>\n Coord (Grid a) ->\n State (Grid a) ->\n Op a\nop (Coord u v) s =\n Op $\n L.fromRows\n [ jacRow (i, j, eqn)\n | eqn <- [EqnG01, EqnG22, EqnSW2],\n i <- [0 .. np - 1],\n j <- [0 .. np - 1]\n ]\n where\n r2s = (r2project #>) <$> s\n r1sr = (r1derivR #>) <$> s\n r1su = (r1derivU #>) <$> s\n r1sv = (r1derivV #>) <$> s\n su = (derivU #>) <$> s\n sv = (derivV #>) <$> s\n suv = (derivUV #>) <$> s\n suu = (derivUU #>) <$> s\n svv = (derivVV #>) <$> s\n jacRow :: (Int, Int, Eqn) -> L.Vector a\n jacRow (i, j, eqn) =\n L.vjoin $\n [ let con :: Grid a -> Dual a\n der :: Grid a -> Dual a\n con x = Dual (x ! (i, j)) 0\n der x = Dual (x ! (i, j)) 1\n scon :: State (Grid a) -> State (Dual a)\n sder :: State (Grid a) -> State (Dual a)\n scon (State g q w) = State (con g) (con q) (con w)\n sder (State g q w) = case var of\n VarG -> State (der g) (con q) (con w)\n VarQ -> State (con g) (der q) (con w)\n VarW -> State (con g) (con q) (der w)\n in ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (sder s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp delta L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (sder r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp r2project L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (sder r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp r1derivR L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (sder r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp r1derivU L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (sder r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp r1derivV L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (sder su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivU L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (sder sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivV L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (sder suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivUV L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (sder suu)\n (scon svv)\n )\n `L.scale` (getOp derivUU L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (sder svv)\n )\n `L.scale` (getOp derivVV L.! (i * np + j))\n )\n | var <- [VarG, VarQ, VarW]\n ]\n\nop5 ::\n forall a.\n (L.Container L.Vector a, L.Field a, RealFloat a, U.Unbox a) =>\n Coord (Grid a) ->\n State (Grid a) ->\n Op a\nop5 (Coord u v) s =\n Op $\n L.fromRows\n [ jacRow (i, j, eqn)\n | eqn <- [EqnG01, EqnG22, EqnSW2, EqnG00, EqnG11],\n i <- [0 .. np - 1],\n j <- [0 .. np - 1]\n ]\n where\n r2s = (r2project #>) <$> s\n r1sr = (r1derivR #>) <$> s\n r1su = (r1derivU #>) <$> s\n r1sv = (r1derivV #>) <$> s\n su = (derivU #>) <$> s\n sv = (derivV #>) <$> s\n suv = (derivUV #>) <$> s\n suu = (derivUU #>) <$> s\n svv = (derivVV #>) <$> s\n jacRow :: (Int, Int, Eqn) -> L.Vector a\n jacRow (i, j, eqn) =\n L.vjoin $\n [ let con :: Grid a -> Dual a\n der :: Grid a -> Dual a\n con x = Dual (x ! (i, j)) 0\n der x = Dual (x ! (i, j)) 1\n scon :: State (Grid a) -> State (Dual a)\n sder :: State (Grid a) -> State (Dual a)\n scon (State g q w) = State (con g) (con q) (con w)\n sder (State g q w) = case var of\n VarG -> State (der g) (con q) (con w)\n VarQ -> State (con g) (der q) (con w)\n VarW -> State (con g) (con q) (der w)\n in ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (sder s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp delta L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (sder r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp r2project L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (sder r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp r1derivR L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (sder r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp r1derivU L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (sder r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp r1derivV L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (sder su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivU L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (sder sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivV L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (sder suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivUV L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (sder suu)\n (scon svv)\n )\n `L.scale` (getOp derivUU L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon r2s)\n (scon r1sr)\n (scon r1su)\n (scon r1sv)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (sder svv)\n )\n `L.scale` (getOp derivVV L.! (i * np + j))\n )\n | var <- [VarG, VarQ, VarW]\n ]\n\n--------------------------------------------------------------------------------\n\ngetTime :: IO Double\ngetTime = do\n t <- getCPUTime\n return $ fromInteger t / 1.0e+12\n\nmain0 :: IO ()\nmain0 =\n do\n putStrLn $ show $ gmaxabs $ coordU @Double\n putStrLn $ show $ gmaxabs $ coordV @Double\n putStrLn $ show $ gmaxabs $ coordR @Double\n putStrLn $ show $ gmaxabs $ coordR1 @Double\n putStrLn $ show $ omaxabs $ zproject @Double\n putStrLn $ show $ omaxabs $ r2project @Double\n putStrLn $ show $ omaxabs $ r1derivR @Double\n putStrLn $ show $ omaxabs $ r1derivU @Double\n putStrLn $ show $ omaxabs $ r1derivV @Double\n putStrLn $ show $ omaxabs $ derivU @Double\n putStrLn $ show $ omaxabs $ derivV @Double\n putStrLn $ show $ omaxabs $ derivUV @Double\n putStrLn $ show $ omaxabs $ derivUU @Double\n putStrLn $ show $ omaxabs $ derivVV @Double\n\nmain :: IO ()\nmain =\n do\n putStrLn \"Spherically Symmetric Scalar Field in double-Null coordinates\"\n let coords = Coord coordU (coordV @Double)\n let ini = State (gmap g guess) (gmap q guess) (gmap w guess)\n vars0 <- return (s2g ini)\n let done (n, vars) =\n let res = eqns coords (g2s vars)\n maxabsres = gmaxabs res\n in isNaN maxabsres\n || isInfinite maxabsres\n || maxabsres < 1.0e-12\n || n >= 5\n let iter (n, vars) = do\n let res = eqns coords (g2s vars)\n let res5 = eqns5 coords (g2s vars)\n t <- getTime\n putStrLn $\n (\"iter \" ++ show n)\n ++ (\" time \" ++ show (round t) ++ \" sec\")\n ++ (\" |res| \" ++ show (gmaxabs res))\n ++ (\" |res5| \" ++ show (gmaxabs res5))\n let jac = op coords (g2s vars)\n let dvars = solve jac res\n return (n + 1, vars ^-^ dvars)\n let done5 (n, vars) =\n let res5 = eqns5 coords (g2s vars)\n maxabsres5 = gmaxabs res5\n in isNaN maxabsres5\n || isInfinite maxabsres5\n || maxabsres5 < 1.0e-12\n || n >= 5\n let iter5 (n, vars) = do\n let res = eqns coords (g2s vars)\n let res5 = eqns5 coords (g2s vars)\n t <- getTime\n putStrLn $\n (\"iter \" ++ show n)\n ++ (\" time \" ++ show (round t) ++ \" sec\")\n ++ (\" |res| \" ++ show (gmaxabs res))\n ++ (\" |res5| \" ++ show (gmaxabs res5))\n let jac5 = op5 coords (g2s vars)\n let dvars = solveLS jac5 res5\n return (n + 1, vars ^-^ dvars)\n -- (n, vars) <- iterateUntilM done iter (0, vars0)\n (n, vars) <- iterateUntilM done5 iter5 (0, vars0)\n let res = eqns coords (g2s vars)\n let res5 = eqns5 coords (g2s vars)\n t <- getTime\n putStrLn $\n (\"iter \" ++ show n)\n ++ (\" time \" ++ show (round t) ++ \" sec\")\n ++ (\" |res| \" ++ show (gmaxabs res))\n ++ (\" |res5| \" ++ show (gmaxabs res5))\n putStrLn $ \"var.g \" ++ show (gmap approx $ g $ g2s vars)\n putStrLn $ \"var.q \" ++ show (gmap approx $ q $ g2s vars)\n putStrLn $ \"var.w \" ++ show (gmap approx $ w $ g2s vars)\n putStrLn $ \"res.G01 \" ++ show (gmap approx $ eqn1 EqnG01 coords (g2s vars))\n putStrLn $ \"res.G22 \" ++ show (gmap approx $ eqn1 EqnG22 coords (g2s vars))\n putStrLn $ \"res.SW2 \" ++ show (gmap approx $ eqn1 EqnSW2 coords (g2s vars))\n putStrLn $ \"res.G00 \" ++ show (gmap approx $ eqn1 EqnG00 coords (g2s vars))\n putStrLn $ \"res.G11 \" ++ show (gmap approx $ eqn1 EqnG11 coords (g2s vars))\n putStrLn $ \"S var.g \" ++ show (gmap approx $ inv vandermonde #> (g $ g2s vars))\n putStrLn $ \"S var.q \" ++ show (gmap approx $ inv vandermonde #> (q $ g2s vars))\n putStrLn $ \"S var.w \" ++ show (gmap approx $ inv vandermonde #> (w $ g2s vars))\n putStrLn $ \"S res.G01 \" ++ show (gmap approx $ inv vandermonde #> (eqn1 EqnG01 coords (g2s vars)))\n putStrLn $ \"S res.G22 \" ++ show (gmap approx $ inv vandermonde #> (eqn1 EqnG22 coords (g2s vars)))\n putStrLn $ \"S res.SW2 \" ++ show (gmap approx $ inv vandermonde #> (eqn1 EqnSW2 coords (g2s vars)))\n putStrLn $ \"S res.G00 \" ++ show (gmap approx $ inv vandermonde #> (eqn1 EqnG00 coords (g2s vars)))\n putStrLn $ \"S res.G11 \" ++ show (gmap approx $ inv vandermonde #> (eqn1 EqnG11 coords (g2s vars)))\n putStrLn \"Done.\"\n where\n approx :: RealFrac a => a -> a\n approx x = fromInteger (round (1.0e+10 * x)) / 1.0e+10\n", "meta": {"hexsha": "035e42ac814ff556b15b856745cb914aa972e36b", "size": 28764, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ScalarWave.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/ScalarWave.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/ScalarWave.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": 36.5954198473, "max_line_length": 177, "alphanum_fraction": 0.3188360451, "num_tokens": 7483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189143592727, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5026716210307496}} {"text": "{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE BangPatterns #-}\n\nmodule Main where\n\nimport Options.Applicative\nimport Data.Semigroup ((<>))\nimport Chart.Heatmap\nimport Control.Lens\nimport Control.Monad (forM_)\nimport Data.List (maximumBy)\nimport Data.Ord (comparing)\nimport Data.Colour.SRGB (sRGB, RGB(..))\nimport Data.Colour.RGBSpace.HSL (hsl)\nimport Data.Complex (magnitude, realPart, imagPart, Complex(..))\nimport Graphics.Rendering.Chart.Easy\nimport Graphics.Rendering.Chart.Backend.Cairo (toFile, FileOptions(..), FileFormat(..))\nimport Data.Array.CArray.Base (unsafeForeignPtrToCArray, toForeignPtr, CArray(..), ixmapWithIndP)\nimport Data.Fixed (mod')\nimport Math.FFT (dftRC)\nimport Numeric.Signal (analytic_signal, auto_correlation, deriv, Filterable)\nimport Data.Maybe (catMaybes)\nimport Sound.MIDI.File\nimport qualified Data.Vector.Storable as VS\nimport qualified Data.Vector as V\nimport qualified Sound.File.Sndfile as SF\nimport qualified Sound.File.Sndfile.Buffer.Vector as SFV\nimport qualified Sound.MIDI.File.Save as MS\nimport qualified Sound.MIDI.File.Event as ME\nimport qualified Sound.MIDI.Message.Channel as MC\nimport qualified Sound.MIDI.Message.Channel.Voice as MCV\nimport qualified Sound.MIDI.Message.Channel.Mode as MCM\nimport qualified Data.EventList.Relative.TimeBody as E\n\ntype Frequency = Double\ntype Amplitude = Double\ntype Step = Double\n\nmaxFrequency :: Double\nmaxFrequency = 7000\n\ndata NoteLetter = A\n | Ais\n | B\n | C\n | Cis\n | D\n | Dis\n | E\n | F\n | Fis\n | G\n | Gis\n deriving (Show, Eq)\n\ntype Octave = Int\n\ndata Note = Note NoteLetter Octave deriving (Show, Eq)\n\ngetBaseFreq :: NoteLetter -> Frequency\ngetBaseFreq A = 27.50\ngetBaseFreq Ais = 29.14\ngetBaseFreq B = 30.87\ngetBaseFreq C = 16.35\ngetBaseFreq Cis = 17.32\ngetBaseFreq D = 18.35\ngetBaseFreq Dis = 19.45\ngetBaseFreq E = 20.60\ngetBaseFreq F = 21.83\ngetBaseFreq Fis = 23.12\ngetBaseFreq G = 24.50\ngetBaseFreq Gis = 25.96\n\ngetFreq :: Note -> Frequency\ngetFreq (Note letter n) = getBaseFreq letter * (fromIntegral n + 1)\n\ngetNote :: Frequency -> Maybe Note\ngetNote freq\n | divisor A `mod'` 1 < 0.02 || divisor A `mod'` 1 > 0.98 = Just\n (Note A (findN freq A))\n | divisor Ais `mod'` 1 < 0.02 || divisor Ais `mod'` 1 > 0.98 = Just\n (Note Ais (findN freq Ais))\n | divisor B `mod'` 1 < 0.02 || divisor B `mod'` 1 > 0.98 = Just\n (Note B (findN freq B))\n | divisor C `mod'` 1 < 0.02 || divisor C `mod'` 1 > 0.98 = Just\n (Note C (findN freq C))\n | divisor Cis `mod'` 1 < 0.02 || divisor Cis `mod'` 1 > 0.98 = Just\n (Note Cis (findN freq Cis))\n | divisor D `mod'` 1 < 0.02 || divisor D `mod'` 1 > 0.98 = Just\n (Note D (findN freq D))\n | divisor Dis `mod'` 1 < 0.02 || divisor Dis `mod'` 1 > 0.98 = Just\n (Note Dis (findN freq Dis))\n | divisor E `mod'` 1 < 0.02 || divisor E `mod'` 1 > 0.98 = Just\n (Note E (findN freq E))\n | divisor F `mod'` 1 < 0.02 || divisor F `mod'` 1 > 0.98 = Just\n (Note F (findN freq F))\n | divisor Fis `mod'` 1 < 0.02 || divisor Fis `mod'` 1 > 0.98 = Just\n (Note Fis (findN freq Fis))\n | divisor G `mod'` 1 < 0.02 || divisor G `mod'` 1 > 0.98 = Just\n (Note G (findN freq G))\n | divisor Gis `mod'` 1 < 0.02 || divisor Gis `mod'` 1 > 0.98 = Just\n (Note Gis (findN freq Gis))\n | otherwise = Nothing\n where\n findN f n = round $ logBase 2 (f / getBaseFreq n) :: Int\n divisor note = logBase 2 (freq / getBaseFreq note)\n\n-- samples = N = number of samples\n-- n = sample number\nhannWindow :: Integer -> Integer -> Double\nhannWindow samples n =\n 0.5 * (1 - cos (2 * pi * fromIntegral n / (fromIntegral samples - 1)))\n\nsinFunc :: Double -> Double -> Double -> Double -> Double\nsinFunc samples cycle amplitude p =\n -amplitude * sin (2 * pi * cycle * p / samples)\n\ncosFunc :: Double -> Double -> Double -> Double -> Double\ncosFunc samples cycle amplitude p =\n amplitude * cos (2 * pi * cycle * p / samples)\n\nperformFFT :: VS.Vector Double -> Int -> IO (VS.Vector (Complex Double))\nperformFFT vector intSamples = do\n let (vec, x1, x2) = VS.unsafeToForeignPtr $ VS.take intSamples vector\n carray <- unsafeForeignPtrToCArray vec (x1, x2)\n let fft = dftRC carray\n let (len, fftptr) = toForeignPtr fft\n return (VS.unsafeFromForeignPtr fftptr 0 len)\n\n-- |Filter an array of maxima by partioning fftabs into bins of 100 elements, then finding the\n-- largest value in that bin.\n-- peaks are the list of indexes of the maxima.\nfilterMaxima :: V.Vector Int -> V.Vector Double -> V.Vector Int\nfilterMaxima peaks fftabs\n | V.null peaks = V.empty\n | otherwise = V.filter (> -1) $ V.map\n (\\i ->\n let\n section = V.map\n (\\x -> (x, fftabs V.! x))\n (V.filter (\\x -> x < V.length fftabs && x >= i && x < i + binSize)\n peaks\n )\n in if V.null section\n then -1\n else fst $ V.maximumBy (comparing snd)\n -- list of (index, magnitude)\n section\n )\n (V.fromList [0, binSize .. V.last peaks])\n where binSize = 100\n\n-- | Find the maxima from fftabs by finding all points where the left and right points\n-- are less than the current point.\nfindMaxima :: V.Vector Double -> V.Vector Int\nfindMaxima fftabs = V.filter\n (\\x -> (diffs' V.! x) > 0 && (diffs' V.! (x + 1)) < 0)\n (V.fromList [1 .. (V.length diffs' - 2)])\n where\n diff f x = f x - f (x - 1)\n diffs' = V.map (diff (fftabs V.!)) (V.fromList [1 .. (V.length fftabs - 1)])\n\n-- | Find maxima by finding points where that point is the maximum in it's neighbourhood.\nfindMaxima2 :: Filterable a => Int -> V.Vector a -> V.Vector (Int, a)\nfindMaxima2 radius v =\n V.filter (\\(i, x) -> x == V.maximum (neighbours i))\n $ V.imap (\\i x -> (i, x)) v\n where neighbours x0 = V.ifilter (\\i _ -> abs (x0 - i) <= radius) v\n\nfindSignificantNotesForSection\n :: Int -> Int -> V.Vector (Complex Double) -> [(Frequency, Double)]\nfindSignificantNotesForSection sampleRate samples fftSection = fmap\n (\\cycle ->\n ( fromIntegral cycle * fromIntegral sampleRate / fromIntegral samples\n , fftabs V.! cycle\n )\n )\n maxima'\n where\n fftabs = V.map magnitude fftSection :: V.Vector Double\n peaks = findMaxima fftabs\n peaks' = filterMaxima peaks fftabs\n maxima = V.toList peaks' -- tricky: the cycles returned is the cycles+1\n maxima' = filter (\\value -> fftabs V.! value > 20) maxima -- Find 'large' maxima\n\nmidiPitch :: Note -> Int\nmidiPitch (Note letter n) =\n round $ 12 * logBase 2 (((2 ^ n) * getBaseFreq letter) / 440) + 69\n\n-- | Find notes that standout in each stft section.\nfindSignificantNotes\n :: Int -> Int -> [(Step, [Complex Double])] -> String -> IO ()\nfindSignificantNotes sampleRate samples stft filePrefix = do\n notes <-\n mapM\n (\\(step, fft) -> do\n let freqs =\n findSignificantNotesForSection sampleRate samples (V.fromList fft)\n let notes = fmap (\\(f, _) -> getNote f)\n (filter (\\(f, _) -> f < maxFrequency) freqs)\n return $ map (\\note -> (step, note)) $ catMaybes notes\n )\n stft :: IO [[(Step, Note)]]\n\n print $ map (map (\\(s, note) -> (s, note, midiPitch note))) notes\n\n let\n sections = map\n (foldl\n (\\acc (step, note) -> E.append\n acc\n (E.singleton\n (toElapsedTime 0)\n (ME.MIDIEvent\n (MC.Cons\n (MC.toChannel 1)\n (MC.Voice\n (MCV.NoteOn (MC.toPitch (midiPitch note)) (MC.toVelocity 20))\n )\n )\n )\n )\n )\n E.empty\n )\n notes\n\n let\n t =\n E.append\n (foldl (\\acc section -> E.append acc (E.delay 100 section))\n E.empty\n sections\n )\n $ E.singleton\n (toElapsedTime 100)\n (ME.MIDIEvent (MC.Cons (MC.toChannel 1) (MC.Mode MCM.AllNotesOff)))\n\n let midi = Cons Serial (Ticks 120) [t] :: T\n\n MS.toFile (filePrefix ++ \".midi\") midi\n\n-- toFile def{_fo_format=SVG} \"diff.svg\" $ do\n-- layout_title .= \"First derivative\"\n-- plot (points \"diff\" $ zip fftx (VS.toList fftabs))\n\n-- print $ V.map (\\x -> (x, fftabs VS.! x)) peaks'\n --toFile def{_fo_format=SVG} \"diff2.svg\" $ do\n -- layout_title .= \"Second derivative\"\n -- plot (points \"diff\" $ zip fftx diffs'')\n\n --let sinAmplitudes = take 500 $ fmap (\\(cycle, _) -> (fromIntegral cycle, fftimg VS.! cycle / fromIntegral (samples `div` 2))) maxima :: [(Double, Double)]\n --let cosAmplitudes = take 500 $ fmap (\\(cycle, _) -> (fromIntegral cycle, fftreals VS.! cycle / fromIntegral (samples `div` 2))) maxima :: [(Double, Double)]\n\n --print \"sin amps\"\n --print sinAmplitudes\n --print \"cos amps\"\n --print cosAmplitudes\n\n --toFile def{_fo_format=SVG} \"sine2.svg\" $ do\n -- layout_title .= \"curve\"\n -- plot (line \"data\" [zip x y])\n -- plot\n -- (line \"fit\"\n -- [zip\n -- x\n -- (fmap\n -- (\\p -> foldr (\\(cycle, amplitude) total -> total + sinFunc (fromIntegral samples) cycle amplitude p) 0 sinAmplitudes +\n -- foldr (\\(cycle, amplitude) total -> total + cosFunc (fromIntegral samples) cycle amplitude p) 0 cosAmplitudes) x)])\n\n --let signal = VS.take samples $ analytic_signal vector\n --let signalReal = VS.toList $ VS.map realPart signal\n --let signalImag = VS.toList $ VS.map imagPart signal\n ----print $ VS.length signal\n --toFile def{_fo_format=SVG} \"signal.svg\" $ do\n -- layout_title .= \"Hibert transform derivative\"\n -- plot (line \"Hilbert transform\" [zip x (VS.toList $ VS.map imagPart signal)])\n -- plot (line \"Original signal\" [zip x intList])\n -- plot (line \"Analytic signal\" [zip x $ VS.toList (VS.map magnitude signal)])\n\nautoCorrelate :: Filterable a => VS.Vector a -> Int -> IO ()\nautoCorrelate vector sampleRate = do\n let result = auto_correlation 1000 vector\n let y = map realToFrac $ VS.toList result :: [Double]\n --let values = [zip (map (\\x -> x / fromIntegral sampleRate) [1..]) y] :: [[(Double, Double)]]\n let values = [zip [1 ..] y] :: [[(Double, Double)]]\n toFile def { _fo_format = SVG } \"autocorrelation.svg\" $ do\n layout_title .= \"auto correlation\"\n plot (line \"\" values)\n\n let localMaxima = findMaxima2 10 (VS.convert result)\n print $ V.map (\\(i, x) -> (i, realToFrac x)) localMaxima\n print $ V.imap\n (\\j (i, _) -> if j == 0 then j else i - fst (localMaxima V.! (j - 1)))\n localMaxima\n print $ fromIntegral sampleRate / fromIntegral\n (V.maximum\n (V.imap\n (\\j (i, _) -> if j == 0 then j else i - fst (localMaxima V.! (j - 1)))\n localMaxima\n )\n )\n\ngraphSignal :: Filterable a => VS.Vector a -> Int -> IO ()\ngraphSignal vector sampleRate = do\n let intList = map realToFrac $ VS.toList vector :: [Double]\n let y = intList\n let x = map (\\x -> x / fromIntegral sampleRate) [1 .. 200] :: [Double]\n toFile def { _fo_format = SVG } \"signal.svg\" $ do\n layout_x_axis . laxis_title .= \"Elapsed time (s)\"\n layout_title .= \"signal curve\"\n plot (line \"\" [zip x y])\n\ngraphFFTSignal :: VS.Vector (Complex Double) -> Int -> Int -> IO ()\ngraphFFTSignal fftvec samples sampleRate = do\n let fftreals = VS.toList $ VS.map realPart fftvec :: [Double]\n let fftimg = VS.toList $ VS.map imagPart fftvec :: [Double]\n let fftabs = VS.toList $ VS.map magnitude fftvec :: [Double]\n let fftx =\n map (\\x -> fromIntegral (x * sampleRate) / fromIntegral samples)\n [0 .. 1000] :: [Double]\n toFile def { _fo_format = SVG } \"fft.svg\" $ do\n layout_title .= \"fft curve\"\n layout_x_axis . laxis_title .= \"Frequency (Hz)\"\n plot (points \"abs\" $ zip fftx fftabs)\n plot (points \"real\" $ zip fftx fftreals)\n plot (points \"imaginary\" $ zip fftx fftimg)\n\ndata Options = Options {\n sourceFile :: String,\n stepWidth :: Int\n}\n\nargs :: ParserInfo Options\nargs = info\n (Options <$> strOption (long \"src\" <> metavar \"SOURCE\") <*> option\n auto\n (long \"step-width\" <> metavar \"STEP_WIDTH\" <> value 10000 <> showDefault)\n )\n (fullDesc <> progDesc \"Desc\" <> header \"test\")\n\nmain :: IO ()\nmain = do\n opts <- execParser args\n (i, content) <-\n SF.readFile (sourceFile opts) :: IO (SF.Info, Maybe (SFV.Buffer Double))\n let sampleRate = SF.samplerate i\n let samples = SF.frames i * SF.channels i\n print samples\n print i\n let v = fmap SFV.fromBuffer content\n case v of\n Nothing -> print \"Nothing!\"\n Just vector -> do\n graphSignal vector sampleRate\n\n -- Run FFT on whole dataset and plot the result\n fftvec <- performFFT vector samples\n graphFFTSignal fftvec samples sampleRate\n findSignificantNotes sampleRate samples [(0, VS.toList fftvec)] \"fft\"\n\n -- get auto correlation\n autoCorrelate vector sampleRate\n\n -- plot histogram\n let (vec, x1, x2) = VS.unsafeToForeignPtr vector\n carray <- unsafeForeignPtrToCArray vec (x1, x2)\n --let stepWidth = fromIntegral samples :: Integer\n let stepWidth = 5000 :: Integer\n print $ \"Step width: \" ++ show stepWidth\n let cutSamples =\n (samples `div` fromIntegral stepWidth) * fromIntegral stepWidth :: Int\n\n -- windows of size stepWidth\n let stft =\n fmap (stftSection carray cutSamples stepWidth)\n [0, stepWidth `div` 2 .. fromIntegral cutSamples] :: [ ( Step\n , [Complex Double]\n )\n ]\n\n findSignificantNotes sampleRate cutSamples stft \"stft\"\n\n -- (window start, fft for window)\n let plots' =\n concatMap\n (spectrogramIntensity (fromIntegral cutSamples) sampleRate)\n stft :: [(Step, Frequency, Amplitude)]\n\n let stftData = generateStftData (fromIntegral stepWidth) plots'\n let stftData' = filter (\\((_, _), (_, _), z) -> z > 1) stftData\n toFile def { _fo_format = PNG } \"stft.png\" $ do\n layout_title .= \"curve\"\n plot\n (liftEC $ do\n plot_rect_title .= \"title\"\n plot_rect_style .= \\amp ->\n let RGB a b c = hsl ((1 - amp) * 240) 1 (amp * 0.6)\n in solidFillStyle (opaque $ sRGB a b c)\n plot_rect_values .= stftData'\n )\n\n return ()\n\n-- convert to plottable set of values\ngenerateStftData\n :: Step\n -> [(Step, Frequency, Amplitude)]\n -> [((Double, Double), (Double, Double), Amplitude)]\ngenerateStftData windowSize = map (generateColumn windowSize)\n\n-- column in spectrogram\ngenerateColumn\n :: Step\n -> (Step, Frequency, Amplitude)\n -> ((Double, Double), (Double, Double), Amplitude)\ngenerateColumn windowSize (step, freq, amp) =\n ((step, windowSize + step), (freq, freq + 1), amp)\n\nspectrogramIntensity\n :: Double -> Int -> (Step, [Complex Double]) -> [(Step, Frequency, Amplitude)]\nspectrogramIntensity totalSamples sampleRate (step, fft) =\n let rate = fromIntegral sampleRate / totalSamples\n in filter\n (\\(_, f, _) -> f < 4000)\n (map (\\(cycle, x) -> (step, cycle * rate, magnitude (x + 0) ** 2))\n (zip [0 ..] fft)\n )\n\nftSignals :: Double -> [Complex Double] -> [Double] -> [Double]\nftSignals totalSamples fft = fmap\n (\\x ->\n foldr\n (\\(cycle, amplitude) total ->\n total + sinFunc totalSamples cycle amplitude x\n )\n 0\n sinAmplitudes\n + foldr\n (\\(cycle, amplitude) total ->\n total + cosFunc totalSamples cycle amplitude x\n )\n 0\n cosAmplitudes\n )\n where\n significantSignals = filter (\\x -> magnitude x > 5) fft\n cycles = zip [0 ..] significantSignals\n sinAmplitudes =\n fmap\n (\\(cycle, signal) ->\n (fromIntegral cycle, realPart signal / (totalSamples / 2.0))\n )\n cycles :: [(Double, Double)]\n cosAmplitudes =\n fmap\n (\\(cycle, signal) ->\n (fromIntegral cycle, imagPart signal / (totalSamples / 2.0))\n )\n cycles :: [(Double, Double)]\n\n-- | Apply window function to the set of samples\nwindowedSection\n :: CArray Int Double -> Int -> Integer -> Integer -> CArray Int Double\nwindowedSection data_ totalSamples n stepWidth = ixmapWithIndP\n (0, totalSamples)\n id\n (\\_ x i' -> if i' < fromIntegral n || i' >= fromIntegral (n + stepWidth)\n then 0\n else x * hannWindow (fromIntegral stepWidth) (fromIntegral i' - n)\n )\n data_\n\n-- | n = start of step sample number\nstftSection\n :: CArray Int Double -> Int -> Integer -> Integer -> (Step, [Complex Double])\nstftSection !completeSample totalSamples stepWidth n =\n (fromIntegral n, VS.toList $ VS.unsafeFromForeignPtr fftptr 0 len)\n where\n fft = dftRC (windowedSection completeSample totalSamples n stepWidth)\n (len, fftptr) = toForeignPtr fft\n", "meta": {"hexsha": "e074f7752c0451f5371a014a9ba1c40692764695", "size": 16822, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "Deadleg/music-listener", "max_stars_repo_head_hexsha": "d61fa6488238fecc559ca1a08295b98d0586db83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "Deadleg/music-listener", "max_issues_repo_head_hexsha": "d61fa6488238fecc559ca1a08295b98d0586db83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "Deadleg/music-listener", "max_forks_repo_head_hexsha": "d61fa6488238fecc559ca1a08295b98d0586db83", "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.9004149378, "max_line_length": 162, "alphanum_fraction": 0.6102128165, "num_tokens": 4928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5016014273495156}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n-- | Fourier amplitude sensitivity test, a quasi-monte carlo method\n--\n-- does not yet play well with \"ErrorProp.MonteCarlo\", though a function\n-- like 'ErrorProp.MonteCarlo.sample' should be straightforward to\n-- implement. However, 'fast' provides the core of such a function\nmodule ErrorProp.QuasiMC where\n\nimport qualified Data.Map as M\nimport Math.Polynomial\nimport Math.Polynomial.Bernoulli\nimport qualified Data.Vector.Unboxed as V\nimport qualified Data.Vector.Generic as VG\nimport Data.List\n\nimport Data.Numbers.Primes\nimport Data.VectorSpace\n\nimport ErrorProp.QuasiMC.Cukier (cukierOmegas)\n\nimport Statistics.Sample\nimport Data.Maybe\n\n\nimport ErrorProp.MonteCarlo\nimport ErrorProp.Common\n\n\n\nf1 alpha2 = constPoly 1 ^+^ ((-1)^(1 + alpha2 `mod` 2) * (2*pi)^(2*alpha2)) *^ bx\n where bx = bernoulliPoly !! (2*alpha2)\n\n-- the explicit equations for F2,F4,F6 (equation 4.14,15,16) are correct\nprop_f11 x = f11 x ~= f1 1 `evalPoly` x\n where f11 x = 1 + 2 * pi^2 * (x^2 - x + 1/6)\n\nprop_f12 x = f12 x ~= f1 2 `evalPoly` x\n where f12 x = 1 + pi^4/45 * (1 - 30* x^2 * (1-x)^2)\n\nprop_f13 x = f13 x ~= f1 3 `evalPoly` x\n where f13 x = 1 + (2*pi^6/945) * (1 - 21*x^2 + 105*x^4 -126*x^5 + 42*x^6)\n\nx ~= y = (2 * abs(x-y) / (1 + abs x + abs y)) < (1e-8 :: Double)\ninfix 4 ~=\n\n-- eqn 4.10. Is the function integrated to generate the \"best\"\n-- lattice points\nf2 alpha2 xs = V.product $ V.map (f1 alpha2 `evalPoly`) xs\n\n-- | Korbov's construction for good lattice points. Is an LCG\n--\n-- 4.32\nkorbov l n s = V.iterateN s (\\p -> (p * l) `mod` n) 1\n\n-- | try all values of L up to n/2\nkorbovLExhaustive alpha2 n s =\n head $\n sort [ (abs (r1-1) :: Double, l)\n | l <- [1 .. n `div` 2 ],\n let r1 = rank1 (korbov l n s) n (V.replicate s 0) (f2 alpha2) ]\n\n-- | assume L has k prime factors. Provides candidate L values,\n-- and the error in the integral used to decide that L is the best.\n-- The error is absolute and relative, since the target function\n-- integrates to 1.\nkorbovLCompositeK\n :: Int -- ^ alpha/2, roughness of the function being integrated\n -> Int -- ^ k\n -> Int -- ^ n, number of points in the quadrature\n -> Int -- ^ s, dimension\n -> [(Double, Int)] -- ^ (error, best l)\nkorbovLCompositeK alpha2 k n s =\n sort [ (abs (rankL l - 1) :: Double, l)\n | l <- go k ps 1 ]\n where \n rankL l = rank1 (korbov l n s) n (V.replicate s 0) (f2 alpha2)\n go 0 _ n = [n]\n go k ps1 n = do\n q : ps1' @ (_:_) <- tails ps1\n go (k-1) ps1' (n*q)\n \n ps = takeWhile ( < round ( (fromIntegral n / 2) ** (1/fromIntegral k)))\n primes\n\n{- | rank1 shifted lattice rule\n\nGiven\n\n> f :: [0,1)^s -> R\n\ncalculate\n\n> Q(Z,N,C)f = (1/N) sum_j=0^N f { j z/N + c }\n\nis an approximation to the integral of @f@ (@If@) over that region.\n\nequation 4.42 Sloan&Joe 1994 pg 89\n\n\nIf C is multivariant uniform [0,1)^s, we can do a CI for the actual\nintegral\n\nP( |Q - I| < sigma v) >= 1 - (1/v^2)\n\nwith sigma^2 estimated by sum_k=1^q (Q - Qbar)^2 / ( q (q-1))\n\nis unbiased. Quantiles are biased (Lemieux 2008). Bootstrap/jacknife resample to estimate bias.\n\n\ntrapezoidal / rectangle rule is good for the periodic integral here,\nbut possibly try \"GA Evans, JR Webster 1999\"\n\n\n-}\nrank1 :: (Integral i, RealFrac a, VG.Vector v a, VG.Vector vi i,\n VG.Vector vi a)\n => vi i -- ^ z\n -> Int -- ^ N\n -> v a -- ^ c\n -> (v a -> a) -- ^ f\n -> a\nrank1 z n c f = go 0 0\n where\n zn = VG.convert $ VG.map (\\zi -> fromIntegral zi / fromIntegral n) z\n\n go !j !accum\n | j == VG.length zn = accum\n | otherwise = go (j+1) $ f $ VG.zipWith (+) c\n $ VG.map (\\zni -> fracPart $ fromIntegral j*zni) zn \n\n{- |\n\n>>> map fracPart [12.3, -2.5]\n[0.3, 0.5]\n\n-}\nfracPart x = x - fromInteger (floor x)\n\n\n-- | fourier amplitude sensitivity test\nfast :: \n (RealFrac b, VG.Vector V.Vector b) =>\n V.Vector Int -- ^ N incommensurate frequencies (see 'korbov', 'cukierOmegas', or others)\n -> (V.Vector b -> Double) -- ^ a function of N variables which will be sampled on @[0, 1)^N@\n -> V.Vector Double -- ^ fraction of the total variance attributed to the i'th variable\nfast omegas f =\n let omegaMax = VG.maximum omegas\n q = omegaMax\n\n xj k = VG.map (\\w -> fracPart $ fromIntegral (w*k) / fromIntegral (2*q+1)) omegas\n sks = V.enumFromTo (-q) q\n fks = VG.map (f . xj) sks\n\n withK k = VG.map (\\w -> mean\n $ VG.zipWith (\\s f -> f * k (w*s)) sks fks)\n omegas\n\n nq = fromIntegral (2*q+1)\n\n a i = withK (cos . (*(2*i*pi/nq)) . fromIntegral)\n b i = withK (sin . (*(2*i*pi/nq)) . fromIntegral)\n\n vjs = foldl1 (V.zipWith (+))\n $ map (V.map (^2))\n [ if odd j then b fij else a fij\n | j <- [1 .. 2],\n let fij = fromIntegral j ]\n\n -- normalizeFac = 2 / variance fks -- XXX the\n -- correct normalization should be some analytical\n -- expression... like above, not the value below\n normalizeFac = recip $ V.sum vjs\n\n in V.map (*normalizeFac) vjs\n\nfastKi s np k =\n let n = primes !! np\n (_, l) = korbovLExhaustive 1 n s\n omegas = korbov l n s\n\n in fast omegas (\\v -> v V.! k)\n\nfastKis np s = [ (k,fastKi s np k) | k <- [0 .. s-1]]\n{- properties.\n\n> ki k = fast omegas (\\x -> x V.! k)\n\n> ki k V.! j == 1 if k==j else 0\n\n-}\n\n-- | `pickNP err s` uses 'fastKis' to pick the parameter np, such that the\n-- value that should be 1 is within err of 1, for a problem of dimension s\npickNP err s = head [ np\n | np <- [ 2 .. ],\n all ok (fastKis np s) ]\n where ok (i, v) = abs (1 - v V.! i) < err\n\nsampleQMC :: Double -- ^ error tolerance (see 'pickNP')\n -> MV Double\n -> [(String, Double)] -- variable name, fraction of the total variance\nsampleQMC err mv =\n let n = wheelSieve 5 !! pickNP err s\n (_, l) = korbovLExhaustive 1 n s\n omegas = korbov l n s\n s = M.size (mv_vars mv)\n\n f v = mv_sample mv (updateMV v (mv_vars mv))\n in M.keys (mv_vars mv) `zip` VG.toList (fast omegas f)\n\nupdateMV :: (Floating b, V.Unbox b) => V.Vector b -> M.Map String (Maybe b) -> M.Map String b\nupdateMV v m = snd $ M.mapAccum (\\ n e -> (n+1, fromMaybe 1 e * toUnitVar (v V.! n))) 0 m\n where \n toUnitVar x = sqrt 12 * (x - 0.5)\n", "meta": {"hexsha": "1c6663c351e441edebaac13b272abcc04f3e65da", "size": 6365, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "ErrorProp/QuasiMC.hs", "max_stars_repo_name": "aavogt/ErrorProp", "max_stars_repo_head_hexsha": "1bc3d16cee6c05718b56446c4816e35124f79b38", "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": "ErrorProp/QuasiMC.hs", "max_issues_repo_name": "aavogt/ErrorProp", "max_issues_repo_head_hexsha": "1bc3d16cee6c05718b56446c4816e35124f79b38", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ErrorProp/QuasiMC.hs", "max_forks_repo_name": "aavogt/ErrorProp", "max_forks_repo_head_hexsha": "1bc3d16cee6c05718b56446c4816e35124f79b38", "max_forks_repo_licenses": ["BSD-3-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.4675925926, "max_line_length": 95, "alphanum_fraction": 0.5921445405, "num_tokens": 2144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624738835051, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5014016537473776}} {"text": "{-# LANGUAGE PartialTypeSignatures, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -Wno-orphans -funbox-strict-fields #-}\n-- | Provides @'Matrix'@ and @'MMatrix'@ instances for\n-- @'LA.Matrix'@ type of @hmatrix@ package.\nmodule Algebra.Matrix.HMatrix (STMatrix) where\nimport Algebra.Matrix.Generic\nimport Algebra.Matrix.Generic.Mutable (MMatrix (..))\nimport Algebra.Prelude.Core\nimport Control.Monad (forM_)\nimport Control.Monad.Primitive\nimport qualified Data.Coerce as DC\nimport qualified Data.Vector.Storable as SV\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Numeric.LinearAlgebra.Devel as LA\n\ntype instance Mutable LA.Matrix = STMatrix\ntype instance Row LA.Matrix = LA.Vector\ntype instance Column LA.Matrix = LA.Vector\ntype instance Row STMatrix = LA.Vector\ntype instance Column STMatrix = LA.Vector\n\n-- | Wrapper type for @hmatrix@'s @'LA.STMatrix'@.\ndata STMatrix s a = STMat { stmRows :: !Int\n , stmCols :: !Int\n , unwrapSTM :: LA.STMatrix s a\n }\n\ninstance (Num a, LA.Container LA.Matrix a) => Matrix LA.Matrix (WrapNum a) where\n basicRowCount = LA.rows\n basicColumnCount = LA.cols\n unsafeFromRows rs = DC.coerce $ LA.fromRows (DC.coerce rs :: [LA.Vector a])\n unsafeFromColumns cs = DC.coerce $ LA.fromColumns (DC.coerce cs :: [LA.Vector a])\n basicUnsafeIndexM m i j =\n return $ WrapNum $ (DC.coerce m :: LA.Matrix a) `LA.atIndex` (i, j)\n unsafeFreeze = stToPrim . LA.unsafeFreezeMatrix . unwrapSTM\n unsafeThaw m = stToPrim $ STMat (LA.rows m) (LA.cols m) <$> LA.unsafeThawMatrix m\n basicUnsafeGetRowM m i = return $ DC.coerce $ getRowLA i (DC.coerce m :: LA.Matrix a)\n basicUnsafeGetColumnM m i =\n return $ DC.coerce $ head $ LA.toColumns (DC.coerce m LA.¿ [i] :: LA.Matrix a)\n unsafeGenerate w h f =\n DC.coerce $\n LA.fromRows [ SV.generate w $ \\j -> unwrapNum $ f i j\n | i <- [0..h - 1]\n ]\n\ninstance (Integral a, LA.Container LA.Matrix a) => Matrix LA.Matrix (WrapIntegral a) where\n basicRowCount = LA.rows\n basicColumnCount = LA.cols\n unsafeFromRows rs = DC.coerce $ LA.fromRows (DC.coerce rs :: [LA.Vector a])\n unsafeFromColumns cs = DC.coerce $ LA.fromColumns (DC.coerce cs :: [LA.Vector a])\n basicUnsafeIndexM m i j =\n return $ WrapIntegral $ (DC.coerce m :: LA.Matrix a) `LA.atIndex` (i, j)\n unsafeFreeze = stToPrim . LA.unsafeFreezeMatrix . unwrapSTM\n unsafeThaw m = stToPrim $ STMat (LA.rows m) (LA.cols m) <$> LA.unsafeThawMatrix m\n basicUnsafeGetRowM m i = return $ DC.coerce $ getRowLA i (DC.coerce m :: LA.Matrix a)\n basicUnsafeGetColumnM m i =\n return $ DC.coerce $ head $ LA.toColumns (DC.coerce m LA.¿ [i] :: LA.Matrix a)\n unsafeGenerate w h f =\n DC.coerce $\n LA.fromRows [ SV.generate w $ \\j -> unwrapIntegral $ f i j\n | i <- [0..h - 1]\n ]\n\ninstance (Fractional a, LA.Container LA.Matrix a) => Matrix LA.Matrix (WrapFractional a) where\n basicRowCount = LA.rows\n basicColumnCount = LA.cols\n unsafeFromRows rs = DC.coerce $ LA.fromRows (DC.coerce rs :: [LA.Vector a])\n unsafeFromColumns cs = DC.coerce $ LA.fromColumns (DC.coerce cs :: [LA.Vector a])\n basicUnsafeIndexM m i j =\n return $ WrapFractional $ (DC.coerce m :: LA.Matrix a) `LA.atIndex` (i, j)\n unsafeFreeze = stToPrim . LA.unsafeFreezeMatrix . unwrapSTM\n unsafeThaw m = stToPrim $ STMat (LA.rows m) (LA.cols m) <$> LA.unsafeThawMatrix m\n basicUnsafeGetRowM m i = return $ DC.coerce $ getRowLA i (DC.coerce m :: LA.Matrix a)\n basicUnsafeGetColumnM m i =\n return $ DC.coerce $ head $ LA.toColumns (DC.coerce m LA.¿ [i] :: LA.Matrix a)\n unsafeGenerate w h f =\n DC.coerce $\n LA.fromRows [ SV.generate w $ \\j -> unwrapFractional $ f i j\n | i <- [0..h - 1]\n ]\n\ngetRowLA :: LA.Element t => Int -> LA.Matrix t -> LA.Vector t\ngetRowLA i m = head $ LA.toRows $ m LA.? [i]\ngetColLA :: LA.Element t => Int -> LA.Matrix t -> LA.Vector t\ngetColLA i m = head $ LA.toColumns $ m LA.¿ [i]\n\nunwrapSTMNum :: STMatrix s (WrapNum a) -> LA.STMatrix s a\nunwrapSTMNum = DC.coerce . unwrapSTM\n{-# INLINE unwrapSTMNum #-}\n\ncastSTMatrixNum :: LA.STMatrix s (WrapNum a) -> LA.STMatrix s a\ncastSTMatrixNum = DC.coerce\n{-# INLINE castSTMatrixNum #-}\n\ninstance (Num a, LA.Container LA.Matrix a) => MMatrix STMatrix (WrapNum a) where\n basicUnsafeNew n m = stToPrim $ STMat n m <$> LA.newMatrix 0 n m\n basicInitialise _ = return ()\n basicRowCount = stmRows\n basicColumnCount = stmCols\n unsafeGetRow i m =\n stToPrim $ DC.coerce . getRowLA i <$> LA.unsafeFreezeMatrix (unwrapSTMNum m)\n unsafeGetColumn i m = stToPrim $ DC.coerce . getColLA i <$> LA.unsafeFreezeMatrix (unwrapSTMNum m)\n unsafeFill n m a = stToPrim $ STMat n m <$> LA.newMatrix a n m\n unsafeFromRow r = stToPrim $ STMat 1 (SV.length r) <$> LA.unsafeThawMatrix (LA.asRow r)\n unsafeFromRows rs = stToPrim $ do\n let m = LA.fromRows (DC.coerce rs :: [LA.Vector a])\n STMat (LA.rows m) (LA.cols m) . DC.coerce <$> LA.unsafeThawMatrix m\n unsafeFromColumn c = stToPrim $ STMat (SV.length c) 1 <$> LA.unsafeThawMatrix (LA.asColumn c)\n unsafeFromColumns rs = stToPrim $ do\n let m = LA.fromColumns (DC.coerce rs :: [LA.Vector a])\n STMat (LA.rows m) (LA.cols m) . DC.coerce <$> LA.unsafeThawMatrix m\n unsafeCopy (STMat r c m) (STMat _ _ m') = stToPrim $ do\n m0 <- LA.unsafeFreezeMatrix m'\n LA.setMatrix (DC.coerce m :: LA.STMatrix w a) r c (DC.coerce m0 :: LA.Matrix a)\n unsafeRead (STMat _ _ m) i j = stToPrim $ LA.readMatrix m i j\n unsafeWrite (STMat _ _ m) i j x = stToPrim $ LA.writeMatrix m i j x\n basicSet (STMat r c m) x = stToPrim $ LA.modifyMatrix m r c $ const x\n basicUnsafeSwapRows (STMat _ _ m) i j =\n stToPrim $ LA.rowOper (LA.SWAP i j LA.AllCols) $ castSTMatrixNum m\n unsafeScaleRow (STMat _ _ m) i c =\n stToPrim $ LA.rowOper (LA.SCAL (unwrapNum c) (LA.Row i) LA.AllCols) $ castSTMatrixNum m\n basicUnsafeIMapRowM (STMat _ c m) i f = forM_ [0..c-1] $ \\j ->\n stToPrim . LA.writeMatrix m i j =<< f j =<< stToPrim (LA.readMatrix m i j)\n toRows (STMat _ _ m) =\n stToPrim $ DC.coerce . LA.toRows <$> LA.unsafeFreezeMatrix (castSTMatrixNum m)\n toColumns (STMat _ _ m) =\n stToPrim $ DC.coerce . LA.toColumns <$> LA.unsafeFreezeMatrix (castSTMatrixNum m)\n\nunwrapSTMFractional :: STMatrix s (WrapFractional a) -> LA.STMatrix s a\nunwrapSTMFractional = DC.coerce . unwrapSTM\n{-# INLINE unwrapSTMFractional #-}\n\ncastSTMatrixFractional :: LA.STMatrix s (WrapFractional a) -> LA.STMatrix s a\ncastSTMatrixFractional = DC.coerce\n{-# INLINE castSTMatrixFractional #-}\n\ninstance (Fractional a, LA.Container LA.Matrix a) => MMatrix STMatrix (WrapFractional a) where\n basicUnsafeNew n m = stToPrim $ STMat n m <$> LA.newMatrix 0 n m\n basicInitialise _ = return ()\n basicRowCount = stmRows\n basicColumnCount = stmCols\n unsafeGetRow i m =\n stToPrim $ DC.coerce . getRowLA i <$> LA.unsafeFreezeMatrix (unwrapSTMFractional m)\n unsafeGetColumn i m = stToPrim $ DC.coerce . getColLA i <$> LA.unsafeFreezeMatrix (unwrapSTMFractional m)\n unsafeFill n m a = stToPrim $ STMat n m <$> LA.newMatrix a n m\n unsafeFromRow r = stToPrim $ STMat 1 (SV.length r) <$> LA.unsafeThawMatrix (LA.asRow r)\n unsafeFromRows rs = stToPrim $ do\n let m = LA.fromRows (DC.coerce rs :: [LA.Vector a])\n STMat (LA.rows m) (LA.cols m) . DC.coerce <$> LA.unsafeThawMatrix m\n unsafeFromColumn c = stToPrim $ STMat (SV.length c) 1 <$> LA.unsafeThawMatrix (LA.asColumn c)\n unsafeFromColumns rs = stToPrim $ do\n let m = LA.fromColumns (DC.coerce rs :: [LA.Vector a])\n STMat (LA.rows m) (LA.cols m) . DC.coerce <$> LA.unsafeThawMatrix m\n unsafeCopy (STMat r c m) (STMat _ _ m') = stToPrim $ do\n m0 <- LA.unsafeFreezeMatrix m'\n LA.setMatrix (DC.coerce m :: LA.STMatrix w a) r c (DC.coerce m0 :: LA.Matrix a)\n unsafeRead (STMat _ _ m) i j = stToPrim $ LA.readMatrix m i j\n unsafeWrite (STMat _ _ m) i j x = stToPrim $ LA.writeMatrix m i j x\n basicSet (STMat r c m) x = stToPrim $ LA.modifyMatrix m r c $ const x\n basicUnsafeSwapRows (STMat _ _ m) i j =\n stToPrim $ LA.rowOper (LA.SWAP i j LA.AllCols) $ castSTMatrixFractional m\n unsafeScaleRow (STMat _ _ m) i c =\n stToPrim $ LA.rowOper (LA.SCAL (unwrapFractional c) (LA.Row i) LA.AllCols) $ castSTMatrixFractional m\n basicUnsafeIMapRowM (STMat _ c m) i f = forM_ [0..c-1] $ \\j ->\n stToPrim . LA.writeMatrix m i j =<< f j =<< stToPrim (LA.readMatrix m i j)\n toRows (STMat _ _ m) =\n stToPrim $ DC.coerce . LA.toRows <$> LA.unsafeFreezeMatrix (castSTMatrixFractional m)\n toColumns (STMat _ _ m) =\n stToPrim $ DC.coerce . LA.toColumns <$> LA.unsafeFreezeMatrix (castSTMatrixFractional m)\n\nunwrapSTMIntegral :: STMatrix s (WrapIntegral a) -> LA.STMatrix s a\nunwrapSTMIntegral = DC.coerce . unwrapSTM\n{-# INLINE unwrapSTMIntegral #-}\n\ncastSTMatrixIntegral :: LA.STMatrix s (WrapIntegral a) -> LA.STMatrix s a\ncastSTMatrixIntegral = DC.coerce\n{-# INLINE castSTMatrixIntegral #-}\n\ninstance (Integral a, LA.Container LA.Matrix a) => MMatrix STMatrix (WrapIntegral a) where\n basicUnsafeNew n m = stToPrim $ STMat n m <$> LA.newMatrix 0 n m\n basicInitialise _ = return ()\n basicRowCount = stmRows\n basicColumnCount = stmCols\n unsafeGetRow i m =\n stToPrim $ DC.coerce . getRowLA i <$> LA.unsafeFreezeMatrix (unwrapSTMIntegral m)\n unsafeGetColumn i m = stToPrim $ DC.coerce . getColLA i <$> LA.unsafeFreezeMatrix (unwrapSTMIntegral m)\n unsafeFill n m a = stToPrim $ STMat n m <$> LA.newMatrix a n m\n unsafeFromRow r = stToPrim $ STMat 1 (SV.length r) <$> LA.unsafeThawMatrix (LA.asRow r)\n unsafeFromRows rs = stToPrim $ do\n let m = LA.fromRows (DC.coerce rs :: [LA.Vector a])\n STMat (LA.rows m) (LA.cols m) . DC.coerce <$> LA.unsafeThawMatrix m\n unsafeFromColumn c = stToPrim $ STMat (SV.length c) 1 <$> LA.unsafeThawMatrix (LA.asColumn c)\n unsafeFromColumns rs = stToPrim $ do\n let m = LA.fromColumns (DC.coerce rs :: [LA.Vector a])\n STMat (LA.rows m) (LA.cols m) . DC.coerce <$> LA.unsafeThawMatrix m\n unsafeCopy (STMat r c m) (STMat _ _ m') = stToPrim $ do\n m0 <- LA.unsafeFreezeMatrix m'\n LA.setMatrix (DC.coerce m :: LA.STMatrix w a) r c (DC.coerce m0 :: LA.Matrix a)\n unsafeRead (STMat _ _ m) i j = stToPrim $ LA.readMatrix m i j\n unsafeWrite (STMat _ _ m) i j x = stToPrim $ LA.writeMatrix m i j x\n basicSet (STMat r c m) x = stToPrim $ LA.modifyMatrix m r c $ const x\n basicUnsafeSwapRows (STMat _ _ m) i j =\n stToPrim $ LA.rowOper (LA.SWAP i j LA.AllCols) $ castSTMatrixIntegral m\n unsafeScaleRow (STMat _ _ m) i c =\n stToPrim $ LA.rowOper (LA.SCAL (unwrapIntegral c) (LA.Row i) LA.AllCols) $ castSTMatrixIntegral m\n basicUnsafeIMapRowM (STMat _ c m) i f = forM_ [0..c-1] $ \\j ->\n stToPrim . LA.writeMatrix m i j =<< f j =<< stToPrim (LA.readMatrix m i j)\n toRows (STMat _ _ m) =\n stToPrim $ DC.coerce . LA.toRows <$> LA.unsafeFreezeMatrix (castSTMatrixIntegral m)\n toColumns (STMat _ _ m) =\n stToPrim $ DC.coerce . LA.toColumns <$> LA.unsafeFreezeMatrix (castSTMatrixIntegral m)\n\ninstance {-# OVERLAPPING #-} (LA.Container LA.Matrix a, Show a) => Show (LA.Matrix (WrapNum a)) where\n showsPrec d = showsPrec d . (DC.coerce :: LA.Matrix (WrapNum a) -> LA.Matrix a)\n\ninstance {-# OVERLAPPING #-} (LA.Container LA.Matrix a, Show a) => Show (LA.Matrix (WrapIntegral a)) where\n showsPrec d = showsPrec d . (DC.coerce :: LA.Matrix (WrapIntegral a) -> LA.Matrix a)\n\ninstance {-# OVERLAPPING #-} (LA.Container LA.Matrix a, Show a) => Show (LA.Matrix (WrapFractional a)) where\n showsPrec d = showsPrec d . (DC.coerce :: LA.Matrix (WrapFractional a) -> LA.Matrix a)\n", "meta": {"hexsha": "060a051d758a0353936238069dd9287bfb45d681", "size": 11684, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "halg-matrices/src/Algebra/Matrix/HMatrix.hs", "max_stars_repo_name": "hangingman/computational-algebra", "max_stars_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2015-02-09T01:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T04:37:09.000Z", "max_issues_repo_path": "halg-matrices/src/Algebra/Matrix/HMatrix.hs", "max_issues_repo_name": "hangingman/computational-algebra", "max_issues_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-09-18T16:31:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T08:28:37.000Z", "max_forks_repo_path": "halg-matrices/src/Algebra/Matrix/HMatrix.hs", "max_forks_repo_name": "hangingman/computational-algebra", "max_forks_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-12-22T16:04:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T19:35:53.000Z", "avg_line_length": 52.8687782805, "max_line_length": 108, "alphanum_fraction": 0.6736562821, "num_tokens": 3678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5012680002203327}} {"text": "{-# OPTIONS_GHC -Wall #-}\n{-# LANGUAGE BangPatterns #-}\n\nmodule Numeric.MCMC.Langevin ( \n MarkovChain(..), Options(..)\n , runChain\n ) where\n\nimport Control.Monad\nimport Control.Monad.Trans\nimport Control.Monad.Reader\nimport Control.Monad.Primitive\nimport Control.Arrow \nimport System.Random.MWC\nimport System.Random.MWC.Distributions\nimport Data.List\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal hiding (standard)\nimport GHC.Float\n\n-- | State of the Markov chain. Current parameter values are held in 'theta', \n-- while accepts counts the number of proposals accepted.\ndata MarkovChain = MarkovChain { theta :: [Double] \n , accepts :: {-# UNPACK #-} !Int }\n\n-- | Options for the chain. The target (expected to be a log density), its \n-- gradient, and a step size tuning parameter.\ndata Options = Options { _target :: [Double] -> Double\n , _gTarget :: [Double] -> [Double]\n , _eps :: {-# UNPACK #-} !Double }\n\n-- | A result with this type has a view of the chain options.\ntype ViewsOptions = ReaderT Options\n\n-- | Display the current state. \ninstance Show MarkovChain where\n show config = filter (`notElem` \"[]\") $ show (map double2Float (theta config))\n\n-- | Density function for an isotropic Gaussian. The (identity) covariance \n-- matrix is multiplied by the scalar 'sig'.\nisoGauss :: [Double] -> [Double] -> Double -> Double\nisoGauss xs mu sig = foldl1' (*) (zipWith density nds xs)\n where nds = map (`normalDistr` sig) mu\n{-# INLINE isoGauss #-}\n\n-- | Mean function for the discretized Langevin diffusion.\nlocalMean :: Monad m \n => [Double] -- Current state\n -> ViewsOptions m [Double] -- Localized mean \nlocalMean t = do\n Options _ gTarget e <- ask\n return $! zipWith (+) t (map (* (0.5 * e^(2 :: Int))) (gTarget t))\n{-# INLINE localMean #-}\n\n-- | Perturb the state, creating a new proposal.\nperturb :: PrimMonad m \n => [Double] -- Current state\n -> Gen (PrimState m) -- MWC PRNG\n -> ViewsOptions m [Double] -- Resulting perturbation.\nperturb t g = do\n Options _ _ e <- ask\n zs <- replicateM (length t) (lift $ standard g)\n t0 <- localMean t\n let perturbedState = zipWith (+) t0 t1 \n t1 = map (* e) zs\n return $! perturbedState \n{-# INLINE perturb #-}\n\n-- | Perform a Metropolis accept/reject step.\nmetropolisStep :: PrimMonad m \n => MarkovChain -- Current state\n -> Gen (PrimState m) -- MWC PRNG \n -> ViewsOptions m MarkovChain -- New state\nmetropolisStep state g = do\n Options target _ e <- ask\n let (t0, nacc) = (theta &&& accepts) state\n zc <- lift $ uniformR (0, 1) g\n proposal <- perturb t0 g\n t0Mean <- localMean t0\n proposalMean <- localMean proposal\n let mc = if zc < acceptProb \n then (proposal, 1)\n else (t0, 0)\n\n acceptProb = if isNaN val then 0 else val where val = arRatio \n \n arRatio = exp . min 0 $ \n target proposal + log (isoGauss proposal t0Mean (e^(2 :: Int)))\n - target t0 - log (isoGauss t0 proposalMean (e^(2 :: Int)))\n\n return $! MarkovChain (fst mc) (nacc + snd mc)\n{-# INLINE metropolisStep #-}\n\n-- | Diffuse through states.\nrunChain :: Options -- Options of the Markov chain.\n -> Int -- Number of epochs to iterate the chain.\n -> Int -- Print every nth iteration\n -> MarkovChain -- Initial state of the Markov chain.\n -> Gen RealWorld -- MWC PRNG\n -> IO MarkovChain -- End state of the Markov chain, wrapped in IO.\nrunChain = go\n where go o n t !c g | n == 0 = return c\n | n `rem` t /= 0 = do\n r <- runReaderT (metropolisStep c g) o\n go o (n - 1) t r g\n | otherwise = do\n r <- runReaderT (metropolisStep c g) o\n print r\n go o (n - 1) t r g\n{-# INLINE runChain #-}\n\n", "meta": {"hexsha": "41d30e8404d403d54263f21ceffdf5ad8c63d93a", "size": 4204, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/MCMC/Langevin.hs", "max_stars_repo_name": "jtobin/lazy-langevin", "max_stars_repo_head_hexsha": "147bf3b433d1b7290fda715c7689ecf2b7486eab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-09-05T02:55:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-10T03:12:37.000Z", "max_issues_repo_path": "Numeric/MCMC/Langevin.hs", "max_issues_repo_name": "jtobin/lazy-langevin", "max_issues_repo_head_hexsha": "147bf3b433d1b7290fda715c7689ecf2b7486eab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numeric/MCMC/Langevin.hs", "max_forks_repo_name": "jtobin/lazy-langevin", "max_forks_repo_head_hexsha": "147bf3b433d1b7290fda715c7689ecf2b7486eab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-22T05:08:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T05:08:38.000Z", "avg_line_length": 37.5357142857, "max_line_length": 82, "alphanum_fraction": 0.5687440533, "num_tokens": 1066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5010852725498578}} {"text": "{-# LANGUAGE PatternGuards #-}\n-- |\n-- Module : Statistics.Matrix\n-- Copyright : 2011 Aleksey Khudyakov, 2014 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Basic matrix operations.\n--\n-- There isn't a widely used matrix package for Haskell yet, so\n-- we implement the necessary minimum here.\n\nmodule Statistics.Matrix\n ( -- * Data types\n Matrix(..)\n , Vector\n -- * Conversion from/to lists/vectors\n , fromVector\n , dimension\n -- , center\n , multiplyV\n , transpose\n , norm\n , column\n -- , row\n , for\n , unsafeIndex\n ) where\n\nimport Prelude hiding (exponent, map, sum)\nimport qualified Data.Vector.Unboxed as U\n\nimport Statistics.Function (for, square)\nimport Statistics.Matrix.Types\nimport Statistics.Sample.Internal (sum)\n\n\n----------------------------------------------------------------\n-- Conversion to/from vectors/lists\n----------------------------------------------------------------\n\n-- | Convert from a row-major vector.\nfromVector :: Int -- ^ Number of rows.\n -> Int -- ^ Number of columns.\n -> U.Vector Double -- ^ Flat list of values, in row-major order.\n -> Matrix\nfromVector r c v\n | r*c /= len = error \"input size mismatch\"\n | otherwise = Matrix r c 0 v\n where len = U.length v\n\n----------------------------------------------------------------\n-- Other\n----------------------------------------------------------------\n\n-- | Return the dimensions of this matrix, as a (row,column) pair.\ndimension :: Matrix -> (Int, Int)\ndimension (Matrix r c _ _) = (r, c)\n\n-- | Matrix-vector multiplication.\nmultiplyV :: Matrix -> Vector -> Vector\nmultiplyV m v\n | cols m == c = U.generate (rows m) (sum . U.zipWith (*) v . row m)\n | otherwise = error $ \"matrix/vector unconformable \" ++ show (cols m,c)\n where c = U.length v\n\n-- | Calculate the Euclidean norm of a vector.\nnorm :: Vector -> Double\nnorm = sqrt . sum . U.map square\n\n-- | Return the given column.\ncolumn :: Matrix -> Int -> Vector\ncolumn (Matrix r c _ v) i = U.backpermute v $ U.enumFromStepN i c r\n{-# INLINE column #-}\n\n-- | Return the given row.\nrow :: Matrix -> Int -> Vector\nrow (Matrix _ c _ v) i = U.slice (c*i) c v\n\nunsafeIndex :: Matrix\n -> Int -- ^ Row.\n -> Int -- ^ Column.\n -> Double\nunsafeIndex = unsafeBounds U.unsafeIndex\n\n-- | Given row and column numbers, calculate the offset into the flat\n-- row-major vector, without checking.\nunsafeBounds :: (Vector -> Int -> r) -> Matrix -> Int -> Int -> r\nunsafeBounds k (Matrix _ cs _ v) r c = k v $! r * cs + c\n{-# INLINE unsafeBounds #-}\n\n\ntranspose :: Matrix -> Matrix\ntranspose m@(Matrix r0 c0 e _) = Matrix c0 r0 e . U.generate (r0*c0) $ \\i ->\n let (r,c) = i `quotRem` r0\n in unsafeIndex m c r\n", "meta": {"hexsha": "345bf359d4a29889e175d25cadf85b6095f5f25b", "size": 2803, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "statistics/Statistics/Matrix.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/Matrix.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/Matrix.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": 29.1979166667, "max_line_length": 77, "alphanum_fraction": 0.5561897966, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5010496452043454}} {"text": "{-# OPTIONS_GHC -Wall #-}\n\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE OverloadedLists #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule Heat2D (main, a1, a2) where\n\nimport Data.Number.Symbolic\nimport Data.Proxy\n\nimport qualified Naperian as N\nimport qualified GHC.TypeLits as M\nimport Data.Functor\nimport System.IO\n\nimport Numeric.Sundials\nimport Numeric.LinearAlgebra\n\n\nkx, ky :: Floating a => a\nkx = 0.5\nky = 0.75\n\n-- x mesh spacing\n-- y mesh spacing\ndx :: Floating a => a\ndx = 1 / (fromIntegral nx - 1)\n\ndy :: Floating a => a\ndy = 1 / (fromIntegral ny - 1)\n\nc1, c2 :: Floating a => a\nc1 = kx/dx/dx\nc2 = ky/dy/dy\n\npreA2 :: forall b m n . (M.KnownNat m, M.KnownNat n, Num b) =>\n N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] b\npreA2 = N.Prism $ N.Prism $ N.Prism $ N.Prism $ N.Scalar $\n N.viota @m <&> (\\(N.Fin x) ->\n N.viota @n <&> (\\(N.Fin w) ->\n N.viota @m <&> (\\(N.Fin v) ->\n N.viota @n <&> (\\(N.Fin u) ->\n (f m n x w v u)))))\n where\n m = fromIntegral $ M.natVal (undefined :: Proxy m)\n n = fromIntegral $ M.natVal (undefined :: Proxy n)\n f p q i j k l | i == 0 = 0\n | j == 0 = 0\n | i == p - 1 = 0\n | j == q - 1 = 0\n | k == i - 1 && l == j = 1\n | k == i && l == j = -2\n | k == i + 1 && l == j = 1\n | otherwise = 0\n\na2Num :: forall a m n . (M.KnownNat m, M.KnownNat n, Floating a) =>\n N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] a\na2Num = N.binary (*) (N.Scalar c2) preA2\n\na2 :: forall a m n . (M.KnownNat m, M.KnownNat n, Floating a, Eq a) =>\n N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] (Sym a)\na2 = N.binary (*) (N.Scalar $ var \"a\") preA2\n\npreA1 :: forall b m n . (M.KnownNat m, M.KnownNat n, Num b) =>\n N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] b\npreA1 = N.Prism $ N.Prism $ N.Prism $ N.Prism $ N.Scalar $\n N.viota @m <&> (\\(N.Fin x) ->\n N.viota @n <&> (\\(N.Fin w) ->\n N.viota @m <&> (\\(N.Fin v) ->\n N.viota @n <&> (\\(N.Fin u) ->\n (f m n x w v u)))))\n where\n m = fromIntegral $ M.natVal (undefined :: Proxy m)\n n = fromIntegral $ M.natVal (undefined :: Proxy n)\n f :: Int -> Int -> Int -> Int -> Int -> Int -> b\n f p q i j k l | i == 0 = 0\n | j == 0 = 0\n | i == p - 1 = 0\n | j == q - 1 = 0\n | k == i && l == j - 1 = 1\n | k == i && l == j = -2\n | k == i && l == j + 1 = 1\n | otherwise = 0\n\na1Num :: forall a m n . (M.KnownNat m, M.KnownNat n, Floating a) =>\n N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] a\na1Num = N.binary (*) (N.Scalar c1) preA1\n\na1 :: forall a m n . (M.KnownNat m, M.KnownNat n, Floating a, Eq a) =>\n N.Hyper '[N.Vector n, N.Vector m, N.Vector n, N.Vector m] (Sym a)\na1 = N.binary (*) (N.Scalar $ var \"b\") preA1\n\nh :: forall m n a . (M.KnownNat m, M.KnownNat n, Floating a) =>\n N.Hyper '[N.Vector m, N.Vector n] a\nh = N.Prism $ N.Prism $ N.Scalar $\n N.viota @n <&> (\\(N.Fin x) ->\n N.viota @m <&> (\\(N.Fin w) ->\n sin (pi * (fromIntegral w) * dx)\n * sin (2 * pi * (fromIntegral x) * dy)))\n\n-- spatial mesh size\nnx, ny :: Int\nnx = 30\nny = 60\n\nbigA :: Matrix Double\nbigA = fromLists $\n fmap (N.elements . N.Prism . N.Prism . N.Scalar) $\n N.elements $ N.crystal $ N.crystal $\n N.binary (+) (a2Num @Double @60 @30) (a1Num @Double @60 @30)\n\nb :: Vector Double\nb = fromList $ N.elements (h @30 @60 @Double)\n\nt0, tf :: Double\nt0 = 0.0\ntf = 0.3\n\nbigNt :: Int\nbigNt = 20\n\ndTout :: Double\ndTout = (tf - t0) / (fromIntegral bigNt)\n\nts :: [Double]\nts = map (dTout *) $ map fromIntegral [1..bigNt]\n\nsol :: Matrix Double\n-- sol = odeSolveV SDIRK_5_3_4' Nothing 1.0e-5 1.0e-10 (const bigU') (assoc (nx * ny) 0.0 [] :: Vector Double) (fromList $ ts)\n-- where\n-- bigU' bigU = bigA #> bigU + b\nsol = undefined\n\nmain :: IO ()\nmain = do\n h1 <- openFile \"heat2e.000.txt\" WriteMode\n mapM_ (hPutStrLn h1) $ map (concatMap (' ':)) $ map (map show) $ toLists sol\n hClose h1\n mapM_ (\\i -> putStrLn $ show $ sqrt $ (sol!i) <.> (sol!i) / (fromIntegral nx) / (fromIntegral ny)) ([0 .. length ts - 1] :: [Int])\n", "meta": {"hexsha": "eb3e0c43e1559b34df6d1a3ff4e3564f5cd6c527", "size": 4885, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Heat2D.hs", "max_stars_repo_name": "idontgetoutmuch/Diffusions", "max_stars_repo_head_hexsha": "b07eb63aeb8d7b12e5a2ba18a01eca520af3e128", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Heat2D.hs", "max_issues_repo_name": "idontgetoutmuch/Diffusions", "max_issues_repo_head_hexsha": "b07eb63aeb8d7b12e5a2ba18a01eca520af3e128", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Heat2D.hs", "max_forks_repo_name": "idontgetoutmuch/Diffusions", "max_forks_repo_head_hexsha": "b07eb63aeb8d7b12e5a2ba18a01eca520af3e128", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.231292517, "max_line_length": 132, "alphanum_fraction": 0.4792221085, "num_tokens": 1647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.5007594917654546}}