{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-|\nModule : Grenade.Layers.Tanh\nDescription : Hyperbolic tangent nonlinear layer\nCopyright : (c) Huw Campbell, 2016-2017\nLicense : BSD2\nStability : experimental\n-}\nmodule Grenade.Layers.Tanh\n ( Tanh(..)\n , SpecTanh (..)\n , specTanh1D\n , specTanh2D\n , specTanh3D\n , specTanh\n , tanhLayer\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\nimport Grenade.Utils.Conversion\nimport Grenade.Utils.Vector\n\n-- | A Tanh layer.\n-- A layer which can act between any shape of the same dimension, performing a tanh function.\ndata Tanh = Tanh\n deriving (Generic,NFData,Show)\n\ninstance UpdateLayer Tanh where\n type Gradient Tanh = ()\n runUpdate _ _ _ = Tanh\n\ninstance RandomLayer Tanh where\n createRandomWith _ _ = return Tanh\n\ninstance Serialize Tanh where\n put _ = return ()\n get = return Tanh\n\ninstance (a ~ b, SingI a) => Layer Tanh a b where\n type Tape Tanh a b = S a\n -- runForwards _ (S1DV v) = (S1DV v, S1DV $ mapVectorInPlace tanh v) -- This is inplace replacement!\n -- runForwards _ (S2DV v) = (S2DV v, S2DV $ mapVectorInPlace tanh v) -- This is inplace replacement!\n runForwards _ a = (a, tanh a)\n runBackwards _ (S1DV v) (S1DV gs) = ((), S1DV $ zipWithVector (\\t g -> max 0.005 (1 - (tanh t) ^ (2 :: Int)) * g) v gs)\n runBackwards _ (S2DV v) (S2DV gs) = ((), S2DV $ zipWithVector (\\t g -> max 0.005 (1 - (tanh t) ^ (2 :: Int)) * g) v gs)\n runBackwards _ (S1D a) (S1D g)= ((), S1D $ LAS.dvmap (max 0.005) (tanh' a) * g)\n runBackwards _ (S2D a) (S2D g)= ((), S2D $ LAS.dmmap (max 0.005) (tanh' a) * g)\n runBackwards _ (S3D a) (S3D g)= ((), S3D $ LAS.dmmap (max 0.005) (tanh' a) * g)\n runBackwards l x y = runBackwards l x (toLayerShape x y)\n -- runBackwards _ a g = ((), tanh' a * g)\n\ntanh' :: (Floating a) => a -> a\ntanh' t = 1 - s ^ (2 :: Int) where s = tanh t\n\n-------------------- DynamicNetwork instance --------------------\n\ninstance FromDynamicLayer Tanh where\n fromDynamicLayer inp _ _ = SpecNetLayer $ SpecTanh (tripleFromSomeShape inp)\n\ninstance ToDynamicLayer SpecTanh where\n toDynamicLayer _ _ (SpecTanh (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 Tanh (sing :: Sing ('D1 rows)) (sing :: Sing ('D1 rows))\n (_, _, 1) -> return $ SpecLayer Tanh (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 Tanh (sing :: Sing ('D3 rows cols depth)) (sing :: Sing ('D3 rows cols depth))\n\n\n-- | Create a specification for a Tanh layer.\nspecTanh1D :: Integer -> SpecNet\nspecTanh1D i = specTanh3D (i, 1, 1)\n\n-- | Create a specification for a Tanh layer.\nspecTanh2D :: (Integer, Integer) -> SpecNet\nspecTanh2D (i, j) = specTanh3D (i, j, 1)\n\n-- | Create a specification for a Tanh layer.\nspecTanh3D :: (Integer, Integer, Integer) -> SpecNet\nspecTanh3D = SpecNetLayer . SpecTanh\n\n-- | Create a specification for a Tanh layer.\nspecTanh :: (Integer, Integer, Integer) -> SpecNet\nspecTanh = SpecNetLayer . SpecTanh\n\n-- | Add a Tanh layer to your build.\ntanhLayer :: BuildM ()\ntanhLayer = buildGetLastLayerOut >>= buildAddSpec . SpecNetLayer . SpecTanh\n\n\n-------------------- GNum instances --------------------\n\ninstance GNum Tanh where\n _ |* Tanh = Tanh\n _ |+ Tanh = Tanh\n sumG _ = Tanh\n", "meta": {"hexsha": "b3217d1082e146276ff8bad98ead41aa11207ed1", "size": 4465, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Tanh.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/Tanh.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/Tanh.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": 37.2083333333, "max_line_length": 121, "alphanum_fraction": 0.6091825308, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3498664335137021}} {"text": "{-# LANGUAGE FlexibleContexts #-} {- Container (Vector a) => ..., etc. -}\n{-# LANGUAGE RankNTypes #-} {- For type traces w/ ST -}\n{-# LANGUAGE Strict #-} {- Lazy evaluation is no good here -}\n{-# LANGUAGE TemplateHaskell #-} {- Since we're using lenses aplenty -}\n\n{-\n TODO LIST:\n * Make sure basic functionality works, write some tests.\n * Use Numeric.LinearAlgebra.Devel to guarantee that ALL matrix operations\n are zero-copy or low allocation overhead.\n * Leverage chunk-based parallelism (lots of embarassing parallelism!)\n-}\n\nmodule Optimization.NelderMead\n ( nelderMeadAt\n , nelderMeadFull\n , nelderMead\n ) where\n\nimport Control.Applicative\nimport Control.Lens\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Maybe\nimport Data.Ord ( comparing )\nimport Data.STRef ( STRef\n , modifySTRef\n , newSTRef\n , readSTRef\n , writeSTRef )\n \nimport Data.Vector.Storable as VS hiding ( take\n , forM_\n , (!) )\nimport Data.Vector.Algorithms.Intro ( sortBy )\nimport Data.Vector.Mutable as VM hiding ( take )\nimport Data.Vector.Storable.Mutable as VSM hiding ( take )\n\nimport Numeric.LinearAlgebra.Data as LA\nimport Numeric.LinearAlgebra.HMatrix as HM\nimport Numeric.LinearAlgebra.Devel as MutM\n\nimport Optimization.Types\n\n-- One point of the simplex and its associated score.\ndata Vertex s = Vertex {\n which :: Int,\n score :: s\n }\n\n-- Ranked vertices for NM search.\ndata VertexRank a b = VertexRank {\n bestOf :: Vertex b,\n nextBestOf :: Vertex b,\n worstOf :: Vertex b,\n goodCentroidOf :: Vector a\n }\n\n-- Create a VertexRank from the available data.\npickBestAndWorstVerts ::\n (Numeric a, Fractional a, Ord b) =>\n --(Container Vector a, Element a, Ord b, Transposable (Simplex a) (Simplex a)) =>\n (Vector a -> b) -> -- A function from a point on the simplex to some orderable type.\n Simplex a -> -- The simplex to consider.\n VertexRank a b -- Vertex rank.\npickBestAndWorstVerts f s = runST $ do\n let\n nDims = rows s\n points = tr s\n\n scores <- VM.new nDims\n forM_ [0..(nDims - 1)] (\\i -> VM.unsafeWrite scores i (i, f $ points ! i))\n sortBy (comparing snd) scores\n let\n mvertex j = liftM (uncurry Vertex) (VM.unsafeRead scores j)\n h <- mvertex 0\n sh <- mvertex 1\n l <- mvertex (nDims - 1)\n \n return $ VertexRank h sh l (center $ allButIth (which l) s)\n\n-- Increment a termination criterion by one iteration.\nincrement :: TerminationCriterion a -> TerminationCriterion a\nincrement p\n | isJust (view maxit p) = over maxit (fmap pred) p\n | otherwise = p\n\n-- Compute the center of the NM Simplex.\ncenter ::\n (Numeric a, Fractional a) =>\n Simplex a ->\n Vector a\ncenter s = runST $ do \n centroid <- VSM.new (rows s)\n \n forM_ [0..((rows s) - 1)] (\\i -> do\n forM_ [0..((cols s) - 1)] (\\j -> do\n let\n u = fromIntegral (cols s)\n VSM.unsafeWrite centroid i ((s `atIndex` (i,j)) / u) ))\n\n freeze centroid\n\n-- Create a simplex with all points but the i-th.\nallButIth :: (Numeric a) => Int -> Simplex a -> Simplex a\nallButIth l s\n | l == 0 = subMatrix (0,1) (nDims, nDims) s\n | l == (cols s) = subMatrix (0,0) (nDims, nDims) s\n | otherwise = ls ||| rs where\n nDims = rows s\n ls = subMatrix (0, l - 1) (nDims, l - 1) s\n rs = subMatrix (0, l + 1) (nDims, nDims - l) s\n\n-- The centroid of all points except whichever is worst.\ngoodCentroid :: (Numeric a, Fractional a, Ord b) =>\n VertexRank a b ->\n Simplex a ->\n Vector a\ngoodCentroid r splx = center $ allButIth ((which . worstOf) r) splx\n\n-- Get the i-th point of a simplex.\nnthPoint :: (Numeric a, Element a) => Int -> Simplex a -> Vector a\nnthPoint i s = flatten $ subMatrix (0, i) (rows s, 1) s\n\n-- Get an estimate of simplex size by computing the sum of all\n-- elements in the simplex, translated so that its centroid\n-- lies at zero.\nsimplexSize :: (Numeric a, Fractional a) =>\n Simplex a ->\n a\nsimplexSize s = fastSimplexL1 (moveToOrigin s) where\n fastSimplexL1 m = runST $ do\n acc <- newSTRef 0\n mut <- unsafeThawMatrix m\n forM_ [0..((rows m) - 1)] $ \\i -> do\n forM_ [0..((cols m) - 1)] $ \\j -> do\n elem <- unsafeReadMatrix mut i j\n modifySTRef acc (+ elem)\n readSTRef acc\n\nmoveToOrigin :: (Numeric a, Fractional a) =>\n Simplex a ->\n Simplex a\nmoveToOrigin s = runSTMatrix $ do\n sm <- thawMatrix s\n ctr <- unsafeThawVector (center s)\n\n forM_ [0..((rows s) - 1)] $ \\i -> do\n c_entry <- unsafeReadVector ctr i\n forM_ [0..((cols s) - 1)] $ \\j -> do\n m_entry <- unsafeReadMatrix sm i j\n unsafeWriteMatrix sm i j (m_entry - c_entry)\n\n return sm\n\n-- Check if current simplex state and termination criterion indicate that we should\n-- be finished.\nisDone tc simplex = noMoreIters || closeEnough || neitherValid where\n noMoreIters = (fromMaybe 1 (view maxit tc)) == 0\n thresh = view threshold tc\n closeEnough = fromMaybe False (fmap ((simplexSize simplex) <) thresh)\n neitherValid = (isNothing (view maxit tc)) && (isNothing (view threshold tc))\n\n-- Update the i-th point of simplex sx with vector p.\nupdateSimplex :: (Numeric a) => Int -> Vector a -> Simplex a -> Simplex a\nupdateSimplex i v sx = runSTMatrix $ do\n sxm <- thawMatrix sx\n vm <- unsafeThawVector v\n forM_ [0..((cols sx) - 1)] $ \\d -> do\n updated <- unsafeReadVector vm d\n unsafeWriteMatrix sxm d i updated\n return sxm\n\n-- Reflect the simplex's \"worst\" point around the hyperplane defined by the \n-- other points. If this constitutes a significant improvement, then consider\n-- \"expanding\" even farther in the same direction. Otherwise, give up.\nreflectAndExpand :: forall a b s. (Num a, Numeric a, Fractional a, Ord b) =>\n NMStepParameters a ->\n (Vector a -> b) ->\n STRef s (Simplex a) ->\n STRef s (VertexRank a b) ->\n ST s Bool\nreflectAndExpand params f s vrank = do\n r <- readSTRef vrank\n sx <- readSTRef s\n \n let\n x0 = goodCentroid r sx\n x_best = nthPoint ((which . bestOf) r) sx\n sx_best = (score . bestOf) r -- Score of best x\n sx_next = (score . nextBestOf) r -- Score of next best x\n \n a = view alpha params\n xr = x0 + ((x0 - x_best) `scaleBy` a) -- x reflected\n sxr = f xr -- score of x reflected\n\n -- How does the reflected point fare?\n if (sxr < sx_next && sxr > sx_best)\n then do\n modifySTRef s (updateSimplex ((which . worstOf) r) xr)\n return True\n else do\n\n -- Consider expansion.\n if (sxr < sx_best)\n then do\n let\n g = view gamma params\n xe = x0 + ((xr - x0) `scaleBy` g)\n sxe = f xe\n\n -- Is expansion better?\n if (sxe < sxr)\n then do\n modifySTRef s (updateSimplex ((which . worstOf) r) xe)\n return True\n else do\n modifySTRef s (updateSimplex ((which . worstOf) r) xr)\n return True\n else do\n return False\n\n-- Move the worst point of the simplex inward toward the centroid of all the\n-- better points. If this doesn't result in an improvement, don't do anything.\ncontract :: forall a b s. (Numeric a, Fractional a, Ord b) =>\n NMStepParameters a ->\n (Vector a -> b) ->\n STRef s (Simplex a) ->\n STRef s (VertexRank a b) ->\n ST s Bool\ncontract params f s vrank = do\n r <- readSTRef vrank\n sx <- readSTRef s\n let\n x0 = goodCentroid r sx\n x_worst = nthPoint ((which . worstOf) r) sx\n sx_worst = (score . worstOf) r\n \n rh = view rho params\n xc = x0 + ((x_worst - x0) `scaleBy` rh)\n sxc = f xc\n\n if (sxc < sx_worst)\n then do\n modifySTRef s (updateSimplex ((which . worstOf) r) xc)\n return True\n else do\n return False \n\n\n-- Move all points of a simplex slightly towards the best point.\nshrink :: forall a b s. (Num a, Fractional a, Storable a, Ord b) =>\n NMStepParameters a ->\n (Vector a -> b) ->\n STRef s (Simplex a) ->\n STRef s (VertexRank a b) ->\n ST s Bool\nshrink params f s vrank = do\n sx <- readSTRef s\n r <- readSTRef vrank\n let\n sig = view sigma r\n x_best = nthPoint ((which . bestOf) r) sx\n\n forM_ (\\i -> do\n modifySTRef s (\\simplex ->\n if (i == ((which . bestOf) r))\n then\n simplex\n else\n let\n xi = nthPoint i simplex\n xi' = x_best + (sig * (xi - x_best)) in\n updateSimplex i xi' simplex\n )\n ) [0..((cols sx) - 1)]\n return True\n\n \n-- |Predict the location of a minimum of an objective function using the Nelder-Mead simplex\n-- search. This function permits tuning of all parameters, including the starting simplex.\nnelderMeadFull :: (Num a, Fractional a, Storable a, Ord b) =>\n NMStepParameters a -> -- ^Nelder-Mead step parameters\n TerminationCriterion a -> -- ^Reason we would terminate\n (Vector a -> b) -> -- ^Objective function\n Simplex a -> -- ^Starting simplex\n Vector a -- ^Predicted minimum\nnelderMeadFull params term_conditions func initial = (center . runST) $ do\n \n simplex <- newSTRef initial\n vtx_rank <- newSTRef (pickBestAndWorstVerts simplex)\n\n nelderMeadStep params term_conditions func simplex vtx_rank where\n \n nelderMeadStep p tc f s vrank = do\n -- Update rank and see if we're done.\n modifySTRef vrank (pickBestAndWorstVerts func)\n finished <- isDone <$> readSTRef s\n\n if (finished)\n then do\n rnk <- readSTRef vrank\n sx <- readSTRef s\n return $ nthPoint ((which . bestOf) rnk) sx\n\n -- Attempt to improve simplex.\n else do\n reflected <- reflectAndExpand p f s vrank\n unless reflected $ do\n contracted <- contract p f s vrank\n unless contracted $ do\n shrink p f s vrank\n \n nelderMeadStep p (iterate tc) f s vrank\n \n-- |Predict the location of a minimum of an objective function using the\n-- Nelder-Mead simplex search. This version is like nelderMeadFull, but accepts\n-- a starting point rather than an entire simplex.\nnelderMeadAt :: (Num a, Fractional a, Storable a, Ord b) =>\n NMStepParameters a -> -- ^Nelder-Mead step parameters\n TerminationCriterion a -> -- ^Reason we would terminate\n (Vector a -> b) -> -- ^Objective function\n Vector a -> -- ^Starting point.\n Vector a -- ^Predicted minimum.\nnelderMeadAt p t f i = nelderMeadFull p t f (makeSimplexAround i e) where\n e = view epsilon p\n\n-- |Minimize an objective function using the Nelder-Mead simplex search. This\n-- invokation uses \"default\" step parameters.\nnelderMead :: (Num a, Fractional a, Storable a, Ord b) =>\n TerminationCriterion a -> -- ^Reason we would terminate\n (Vector a -> b) -> -- ^Objective function\n Vector a -- ^Initial guess\nnelderMead tc f x = nelderMeadAt defaultStep tc f x\n\n{-\n Construct a simplex around a point by creating another vertex epsilon away from the initial\n guess along each vector of the canonical basis.\n-}\nmakeSimplexAround :: (Element a) =>\n Vector a -> -- One vertex of the simplex\n a -> -- Epsilon used to expand the simplex along the canonical basis\n Simplex a -- Resultant simplex.\nmakeSimplexAround initial = fromBlocks [[asColumn initial, cloned + identity]]\n where\n dimension = size initial\n cloned = asColumns (take dimension $ repeat initial)\n identity = ident dimension\n\nscaleBy :: (Num a) => Vector a -> a -> Vector a\nscaleBy v a = runST $ do\n vm <- thawVector\n forM_ [0..((VS.length v) - 1)] $ \\i -> do\n e <- unsafeReadVector vm i\n unsafeWriteVector vm i (e * a)\n freezeVector vm\n", "meta": {"hexsha": "1dfb6a6ff899e1ad09455296279d25ae9304ff38", "size": 12079, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Optimization/NelderMead.hs", "max_stars_repo_name": "agbrooks/buzzwords", "max_stars_repo_head_hexsha": "89fa4ef0dc5a2317b6f19bd05f1d44a5b7aa9763", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-10-10T07:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-10T07:11:28.000Z", "max_issues_repo_path": "src/Optimization/NelderMead.hs", "max_issues_repo_name": "agbrooks/buzzwords", "max_issues_repo_head_hexsha": "89fa4ef0dc5a2317b6f19bd05f1d44a5b7aa9763", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Optimization/NelderMead.hs", "max_forks_repo_name": "agbrooks/buzzwords", "max_forks_repo_head_hexsha": "89fa4ef0dc5a2317b6f19bd05f1d44a5b7aa9763", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7402234637, "max_line_length": 94, "alphanum_fraction": 0.6081629274, "num_tokens": 3400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3484076478956241}} {"text": "{- |\nCopyright: (c) 2020 Thomas Tuegel\nSPDX-License-Identifier: BSD-3-Clause\nMaintainer: Thomas Tuegel \n\n-}\n\nmodule Injection\n ( Injection (..)\n , Retraction (..)\n ) where\n\nimport Data.Complex (Complex ((:+)))\nimport Data.Dynamic (Dynamic, Typeable, fromDynamic, toDyn)\nimport Data.Fixed (Fixed, HasResolution)\nimport Data.Functor.Const (Const (..))\nimport Data.Functor.Identity (Identity (..))\nimport Data.List.NonEmpty (NonEmpty (..))\nimport Data.Maybe (maybeToList)\nimport Data.Monoid (Dual (..))\nimport Data.Monoid (Product (..))\nimport Data.Monoid (Sum (..))\nimport Data.Monoid (Any (..))\nimport Data.Monoid (All (..))\nimport qualified Data.Monoid as Monoid (First (..), Last (..))\nimport Data.Ord (Down (..))\nimport Data.Ratio (Ratio)\nimport qualified Data.Ratio as Ratio\nimport Data.Semigroup (Max (..), Min (..))\nimport qualified Data.Semigroup as Semigroup (First (..), Last (..))\nimport Data.Text (Text)\nimport qualified Data.Text as Text\nimport qualified Data.Text.Lazy as Lazy (Text)\nimport qualified Data.Text.Lazy as Text.Lazy\nimport Data.Void (Void)\nimport Numeric.Natural (Natural)\n\n{- | @Injection@ describes a lossless conversion that includes one type in another.\n\nThe sole method of this class,\n\n> inject :: from -> into\n\ntakes a value @input :: from@ and returns a value @output :: into@ which preserves all the information contained in the input.\nSpecifically, each @input@ is mapped to a /unique/ @output@.\nIn mathematical terminology, @inject@ is /injective/:\n\n> inject a ≡ inject b → a ≡ b\n\nThe name of the class is derived from the mathematical term.\n\n@Injection@ models the \"is-a\" relationship used in languages with subtypes (such as in object-oriented programming),\nbut an explicit cast with @inject@ is required in Haskell.\n\nAlthough it is often possible to infer the type parameters of this class,\nit is advisable to specify one or both of the parameters to @inject@\nusing a type signature or the @TypeApplications@ language extension.\nSpecifying the type parameters will give clearer error messages from the type checker in any case.\n\n-}\nclass Injection from into where\n inject :: from -> into\n\n{- | @Retraction@ undoes an 'Injection'.\n\nBecause 'Injection' is a lossless conversion, we can define a @Retraction@ which undoes it.\nThe method\n\n> retract :: into -> Maybe from\n\nis the (left) inverse of 'inject':\n\n> retract (inject x) = Just x\n\n'retract' is partial (returns 'Maybe') because the type @into@ may be larger than the type @from@;\nthat is, there may be values in @into@ which are not 'inject'-ed from @from@,\nand in that case @retract@ may return 'Nothing'.\n\nAlthough it is often possible to infer the type parameters of this class,\nit is advisable to specify one or both of the parameters to @retract@\nusing a type signature or the @TypeApplications@ language extension.\nSpecifying the type parameters will give clearer error messages from the type checker in any case.\n\n-}\nclass Injection from into => Retraction from into where\n retract :: into -> Maybe from\n\ninstance Injection a a where\n inject = id\n {-# INLINE inject #-}\n\ninstance Retraction a a where\n retract = Just\n {-# INLINE retract #-}\n\ninstance Typeable a => Injection a Dynamic where\n inject = toDyn\n {-# INLINE inject #-}\n\ninstance Typeable a => Retraction a Dynamic where\n retract = fromDynamic\n {-# INLINE retract #-}\n\ninstance Injection a b => Injection a (Maybe b) where\n inject = Just . inject\n {-# INLINE inject #-}\n\ninstance Retraction a b => Retraction a (Maybe b) where\n retract = \\x -> x >>= retract @a @b\n {-# INLINE retract #-}\n\ninstance Injection a b => Injection (Maybe a) [b] where\n inject = maybeToList . fmap (inject @a @b)\n {-# INLINE inject #-}\n\ninstance Retraction a b => Retraction (Maybe a) [b] where\n retract [] = Just Nothing\n retract [b] = Just <$> retract @a @b b\n retract _ = Nothing\n\ninstance Injection Natural Integer where\n inject = toInteger\n {-# INLINE inject #-}\n\ninstance Retraction Natural Integer where\n retract x\n | x < 0 = Nothing\n | otherwise = Just (fromInteger x)\n {-# INLINE retract #-}\n\ninstance Injection Void any where\n inject = \\case {}\n {-# INLINE inject #-}\n\n-- | 'Text.unpack' is the canonical injection @'Text' -> 'String'@.\n-- There is no injection in the other direction because 'String' can represent\n-- invalid surrogate code points, but 'Text' cannot; for details, see\n-- \"Data.Text\".\ninstance Injection Text String where\n inject = Text.unpack\n {-# INLINE inject #-}\n\n-- | 'Text.Lazy.unpack' is the canonical injection @'Lazy.Text' -> 'String'@.\n-- There is no injection in the other direction because 'String' can represent\n-- invalid surrogate code points, but 'Lazy.Text' cannot; for details, see\n-- \"Data.Text.Lazy\".\ninstance Injection Lazy.Text String where\n inject = Text.Lazy.unpack\n {-# INLINE inject #-}\n\ninstance Injection Text Lazy.Text where\n inject = Text.Lazy.fromStrict\n {-# INLINE inject #-}\n\ninstance Injection Lazy.Text Text where\n inject = Text.Lazy.toStrict\n {-# INLINE inject #-}\n\ninstance HasResolution a => Injection Integer (Fixed a) where\n inject = fromInteger\n {-# INLINE inject #-}\n\ninstance HasResolution a => Retraction Integer (Fixed a) where\n retract x = retract @Integer (toRational x)\n {-# INLINE retract #-}\n\ninstance Injection a (Const a b) where\n inject = Const\n {-# INLINE inject #-}\n\ninstance Injection (Const a b) a where\n inject = getConst\n {-# INLINE inject #-}\n\ninstance Injection Integer (Ratio Integer) where\n inject = fromInteger\n {-# INLINE inject #-}\n\ninstance Retraction Integer (Ratio Integer) where\n retract x\n | Ratio.denominator x == 1 = Just (Ratio.numerator x)\n | otherwise = Nothing\n {-# INLINE retract #-}\n\ninstance Num a => Injection a (Complex a) where\n inject = (:+ 0)\n {-# INLINE inject #-}\n\ninstance (Eq a, Num a) => Retraction a (Complex a) where\n retract (x :+ y)\n | y == 0 = Just x\n | otherwise = Nothing\n {-# INLINE retract #-}\n\ninstance Injection a (Identity a) where\n inject = Identity\n {-# INLINE inject #-}\n\ninstance Injection (Identity a) a where\n inject = runIdentity\n {-# INLINE inject #-}\n\ninstance Injection (NonEmpty a) [a] where\n inject (x :| xs) = x : xs\n {-# INLINE inject #-}\n\ninstance Retraction (NonEmpty a) [a] where\n retract (x : xs) = Just (x :| xs)\n retract [] = Nothing\n {-# INLINE retract #-}\n\ninstance Injection a (Down a) where\n inject = pure\n {-# INLINE inject #-}\n\ninstance Injection (Down a) a where\n inject = \\(Down a) -> a\n {-# INLINE inject #-}\n\ninstance Injection a (Product a) where\n inject = pure\n {-# INLINE inject #-}\n\ninstance Injection (Product a) a where\n inject = getProduct\n {-# INLINE inject #-}\n\ninstance Injection a (Sum a) where\n inject = pure\n {-# INLINE inject #-}\n\ninstance Injection (Sum a) a where\n inject = getSum\n {-# INLINE inject #-}\n\ninstance Injection a (Dual a) where\n inject = pure\n {-# INLINE inject #-}\n\ninstance Injection (Dual a) a where\n inject = getDual\n {-# INLINE inject #-}\n\ninstance Injection a (Monoid.Last a) where\n inject = pure\n {-# INLINE inject #-}\n\ninstance Retraction a (Monoid.Last a) where\n retract = Monoid.getLast\n {-# INLINE retract #-}\n\ninstance Injection a (Monoid.First a) where\n inject = pure\n {-# INLINE inject #-}\n\ninstance Retraction a (Monoid.First a) where\n retract = Monoid.getFirst\n {-# INLINE retract #-}\n\ninstance Injection a (Semigroup.First a) where\n inject = pure\n {-# INLINE inject #-}\n\ninstance Injection (Semigroup.First a) a where\n inject = Semigroup.getFirst\n {-# INLINE inject #-}\n\ninstance Injection a (Semigroup.Last a) where\n inject = pure\n {-# INLINE inject #-}\n\ninstance Injection (Semigroup.Last a) a where\n inject = Semigroup.getLast\n {-# INLINE inject #-}\n\ninstance Injection a (Max a) where\n inject = pure\n {-# INLINE inject #-}\n\ninstance Injection (Max a) a where\n inject = getMax\n {-# INLINE inject #-}\n\ninstance Injection a (Min a) where\n inject = pure\n {-# INLINE inject #-}\n\ninstance Injection (Min a) a where\n inject = getMin\n {-# INLINE inject #-}\n\ninstance Injection a (r -> a) where\n inject = const\n {-# INLINE inject #-}\n\ninstance Injection Bool Any where\n inject = Any\n {-# INLINE inject #-}\n\ninstance Injection Any Bool where\n inject = getAny\n {-# INLINE inject #-}\n\ninstance Injection Bool All where\n inject = All\n {-# INLINE inject #-}\n\ninstance Injection All Bool where\n inject = getAll\n {-# INLINE inject #-}\n", "meta": {"hexsha": "864f8608c1008bc13bb9d1006b7e0d632e74ac38", "size": 8655, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Injection.hs", "max_stars_repo_name": "ttuegel/injection", "max_stars_repo_head_hexsha": "e5741923a59c6e762ca776569a3008a13892f06e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Injection.hs", "max_issues_repo_name": "ttuegel/injection", "max_issues_repo_head_hexsha": "e5741923a59c6e762ca776569a3008a13892f06e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Injection.hs", "max_forks_repo_name": "ttuegel/injection", "max_forks_repo_head_hexsha": "e5741923a59c6e762ca776569a3008a13892f06e", "max_forks_repo_licenses": ["BSD-3-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.8295819936, "max_line_length": 126, "alphanum_fraction": 0.6756787984, "num_tokens": 2109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.34548181972574316}} {"text": "{-# LANGUAGE TypeFamilies #-}\n-- | Tools for implementing (and debugging the use of) gradient descent schemes.\nmodule HordeAd.Core.OptimizerTools\n ( updateWithGradient\n , gradientIsNil, minimumGradient, maximumGradient\n , ArgsAdam(..), defaultArgsAdam\n , StateAdam(..), initialStateAdam\n , liftMatrix43, updateWithGradientAdam\n ) where\n\nimport Prelude\n\nimport Control.Monad.ST.Strict (runST)\nimport qualified Data.Array.DynamicS as OT\nimport qualified Data.Vector.Generic as V\nimport qualified Data.Vector.Generic.Mutable as VM\nimport HordeAd.Internal.OrthotopeOrphanInstances (liftVT2)\nimport Numeric.LinearAlgebra (Element, Matrix, Numeric, Vector)\nimport qualified Numeric.LinearAlgebra as HM\nimport Numeric.LinearAlgebra.Data (flatten)\nimport Numeric.LinearAlgebra.Devel\n (MatrixOrder (..), liftMatrix, liftMatrix2, matrixFromVector, orderOf)\n\nimport HordeAd.Internal.Delta (Domains, isTensorDummy)\n\n{-\n60% of heap allocation in matrix- and vector-based MNIST\nwith simple gradient descent (no mini-batches) is performed\nby @updateWithGradient.updateVector@ below\n\n let updateVector i r = i - HM.scale gamma r\n\ndue to allocating once in @scale@ and again in @-@\n(and there seems to be one more allocation judging by the numbers).\nSomething like the following code would be needed to eliminate\none allocation, but it would requre the hmatrix maintainer to expose\ninternal modules.\n\nimport Internal.Vectorized\n ( FunCodeSV (Scale), FunCodeVV (Sub), applyRaw, c_vectorMapValR\n , c_vectorZipR, createVector )\n\nminusTimesGamma :: Storable r => r -> Vector r -> Vector r -> Vector r\nminusTimesGamma gamma u v = unsafePerformIO $ do\n r <- createVector (dim0 u)\n pval <- newArray [gamma]\n (v `applyRaw` (r `applyRaw` id))\n (c_vectorMapValR (fromei Scale) pval)\n #| \"minusTimesGamma1\"\n free pval\n (u `applyRaw` (v `applyRaw` (r `applyRaw` id)))\n (c_vectorZipR (fromei Sub))\n #| \"minusTimesGamma2\"\n return r\n\nBTW, a version with HM.Devel.zipVectorWith makes\nthe test twice slower and allocate twice more\n\n let updateVector = zipVectorWith (\\i r -> i - gamma * r)\n\nand a version with Vector.Storable makes the test thrice slower\nand allocate thrice more\n\n let updateVector = V.zipWith (\\i r -> i - gamma * r)\n\nwhich is probably a bug in stream fusion which, additionally in this case,\ncan't fuse with anything and so can't pay for its overhead.\n\n-}\n\nupdateWithGradient :: (Numeric r, Floating (Vector r))\n => r -> Domains r -> Domains r -> Domains r\nupdateWithGradient gamma (params0, params1, params2, paramsX)\n (gradient0, gradient1, gradient2, gradientX) =\n let updateVector i r = i - HM.scale gamma r\n !params0New = updateVector params0 gradient0\n update1 i r = if V.null r -- eval didn't update it, would crash\n then i\n else updateVector i r\n !params1New = V.zipWith update1 params1 gradient1\n update2 i r = if HM.rows r <= 0 -- eval didn't update it, would crash\n then i\n else liftMatrix2 updateVector i r\n !params2New = V.zipWith update2 params2 gradient2\n updateX i r = if isTensorDummy r -- eval didn't update it, would crash\n then i\n else liftVT2 updateVector i r\n -- TODO: this is slow; add @liftArray2@ and use HM,\n -- unless we move away from HM; similarly other OT calls\n !paramsXNew = V.zipWith updateX paramsX gradientX\n in (params0New, params1New, params2New, paramsXNew)\n\ngradientIsNil :: (Eq r, Numeric r)\n => Domains r -> Bool\ngradientIsNil (gradient0, gradient1, gradient2, gradientX) =\n V.all (== 0) gradient0\n && V.all V.null gradient1\n && V.all (\\r -> HM.rows r <= 0) gradient2\n && V.all isTensorDummy gradientX\n\nminimumGradient :: (Ord r, Numeric r)\n => Domains r -> r\nminimumGradient (gradient0, gradient1, gradient2, gradientX) =\n min (if V.null gradient0 then 0 else HM.minElement gradient0)\n (min (if V.null gradient1 then 0\n else V.minimum (V.map HM.minElement gradient1))\n (min (if V.null gradient2 then 0\n else V.minimum (V.map HM.minElement gradient2))\n (if V.null gradientX then 0\n else V.minimum (V.map OT.minimumA gradientX))))\n\nmaximumGradient :: (Ord r, Numeric r)\n => Domains r -> r\nmaximumGradient (gradient0, gradient1, gradient2, gradientX) =\n max (if V.null gradient0 then 0 else HM.maxElement gradient0)\n (max (if V.null gradient1 then 0\n else V.maximum (V.map HM.maxElement gradient1))\n (max (if V.null gradient2 then 0\n else V.maximum (V.map HM.maxElement gradient2))\n (if V.null gradientX then 0\n else V.maximum (V.map OT.maximumA gradientX))))\n\ndata ArgsAdam r = ArgsAdam\n { alpha :: r\n , betaOne :: r\n , betaTwo :: r\n , epsilon :: r\n }\n\n-- The defaults taken from\n-- https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adam\ndefaultArgsAdam :: Fractional r => ArgsAdam r\ndefaultArgsAdam = ArgsAdam\n { alpha = 0.001\n , betaOne = 0.9\n , betaTwo = 0.999\n , epsilon = 1e-7\n }\n\ndata StateAdam r = StateAdam\n { tAdam :: Int -- iteration count\n , mAdam :: Domains r\n , vAdam :: Domains r\n }\n\n-- The arguments are just sample params0, for dimensions.\nzeroParameters :: Numeric r\n => Domains r -> Domains r\nzeroParameters (params0, params1, params2, paramsX) =\n let zeroVector v = runST $ do\n vThawed <- V.thaw v\n VM.set vThawed 0\n V.unsafeFreeze vThawed\n in ( zeroVector params0\n , V.map zeroVector params1\n , V.map (liftMatrix zeroVector) params2\n , V.map (\\a -> OT.constant (OT.shapeL a) 0) paramsX ) -- fast allright\n\ninitialStateAdam :: Numeric r\n => Domains r -> StateAdam r\ninitialStateAdam parameters0 =\n let zeroP = zeroParameters parameters0\n in StateAdam\n { tAdam = 0\n , mAdam = zeroP\n , vAdam = zeroP\n }\n\n-- | Application of a vector function on the flattened matrices elements.\nliftMatrix43 :: ( Numeric a, Numeric b, Numeric c, Numeric d\n , Element x, Element y, Element z )\n => (Vector a -> Vector b -> Vector c -> Vector d\n -> (Vector x, Vector y, Vector z))\n -> Matrix a -> Matrix b -> Matrix c -> Matrix d\n -> (Matrix x, Matrix y, Matrix z)\nliftMatrix43 f m1 m2 m3 m4 =\n let sz@(r, c) = HM.size m1\n rowOrder = orderOf m1\n -- checking @m4@ (gradient) makes RNN LL test much faster and BB slower\n -- so this needs much more benchmarking and understading to tweak\n in if sz == HM.size m2 && sz == HM.size m3 && sz == HM.size m4\n then\n let (vx, vy, vz) = case rowOrder of\n RowMajor -> f (flatten m1) (flatten m2) (flatten m3) (flatten m4)\n ColumnMajor -> f (flatten (HM.tr' m1)) (flatten (HM.tr' m2))\n (flatten (HM.tr' m3)) (flatten (HM.tr' m4))\n in ( matrixFromVector rowOrder r c vx\n , matrixFromVector rowOrder r c vy\n , matrixFromVector rowOrder r c vz\n )\n else error $ \"nonconformant matrices in liftMatrix43: \"\n ++ show (HM.size m1, HM.size m2, HM.size m3, HM.size m4)\n\n-- TOOD: make sure this is not worse that OT.zipWith3A when transposing\n-- between each application or that we never encounter such situations\n--\n-- | Application of a vector function on the flattened arrays elements.\nliftArray43 :: ( Numeric a, Numeric b, Numeric c, Numeric d\n , Numeric x, Numeric y, Numeric z )\n => (Vector a -> Vector b -> Vector c -> Vector d\n -> (Vector x, Vector y, Vector z))\n -> OT.Array a -> OT.Array b -> OT.Array c -> OT.Array d\n -> (OT.Array x, OT.Array y, OT.Array z)\nliftArray43 f m1 m2 m3 m4 =\n let sz = OT.shapeL m1\n in if sz == OT.shapeL m2 && sz == OT.shapeL m3 && sz == OT.shapeL m4\n then\n let (vx, vy, vz) = f (OT.toVector m1) (OT.toVector m2)\n (OT.toVector m3) (OT.toVector m4)\n in ( OT.fromVector sz vx\n , OT.fromVector sz vy\n , OT.fromVector sz vz\n )\n else error\n $ \"nonconformant arrays in liftArray43: \"\n ++ show (OT.shapeL m1, OT.shapeL m2, OT.shapeL m3, OT.shapeL m4)\n\nupdateWithGradientAdam\n :: forall r. (Numeric r, Floating r, Floating (Vector r))\n => ArgsAdam r -> StateAdam r -> Domains r -> Domains r\n -> (Domains r, StateAdam r)\nupdateWithGradientAdam ArgsAdam{..}\n StateAdam{ tAdam\n , mAdam = (mAdam0, mAdam1, mAdam2, mAdamX)\n , vAdam = (vAdam0, vAdam1, vAdam2, vAdamX)\n }\n (params0, params1, params2, paramsX)\n (gradient0, gradient1, gradient2, gradientX) =\n let tAdamNew = tAdam + 1\n oneMinusBeta1 = 1 - betaOne\n oneMinusBeta2 = 1 - betaTwo\n updateVector :: Vector r -> Vector r\n -> Vector r -> Vector r\n -> (Vector r, Vector r, Vector r)\n updateVector mA vA p g =\n let mANew = HM.scale betaOne mA + HM.scale oneMinusBeta1 g\n vANew = HM.scale betaTwo vA + HM.scale oneMinusBeta2 (g * g)\n alphat = alpha * sqrt (1 - betaTwo ^ tAdamNew)\n / (1 - betaOne ^ tAdamNew)\n in ( mANew\n , vANew\n , p - HM.scale alphat mANew\n / (sqrt vANew + HM.scalar epsilon) ) -- the @scalar@ is safe\n -- @addConstant@ would be better, but it's not exposed\n (!mAdam0New, !vAdam0New, !params0New) =\n updateVector mAdam0 vAdam0 params0 gradient0\n update1 mA vA p g = if V.null g -- eval didn't update it, would crash\n then (mA, vA, p)\n else updateVector mA vA p g\n (!mAdam1New, !vAdam1New, !params1New) =\n V.unzip3 $ V.zipWith4 update1 mAdam1 vAdam1 params1 gradient1\n update2 mA vA p g = if HM.rows g <= 0 -- eval didn't update it; crash\n then (mA, vA, p)\n else liftMatrix43 updateVector mA vA p g\n (!mAdam2New, !vAdam2New, !params2New) =\n V.unzip3 $ V.zipWith4 update2 mAdam2 vAdam2 params2 gradient2\n updateX mA vA p g = if isTensorDummy g -- eval didn't update it\n then (mA, vA, p)\n else liftArray43 updateVector mA vA p g\n (!mAdamXNew, !vAdamXNew, !paramsXNew) =\n V.unzip3 $ V.zipWith4 updateX mAdamX vAdamX paramsX gradientX\n in ( (params0New, params1New, params2New, paramsXNew)\n , StateAdam { tAdam = tAdamNew\n , mAdam = (mAdam0New, mAdam1New, mAdam2New, mAdamXNew)\n , vAdam = (vAdam0New, vAdam1New, vAdam2New, vAdamXNew)\n }\n )\n", "meta": {"hexsha": "f1e457521ff4d45bc031f59232ae34ffb6800430", "size": 11004, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Core/OptimizerTools.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HordeAd/Core/OptimizerTools.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "src/HordeAd/Core/OptimizerTools.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.0597014925, "max_line_length": 80, "alphanum_fraction": 0.6114140313, "num_tokens": 3003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3452606306180124}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# HLINT ignore \"Use camelCase\" #-}\n{-|\nModule : Grenade.Layers.Internal.Add\nDescription : Fast functions for performing convolutions and helper functions\nLicense : BSD2\nStability : experimental\n-}\nmodule Grenade.Layers.Internal.Convolution (\n -- * im2col functions\n im2col\n , col2im\n , col2vid\n , vid2col\n\n -- * convolution functions\n , forwardConv2d\n , forwardBiasConv2d\n , backwardConv2d\n , backwardBiasConv2d\n ) where\n\nimport qualified Data.Vector.Storable as U (unsafeFromForeignPtr0,\n unsafeToForeignPtr0)\n\nimport Foreign (mallocForeignPtrArray,\n withForeignPtr)\nimport Foreign.Ptr (Ptr)\nimport Grenade.Types\nimport Numeric.LinearAlgebra (Matrix, Vector, cols, flatten,\n rows)\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Numeric.LinearAlgebra.Devel as U\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport Grenade.Layers.Internal.Hmatrix\n\n-- | Rearrange the matrix columns into blocks, calculates the number of channels automatically.\ncol2vid :: Int -- ^ kernel rows\n -> Int -- ^ kernel columns \n -> Int -- ^ stride rows\n -> Int -- ^ stride columns\n -> Int -- ^ input height\n -> Int -- ^ input width\n -> Matrix RealNum -- ^ input matrix\n -> Matrix RealNum -- ^ output matrix \ncol2vid kernelRows kernelColumns strideRows strideColumns height width dataCol =\n let channels = cols dataCol `div` (kernelRows * kernelColumns)\n outRows = (height - kernelRows) `div` strideRows + 1\n outCols = (width - kernelColumns) `div` strideColumns + 1\n in col2im_c channels height width kernelRows kernelColumns strideRows strideColumns 0 0 outRows outCols dataCol\n\n-- | Rearrange the matrix columns into blocks, assumes there is only one channel\ncol2im :: Int -- ^ kernel rows\n -> Int -- ^ kernel columns \n -> Int -- ^ stride rows\n -> Int -- ^ stride columns\n -> Int -- ^ input height\n -> Int -- ^ input width\n -> Matrix RealNum -- ^ input matrix\n -> Matrix RealNum -- ^ output matrix \ncol2im kernelRows kernelColumns strideRows strideColumns height width dataCol =\n let channels = 1\n outRows = (height - kernelRows) `div` strideRows + 1\n outCols = (width - kernelColumns) `div` strideColumns + 1\n in col2im_c channels height width kernelRows kernelColumns strideRows strideColumns 0 0 outRows outCols dataCol\n\ncol2im_c :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix RealNum -> Matrix RealNum\ncol2im_c channels height width kernelRows kernelColumns strideRows strideColumns padl padt outRows outCols dataCol =\n let vec = flatten dataCol\n in unsafePerformIO $ do\n outPtr <- mallocForeignPtrArray (height * width * channels)\n let (inPtr, _) = U.unsafeToForeignPtr0 vec\n\n withForeignPtr inPtr $ \\inPtr' ->\n withForeignPtr outPtr $ \\outPtr' ->\n col2im_cpu inPtr' channels height width kernelRows kernelColumns strideRows strideColumns padt padl outRows outCols outPtr'\n\n let matVec = U.unsafeFromForeignPtr0 outPtr (height * width * channels)\n return $ U.matrixFromVector U.RowMajor (height * channels) width matVec\n{-# INLINE col2im_c #-}\n\nforeign import ccall unsafe\n col2im_cpu\n :: Ptr RealNum -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr RealNum -> IO ()\n\n-- | Rearrange the matrix blocks into columns, calculates the number of channels automatically.\nvid2col :: Int -- ^ kernel rows\n -> Int -- ^ kernel columns \n -> Int -- ^ stride rows\n -> Int -- ^ stride columns\n -> Int -- ^ input height\n -> Int -- ^ input width\n -> Matrix RealNum -- ^ input matrix\n -> Matrix RealNum -- ^ output matrix \nvid2col kernelRows kernelColumns strideRows strideColumns height width dataVid =\n let channels = rows dataVid `div` height\n rowOut = (height - kernelRows) `div` strideRows + 1\n colOut = (width - kernelColumns) `div` strideColumns + 1\n in im2col_c channels height width kernelRows kernelColumns strideRows strideColumns 0 0 dataVid rowOut colOut\n\n-- | Rearrange the matrix blocks into columns, assumes there is only one channel\nim2col :: Int -- ^ kernel rows\n -> Int -- ^ kernel columns \n -> Int -- ^ stride rows\n -> Int -- ^ stride columns\n -> Matrix RealNum -- ^ input matrix\n -> Matrix RealNum -- ^ output matrix \nim2col kernelRows kernelColumns strideRows strideColumns dataIm =\n let channels = 1\n height = rows dataIm\n width = cols dataIm\n rowOut = (height - kernelRows) `div` strideRows + 1\n colOut = (width - kernelColumns) `div` strideColumns + 1\n in im2col_c channels height width kernelRows kernelColumns strideRows strideColumns 0 0 dataIm rowOut colOut\n\nim2col_c :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix RealNum -> Int -> Int -> Matrix RealNum\nim2col_c channels height width kernelRows kernelColumns strideRows strideColumns padl padt dataIm outRows outCols =\n let vec = flatten dataIm\n kernelSize = kernelRows * kernelColumns\n numberOfPatches = outRows * outCols\n in unsafePerformIO $ do\n outPtr <- mallocForeignPtrArray (numberOfPatches * kernelSize * channels)\n let (inPtr, _) = U.unsafeToForeignPtr0 vec\n\n withForeignPtr inPtr $ \\inPtr' ->\n withForeignPtr outPtr $ \\outPtr' ->\n im2col_cpu inPtr' channels height width kernelRows kernelColumns strideRows strideColumns padt padl outRows outCols outPtr'\n\n let matVec = U.unsafeFromForeignPtr0 outPtr (numberOfPatches * kernelSize * channels)\n return $ U.matrixFromVector U.RowMajor (kernelSize * channels) numberOfPatches matVec\n{-# INLINE im2col_c #-}\n\nforeign import ccall unsafe\n im2col_cpu\n :: Ptr RealNum -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr RealNum -> IO ()\n\nforeign import ccall unsafe\n in_place_add_per_channel_cpu\n :: Ptr RealNum -> Int -> Int -> Int -> Ptr RealNum -> IO ()\n\n-- | Efficient implementation of convolutions using the im2col trick as popularised by Caffe\nforwardConv2d :: Matrix RealNum -- ^ input\n -> Int -- ^ input channels\n -> Int -- ^ input rows\n -> Int -- ^ input columns\n -> Matrix RealNum -- ^ kernel\n -> Int -- ^ kernel filters\n -> Int -- ^ kernel rows\n -> Int -- ^ kernel columns\n -> Int -- ^ stride height\n -> Int -- ^ stride width\n -> Int -- ^ output rows\n -> Int -- ^ output columns\n -> Int -- ^ pad left\n -> Int -- ^ pad top\n -> Matrix RealNum -- ^ output of convolution\nforwardConv2d input channels rows cols kernel filters kernelRows kernelCols strideRows strideCols outRows outCols padLeft padTop\n = let dataCol = im2col_c channels rows cols kernelRows kernelCols strideRows strideCols padLeft padTop input outRows outCols\n gemmM = LA.tr kernel LA.<> dataCol\n dataVid = reshapeMatrix (filters * outRows) outCols gemmM\n in dataVid\n\n-- | Efficient implementation of convolutions using the im2col trick as popularised by Caffe\n-- also adds some bias to the functions, note that it does it in place to prevent unnecessary allocation.\nforwardBiasConv2d :: Matrix RealNum -- ^ input\n -> Int -- ^ input channels\n -> Int -- ^ input rows\n -> Int -- ^ input columns\n -> Vector RealNum -- ^ bias\n -> Matrix RealNum -- ^ kernel\n -> Int -- ^ kernel filters\n -> Int -- ^ kernel rows\n -> Int -- ^ kernel columns\n -> Int -- ^ stride height\n -> Int -- ^ stride width\n -> Int -- ^ output rows\n -> Int -- ^ output columns\n -> Int -- ^ pad left\n -> Int -- ^ pad top\n -> Matrix RealNum -- ^ output of convolution\nforwardBiasConv2d input channels rows cols bias kernel filters kernelRows kernelCols strideRows strideCols outRows outCols padLeft padTop =\n let outSize = outRows * outCols * filters\n in unsafePerformIO $ do\n let dataCol = im2col_c channels rows cols kernelRows kernelCols strideRows strideCols padLeft padTop input outRows outCols\n gemmM = LA.tr kernel LA.<> dataCol\n dataVid = flatten gemmM\n (xPtr, _) = U.unsafeToForeignPtr0 dataVid\n (bPtr, _) = U.unsafeToForeignPtr0 bias\n\n withForeignPtr xPtr $ \\xPtr' ->\n withForeignPtr bPtr $ \\bPtr' ->\n in_place_add_per_channel_cpu xPtr' filters outRows outCols bPtr'\n\n let matVec = U.unsafeFromForeignPtr0 xPtr outSize\n return $ U.matrixFromVector U.RowMajor (outRows * filters) outCols matVec\n\n-- | Efficient implementation of the backward pass for convolutions using the im2col trick as popularised by Caffe\nbackwardConv2d :: Matrix RealNum -- ^ input\n -> Int -- ^ input channels\n -> Int -- ^ input rows\n -> Int -- ^ input columns\n -> Matrix RealNum -- ^ kernel\n -> Int -- ^ kernel filters\n -> Int -- ^ kernel rows\n -> Int -- ^ kernel columns\n -> Int -- ^ stride height\n -> Int -- ^ stride width\n -> Int -- ^ pad left\n -> Int -- ^ pad top\n -> Int -- ^ pad right\n -> Int -- ^ pad bottom\n -> Matrix RealNum -- ^ derivative wrt out of layer\n -> Int -- ^ output rows\n -> Int -- ^ output columns\n -> (Matrix RealNum, Matrix RealNum) -- ^ (derivated wrt input, derivative wrt kernel)\nbackwardConv2d input channels rows cols kernel filters kernelRows kernelCols strideRows strideCols padl padt padr padb dout outRows outCols =\n let dout' = LA.reshape (outRows * outCols) $ LA.flatten dout\n dX_col = kernel LA.<> dout'\n rowCol = (div (rows + padt + padb - kernelRows) strideRows) + 1\n colCol = (div (cols + padl + padr - kernelCols) strideCols) + 1\n dX = col2im_c channels rows cols kernelRows kernelCols strideRows strideCols padl padt rowCol colCol dX_col\n\n x_col = im2col_c channels rows cols kernelRows kernelCols strideRows strideCols padl padt input outRows outCols\n dw_col = dout' LA.<> (LA.tr x_col)\n dw = LA.tr $ reshapeMatrix filters (kernelRows * kernelCols * channels) dw_col \n in (dX, dw) \n\n-- | Efficient implementation of the backward pass for convolutions using the im2col trick as popularised by Caffe\nbackwardBiasConv2d :: Matrix RealNum -- ^ input\n -> Int -- ^ input channels\n -> Int -- ^ input rows\n -> Int -- ^ input columns\n -> Matrix RealNum -- ^ kernel\n -> Int -- ^ kernel filters\n -> Int -- ^ kernel rows\n -> Int -- ^ kernel columns\n -> Int -- ^ stride height\n -> Int -- ^ stride width\n -> Int -- ^ pad left\n -> Int -- ^ pad top\n -> Int -- ^ pad right\n -> Int -- ^ pad bottom\n -> Matrix RealNum -- ^ derivative wrt out of layer\n -> Int -- ^ output rows\n -> Int -- ^ output columns\n -> (Matrix RealNum, Matrix RealNum, Vector RealNum) -- ^ (derivated wrt input, derivative wrt kernel, derivative wrt bias)\nbackwardBiasConv2d input channels rows cols kernel filters kernelRows kernelCols strideRows strideCols padl padt padr padb dout outRows outCols =\n let (dX, dw) = backwardConv2d input channels rows cols kernel filters kernelRows kernelCols strideRows strideCols padl padt padr padb dout outRows outCols\n dB = sum_over_channels_c dout filters outRows outCols\n in (dX, dw, dB)\n\nsum_over_channels_c :: Matrix RealNum -> Int -> Int -> Int -> Vector RealNum\nsum_over_channels_c mat channels rows cols = unsafePerformIO $ do\n let (xPtr, _) = U.unsafeToForeignPtr0 . flatten $ mat\n outPtr <- mallocForeignPtrArray channels\n\n withForeignPtr xPtr $ \\xPtr' ->\n withForeignPtr outPtr $ \\outPtr' ->\n sum_over_channels_cpu xPtr' channels rows cols outPtr'\n\n return $ U.unsafeFromForeignPtr0 outPtr channels\n\nforeign import ccall unsafe\n sum_over_channels_cpu\n :: Ptr RealNum -> Int -> Int -> Int -> Ptr RealNum -> IO ()\n", "meta": {"hexsha": "7231eb1e040915813837ac55c63b2b35d7e37c98", "size": 13496, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Internal/Convolution.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/Internal/Convolution.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Internal/Convolution.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.3582089552, "max_line_length": 156, "alphanum_fraction": 0.5878037937, "num_tokens": 3140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.34410822933137425}} {"text": "{-# LANGUAGE CPP, OverloadedStrings, TypeOperators #-}\n\nmodule Main where\n\nimport Control.Exception\nimport qualified Data.Array.Accelerate as A\nimport qualified Data.Array.Accelerate.Interpreter as ALI\nimport Data.Array.Accelerate.Math.Hilbert\nimport Data.Array.Accelerate.Math.Qtfd\nimport Data.Array.Accelerate.Math.WindowFunc\nimport Data.Attoparsec.Text\nimport ParseArgs\nimport ParseFile\nimport System.Directory\n#ifdef ACCELERATE_LLVM_NATIVE_BACKEND\nimport qualified Data.Array.Accelerate.LLVM.Native as ALN\n#endif\n#ifdef ACCELERATE_LLVM_PTX_BACKEND\nimport qualified Data.Array.Accelerate.LLVM.PTX as ALP\n#endif\nimport Data.Array.Accelerate.Array.Sugar as S\nimport qualified Data.ByteString.Builder as BB\nimport Data.Complex\nimport qualified Data.Double.Conversion.Convertable as DC\nimport Data.List\nimport Data.Monoid\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as TI\nimport qualified Data.Vector as V\nimport GHC.Float\nimport Math.Gamma\nimport System.IO\n\n\nmain :: IO ()\nmain = do\n args <- opts\n makeQTFDAll args\n\n-- | Transform data to text(using Float conversion. It is much faster) and write it to file.\n\nwriteData ::\n Handle -- ^ output file\n -> [Float] -- ^ Data to write\n -> Int -- ^ number of element\n -> Int -- ^ elements per row\n -> IO ()\nwriteData _ [] _ _ = return ()\nwriteData file (x:xs) w n = do\n TI.hPutStr file $ DC.toPrecision 5 x <> \" \"\n if (n `mod` w) == 0\n then do\n TI.hPutStr file \"\\n\"\n writeData file xs w (n + 1)\n else writeData file xs w (n + 1)\n\nmakeString ::\n Handle\n -> [Float] -- ^ Data to write\n -> Int -- ^ number of element\n -> Int -- ^ elements per row\n -> BB.Builder\n -> IO ()\nmakeString _ [] _ _ _ = return ()\nmakeString file (x:xs) w n acc =\n if (n `mod` w) == 0\n then BB.hPutBuilder file (acc <> DC.toPrecision 5 x <> \" \" <> \"\\n\") >> makeString file xs w (n+1) \"\"\n else makeString file xs w (n+1) (acc <> DC.toPrecision 5 x <> \" \")\n\n-- | make Pseudo Wigner-Ville transform to all files in a directory.\n\nmakeQTFDAll :: Opts -> IO ()\nmakeQTFDAll opts = do\n let path = getPath opts\n nosAVGflag = subAVGflag opts\n files <- listDirectory path\n setCurrentDirectory path\n let fFiles = filter (isSuffixOf \".txt\") files\n sAVGflag = A.constant $ not nosAVGflag\n case opts of\n (OptsPWV _ dev wlen wfun _) ->\n do\n if (even wlen)\n then error \"Window length maust be odd !\"\n else\n do\n let window = makeWindow wfun (A.unit $ A.constant wlen) :: A.Acc (A.Array A.DIM1 Float)\n mapM_ (makePWV dev window sAVGflag) fFiles\n (OptsWV path dev nosAVGflag) -> mapM_ (makeWV dev sAVGflag) fFiles\n (OptsCW path dev sigma uWindow uWindowFunc nWindow nWindowFunc normalise nosAVGflag) ->\n do\n if (even uWindow || even nWindow)\n then error \"Window length maust be odd !\"\n else\n let uWindowArray = makeWindow uWindowFunc (A.unit $ A.constant uWindow) :: A.Acc (A.Array A.DIM1 Float)\n nWindowArray = makeWindow nWindowFunc (A.unit $ A.constant nWindow) :: A.Acc (A.Array A.DIM1 Float)\n bothRectangular = uWindowFunc == Rect && nWindowFunc == Rect\n in mapM_ (makeCW dev sAVGflag sigma uWindowArray nWindowArray normalise bothRectangular) fFiles\n (OptsBJ path dev alpha uWindow uWindowFunc nWindow nWindowFunc nosAVGflag) ->\n do\n if (even uWindow || even nWindow)\n then error \"Window length maust be odd !\"\n else\n let uWindowArray = makeWindow uWindowFunc (A.unit $ A.constant uWindow) :: A.Acc (A.Array A.DIM1 Float)\n nWindowArray = makeWindow nWindowFunc (A.unit $ A.constant nWindow) :: A.Acc (A.Array A.DIM1 Float)\n bothRectangular = uWindowFunc == Rect && nWindowFunc == Rect\n in mapM_ (makeBJ dev sAVGflag alpha uWindowArray nWindowArray bothRectangular) fFiles\n (OptsEMBD path dev alpha beta uWindow uWindowFunc nWindow nWindowFunc normalise nosAVGflag) ->\n do\n if (even uWindow || even nWindow)\n then error \"Window length maust be odd !\"\n else let gammas = makeGammaArray beta uWindow\n uWindowArray = makeWindow uWindowFunc (A.unit $ A.constant uWindow) :: A.Acc (A.Array A.DIM1 Float)\n nWindowArray = makeWindow nWindowFunc (A.unit $ A.constant nWindow) :: A.Acc (A.Array A.DIM1 Float)\n bothRectangular = uWindowFunc == Rect && nWindowFunc == Rect\n in mapM_ (makeEMBD dev sAVGflag alpha gammas uWindowArray nWindowArray bothRectangular normalise) fFiles\n return ()\n\nmakeCW :: CalcDev -- ^ Calculation device - CPU or GPU\n -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column.\n -> Float -- ^ sigma\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd.\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd.\n -> Bool -- ^ if the core array should be normalised\n -> Bool -- ^ if Both windows are rectangular\n -> FilePath -- ^ Name of file with data.\n -> IO ()\nmakeCW dev sAVGflag sigma uWindowArray nWindowArray normalise bothRect file = do\n putStrLn $ \"processing \" ++ file ++ \"...\"\n text <- TI.readFile file\n let parseRes = parseOnly parseFile text\n case parseRes of\n (Left errStr) -> error $ errStr\n (Right dataF) -> mapM_ (startCW dev file sAVGflag sigma uWindowArray nWindowArray normalise bothRect) dataF\n\nmakeBJ :: CalcDev -- ^ Calculation device - CPU or GPU\n -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column.\n -> Float -- ^ sigma\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd.\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd.\n -> Bool -- ^ if Both windows are rectangular\n -> FilePath -- ^ Name of file with data.\n -> IO ()\nmakeBJ dev sAVGflag alpha uWindowArray nWindowArray bothRect file = do\n putStrLn $ \"processing \" ++ file ++ \"...\"\n text <- TI.readFile file\n let parseRes = parseOnly parseFile text\n case parseRes of\n (Left errStr) -> error $ errStr\n (Right dataF) -> mapM_ (startBJ dev file sAVGflag alpha uWindowArray nWindowArray bothRect) dataF\n\n-- | Make Pseudo Wigner-Ville transform to all columns in the given file\n\nmakePWV ::\n CalcDev -- ^ Calculation device - CPU or GPU\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd.\n -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column.\n -> FilePath -- ^ Name of file with data.\n -> IO ()\nmakePWV dev window sAVGflag file = do\n putStrLn $ \"processing \" ++ file ++ \"...\"\n text <- TI.readFile file\n let parseRes = parseOnly parseFile text\n case parseRes of\n (Left errStr) -> error $ errStr\n (Right dataF) -> mapM_ (startPWV dev window file sAVGflag) dataF\n\n--makeEMBD dev alpha gammas uWindowArray nWindowArray bothRectangular normalise \n\nmakeEMBD :: CalcDev -- ^ Calculation device - CPU or GPU\n -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column.\n -> Float -- ^ alpha\n -> [Float] -- ^ gammas \n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd.\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd.\n -> Bool -- ^ if the core array should be normalised\n -> Bool -- ^ if Both windows are rectangular\n -> FilePath -- ^ Name of file with data.\n -> IO ()\nmakeEMBD dev sAVGflag alpha gammas uWindowArray nWindowArray normalise bothRect file = do\n putStrLn $ \"processing \" ++ file ++ \"...\"\n text <- TI.readFile file\n let parseRes = parseOnly parseFile text\n case parseRes of\n (Left errStr) -> error $ errStr\n (Right dataF) -> mapM_ (startEMBD dev file sAVGflag alpha gammas uWindowArray nWindowArray normalise bothRect) dataF\n\n-- | Make Pseudo Wigner-Ville transform to the given column.\n-- At first it makes subtraction of average value (if supAVGflag) and applies hilbert transform to make analytic signal. After that it applies Pseudo-Wigner transftorm\n-- and save data to file with\n\n\nstartPWV ::\n CalcDev -- ^ Calculation device - CPU or GPU\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd.\n -> FilePath -- ^ Name of file with data.\n -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column.\n -> (T.Text,[Float]) -- ^ Name of column and parsed data from column\n -> IO ()\nstartPWV dev window oldName sAVGflag (column_name,dataF) = do\n let newFName = oldName ++ \"-\" ++ T.unpack column_name ++ \".txt\"\n putStr $ \" Creating file \" ++ newFName ++ \" ...\"\n let leng = length dataF\n pData = A.fromList (A.Z A.:. leng) dataF\n appPWV = (pWignerVille window) . hilbert . supAVG sAVGflag\n processed = case dev of\n#ifdef ACCELERATE_LLVM_NATIVE_BACKEND\n CPU -> ALN.run1 appPWV pData\n#endif\n#ifdef ACCELERATE_LLVM_PTX_BACKEND\n GPU -> ALP.run1 appPWV pData\n#endif\n CPU -> ALI.run1 appPWV pData\n GPU -> error \"Compiled without GPU support\"\n pList = S.toList $! processed\n file <- openFile newFName WriteMode\n onException (writeData file pList leng 1) (removeFile newFName)\n hClose file\n putStrLn \"Done !\"\n\n-- | Make Wigner-Ville transform to all columns in the given file\n\nmakeWV ::\n CalcDev -- ^ Calculation device - CPU or GPU\n -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column.\n -> FilePath -- ^ Name of file with data.\n -> IO ()\nmakeWV dev sAVGflag file = do\n putStrLn $ \"processing \" ++ file ++ \"...\"\n text <- TI.readFile file\n let parseRes = parseOnly parseFile text\n case parseRes of\n (Left errStr) -> error $ errStr\n (Right dataF) -> mapM_ (startWV dev file sAVGflag) dataF\n\n-- | Make Wigner-Ville transform to the given column.\n-- At first it makes subtraction of average value (if supAVGflag) and applies hilbert transform to make analytic signal. After that it applies Pseudo-Wigner transftorm\n-- and save data to file with\n\nstartWV ::\n CalcDev -- ^ Calculation device - CPU or GPU\n -> FilePath -- ^ Name of file with data.\n -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column.\n -> (T.Text,[Float]) -- ^ Name of column and parsed data from column\n -> IO ()\nstartWV dev oldName sAVGflag (column_name,dataF) = do\n let newFName = oldName ++ \"-\" ++ T.unpack column_name ++ \".txt\"\n putStr $ \" Creating file \" ++ newFName ++ \" ...\"\n let leng = length dataF\n pData = A.fromList (A.Z A.:. leng) dataF\n appWV = wignerVilleNew . hilbert . supAVG sAVGflag\n appWVGPU = wignerVille . hilbert . supAVG sAVGflag\n processed = case dev of\n#ifdef ACCELERATE_LLVM_NATIVE_BACKEND\n CPU -> ALN.run1 appWV pData\n#endif\n#ifdef ACCELERATE_LLVM_PTX_BACKEND\n GPU -> ALP.run1 appWV pData\n#endif\n CPU -> ALI.run1 appWV pData\n GPU -> error \"Compiled without GPU support\"\n pList = S.toList $ processed\n file <- openFile newFName WriteMode\n hSetBinaryMode file True >> hSetBuffering file LineBuffering\n -- let resultBsBuilder = makeString pList leng 1 \"\"\n onException (makeString file pList leng 1 \"\") (removeFile newFName) >> hFlush file\n hClose file\n putStrLn \"Done !\"\n\nstartCW ::\n CalcDev -- ^ Calculation device - CPU or GPU\n -> FilePath -- ^ Name of file with data.\n -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column.\n -> Float -- ^ Sigma\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd.\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd.\n -> Bool -- ^ if the core array should be normalised\n -> Bool -- ^ if Both windows are rectangular\n -> (T.Text,[Float]) -- ^ Name of column and parsed data from column\n -> IO ()\nstartCW dev oldName sAVGflag sigma uWindowArray nWindowArray normalise bothRect (column_name,dataF) = do\n let newFName = oldName ++ \"-\" ++ T.unpack column_name ++ \".txt\"\n putStr $ \" Creating file \" ++ newFName ++ \" ...\"\n let leng = length dataF\n uWindow = A.length uWindowArray\n nWindow = A.length nWindowArray\n mWindowArrays = if bothRect then Nothing else Just (uWindowArray,nWindowArray)\n pData = A.fromList (A.Z A.:. leng) dataF\n appCW = (choiWilliams (A.constant sigma) mWindowArrays uWindow nWindow normalise) . hilbert . supAVG sAVGflag\n processed = case dev of\n#ifdef ACCELERATE_LLVM_NATIVE_BACKEND\n CPU -> ALN.run1 appCW pData\n#endif\n#ifdef ACCELERATE_LLVM_PTX_BACKEND\n GPU -> ALP.run1 appCW pData\n#endif\n CPU -> ALI.run1 appCW pData\n GPU -> error \"Compiled without GPU support\"\n pList = S.toList $ processed\n file <- openFile newFName WriteMode\n onException (writeData file pList leng 1) (removeFile newFName)\n hClose file\n putStrLn \"Done !\"\n\nstartBJ ::\n CalcDev -- ^ Calculation device - CPU or GPU\n -> FilePath -- ^ Name of file with data.\n -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column.\n -> Float -- ^ Sigma\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd.\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd.\n -> Bool -- ^ if Both windows are rectangular\n -> (T.Text,[Float]) -- ^ Name of column and parsed data from column\n -> IO ()\nstartBJ dev oldName sAVGflag alpha uWindowArray nWindowArray bothRect (column_name,dataF) = do\n let newFName = oldName ++ \"-\" ++ T.unpack column_name ++ \".txt\"\n putStr $ \" Creating file \" ++ newFName ++ \" ...\"\n let leng = length dataF\n uWindow = A.length uWindowArray\n nWindow = A.length nWindowArray\n mWindowArrays = if bothRect then Nothing else Just (uWindowArray,nWindowArray)\n pData = A.fromList (A.Z A.:. leng) dataF\n appCW = (bornJordan (A.constant alpha) mWindowArrays uWindow nWindow) . hilbert . supAVG sAVGflag\n processed = case dev of\n#ifdef ACCELERATE_LLVM_NATIVE_BACKEND\n CPU -> ALN.run1 appCW pData\n#endif\n#ifdef ACCELERATE_LLVM_PTX_BACKEND\n GPU -> ALP.run1 appCW pData\n#endif\n CPU -> ALI.run1 appCW pData\n GPU -> error \"Compiled without GPU support\"\n pList = S.toList $ processed\n file <- openFile newFName WriteMode\n onException (writeData file pList leng 1) (removeFile newFName)\n hClose file\n putStrLn \"Done !\"\n\nstartEMBD ::\n CalcDev -- ^ Calculation device - CPU or GPU\n -> FilePath -- ^ Name of file with data.\n -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column.\n -> Float -- ^ Alpha \n -> [Float] -- ^ Gammas \n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd.\n -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd.\n -> Bool -- ^ if the core array should be normalised\n -> Bool -- ^ if Both windows are rectangular\n -> (T.Text,[Float]) -- ^ Name of column and parsed data from column\n -> IO ()\nstartEMBD dev oldName sAVGflag alpha gammas uWindowArray nWindowArray normalise bothRect (column_name,dataF) = do\n let newFName = oldName ++ \"-\" ++ T.unpack column_name ++ \".txt\"\n putStr $ \" Creating file \" ++ newFName ++ \" ...\"\n let leng = length dataF\n uWindow = A.length uWindowArray\n nWindow = A.length nWindowArray\n gammasArr = A.use $ A.fromList (A.Z A.:. (length gammas)) gammas \n mWindowArrays = if bothRect then Nothing else Just (uWindowArray,nWindowArray)\n pData = A.fromList (A.Z A.:. leng) dataF\n appEMBD = (eModifiedB (A.constant alpha) gammasArr mWindowArrays uWindow nWindow normalise) . hilbert . supAVG sAVGflag\n processed = case dev of\n#ifdef ACCELERATE_LLVM_NATIVE_BACKEND\n CPU -> ALN.run1 appEMBD pData\n#endif\n#ifdef ACCELERATE_LLVM_PTX_BACKEND\n GPU -> ALP.run1 appEMBD pData\n#endif\n CPU -> ALI.run1 appEMBD pData\n GPU -> error \"Compiled without GPU support\"\n pList = S.toList $ processed\n file <- openFile newFName WriteMode\n onException (writeData file pList leng 1) (removeFile newFName)\n hClose file\n putStrLn \"Done !\"\n\n\n-- | Subtraction of average value from all elements of column\n\nsupAVG :: A.Exp Bool -> A.Acc (Array DIM1 Float) -> A.Acc (Array DIM1 Float)\nsupAVG flag arr =\n A.acond flag (A.map (\\x -> x - avg) arr) arr\n where leng = A.length arr\n avg = (A.the $ A.sum arr)/(A.fromIntegral leng)\n\n\nmakeGammaArray :: Float -> Int -> [Float]\nmakeGammaArray beta wLength =\n let dwLength = fromIntegral wLength :: Float\n v = [(-0.5), ((-0.5) + 1.0/dwLength)..0.5]\n s = map (\\x -> beta :+ pi*x) v\n f = map (\\x -> abs $ ((magnitude $ gamma x) ^ 2)/((gamma beta) ^ 2)) s\n n = floor $ (fromIntegral $ length f)/2.0\n frst = Data.List.take (n-1) f\n secnd = Data.List.drop n f\n in secnd ++ frst\n", "meta": {"hexsha": "9b3d8744be75d1fcbe51ebfda672e60973945170", "size": 18082, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "Haskell-mouse/WVille", "max_stars_repo_head_hexsha": "e71506773f587510a4b1832e8a649b6135a85373", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T13:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T13:56:35.000Z", "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "Haskell-mouse/WVille", "max_issues_repo_head_hexsha": "e71506773f587510a4b1832e8a649b6135a85373", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "Haskell-mouse/WVille", "max_forks_repo_head_hexsha": "e71506773f587510a4b1832e8a649b6135a85373", "max_forks_repo_licenses": ["BSD-3-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.6616161616, "max_line_length": 167, "alphanum_fraction": 0.6320097334, "num_tokens": 4817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.5, "lm_q1q2_score": 0.342974733924196}} {"text": "{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, OverloadedStrings,\n RecordWildCards #-}\n\n-- |\n-- Module : Statistics.Resampling.Bootstrap\n-- Copyright : (c) 2009, 2011 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- The bootstrap method for statistical inference.\n\nmodule Statistics.Resampling.Bootstrap\n (\n Estimate(..)\n , bootstrapBCA\n , scale\n -- * References\n -- $references\n ) where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.DeepSeq (NFData)\nimport Control.Exception (assert)\nimport Control.Monad.Par (parMap, runPar)\nimport Data.Aeson (FromJSON, ToJSON)\nimport Data.Binary (Binary)\nimport Data.Binary (put, get)\nimport Data.Data (Data)\nimport Data.Typeable (Typeable)\nimport Data.Vector.Unboxed ((!))\nimport GHC.Generics (Generic)\nimport Statistics.Distribution (cumulative, quantile)\nimport Statistics.Distribution.Normal\nimport Statistics.Resampling (Resample(..), jackknife)\nimport Statistics.Sample (mean)\nimport Statistics.Types (Estimator, Sample)\nimport qualified Data.Vector.Unboxed as U\nimport qualified Statistics.Resampling as R\n\n-- | A point and interval estimate computed via an 'Estimator'.\ndata Estimate = Estimate {\n estPoint :: {-# UNPACK #-} !Double\n -- ^ Point estimate.\n , estLowerBound :: {-# UNPACK #-} !Double\n -- ^ Lower bound of the estimate interval (i.e. the lower bound of\n -- the confidence interval).\n , estUpperBound :: {-# UNPACK #-} !Double\n -- ^ Upper bound of the estimate interval (i.e. the upper bound of\n -- the confidence interval).\n , estConfidenceLevel :: {-# UNPACK #-} !Double\n -- ^ Confidence level of the confidence intervals.\n } deriving (Eq, Read, Show, Typeable, Data, Generic)\n\ninstance FromJSON Estimate\ninstance ToJSON Estimate\n\ninstance Binary Estimate where\n put (Estimate w x y z) = put w >> put x >> put y >> put z\n get = Estimate <$> get <*> get <*> get <*> get\ninstance NFData Estimate\n\n-- | Multiply the point, lower bound, and upper bound in an 'Estimate'\n-- by the given value.\nscale :: Double -- ^ Value to multiply by.\n -> Estimate -> Estimate\nscale f e@Estimate{..} = e {\n estPoint = f * estPoint\n , estLowerBound = f * estLowerBound\n , estUpperBound = f * estUpperBound\n }\n\nestimate :: Double -> Double -> Double -> Double -> Estimate\nestimate pt lb ub cl =\n assert (lb <= ub) .\n assert (cl > 0 && cl < 1) $\n Estimate { estPoint = pt\n , estLowerBound = lb\n , estUpperBound = ub\n , estConfidenceLevel = cl\n }\n\ndata T = {-# UNPACK #-} !Double :< {-# UNPACK #-} !Double\ninfixl 2 :<\n\n-- | Bias-corrected accelerated (BCA) bootstrap. This adjusts for both\n-- bias and skewness in the resampled distribution.\nbootstrapBCA :: Double -- ^ Confidence level\n -> Sample -- ^ Sample data\n -> [Estimator] -- ^ Estimators\n -> [Resample] -- ^ Resampled data\n -> [Estimate]\nbootstrapBCA confidenceLevel sample estimators resamples\n | confidenceLevel > 0 && confidenceLevel < 1\n = runPar $ parMap (uncurry e) (zip estimators resamples)\n | otherwise = error \"Statistics.Resampling.Bootstrap.bootstrapBCA: confidence level outside (0,1) range\"\n where\n e est (Resample resample)\n | U.length sample == 1 || isInfinite bias =\n estimate pt pt pt confidenceLevel\n | otherwise =\n estimate pt (resample ! lo) (resample ! hi) confidenceLevel\n where\n pt = R.estimate est sample\n lo = max (cumn a1) 0\n where a1 = bias + b1 / (1 - accel * b1)\n b1 = bias + z1\n hi = min (cumn a2) (ni - 1)\n where a2 = bias + b2 / (1 - accel * b2)\n b2 = bias - z1\n z1 = quantile standard ((1 - confidenceLevel) / 2)\n cumn = round . (*n) . cumulative standard\n bias = quantile standard (probN / n)\n where probN = fromIntegral . U.length . U.filter (\n", "meta": {"hexsha": "e1eef10d95108815345e0414810fdedc675f570d", "size": 4730, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Resampling/Bootstrap.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/Resampling/Bootstrap.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/Resampling/Bootstrap.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": 36.106870229, "max_line_length": 106, "alphanum_fraction": 0.599154334, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3414343228901938}} {"text": "-- This file is auto-generated. Do not edit directly.\n-- |\n-- Stability: Experimental\n--\n-- Generic interface to Blas using unsafe foreign calls. Refer to the GHC\n-- documentation for more information regarding appropriate use of safe and unsafe\n-- foreign calls.\n--\n-- The functions here are named in a similar fashion to the original Blas interface, with\n-- the type-dependent letter(s) removed. Some functions have been merged with\n-- others to allow the interface to work on both real and complex numbers. If you can't a\n-- particular function, try looking for its corresponding complex equivalent (e.g.\n-- @symv@ is a special case of 'hemv' applied to real numbers).\n--\n-- Note: although complex versions of @rot@ and @rotg@ exist in many implementations,\n-- they are not part of the official Blas standard and therefore not included here. If\n-- you /really/ need them, submit a ticket so we can try to come up with a solution.\n--\n-- The documentation here is still incomplete. Consult the\n-- for more\n-- information.\n--\n-- Notation:\n--\n-- * @⋅@ denotes dot product (without any conjugation).\n-- * @*@ denotes complex conjugation.\n-- * @⊤@ denotes transpose.\n-- * @†@ denotes conjugate transpose (Hermitian conjugate).\n--\n-- Conventions:\n--\n-- * All scalars are denoted with lowercase Greek letters\n-- * All vectors are denoted with lowercase Latin letters and are\n-- assumed to be column vectors (unless transposed).\n-- * All matrices are denoted with uppercase Latin letters.\n--\n-- /Since: 0.1.1/\nmodule Blas.Specialized.ComplexDouble.Unsafe (\n -- * Level 1: vector-vector operations\n -- ** Basic operations\n swap\n , scal\n , copy\n , axpy\n , dotu\n , dotc\n -- ** Norm operations\n , nrm2\n , asum\n , iamax\n -- * Level 2: matrix-vector operations\n -- ** Multiplication\n , gemv\n , gbmv\n , hemv\n , hbmv\n , hpmv\n -- ** Triangular operations\n , trmv\n , tbmv\n , tpmv\n , trsv\n , tbsv\n , tpsv\n -- ** Rank updates\n , geru\n , gerc\n , her\n , hpr\n , her2\n , hpr2\n -- * Level 3: matrix-matrix operations\n -- ** Multiplication\n , gemm\n , symm\n , hemm\n -- ** Rank updates\n , syrk\n , herk\n , syr2k\n , her2k\n -- ** Triangular operations\n , trmm\n , trsm\n ) where\nimport Prelude (Double, Int, IO)\nimport Foreign (Ptr)\nimport Data.Complex (Complex((:+)))\nimport FFI (getReturnValue)\nimport Blas.Primitive.Types (Order, Transpose, Uplo, Diag, Side)\nimport qualified Blas.Primitive.Unsafe as C\n\n-- | Swap two vectors:\n--\n-- > (x, y) ← (y, x)\nswap :: Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\nswap = C.zswap\n\n\n-- | Multiply a vector by a scalar.\n--\n-- > x ← α x\nscal :: Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\nscal n (alpha :+ 0) = C.zdscal n alpha\nscal n alpha = C.zscal n alpha\n\n\n-- | Copy a vector into another vector:\n--\n-- > y ← x\ncopy :: Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ncopy = C.zcopy\n\n\n-- | Add a scalar-vector product to a vector.\n--\n-- > y ← α x + y\naxpy :: Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\naxpy = C.zaxpy\n\n\n-- | Calculate the bilinear dot product of two vectors:\n--\n-- > x ⋅ y ≡ ∑[i] x[i] y[i]\ndotu :: Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO (Complex Double)\ndotu a b c d e = getReturnValue (C.zdotu_sub a b c d e)\n\n\n-- | Calculate the sesquilinear dot product of two vectors.\n--\n-- > x* ⋅ y ≡ ∑[i] x[i]* y[i]\ndotc :: Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO (Complex Double)\ndotc a b c d e = getReturnValue (C.zdotc_sub a b c d e)\n\n\n-- | Calculate the Euclidean (L²) norm of a vector:\n--\n-- > ‖x‖₂ ≡ √(∑[i] x[i]²)\nnrm2 :: Int\n -> Ptr (Complex Double)\n -> Int\n -> IO Double\nnrm2 = C.dznrm2\n\n\n-- | Calculate the Manhattan (L¹) norm, equal to the sum of the magnitudes of the elements:\n--\n-- > ‖x‖₁ = ∑[i] |x[i]|\nasum :: Int\n -> Ptr (Complex Double)\n -> Int\n -> IO Double\nasum = C.dzasum\n\n\n-- | Calculate the index of the element with the maximum magnitude (absolute value).\niamax :: Int\n -> Ptr (Complex Double)\n -> Int\n -> IO Int\niamax = C.izamax\n\n\n-- | Perform a general matrix-vector update.\n--\n-- > y ← α T(A) x + β y\ngemv :: Order\n -> Transpose\n -> Int\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ngemv = C.zgemv\n\n\n-- | Perform a general banded matrix-vector update.\n--\n-- > y ← α T(A) x + β y\ngbmv :: Order\n -> Transpose\n -> Int\n -> Int\n -> Int\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ngbmv = C.zgbmv\n\n\n-- | Perform a hermitian matrix-vector update.\n--\n-- > y ← α A x + β y\nhemv :: Order\n -> Uplo\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\nhemv = C.zhemv\n\n\n-- | Perform a hermitian banded matrix-vector update.\n--\n-- > y ← α A x + β y\nhbmv :: Order\n -> Uplo\n -> Int\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\nhbmv = C.zhbmv\n\n\n-- | Perform a hermitian packed matrix-vector update.\n--\n-- > y ← α A x + β y\nhpmv :: Order\n -> Uplo\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Ptr (Complex Double)\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\nhpmv = C.zhpmv\n\n\n-- | Multiply a triangular matrix by a vector.\n--\n-- > x ← T(A) x\ntrmv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ntrmv = C.ztrmv\n\n\n-- | Multiply a triangular banded matrix by a vector.\n--\n-- > x ← T(A) x\ntbmv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ntbmv = C.ztbmv\n\n\n-- | Multiply a triangular packed matrix by a vector.\n--\n-- > x ← T(A) x\ntpmv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Ptr (Complex Double)\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ntpmv = C.ztpmv\n\n\n-- | Multiply an inverse triangular matrix by a vector.\n--\n-- > x ← T(A⁻¹) x\ntrsv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ntrsv = C.ztrsv\n\n\n-- | Multiply an inverse triangular banded matrix by a vector.\n--\n-- > x ← T(A⁻¹) x\ntbsv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ntbsv = C.ztbsv\n\n\n-- | Multiply an inverse triangular packed matrix by a vector.\n--\n-- > x ← T(A⁻¹) x\ntpsv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Ptr (Complex Double)\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ntpsv = C.ztpsv\n\n\n-- | Perform an unconjugated rank-1 update of a general matrix.\n--\n-- > A ← α x y⊤ + A\ngeru :: Order\n -> Int\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ngeru = C.zgeru\n\n\n-- | Perform a conjugated rank-1 update of a general matrix.\n--\n-- > A ← α x y† + A\ngerc :: Order\n -> Int\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ngerc = C.zgerc\n\n\n-- | Perform a rank-1 update of a Hermitian matrix.\n--\n-- > A ← α x y† + A\nher :: Order\n -> Uplo\n -> Int\n -> Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\nher = C.zher\n\n\n-- | Perform a rank-1 update of a Hermitian packed matrix.\n--\n-- > A ← α x y† + A\nhpr :: Order\n -> Uplo\n -> Int\n -> Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> IO ()\nhpr = C.zhpr\n\n\n-- | Perform a rank-2 update of a Hermitian matrix.\n--\n-- > A ← α x y† + y (α x)† + A\nher2 :: Order\n -> Uplo\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\nher2 = C.zher2\n\n\n-- | Perform a rank-2 update of a Hermitian packed matrix.\n--\n-- > A ← α x y† + y (α x)† + A\nhpr2 :: Order\n -> Uplo\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> IO ()\nhpr2 = C.zhpr2\n\n\n-- | Perform a general matrix-matrix update.\n--\n-- > C ← α T(A) U(B) + β C\ngemm :: Order -- ^ Layout of all the matrices.\n -> Transpose -- ^ The operation @T@ to be applied to @A@.\n -> Transpose -- ^ The operation @U@ to be applied to @B@.\n -> Int -- ^ Number of rows of @T(A)@ and @C@.\n -> Int -- ^ Number of columns of @U(B)@ and @C@.\n -> Int -- ^ Number of columns of @T(A)@ and number of rows of @U(B)@.\n -> Complex Double -- ^ Scaling factor @α@ of the product.\n -> Ptr (Complex Double) -- ^ Pointer to a matrix @A@.\n -> Int -- ^ Stride of the major dimension of @A@.\n -> Ptr (Complex Double) -- ^ Pointer to a matrix @B@.\n -> Int -- ^ Stride of the major dimension of @B@.\n -> Complex Double -- ^ Scaling factor @β@ of the original @C@.\n -> Ptr (Complex Double) -- ^ Pointer to a mutable matrix @C@.\n -> Int -- ^ Stride of the major dimension of @C@.\n -> IO ()\ngemm = C.zgemm\n\n\n-- | Perform a symmetric matrix-matrix update.\n--\n-- > C ← α A B + β C or C ← α B A + β C\n--\n-- where @A@ is symmetric. The matrix @A@ must be in an unpacked format, although the\n-- routine will only access half of it as specified by the @'Uplo'@ argument.\nsymm :: Order -- ^ Layout of all the matrices.\n -> Side -- ^ Side that @A@ appears in the product.\n -> Uplo -- ^ The part of @A@ that is used.\n -> Int -- ^ Number of rows of @C@.\n -> Int -- ^ Number of columns of @C@.\n -> Complex Double -- ^ Scaling factor @α@ of the product.\n -> Ptr (Complex Double) -- ^ Pointer to a symmetric matrix @A@.\n -> Int -- ^ Stride of the major dimension of @A@.\n -> Ptr (Complex Double) -- ^ Pointer to a matrix @B@.\n -> Int -- ^ Stride of the major dimension of @B@.\n -> Complex Double -- ^ Scaling factor @α@ of the original @C@.\n -> Ptr (Complex Double) -- ^ Pointer to a mutable matrix @C@.\n -> Int -- ^ Stride of the major dimension of @C@.\n -> IO ()\nsymm = C.zsymm\n\n\n-- | Perform a Hermitian matrix-matrix update.\n--\n-- > C ← α A B + β C or C ← α B A + β C\n--\n-- where @A@ is Hermitian. The matrix @A@ must be in an unpacked format, although the\n-- routine will only access half of it as specified by the @'Uplo'@ argument.\nhemm :: Order -- ^ Layout of all the matrices.\n -> Side -- ^ Side that @A@ appears in the product.\n -> Uplo -- ^ The part of @A@ that is used.\n -> Int -- ^ Number of rows of @C@.\n -> Int -- ^ Number of columns of @C@.\n -> Complex Double -- ^ Scaling factor @α@ of the product.\n -> Ptr (Complex Double) -- ^ Pointer to a Hermitian matrix @A@.\n -> Int -- ^ Stride of the major dimension of @A@.\n -> Ptr (Complex Double) -- ^ Pointer to a matrix @B@.\n -> Int -- ^ Stride of the major dimension of @B@.\n -> Complex Double -- ^ Scaling factor @α@ of the original @C@.\n -> Ptr (Complex Double) -- ^ Pointer to a mutable matrix @C@.\n -> Int -- ^ Stride of the major dimension of @C@.\n -> IO ()\nhemm = C.zhemm\n\n\n-- | Perform a symmetric rank-k update.\n--\n-- > C ← α A A⊤ + β C or C ← α A⊤ A + β C\nsyrk :: Order\n -> Uplo\n -> Transpose\n -> Int\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\nsyrk = C.zsyrk\n\n\n-- | Perform a Hermitian rank-k update.\n--\n-- > C ← α A A† + β C or C ← α A† A + β C\nherk :: Order\n -> Uplo\n -> Transpose\n -> Int\n -> Int\n -> Double\n -> Ptr (Complex Double)\n -> Int\n -> Double\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\nherk = C.zherk\n\n\n-- | Perform a symmetric rank-2k update.\n--\n-- > C ← α A B⊤ + α* B A⊤ + β C or C ← α A⊤ B + α* B⊤ A + β C\nsyr2k :: Order\n -> Uplo\n -> Transpose\n -> Int\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\nsyr2k = C.zsyr2k\n\n\n-- | Perform a Hermitian rank-2k update.\n--\n-- > C ← α A B† + α* B A† + β C or C ← α A† B + α* B† A + β C\nher2k :: Order\n -> Uplo\n -> Transpose\n -> Int\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> Double\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\nher2k = C.zher2k\n\n\n-- | Perform a triangular matrix-matrix multiplication.\n--\n-- > B ← α T(A) B or B ← α B T(A)\n--\n-- where @A@ is triangular.\ntrmm :: Order\n -> Side\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ntrmm = C.ztrmm\n\n\n-- | Perform an inverse triangular matrix-matrix multiplication.\n--\n-- > B ← α T(A⁻¹) B or B ← α B T(A⁻¹)\n--\n-- where @A@ is triangular.\ntrsm :: Order\n -> Side\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Int\n -> Complex Double\n -> Ptr (Complex Double)\n -> Int\n -> Ptr (Complex Double)\n -> Int\n -> IO ()\ntrsm = C.ztrsm\n", "meta": {"hexsha": "b79a7703c62a32035c3341a9387148bcdf6843cf", "size": 14483, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Blas/Specialized/ComplexDouble/Unsafe.hs", "max_stars_repo_name": "Rufflewind/blas-hs", "max_stars_repo_head_hexsha": "59fdc1c48b19024f9bb6283b4ddc90fe45383937", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-01-20T04:34:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-09T12:09:06.000Z", "max_issues_repo_path": "src/Blas/Specialized/ComplexDouble/Unsafe.hs", "max_issues_repo_name": "Rufflewind/blas-hs", "max_issues_repo_head_hexsha": "59fdc1c48b19024f9bb6283b4ddc90fe45383937", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-04-25T05:53:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-28T22:27:04.000Z", "max_forks_repo_path": "src/Blas/Specialized/ComplexDouble/Unsafe.hs", "max_forks_repo_name": "Rufflewind/blas-hs", "max_forks_repo_head_hexsha": "59fdc1c48b19024f9bb6283b4ddc90fe45383937", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8446455505, "max_line_length": 92, "alphanum_fraction": 0.5358696403, "num_tokens": 4471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34050163185622123}} {"text": "{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule BlueRipple.Model.Preference where\n\nimport qualified Control.Foldl as FL\nimport qualified Control.Lens as L\nimport qualified Control.Monad.Except as X\nimport Control.Monad.IO.Class ( MonadIO(liftIO) )\nimport qualified Colonnade as C\nimport qualified Text.Blaze.Colonnade as BC\nimport qualified Text.Blaze.Html as BH\nimport qualified Text.Blaze.Html5.Attributes as BHA\nimport qualified Data.List as L\nimport qualified Data.Map as M\nimport qualified Data.Array as A\nimport qualified Data.Vector as VB\nimport qualified Data.Vector.Storable as VS\n\nimport qualified Text.Pandoc.Error as PA\n\nimport qualified Data.Profunctor as PF\nimport qualified Data.Text as T\nimport qualified Data.Time.Calendar as Time\nimport qualified Data.Time.Clock as Time\nimport qualified Data.Time.Format as Time\nimport qualified Data.Vinyl as V\nimport qualified Text.Printf as PF\nimport qualified Frames as F\nimport qualified Frames.Melt as F\nimport qualified Frames.CSV as F\nimport qualified Frames.InCore as F\n hiding ( inCoreAoS )\n\nimport qualified Pipes as P\nimport qualified Pipes.Prelude as P\nimport qualified Statistics.Types as S\nimport qualified Statistics.Distribution as S\nimport qualified Statistics.Distribution.StudentT as S\n\nimport qualified Numeric.LinearAlgebra as LA\n\nimport qualified Graphics.Vega.VegaLite as GV\nimport Graphics.Vega.VegaLite.Configuration as FV\nimport qualified Graphics.Vega.VegaLite.Compat as FV\n\nimport qualified Frames.Visualization.VegaLite.Data\n as FV\nimport qualified Frames.Visualization.VegaLite.StackedArea\n as FV\nimport qualified Frames.Visualization.VegaLite.LineVsTime\n as FV\nimport qualified Frames.Visualization.VegaLite.ParameterPlots\n as FV\n\nimport qualified Frames.Visualization.VegaLite.Correlation\n as FV\n\nimport qualified Frames.Transform as FT\nimport qualified Frames.Folds as FF\nimport qualified Frames.MapReduce as MR\nimport qualified Frames.Enumerations as FE\n\nimport qualified Knit.Report as K\nimport qualified Knit.Report.Input.MarkDown.PandocMarkDown as K\nimport Polysemy.Error (Error)\nimport qualified Text.Pandoc.Options as PA\n\nimport Data.String.Here ( here, i )\nimport qualified Relude.Extra as Relude\nimport BlueRipple.Configuration\nimport BlueRipple.Utilities.KnitUtils\nimport BlueRipple.Utilities.TableUtils\nimport BlueRipple.Data.DataFrames\nimport BlueRipple.Data.PrefModel\nimport BlueRipple.Data.PrefModel.SimpleAgeSexRace\nimport BlueRipple.Data.PrefModel.SimpleAgeSexEducation\nimport qualified BlueRipple.Model.PreferenceBayes as PB\nimport qualified BlueRipple.Model.TurnoutAdjustment as TA\n\n\nmodeledResults :: ( MonadIO (K.Sem r)\n , K.KnitEffects r\n , Show tr\n , Show b\n , Enum b\n , Bounded b\n , A.Ix b\n , FL.Vector (F.VectorFor b) b)\n => DemographicStructure dr tr HouseElections b\n -> (F.Record LocationKey -> Bool)\n -> F.Frame dr\n -> F.Frame tr\n -> F.Frame HouseElections\n -> M.Map Int Int\n -> K.Sem r (M.Map Int (PreferenceResults b FV.ParameterEstimate))\nmodeledResults ds locFilter dFrame tFrame eFrame years = flip traverse years $ \\y -> do\n K.logLE K.Info $ \"inferring \" <> show (dsCategories ds) <> \" for \" <> show y\n preferenceModel ds locFilter y dFrame eFrame tFrame\n\n-- PreferenceResults to list of group names and predicted D votes\n-- But we want them as a fraction of D/D+R\ndata VoteShare = ShareOfAll | ShareOfD\n\nmodeledDVotes :: forall b. (A.Ix b, Bounded b, Enum b, Show b)\n => VoteShare -> PreferenceResults b Double -> [(T.Text, Double)]\nmodeledDVotes vs pr =\n let\n summed = FL.fold\n (votesAndPopByDistrictF @b)\n (F.rcast <$> votesAndPopByDistrict pr)\n popArray =\n F.rgetField @(PopArray b) summed\n turnoutArray =\n F.rgetField @(TurnoutArray b) summed\n predVoters = zipWith (*) (A.elems turnoutArray) $ fmap realToFrac (A.elems popArray)\n allDVotes = F.rgetField @DVotes summed\n allRVotes = F.rgetField @RVotes summed\n dVotes b =\n realToFrac (popArray A.! b)\n * (turnoutArray A.! b)\n * (modeled pr A.! b)\n allPredictedD = FL.fold FL.sum $ fmap dVotes Relude.universe --[minBound..maxBound]\n scale = case vs of\n ShareOfAll -> (realToFrac allDVotes/realToFrac (allDVotes + allRVotes))/allPredictedD\n ShareOfD -> 1/allPredictedD\n in\n fmap (\\b -> (show b, scale * dVotes b))\n [(minBound :: b) .. maxBound]\n\n\ndata DeltaTableRow =\n DeltaTableRow\n { dtrGroup :: T.Text\n , dtrPop :: Int\n , dtrFromPop :: Int\n , dtrFromTurnout :: Int\n , dtrFromOpinion :: Int\n , dtrTotal :: Int\n , dtrPct :: Double\n } deriving (Show)\n\ndeltaTable\n :: forall dr tr e b r\n . (A.Ix b\n , Bounded b\n , Enum b\n , Show b\n , MonadIO (K.Sem r)\n , K.KnitEffects r\n )\n => DemographicStructure dr tr e b\n -> (F.Record LocationKey -> Bool)\n -> F.Frame e\n -> Int -- ^ year A\n -> Int -- ^ year B\n -> PreferenceResults b FV.ParameterEstimate\n -> PreferenceResults b FV.ParameterEstimate\n -> K.Sem r ([DeltaTableRow], (Int, Int), (Int, Int))\ndeltaTable ds locFilter electionResultsFrame yA yB trA trB = do\n let\n groupNames = show <$> dsCategories ds\n getPopAndTurnout\n :: Int -> PreferenceResults b FV.ParameterEstimate -> K.Sem r (A.Array b Int, A.Array b Double)\n getPopAndTurnout y tr = do\n resultsFrame <- knitX $ dsPreprocessElectionData ds y electionResultsFrame\n let\n totalDRVotes =\n let filteredResultsF = F.filterFrame (locFilter . F.rcast) resultsFrame\n in FL.fold (FL.premap (\\r -> F.rgetField @DVotes r + F.rgetField @RVotes r) FL.sum) filteredResultsF\n totalRec = FL.fold\n votesAndPopByDistrictF\n ( fmap\n (F.rcast\n @'[PopArray b, TurnoutArray b, DVotes, RVotes]\n )\n $ F.filterFrame (locFilter . F.rcast)\n $ F.toFrame\n $ votesAndPopByDistrict tr\n )\n totalCounts = F.rgetField @(PopArray b) totalRec\n unAdjTurnout = nationalTurnout tr\n tDelta <- liftIO $ TA.findDeltaA totalDRVotes totalCounts unAdjTurnout\n let adjTurnout = TA.adjTurnoutP tDelta unAdjTurnout\n return (totalCounts, adjTurnout)\n\n (popA, turnoutA) <- getPopAndTurnout yA trA\n (popB, turnoutB) <- getPopAndTurnout yB trB\n{- K.logLE K.Info $ (T.pack $ show yA) <> \"->\" <> (T.pack $ show yB)\n K.logLE K.Info $ T.pack $ show turnoutA\n K.logLE K.Info $ T.pack $ show turnoutB -}\n let\n pop = FL.fold FL.sum popA\n probsArray = fmap FV.value . modeled\n probA = probsArray trA\n probB = probsArray trB\n modeledVotes popArray turnoutArray probArray =\n let dVotes b =\n round\n $ realToFrac (popArray A.! b)\n * (turnoutArray A.! b)\n * (probArray A.! b)\n rVotes b =\n round\n $ realToFrac (popArray A.! b)\n * (turnoutArray A.! b)\n * (1.0 - probArray A.! b)\n in FL.fold\n ((,) <$> FL.premap dVotes FL.sum <*> FL.premap rVotes FL.sum) Relude.universe\n makeDTR b =\n let pop0 = realToFrac $ popA A.! b\n dPop = realToFrac $ (popB A.! b) - (popA A.! b)\n turnout0 = realToFrac $ turnoutA A.! b\n dTurnout = realToFrac $ (turnoutB A.! b) - (turnoutA A.! b)\n prob0 = realToFrac (probA A.! b)\n dProb = realToFrac $ (probB A.! b) - (probA A.! b)\n dtrCombo = dPop * dTurnout * (2 * dProb) / 4 -- the rest is accounted for in other terms, we spread this among them\n dtrN =\n round\n $ dPop\n * (turnout0 + dTurnout / 2)\n * (2 * (prob0 + dProb / 2) - 1)\n + (dtrCombo / 3)\n dtrT =\n round\n $ (pop0 + dPop / 2)\n * dTurnout\n * (2 * (prob0 + dProb / 2) - 1)\n + (dtrCombo / 3)\n dtrO =\n round\n $ (pop0 + dPop / 2)\n * (turnout0 + dTurnout / 2)\n * (2 * dProb)\n + (dtrCombo / 3)\n dtrTotal = dtrN + dtrT + dtrO\n in DeltaTableRow (show b)\n (popB A.! b)\n dtrN\n dtrT\n dtrO\n dtrTotal\n (realToFrac dtrTotal / realToFrac pop)\n groupRows = fmap makeDTR [minBound ..]\n addRow (DeltaTableRow g p fp ft fo t _) (DeltaTableRow _ p' fp' ft' fo' t' _)\n = DeltaTableRow g\n (p + p')\n (fp + fp')\n (ft + ft')\n (fo + fo')\n (t + t')\n (realToFrac (t + t') / realToFrac (p + p'))\n totalRow = FL.fold\n (FL.Fold addRow (DeltaTableRow \"Total\" 0 0 0 0 0 0) id)\n groupRows\n dVotesA = modeledVotes popA turnoutA probA\n dVotesB = modeledVotes popB turnoutB probB\n return (groupRows ++ [totalRow], dVotesA, dVotesB)\n\ndeltaTableColonnade :: C.Colonnade C.Headed DeltaTableRow T.Text\ndeltaTableColonnade =\n C.headed \"Group\" dtrGroup\n <> C.headed \"Population (k)\" (show . (`div` 1000) . dtrPop)\n <> C.headed \"+/- From Population (k)\"\n (show . (`div` 1000) . dtrFromPop)\n <> C.headed \"+/- From Turnout (k)\"\n (show . (`div` 1000) . dtrFromTurnout)\n <> C.headed \"+/- From Opinion (k)\"\n (show . (`div` 1000) . dtrFromOpinion)\n <> C.headed \"+/- Total (k)\" (show . (`div` 1000) . dtrTotal)\n <> C.headed \"+/- %Vote\" (toText @String . PF.printf \"%2.2f\" . (* 100) . dtrPct)\n\ndeltaTableColonnadeBlaze :: CellStyle DeltaTableRow T.Text -> C.Colonnade C.Headed DeltaTableRow BC.Cell\ndeltaTableColonnadeBlaze cas =\n C.headed \"Group\" (toCell cas \"Group\" \"\" (textToStyledHtml . dtrGroup))\n <> C.headed \"Population (k)\" (toCell cas \"Population\" \"Population\" (textToStyledHtml . show . (`div` 1000) . dtrPop))\n <> C.headed \"+/- From Population (k)\"\n (toCell cas \"FromPop\" \"+/- From Population\" (numberToStyledHtml \"%d\" . (`div` 1000) . dtrFromPop))\n <> C.headed \"+/- From Turnout (k)\"\n (toCell cas \"FromTurnout\" \"+/- From Turnout\" (numberToStyledHtml \"%d\" . (`div` 1000) . dtrFromTurnout))\n <> C.headed \"+/- From Opinion (k)\"\n (toCell cas \"FromOpinion\" \"+/- From Opinion\" (numberToStyledHtml \"%d\" . (`div` 1000) . dtrFromOpinion))\n-- (\\tr -> (numberCell \"%.0d\" (opinionHighlight (dtrGroup tr)) . (`div` 1000) $ dtrFromOpinion tr))\n <> C.headed \"+/- Total (k)\" (toCell cas \"Total\" \"Total\" (numberToStyledHtml \"%d\" . (`div` 1000) . dtrTotal))\n <> C.headed \"+/- %Vote\" (toCell cas \"PctVote\" \"% Vote\" (numberToStyledHtml \"%2.2f\" . (* 100) . dtrPct))\n\ntype X = \"X\" F.:-> Double\ntype ScaledDVotes = \"ScaledDVotes\" F.:-> Int\ntype ScaledRVotes = \"ScaledRVotes\" F.:-> Int\ntype PopArray b = \"PopArray\" F.:-> A.Array b Int\ntype TurnoutArray b = \"TurnoutArray\" F.:-> A.Array b Double\n\nvotesAndPopByDistrictF\n :: forall b\n . (A.Ix b, Bounded b, Enum b)\n => FL.Fold\n (F.Record '[PopArray b, TurnoutArray b, DVotes, RVotes])\n (F.Record '[PopArray b, TurnoutArray b, DVotes, RVotes])\nvotesAndPopByDistrictF =\n let voters r = A.listArray (minBound, maxBound)\n $ zipWith (*) (A.elems $ F.rgetField @(TurnoutArray b) r) (fmap realToFrac $ A.elems $ F.rgetField @(PopArray b) r)\n g r = A.listArray (minBound, maxBound)\n $ zipWith (/) (A.elems $ F.rgetField @(TurnoutArray b) r) (fmap realToFrac $ A.elems $ F.rgetField @(PopArray b) r)\n recomputeTurnout r = F.rputField @(TurnoutArray b) (g r) r\n in PF.dimap (F.rcast @'[PopArray b, TurnoutArray b, DVotes, RVotes]) recomputeTurnout\n $ FF.sequenceRecFold\n $ FF.FoldRecord (PF.dimap (F.rgetField @(PopArray b)) V.Field FE.sumTotalNumArray)\n V.:& FF.FoldRecord (PF.dimap voters V.Field FE.sumTotalNumArray)\n V.:& FF.FoldRecord (PF.dimap (F.rgetField @DVotes) V.Field FL.sum)\n V.:& FF.FoldRecord (PF.dimap (F.rgetField @RVotes) V.Field FL.sum)\n V.:& V.RNil\n\n\ndata Aggregation c b where\n Aggregation :: (Enum b, Bounded b, Eq b, Ord b, A.Ix b,\n Enum c, Bounded c, Eq c, Ord c, A.Ix c) => (c -> [b]) -> Aggregation c b\n\n\naggregateFold :: forall c b a x. Aggregation c b -> FL.Fold a x -> A.Array b a -> A.Array c x\naggregateFold (Aggregation children) fld arr =\n let cs = Relude.universe\n expanded :: [[a]]\n expanded = fmap (fmap (arr A.!) . children) cs\n folded = fmap (FL.fold fld) expanded\n in A.listArray (minBound,maxBound) folded\n\naggregateFold2 :: Aggregation c b -> FL.Fold (a,w) x -> A.Array b a -> A.Array b w -> A.Array c x\naggregateFold2 (Aggregation children) fld arrA arrW =\n let cs = Relude.universe\n as = fmap (fmap (arrA A.!) . children) cs\n ws = fmap (fmap (arrW A.!) . children) cs\n folded = FL.fold fld . uncurry zip <$> zip as ws\n in A.listArray (minBound, maxBound) folded\n\nweightedFold :: (Num a, Fractional a) => FL.Fold (a,a) a\nweightedFold =\n let sumWeightsF = FL.premap snd FL.sum\n weightedSumF = FL.premap (uncurry (*)) FL.sum\n in fmap (uncurry (/)) $ (,) <$> weightedSumF <*> sumWeightsF\n\npopWeightedAggregate :: (Num d, Fractional d) => Aggregation c b -> A.Array b Int -> A.Array b d -> A.Array c d\npopWeightedAggregate agg popArray datArray = aggregateFold2 agg weightedFold datArray (fmap realToFrac popArray)\n\naggregateRecord\n :: forall b c. Aggregation c b\n -> F.Record [StateAbbreviation\n , CongressionalDistrict\n , PopArray b -- population by group\n , TurnoutArray b -- adjusted turnout by group\n , DVotes\n , RVotes\n ]\n -> F.Record [StateAbbreviation\n , CongressionalDistrict\n , PopArray c -- population by group\n , TurnoutArray c -- adjusted turnout by group\n , DVotes\n , RVotes\n ]\naggregateRecord agg r =\n let\n f :: F.Record [PopArray b, TurnoutArray b] -> F.Record [PopArray c, TurnoutArray c]\n f x =\n let popB = F.rgetField @(PopArray b) x\n turnoutB = F.rgetField @(TurnoutArray b) x\n in aggregateFold agg FL.sum popB F.&: popWeightedAggregate agg popB turnoutB F.&: V.RNil\n in F.rcast $ FT.transform f r\n\ncByB :: Aggregation c b -> LA.Matrix Double\ncByB (Aggregation children) =\n let allBs = Relude.universe\n toZeroOne y = if y then 1 else 0\n getCol c = LA.fromList $ fmap (toZeroOne . (`elem` children c)) allBs\n in LA.fromColumns $ fmap getCol Relude.universe\n\naggregatePreferenceResults :: Fractional a => Aggregation c b -> PreferenceResults b a -> PreferenceResults c a\naggregatePreferenceResults agg pr =\n let prVBPAD' = fmap (aggregateRecord agg) (votesAndPopByDistrict pr)\n prTurnout' = popWeightedAggregate agg (nationalVoters pr) (nationalTurnout pr)\n prVoters' = aggregateFold agg FL.sum (nationalVoters pr)\n prModeled' = popWeightedAggregate agg (nationalVoters pr) (modeled pr)\n mCB = cByB agg\n prCovar' = LA.tr mCB LA.<> covariances pr LA.<> mCB\n in PreferenceResults prVBPAD' prTurnout' prVoters' prModeled' prCovar'\n\n\ndata PreferenceResults b a = PreferenceResults\n {\n votesAndPopByDistrict :: [F.Record [ StateAbbreviation\n , CongressionalDistrict\n , PopArray b -- population by group\n , TurnoutArray b -- adjusted turnout by group\n , DVotes\n , RVotes\n ]]\n , nationalTurnout :: A.Array b Double\n , nationalVoters :: A.Array b Int\n , modeled :: A.Array b a\n , covariances :: LA.Matrix Double\n }\n\ninstance Functor (PreferenceResults b) where\n fmap f (PreferenceResults v nt nv m c) = PreferenceResults v nt nv (fmap f m) c\n\npreferenceModel\n :: forall dr tr b r\n . ( Show tr\n , Show b\n , Enum b\n , Bounded b\n , A.Ix b\n , FL.Vector (F.VectorFor b) b\n , K.KnitEffects r\n , MonadIO (K.Sem r)\n )\n => DemographicStructure dr tr HouseElections b\n -> (F.Record LocationKey -> Bool)\n -> Int\n -> F.Frame dr\n -> F.Frame HouseElections\n -> F.Frame tr\n -> K.Sem\n r\n (PreferenceResults b FV.ParameterEstimate)\npreferenceModel ds locFilter year identityDFrame houseElexFrame turnoutFrame =\n do\n -- reorganize data from loaded Frames\n resultsFlattenedFrameFull <- knitX\n $ dsPreprocessElectionData ds year houseElexFrame\n let resultsFlattenedFrame = F.filterFrame (locFilter . F.rcast) resultsFlattenedFrameFull\n filteredTurnoutFrame <- knitX\n $ dsPreprocessTurnoutData ds year turnoutFrame\n let year' = year --if (year == 2018) then 2017 else year -- we're using 2017 for now, until census updated ACS data\n longByDCategoryFrame <- knitX\n $ dsPreprocessDemographicData ds year' identityDFrame\n\n -- turn long-format data into Arrays by demographic category, beginning with national turnout\n turnoutByGroupArray <-\n K.knitMaybe \"Missing or extra group in turnout data?\" $ FL.foldM\n (FE.makeArrayMF (F.rgetField @(DemographicCategory b))\n (F.rgetField @VotedPctOfAll)\n (flip const)\n )\n filteredTurnoutFrame\n\n -- now the populations in each district\n let votersArrayMF = MR.mapReduceFoldM\n (MR.generalizeUnpack MR.noUnpack)\n (MR.generalizeAssign $ MR.splitOnKeys @LocationKey)\n (MR.foldAndLabelM\n (fmap (FT.recordSingleton @(PopArray b))\n (FE.recordsToArrayMF @(DemographicCategory b) @PopCount)\n )\n V.rappend\n )\n -- F.Frame (LocationKey V.++ (PopArray b))\n populationsFrame <-\n K.knitMaybe \"Error converting long demographic data to arrays!\"\n $ F.toFrame\n <$> FL.foldM votersArrayMF longByDCategoryFrame\n\n -- and the total populations in each group\n let addArray :: (A.Ix k, Num a) => A.Array k a -> A.Array k a -> A.Array k a\n addArray a1 a2 = A.accum (+) a1 (A.assocs a2)\n zeroArray :: (A.Ix k, Bounded k, Enum k, Num a) => A.Array k a\n zeroArray = A.listArray (minBound, maxBound) $ L.repeat 0\n popByGroupArray = FL.fold (FL.premap (F.rgetField @(PopArray b)) (FL.Fold addArray zeroArray id)) populationsFrame\n\n let\n resultsWithPopulationsFrame =\n catMaybes $ fmap F.recMaybe $ F.leftJoin @LocationKey resultsFlattenedFrame\n populationsFrame\n\n K.logLE K.Info \"Computing Ghitza-Gelman turnout adjustment for each district so turnouts produce correct number D+R votes.\"\n resultsWithPopulationsAndGGAdjFrame <- fmap F.toFrame $ flip traverse resultsWithPopulationsFrame $ \\r -> do\n let tVotesF x = F.rgetField @DVotes x + F.rgetField @RVotes x -- Should this be D + R or total?\n ggDelta <- ggTurnoutAdj r tVotesF turnoutByGroupArray\n K.logLE K.Diagnostic $\n \"Ghitza-Gelman turnout adj=\"\n <> show ggDelta\n <> \"; Adj Turnout=\" <> show (TA.adjTurnoutP ggDelta turnoutByGroupArray)\n return $ FT.mutate (const $ FT.recordSingleton @(TurnoutArray b) $ TA.adjTurnoutP ggDelta turnoutByGroupArray) r\n\n let onlyOpposed r =\n (F.rgetField @DVotes r > 0) && (F.rgetField @RVotes r > 0)\n opposedFrame = F.filterFrame onlyOpposed resultsWithPopulationsAndGGAdjFrame\n numCompetitiveRaces = FL.fold FL.length opposedFrame\n\n K.logLE K.Info\n $ \"After removing races where someone is running unopposed we have \"\n <> show numCompetitiveRaces\n <> \" contested races.\"\n\n totalVoteDiagnostics @b resultsWithPopulationsAndGGAdjFrame opposedFrame\n\n\n let\n scaleInt s n = round $ s * realToFrac n\n mcmcData =\n fmap\n (\\r ->\n ( F.rgetField @DVotes r\n , VB.fromList $ fmap round (adjVotersL (F.rgetField @(TurnoutArray b) r) (F.rgetField @(PopArray b) r))\n )\n )\n $ FL.fold FL.list opposedFrame\n numParams = length $ dsCategories ds\n (cgRes, _, _) <- liftIO $ PB.cgOptimizeAD mcmcData (VB.fromList $ (const 0.5) <$> dsCategories ds)\n let cgParamsA = A.listArray (minBound :: b, maxBound) $ VB.toList cgRes\n cgVarsA = A.listArray (minBound :: b, maxBound) $ VS.toList $ PB.variances mcmcData cgRes\n npe cl b =\n let\n x = cgParamsA A.! b\n sigma = sqrt $ cgVarsA A.! b\n dof = realToFrac $ numCompetitiveRaces - L.length (A.elems cgParamsA)\n interval = S.quantile (S.studentTUnstandardized dof 0 sigma) (1.0 - (S.significanceLevel cl/2))\n in FV.ParameterEstimate x (x - interval/2.0, x + interval/2.0)\n-- in FV.NamedParameterEstimate (T.pack $ show b) pEstimate\n parameterEstimatesA = A.listArray (minBound :: b, maxBound) $ fmap (npe S.cl95) Relude.universe\n\n K.logLE K.Info $ \"MLE results: \" <> show (A.elems parameterEstimatesA)\n-- For now this bit is diagnostic. But we should chart the correlations\n-- and, perhaps, the eigenvectors of the covariance??\n let cgCovar = PB.covar mcmcData cgRes -- TODO: make a chart out of this\n (cgEv, cgEvs) = PB.mleCovEigens mcmcData cgRes\n K.logLE K.Diagnostic $ \"sigma = \" <> show (fmap sqrt $ cgVarsA)\n K.logLE K.Diagnostic $ \"Covariances=\" <> toText (PB.disps 3 cgCovar)\n K.logLE K.Diagnostic $ \"Correlations=\" <> toText (PB.disps 3 $ PB.correlFromCov cgCovar)\n K.logLE K.Diagnostic $ \"Eigenvalues=\" <> show cgEv\n K.logLE K.Diagnostic $ \"Eigenvectors=\" <> toText (PB.disps 3 cgEvs)\n\n return $ PreferenceResults\n (F.rcast <$> FL.fold FL.list opposedFrame)\n turnoutByGroupArray\n popByGroupArray\n parameterEstimatesA\n cgCovar\n\nggTurnoutAdj :: forall b rs r. (A.Ix b\n , F.ElemOf rs (PopArray b)\n , MonadIO (K.Sem r)\n ) => F.Record rs -> (F.Record rs -> Int) -> A.Array b Double -> K.Sem r Double\nggTurnoutAdj r totalVotesF unadjTurnoutP = do\n let population = F.rgetField @(PopArray b) r\n totalVotes = totalVotesF r\n liftIO $ TA.findDeltaA totalVotes population unadjTurnoutP\n\nadjVotersL :: A.Array b Double -> A.Array b Int -> [Double]\nadjVotersL turnoutPA popA = zipWith (*) (A.elems turnoutPA) (realToFrac <$> A.elems popA)\n\ntotalVoteDiagnostics :: forall b rs f r\n . (A.Ix b\n , Foldable f\n , F.ElemOf rs (PopArray b)\n , F.ElemOf rs (TurnoutArray b)\n , F.ElemOf rs Totalvotes\n , F.ElemOf rs DVotes\n , F.ElemOf rs RVotes\n , K.KnitEffects r\n )\n => f (F.Record rs) -- ^ frame with all rows\n -> f (F.Record rs) -- ^ frame with only rows from competitive races\n -> K.Sem r ()\ntotalVoteDiagnostics allFrame opposedFrame = K.wrapPrefix \"VoteSummary\" $ do\n let allVoters r = FL.fold FL.sum\n $ zipWith (*) (A.elems $ F.rgetField @(TurnoutArray b) r) (fmap realToFrac $ A.elems $ F.rgetField @(PopArray b) r)\n allVotersF = FL.premap allVoters FL.sum\n allVotesF = FL.premap (F.rgetField @Totalvotes) FL.sum\n allDVotesF = FL.premap (F.rgetField @DVotes) FL.sum\n allRVotesF = FL.premap (F.rgetField @RVotes) FL.sum\n -- allDRVotesF = FL.premap (\\r -> F.rgetField @DVotes r + F.rgetField @RVotes r) FL.sum\n (totalVoters, totalVotes, totalDVotes, totalRVotes) = FL.fold\n ((,,,) <$> allVotersF <*> allVotesF <*> allDVotesF <*> allRVotesF)\n allFrame\n (totalVotersCD, totalVotesCD, totalDVotesCD, totalRVotesCD) = FL.fold\n ((,,,) <$> allVotersF <*> allVotesF <*> allDVotesF <*> allRVotesF)\n opposedFrame\n K.logLE K.Info $ \"voters=\" <> show totalVoters\n K.logLE K.Info $ \"house votes=\" <> show totalVotes\n K.logLE K.Info\n $ \"D/R/D+R house votes=\"\n <> show totalDVotes\n <> \"/\"\n <> show totalRVotes\n <> \"/\"\n <> show (totalDVotes + totalRVotes)\n K.logLE K.Info\n $ \"voters (competitive districts)=\"\n <> show totalVotersCD\n K.logLE K.Info\n $ \"house votes (competitive districts)=\"\n <> show totalVotesCD\n K.logLE K.Info\n $ \"D/R/D+R house votes (competitive districts)=\"\n <> show totalDVotesCD\n <> \"/\"\n <> show totalRVotesCD\n <> \"/\"\n <> show (totalDVotesCD + totalRVotesCD)\n\n\ntotalArrayZipWith :: (A.Ix b, Enum b, Bounded b)\n => (x -> y -> z)\n -> A.Array b x\n -> A.Array b y\n -> A.Array b z\ntotalArrayZipWith f xs ys = A.listArray (minBound, maxBound) $ zipWith f (A.elems xs) (A.elems ys)\n\nvlGroupingChart :: Foldable f\n => T.Text\n -> FV.ViewConfig\n -> f (F.Record ['(\"Group\", T.Text)\n ,'(\"VotingAgePop\", Int)\n ,'(\"Turnout\",Double)\n ,'(\"Voters\", Int)\n ,'(\"D Voter Preference\", Double)\n ])\n -> GV.VegaLite\nvlGroupingChart title vc rows =\n let dat = FV.recordsToVLData id FV.defaultParse rows\n xLabel = \"Inferred (%) Likelihood of Voting Democratic\"\n estimateXenc = GV.position GV.X [FV.pName @'(\"D Voter Preference\", Double)\n ,GV.PmType GV.Quantitative\n ,GV.PAxis [GV.AxTitle xLabel]\n ]\n estimateYenc = GV.position GV.Y [FV.pName @'(\"Group\",T.Text)\n ,GV.PmType GV.Ordinal\n ,GV.PAxis [GV.AxTitle \"Demographic Group\"]\n ]\n estimateSizeEnc = GV.size [FV.mName @'(\"Voters\",Int)\n , GV.MmType GV.Quantitative\n , GV.MScale [GV.SDomain $ GV.DNumbers [5e6,30e6]]\n , GV.MLegend [GV.LFormatAsNum]\n\n ]\n estimateColorEnc = GV.color [FV.mName @'(\"Turnout\", Double)\n , GV.MmType GV.Quantitative\n , GV.MScale [GV.SDomain $ GV.DNumbers [0.2,0.8]\n ,GV.SScheme \"blues\" [0.3,1.0]\n ]\n , GV.MLegend [GV.LGradientLength (vcHeight vc / 3)\n , GV.LFormatAsNum\n , GV.LFormat \"%\"\n ]\n ]\n estEnc = estimateXenc . estimateYenc . estimateSizeEnc . estimateColorEnc\n estSpec = GV.asSpec [(GV.encoding . estEnc) [], GV.mark GV.Point [GV.MFilled True]]\n in\n FV.configuredVegaLite vc [FV.title title, GV.layer [estSpec], dat]\n\nexitCompareChart :: Foldable f\n => T.Text\n -> FV.ViewConfig\n -> f (F.Record ['(\"Group\", T.Text)\n ,'(\"Model Dem Pref\", Double)\n ,'(\"ModelvsExit\",Double)\n ])\n -> GV.VegaLite\nexitCompareChart title vc rows =\n let dat = FV.recordsToVLData id FV.defaultParse rows\n xLabel = \"Modeled % Likelihood of Voting Democratic\"\n xEnc = GV.position GV.X [FV.pName @'(\"Model Dem Pref\", Double)\n ,GV.PmType GV.Quantitative\n ,GV.PAxis [GV.AxTitle xLabel\n , GV.AxFormatAsNum\n , GV.AxFormat \"%\"\n ]\n ]\n yEnc = GV.position GV.Y [FV.pName @'(\"ModelvsExit\", Double)\n ,GV.PmType GV.Quantitative\n ,GV.PScale [GV.SDomain $ GV.DNumbers [negate 0.15,0.15]]\n ,GV.PAxis [GV.AxTitle \"Model - Exit Poll\"\n , GV.AxFormatAsNum\n , GV.AxFormat \"%\"\n ]\n ]\n colorEnc = GV.color [FV.mName @'(\"Group\", T.Text)\n , GV.MmType GV.Nominal\n ]\n enc = xEnc . yEnc . colorEnc\n spec = GV.asSpec [(GV.encoding . enc) [], GV.mark GV.Point [GV.MFilled True, GV.MSize 100]]\n in\n FV.configuredVegaLite vc [FV.title title, GV.layer [spec], dat]\n\n\n\nvlGroupingChartExit :: Foldable f\n => T.Text\n -> FV.ViewConfig\n -> f (F.Record ['(\"Group\", T.Text)\n ,'(\"VotingAgePop\", Int)\n ,'(\"Voters\", Int)\n ,'(\"D Voter Preference\", Double)\n ,'(\"InfMinusExit\", Double)\n ])\n -> GV.VegaLite\nvlGroupingChartExit title vc rows =\n let dat = FV.recordsToVLData id FV.defaultParse rows\n xLabel = \"Inferred Likelihood of Voting Democratic\"\n estimateXenc = GV.position GV.X [FV.pName @'(\"D Voter Preference\", Double)\n ,GV.PmType GV.Quantitative\n ,GV.PAxis [GV.AxTitle xLabel]\n ]\n estimateYenc = GV.position GV.Y [FV.pName @'(\"Group\",T.Text)\n ,GV.PmType GV.Ordinal\n ]\n estimateSizeEnc = GV.size [FV.mName @'(\"VotingAgePop\",Int)\n , GV.MmType GV.Quantitative]\n estimateColorEnc = GV.color [FV.mName @'(\"InfMinusExit\", Double)\n , GV.MmType GV.Quantitative]\n estEnc = estimateXenc . estimateYenc . estimateSizeEnc . estimateColorEnc\n estSpec = GV.asSpec [(GV.encoding . estEnc) [], GV.mark GV.Point []]\n in\n FV.configuredVegaLite vc [FV.title title, GV.layer [estSpec], dat]\n", "meta": {"hexsha": "55312342af6883b3d2898ce29cb22e0718f8643c", "size": 31680, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "blueripple-glm/src/BlueRipple/Model/Preference.hs", "max_stars_repo_name": "blueripple/preference-model", "max_stars_repo_head_hexsha": "beae97c2d854830bc0e9027609e54166f93d976b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T11:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T11:32:48.000Z", "max_issues_repo_path": "blueripple-glm/src/BlueRipple/Model/Preference.hs", "max_issues_repo_name": "blueripple/preference-model", "max_issues_repo_head_hexsha": "beae97c2d854830bc0e9027609e54166f93d976b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blueripple-glm/src/BlueRipple/Model/Preference.hs", "max_forks_repo_name": "blueripple/preference-model", "max_forks_repo_head_hexsha": "beae97c2d854830bc0e9027609e54166f93d976b", "max_forks_repo_licenses": ["BSD-3-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.8174273859, "max_line_length": 135, "alphanum_fraction": 0.5647727273, "num_tokens": 8346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3394353658409171}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE RankNTypes #-}\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702\n{-# LANGUAGE Trustworthy #-}\n{-# LANGUAGE DeriveGeneric #-}\n#endif\n{-# LANGUAGE DeriveDataTypeable #-}\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 708\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n#endif\n-----------------------------------------------------------------------------\n-- |\n-- License : BSD-style (see the file LICENSE)\n-- Maintainer : Edward Kmett \n-- Stability : provisional\n-- Portability : portable\n--\n-- Operations on affine spaces.\n-----------------------------------------------------------------------------\nmodule Linear.Affine where\n\nimport Control.Applicative\nimport Control.Lens\nimport Data.Complex (Complex)\nimport Data.Data\nimport Data.Distributive\nimport Data.Foldable as Foldable\nimport Data.Functor.Bind\nimport Data.Functor.Rep as Rep\nimport Data.HashMap.Lazy (HashMap)\nimport Data.Hashable\nimport Data.IntMap (IntMap)\nimport Data.Ix\nimport Data.Map (Map)\nimport Data.Vector (Vector)\nimport Foreign.Storable\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702\nimport GHC.Generics (Generic)\n#endif\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706\nimport GHC.Generics (Generic1)\n#endif\nimport Linear.Epsilon\nimport Linear.Metric\nimport Linear.Plucker\nimport Linear.Quaternion\nimport Linear.V\nimport Linear.V0\nimport Linear.V1\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport Linear.Vector\n\n#ifdef HLINT\n{-# ANN module \"HLint: ignore Unused LANGUAGE pragma\" #-}\n#endif\n\n-- | An affine space is roughly a vector space in which we have\n-- forgotten or at least pretend to have forgotten the origin.\n--\n-- > a .+^ (b .-. a) = b@\n-- > (a .+^ u) .+^ v = a .+^ (u ^+^ v)@\n-- > (a .-. b) ^+^ v = (a .+^ v) .-. q@\nclass Additive (Diff p) => Affine p where\n type Diff p :: * -> *\n\n infixl 6 .-.\n -- | Get the difference between two points as a vector offset.\n (.-.) :: Num a => p a -> p a -> Diff p a\n\n infixl 6 .+^\n -- | Add a vector offset to a point.\n (.+^) :: Num a => p a -> Diff p a -> p a\n\n infixl 6 .-^\n -- | Subtract a vector offset from a point.\n (.-^) :: Num a => p a -> Diff p a -> p a\n p .-^ v = p .+^ negated v\n {-# INLINE (.-^) #-}\n\n-- | Compute the quadrance of the difference (the square of the distance)\nqdA :: (Affine p, Foldable (Diff p), Num a) => p a -> p a -> a\nqdA a b = Foldable.sum (fmap (join (*)) (a .-. b))\n{-# INLINE qdA #-}\n\n-- | Distance between two points in an affine space\ndistanceA :: (Floating a, Foldable (Diff p), Affine p) => p a -> p a -> a\ndistanceA a b = sqrt (qdA a b)\n{-# INLINE distanceA #-}\n\n#define ADDITIVEC(CTX,T) instance CTX => Affine T where type Diff T = T ; \\\n (.-.) = (^-^) ; {-# INLINE (.-.) #-} ; (.+^) = (^+^) ; {-# INLINE (.+^) #-} ; \\\n (.-^) = (^-^) ; {-# INLINE (.-^) #-}\n#define ADDITIVE(T) ADDITIVEC((), T)\n\nADDITIVE([])\nADDITIVE(Complex)\nADDITIVE(ZipList)\nADDITIVE(Maybe)\nADDITIVE(IntMap)\nADDITIVE(Identity)\nADDITIVE(Vector)\nADDITIVE(V0)\nADDITIVE(V1)\nADDITIVE(V2)\nADDITIVE(V3)\nADDITIVE(V4)\nADDITIVE(Plucker)\nADDITIVE(Quaternion)\nADDITIVE(((->) b))\nADDITIVEC(Ord k, (Map k))\nADDITIVEC((Eq k, Hashable k), (HashMap k))\nADDITIVEC(Dim n, (V n))\n\n-- | A handy wrapper to help distinguish points from vectors at the\n-- type level\nnewtype Point f a = P (f a)\n deriving ( Eq, Ord, Show, Read, Monad, Functor, Applicative, Foldable\n , Traversable, Apply, Additive, Metric\n , Fractional , Num, Ix, Storable, Epsilon\n , Hashable\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702\n , Generic\n#endif\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706\n , Generic1\n#endif\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 708\n , Typeable, Data\n#endif\n )\n\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 708\ninstance forall f. Typeable1 f => Typeable1 (Point f) where\n typeOf1 _ = mkTyConApp (mkTyCon3 \"linear\" \"Linear.Affine\" \"Point\") [] `mkAppTy`\n typeOf1 (undefined :: f a)\n\nderiving instance (Data (f a), Typeable1 f, Typeable a) => Data (Point f a)\n#endif\n\nlensP :: Lens' (Point g a) (g a)\nlensP afb (P a) = P <$> afb a\n{-# INLINE lensP #-}\n\n_Point :: Iso' (Point f a) (f a)\n_Point = iso (\\(P a) -> a) P\n{-# INLINE _Point #-}\n\ninstance (t ~ Point g b) => Rewrapped (Point f a) t\ninstance Wrapped (Point f a) where\n type Unwrapped (Point f a) = f a\n _Wrapped' = _Point\n {-# INLINE _Wrapped' #-}\n\ninstance Bind f => Bind (Point f) where\n join (P m) = P $ join $ fmap (\\(P m')->m') m\n\ninstance Distributive f => Distributive (Point f) where\n distribute = P . collect (\\(P p) -> p)\n\ninstance Representable f => Representable (Point f) where\n type Rep (Point f) = Rep f\n tabulate f = P (tabulate f)\n {-# INLINE tabulate #-}\n index (P xs) = Rep.index xs\n {-# INLINE index #-}\n\ntype instance Index (Point f a) = Index (f a)\ntype instance IxValue (Point f a) = IxValue (f a)\n\ninstance Ixed (f a) => Ixed (Point f a) where\n ix l = lensP . ix l\n {-# INLINE ix #-}\n\ninstance Traversable f => Each (Point f a) (Point f b) a b where\n each = traverse\n {-# INLINE each #-}\n\ninstance R1 f => R1 (Point f) where\n _x = lensP . _x\n {-# INLINE _x #-}\n\ninstance R2 f => R2 (Point f) where\n _y = lensP . _y\n {-# INLINE _y #-}\n _xy = lensP . _xy\n {-# INLINE _xy #-}\n\ninstance R3 f => R3 (Point f) where\n _z = lensP . _z\n {-# INLINE _z #-}\n _xyz = lensP . _xyz\n {-# INLINE _xyz #-}\n\ninstance R4 f => R4 (Point f) where\n _w = lensP . _w\n {-# INLINE _w #-}\n _xyzw = lensP . _xyzw\n {-# INLINE _xyzw #-}\n\ninstance Additive f => Affine (Point f) where\n type Diff (Point f) = f\n P x .-. P y = x ^-^ y\n {-# INLINE (.-.) #-}\n P x .+^ v = P (x ^+^ v)\n {-# INLINE (.+^) #-}\n P x .-^ v = P (x ^-^ v)\n {-# INLINE (.-^) #-}\n\n-- | Vector spaces have origins.\norigin :: (Additive f, Num a) => Point f a\norigin = P zero\n\n-- | An isomorphism between points and vectors, given a reference\n-- point.\nrelative :: (Additive f, Num a) => Point f a -> Iso' (Point f a) (f a)\nrelative p0 = iso (.-. p0) (p0 .+^)\n{-# INLINE relative #-}\n\n", "meta": {"hexsha": "5a33cad8ba8a412a01cbba70db2312092bdd4d70", "size": 6417, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Linear/Affine.hs", "max_stars_repo_name": "abbradar/linear", "max_stars_repo_head_hexsha": "65f84b187dee38e9d8adba27d4c2cfbf9c816334", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Linear/Affine.hs", "max_issues_repo_name": "abbradar/linear", "max_issues_repo_head_hexsha": "65f84b187dee38e9d8adba27d4c2cfbf9c816334", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Linear/Affine.hs", "max_forks_repo_name": "abbradar/linear", "max_forks_repo_head_hexsha": "65f84b187dee38e9d8adba27d4c2cfbf9c816334", "max_forks_repo_licenses": ["BSD-3-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.0218340611, "max_line_length": 81, "alphanum_fraction": 0.6164874552, "num_tokens": 2032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3383108631420962}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n#if __GLASGOW_HASKELL__ >= 805\n{-# LANGUAGE ExplicitNamespaces #-}\n{-# LANGUAGE NoStarIsType #-}\n#endif\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule Eigen.Matrix\n ( \n -- * Types \n Matrix(..)\n , Vec(..)\n , MatrixXf\n , MatrixXd\n , MatrixXcf\n , MatrixXcd\n\n -- * Common API\n , Elem\n , C\n , natToInt\n , Row(..)\n , Col(..)\n\n -- * Encode/Decode a Matrix\n , encode\n , decode\n\n -- * Querying a Matrix\n , null\n , square\n , rows\n , cols\n , dims\n \n -- * Constructing a Matrix\n , empty\n , constant\n , zero\n , ones\n , identity\n , random\n , diagonal\n\n , (!)\n , coeff\n , generate\n , sum\n , prod\n , mean\n , trace\n , all\n , any\n , count\n , norm\n , squaredNorm\n , blueNorm\n , hypotNorm\n , determinant\n , add\n , sub\n , mul\n , map\n , imap\n , TriangularMode(..)\n , triangularView\n , filter\n , ifilter\n , length\n , foldl\n , foldl'\n , inverse\n , adjoint\n , transpose\n , conjugate\n , normalize\n , modify\n , block\n , unsafeFreeze\n , unsafeWith\n , fromList\n , toList\n ) where\n\nimport Control.Monad (when)\nimport Control.Monad.ST (ST)\nimport Prelude hiding\n (map, null, filter, length, foldl, any, all, sum)\nimport Control.Monad (forM_)\nimport Control.Monad.Primitive (PrimMonad(..))\nimport Data.Binary (Binary(..))\nimport qualified Data.Binary as Binary\nimport qualified Data.ByteString.Lazy as BSL\nimport Data.Complex (Complex)\nimport Data.Constraint.Nat\nimport Eigen.Internal\n ( Elem\n , Cast(..)\n , natToInt\n , Row(..)\n , Col(..)\n )\nimport qualified Eigen.Internal as Internal\nimport qualified Eigen.Matrix.Mutable as M\nimport qualified Data.List as List\nimport Data.Kind (Type)\nimport GHC.TypeLits (Nat, type (*), type (<=), KnownNat)\nimport Foreign.C.Types (CInt)\nimport Foreign.C.String (CString)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Ptr (Ptr)\nimport Foreign.Storable (peek)\n\nimport qualified Data.Vector.Storable as VS\nimport qualified Data.Vector.Storable.Mutable as VSM\n\n-- | Matrix to be used in pure computations.\n--\n-- * Uses column majour memory layout.\n--\n-- * Has a copy-free FFI using the library.\n--\nnewtype Matrix :: Nat -> Nat -> Type -> Type where\n Matrix :: Vec (n * m) a -> Matrix n m a\n\n-- | Used internally to track the size and corresponding C type of the matrix.\nnewtype Vec :: Nat -> Type -> Type where\n Vec :: VS.Vector (C a) -> Vec n a\n\ninstance forall n m a. (Elem a, Show a, KnownNat n, KnownNat m) => Show (Matrix n m a) where\n show m = List.concat\n [ \"Matrix \", show (rows m), \"x\", show (cols m)\n , \"\\n\", List.intercalate \"\\n\" $ List.map (List.intercalate \"\\t\" . List.map show) $ toList m, \"\\n\"\n ]\n\ninstance forall n m a. (KnownNat n, KnownNat m, Elem a) => Binary (Matrix n m a) where\n put (Matrix (Vec vals)) = do\n put $ Internal.magicCode (undefined :: C a)\n put $ natToInt @n\n put $ natToInt @m\n put vals\n\n get = do\n get >>= (`when` fail \"wrong matrix type\") . (/= Internal.magicCode (undefined :: C a))\n Matrix . Vec <$> get\n\n-- | Encode the sparse matrix as a lazy bytestring\nencode :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> BSL.ByteString\nencode = Binary.encode\n\n-- | Decode the sparse matrix from a lazy bytestring\ndecode :: (Elem a, KnownNat n, KnownNat m) => BSL.ByteString -> Matrix n m a\ndecode = Binary.decode\n\n-- | Alias for single precision matrix\ntype MatrixXf n m = Matrix n m Float\n-- | Alias for double precision matrix\ntype MatrixXd n m = Matrix n m Double\n-- | Alias for single precision matrix of complex numbers\ntype MatrixXcf n m = Matrix n m (Complex Float)\n-- | Alias for double precision matrix of complex numbers\ntype MatrixXcd n m = Matrix n m (Complex Double)\n\n-- | Construct an empty 0x0 matrix\nempty :: Elem a => Matrix 0 0 a\n{-# INLINE empty #-}\nempty = Matrix (Vec (VS.empty))\n\n-- | Is matrix empty?\nnull :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> Bool\n{-# INLINE null #-}\nnull m = cols m == 0 && rows m == 0\n\n-- | Is matrix square?\n--\nsquare :: forall n m a. (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> Bool\n{-# INLINE square #-}\nsquare _ = natToInt @n == natToInt @m\n\n-- | Matrix where all coeffs are filled with the given value\nconstant :: forall n m a. (Elem a, KnownNat n, KnownNat m) => a -> Matrix n m a\n{-# INLINE constant #-}\nconstant !val =\n let !cval = toC val\n in withDims $ \\rs cs -> VS.replicate (rs * cs) cval\n\n-- | Matrix where all coeffs are filled with 0\nzero :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a\n{-# INLINE zero #-}\nzero = constant 0\n\n-- | Matrix where all coeffs are filled with 1\nones :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a\n{-# INLINE ones #-}\nones = constant 1\n\n-- | The identity matrix (not necessarily square)\nidentity :: forall n m a. (Elem a, KnownNat n, KnownNat m) => Matrix n m a\nidentity =\n Internal.performIO $ do\n m :: M.IOMatrix n m a <- M.new\n Internal.call $ M.unsafeWith m Internal.identity\n unsafeFreeze m\n\n-- | The random matrix of a given size\nrandom :: forall n m a. (Elem a, KnownNat n, KnownNat m) => IO (Matrix n m a)\nrandom = do\n m :: M.IOMatrix n m a <- M.new\n Internal.call $ M.unsafeWith m Internal.random\n unsafeFreeze m\n\nwithDims :: forall n m a. (Elem a, KnownNat n, KnownNat m) => (Int -> Int -> VS.Vector (C a)) -> Matrix n m a\n{-# INLINE withDims #-}\nwithDims f =\n let !r = natToInt @n\n !c = natToInt @m\n in Matrix $ Vec $ f r c\n\n-- | The number of rows in the matrix\nrows :: forall n m a. KnownNat n => Matrix n m a -> Int\n{-# INLINE rows #-}\nrows _ = natToInt @n\n\n-- | The number of colums in the matrix\ncols :: forall n m a. KnownNat m => Matrix n m a -> Int\n{-# INLINE cols #-}\ncols _ = natToInt @m\n\n-- | Return Matrix size as a pair of (rows, cols)\ndims :: forall n m a. (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> (Int, Int)\n{-# INLINE dims #-}\ndims _ = (natToInt @n, natToInt @m)\n\n-- | Return the value at the given position.\n(!) :: forall n m a r c. (Elem a, KnownNat n, KnownNat r, KnownNat c, r <= n, c <= m) => Row r -> Col c -> Matrix n m a -> a\n{-# INLINE (!) #-}\n(!) = coeff\n\n-- | Return the value at the given position.\ncoeff :: forall n m a r c. (Elem a, KnownNat n, KnownNat r, KnownNat c, r <= n, c <= m) => Row r -> Col c -> Matrix n m a -> a\n{-# INLINE coeff #-}\ncoeff _ _ m@(Matrix (Vec vals)) =\n let !row = natToInt @r\n !col = natToInt @c\n in fromC $! VS.unsafeIndex vals $! col * rows m + row\n\nunsafeCoeff :: (Elem a, KnownNat n) => Int -> Int -> Matrix n m a -> a\n{-# INLINE unsafeCoeff #-}\nunsafeCoeff row col m@(Matrix (Vec vals)) = fromC $! VS.unsafeIndex vals $! col * rows m + row\n\n-- | Given a generation function `f :: Int -> Int -> a`, construct a Matrix of known size\n-- using points in the matrix as inputs.\ngenerate :: forall n m a. (Elem a, KnownNat n, KnownNat m) => (Int -> Int -> a) -> Matrix n m a\ngenerate f = withDims $ \\rs cs -> VS.create $ do\n vals :: VSM.MVector s (C a) <- VSM.new (rs * cs)\n forM_ [0 .. pred rs] $ \\r ->\n forM_ [0 .. pred cs] $ \\c ->\n VSM.write vals (c * rs + r) (toC $! f r c)\n pure vals\n\n-- | The sum of all coefficients in the matrix\nsum :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> a\nsum = _prop Internal.sum\n\n-- | The product of all coefficients in the matrix\nprod :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> a\nprod = _prop Internal.prod\n\n-- | The arithmetic mean of all coefficients in the matrix\nmean :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> a\nmean = _prop Internal.mean\n\n-- | The trace of a matrix is the sum of the diagonal coefficients.\n-- \n-- 'trace' m == 'sum' ('diagonal' m)\ntrace :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> a\ntrace = _prop Internal.trace\n\n-- | Given a predicate p, determine if all values in the Matrix satisfy p.\nall :: (Elem a, KnownNat n, KnownNat m) => (a -> Bool) -> Matrix n m a -> Bool\nall f (Matrix (Vec vals)) = VS.all (f . fromC) vals\n\n-- | Given a predicate p, determine if any values in the Matrix satisfy p.\nany :: (Elem a, KnownNat n, KnownNat m) => (a -> Bool) -> Matrix n m a -> Bool\nany f (Matrix (Vec vals)) = VS.any (f . fromC) vals\n\n-- | Given a predicate p, determine how many values in the Matrix satisfy p.\ncount :: (Elem a, KnownNat n, KnownNat m) => (a -> Bool) -> Matrix n m a -> Int\ncount f (Matrix (Vec vals)) = VS.foldl' (\\n x-> if f (fromC x) then (n + 1) else n) 0 vals\n\nnorm, squaredNorm, blueNorm, hypotNorm :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> a\n\n{-| For vectors, the l2 norm, and for matrices the Frobenius norm.\n In both cases, it consists in the square root of the sum of the square of all the matrix entries.\n For vectors, this is also equals to the square root of the dot product of this with itself.\n-}\nnorm = _prop Internal.norm\n\n-- | For vectors, the squared l2 norm, and for matrices the Frobenius norm. In both cases, it consists in the sum of the square of all the matrix entries. For vectors, this is also equals to the dot product of this with itself.\nsquaredNorm = _prop Internal.squaredNorm\n\n-- | The l2 norm of the matrix using the Blue's algorithm. A Portable Fortran Program to Find the Euclidean Norm of a Vector, ACM TOMS, Vol 4, Issue 1, 1978.\nblueNorm = _prop Internal.blueNorm\n\n-- | The l2 norm of the matrix avoiding undeflow and overflow. This version use a concatenation of hypot calls, and it is very slow.\nhypotNorm = _prop Internal.hypotNorm\n\n-- | The determinant of the matrix\ndeterminant :: forall n a. (Elem a, KnownNat n) => Matrix n n a -> a\ndeterminant m = _prop Internal.determinant m\n\n-- | Add two matrices.\nadd :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> Matrix n m a -> Matrix n m a\nadd m1 m2 = _binop Internal.add m1 m2\n\n-- | Subtract two matrices.\nsub :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> Matrix n m a -> Matrix n m a\nsub m1 m2 = _binop Internal.sub m1 m2\n\n-- | Multiply two matrices.\nmul :: (Elem a, KnownNat p, KnownNat q, KnownNat r) => Matrix p q a -> Matrix q r a -> Matrix p r a\nmul m1 m2 = _binop Internal.mul m1 m2\n\n{- | Apply a given function to each element of the matrix.\nHere is an example how to implement scalar matrix multiplication:\n\n>>> let a = fromList [[1,2],[3,4]] :: MatrixXf 2 2\n>>> a\nMatrix 2x2\n1.0 2.0\n3.0 4.0\n>>> map (*10) a\nMatrix 2x2\n10.0 20.0\n30.0 40.0\n-}\nmap :: Elem a => (a -> a) -> Matrix n m a -> Matrix n m a\nmap f (Matrix (Vec vals)) = Matrix $ Vec $ VS.map (toC . f . fromC) vals\n\n{- | Apply a given function to each element of the matrix.\nHere is an example how upper triangular matrix can be implemented:\n>>> let a = fromList [[1,2,3],[4,5,6],[7,8,9]] :: MatrixXf\n>>> a\nMatrix 3x3\n1.0 2.0 3.0\n4.0 5.0 6.0\n7.0 8.0 9.0\n>>> imap (\\row col val -> if row <= col then val else 0) a\nMatrix 3x3\n1.0 2.0 3.0\n0.0 5.0 6.0\n0.0 0.0 9.0\n-}\nimap :: (Elem a, KnownNat n, KnownNat m) => (Int -> Int -> a -> a) -> Matrix n m a -> Matrix n m a\nimap f (Matrix (Vec vals)) =\n withDims $ \\rs _ ->\n VS.imap (\\n ->\n let (c,r) = divMod n rs\n in toC . f r c . fromC) vals\n\n-- | Provide a view of the matrix for extraction of a subset.\ndata TriangularMode\n -- | View matrix as a lower triangular matrix.\n = Lower\n -- | View matrix as an upper triangular matrix.\n | Upper\n -- | View matrix as a lower triangular matrix with zeros on the diagonal.\n | StrictlyLower\n -- | View matrix as an upper triangular matrix with zeros on the diagonal.\n | StrictlyUpper\n -- | View matrix as a lower triangular matrix with ones on the diagonal.\n | UnitLower\n -- | View matrix as an upper triangular matrix with ones on the diagonal.\n | UnitUpper\n deriving (Eq, Enum, Show, Read)\n\n-- | Triangular view extracted from the current matrix\ntriangularView :: (Elem a, KnownNat n, KnownNat m) => TriangularMode -> Matrix n m a -> Matrix n m a\ntriangularView = \\case\n Lower -> imap $ \\row col val -> case compare row col of { LT -> 0; _ -> val }\n Upper -> imap $ \\row col val -> case compare row col of { GT -> 0; _ -> val }\n StrictlyLower -> imap $ \\row col val -> case compare row col of { GT -> val; _ -> 0 }\n StrictlyUpper -> imap $ \\row col val -> case compare row col of { LT -> val; _ -> 0 }\n UnitLower -> imap $ \\row col val -> case compare row col of { GT -> val; LT -> 0; EQ -> 1 }\n UnitUpper -> imap $ \\row col val -> case compare row col of { LT -> val; GT -> 0; EQ -> 1 }\n\n-- | Filter elements in the matrix. Filtered elements will be replaced by 0.\nfilter :: Elem a => (a -> Bool) -> Matrix n m a -> Matrix n m a\nfilter f = map (\\x -> if f x then x else 0)\n\n-- | Filter elements in the matrix with an indexed predicate. Filtered elements will be replaces by 0.\nifilter :: (Elem a, KnownNat n, KnownNat m) => (Int -> Int -> a -> Bool) -> Matrix n m a -> Matrix n m a\nifilter f = imap (\\r c x -> if f r c x then x else 0)\n\n-- | The length of the matrix.\nlength :: forall n m a r. (Elem a, KnownNat n, KnownNat m, r ~ (n * m), KnownNat r) => Matrix n m a -> Int\nlength _ = natToInt @r\n\n-- | Left fold of a matrix, where accumulation is lazy.\nfoldl :: (Elem a, KnownNat n, KnownNat m) => (b -> a -> b) -> b -> Matrix n m a -> b\nfoldl f b (Matrix (Vec vals)) = VS.foldl (\\a x -> f a (fromC x)) b vals\n\n-- | Right fold of a matrix, where accumulation is strict.\nfoldl' :: Elem a => (b -> a -> b) -> b -> Matrix n m a -> b\nfoldl' f b (Matrix (Vec vals)) = VS.foldl' (\\ !a x -> f a (fromC x)) b vals\n\n-- | Return the diagonal of a matrix.\ndiagonal :: (Elem a, KnownNat n, KnownNat m, r ~ Min n m, KnownNat r) => Matrix n m a -> Matrix r 1 a\ndiagonal = _unop Internal.diagonal\n\n{- | Inverse of the matrix\nFor small fixed sizes up to 4x4, this method uses cofactors. In the general case, this method uses PartialPivLU decomposition\n-}\ninverse :: forall n a. (Elem a, KnownNat n) => Matrix n n a -> Matrix n n a\ninverse = _unop Internal.inverse\n\n-- | Adjoint of the matrix\nadjoint :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> Matrix m n a\nadjoint = _unop Internal.adjoint\n\n-- | Transpose of the matrix\ntranspose :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> Matrix m n a\ntranspose = _unop Internal.transpose\n\n-- | Conjugate of the matrix\nconjugate :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> Matrix n m a\nconjugate = _unop Internal.conjugate\n\n-- | Normalise the matrix by dividing it on its 'norm'\nnormalize :: forall n m a. (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> Matrix n m a\nnormalize (Matrix (Vec vals)) = Internal.performIO $ do\n vals' <- VS.thaw vals\n VSM.unsafeWith vals' $ \\p ->\n let !rs = natToInt @n\n !cs = natToInt @m\n in Internal.call $ Internal.normalize p (toC rs) (toC cs)\n Matrix . Vec <$> VS.unsafeFreeze vals'\n\n-- | Apply a destructive operation to a matrix. The operation will be performed in-place, if it is safe\n-- to do so - otherwise, it will create a copy of the matrix.\nmodify :: (Elem a, KnownNat n, KnownNat m) => (forall s. M.MMatrix n m s a -> ST s ()) -> Matrix n m a -> Matrix n m a\nmodify f (Matrix (Vec vals)) = Matrix $ Vec $ VS.modify (f . M.fromVector ) vals\n\n-- | Extract rectangular block from matrix defined by startRow startCol blockRows blockCols\nblock :: forall sr sc br bc n m a.\n (Elem a, KnownNat sr, KnownNat sc, KnownNat br, KnownNat bc, KnownNat n, KnownNat m)\n => (sr <= n, sc <= m, br <= n, bc <= m)\n => Row sr -- ^ starting row\n -> Col sc -- ^ starting col\n -> Row br -- ^ block of rows\n -> Col bc -- ^ block of cols\n -> Matrix n m a -- ^ extract from this\n -> Matrix br bc a -- ^ extraction\nblock _ _ _ _ m =\n let !startRow = natToInt @sr\n !startCol = natToInt @sc\n in generate $ \\row col -> unsafeCoeff (startRow + row) (startCol + col) m\n\n-- | Turn a mutable matrix into an immutable matrix without copying.\n-- The mutable matrix should not be modified after this conversion.\nunsafeFreeze :: (Elem a, KnownNat n, KnownNat m, PrimMonad p) => M.MMatrix n m (PrimState p) a -> p (Matrix n m a)\nunsafeFreeze m = VS.unsafeFreeze (M.vals m) >>= pure . Matrix . Vec\n \n-- | Pass a pointer to the matrix's data to the IO action. The data may not be modified through the pointer.\nunsafeWith :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> (Ptr (C a) -> CInt -> CInt -> IO b) -> IO b\nunsafeWith m@(Matrix (Vec (vals))) f =\n VS.unsafeWith vals $ \\p ->\n let !rs = toC $! rows m\n !cs = toC $! cols m\n in f p rs cs\n\n_prop :: (Elem a, KnownNat n, KnownNat m) => (Ptr (C a) -> Ptr (C a) -> CInt -> CInt -> IO CString) -> Matrix n m a -> a\n{-# INLINE _prop #-}\n_prop f m = fromC $ Internal.performIO $ alloca $ \\p -> do\n Internal.call $ unsafeWith m (f p)\n peek p\n\n_binop :: forall n m n1 m1 n2 m2 a. (Elem a, KnownNat n, KnownNat m, KnownNat n1, KnownNat m1, KnownNat n2, KnownNat m2)\n => (Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString)\n -> Matrix n m a\n -> Matrix n1 m1 a\n -> Matrix n2 m2 a\n{-# INLINE _binop #-}\n_binop g m1 m2 = Internal.performIO $ do\n m0 :: M.IOMatrix n2 m2 a <- M.new\n M.unsafeWith m0 $ \\vals0 rows0 cols0 ->\n unsafeWith m1 $ \\vals1 rows1 cols1 ->\n unsafeWith m2 $ \\vals2 rows2 cols2 ->\n Internal.call $ g\n vals0 rows0 cols0\n vals1 rows1 cols1\n vals2 rows2 cols2\n unsafeFreeze m0\n\n_unop :: forall n m n1 m1 a. (Elem a, KnownNat n, KnownNat m, KnownNat n1, KnownNat m1)\n => (Ptr (C a) -> CInt -> CInt -> Ptr (C a) -> CInt -> CInt -> IO CString)\n -> Matrix n m a\n -> Matrix n1 m1 a\n{-# INLINE _unop #-}\n_unop g m1 = Internal.performIO $ do\n m0 :: M.IOMatrix n1 m1 a <- M.new\n M.unsafeWith m0 $ \\vals0 rows0 cols0 ->\n unsafeWith m1 $ \\vals1 rows1 cols1 ->\n Internal.call $ g\n vals0 rows0 cols0\n vals1 rows1 cols1\n unsafeFreeze m0\n\n-- | Convert a matrix to a list.\ntoList :: (Elem a, KnownNat n, KnownNat m) => Matrix n m a -> [[a]]\n{-# INLINE toList #-}\ntoList m@(Matrix (Vec vals))\n | null m = []\n | otherwise = [[fromC $ vals `VS.unsafeIndex` (col * _rows + row) | col <- [0..pred _cols]] | row <- [0..pred _rows]]\n where\n !_rows = rows m\n !_cols = cols m\n\n-- | Convert a list to a matrix. Returns 'Nothing' if the dimensions of the list do not match that\n-- of the matrix.\nfromList :: forall n m a. (Elem a, KnownNat n, KnownNat m) => [[a]] -> Maybe (Matrix n m a)\nfromList list = do\n let myRows = natToInt @n\n let myCols = natToInt @m\n let _rows = List.length list\n let _cols = List.foldl' max 0 (List.map List.length list)\n if ((myRows /= _rows) || (myCols /= _cols))\n then Nothing\n else (Just . Matrix . Vec) $ VS.create $ do\n vm <- VSM.replicate (_rows * _cols) (toC (0 :: a))\n forM_ (zip [0..] list) $ \\(row,vals) ->\n forM_ (zip [0..] vals) $ \\(col, val) ->\n VSM.write vm (col * _rows + row) (toC val)\n pure vm", "meta": {"hexsha": "356ae29a0def31bdbde4c7f69a1b0b9c4899a7d9", "size": 19076, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Eigen/Matrix.hs", "max_stars_repo_name": "nilsalex/eigen", "max_stars_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-07-17T08:14:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T10:27:07.000Z", "max_issues_repo_path": "src/Eigen/Matrix.hs", "max_issues_repo_name": "nilsalex/eigen", "max_issues_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2018-07-17T14:12:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T11:37:18.000Z", "max_forks_repo_path": "src/Eigen/Matrix.hs", "max_forks_repo_name": "nilsalex/eigen", "max_forks_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-11-22T08:11:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T07:40:02.000Z", "avg_line_length": 35.0018348624, "max_line_length": 227, "alphanum_fraction": 0.6349339484, "num_tokens": 5892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.33699140281104284}} {"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-|\nModule : Grenade.Core.Shape\nDescription : Dependently typed shapes of data which are passed between layers of a network\nCopyright : (c) Huw Campbell, 2016-2017\nLicense : BSD2\nStability : experimental\n\n\n-}\nmodule Grenade.Core.Shape (\n S (..)\n , Shape (..)\n#if MIN_VERSION_singletons(2,6,0)\n , SShape (..)\n#else\n , Sing (..)\n#endif\n\n , randomOfShape\n , fromStorable\n , fromStorableMatrix\n , nk\n , visualise2D\n , splitChannels\n , combineChannels\n ) where\n\n#if MIN_VERSION_singletons(2,6,0)\nimport Data.Kind (Type)\n#endif\n\nimport Control.DeepSeq (NFData (..))\nimport Data.List.Split (chunksOf)\nimport Data.Maybe (fromJust)\nimport Data.Proxy\nimport Data.Serialize\nimport Data.Singletons\nimport Data.Singletons.TypeLits\nimport Data.Vector.Storable (Vector)\nimport qualified Data.Vector.Storable as V\nimport GHC.TypeLits hiding (natVal)\nimport Numeric.LinearAlgebra (Matrix)\nimport qualified Numeric.LinearAlgebra as NLA\nimport qualified Numeric.LinearAlgebra.Data as NLAD\nimport Numeric.LinearAlgebra.Static\nimport qualified Numeric.LinearAlgebra.Static as H\n\nimport System.Random.MWC\n\nimport Grenade.Types\n\n-- | The current shapes we accept.\n-- at the moment this is just one, two, and three dimensional\n-- Vectors/Matricies.\n--\n-- These are only used with DataKinds, as Kind `Shape`, with Types 'D1, 'D2, 'D3.\ndata Shape\n = D1 Nat\n -- ^ One dimensional vector\n | D2 Nat Nat\n -- ^ Two dimensional matrix. Row, Column.\n | D3 Nat Nat Nat\n -- ^ Three dimensional matrix. Row, Column, Channels.\n | D4 Nat Nat Nat Nat\n -- ^ Four dimensional matrix. Depth, Channels, Row, Column\n\n-- | Concrete data structures for a Shape.\n--\n-- All shapes are held in contiguous memory.\n-- 3D is held in a matrix (usually row oriented) which has height depth * rows.\ndata S (n :: Shape) where\n S1D :: ( KnownNat len )\n => R len\n -> S ('D1 len)\n\n S2D :: ( KnownNat rows, KnownNat columns )\n => L rows columns\n -> S ('D2 rows columns)\n\n S3D :: ( KnownNat rows\n , KnownNat columns\n , KnownNat channels\n , KnownNat (rows * channels) )\n => L (rows * channels) columns\n -> S ('D3 rows columns channels)\n\n S4D :: ( KnownNat rows\n , KnownNat columns\n , KnownNat channels\n , KnownNat depth)\n => L (depth * channels * rows) columns\n -> S ('D4 depth channels rows columns)\n\nderiving instance Show (S n)\n\n-- Singleton instances.\n--\n-- These could probably be derived with template haskell, but this seems\n-- clear and makes adding the KnownNat constraints simple.\n-- We can also keep our code TH free, which is great.\n#if MIN_VERSION_singletons(2,6,0)\n-- In singletons 2.6 Sing switched from a data family to a type family.\ntype instance Sing = SShape\n\n-- | Datatype to allow \"pattern matching\" on shapes at the type level through\n-- the use the sing function from Singletons.\ndata SShape :: Shape -> Type where\n D1Sing :: Sing a -> SShape ('D1 a)\n D2Sing :: Sing a -> Sing b -> SShape ('D2 a b)\n D3Sing :: KnownNat (a * c) => Sing a -> Sing b -> Sing c -> SShape ('D3 a b c)\n D4Sing :: KnownNat (a * c * d) => Sing a -> Sing b -> Sing c -> Sing d -> SShape ('D4 a b c d)\n#else\ndata instance Sing (n :: Shape) where\n D1Sing :: Sing a -> Sing ('D1 a)\n D2Sing :: Sing a -> Sing b -> Sing ('D2 a b)\n D3Sing :: KnownNat (a * c) => Sing a -> Sing b -> Sing c -> Sing ('D3 a b c)\n D4Sing :: KnownNat (a * c * d) => Sing a -> Sing b -> Sing c -> Sing d -> Sing ('D4 a b c d)\n#endif\n\ninstance KnownNat a => SingI ('D1 a) where\n sing = D1Sing sing\ninstance (KnownNat a, KnownNat b) => SingI ('D2 a b) where\n sing = D2Sing sing sing\ninstance (KnownNat a, KnownNat b, KnownNat c, KnownNat (a * c)) => SingI ('D3 a b c) where\n sing = D3Sing sing sing sing\ninstance (KnownNat a, KnownNat b, KnownNat c, KnownNat d) => SingI ('D4 a b c d) where\n sing = D4Sing sing sing sing sing\n\ninstance SingI x => Num (S x) where\n (+) = n2 (+)\n (-) = n2 (-)\n (*) = n2 (*)\n abs = n1 abs\n signum = n1 signum\n fromInteger x = nk (fromInteger x)\n\ninstance SingI x => Fractional (S x) where\n (/) = n2 (/)\n recip = n1 recip\n fromRational x = nk (fromRational x)\n\ninstance SingI x => Floating (S x) where\n pi = nk pi\n exp = n1 exp\n log = n1 log\n sqrt = n1 sqrt\n (**) = n2 (**)\n logBase = n2 logBase\n sin = n1 sin\n cos = n1 cos\n tan = n1 tan\n asin = n1 asin\n acos = n1 acos\n atan = n1 atan\n sinh = n1 sinh\n cosh = n1 cosh\n tanh = n1 tanh\n asinh = n1 asinh\n acosh = n1 acosh\n atanh = n1 atanh\n\n--\n-- I haven't made shapes strict, as sometimes they're not needed\n-- (the last input gradient back for instance)\n--\ninstance NFData (S x) where\n rnf (S1D x) = rnf x\n rnf (S2D x) = rnf x\n rnf (S3D x) = rnf x\n rnf (S4D x) = rnf x\n\n-- | Generate random data of the desired shape\nrandomOfShape :: forall x . (SingI x) => IO (S x)\nrandomOfShape = do\n seed :: Int <- withSystemRandom . asGenST $ \\gen -> uniform gen\n return $ case (sing :: Sing x) of\n D1Sing SNat ->\n S1D (H.randomVector seed H.Uniform * 2 - 1)\n\n D2Sing SNat SNat ->\n S2D (H.uniformSample seed (-1) 1)\n\n D3Sing SNat SNat SNat ->\n S3D (H.uniformSample seed (-1) 1)\n\n D4Sing SNat SNat SNat SNat ->\n S4D (H.uniformSample seed (-1) 1)\n\n-- | Generate a shape from a Storable Vector.\n--\n-- Returns Nothing if the vector is of the wrong size.\nfromStorable :: forall x. SingI x => Vector RealNum -> Maybe (S x)\nfromStorable xs = case sing :: Sing x of\n D1Sing SNat ->\n S1D <$> H.create xs\n\n D2Sing SNat SNat ->\n S2D <$> mkL xs\n\n D3Sing SNat SNat SNat ->\n S3D <$> mkL xs\n\n D4Sing SNat SNat SNat SNat ->\n S4D <$> mkL xs\n where\n mkL :: forall rows columns. (KnownNat rows, KnownNat columns)\n => Vector RealNum -> Maybe (L rows columns)\n mkL v =\n let rows = fromIntegral $ natVal (Proxy :: Proxy rows)\n columns = fromIntegral $ natVal (Proxy :: Proxy columns)\n in if rows * columns == V.length v\n then H.create $ NLA.reshape columns v\n else Nothing\n\n-- | Generate a shape from a Storable Matrix.\n--\n-- Returns Nothing if the matrix is of the wrong size (or one dimensional)\nfromStorableMatrix :: forall x. SingI x => Matrix RealNum -> Maybe (S x)\nfromStorableMatrix xs = case sing :: Sing x of\n D1Sing SNat ->\n Nothing\n\n D2Sing SNat SNat ->\n S2D <$> mkL xs\n\n D3Sing SNat SNat SNat ->\n S3D <$> mkL xs\n\n D4Sing SNat SNat SNat SNat ->\n S4D <$> mkL xs\n where\n mkL :: forall rows columns. (KnownNat rows, KnownNat columns)\n => Matrix RealNum -> Maybe (L rows columns)\n mkL m =\n let rows = fromIntegral $ natVal (Proxy :: Proxy rows)\n columns = fromIntegral $ natVal (Proxy :: Proxy columns)\n (h, w) = NLA.size m\n in if rows == h && columns == w\n then H.create m\n else Nothing\n\ninstance SingI x => Serialize (S x) where\n put i = (case i of\n (S1D x) -> putListOf put . NLA.toList . H.extract $ x\n (S2D x) -> putListOf put . NLA.toList . NLA.flatten . H.extract $ x\n (S3D x) -> putListOf put . NLA.toList . NLA.flatten . H.extract $ x\n (S4D x) -> putListOf put . NLA.toList . NLA.flatten . H.extract $ x\n ) :: PutM ()\n\n get = do\n Just i <- fromStorable . V.fromList <$> getListOf get\n return i\n\n-- Helper function for creating the number instances\nn1 :: ( forall a. Floating a => a -> a ) -> S x -> S x\nn1 f (S1D x) = S1D (f x)\nn1 f (S2D x) = S2D (f x)\nn1 f (S3D x) = S3D (f x)\nn1 f (S4D x) = S4D (f x)\n\n-- Helper function for creating the number instances\nn2 :: ( forall a. Floating a => a -> a -> a ) -> S x -> S x -> S x\nn2 f (S1D x) (S1D y) = S1D (f x y)\nn2 f (S2D x) (S2D y) = S2D (f x y)\nn2 f (S3D x) (S3D y) = S3D (f x y)\nn2 f (S4D x) (S4D y) = S4D (f x y)\n\n-- | Helper function for creating the number instances\nnk :: forall x. SingI x => RealNum -> S x\nnk x = case (sing :: Sing x) of\n D1Sing SNat ->\n S1D (H.konst x)\n\n D2Sing SNat SNat ->\n S2D (H.konst x)\n\n D3Sing SNat SNat SNat ->\n S3D (H.konst x)\n\n D4Sing SNat SNat SNat SNat ->\n S4D (H.konst x)\n\n-- | Prints out the contents of a matrix with entries between zero and the max value\nvisualise2D :: S ('D2 a b) -- ^ input matrix\n -> RealNum -- ^ maximum element value\n -> String -- ^ pretty printed matrix\nvisualise2D (S2D mm) max =\n let m = H.extract mm\n ms = NLAD.toLists m\n render n' | n' <= 0.2 * max = ' '\n | n' <= 0.4 * max = '.'\n | n' <= 0.6 * max = '-'\n | n' <= 0.8 * max = '='\n | otherwise = '#'\n px = (fmap . fmap) render ms\n in unlines px\n\n-- | TODO Theo\nsplitChannels :: forall rows columns channels.\n (KnownNat rows, KnownNat columns)\n => S ('D3 rows columns channels) -> [S ('D2 rows columns)]\nsplitChannels (S3D x)\n = let r = fromIntegral $ natVal (Proxy :: Proxy rows)\n rs = NLA.toRows $ H.extract x\n rs' = chunksOf r rs\n ms = map (S2D . fromJust . H.create . NLA.fromRows) rs' :: [S ('D2 rows columns)]\n in ms\n\n-- | TODO Theo\ncombineChannels :: forall rows columns channels.\n (KnownNat rows, KnownNat columns, KnownNat channels)\n => [S ('D2 rows columns)] -> S ('D3 rows columns channels)\ncombineChannels xs\n = let xs' = map (\\(S2D x) -> NLA.toRows $ H.extract x) xs :: [[Vector RealNum]]\n xs'' = concat xs'\n in S3D $ fromJust . H.create . NLA.fromRows $ xs''\n", "meta": {"hexsha": "52a4a9e815284263ef527c7de1748922b2914b74", "size": 10217, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Core/Shape.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Core/Shape.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Core/Shape.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0547112462, "max_line_length": 96, "alphanum_fraction": 0.5924439659, "num_tokens": 3121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.3355929902861035}} {"text": "-- | See Hoffman, Gelman (2011) The No U-Turn Sampler: Adaptively Setting Path\n-- Lengths in Hamiltonian Monte Carlo.\n\nmodule Numeric.MCMC.NUTS where\n\nimport Control.Monad\nimport Control.Monad.Loops\nimport Control.Monad.Primitive\nimport System.Random.MWC\nimport System.Random.MWC.Distributions hiding (gamma)\nimport Statistics.Distribution.Normal\n\ntype Parameters = [Double] \ntype Density = Parameters -> Double\ntype Gradient = Parameters -> Parameters\ntype Particle = (Parameters, Parameters)\ntype StateSpecs = ([Double], [Double], [Double], [Double], [Double], Int, Int)\n\nnewtype StateTree = StateTree { \n getStateTree :: StateSpecs\n }\n\ninstance Show StateTree where\n show (StateTree (tm, rm, tp, rp, t', n, s)) = \n \"\\n\" ++ \"tm: \" ++ show tm \n ++ \"\\n\" ++ \"tp: \" ++ show tp\n ++ \"\\n\" ++ \"t': \" ++ show t'\n ++ \"\\n\" ++ \"n : \" ++ show n\n ++ \"\\n\" ++ \"s : \" ++ show s\n\ndata DualAveragingParameters = DualAveragingParameters {\n mAdapt :: Int\n , delta :: Double\n , mu :: Double\n , gamma :: Double\n , tau0 :: Double\n , kappa :: Double\n } deriving Show\n\n-- | The NUTS sampler.\nnuts \n :: PrimMonad m\n => Density\n -> Gradient\n -> Int\n -> Double\n -> Parameters\n -> Gen (PrimState m)\n -> m [Parameters]\nnuts lTarget glTarget n e t g = go t 0 []\n where go position j acc\n | j >= n = return acc\n | otherwise = do\n nextPosition <- nutsKernel lTarget glTarget e position g\n go nextPosition (succ j) (nextPosition : acc)\n\n-- | The NUTS sampler with dual averaging.\nnutsDualAveraging\n :: PrimMonad m\n => Density\n -> Gradient\n -> Int\n -> Int\n -> Parameters\n -> Gen (PrimState m)\n -> m [Parameters]\nnutsDualAveraging lTarget glTarget n nAdapt t g = do\n e0 <- findReasonableEpsilon lTarget glTarget t g\n let daParams = basicDualAveragingParameters e0 nAdapt\n chain <- unfoldrM (kernel daParams) (1, e0, 1, 0, t)\n return $ drop nAdapt chain\n where\n kernel params (m, e, eAvg, h, t0) = do\n (eNext, eAvgNext, hNext, tNext) <- \n nutsKernelDualAvg lTarget glTarget e eAvg h m params t0 g\n return $ if m > n + nAdapt\n then Nothing\n else Just (t0, (succ m, eNext, eAvgNext, hNext, tNext))\n\n-- | Default DA parameters, given a base step size and burn in period.\nbasicDualAveragingParameters :: Double -> Int -> DualAveragingParameters\nbasicDualAveragingParameters step burnInPeriod = DualAveragingParameters {\n mu = log (10 * step)\n , delta = 0.5\n , mAdapt = burnInPeriod\n , gamma = 0.05\n , tau0 = 10\n , kappa = 0.75\n }\n\n-- | A single iteration of dual-averaging NUTS.\nnutsKernelDualAvg \n :: PrimMonad m \n => Density\n -> Gradient\n -> Double\n -> Double\n -> Double\n -> Int\n -> DualAveragingParameters\n -> [Double]\n -> Gen (PrimState m)\n -> m (Double, Double, Double, Parameters)\nnutsKernelDualAvg lTarget glTarget e eAvg h m daParams t g = do\n r0 <- replicateM (length t) (normal 0 1 g)\n z0 <- exponential 1 g\n let logu = log (auxilliaryTarget lTarget t r0) - z0\n\n let go (tn, tp, rn, rp, tm, j, n, s, a, na) g\n | s == 1 = do\n vj <- symmetricCategorical [-1, 1] g\n z <- uniform g\n\n (tnn, rnn, tpp, rpp, t1, n1, s1, a1, na1) <-\n if vj == -1\n then do\n (tnn', rnn', _, _, t1', n1', s1', a1', na1') <- \n buildTreeDualAvg lTarget glTarget g tn rn logu vj j e t r0\n return (tnn', rnn', tp, rp, t1', n1', s1', a1', na1')\n else do\n (_, _, tpp', rpp', t1', n1', s1', a1', na1') <- \n buildTreeDualAvg lTarget glTarget g tp rp logu vj j e t r0\n return (tn, rn, tpp', rpp', t1', n1', s1', a1', na1')\n\n let accept = s1 == 1 && (min 1 (fi n1 / fi n :: Double)) > z \n\n n2 = n + n1\n s2 = s1 * stopCriterion tnn tpp rnn rpp\n j1 = succ j\n t2 | accept = t1\n | otherwise = tm\n\n go (tnn, tpp, rnn, rpp, t2, j1, n2, s2, a1, na1) g\n\n | otherwise = return (tm, a, na)\n\n (nextPosition, alpha, nalpha) <- go (t, t, r0, r0, t, 0, 1, 1, 0, 0) g\n \n let (hNext, eNext, eAvgNext) =\n if m <= mAdapt daParams\n then (hm, exp logEm, exp logEbarM)\n else (h, eAvg, eAvg)\n where\n eta = 1 / (fromIntegral m + tau0 daParams)\n hm = (1 - eta) * h \n + eta * (delta daParams - alpha / fromIntegral nalpha)\n\n zeta = fromIntegral m ** (- (kappa daParams))\n\n logEm = mu daParams - sqrt (fromIntegral m) / gamma daParams * hm\n logEbarM = (1 - zeta) * log eAvg + zeta * logEm\n\n return (eNext, eAvgNext, hNext, nextPosition)\n\n-- | A single iteration of NUTS.\nnutsKernel \n :: PrimMonad m \n => Density\n -> Gradient\n -> Double\n -> Parameters\n -> Gen (PrimState m)\n -> m Parameters\nnutsKernel lTarget glTarget e t g = do\n r0 <- replicateM (length t) (normal 0 1 g)\n z0 <- exponential 1 g\n let logu = log (auxilliaryTarget lTarget t r0) - z0\n\n let go (tn, tp, rn, rp, tm, j, n, s) g\n | s == 1 = do\n vj <- symmetricCategorical [-1, 1] g\n z <- uniform g\n\n (tnn, rnn, tpp, rpp, t1, n1, s1) <- \n if vj == -1\n then do\n (tnn', rnn', _, _, t1', n1', s1') <- \n buildTree lTarget glTarget g tn rn logu vj j e\n return (tnn', rnn', tp, rp, t1', n1', s1')\n else do\n (_, _, tpp', rpp', t1', n1', s1') <- \n buildTree lTarget glTarget g tp rp logu vj j e\n return (tn, rn, tpp', rpp', t1', n1', s1')\n\n let accept = s1 == 1 && (min 1 (fi n1 / fi n :: Double)) > z\n\n n2 = n + n1\n s2 = s1 * stopCriterion tnn tpp rnn rpp\n j1 = succ j\n t2 | accept = t1\n | otherwise = tm\n\n go (tnn, tpp, rnn, rpp, t2, j1, n2, s2) g\n\n | otherwise = return tm\n\n go (t, t, r0, r0, t, 0, 1, 1) g\n\n-- | Build the 'tree' of candidate states.\nbuildTree \n :: PrimMonad m \n => Density\n -> Gradient\n -> Gen (PrimState m)\n -> Parameters\n -> Parameters\n -> Double\n -> Double\n -> Int\n -> Double\n -> m StateSpecs\nbuildTree lTarget glTarget g t r logu v 0 e = do\n let (t0, r0) = leapfrog glTarget (t, r) (v * e)\n joint = log $ auxilliaryTarget lTarget t0 r0\n n = indicate (logu < joint)\n s = indicate (logu - 1000 < joint)\n return (t0, r0, t0, r0, t0, n, s)\n\nbuildTree lTarget glTarget g t r logu v j e = do\n z <- uniform g\n (tn, rn, tp, rp, t0, n0, s0) <- \n buildTree lTarget glTarget g t r logu v (pred j) e\n\n if s0 == 1\n then do\n (tnn, rnn, tpp, rpp, t1, n1, s1) <- \n if v == -1\n then do\n (tnn', rnn', _, _, t1', n1', s1') <- \n buildTree lTarget glTarget g tn rn logu v (pred j) e\n return (tnn', rnn', tp, rp, t1', n1', s1')\n else do\n (_, _, tpp', rpp', t1', n1', s1') <- \n buildTree lTarget glTarget g tp rp logu v (pred j) e\n return (tn, rn, tpp', rpp', t1', n1', s1')\n\n let accept = (fi n1 / max (fi (n0 + n1)) 1) > (z :: Double)\n n2 = n0 + n1\n s2 = s0 * s1 * stopCriterion tnn tpp rnn rpp\n t2 | accept = t1\n | otherwise = t0 \n\n return (tnn, rnn, tpp, rpp, t2, n2, s2)\n else return (tn, rn, tp, rp, t0, n0, s0)\n\n-- | Determine whether or not to stop doubling the tree of candidate states.\nstopCriterion :: (Integral a, Num b, Ord b) => [b] -> [b] -> [b] -> [b] -> a\nstopCriterion tn tp rn rp = \n indicate (positionDifference `innerProduct` rn >= 0)\n * indicate (positionDifference `innerProduct` rp >= 0)\n where\n positionDifference = tp .- tn\n\n-- | Build the tree of candidate states under dual averaging.\nbuildTreeDualAvg\n :: PrimMonad m \n => Density\n -> Gradient\n -> Gen (PrimState m)\n -> Parameters\n -> Parameters\n -> Double\n -> Double\n -> Int\n -> Double\n -> Parameters\n -> Parameters\n -> m ([Double], [Double], [Double], [Double], [Double], Int, Int, Double, Int)\nbuildTreeDualAvg lTarget glTarget g t r logu v 0 e t0 r0 = do\n let (t1, r1) = leapfrog glTarget (t, r) (v * e)\n joint = log $ auxilliaryTarget lTarget t1 r1\n n = indicate (logu < joint)\n s = indicate (logu - 1000 < joint)\n a = min 1 (acceptanceRatio lTarget t0 t1 r0 r1)\n return (t1, r1, t1, r1, t1, n, s, a, 1)\n \nbuildTreeDualAvg lTarget glTarget g t r logu v j e t0 r0 = do\n z <- uniform g\n (tn, rn, tp, rp, t1, n1, s1, a1, na1) <- \n buildTreeDualAvg lTarget glTarget g t r logu v (pred j) e t0 r0\n\n if s1 == 1\n then do\n (tnn, rnn, tpp, rpp, t2, n2, s2, a2, na2) <-\n if v == -1\n then do \n (tnn', rnn', _, _, t1', n1', s1', a1', na1') <- \n buildTreeDualAvg lTarget glTarget g tn rn logu v (pred j) e t0 r0\n return (tnn', rnn', tp, rp, t1', n1', s1', a1', na1')\n else do\n (_, _, tpp', rpp', t1', n1', s1', a1', na1') <-\n buildTreeDualAvg lTarget glTarget g tp rp logu v (pred j) e t0 r0\n return (tn, rn, tpp', rpp', t1', n1', s1', a1', na1')\n\n let p = fi n2 / max (fi (n1 + n2)) 1\n accept = p > (z :: Double)\n n3 = n1 + n2\n a3 = a1 + a2\n na3 = na1 + na2\n s3 = s1 * s2 * stopCriterion tnn tpp rnn rpp\n\n t3 | accept = t2\n | otherwise = t1\n\n return (tnn, rnn, tpp, rpp, t3, n3, s3, a3, na3)\n else return (tn, rn, tp, rp, t1, n1, s1, a1, na1)\n\n-- | Heuristic for initializing step size.\nfindReasonableEpsilon \n :: PrimMonad m \n => Density\n -> Gradient\n -> Parameters\n -> Gen (PrimState m) \n -> m Double\nfindReasonableEpsilon lTarget glTarget t0 g = do\n r0 <- replicateM (length t0) (normal 0 1 g)\n let (t1, r1) = leapfrog glTarget (t0, r0) 1.0\n a = 2 * indicate (acceptanceRatio lTarget t0 t1 r0 r1 > 0.5) - 1\n\n go j e t r \n | j <= 0 = e -- no need to shrink this excessively\n | (acceptanceRatio lTarget t0 t r0 r) ^^ a > 2 ^^ (-a) = \n let (tn, rn) = leapfrog glTarget (t, r) e\n in go (pred j) (2 ^^ a * e) tn rn \n | otherwise = e\n\n return $ go 10 1.0 t1 r1\n\n-- | Simulate a single step of Hamiltonian dynamics.\nleapfrog :: Gradient -> Particle -> Double -> Particle\nleapfrog glTarget (t, r) e = (tf, rf)\n where \n rm = adjustMomentum glTarget e t r\n tf = adjustPosition e rm t\n rf = adjustMomentum glTarget e tf rm\n\n-- | Adjust momentum.\nadjustMomentum :: Fractional c => (t -> [c]) -> c -> t -> [c] -> [c]\nadjustMomentum glTarget e t r = r .+ ((e / 2) .* glTarget t)\n\n-- | Adjust position.\nadjustPosition :: Num c => c -> [c] -> [c] -> [c]\nadjustPosition e r t = t .+ (e .* r)\n\n-- | The MH acceptance ratio for a given proposal.\nacceptanceRatio :: Floating a => (t -> a) -> t -> t -> [a] -> [a] -> a\nacceptanceRatio lTarget t0 t1 r0 r1 = auxilliaryTarget lTarget t1 r1\n / auxilliaryTarget lTarget t0 r0\n\n-- | The negative potential. \nauxilliaryTarget :: Floating a => (t -> a) -> t -> [a] -> a\nauxilliaryTarget lTarget t r = exp (lTarget t - 0.5 * innerProduct r r)\n\n-- | Simple inner product.\ninnerProduct :: Num a => [a] -> [a] -> a\ninnerProduct xs ys = sum $ zipWith (*) xs ys\n\n-- | Vectorized multiplication.\n(.*) :: Num b => b -> [b] -> [b]\nz .* xs = map (* z) xs\n\n-- | Vectorized subtraction.\n(.-) :: Num a => [a] -> [a] -> [a]\nxs .- ys = zipWith (-) xs ys\n\n-- | Vectorized addition.\n(.+) :: Num a => [a] -> [a] -> [a]\nxs .+ ys = zipWith (+) xs ys\n\n-- | Indicator function.\nindicate :: Integral a => Bool -> a\nindicate True = 1\nindicate False = 0\n\n-- | A symmetric categorical (discrete uniform) distribution.\nsymmetricCategorical :: PrimMonad m => [a] -> Gen (PrimState m) -> m a\nsymmetricCategorical [] _ = error \"symmetricCategorical: no candidates\"\nsymmetricCategorical zs g = do\n j <- uniformR (0, length zs - 1) g\n return $ zs !! j\n\n-- | Alias for fromIntegral.\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\n\n", "meta": {"hexsha": "83169a6e9468268c97ae7d82a6882a030b717027", "size": 12092, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/MCMC/NUTS.hs", "max_stars_repo_name": "jtobin/hnuts", "max_stars_repo_head_hexsha": "5fa71a62057073bfdb32bf1d0264a1da3c32f247", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-01-16T15:03:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-19T21:38:56.000Z", "max_issues_repo_path": "src/Numeric/MCMC/NUTS.hs", "max_issues_repo_name": "jtobin/hnuts", "max_issues_repo_head_hexsha": "5fa71a62057073bfdb32bf1d0264a1da3c32f247", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-01-25T14:08:57.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-28T12:34:50.000Z", "max_forks_repo_path": "src/Numeric/MCMC/NUTS.hs", "max_forks_repo_name": "jtobin/hnuts", "max_forks_repo_head_hexsha": "5fa71a62057073bfdb32bf1d0264a1da3c32f247", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-01-16T13:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T05:08:21.000Z", "avg_line_length": 31.2454780362, "max_line_length": 80, "alphanum_fraction": 0.5493714853, "num_tokens": 4131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3355019760181963}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeOperators #-}\nmodule FokkerPlanck.Pinwheel\n ( module Filter.Pinwheel\n , module FokkerPlanck.Pinwheel\n ) where\n\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Unboxed as VU\nimport Filter.Pinwheel\nimport FokkerPlanck.Interpolation\nimport Numeric.LinearAlgebra.Data as NL\nimport Numeric.LinearAlgebra.HMatrix\nimport Types\nimport Utils.Array\nimport Utils.Coordinates\nimport Utils.Parallel\n\n{-# INLINE computeR2Z1T0ArrayRadial #-}\ncomputeR2Z1T0ArrayRadial ::\n (R.Source r Double)\n => R.Array r DIM3 Double\n -> Int\n -> Int\n -> Double\n -> [Double]\n -> [Double]\n -> R.Array D DIM4 (Complex Double)\ncomputeR2Z1T0ArrayRadial radialArr xLen yLen scaleFactor thetaFreqs theta0Freqs =\n let pinwheelArr =\n traverse2\n (fromListUnboxed (Z :. L.length thetaFreqs) thetaFreqs)\n (fromListUnboxed (Z :. L.length theta0Freqs) theta0Freqs)\n (\\(Z :. numThetaFreq) (Z :. numTheta0Freq) ->\n (Z :. numThetaFreq :. numTheta0Freq :. xLen :. yLen)) $ \\f f0 (Z :. k :. l :. i :. j) ->\n pinwheel\n (f (Z :. k) - f0 (Z :. l))\n 0\n (exp 1)\n 0\n (i - center xLen)\n (j - center yLen)\n in radialCubicInterpolation radialArr scaleFactor pinwheelArr\n\n\n{-# INLINE computeR2Z2T0S0ArrayRadial #-}\ncomputeR2Z2T0S0ArrayRadial ::\n (R.Source r Double)\n => PinwheelType\n -> R.Array r DIM5 Double\n -> Int\n -> Int\n -> Double\n -> Double\n -> [Double]\n -> [Double]\n -> [Double]\n -> [Double]\n -> R.Array D DIM6 (Complex Double)\ncomputeR2Z2T0S0ArrayRadial pinwheelType radialArr xLen yLen scaleFactor rMax thetaFreqs scaleFreqs theta0Freqs scale0Freqs =\n let pinwheelArr =\n traverse4\n (fromListUnboxed (Z :. L.length thetaFreqs) thetaFreqs)\n (fromListUnboxed (Z :. L.length scaleFreqs) scaleFreqs)\n (fromListUnboxed (Z :. L.length theta0Freqs) theta0Freqs)\n (fromListUnboxed (Z :. L.length scale0Freqs) scale0Freqs)\n (\\(Z :. numThetaFreq) (Z :. numScaleFreq) (Z :. numTheta0Freq) (Z :. numScale0Freq) ->\n (Z :. numThetaFreq :. numScaleFreq :. numTheta0Freq :.\n numScale0Freq :.\n xLen :.\n yLen)) $ \\ft fs ft0 fs0 (Z :. t :. s :. t0 :. s0 :. i :. j) ->\n pinwheelFunc\n pinwheelType\n (ft (Z :. t) - ft0 (Z :. t0))\n (fs (Z :. s) - fs0 (Z :. s0))\n rMax\n 0\n (i - center xLen)\n (j - center yLen)\n in radialCubicInterpolation radialArr scaleFactor pinwheelArr\n\n{-# INLINE computeR2Z2T0S0ArrayRadial' #-}\ncomputeR2Z2T0S0ArrayRadial' ::\n Int\n -> Int\n -> Double\n -> Double\n -> [Double]\n -> [Double]\n -> [Double]\n -> [Double]\n -> R.Array D DIM6 (Complex Double)\ncomputeR2Z2T0S0ArrayRadial' xLen yLen scaleFactor rMax thetaFreqs scaleFreqs theta0Freqs scale0Freqs =\n let pinwheelArr =\n traverse4\n (fromListUnboxed (Z :. L.length thetaFreqs) thetaFreqs)\n (fromListUnboxed (Z :. L.length scaleFreqs) scaleFreqs)\n (fromListUnboxed (Z :. L.length theta0Freqs) theta0Freqs)\n (fromListUnboxed (Z :. L.length scale0Freqs) scale0Freqs)\n (\\(Z :. numThetaFreq) (Z :. numScaleFreq) (Z :. numTheta0Freq) (Z :. numScale0Freq) ->\n (Z :. numThetaFreq :. numScaleFreq :. numTheta0Freq :.\n numScale0Freq :.\n xLen :.\n yLen)) $ \\ft fs ft0 fs0 (Z :. t :. s :. t0 :. s0 :. i :. j) ->\n pinwheel\n (ft (Z :. t) - ft0 (Z :. t0))\n (fs (Z :. s) - fs0 (Z :. s0))\n rMax\n 0\n (i - center xLen)\n (j - center yLen)\n in pinwheelArr\n\n{-# INLINE cutoff #-}\ncutoff :: (R.Source r Double) => Int -> R.Array r DIM5 Double -> R.Array D DIM5 Double\ncutoff r arr =\n R.traverse arr id $ \\f idx@(Z :. _ :. _ :. _ :. _ :. e) ->\n if e > r \n then 0\n else f idx\n\n{-# INLINE computeLocalEigenVector #-}\ncomputeLocalEigenVector ::\n (R.Source r Double)\n => ParallelParams\n -> (Double -> Double -> Double -> Double -> Int -> Int -> Complex Double)\n -> R.Array r DIM5 Double\n -> Int\n -> Int\n -> Double\n -> [Double]\n -> [Double]\n -> R.Array U DIM4 (Complex Double)\ncomputeLocalEigenVector parallelParams pinwheelFunc radialArr xLen yLen rMax thetaFreqs scaleFreqs =\n let (Z :. numThetaFreq :. numScaleFreq :. _ :. _ :. _) = extent radialArr\n len = numThetaFreq * numScaleFreq\n in computeS .\n rotate4D .\n rotate4D .\n fromUnboxed (Z :. xLen :. yLen :. numThetaFreq :. numScaleFreq) .\n VU.concat .\n parMapChunk\n parallelParams\n rdeepseq\n (\\(x, y) ->\n let r =\n sqrt $\n (fromIntegral $ x - center xLen) ^ 2 +\n (fromIntegral $ y - center yLen) ^ 2\n interpolatedArray = cubicInterpolation radialArr r\n interpolatedPinwheel =\n R.traverse3\n interpolatedArray\n (fromListUnboxed (Z :. numThetaFreq) thetaFreqs)\n (fromListUnboxed (Z :. numScaleFreq) scaleFreqs)\n (\\sh _ _ -> sh) $ \\f ft fs idx@(Z :. t :. s :. t0 :. s0) ->\n (f idx :+ 0) *\n pinwheelFunc\n (ft (Z :. t) - ft (Z :. t0))\n (fs (Z :. s) + fs (Z :. s0))\n rMax\n 0\n (x - center xLen)\n (y - center yLen)\n (eigVal, eigVec) =\n eig . (len >< len) . R.toList $ interpolatedPinwheel\n (val, vec) =\n L.head . L.reverse . L.sortOn (magnitude . fst) $\n L.zip (NL.toList eigVal) (toColumns $ eigVec)\n dominantVec = VU.fromList . L.map (* val) . NL.toList $ vec\n in -- VU.zipWith\n -- (*)\n -- (VU.fromList\n -- [ exp\n -- (0 :+\n -- (tf) *\n -- (angleFunctionRad\n -- (fromIntegral $ x - center xLen)\n -- (fromIntegral $ y - center yLen)))\n -- | tf <- thetaFreqs\n -- , sf <- scaleFreqs\n -- ])\n -- dominantVec\n dominantVec\n ) $\n [(x, y) | x <- [0 .. xLen - 1], y <- [0 .. yLen - 1]]\n \n{-# INLINE computeLocalEigenVectorSink #-}\ncomputeLocalEigenVectorSink ::\n (R.Source r Double)\n => ParallelParams\n -> (Double -> Double -> Double -> Double -> Int -> Int -> Complex Double)\n -> R.Array r DIM5 Double\n -> Int\n -> Int\n -> Double\n -> [Double]\n -> [Double]\n -> R.Array U DIM4 (Complex Double)\ncomputeLocalEigenVectorSink parallelParams pinwheelFunc radialArr xLen yLen rMax thetaFreqs scaleFreqs =\n let (Z :. numThetaFreq :. numScaleFreq :. _ :. _ :. _) = extent radialArr\n len = numThetaFreq * numScaleFreq\n in computeS .\n rotate4D .\n rotate4D .\n fromUnboxed (Z :. xLen :. yLen :. numThetaFreq :. numScaleFreq) .\n VU.concat .\n parMapChunk\n parallelParams\n rdeepseq\n (\\(x, y) ->\n let r =\n sqrt $\n (fromIntegral $ x - center xLen) ^ 2 +\n (fromIntegral $ y - center yLen) ^ 2\n interpolatedArray = cubicInterpolation radialArr r\n interpolatedPinwheel =\n R.traverse3\n interpolatedArray\n (fromListUnboxed (Z :. numThetaFreq) thetaFreqs)\n (fromListUnboxed (Z :. numScaleFreq) scaleFreqs)\n (\\sh _ _ -> sh) $ \\f ft fs idx@(Z :. t :. s :. t0 :. s0) ->\n (f idx :+ 0) * (exp (0 :+ (ft (Z :. t) - ft (Z :. t0)) * pi)) *\n pinwheelFunc \n (ft (Z :. t) - ft (Z :. t0))\n (fs (Z :. s) + fs (Z :. s0))\n rMax\n 0\n (x - center xLen)\n (y - center yLen)\n (eigVal, eigVec) =\n eig . (len >< len) . R.toList $ interpolatedPinwheel\n (val, vec) =\n L.head . L.reverse . L.sortOn (realPart . fst) $\n L.zip (NL.toList eigVal) (toColumns $ eigVec)\n in VU.fromList . L.map (* val) . NL.toList $ vec) $\n [(x, y) | x <- [0 .. xLen - 1], y <- [0 .. yLen - 1]]\n", "meta": {"hexsha": "c07bc90066134812cd29ee829abf8e90d5710c74", "size": 8692, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FokkerPlanck/Pinwheel.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FokkerPlanck/Pinwheel.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/FokkerPlanck/Pinwheel.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 36.2166666667, "max_line_length": 124, "alphanum_fraction": 0.5051771744, "num_tokens": 2514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3353840689755873}} {"text": "{-# LANGUAGE RecordWildCards #-}\nmodule DFA where\n\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Control.Monad.State\nimport Data.Maybe\nimport Data.Semigroup (stimes)\nimport Numeric.LinearAlgebra hiding (remap, (<>))\nimport NFA\nimport Utils\nimport qualified Partition as P\nimport LruCache\n\n-- | The DFA type is parameterized on the state type, so that we can use\n-- Sets during the subset construction and then map them to integers for\n-- better efficiency.\ndata DFA s c = DFA\n { dfaStart :: s\n , dfaFinal :: Set.Set s\n , dfaStates :: Set.Set s\n , dfaTransitions :: Set.Set (c, s, s)\n }\n deriving Show\n\n-- | At first, the DFA states are sets of NFA states\ntype DfaState1 = Set.Set NfaState\n\n-- | Then, the sets are mapped into integers\ntype DfaState2 = Int\n\n----------------------------------------------------------------------\n-- The subset construction\n----------------------------------------------------------------------\n\n-- | Return all epsilon-edges from an NFA state\nepsilonEdges :: Ord c => NFA (Maybe c) -> NfaState -> Set.Set NfaState\nepsilonEdges NFA{nfaTransitions} s =\n fromMaybe mempty . Map.lookup Nothing . fromMaybe mempty . Map.lookup s $\n transitionMap nfaTransitions\n\n-- | Compute an epsilon-closure\nepsilonClosure :: Ord c => NFA (Maybe c) -> Set.Set NfaState -> Set.Set NfaState\nepsilonClosure nfa = go mempty\n where\n go !seen0 !new0\n | Set.null new0 = seen0\n | otherwise =\n let\n seen1 = Set.union seen0 new0\n new1 = Set.difference (sconcatMap (epsilonEdges nfa) new0) seen0\n in go seen1 new1\n\n-- | @move nfa s a@ is a set of NFA states where we can get from one of the\n-- states in @s@ after receiving @a@ as an input\nmove :: Ord c => NFA (Maybe c) -> DfaState1 -> c -> DfaState1\nmove NFA{nfaTransitions} ss c = sconcatMap\n (\\s -> fromMaybe mempty . Map.lookup (Just c) .\n fromMaybe mempty . Map.lookup s $\n transitionMap nfaTransitions)\n ss\n\n-- | Build a DFA from an NFA\nnfaToDfa :: forall c . Ord c => [c] -> NFA (Maybe c) -> DFA DfaState1 c\nnfaToDfa alphabet nfa =\n let\n start :: DfaState1\n start = epsilonClosure nfa (nfaStart nfa)\n transitions = go Set.empty (Set.singleton $ start) Set.empty\n all_states = concat [ [s1,s2] | (_, s1, s2) <- Set.toList transitions ]\n contains_final :: DfaState1 -> Bool\n contains_final dfa_st = not . Set.null $ Set.intersection (nfaFinal nfa) dfa_st\n in\n DFA\n { dfaStart = start\n , dfaFinal = Set.fromList $ filter contains_final all_states\n , dfaStates = Set.fromList all_states\n , dfaTransitions = transitions\n }\n where\n go\n :: Set.Set DfaState1\n -> Set.Set DfaState1\n -> Set.Set (c, DfaState1, DfaState1)\n -> Set.Set (c, DfaState1, DfaState1)\n go !seen0 !new0 !transitions0\n | Set.null new0 = transitions0\n | otherwise =\n let\n seen1 = Set.union seen0 new0\n -- where can we get from the DFA states in new1?\n (transitions1, new1) =\n flip foldMap new0 $ \\s ->\n flip foldMap alphabet $ \\c ->\n let\n next :: DfaState1\n next = epsilonClosure nfa (move nfa s c)\n in (Set.singleton (c, s, next), Set.singleton next)\n\n transitions2 = transitions0 `Set.union` transitions1\n new2 = new1 `Set.difference` seen1\n in go seen1 new2 transitions2\n\n----------------------------------------------------------------------\n-- DFA optimization\n----------------------------------------------------------------------\n\n-- | Map all DFA states\nmapStates\n :: (Ord s1, Ord s2, Ord c)\n => (s1 -> s2)\n -> DFA s1 c\n -> DFA s2 c\nmapStates remap DFA{..} =\n DFA\n { dfaStart = remap dfaStart\n , dfaFinal = Set.map remap dfaFinal\n , dfaStates = Set.map remap dfaStates\n , dfaTransitions = Set.map (\\(c,s0,s1) -> (c, remap s0, remap s1)) dfaTransitions\n }\n\n-- | Convert all states of the DFA to consecutive integers starting from 0\nmapStatesToInt\n :: (Ord s, Ord c)\n => DFA s c\n -> DFA DfaState2 c\nmapStatesToInt dfa =\n let\n stateMap = Map.fromList $ zip (Set.toList . dfaStates $ dfa) [0..]\n remap = (stateMap Map.!)\n in\n mapStates remap dfa\n\nminimizeDfa\n :: forall s c . (Ord c, Ord s)\n => DFA s c\n -> DFA Int c\nminimizeDfa dfa@DFA{..} = flip evalState 0 $ do\n initialPartition <- liftM2 (<>)\n (P.singleton dfaFinal)\n (P.singleton $ dfaStates `Set.difference` dfaFinal)\n\n let\n transitionMap :: Map.Map s (Map.Map c s)\n transitionMap = Map.fromListWith Map.union\n [ (s0, Map.singleton c s1)\n | (c, s0, s1) <- Set.toList dfaTransitions\n ]\n\n classify :: P.Partition s -> s -> Map.Map c Int\n classify pt s = fmap (P.lookupState pt) $ transitionMap Map.! s\n\n finalPartition <- P.subpartitionFixpoint classify initialPartition\n\n return $ mapStates (P.lookupState finalPartition) dfa\n\n----------------------------------------------------------------------\n-- Transfer matrices and probabilities\n----------------------------------------------------------------------\n\ndata TransferMatrix = TransferMatrix\n { tmMatrix :: Matrix Double\n -- ^ transfer matrix itself\n , tmStart :: Vector Double\n -- ^ the indicator vector of the start state\n , tmFinal :: Vector Double\n -- ^ the indicator vector of the final states\n }\n deriving (Show)\n\n-- | Construct the DFA transfer matrix assuming the uniform distribution\n-- over nucleotides.\n--\n-- Return the matrix and the 0-based indices of the start and end states.\ndfaTransferMatrix\n :: (Ord c, Ord s)\n => Map.Map c Double -- ^ character probabilities\n -> DFA s c\n -> TransferMatrix\ndfaTransferMatrix freqs (mapStatesToInt -> DFA{..}) =\n -- we remap the DFA once again to make sure the numbers are consecutive\n let\n n = Set.size dfaStates\n elts =\n [ ((s0, s1), freqs Map.! c)\n | (c, s0, s1) <- Set.toList dfaTransitions\n ]\n in\n TransferMatrix\n { tmMatrix = (assoc (n,n) 0 . assocSum) elts\n , tmStart = assoc n 0 [ (dfaStart, 1) ]\n , tmFinal = assoc n 0 [ (st, 1) | st <- Set.toList dfaFinal ]\n }\n where\n assocSum = Map.toList . Map.fromListWith (+)\n\ndfaProbability\n :: TransferMatrix\n -> Int -- ^ length of the random string where they motif may occur\n -> Double\ndfaProbability TransferMatrix{..} len =\n (tmStart <# stimes len tmMatrix) <.> tmFinal\n\ndfaProbabilityCached\n :: MonadLru Int (Matrix Double) m\n => TransferMatrix\n -> Int -- ^ length of the random string where they motif may occur\n -> m Double\ndfaProbabilityCached TransferMatrix{..} len = do\n pw <- lruPow len tmMatrix\n return $ (tmStart <# pw) <.> tmFinal\n", "meta": {"hexsha": "97d2bad72c59adfc76d2aeca8ab2220c2bd5bff1", "size": 6654, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/DFA.hs", "max_stars_repo_name": "feuerbach/motif-stats", "max_stars_repo_head_hexsha": "6d2fb78a6fed68f0d7ccddfd9383427e339533c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-20T11:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T14:46:48.000Z", "max_issues_repo_path": "src/DFA.hs", "max_issues_repo_name": "feuerbach/motif-stats", "max_issues_repo_head_hexsha": "6d2fb78a6fed68f0d7ccddfd9383427e339533c0", "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/DFA.hs", "max_forks_repo_name": "feuerbach/motif-stats", "max_forks_repo_head_hexsha": "6d2fb78a6fed68f0d7ccddfd9383427e339533c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3867924528, "max_line_length": 83, "alphanum_fraction": 0.6101593027, "num_tokens": 1855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3318968176070757}} {"text": "{-# LANGUAGE RecordWildCards #-}\n\nmodule HEP.Kinematics.Variable.M2\n (\n M2Solution (..)\n\n , mkInput\n\n , m2XXSQP\n , m2CXSQP\n , m2XCSQP\n , m2CCSQP\n\n , m2XXAugLag\n , m2CXAugLag\n , m2XCAugLag\n , m2CCAugLag\n ) where\n\nimport HEP.Kinematics\nimport HEP.Kinematics.Vector.LorentzVector (setXYZT)\n\nimport Numeric.LinearAlgebra (Vector, fromList, toList)\nimport Numeric.NLOPT\n\n-- import Numeric.GSL.Differentiation\n-- import Debug.Trace\n\n-- | All the components are rescaled by '_scale'.\ndata InputKinematics = InputKinematics\n { _p1 :: FourMomentum -- ^ p1 = a1 + b1\n , _p2 :: FourMomentum -- ^ p2 = a2 + b2\n , _q1 :: FourMomentum -- ^ q1 = b1\n , _q2 :: FourMomentum -- ^ q2 = b2\n , _ptmiss :: TransverseMomentum\n -- | squared mass of the invisible particle\n , _mInvSq :: !Double\n , _scale :: !Double }\n\n-- | creates the input for the process of\n--\n-- A1 + A2 --> a1 B1 + a2 B2 --> a1 b1 C1 + a2 b2 C2.\n--\nmkInput :: [FourMomentum] -- ^ [a1, a2]\n -> [FourMomentum] -- ^ [b1, b2]\n -> TransverseMomentum -- ^ pT(miss)\n -> Double -- ^ M_{invisible}\n -> Maybe InputKinematics\nmkInput as bs ptmiss mInv\n | length as /= 2 || length bs /= 2 = Nothing\n | otherwise = do\n let ps = zipWith (+) as bs\n p1 = head ps\n p2 = ps !! 1\n\n m1 = mass p1\n m2 = mass p2\n mInvSq = mInv * mInv\n scaleSq = m1 * m1 + m2 * m2 + 2 * mInvSq\n if scaleSq <= 0 -- why?\n then Nothing\n else do let scale = sqrt scaleSq\n p1' = p1 ^/ scale\n p2' = p2 ^/ scale\n q1' = head bs ^/ scale\n q2' = (bs !! 1) ^/ scale\n ptmiss' = ptmiss ^/ scale\n mInv' = mInv / scale\n return $ InputKinematics { _p1 = p1'\n , _p2 = p2'\n , _q1 = q1'\n , _q2 = q2'\n , _ptmiss = ptmiss'\n , _mInvSq = mInv' * mInv'\n , _scale = scale }\n\ndata M2Solution = M2Solution { _M2 :: Double\n , _k1sol :: FourMomentum\n , _k2sol :: FourMomentum\n } deriving Show\n\ngetM2Solution :: InputKinematics -> Either Result Solution -> Maybe M2Solution\ngetM2Solution inp@InputKinematics {..} sol =\n case sol of\n Left _ -> Nothing\n -- sol0@(Right (Solution m2 ks _)) -> do\n Right (Solution m2 ks _) -> do\n let Invisibles k1 k2 = mkInvisibles inp (vecToVars ks)\n -- traceM (\"sol = \" ++ show sol0)\n return $ M2Solution { _M2 = m2 * _scale\n , _k1sol = k1 ^* _scale\n , _k2sol = k2 ^* _scale }\n\n{-\ninitialGuess :: InputKinematics -> Vector Double\ninitialGuess InputKinematics { _ptmiss = ptmiss } =\n fromList [0.5 * px ptmiss, 0.5 * py ptmiss, 0, 0]\n-}\ninitialGuess :: InputKinematics -> Vector Double\ninitialGuess inp@InputKinematics {..} =\n let objf ks = let Invisibles k1 k2 = mkInvisibles inp (vecToVars ks)\n in invariantMass [_p1, _p2, k1, k2]\n ks0 = fromList [0.5 * px _ptmiss, 0.5 * py _ptmiss, 0, 0]\n eps' = eps * 0.1\n stop = MaximumEvaluations 1000\n :| [ ObjectiveAbsoluteTolerance eps'\n , ObjectiveRelativeTolerance eps']\n algorithm = NELDERMEAD objf [] Nothing\n problem = LocalProblem 4 stop algorithm\n sol = minimizeLocal problem ks0\n in case sol of\n Left _ -> ks0\n Right (Solution _ ksSol _) -> ksSol\n\neps :: Double\neps = 1e-3\n\nstopObjCond :: [StoppingCondition]\nstopObjCond = [ObjectiveAbsoluteTolerance eps', ObjectiveRelativeTolerance eps']\n where eps' = eps * 1e-3\n\ntype MultivarFunc = Vector Double -> (Double, Vector Double)\n\nm2SQP :: [InputKinematics -> MultivarFunc] -- ^ constraint functions\n -> Maybe InputKinematics\n -> Maybe M2Solution\nm2SQP _ Nothing = Nothing\nm2SQP cfs (Just inp@InputKinematics {..}) =\n let -- objective function with gradient\n objfD = m2ObjF inp\n\n -- constraint function with gradient\n constraints' = ($ inp) <$> cfs\n constraints = (\\cf -> EqualityConstraint (Scalar cf) eps)\n <$> constraints'\n\n stop = MaximumEvaluations 1000 :| stopObjCond\n algorithm = SLSQP objfD [] [] constraints\n problem = LocalProblem 4 stop algorithm\n\n sol = minimizeLocal problem (initialGuess inp)\n in getM2Solution inp sol\n\nm2XXSQP, m2CXSQP, m2XCSQP, m2CCSQP :: Maybe InputKinematics -> Maybe M2Solution\nm2XXSQP = m2SQP []\nm2CXSQP = m2SQP [constraintA]\nm2XCSQP = m2SQP [constraintB]\nm2CCSQP = m2SQP [constraintA, constraintB]\n\nm2AugLag :: [InputKinematics -> MultivarFunc] -- ^ constraint functions\n -> Maybe InputKinematics\n -> Maybe M2Solution\nm2AugLag _ Nothing = Nothing\nm2AugLag cfs (Just inp@InputKinematics {..}) =\n let -- objective function without gradient\n -- objf = m2ObjF inp\n objf = getResultOnly (m2ObjF inp)\n\n -- constraint function without gradient\n constraints' = ($ inp) <$> cfs\n -- constraints = (\\cf -> EqualityConstraint (Scalar cf) eps)\n -- <$> constraints'\n constraints = (\\cf -> EqualityConstraint (Scalar (getResultOnly cf))\n eps) <$> constraints'\n\n stop = MaximumEvaluations 5000 :| stopObjCond\n -- algorithm = VAR1 objf Nothing\n -- algorithm = LBFGS objf Nothing\n -- algorithm = SLSQP objf [] [] constraints\n algorithm = NELDERMEAD objf [] Nothing\n\n subproblem = LocalProblem 4 stop algorithm\n -- problem = AugLagProblem [] constraints (AUGLAG_EQ_LOCAL subproblem)\n problem = AugLagProblem constraints [] (AUGLAG_EQ_LOCAL subproblem)\n\n sol = minimizeAugLag problem (initialGuess inp)\n in getM2Solution inp sol\n where\n getResultOnly :: MultivarFunc -> Vector Double -> Double\n getResultOnly fD ks = let (result, _) = fD ks in result\n\nm2XXAugLag, m2CXAugLag, m2XCAugLag, m2CCAugLag\n :: Maybe InputKinematics -> Maybe M2Solution\nm2XXAugLag = m2AugLag []\nm2CXAugLag = m2AugLag [constraintA]\nm2XCAugLag = m2AugLag [constraintB]\nm2CCAugLag = m2AugLag [constraintA, constraintB]\n\n-- | (k1x, k1y, k1z, k2z).\ntype Variables = (Double, Double, Double, Double)\n\n-- | unsafe transformation, but it would be fine.\nvecToVars :: Vector Double -> Variables\nvecToVars ks = let [k1x, k1y, k1z, k2z] = toList ks in (k1x, k1y, k1z, k2z)\n\ndata Invisibles = Invisibles { _k1 :: FourMomentum , _k2 :: FourMomentum }\n\nmkInvisibles :: InputKinematics -> Variables -> Invisibles\nmkInvisibles InputKinematics {..} (k1x, k1y, k1z, k2z) = Invisibles k1 k2\n where\n eInv1 = sqrt (k1x * k1x + k1y * k1y + k1z * k1z + _mInvSq)\n k1 = eInv1 `seq` setXYZT k1x k1y k1z eInv1\n\n k2x = px _ptmiss - k1x\n k2y = py _ptmiss - k1y\n eInv2 = sqrt (k2x * k2x + k2y * k2y + k2z * k2z + _mInvSq)\n k2 = eInv2 `seq` setXYZT k2x k2y k2z eInv2\n\n-- | the unknowns are (k1x, k2x, k1z, k2z).\nm2ObjF :: InputKinematics -> MultivarFunc\nm2ObjF inp@InputKinematics {..} ks =\n if m1 < m2 then (m2, grad2) else (m1, grad1)\n where\n invs = mkInvisibles inp (vecToVars ks)\n (grad1, grad2, m1, m2) = m2Grad inp invs _p1 _p2 ks\n\nm2Grad :: InputKinematics\n -> Invisibles\n -> FourMomentum -- ^ p1 (or q1)\n -> FourMomentum -- ^ p2 (or q2)\n -> Vector Double\n -> (Vector Double, Vector Double, Double, Double)\nm2Grad InputKinematics {..} (Invisibles k1 k2) p1 p2 ks = (d1, d2, m1, m2)\n where\n (k1x, k1y, k1z, k2z) = vecToVars ks\n\n (e1, p1x, p1y, p1z) = epxpypz p1\n m1 = invariantMass [p1, k1]\n m1' = safeDivisor m1\n r1 = e1 / safeDivisor (energy k1)\n d1 = fromList $ ( / m1') <$> [ r1 * k1x - p1x\n , r1 * k1y - p1y\n , r1 * k1z - p1z\n , 0 ]\n\n (e2, p2x, p2y, p2z) = epxpypz p2\n m2 = invariantMass [p2, k2]\n m2' = safeDivisor m2\n r2 = e2 / safeDivisor (energy k2)\n d2 = fromList $ ( / m2') <$> [ r2 * (k1x - px _ptmiss) + p2x\n , r2 * (k1y - py _ptmiss) + p2y\n , 0\n , r2 * k2z - p2z ]\n\nconstraintF :: FourMomentum -> FourMomentum -> InputKinematics -> MultivarFunc\nconstraintF p1 p2 inp ks = (m1 - m2, grad1 - grad2)\n where\n invs = mkInvisibles inp (vecToVars ks)\n (grad1, grad2, m1, m2) = m2Grad inp invs p1 p2 ks\n\nconstraintA, constraintB :: InputKinematics -> MultivarFunc\nconstraintA inp@InputKinematics {..} = constraintF _p1 _p2 inp\nconstraintB inp@InputKinematics {..} = constraintF _q1 _q2 inp\n\nsafeDivisor :: Double -> Double\nsafeDivisor x | x >= 0 = max eps0 x\n | otherwise = min (-eps0) x\n where eps0 = 1.0e-8\n\n{-\nm2ObjF :: InputKinematics -> MultivarFunc\nm2ObjF inp ks = (m, d)\n where\n ks0 = vecToVars ks\n m = fst $ m2ObjF' inp ks0\n d = m2ObjFDNumeric inp ks0\n\nm2ObjF' :: InputKinematics -> Variables -> (Double, Vector Double)\nm2ObjF' inp@InputKinematics {..} ks =\n if m1 < m2 then (m2, grad2) else (m1, grad1)\n where\n invs@(Invisibles k1 k2) = mkInvisibles inp ks\n m1 = invariantMass [_p1, k1]\n m2 = invariantMass [_p2, k2]\n (k1x, k1y, k1z, k2z) = ks\n (grad1, grad2, _) = m2Grad inp invs _p1 _p2 (fromList [k1x, k1y, k1z, k2z])\n\nm2ObjFDNumeric :: InputKinematics -> Variables -> Vector Double\nm2ObjFDNumeric inp@InputKinematics {..} = fDNumeric f\n where f ks = fst (m2ObjF' inp ks)\n\nm2GradNumeric :: InputKinematics\n -> Invisibles\n -> FourMomentum -- ^ p1 (or q1)\n -> FourMomentum -- ^ p2 (or q2)\n -> Vector Double\n -> (Vector Double, Vector Double, Double)\nm2GradNumeric inp@(InputKinematics {..}) _ p1 p2 ks = (d1, d2, m1 - m2)\n where\n ks0 = vecToVars ks\n\n m1F ks' = let Invisibles k1 _ = mkInvisibles inp ks'\n in invariantMass [p1, k1]\n m1 = m1F ks0\n d1 = fDNumeric m1F ks0\n\n m2F ks' = let Invisibles _ k2 = mkInvisibles inp ks'\n in invariantMass [p2, k2]\n m2 = m2F ks0\n d2 = fDNumeric m2F ks0\n\nfDNumeric :: (Variables -> Double) -> Variables -> Vector Double\nfDNumeric f (k1x, k1y, k1z, k2z) = fromList [fk1xD, fk1yD, fk1zD, fk2zD]\n where\n fk1x a = f (a, k1y, k1z, k2z)\n fk1y a = f (k1x, a, k1z, k2z)\n fk1z a = f (k1x, k1y, a, k2z)\n fk2z a = f (k1x, k1y, k1z, a)\n\n epsN = 1e-8\n\n fk1xD = fst $ derivCentral epsN fk1x k1x\n fk1yD = fst $ derivCentral epsN fk1y k1y\n fk1zD = fst $ derivCentral epsN fk1z k1z\n fk2zD = fst $ derivCentral epsN fk2z k2z\n-}\n", "meta": {"hexsha": "3ac7bc0139b052fafd28bc3f5d8a940793bfed25", "size": 11388, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HEP/Kinematics/Variable/M2.hs", "max_stars_repo_name": "cbpark/hyam2", "max_stars_repo_head_hexsha": "07fc829ebc5703ad042268a2ea160777bb00eae9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HEP/Kinematics/Variable/M2.hs", "max_issues_repo_name": "cbpark/hyam2", "max_issues_repo_head_hexsha": "07fc829ebc5703ad042268a2ea160777bb00eae9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HEP/Kinematics/Variable/M2.hs", "max_forks_repo_name": "cbpark/hyam2", "max_forks_repo_head_hexsha": "07fc829ebc5703ad042268a2ea160777bb00eae9", "max_forks_repo_licenses": ["BSD-3-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.9242902208, "max_line_length": 80, "alphanum_fraction": 0.5524236038, "num_tokens": 3670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.33137971470293753}} {"text": "-- | https://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours/Parsing\n\nmodule Main where\n\nimport Control.Monad\nimport Data.Char (digitToInt, isDigit)\nimport Data.Complex\nimport Data.Ratio (denominator, numerator, (%))\nimport Numeric (readDec, readFloat, readHex,\n readInt, readOct)\nimport System.Environment\nimport Text.ParserCombinators.Parsec hiding (spaces)\n\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+-/:<=>?@^_~\" \"a symbol\"\n\n-- readExpr :: String -> Either ParseError LispVal\n-- readExpr = parse parseExpr \"lisp\"\n\n-- Whitespace\nspaces :: Parser ()\nspaces = skipMany1 space\n\n-- Return Values\ndata LispVal = Atom String\n | List [LispVal]\n | DottedList [LispVal] LispVal\n | Number Integer\n | Float Double\n | Ratio Rational\n | Complex (Complex Double)\n | Character Char\n | String String\n | Bool Bool\n\nparseString :: Parser LispVal\nparseString = do\n char '\"'\n str <- many (parseHelper <|> noneOf \"\\\\\\\"\")\n char '\"'\n return $ String str\n \"a string for parseString\"\n where parseHelper :: Parser Char\n parseHelper = do\n char '\\\\'\n x <- oneOf \"\\\\\\\"nrt\"\n return $ case x of\n '\\\\' -> x\n '\"' -> x\n 'n' -> '\\n'\n 'r' -> '\\r'\n 't' -> '\\t'\n\nparseAtom :: Parser LispVal\nparseAtom = do\n first <- letter <|> symbol\n rest <- many $ letter <|> symbol <|> digit\n return $ Atom (first : rest)\n \"a atom for parseAtom\"\n\nparseBool :: Parser LispVal\nparseBool = do\n x <- try (string \"#t\") <|> string \"#f\"\n return $ if x == \"#t\"\n then Bool True\n else Bool False\n\nparseNumber :: Parser LispVal\nparseNumber = parseDigit <|> try parseOct <|> try parseDec <|> try parseHex <|> parseBin\n where parseOct = do\n char '#' >> oneOf \"oO\"\n str <- many1 octDigit\n let [(n, _)] = readOct str\n return $ Number n\n parseDec = do\n char '#' >> oneOf \"dD\"\n str <- many1 digit\n let [(n, _)] = readDec str\n return $ Number n\n parseHex = do\n char '#' >> oneOf \"xX\"\n str <- many1 hexDigit\n let [(n, _)] = readHex str\n return $ Number n\n parseBin = do\n char '#' >> oneOf \"bB\"\n str <- many1 $ oneOf \"01\"\n let [(n, _)] = readInt 2 (`elem` \"01\") digitToInt str\n return $ Number n\n parseDigit = do\n str <- many1 digit\n return $ (Number . read) str\n\nparseChar :: Parser LispVal\nparseChar = do\n string \"#\\\\\"\n x <- many $ letter <|> digit\n return $ case length x of\n 0 -> Character '\\n'\n 1 -> Character $ head x\n _ -> case x of\n \"newline\" -> Character '\\n'\n \"tab\" -> Character '\\t'\n \"space\" -> Character ' '\n\nparseFloat :: Parser LispVal\nparseFloat = do\n x <- many1 digit\n char '.'\n y <- many1 digit\n return $ let [(n, _)] = readFloat (x ++ '.' : y) in Float n\n\nparseRatio :: Parser LispVal\nparseRatio = do\n x <- many1 digit\n char '/'\n y <- many1 digit\n return $ Ratio (read x % read y)\n\nparseComplex :: Parser LispVal\nparseComplex = do\n x <- try parseFloat <|> parseNumber\n char '+'\n y <- try parseFloat <|> parseNumber\n char 'i'\n return $ Complex (toDouble x :+ toDouble y)\n where toDouble :: LispVal -> Double\n toDouble (Float f) = f\n toDouble (Number n) = fromIntegral n\n\n-- Recursive Parsers: Adding lists, dotted lists, and quoted datums\n\nparseList :: Parser LispVal\nparseList = do\n char '('\n x <- sepBy parseExpr spaces\n char ')'\n return $ List x\n\nparseDottedList :: Parser LispVal\nparseDottedList = do\n char '('\n x <- endBy parseExpr spaces\n y <- char '.' >> spaces >> parseExpr\n char ')'\n return $ DottedList x y\n\nparseQuoted :: Parser LispVal\nparseQuoted = do\n char '\\''\n x <- parseExpr\n return $ List [Atom \"quote\", x]\n\nparseBackquote :: Parser LispVal\nparseBackquote = do\n char '`'\n x <- parseExpr\n return $ List [Atom \"quasiquote\", x]\n\nparseUnquote :: Parser LispVal\nparseUnquote = do\n char ','\n y <- parseExpr\n return $ List [Atom \"unquote\", y]\n\nparseUnquoteSplicing :: Parser LispVal\nparseUnquoteSplicing = do\n char ',' >> char '@'\n y <- parseExpr\n return $ List [Atom \"unquote-splicing\", y]\n\nparseExpr :: Parser LispVal\nparseExpr = parseAtom\n <|> try parseBool\n <|> try parseRatio\n <|> try parseComplex\n <|> try parseFloat\n <|> try parseNumber\n <|> parseChar\n <|> parseString\n <|> try parseList\n <|> parseDottedList\n <|> parseQuoted\n <|> parseBackquote\n <|> try parseUnquoteSplicing\n <|> parseUnquote\n\n\n-- Beginning the Evaluator\nshowVal :: LispVal -> String\nshowVal (Atom x) = x\nshowVal (Bool True) = \"#t\"\nshowVal (Bool False) = \"#f\"\nshowVal (Ratio x) = show (numerator x) ++ ('/' : show (denominator x))\nshowVal (Complex x) = show (realPart x) ++ ('+' : show (imagPart x) ++ \"i\")\nshowVal (Float x) = show x\nshowVal (Number x) = show x\nshowVal (Character x) = \"#\\\\\" ++ show x\nshowVal (String x) = \"\\\"\" ++ x ++ \"\\\"\"\nshowVal (List x) = \"(\" ++ unwordsList x ++ \")\"\nshowVal (DottedList first rest)= \"(\" ++ unwordsList first ++ \" . \" ++ showVal rest ++ \")\"\n\nunwordsList :: [LispVal] -> String\nunwordsList = unwords . map showVal\n\ninstance Show LispVal where\n show = showVal\n\nreadExpr :: String -> LispVal\nreadExpr input = case parse parseExpr \"lisp\" input of\n Left err -> String $ \"No match: \" ++ show err\n Right val -> val\n\n-- Beginnings of an evaluator: Primitives\nmain :: IO ()\nmain = getArgs >>= print . eval . readExpr . head\n\neval :: LispVal -> LispVal\neval val@(String _) = val\neval val@(Bool _) = val\neval val@(Ratio _) = val\neval val@(Complex _) = val\neval val@(Float _) = val\neval val@(Number _) = val\neval val@(Character _) = val\neval (List [Atom \"quote\", val]) = val\n\n-- Adding basic primitives\neval (List (Atom func : args)) = apply func $ map eval args\n\napply :: String -> [LispVal] -> LispVal\napply func args = maybe (Bool False) ($ args) $ lookup func primitives\n\nprimitives :: [(String, [LispVal] -> LispVal)]\nprimitives = [(\"+\", numericBinop (+)),\n (\"-\", numericBinop (-)),\n (\"*\", numericBinop (*)),\n (\"/\", numericBinop div),\n (\"mod\", numericBinop mod),\n (\"quotient\", numericBinop quot),\n (\"remainder\", numericBinop rem),\n (\"symbol?\", unaryOp symbolp),\n (\"string?\", unaryOp stringp),\n (\"number?\", unaryOp numberp),\n (\"bool?\", unaryOp boolp),\n (\"list?\", unaryOp listp),\n (\"pair?\", unaryOp pairp)]\n\nnumericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> LispVal\nnumericBinop op args = Number $ foldl1 op $ map unpackNum args\n where unpackNum :: LispVal -> Integer\n unpackNum (Number n) = n\n unpackNum (String n) = let parsed = readDec n in\n if null parsed\n then 0\n else fst $ head parsed\n unpackNum (List [n]) = unpackNum n\n unpackNum _ = 0\n\nunaryOp :: (LispVal -> LispVal) -> [LispVal] -> LispVal\nunaryOp op [x] = op x\n\nsymbolp :: LispVal -> LispVal\nsymbolp (Atom _) = Bool True\nsymbolp _ = Bool False\n\nstringp :: LispVal -> LispVal\nstringp (String _) = Bool True\nstringp _ = Bool False\n\nnumberp :: LispVal -> LispVal\nnumberp (Number _) = Bool True\nnumberp _ = Bool False\n\nboolp :: LispVal -> LispVal\nboolp (Bool _) = Bool True\nboolp _ = Bool False\n\nlistp :: LispVal -> LispVal\nlistp (List _) = Bool True\nlistp _ = Bool False\n\npairp :: LispVal -> LispVal\npairp (List _) = Bool True\npairp (DottedList _ _) = Bool True\npairp _ = Bool False\n", "meta": {"hexsha": "5b9a3cde3f511bf511e0dcaca07aa32bba8a088b", "size": 7885, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "WriteYourselfAScheme/sec3-evaluation/exercises/ex1.hs", "max_stars_repo_name": "zeqing-guo/Haskell-Exercises", "max_stars_repo_head_hexsha": "54f84d2f3ab98469d2e670170f679c0bf51e9774", "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": "WriteYourselfAScheme/sec3-evaluation/exercises/ex1.hs", "max_issues_repo_name": "zeqing-guo/Haskell-Exercises", "max_issues_repo_head_hexsha": "54f84d2f3ab98469d2e670170f679c0bf51e9774", "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": "WriteYourselfAScheme/sec3-evaluation/exercises/ex1.hs", "max_forks_repo_name": "zeqing-guo/Haskell-Exercises", "max_forks_repo_head_hexsha": "54f84d2f3ab98469d2e670170f679c0bf51e9774", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4738675958, "max_line_length": 89, "alphanum_fraction": 0.5682942295, "num_tokens": 2183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3312966214110021}} {"text": "{-# LANGUAGE BangPatterns #-}\nmodule Polestar.Eval\n (termShift\n ,termTypeSubst\n ,termSubstD\n ,termSubst\n ,ValueBinding(..)\n ,getValueFromContext\n ,eval1\n ,eval\n ) where\nimport Polestar.Type\nimport Polestar.TypeCheck\nimport Data.Complex\nimport GHC.Float (expm1, log1p)\n\ntermSubstD :: Int -> Term -> Int -> Term -> Term\ntermSubstD !depth s !i t = case t of\n TmAbs name ty body -> TmAbs name (typeShift (-1) i ty) (termSubstD depth s (i + 1) body)\n TmTyAbs name bound body -> TmTyAbs name (typeShift (-1) i <$> bound) (termSubstD depth s (i + 1) body)\n TmRef j | j == i -> termShift depth 0 s\n | j > i -> TmRef (j - 1)\n | otherwise -> t\n TmApp u v -> TmApp (termSubstD depth s i u) (termSubstD depth s i v)\n TmTyApp u t -> TmTyApp (termSubstD depth s i u) (typeShift (-1) i t)\n TmLet name def body -> TmLet name (termSubstD depth s i def) (termSubstD depth s (i + 1) body) -- ?\n TmIf cond then_ else_ -> TmIf (termSubstD depth s i cond) (termSubstD depth s i then_) (termSubstD depth s i else_)\n TmPrim _ -> t\n TmCoerce x ty -> TmCoerce (termSubstD depth s i x) (typeShift (-1) i ty)\n TmAlt name tys body -> TmAlt name (map (typeShift (-1) i) tys) (termSubstD depth s (i + 1) body)\n TmTuple components -> TmTuple $ termSubstD depth s i <$> components\n TmProj tuple j -> TmProj (termSubstD depth s i tuple) j\n TmCoherentTuple components -> TmCoherentTuple $ termSubstD depth s i <$> components\n\n-- replaces occurrences of TRef j (j > i) with TRef (j-1), and TRef i with the given term\ntermSubst = termSubstD 0\n\nnatFromValue :: Term -> Either String Integer\nnatFromValue (TmPrim (PVZero)) = return 0\nnatFromValue (TmPrim (PVInt x)) | x >= 0 = return x\nnatFromValue _ = Left \"type error (expected a natural number)\"\n\nintFromValue :: Term -> Either String Integer\nintFromValue (TmPrim (PVZero)) = return 0\nintFromValue (TmPrim (PVInt x)) = return x\nintFromValue _ = Left \"type error (expected an integer)\"\n\nnnrealFromValue :: Term -> Either String Double\nnnrealFromValue (TmPrim (PVZero)) = return 0\nnnrealFromValue (TmPrim (PVInt x)) | x >= 0 = return (fromIntegral x)\nnnrealFromValue (TmPrim (PVReal x)) | x >= 0 = return x\nnnrealFromValue _ = Left \"type error (expected a non-negative real number)\"\n\nrealFromValue :: Term -> Either String Double\nrealFromValue (TmPrim (PVZero)) = return 0\nrealFromValue (TmPrim (PVInt x)) = return (fromIntegral x)\nrealFromValue (TmPrim (PVReal x)) = return x\nrealFromValue _ = Left \"type error (expected a real number)\"\n\nimaginaryFromValue :: Term -> Either String Double\nimaginaryFromValue (TmPrim (PVZero)) = return 0\nimaginaryFromValue (TmPrim (PVImaginary x)) = return x\nimaginaryFromValue _ = Left \"type error (expected an imaginary number)\"\n\ncomplexFromValue :: Term -> Either String (Complex Double)\ncomplexFromValue (TmPrim (PVZero)) = return 0\ncomplexFromValue (TmPrim (PVInt x)) = return (fromIntegral x)\ncomplexFromValue (TmPrim (PVReal x)) = return (x:+0)\ncomplexFromValue (TmPrim (PVImaginary x)) = return (0:+x)\ncomplexFromValue (TmPrim (PVComplex z)) = return z\ncomplexFromValue _ = Left \"type error (expected a complex number)\"\n\nboolFromValue :: Term -> Either String Bool\nboolFromValue (TmPrim (PVBool x)) = return x\nboolFromValue _ = Left \"type error (expected a boolean)\"\n\napplyBuiltinUnary :: Builtin -> Term -> Either String Term\napplyBuiltinUnary f v = case f of\n BNegate -> case v of\n TmPrim PVZero -> return v\n TmPrim (PVInt x) -> return (TmPrim $ PVInt $ negate x)\n TmPrim (PVReal x) -> return (TmPrim $ PVReal $ negate x)\n TmPrim (PVImaginary x) -> return (TmPrim $ PVImaginary $ negate x)\n TmPrim (PVComplex x) -> return (TmPrim $ PVComplex $ negate x)\n _ -> Left \"type error (expected an integer or a real number)\"\n BLogicalNot -> (TmPrim . PVBool . not) <$> boolFromValue v\n BNatToInt -> (TmPrim . PVInt) <$> natFromValue v\n BNatToNNReal -> (TmPrim . PVReal . fromIntegral) <$> natFromValue v\n BIntToNat -> (\\x -> if x >= 0 then TmPrim (PVInt x) else TmPrim PVZero) <$> intFromValue v\n BIntToReal -> (TmPrim . PVReal . fromIntegral) <$> intFromValue v\n BNNRealToReal -> (TmPrim . PVReal) <$> realFromValue v\n BRealToComplex -> (TmPrim . PVComplex . (:+0)) <$> realFromValue v\n BMkImaginary -> (TmPrim . PVImaginary) <$> realFromValue v\n BImaginaryToComplex -> (TmPrim . PVComplex . (0:+)) <$> imaginaryFromValue v\n BRealPart -> case v of\n TmPrim PVZero -> return v\n TmPrim (PVInt _) -> return v\n TmPrim (PVReal _) -> return v\n TmPrim (PVImaginary _) -> return $ TmPrim PVZero\n TmPrim (PVComplex z) -> return $ TmPrim (PVReal (realPart z))\n _ -> Left \"type error (expected a complex number)\"\n BImagPart -> case v of\n TmPrim PVZero -> return $ TmPrim PVZero\n TmPrim (PVInt _) -> return $ TmPrim PVZero\n TmPrim (PVReal _) -> return $ TmPrim PVZero\n TmPrim (PVImaginary x) -> return $ TmPrim (PVReal x)\n TmPrim (PVComplex z) -> return $ TmPrim (PVReal (imagPart z))\n _ -> Left \"type error (expected a complex number)\"\n BAbs -> case v of\n TmPrim PVZero -> return $ TmPrim PVZero\n TmPrim (PVInt x) -> return $ TmPrim (PVInt (abs x))\n TmPrim (PVReal x) -> return $ TmPrim (PVReal (abs x))\n TmPrim (PVImaginary x) -> return $ TmPrim (PVReal (abs x))\n TmPrim (PVComplex z) -> return $ TmPrim (PVReal (magnitude z))\n _ -> Left \"type error (expected a complex number)\"\n BSqrt -> case v of\n TmPrim PVZero -> return $ TmPrim PVZero\n TmPrim (PVInt x) | x >= 0 -> return $ TmPrim (PVReal (sqrt $ fromIntegral x))\n TmPrim (PVReal x) | x >= 0 -> return $ TmPrim (PVReal (sqrt x))\n TmPrim (PVImaginary x) -> return $ TmPrim (PVComplex (sqrt (0:+x)))\n TmPrim (PVComplex z) -> return $ TmPrim (PVComplex (sqrt z))\n _ -> Left \"type error (expected a complex number)\"\n BExp -> makeOverloadedFn [(TmPrim . PVReal . exp) <$> realFromValue v\n ,(TmPrim . PVComplex . exp) <$> complexFromValue v\n ]\n BExpm1 -> makeOverloadedFn [(TmPrim . PVReal . expm1) <$> realFromValue v\n ,(TmPrim . PVComplex . expm1) <$> complexFromValue v\n ]\n BLog -> makeOverloadedFn [(TmPrim . PVReal . log) <$> nnrealFromValue v\n ,(TmPrim . PVComplex . log) <$> complexFromValue v\n ]\n BLog1p -> makeOverloadedFn [(TmPrim . PVReal . log1p) <$> nnrealFromValue v\n ,(TmPrim . PVComplex . log1p) <$> complexFromValue v\n ]\n BSin -> makeOverloadedFn [(TmPrim . PVReal . sin) <$> realFromValue v\n ,(TmPrim . PVImaginary . sinh) <$> imaginaryFromValue v\n ,(TmPrim . PVComplex . sin) <$> complexFromValue v\n ]\n BCos -> makeOverloadedFn [(TmPrim . PVReal . cos) <$> realFromValue v\n ,(TmPrim . PVReal . cosh) <$> imaginaryFromValue v\n ,(TmPrim . PVComplex . cos) <$> complexFromValue v\n ]\n BTan -> makeOverloadedFn [(TmPrim . PVReal . tan) <$> realFromValue v\n ,(TmPrim . PVComplex . tan) <$> complexFromValue v\n ]\n BSinh -> makeOverloadedFn [(TmPrim . PVReal . sinh) <$> realFromValue v\n ,(TmPrim . PVImaginary . sin) <$> imaginaryFromValue v\n ,(TmPrim . PVComplex . sinh) <$> complexFromValue v\n ]\n BCosh -> makeOverloadedFn [(TmPrim . PVReal . cosh) <$> realFromValue v\n ,(TmPrim . PVReal . cos) <$> imaginaryFromValue v\n ,(TmPrim . PVComplex . cosh) <$> complexFromValue v\n ]\n BTanh -> makeOverloadedFn [(TmPrim . PVReal . tan) <$> realFromValue v\n ,(TmPrim . PVImaginary . tanh) <$> imaginaryFromValue v\n ,(TmPrim . PVComplex . tan) <$> complexFromValue v\n ]\n BAsin -> makeOverloadedFn [(TmPrim . PVImaginary . asinh) <$> imaginaryFromValue v\n ,(TmPrim . PVComplex . asin) <$> complexFromValue v\n ]\n BAcos -> makeOverloadedFn [(TmPrim . PVComplex . acos) <$> complexFromValue v\n ]\n BAtan -> makeOverloadedFn [(TmPrim . PVReal . atan) <$> realFromValue v\n ,(TmPrim . PVComplex . atan) <$> complexFromValue v\n ]\n BAsinh -> makeOverloadedFn [(TmPrim . PVReal . asinh) <$> realFromValue v\n ,(TmPrim . PVComplex . asinh) <$> complexFromValue v\n ]\n BAcosh -> makeOverloadedFn [(TmPrim . PVReal . acosh) <$> realFromValue v\n ]\n BAtanh -> makeOverloadedFn [(TmPrim . PVImaginary . atan) <$> imaginaryFromValue v\n ,(TmPrim . PVComplex . atanh) <$> complexFromValue v\n ]\n _ -> Left \"applyBuiltinUnary: not unary\"\n\nmakeOverloadedFn :: [Either String Term] -> Either String Term\nmakeOverloadedFn [] = Left \"no overload\"\nmakeOverloadedFn [x] = x\nmakeOverloadedFn (Left _ : xs) = makeOverloadedFn xs\nmakeOverloadedFn (Right x : xs) = Right x\n\nisZero :: Term -> Bool\nisZero (TmPrim PVZero) = True\nisZero _ = False\n\nisNonNegative :: Term -> Bool\nisNonNegative (TmPrim PVZero) = True\nisNonNegative (TmPrim (PVInt x)) = x >= 0\nisNonNegative (TmPrim (PVReal x)) = x >= 0\nisNonNegative _ = False\n\napplyBuiltinBinary :: Builtin -> Term -> Term -> Either String Term\napplyBuiltinBinary f u v = case f of\n BAdd -> makeOverloadedFn [if isZero u && isZero v then return (TmPrim PVZero) else Left \"not zero\"\n ,(TmPrim . PVInt) <$> ((+) <$> intFromValue u <*> intFromValue v)\n ,(TmPrim . PVReal) <$> ((+) <$> realFromValue u <*> realFromValue v)\n ,(TmPrim . PVImaginary) <$> ((+) <$> imaginaryFromValue u <*> imaginaryFromValue v)\n ,(TmPrim . PVComplex) <$> ((+) <$> complexFromValue u <*> complexFromValue v)\n ]\n BSub -> makeOverloadedFn [if isZero u && isZero v then return (TmPrim PVZero) else Left \"not zero\"\n ,(TmPrim . PVInt) <$> ((-) <$> intFromValue u <*> intFromValue v)\n ,(TmPrim . PVReal) <$> ((-) <$> realFromValue u <*> realFromValue v)\n ,(TmPrim . PVImaginary) <$> ((-) <$> imaginaryFromValue u <*> imaginaryFromValue v)\n ,(TmPrim . PVComplex) <$> ((-) <$> complexFromValue u <*> complexFromValue v)\n ]\n BMul -> makeOverloadedFn [if isZero u || isZero v then return (TmPrim PVZero) else Left \"not zero\"\n ,(TmPrim . PVInt) <$> ((*) <$> intFromValue u <*> intFromValue v)\n ,(TmPrim . PVReal) <$> ((*) <$> realFromValue u <*> realFromValue v)\n ,(TmPrim . PVImaginary) <$> ((*) <$> realFromValue u <*> imaginaryFromValue v)\n ,(TmPrim . PVImaginary) <$> ((*) <$> imaginaryFromValue u <*> realFromValue v)\n ,(TmPrim . PVReal . negate) <$> ((*) <$> imaginaryFromValue u <*> imaginaryFromValue v)\n ,(TmPrim . PVComplex) <$> ((*) <$> complexFromValue u <*> complexFromValue v)\n ]\n BDiv -> makeOverloadedFn [(TmPrim . PVReal) <$> ((/) <$> realFromValue u <*> realFromValue v)\n ,(TmPrim . PVImaginary) <$> ((/) <$> imaginaryFromValue u <*> realFromValue v)\n ,(TmPrim . PVImaginary . negate) <$> ((/) <$> realFromValue u <*> imaginaryFromValue v)\n ,(TmPrim . PVReal) <$> ((/) <$> imaginaryFromValue u <*> imaginaryFromValue v)\n ,(TmPrim . PVComplex) <$> ((/) <$> complexFromValue u <*> complexFromValue v)\n ]\n BPow -> makeOverloadedFn [if isZero v then return (TmPrim (PVInt 1)) else Left \"not zero\"\n ,(TmPrim . PVInt) <$> ((^) <$> intFromValue u <*> natFromValue v)\n ,(TmPrim . PVReal) <$> ((**) <$> nnrealFromValue u <*> realFromValue v)\n ,(TmPrim . PVReal) <$> ((^^) <$> realFromValue u <*> intFromValue v)\n ,(TmPrim . PVComplex) <$> ((**) <$> complexFromValue u <*> complexFromValue v)\n ]\n BTSubNat -> do u' <- natFromValue u\n v' <- natFromValue v\n let w | u' >= v' = u' - v'\n | otherwise = 0\n return (TmPrim (PVInt w))\n BLt -> (TmPrim . PVBool) <$> ((<) <$> realFromValue u <*> realFromValue v)\n BLe -> (TmPrim . PVBool) <$> ((<=) <$> realFromValue u <*> realFromValue v)\n BEqual -> (TmPrim . PVBool) <$> ((==) <$> complexFromValue u <*> complexFromValue v)\n BMax -> makeOverloadedFn [(TmPrim . PVInt) <$> (max <$> intFromValue u <*> intFromValue v)\n ,(TmPrim . PVReal) <$> (max <$> realFromValue u <*> realFromValue v)\n ]\n BMin -> makeOverloadedFn [if (isZero u && isNonNegative v) || (isZero v && isNonNegative u) then return (TmPrim PVZero) else Left \"not zero\"\n ,(TmPrim . PVInt) <$> (min <$> intFromValue u <*> intFromValue v)\n ,(TmPrim . PVReal) <$> (min <$> realFromValue u <*> realFromValue v)\n ]\n BIntDiv -> (TmPrim . PVInt) <$> (div <$> intFromValue u <*> intFromValue v)\n BIntMod -> (TmPrim . PVInt) <$> (mod <$> intFromValue u <*> intFromValue v)\n BGcd -> (TmPrim . PVInt) <$> (gcd <$> intFromValue u <*> intFromValue v)\n BLcm -> (TmPrim . PVInt) <$> (lcm <$> intFromValue u <*> intFromValue v)\n BLogicalAnd -> (TmPrim . PVBool) <$> ((&&) <$> boolFromValue u <*> boolFromValue v)\n BLogicalOr -> (TmPrim . PVBool) <$> ((||) <$> boolFromValue u <*> boolFromValue v)\n _ -> Left \"not implemented yet; sorry\"\n\ndata ValueBinding = ValueBind !Term\n | TypeBind\n deriving (Eq,Show)\n\ngetValueFromContext :: [ValueBinding] -> Int -> Term\ngetValueFromContext ctx i\n | i < length ctx = case ctx !! i of\n ValueBind x -> x\n b -> error (\"TRef: expected a variable binding, found \" ++ show b)\n | otherwise = error \"TRef: index out of bounds\"\n\neval1 :: [ValueBinding] -> Term -> Either String Term\neval1 ctx t = case t of\n TmPrim _ -> return t\n TmAbs _ _ _ -> return t\n TmTyAbs _ _ _ -> return t\n TmRef i -> return $ getValueFromContext ctx i\n TmApp u v\n | isValue u && isValue v -> case u of\n TmAbs _name _ty body -> return $ termSubst v 0 body -- no type checking here\n TmPrim (PVBuiltin f) | isUnary f -> applyBuiltinUnary f v\n TmPrim (PVBuiltin _) -> return t -- partial application\n TmApp (TmPrim (PVBuiltin f)) u' | isBinary f -> applyBuiltinBinary f u' v\n TmApp (TmApp (TmTyApp (TmPrim (PVBuiltin BIterate)) ty) n) z -> do\n n' <- natFromValue n\n if n' == 0\n then return $ z\n else return $ TmApp (TmApp (TmApp (TmTyApp (TmPrim (PVBuiltin BIterate)) ty) (TmPrim (PVInt (n' - 1)))) (TmApp v z)) v\n _ -> Left \"invalid function application (expected function type)\"\n | isValue u -> TmApp u <$> (eval1 ctx v)\n | otherwise -> TmApp <$> (eval1 ctx u) <*> pure v\n TmTyApp u ty\n | isValue u -> case u of\n TmTyAbs _name _bound body -> return $ termTypeSubst ty 0 body\n _ -> Left \"invalid type application (expected forall type)\"\n | otherwise -> TmTyApp <$> eval1 ctx u <*> pure ty\n TmLet name def body\n | isValue def -> return $ termSubst def 0 body\n | otherwise -> TmLet name <$> eval1 ctx def <*> pure body\n TmIf cond then_ else_\n | isValue cond -> case cond of\n TmPrim (PVBool True) -> return then_ -- no type checking here\n TmPrim (PVBool False) -> return else_ -- no type checking here\n _ -> Left \"if-then-else: condition must be boolean\"\n | otherwise -> TmIf <$> (eval1 ctx cond) <*> pure then_ <*> pure else_\n TmCoerce x ty\n | isValue x -> return x\n | otherwise -> TmCoerce <$> eval1 ctx x <*> pure ty\n TmAlt name tys x\n | isValue x -> return $ termTypeSubst TyUnit 0 x -- dummy type\n | otherwise -> TmAlt name tys <$> eval1 ctx x\n TmTuple components -> case span isValue components of\n (_,[]) -> return t\n (v,w:ws) -> eval1 ctx w >>= \\w' -> return (TmTuple (v ++ (w':ws)))\n TmProj tuple j\n | isValue tuple -> case tuple of\n TmTuple components | length components > j -> return $ components !! j\n | otherwise -> Left \"tuple too short\"\n _ -> Left \"projection: not a tuple\"\n | otherwise -> TmProj <$> eval1 ctx tuple <*> pure j\n TmCoherentTuple components -> Left \"coherenet tuple: not supported yet\"\n\neval :: [ValueBinding] -> Term -> Either String Term\neval ctx t | isValue t = return t\n | otherwise = eval1 ctx t >>= eval ctx\n", "meta": {"hexsha": "aec78765ea8928ad203c6734fadb5d4f78c04374", "size": 17036, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Polestar/Eval.hs", "max_stars_repo_name": "minoki/polestar", "max_stars_repo_head_hexsha": "df73b793c65b1f6e7bc618b3175d6661a6722240", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Polestar/Eval.hs", "max_issues_repo_name": "minoki/polestar", "max_issues_repo_head_hexsha": "df73b793c65b1f6e7bc618b3175d6661a6722240", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Polestar/Eval.hs", "max_forks_repo_name": "minoki/polestar", "max_forks_repo_head_hexsha": "df73b793c65b1f6e7bc618b3175d6661a6722240", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.2547770701, "max_line_length": 142, "alphanum_fraction": 0.5809462315, "num_tokens": 4945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3309614379249971}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Data.Elem.LAPACK.C\n-- Copyright : Copyright (c) , Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Low-level interface to LAPACK.\n--\n\nmodule Data.Elem.LAPACK.C\n where\n\nimport Control.Exception( assert )\nimport Control.Monad\nimport Data.Complex( Complex )\nimport Data.Elem.BLAS.Level3\nimport Data.Matrix.Class( TransEnum(..), SideEnum(..) )\nimport Foreign\nimport LAPACK.CTypes\n\nimport Data.Elem.LAPACK.Double\nimport Data.Elem.LAPACK.Zomplex\n\n-- | The LAPACK typeclass.\nclass (BLAS3 e) => LAPACK e where\n geqrf :: Int -> Int -> Ptr e -> Int -> Ptr e -> IO ()\n gelqf :: Int -> Int -> Ptr e -> Int -> Ptr e -> IO ()\n unmqr :: SideEnum -> TransEnum -> Int -> Int -> Int -> Ptr e -> Int -> Ptr e -> Ptr e -> Int -> IO ()\n unmlq :: SideEnum -> TransEnum -> Int -> Int -> Int -> Ptr e -> Int -> Ptr e -> Ptr e -> Int -> IO ()\n larfg :: Int -> Ptr e -> Ptr e -> Int -> IO e\n\ncallWithWork :: (Storable e) => (Ptr e -> Int -> IO a) -> IO a\ncallWithWork call =\n alloca $ \\pQuery -> do\n call pQuery (-1)\n ldWork <- peek (castPtr pQuery) :: IO Double\n let lWork = max 1 $ ceiling ldWork\n allocaArray lWork $ \\pWork -> do\n call pWork lWork\n\ncheckInfo :: Int -> IO ()\ncheckInfo info = assert (info == 0) $ return ()\n \ninstance LAPACK Double where\n geqrf m n pA ldA pTau =\n checkInfo =<< callWithWork (dgeqrf m n pA ldA pTau)\n gelqf m n pA ldA pTau =\n checkInfo =<< callWithWork (dgelqf m n pA ldA pTau)\n unmqr s t m n k pA ldA pTau pC ldC =\n checkInfo =<< callWithWork (dormqr (cblasSide s) (cblasTrans t) m n k pA ldA pTau pC ldC)\n unmlq s t m n k pA ldA pTau pC ldC =\n checkInfo =<< callWithWork (dormlq (cblasSide s) (cblasTrans t) m n k pA ldA pTau pC ldC)\n larfg n alpha x incx = with 0 $ \\pTau -> \n dlarfg n alpha x incx pTau >> peek pTau\n\ninstance LAPACK (Complex Double) where\n geqrf m n pA ldA pTau =\n checkInfo =<< callWithWork (zgeqrf m n pA ldA pTau)\n gelqf m n pA ldA pTau =\n checkInfo =<< callWithWork (zgelqf m n pA ldA pTau)\n unmqr s t m n k pA ldA pTau pC ldC =\n checkInfo =<< callWithWork (zunmqr (cblasSide s) (cblasTrans t) m n k pA ldA pTau pC ldC)\n unmlq s t m n k pA ldA pTau pC ldC =\n checkInfo =<< callWithWork (zunmlq (cblasSide s) (cblasTrans t) m n k pA ldA pTau pC ldC)\n larfg n alpha x incx = with 0 $ \\pTau -> \n zlarfg n alpha x incx pTau >> peek pTau\n", "meta": {"hexsha": "b15fac6ebfb56315de728619c64482fcba4a60c7", "size": 2668, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Data/Elem/LAPACK/C.hs", "max_stars_repo_name": "patperry/lapack", "max_stars_repo_head_hexsha": "e47271400903cc1e770e19af6487518e43278204", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-05-08T21:13:55.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-08T21:13:55.000Z", "max_issues_repo_path": "lib/Data/Elem/LAPACK/C.hs", "max_issues_repo_name": "patperry/lapack", "max_issues_repo_head_hexsha": "e47271400903cc1e770e19af6487518e43278204", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Data/Elem/LAPACK/C.hs", "max_forks_repo_name": "patperry/lapack", "max_forks_repo_head_hexsha": "e47271400903cc1e770e19af6487518e43278204", "max_forks_repo_licenses": ["BSD-3-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.1142857143, "max_line_length": 105, "alphanum_fraction": 0.5989505247, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3309136856050476}} {"text": "{-|\nModule : HABQTlib.UnsafeAPI\n\nThis module contains functions for performing and simulating HABQT in Haskell.\n\n__Caution__: functions in this module perform no input validation and are partial. For a safe API refer to \"HABQTlib\".\n-}\nmodule HABQTlib.UnsafeAPI where\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM)\nimport Control.Monad.State.Lazy\nimport Data.Maybe (fromJust)\nimport qualified Data.Vector as V\nimport HABQTlib.Data\nimport HABQTlib.Data.Particle\nimport HABQTlib.MeasurementProcessing\nimport HABQTlib.RandomStates\nimport qualified Numeric.LinearAlgebra as LA\nimport Streaming\nimport qualified Streaming.Prelude as S\nimport qualified System.Random.MWC as MWC\nimport Text.Printf (printf)\n\n-- | Tomography keeps track of the particle hierarchy and list of previous\n-- measurement results, IO is used for verbose output and assorted random state\n-- generation.\ntype TomState = StateT (ParticleHierarchy, [PureStateVector]) IO\n\n-- | Tomography function takes a measurement result and returns state-dependent\n-- Bayesian mean estimate of state and the optimal next POVM to perform.\ntype TomFun = PureStateVector -> TomState (DensityMatrix, PurePOVM)\n\n-- | Given parameters such as output verbosity level and number of quantum\n-- bits, set up the tomography function.\ntomographyFun' ::\n QBitNum -- ^ Number of quantum bits under tomography\n -> MHMCiter -- ^ Number of MHMC iterations to perform when resampling\n -> OptIter -- ^ Number of POVM optimisation steps to perform\n -> OutputVerb -- ^ Verbosity of stdout output\n -> MWC.GenIO -- ^ IO generator for variates from \"System.Random.MWC\"\n -> TomFun\ntomographyFun' nq mi oi outv gen nextResult = do\n (ph, ms) <- get\n let nextPH = updateParticleHierarchy nextResult ph\n dim = LA.rows . getStateVector $ nextResult\n effectiveSizes =\n V.map (liftA2 (/) effectiveSize (fromIntegral . ptsNumber)) nextPH\n ra = ResampleArgs outv gen dim mi\n resampleC es pts =\n if es < 0.5\n then resample ra (nextResult : ms) pts\n else return pts\n nextPH' <- lift $ V.zipWithM resampleC effectiveSizes nextPH\n sv0s <- liftIO $ replicateM nq (genPureSV 2)\n let nextEstimate = getMixedEstimate nextPH'\n nextPOVM = optimiseSingleQbPOVM oi sv0s nextPH'\n put (nextPH', nextResult : ms)\n return (nextEstimate, nextPOVM)\n\n-- | Given a true state's density matrix and parameters, set up a simulation of\n-- quantum tomography that outputs infidelity between mean estimates and true\n-- state.\nsimulatedTomography' ::\n DensityMatrix -- ^ True state's density matrix\n -> QBitNum -- ^ Number of quantum bits under tomography\n -> MHMCiter -- ^ Number of MHMC iterations to perform when resampling\n -> OptIter -- ^ Number of POVM optimisation steps to perform\n -> OutputVerb -- ^ Verbosity of stdout output\n -> MWC.GenIO -- ^ IO generator for variates from \"System.Random.MWC\"\n -> StateT PurePOVM TomState Double\nsimulatedTomography' trueDM nq mi oi outv gen = do\n povm <- get\n nextResult <- liftIO $ simulateMeasuremet trueDM povm gen\n (nextEstimate, nextPOVM) <- lift $ tomographyFun' nq mi oi outv gen nextResult\n (nextPH, _) <- lift get\n put nextPOVM\n let fid = fidelityDM trueDM nextEstimate\n when (outv > NoOutput) . liftIO $ do\n let dim = 2 ^ nq\n rankFids =\n V.map\n (fidelityDM trueDM . snd . getWDM . reduceParticlesToMean)\n nextPH\n weightsAndFids =\n V.zip3 (V.enumFromN (1 :: Rank) dim) (V.map ptsWeight nextPH) rankFids\n putStrLn \"\"\n V.mapM_\n (\\(a, b, c) ->\n printf \"(Rank: %4d, Weight: %10.9f, Fidelity: %10.9f)\\n\" a b c)\n weightsAndFids\n return $ 1 - fid\n\n-- | Stream simulated tomography results.\nstreamResults' ::\n QBitNum -- ^ Number of quantum bits under tomography\n -> Rank -- ^ Rank of true state\n -> NumberOfParticles -- ^ Number of particles (per rank) to use for tomography\n -> MHMCiter -- ^ Number of MHMC iterations to perform when resampling\n -> OptIter -- ^ Number of POVM optimisation steps to perform\n -> OutputVerb -- ^ Verbosity of stdout output\n -> Stream (Of Double) IO ()\nstreamResults' nq rank pn mi oi outv = do\n let dim = 2 ^ nq\n trueDM <- liftIO $ genDM dim rank\n ph <- liftIO $ initialiseParticleHierarchy dim pn\n gen <- liftIO MWC.createSystemRandom\n rPOVM <-\n liftIO $\n productPOVM <$>\n replicateM nq (mkAntipodalPOVM . fromJust . svToAngles <$> genPureSV 2)\n let tomS = S.repeatM (simulatedTomography' trueDM nq mi oi outv gen)\n tomS' = evalStateT (distribute tomS) rPOVM\n initInfid = 1 - fidelityDM trueDM (getMixedEstimate ph)\n S.yield initInfid\n evalStateT (distribute tomS') (ph, [])\n", "meta": {"hexsha": "1b36b2f577ec5b8e4556592a17665b045c7c26ea", "size": 4685, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HABQTlib/UnsafeAPI.hs", "max_stars_repo_name": "Belinsky-L-V/HABQT", "max_stars_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-23T03:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T08:45:58.000Z", "max_issues_repo_path": "src/HABQTlib/UnsafeAPI.hs", "max_issues_repo_name": "Belinsky-L-V/HABQT", "max_issues_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HABQTlib/UnsafeAPI.hs", "max_forks_repo_name": "Belinsky-L-V/HABQT", "max_forks_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0427350427, "max_line_length": 118, "alphanum_fraction": 0.7144076841, "num_tokens": 1285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.33067852913649537}} {"text": "{-# LANGUAGE TypeFamilies #-}\n\nmodule FPNLA.Operations.Parameters(\n -- * Elements\n Elt(..),\n -- * Strategies and contexts\n StratCtx(),\n\n -- * Result type\n -- | In BLAS it's common that operations in higher levels use operations in the lower levels, so, an operation in level three that by its signature manipulates matrices only, internally uses level two operations that manipulates vectors. In order to avoid the /show . read/ problem, the type of the vector (or any other internal data type) must appear in the signature of an operation.\n -- To solve the problem we use phantom types to pass the internally used types to the Haskell type system.\n ResM(),\n ResV(),\n ResS(),\n blasResultM,\n blasResultV,\n blasResultS,\n getResultDataM,\n getResultDataV,\n getResultDataS,\n\n -- * Miscellaneous\n TransType(..),\n UnitType(..),\n TriangType(..),\n unTransT,\n unUnitT,\n unTriangT,\n elemTrans_m,\n dimTrans_m,\n elemSymm,\n dimTriang,\n elemUnit_m,\n dimUnit_m,\n elemTransUnit_m,\n dimTransUnit_m,\n transTrans_m\n\n) where\n\nimport FPNLA.Matrix(Matrix(..))\nimport Data.Complex (Complex, conjugate)\nimport Data.Tuple (swap)\n\n\n-- | This class represents the elements that can be used in the BLAS operations.\n-- The elements in BLAS are real or complex numbers, so we provide default instances for the Haskell 'Double', 'Float' and 'Complex' types.\nclass (Eq e, Floating e) => Elt e where\n -- | Returns the conjugate of a number. For real numbers it's the identity function and for complex numbers it's the common 'Complex.conjugate' function.\n getConjugate :: e -> e\n getConjugate = id\n\ninstance Elt Double\ninstance Elt Float\ninstance (RealFloat e) => Elt (Complex e) where\n getConjugate = conjugate\n\n-- | This type family is used to represent the /context/ of an operation.\n-- A particular implementation is a combination of an algorithm and a parallelism technique, and we call it a /strategy/. A particular strategy may need particular information to execute. For example, an operation that computes the matrix-matrix multiplication by splitting the matrices in blocks must require the size of the blocks.\n-- With this context we allows to pass any additional information that the operation needs to execute as parameters, but maintaining a common signature.\n-- The /s/ type parameter is the strategy so, there must exist a Haskell data type to represent a particular strategy.\ntype family StratCtx s :: *\n\n-- | The 'ResM' data type is used as result of level three BLAS operations and returns a matrix /m/ of elements /e/ and contains the strategy /s/ and vector /v/ as phantom types.\ndata ResM s (v :: * -> *) m e = ResM { unResM :: m e } deriving (Show)\n-- | The 'ResV' data type is used as result of level two BLAS operations and returns a vector /v/ of elements /e/ and contains the strategy /s/ as phantom types.\ndata ResV s v e = ResV { unResV :: v e } deriving (Show)\n-- | The 'ResS' data type is used as result of level one BLAS operations and returns an scalar /e/ and contains the strategy /s/ as phantom types.\ndata ResS s e = ResS { unResS :: e } deriving (Show)\n\n\n-- | Wrap a matrix into a 'ResM'.\nblasResultM :: m e -> ResM s v m e\nblasResultM = ResM\n-- | Unwrap a matrix from a 'ResM'.\ngetResultDataM :: ResM s v m e -> m e\ngetResultDataM = unResM\n\n-- | Wrap a vector into a 'ResV'.\nblasResultV :: v e -> ResV s v e\nblasResultV = ResV\n-- | Unwrap a vector from a 'ResV'.\ngetResultDataV :: ResV s v e -> v e\ngetResultDataV = unResV\n\n-- | Wrap a scalar into a 'ResS'.\nblasResultS :: e -> ResS s e\nblasResultS = ResS\n-- | Unwrap a scalar from a 'ResS'.\ngetResultDataS :: ResS s e -> e\ngetResultDataS = unResS\n\n\n-- | Indicates if a matrix must be considered as normal, transposed or transposed conjugated.\n-- This is part of the common flags in the BLAS operation signatures and it's useful to work with a transposed matrix without really computing the transposed matrix.\ndata TransType m = Trans m | NoTrans m | ConjTrans m deriving (Eq, Show)\n-- | Indicates if a matrix must be considered as unitary or not. An unitary matrix is a matrix that contains ones in the diagonal.\n-- This is part of the common flags in the BLAS operation signatures.\ndata UnitType m = Unit m | NoUnit m deriving (Eq, Show)\n-- | Indicates that a matrix is symmetric and with which triangular part of the matrix the operation is going to work ('Upper' or 'Lower').\n-- The operation only will see the indicated part of the matrix and should not try to access the other part.\n-- This is part of the common flags in the BLAS operation signatures.\ndata TriangType m = Lower m | Upper m deriving (Eq, Show)\n\n-- | Given a data type flagged by a TransType, returns a pair containing the TransType constructor and the data type.\nunTransT :: TransType a -> (b -> TransType b, a)\nunTransT (Trans a) = (Trans, a)\nunTransT (NoTrans a) = (NoTrans, a)\nunTransT (ConjTrans a) = (ConjTrans, a)\n\n-- | Given a data type flagged by a UnitType, returns a pair containing the UnitType constructor and the data type.\nunUnitT :: UnitType a -> (b -> UnitType b, a)\nunUnitT (Unit a) = (Unit, a)\nunUnitT (NoUnit a) = (NoUnit, a)\n\n-- | Given a data type flagged by a TriangType, returns a pair containing the TriangType constructor and the data type.\nunTriangT :: TriangType a -> (b -> TriangType b, a)\nunTriangT (Lower a) = (Lower, a)\nunTriangT (Upper a) = (Upper, a)\n\n\n-- | Given an /i,j/ position and a TransType flagged matrix, returns the element in that position without computing the transpose.\nelemTrans_m :: (Elt e, Matrix m e) => Int -> Int -> TransType (m e) -> e\nelemTrans_m i j (NoTrans m) = elem_m i j m\nelemTrans_m i j (Trans m) = elem_m j i m\nelemTrans_m i j (ConjTrans m) = getConjugate $ elem_m j i m\n\n\n-- | Given a TransType flagged matrix, returns the dimension of the matrix without computing the transpose.\ndimTrans_m :: (Matrix m e) => TransType (m e) -> (Int, Int)\ndimTrans_m (NoTrans m) = dim_m m\ndimTrans_m (ConjTrans m) = swap $ dim_m m\ndimTrans_m (Trans m) = swap $ dim_m m\n\n\n-- | Given an /i,j/ position and a TransType flagged matrix, returns the element in that position only accessing the part indicated by the TransType.\nelemSymm :: (Matrix m e) => Int -> Int -> TriangType (m e) -> e\nelemSymm i j (Upper m)\n | i > j = elem_m j i m\n | otherwise = elem_m i j m\nelemSymm i j (Lower m)\n | i > j = elem_m i j m\n | otherwise = elem_m j i m\n\n-- | Given a TransType flagged matrix, returns the dimension of the matrix.\ndimTriang :: (Matrix m e) => TriangType (m e) -> (Int, Int)\ndimTriang = dim_m . snd . unTriangT\n\n-- | Given an /i,j/ position and a UnitType flagged matrix, returns the element in that position. If the matrix is flagged as Unit and /i == j/ (the element is in the diagonal) returns one.\nelemUnit_m :: (Elt e, Matrix m e) => Int -> Int -> UnitType (m e) -> e\nelemUnit_m i j (Unit m)\n | i == j = 1\n | otherwise = elem_m i j m\nelemUnit_m i j (NoUnit m) = elem_m i j m\n\n-- | Given a UnitType flagged matrix, returns the dimension of the matrix.\ndimUnit_m :: (Matrix m e) => UnitType (m e) -> (Int, Int)\ndimUnit_m (Unit m) = dim_m m\ndimUnit_m (NoUnit m) = dim_m m\n\n-- | Given an /i,j/ position and a TransType-UnitType flagged matrix, returns the element in that position without computing the transpose.\nelemTransUnit_m :: (Elt e, Matrix m e) => Int -> Int -> TransType (UnitType (m e)) -> e\nelemTransUnit_m i j (NoTrans pmA) = elemUnit_m i j pmA\nelemTransUnit_m i j (Trans pmA) = elemUnit_m j i pmA\nelemTransUnit_m i j (ConjTrans pmA) = getConjugate $ elemUnit_m j i pmA\n\n-- | Given a TransType-UnitType flagged matrix, returns the dimension of the matrix.\ndimTransUnit_m :: Matrix m e => TransType (UnitType (m e)) -> (Int, Int)\ndimTransUnit_m = dimUnit_m . snd . unTransT\n\n-- | Given a TransType flagged matrix, computes and returns its transpose.\ntransTrans_m :: (Elt e, Matrix m e) => TransType (m e) -> m e\ntransTrans_m (NoTrans m) = m\ntransTrans_m (ConjTrans m) = map_m getConjugate $ transpose_m m\ntransTrans_m (Trans m) = transpose_m m\n", "meta": {"hexsha": "e7ead850d254c3c04d86055ae013a8020781b7bf", "size": 8055, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FPNLA/Operations/Parameters.hs", "max_stars_repo_name": "mauroblanco/fpnla", "max_stars_repo_head_hexsha": "f1429c59dba36eb81851fbefcac759c2581a8b92", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-07-06T03:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-06T03:07:30.000Z", "max_issues_repo_path": "src/FPNLA/Operations/Parameters.hs", "max_issues_repo_name": "mauroblanco/fpnla", "max_issues_repo_head_hexsha": "f1429c59dba36eb81851fbefcac759c2581a8b92", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FPNLA/Operations/Parameters.hs", "max_forks_repo_name": "mauroblanco/fpnla", "max_forks_repo_head_hexsha": "f1429c59dba36eb81851fbefcac759c2581a8b92", "max_forks_repo_licenses": ["BSD-3-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.7670454545, "max_line_length": 389, "alphanum_fraction": 0.7098696462, "num_tokens": 2234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.32913254495395944}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-|\nModule : Grenade.Layers.LeakyTanh\nDescription : Hyperbolic tangent nonlinear layer\nCopyright : (c) Huw Campbell, 2016-2017\nLicense : BSD2\nStability : experimental\n-}\nmodule Grenade.Layers.LeakyTanh\n ( LeakyTanh(..)\n , SpecLeakyTanh (..)\n , specLeakyTanh1D\n , specLeakyTanh2D\n , specLeakyTanh3D\n , specLeakyTanh\n , leakyTanhLayer\n ) where\n\nimport Control.DeepSeq (NFData (..))\nimport Data.Constraint (Dict (..))\nimport Data.Proxy\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\nimport Grenade.Types\nimport Grenade.Utils.Conversion\nimport Grenade.Utils.Vector\n\n-- | A LeakyTanh layer. A layer which can act between any shape of the same dimension, performing a tanh function. The maximum value is given in Promille, i.e. 995 is 0.995, and is positive and negative. I.e. LeakyTanh(x) = min 0.995 (max (-0.995) x).\ndata LeakyTanh (v :: Nat) = LeakyTanh\n deriving (Generic,NFData,Show)\n\ninstance UpdateLayer (LeakyTanh maxVal) where\n type Gradient (LeakyTanh maxVal) = ()\n runUpdate _ l@LeakyTanh{} _ = l\n\ninstance RandomLayer (LeakyTanh maxVal) where\n createRandomWith _ _ = return LeakyTanh\n\n\ninstance Serialize (LeakyTanh maxVal) where\n put _ = return ()\n get = return LeakyTanh\n\ninstance (a ~ b, SingI a, KnownNat maxVal) => Layer (LeakyTanh maxVal) a b where\n type Tape (LeakyTanh maxVal) a b = S a\n runForwards _ (S1DV v) = (S1DV v, S1DV $ mapVector (tanhMax maxVal) v)\n where\n maxVal = (/ 1000) $ fromIntegral $ max 0 $ min 1000 $ natVal (Proxy :: Proxy maxVal)\n runForwards _ (S2DV v) = (S2DV v, S2DV $ mapVector (tanhMax maxVal) v)\n where\n maxVal = (/ 1000) $ fromIntegral $ max 0 $ min 1000 $ natVal (Proxy :: Proxy maxVal)\n runForwards _ (S1D a) = (S1D a, S1D $ LAS.dvmap (tanhMax maxVal) a)\n where\n maxVal = (/ 1000) $ fromIntegral $ max 0 $ min 1000 $ natVal (Proxy :: Proxy maxVal)\n runForwards _ (S2D a) = (S2D a, S2D $ LAS.dmmap (tanhMax maxVal) a)\n where\n maxVal = (/ 1000) $ fromIntegral $ max 0 $ min 1000 $ natVal (Proxy :: Proxy maxVal)\n runForwards _ (S3D a) = (S3D a, S3D $ LAS.dmmap (tanhMax maxVal) a)\n where\n maxVal = (/ 1000) $ fromIntegral $ max 0 $ min 1000 $ natVal (Proxy :: Proxy maxVal)\n runBackwards _ (S1DV v) (S1DV gs) = ((), S1DV $ zipWithVector (\\t g -> tanhMax' maxVal t * g) v gs)\n where\n maxVal = (/ 1000) $ fromIntegral $ max 0 $ min 1000 $ natVal (Proxy :: Proxy maxVal)\n runBackwards _ (S2DV v) (S2DV gs) = ((), S2DV $ zipWithVector (\\t g -> tanhMax' maxVal t * g) v gs)\n where\n maxVal = (/ 1000) $ fromIntegral $ max 0 $ min 1000 $ natVal (Proxy :: Proxy maxVal)\n runBackwards _ (S1D a) (S1D g) = ((), S1D $ LAS.dvmap (tanhMax' maxVal) a * g)\n where\n maxVal = (/ 1000) $ fromIntegral $ max 0 $ min 1000 $ natVal (Proxy :: Proxy maxVal)\n runBackwards _ (S2D a) (S2D g) = ((), S2D $ LAS.dmmap (tanhMax' maxVal) (tanh' a) * g)\n where\n maxVal = (/ 1000) $ fromIntegral $ max 0 $ min 1000 $ natVal (Proxy :: Proxy maxVal)\n runBackwards _ (S3D a) (S3D g) = ((), S3D $ LAS.dmmap (tanhMax' maxVal) (tanh' a) * g)\n where\n maxVal = (/ 1000) $ fromIntegral $ max 0 $ min 1000 $ natVal (Proxy :: Proxy maxVal)\n runBackwards l x y = runBackwards l x (toLayerShape x y)\n\ntanhMax :: (Ord a, Fractional a) => a -> a -> a\ntanhMax m v\n | v > m = leaky * (v - m) + m\n | v < -m = leaky * (v - m) - m\n | otherwise = v\n where\n leaky = 0.05\n\ntanhMax' :: (Ord a, Fractional a, Floating a) => a -> a -> a\ntanhMax' m v\n | v > m = leaky\n | v < -m = -leaky\n | otherwise = max 0.005 (tanh' v)\n where\n leaky = 0.05\n\n\ntanh' :: (Floating a) => a -> a\ntanh' t = 1 - s ^ (2 :: Int) where s = tanh t\n\n-------------------- DynamicNetwork instance --------------------\n\ninstance (KnownNat maxVal) => FromDynamicLayer (LeakyTanh maxVal) where\n fromDynamicLayer inp _ LeakyTanh = SpecNetLayer $ SpecLeakyTanh maxVal (tripleFromSomeShape inp)\n where maxVal = (/1000) $ fromIntegral $ max 0 $ min 1000 $ natVal (Proxy :: Proxy maxVal)\n\ninstance ToDynamicLayer SpecLeakyTanh where\n toDynamicLayer _ _ (SpecLeakyTanh maxVal (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 reifyNat (round $ 1000 * maxVal) $ \\(_ :: (KnownNat maxVal) => Proxy maxVal) ->\n case (rows, cols, depth) of\n (_, 1, 1) -> case (unsafeCoerce (Dict :: Dict()) :: Dict ()) of\n Dict -> return $ SpecLayer (LeakyTanh :: LeakyTanh maxVal) (sing :: Sing ('D1 rows)) (sing :: Sing ('D1 rows))\n (_, _, 1) -> case (unsafeCoerce (Dict :: Dict()) :: Dict ()) of\n Dict -> return $ SpecLayer (LeakyTanh :: LeakyTanh maxVal) (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 (LeakyTanh :: LeakyTanh maxVal) (sing :: Sing ('D3 rows cols depth)) (sing :: Sing ('D3 rows cols depth))\n\n\n-- | Create a specification for a LeakyTanh layer.\nspecLeakyTanh1D :: RealNum -> Integer -> SpecNet\nspecLeakyTanh1D maxVal i = specLeakyTanh3D maxVal (i, 1, 1)\n\n-- | Create a specification for a LeakyTanh layer.\nspecLeakyTanh2D :: RealNum -> (Integer, Integer) -> SpecNet\nspecLeakyTanh2D maxVal (i, j) = specLeakyTanh3D maxVal (i, j, 1)\n\n-- | Create a specification for a LeakyTanh layer.\nspecLeakyTanh3D :: RealNum -> (Integer, Integer, Integer) -> SpecNet\nspecLeakyTanh3D maxVal = SpecNetLayer . SpecLeakyTanh maxVal\n\n-- | Create a specification for a LeakyTanh layer.\nspecLeakyTanh :: RealNum -> (Integer, Integer, Integer) -> SpecNet\nspecLeakyTanh maxVal = SpecNetLayer . SpecLeakyTanh maxVal\n\n-- | Add a LeakyTanh layer to your build.\nleakyTanhLayer :: RealNum -> BuildM ()\nleakyTanhLayer maxVal\n | maxVal <= 0 || maxVal > 1 = error \"The maxVal parameter of tanhMaxLayer has to be in (0,1]\"\n | otherwise = buildGetLastLayerOut >>= buildAddSpec . SpecNetLayer . SpecLeakyTanh maxVal\n\n\n-------------------- GNum instances --------------------\n\ninstance GNum (LeakyTanh maxVal) where\n _ |* _ = LeakyTanh\n _ |+ _ = LeakyTanh\n sumG _ = LeakyTanh\n", "meta": {"hexsha": "757173c3963d036359c15504eeaf74d77e7d862a", "size": 7113, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/LeakyTanh.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/LeakyTanh.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/LeakyTanh.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": 42.5928143713, "max_line_length": 251, "alphanum_fraction": 0.6243497821, "num_tokens": 2306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.32780391821930666}} {"text": "{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule BlueRipple.Model.MRP where\n\nimport qualified BlueRipple.Data.Keyed as K\nimport qualified BlueRipple.Data.DataFrames as BR\nimport BlueRipple.Data.CountFolds\nimport qualified Control.Foldl as FL\nimport Control.Monad ( join )\nimport qualified Control.Monad.State as State\nimport qualified Data.Array as A\nimport Data.Function ( on )\nimport qualified Data.List as L\nimport qualified Data.Set as S\nimport qualified Data.IntMap as IM\nimport qualified Data.Map as M\nimport Data.Maybe ( isJust\n , fromJust\n )\nimport qualified Data.Text as T\nimport qualified Data.Profunctor as P\nimport qualified Data.Serialize as SE\nimport Data.Serialize.Text ()\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Storable as VS\n\n\nimport qualified Frames as F\nimport qualified Frames.Melt as F\nimport qualified Frames.InCore as FI\nimport qualified Data.Vinyl as V\nimport qualified Data.Vinyl.TypeLevel as V\n\n\nimport qualified Control.MapReduce as MR\nimport qualified Frames.Transform as FT\nimport qualified Frames.Folds as FF\nimport qualified Frames.MapReduce as FMR\nimport qualified Frames.Enumerations as FE\n--import qualified Frames.Misc as FU\nimport qualified Frames.Serialize as FS\n\nimport qualified Knit.Report as K hiding (elements)\nimport qualified Polysemy.Error as P\n ( mapError )\nimport qualified Polysemy as P\n ( raise )\nimport Text.Pandoc.Error as PE\nimport qualified Text.Blaze.Colonnade as BC\nimport qualified Text.Show\n\nimport qualified Numeric.LinearAlgebra as LA\n\nimport qualified Data.IndexedSet as IS\nimport qualified Numeric.GLM.ProblemTypes as GLM\nimport qualified Numeric.GLM.ModelTypes as GLM\nimport qualified Numeric.GLM.FunctionFamily as GLM\nimport Numeric.GLM.MixedModel as GLM\nimport qualified Numeric.GLM.Bootstrap as GLM\nimport qualified Numeric.GLM.Report as GLM\nimport qualified Numeric.GLM.Predict as GLM\nimport qualified Numeric.GLM.Confidence as GLM\nimport qualified Numeric.SparseDenseConversions\n as SD\n\nimport qualified Relude.Extra as Relude\n\nimport qualified Statistics.Types as ST\nimport GHC.Generics ( Generic, Rep )\n\n\n\n{- Moved to BlueRipple.Data.CountFolds\n-- map reduce folds for counting\ntype Count = \"Count\" F.:-> Int\ntype Successes = \"Successes\" F.:-> Int\ntype MeanWeight = \"MeanWeight\" F.:-> Double\ntype VarWeight = \"VarWeight\" F.:-> Double\ntype WeightedSuccesses = \"WeightedSuccesses\" F.:-> Double\ntype UnweightedSuccesses = \"UnweightedSuccesses\" F.:-> Int\n\nbinomialFold\n :: (F.Record r -> Bool) -> FL.Fold (F.Record r) (F.Record '[Count, Successes])\nbinomialFold testRow =\n let successesF = FL.premap (\\r -> if testRow r then 1 else 0) FL.sum\n in (\\n s -> n F.&: s F.&: V.RNil) <$> FL.length <*> successesF\n\ncountFold\n :: forall k r d\n . ( Ord (F.Record k)\n , FI.RecVec (k V.++ '[Count, Successes])\n , k F.⊆ r\n , d F.⊆ r\n )\n => (F.Record d -> Bool)\n -> FL.Fold (F.Record r) [F.FrameRec (k V.++ '[Count, Successes])]\ncountFold testData = MR.mapReduceFold\n MR.noUnpack\n (FMR.assignKeysAndData @k)\n (FMR.foldAndAddKey $ binomialFold testData)\n\ntype CountCols = '[Count, UnweightedSuccesses, WeightedSuccesses, MeanWeight, VarWeight]\n\nzeroCount :: F.Record CountCols\nzeroCount = 0 F.&: 0 F.&: 0 F.&: 1 F.&: 0 F.&: V.RNil\n\nweightedBinomialFold\n :: (F.Record r -> Bool)\n -> (F.Record r -> Double)\n -> FL.Fold (F.Record r) (F.Record CountCols)\nweightedBinomialFold testRow weightRow =\n let wSuccessesF =\n FL.premap (\\r -> if testRow r then weightRow r else 0) FL.sum\n successesF = FL.premap (\\r -> if testRow r then 1 else 0) FL.sum\n meanWeightF = FL.premap weightRow FL.mean\n varWeightF = FL.premap weightRow FL.variance\n f s ws mw = if mw < 1e-6 then realToFrac s else ws / mw -- if meanweight is 0 but\n in (\\n s ws mw vw -> n F.&: s F.&: f s ws mw F.&: mw F.&: vw F.&: V.RNil)\n <$> FL.length\n <*> successesF\n <*> wSuccessesF\n <*> meanWeightF\n <*> varWeightF\n\nweightedCountFold\n :: forall k r d\n . (Ord (F.Record k)\n , FI.RecVec (k V.++ CountCols)\n , k F.⊆ r\n , k F.⊆ (k V.++ r)\n , d F.⊆ (k V.++ r)\n )\n => (F.Record r -> Bool) -- ^ count this row?\n -> (F.Record d -> Bool) -- ^ success ?\n -> (F.Record d -> Double) -- ^ weight\n -> FL.Fold (F.Record r) (F.FrameRec (k V.++ CountCols))\nweightedCountFold {- filterData testData weightData-} = weightedCountFoldGeneral (F.rcast @k)\n{- FMR.concatFold $ FMR.mapReduceFold\n (MR.filterUnpack filterData)\n (FMR.assignKeysAndData @k)\n (FMR.foldAndAddKey $ weightedBinomialFold testData weightData)\n-}\n\nweightedCountFoldGeneral\n :: forall k r d\n . (Ord (F.Record k)\n , FI.RecVec (k V.++ CountCols)\n , k F.⊆ (k V.++ r)\n , d F.⊆ (k V.++ r)\n )\n => (F.Record r -> F.Record k)\n -> (F.Record r -> Bool) -- ^ include this row?\n -> (F.Record d -> Bool) -- ^ success ?\n -> (F.Record d -> Double) -- ^ weight\n -> FL.Fold (F.Record r) (F.FrameRec (k V.++ CountCols))\nweightedCountFoldGeneral getKey filterData testData weightData =\n FL.prefilter filterData $ FMR.concatFold $ FMR.mapReduceFold\n (MR.Unpack $ \\r -> [getKey r `V.rappend` r])\n (FMR.assignKeysAndData @k @d)\n (FMR.foldAndAddKey $ weightedBinomialFold testData weightData)\n\n-}\n\ngetFraction r =\n let n = F.rgetField @Count r\n in if n == 0\n then 0\n else realToFrac (F.rgetField @Successes r) / realToFrac n\n\ngetFractionWeighted r =\n let n = F.rgetField @Count r\n in if n == 0 then 0 else F.rgetField @WeightedSuccesses r / realToFrac n\n\ndata RecordColsProxy k = RecordColsProxy deriving (Show, Enum, Bounded, A.Ix, Eq, Ord)\ntype instance GLM.GroupKey (RecordColsProxy k) = F.Record k\n\n--type instance GLM.GroupKey (Proxy k) = F.Record k\n\nrecordToGroupKey\n :: forall k r . (k F.⊆ r) => F.Record r -> RecordColsProxy k -> F.Record k\nrecordToGroupKey r _ = F.rcast @k r\n\nglmErrorToPandocError :: GLM.GLMError -> PE.PandocError\nglmErrorToPandocError x = PE.PandocSomeError $ show x\n\n\ntype GroupCols gs cs = gs V.++ cs\ntype CountedCols gs cs = GroupCols gs cs V.++ CountCols\n\n\n\n---\nnewtype SimplePredictor ps = SimplePredictor { unSimplePredictor :: F.Record ps }\n\ninstance (Show (F.Record ps)) => Show (SimplePredictor ps) where\n show (SimplePredictor x) = \"SimplePredictor \" ++ show @String x\n\ninstance (Eq (F.Record ps)) => Eq (SimplePredictor ps) where\n (SimplePredictor x) == (SimplePredictor y) = x == y\n\ninstance (Ord (F.Record ps)) => Ord (SimplePredictor ps) where\n compare (SimplePredictor x) (SimplePredictor y) = compare x y\n\ninstance (Ord (F.Record ps), K.FiniteSet (F.Record ps)) => Enum (SimplePredictor ps) where\n toEnum n =\n let im = IM.fromList $ zip [0..] $ SimplePredictor <$> S.toAscList K.elements\n in fromMaybe (error \"Bad n given to toEnum :: Int -> SimplePredictor\") $ IM.lookup n im\n fromEnum a =\n let m = M.fromList $ zip (SimplePredictor <$> S.toAscList K.elements) [0..]\n in fromMaybe (error \"Bad SimplePredictor given to fromEnum :: SimplePredictor -> Int. This means something is very bad.\") $ M.lookup a m\n\ninstance (K.FiniteSet (F.Record ps)) => Bounded (SimplePredictor ps) where\n minBound = fromMaybe (error \"Empty Set of Records used as predictor\") $ viaNonEmpty head $ SimplePredictor <$> S.toList K.elements\n maxBound = fromMaybe (error \"Empty Set of Records used as predictor\") $ viaNonEmpty last $ SimplePredictor <$> S.toList K.elements\n\n\nallSimplePredictors :: K.FiniteSet (F.Record ps) => [SimplePredictor ps]\nallSimplePredictors = SimplePredictor <$> S.toList K.elements\n\ntype SimpleEffect ps = GLM.WithIntercept (SimplePredictor ps)\n\nsimplePredictor :: forall ps rs. (ps F.⊆ rs\n , Eq (F.Record ps)\n )\n => F.Record rs -> SimplePredictor ps -> Double\nsimplePredictor r p = if F.rcast @ps r == unSimplePredictor p then 1 else 0\n\npredMap :: forall cs. (K.FiniteSet (F.Record cs), Ord (F.Record cs), cs F.⊆ cs)\n => F.Record cs -> M.Map (SimplePredictor cs) Double\npredMap r = M.fromList $ Relude.fmapToSnd (simplePredictor r) allSimplePredictors\n\ncatPredMaps :: forall cs. (K.FiniteSet (F.Record cs), Ord (F.Record cs), cs F.⊆ cs)\n => M.Map (F.Record cs) (M.Map (SimplePredictor cs) Double)\ncatPredMaps = M.fromList $ fmap (\\k -> (unSimplePredictor k,predMap (unSimplePredictor k))) allSimplePredictors\n\ndata LocationHolder c f a = LocationHolder { locName :: T.Text\n , locKey :: Maybe (F.Rec f LocationCols)\n , catData :: M.Map (F.Rec f c) a\n } deriving (Generic)\n\nderiving instance (V.RMap c\n , V.ReifyConstraint Show F.ElField c\n , V.RecordToList c\n , Show a) => Show (LocationHolder c F.ElField a)\n\ninstance (SE.Serialize a\n , Ord (F.Rec FS.SElField c)\n , SE.GSerializePut\n (Rep (F.Rec FS.SElField c))\n , SE.GSerializeGet (Rep (F.Rec FS.SElField c))\n , (Generic (F.Rec FS.SElField c))\n ) => SE.Serialize (LocationHolder c FS.SElField a)\n\nlhToS :: (Ord (F.Rec FS.SElField c)\n , V.RMap c\n )\n => LocationHolder c F.ElField a -> LocationHolder c FS.SElField a\nlhToS (LocationHolder n lkM cdm) = LocationHolder n (fmap FS.toS lkM) (M.mapKeys FS.toS cdm)\n\nlhFromS :: (Ord (F.Rec F.ElField c)\n , V.RMap c\n ) => LocationHolder c FS.SElField a -> LocationHolder c F.ElField a\nlhFromS (LocationHolder n lkM cdm) = LocationHolder n (fmap FS.fromS lkM) (M.mapKeys FS.fromS cdm)\n\ntype LocationCols = '[BR.StateAbbreviation]\nlocKeyPretty :: F.Record LocationCols -> T.Text\nlocKeyPretty r =\n let stateAbbr = F.rgetField @BR.StateAbbreviation r\n in stateAbbr\n\n--type ASER = '[BR.SimpleAgeC, BR.SexC, BR.CollegeGradC, BR.SimpleRaceC]\npredictionsByLocation ::\n forall ps r rs. ( V.RMap ps\n , V.ReifyConstraint Show V.ElField ps\n , V.RecordToList ps\n , Ord (F.Record ps)\n , Ord (SimplePredictor ps)\n , FI.RecVec (ps V.++ CountCols)\n , F.ElemOf (ps V.++ CountCols) Count\n , F.ElemOf (ps V.++ CountCols) MeanWeight\n , F.ElemOf (ps V.++ CountCols) UnweightedSuccesses\n , F.ElemOf (ps V.++ CountCols) VarWeight\n , F.ElemOf (ps V.++ CountCols) WeightedSuccesses\n , K.FiniteSet (F.Record ps)\n , Show (F.Record (LocationCols V.++ ps V.++ CountCols))\n , Show (F.Record ps)\n , Enum (SimplePredictor ps)\n , Bounded (SimplePredictor ps)\n , (ps V.++ CountCols) F.⊆ (LocationCols V.++ ps V.++ CountCols)\n , ps F.⊆ (ps V.++ CountCols)\n , ps F.⊆ (LocationCols V.++ ps V.++ CountCols)\n , F.ElemOf rs BR.StateAbbreviation\n , K.KnitEffects r\n )\n => GLM.MinimizeDevianceVerbosity\n -> F.FrameRec rs\n -> FL.Fold (F.Record rs) (F.FrameRec (LocationCols V.++ ps V.++ CountCols))\n -> [SimpleEffect ps]\n -> M.Map (F.Record ps) (M.Map (SimplePredictor ps) Double)\n -> K.Sem r [LocationHolder ps V.ElField Double]\npredictionsByLocation verbosity ccesFrame countFold predictors catPredMap =\n P.mapError glmErrorToPandocError $ K.wrapPrefix \"predictionsByLocation\" $ do\n K.logLE K.Diagnostic \"Inferring\"\n (mm, rc, ebg, bu, vb, bs) <- inferMR @LocationCols @ps @ps\n verbosity\n countFold\n predictors\n simplePredictor\n ccesFrame\n\n let states = FL.fold FL.set $ fmap (F.rgetField @BR.StateAbbreviation) ccesFrame\n allStateKeys = (F.&: V.RNil) <$> FL.fold FL.list states\n predictLoc l = LocationHolder (locKeyPretty l) (Just l) catPredMap\n toPredict = [LocationHolder \"National\" Nothing catPredMap] <> fmap predictLoc allStateKeys\n predict (LocationHolder n lkM cpms) = P.mapError glmErrorToPandocError $ do\n let predictFrom catKey predMap =\n let groupKeyM = fmap (`V.rappend` catKey) lkM --lkM >>= \\lk -> return $ lk `V.rappend` catKey\n emptyAsNationalGKM = case groupKeyM of\n Nothing -> Nothing\n Just k -> k <$ GLM.categoryNumberFromKey rc k (RecordColsProxy @(LocationCols V.++ ps))\n in (fmap snd . GLM.runLogOnGLMException Nothing)\n $ GLM.predictFromBetaB mm (`M.lookup` predMap) (const emptyAsNationalGKM) rc ebg bu vb\n cpreds <- M.traverseWithKey predictFrom cpms\n return $ LocationHolder n lkM cpreds\n traverse predict toPredict\n\n---\n\n\n-- TODO: Add bootstraps back in, make optional\n-- Maybe set up way to serialize all this at this level??\n\n-- ls: are keys for locations (groups with no matching fixed-effect)\n-- cs: are keys for fixedEffects, one for each constructor in b\n-- b: Fixed Effect type\n-- g: group type\ninferMR\n :: forall ls cs ks b g f rs effs\n . ( Foldable f\n , Functor f\n , K.KnitEffects effs\n , F.RDeleteAll ls (ls V.++ ks V.++ CountCols) ~ (ks V.++ CountCols)\n , (ls V.++ ks V.++ CountCols) ~ (ls V.++ (ks V.++ CountCols))\n , Ord (F.Record ls)\n , ls F.⊆ (ls V.++ ks V.++ CountCols)\n , (ks V.++ CountCols) F.⊆ (ls V.++ ks V.++ CountCols)\n , ks F.⊆ (ks V.++ CountCols)\n , (ls V.++ cs) F.⊆ (ls V.++ (ks V.++ CountCols))\n , Show (F.Record (ls V.++ ks V.++ CountCols))\n , FI.RecVec (ls V.++ (ks V.++ CountCols))\n , F.ElemOf (ks V.++ CountCols) Count\n , F.ElemOf (ks V.++ CountCols) MeanWeight\n , F.ElemOf (ks V.++ CountCols) VarWeight\n , F.ElemOf (ks V.++ CountCols) WeightedSuccesses\n , F.ElemOf (ks V.++ CountCols) UnweightedSuccesses\n , F.ElemOf (ls V.++ ks V.++ CountCols) Count\n , F.ElemOf (ls V.++ ks V.++ CountCols) MeanWeight\n , F.ElemOf (ls V.++ ks V.++ CountCols) VarWeight\n , F.ElemOf (ls V.++ ks V.++ CountCols) WeightedSuccesses\n , F.ElemOf (ls V.++ ks V.++ CountCols) UnweightedSuccesses\n , Show (F.Record (ls V.++ cs))\n , K.FiniteSet (F.Record ks)\n , Ord b\n , Show b\n , Enum b\n , Bounded b\n , Ord (F.Record (GroupCols ls cs))\n , g ~ RecordColsProxy (GroupCols ls cs)\n )\n => GLM.MinimizeDevianceVerbosity\n -> FL.Fold (F.Record rs) (F.FrameRec (ls V.++ ks V.++ CountCols))\n -> [GLM.WithIntercept b] -- fixed effects to fit\n -> (F.Record (ls V.++ ks V.++ CountCols) -> b -> Double) -- how to get a fixed effect value from a record\n -> f (F.Record rs)\n -> K.Sem\n effs\n ( GLM.MixedModel b g\n , GLM.RowClassifier g\n , GLM.EffectsByGroup g b\n , GLM.BetaVec\n , LA.Vector Double\n , [(GLM.BetaVec, LA.Vector Double)]\n )\ninferMR verbosity cf fixedEffectList getFixedEffect rows =\n P.mapError glmErrorToPandocError\n $ (fmap snd . GLM.runLogOnGLMException Nothing)\n $ K.wrapPrefix \"inferMR\"\n $ do\n let\n addZeroCountsF = FMR.concatFold $ FMR.mapReduceFold\n FMR.noUnpack\n (FMR.splitOnKeys @ls)\n ( FMR.makeRecsWithKey id\n $ FMR.ReduceFold\n $ const\n $ K.addDefaultRec @ks zeroCount\n )\n counted = FL.fold FL.list $ FL.fold addZeroCountsF $ FL.fold cf rows\n-- K.logLE K.Diagnostic $ T.intercalate \"\\n\" $ fmap (T.pack . show) counted\n let\n vCounts = VS.fromList $ fmap (F.rgetField @Count) counted\n designEffect mw vw = 1 + (vw / (mw * mw))\n vWeights = VS.fromList $ fmap\n (\\r ->\n let mw = F.rgetField @MeanWeight r\n vw = F.rgetField @VarWeight r\n in case (mw < 1e-12, vw < 1e-12) of\n (True, _) -> 0\n (False, True) -> 1\n _ -> 1/sqrt (designEffect mw vw)\n )\n counted -- VS.replicate (VS.length vCounts) 1.0\n\n fixedEffects = GLM.FixedEffects $ IS.fromList fixedEffectList\n groups = IS.fromList [RecordColsProxy]\n (observations, fixedEffectsModelMatrix, rcM) = FL.fold\n (lmePrepFrame getFractionWeighted\n fixedEffects\n groups\n getFixedEffect\n (recordToGroupKey @(GroupCols ls cs))\n )\n counted\n-- K.logLE K.Diagnostic $ \"vCounts=\" <> (T.pack $ show vCounts)\n-- K.logLE K.Diagnostic $ \"vWeights=\" <> (T.pack $ show vWeights)\n-- K.logLE K.Diagnostic $ \"mX=\" <> (T.pack $ show fixedEffectsModelMatrix)\n-- K.logLE K.Diagnostic $ \"vY=\" <> (T.pack $ show observations)\n let regressionModelSpec = GLM.RegressionModelSpec\n fixedEffects\n fixedEffectsModelMatrix\n observations\n rowClassifier <- case rcM of\n Left msg -> K.knitError msg\n Right x -> return x\n-- K.logLE K.Diagnostic $ \"rc=\" <> (T.pack $ show rowClassifier)\n let effectsByGroup =\n M.fromList [(RecordColsProxy, IS.fromList [GLM.Intercept])]\n fitSpecByGroup <- GLM.fitSpecByGroup @b @g fixedEffects\n effectsByGroup\n rowClassifier\n let lmmControls = GLM.LMMControls GLM.LMM_BOBYQA 1e-6 Nothing\n lmmSpec = GLM.LinearMixedModelSpec\n (GLM.MixedModelSpec regressionModelSpec fitSpecByGroup)\n lmmControls\n cc = GLM.PIRLSConvergenceCriterion GLM.PCT_Deviance 1e-6 20\n glmmControls = GLM.GLMMControls GLM.UseCanonical 10 cc\n glmmSpec = GLM.GeneralizedLinearMixedModelSpec\n lmmSpec\n vWeights\n (GLM.Binomial vCounts)\n glmmControls\n mixedModel = GLM.GeneralizedLinearMixedModel glmmSpec\n randomEffectsModelMatrix <- GLM.makeZ fixedEffectsModelMatrix\n fitSpecByGroup\n rowClassifier\n-- K.logLE K.Diagnostic $ \"smZ=\" <> (T.pack $ show randomEffectsModelMatrix)\n let randomEffectCalc = GLM.RandomEffectCalculated\n randomEffectsModelMatrix\n (GLM.makeLambda fitSpecByGroup)\n th0 = GLM.setCovarianceVector fitSpecByGroup 1 0\n -- mdVerbosity = MDVNone\n GLM.checkProblem mixedModel randomEffectCalc\n K.logLE K.Info \"Fitting data...\"\n ((th, pd, sigma2, beta, mzvu, mzvb, cs), vMuSol, cf) <- GLM.minimizeDeviance\n verbosity\n ML\n mixedModel\n randomEffectCalc\n th0\n vb <- K.knitMaybe \"b-vector (random effects coefficients) is zero in MRP.inferMR\" $ GLM.useMaybeZeroVec Nothing Just mzvb\n GLM.report mixedModel\n randomEffectsModelMatrix\n beta\n (SD.toSparseVector vb)\n let fes = GLM.fixedEffectStatistics mixedModel sigma2 cs beta\n K.logLE K.Diagnostic $ \"FixedEffectStatistics: \" <> show fes\n epg <- GLM.effectParametersByGroup @g @b rowClassifier effectsByGroup vb\n-- K.logLE K.Diagnostic\n-- $ \"EffectParametersByGroup: \"\n-- <> (T.pack $ show epg)\n gec <- GLM.effectCovariancesByGroup effectsByGroup mixedModel sigma2 th\n K.logLE K.Diagnostic\n $ \"EffectCovariancesByGroup: \"\n <> show gec\n rebl <- GLM.randomEffectsByLabel epg rowClassifier\n K.logLE K.Diagnostic\n $ \"Random Effects:\\n\"\n <> GLM.printRandomEffectsByLabel rebl\n smCondVar <- GLM.conditionalCovariances mixedModel\n cf\n randomEffectCalc\n th\n beta\n mzvu\n let bootstraps = []\n let GLM.FixedEffectStatistics _ mBetaCov = fes\n let f r = do\n let obs = getFractionWeighted r\n predictCVCI <- GLM.predictWithCI\n mixedModel\n (Just . getFixedEffect r)\n (Just . recordToGroupKey @(GroupCols ls cs) r)\n rowClassifier\n effectsByGroup\n beta\n vb\n (ST.mkCL 0.95)\n (GLM.NaiveCondVarCI mBetaCov smCondVar)\n return (r, obs, predictCVCI)\n fitted <- traverse f (FL.fold FL.list counted)\n K.logLE K.Diagnostic\n $ \"Fitted:\\n\"\n <> (T.intercalate \"\\n\" $ fmap show fitted)\n fixedEffectTable <- GLM.printFixedEffects fes\n K.logLE K.Diagnostic $ \"FixedEffects:\\n\" <> fixedEffectTable\n let GLM.FixedEffectStatistics fep _ = fes\n return\n (mixedModel, rowClassifier, effectsByGroup, beta, vb, bootstraps) -- fes, epg, rowClassifier, bootstraps)\n\nlmePrepFrame\n :: forall p g rs\n . (GLM.PredictorC p, GLM.GroupC g)\n => (F.Record rs -> Double) -- ^ observations\n -> GLM.FixedEffects p\n -> IS.IndexedSet g\n -> (F.Record rs -> p -> Double) -- ^ predictors\n -> (F.Record rs -> g -> GLM.GroupKey g) -- ^ classifiers\n -> FL.Fold\n (F.Record rs)\n ( LA.Vector Double\n , LA.Matrix Double\n , Either T.Text (GLM.RowClassifier g)\n ) -- ^ (X,y,(row-classifier, size of class))\nlmePrepFrame observationF fe groupIndices getPredictorF classifierLabelF\n = let\n makeInfoVector\n :: M.Map g (M.Map (GLM.GroupKey g) Int)\n -> M.Map g (GLM.GroupKey g)\n -> Either T.Text (V.Vector (GLM.ItemInfo g))\n makeInfoVector indexMaps groupKeys =\n let\n g (grp, groupKey) =\n GLM.ItemInfo\n <$> ( maybe\n (Left $ \"Failed on \" <> show (grp, groupKey))\n Right\n $ M.lookup grp indexMaps\n >>= M.lookup groupKey\n )\n <*> pure groupKey\n in fmap V.fromList $ traverse g $ M.toList groupKeys\n makeRowClassifier\n :: Traversable f\n => M.Map g (M.Map (GLM.GroupKey g) Int)\n -> f (M.Map g (GLM.GroupKey g))\n -> Either T.Text (GLM.RowClassifier g)\n makeRowClassifier indexMaps labels = do\n let sizes = fmap M.size indexMaps\n indexed <- traverse (makeInfoVector indexMaps) labels\n return $ GLM.RowClassifier groupIndices\n sizes\n (V.fromList $ FL.fold FL.list indexed)\n indexMaps\n getPredictorF' _ GLM.Intercept = 1\n getPredictorF' row (GLM.Predictor x) = getPredictorF row x\n predictorF row = LA.fromList $ case fe of\n GLM.FixedEffects indexedFixedEffects ->\n getPredictorF' row <$> IS.members indexedFixedEffects\n GLM.InterceptOnly -> [1]\n getClassifierLabels :: F.Record rs -> M.Map g (GLM.GroupKey g)\n getClassifierLabels r =\n M.fromList $ Relude.fmapToSnd (classifierLabelF r) $ IS.members groupIndices\n foldObs = LA.fromList <$> FL.premap observationF FL.list\n foldPred = LA.fromRows <$> FL.premap predictorF FL.list\n foldClass = FL.premap getClassifierLabels FL.list\n g (vY, mX, ls) =\n ( vY\n , mX\n , makeRowClassifier\n (snd $ State.execState (addAll ls) (M.empty, M.empty))\n ls\n )\n in\n g <$> ((,,) <$> foldObs <*> foldPred <*> foldClass)\n\n\n\naddOne\n :: GLM.GroupC g\n => (g, GLM.GroupKey g)\n -> State.State (M.Map g Int, M.Map g (M.Map (GLM.GroupKey g) Int)) ()\naddOne (grp, label) = do\n (nextIndexMap, groupIndexMaps) <- State.get\n let groupIndexMap = fromMaybe M.empty $ M.lookup grp groupIndexMaps\n case M.lookup label groupIndexMap of\n Nothing -> do\n let index = fromMaybe 0 $ M.lookup grp nextIndexMap\n nextIndexMap' = M.insert grp (index + 1) nextIndexMap\n groupIndexMaps' =\n M.insert grp (M.insert label index groupIndexMap) groupIndexMaps\n State.put (nextIndexMap', groupIndexMaps')\n return ()\n _ -> return ()\n\naddMany\n :: (GLM.GroupC g, Traversable h)\n => h (g, GLM.GroupKey g)\n -> State.State (M.Map g Int, M.Map g (M.Map (GLM.GroupKey g) Int)) ()\naddMany = traverse_ addOne\n\naddAll\n :: GLM.GroupC g\n => [M.Map g (GLM.GroupKey g)]\n -> State.State (M.Map g Int, M.Map g (M.Map (GLM.GroupKey g) Int)) ()\naddAll = traverse_ (addMany . M.toList)\n\n-- useful data folds\nweightedSumF :: (Real w, Real v, Fractional y) => FL.Fold (w, v) y\nweightedSumF =\n (/)\n <$> FL.premap (\\(w, v) -> realToFrac w * realToFrac v) FL.sum\n <*> P.dimap fst realToFrac FL.sum\n\nweightedSumRecF\n :: forall w v y rs\n . ( V.KnownField w\n , V.KnownField v\n , Fractional y\n , F.ElemOf rs w\n , F.ElemOf rs v\n , Real (V.Snd w)\n , Real (V.Snd v)\n )\n => FL.Fold (F.Record rs) y\nweightedSumRecF =\n FL.premap (\\r -> (F.rgetField @w r, F.rgetField @v r)) weightedSumF\n\n\nsumProdIfRecF\n :: forall w v t y rs\n . ( V.KnownField w\n , V.KnownField v\n , V.KnownField t\n , Fractional y\n , F.ElemOf rs w\n , F.ElemOf rs v\n , F.ElemOf rs t\n , Real (V.Snd w)\n , Real (V.Snd v)\n )\n => (V.Snd t -> Bool)\n -> FL.Fold (F.Record rs) y\nsumProdIfRecF test = FL.prefilter (test . F.rgetField @t) $ FL.premap\n (\\r -> realToFrac (F.rgetField @w r) * realToFrac (F.rgetField @v r))\n FL.sum\n", "meta": {"hexsha": "7df1257888fa04c763095e6740050ca9da68c3f1", "size": 26964, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "blueripple-glm/src/BlueRipple/Model/MRP.hs", "max_stars_repo_name": "blueripple/preference-model", "max_stars_repo_head_hexsha": "beae97c2d854830bc0e9027609e54166f93d976b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T11:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T11:32:48.000Z", "max_issues_repo_path": "blueripple-glm/src/BlueRipple/Model/MRP.hs", "max_issues_repo_name": "blueripple/preference-model", "max_issues_repo_head_hexsha": "beae97c2d854830bc0e9027609e54166f93d976b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blueripple-glm/src/BlueRipple/Model/MRP.hs", "max_forks_repo_name": "blueripple/preference-model", "max_forks_repo_head_hexsha": "beae97c2d854830bc0e9027609e54166f93d976b", "max_forks_repo_licenses": ["BSD-3-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.2447761194, "max_line_length": 141, "alphanum_fraction": 0.5834445928, "num_tokens": 7348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.32707193148330965}} {"text": "{-# LANGUAGE BangPatterns #-}\nmodule FokkerPlanck.MonteCarlo\n ( -- runMonteCarloFourierCoefficients\n runMonteCarloFourierCoefficientsGPU\n , solveMonteCarloR2S1\n ) where\n\nimport Array.UnboxedArray as UA\nimport Control.DeepSeq\nimport Control.Monad as M\nimport Control.Concurrent.Async\nimport Control.Monad.Parallel as MP\nimport Data.Array.Accelerate (constant, use)\nimport Data.Array.Accelerate.LLVM.PTX\nimport Data.Array.Repa as R\nimport Data.Binary\nimport Data.ByteString.Lazy as BL\nimport Data.Complex\nimport Data.DList as DL\nimport Data.Ix\nimport Data.List as L\nimport Data.Vector.Unboxed as VU\nimport FokkerPlanck.BrownianMotion\nimport FokkerPlanck.FourierSeries\nimport FokkerPlanck.FourierSeriesGPU\nimport FokkerPlanck.Histogram\nimport Foreign.CUDA.Driver as CUDA\nimport Statistics.Distribution\nimport Statistics.Distribution.Laplace\nimport Statistics.Distribution.Normal\nimport Statistics.Distribution.Poisson\nimport Statistics.Distribution.Uniform\nimport System.Directory\nimport System.IO as IO\nimport System.Random.MWC\nimport Text.Printf\nimport Utils.List\nimport Utils.Parallel\nimport Utils.Time\nimport GHC.Float\n\n{-# INLINE runBatch #-}\nrunBatch :: Int -> Int -> Int -> (Int -> a -> [GenIO] -> IO a) -> a -> IO a\nrunBatch !numGens !numTrails !batchSize monterCarloHistFunc !init = do\n let (!numBatch, !numLeftover) = divMod numTrails batchSize\n printf\n \"%d trails and batch size is %d, %d batch in total.\\n\"\n numTrails\n batchSize\n (numBatch +\n if numLeftover > 0\n then 1\n else 0)\n gensList <- M.replicateM numBatch (M.replicateM numGens createSystemRandom)\n x <-\n M.foldM\n (\\y gens -> do\n printCurrentTime \"\"\n monterCarloHistFunc batchSize y gens)\n init\n gensList\n if numLeftover > 0\n then do\n gens <- M.replicateM numGens createSystemRandom\n monterCarloHistFunc numLeftover x gens\n else return x\n\n{-# INLINE computeHistogramFromMonteCarloParallel #-}\ncomputeHistogramFromMonteCarloParallel ::\n (NFData hist, Binary hist, Show hist)\n => FilePath\n -> (GenIO -> IO particle)\n -> ([particle] -> IO hist)\n -> (hist -> hist -> hist)\n -> Int\n -> hist\n -> [GenIO]\n -> IO hist\ncomputeHistogramFromMonteCarloParallel !filePath pointsGenerator histFunc addHist !n !initHist !gens = do\n xs <- MP.mapM (M.replicateM (div n . L.length $ gens) . pointsGenerator) gens\n let tmpFilePath = (filePath L.++ \"_tmp\")\n hist <- L.foldl' addHist initHist <$> M.mapM histFunc xs\n unless\n (L.null filePath)\n (do encodeFile tmpFilePath hist\n copyFile tmpFilePath filePath)\n return hist\n\n{-# INLINE computeHistogramFromMonteCarloParallelSingleGPU #-}\ncomputeHistogramFromMonteCarloParallelSingleGPU ::\n (NFData hist, Binary hist, Show hist)\n => FilePath\n -> (GenIO -> IO particle)\n -> ([particle] -> hist)\n -> (hist -> hist -> hist)\n -> Int\n -> Int\n -> hist\n -> [GenIO]\n -> IO hist\ncomputeHistogramFromMonteCarloParallelSingleGPU !filePath pointsGenerator histFunc addHist !deviceID !n !initHist !gens = do\n xs <- MP.mapM (M.replicateM (div n . L.length $ gens) . pointsGenerator) gens\n let tmpFilePath = (filePath L.++ \"_tmp\")\n !hist = addHist initHist . histFunc . L.concat $ xs\n unless\n (L.null filePath)\n (do encodeFile tmpFilePath hist\n copyFile tmpFilePath filePath)\n return hist\n\n{-# INLINE computeHistogramFromMonteCarloParallelMultipleGPU #-}\ncomputeHistogramFromMonteCarloParallelMultipleGPU ::\n (NFData hist, Binary hist, Show hist, NFData particle)\n => FilePath\n -> (GenIO -> IO particle)\n -> (PTX -> [particle] -> hist)\n -> (hist -> hist -> hist)\n -> [PTX]\n -> Int\n -> hist\n -> [GenIO]\n -> IO hist\ncomputeHistogramFromMonteCarloParallelMultipleGPU !filePath pointsGenerator histFunc addHist !ptxs !n !initHist !gens = do\n xs <-\n L.concat <$>\n mapConcurrently\n (M.replicateM (div n . L.length $ gens) . pointsGenerator)\n gens\n let tmpFilePath = filePath L.++ \"_tmp\"\n !hist =\n L.foldl' addHist initHist .\n parZipWith rdeepseq histFunc ptxs . divideListN (L.length ptxs) $\n xs\n unless\n (L.null filePath)\n (do encodeFile tmpFilePath hist\n copyFile tmpFilePath filePath)\n return hist\n\n-- {-# INLINE runMonteCarloFourierCoefficients #-}\n-- runMonteCarloFourierCoefficients ::\n-- Int\n-- -> Int\n-- -> Int\n-- -> Double\n-- -> Double\n-- -> Double\n-- -> Double\n-- -> [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> Double\n-- -> FilePath\n-- -> Histogram (Complex Double)\n-- -> IO (Histogram (Complex Double))\n-- runMonteCarloFourierCoefficients !numGens !numTrails !batchSize !thetaSigma !scaleSigma !maxScale !tao !phiFreqs !rhoFreqs !thetaFreqs !rFreqs !deltaLog !filePath !initHist = do\n-- when\n-- (maxScale <= 1)\n-- (error $\n-- printf \"runMonteCarloFourierCoefficients error: maxScale(%f) <= 1\" maxScale)\n-- let !thetaDist = normalDistrE 0 thetaSigma\n-- !scaleDist = normalDistrE 0 scaleSigma\n-- pointsGenerator = generatePath thetaDist scaleDist maxScale tao 1\n-- histFunc =\n-- computeFourierCoefficients\n-- phiFreqs\n-- rhoFreqs\n-- thetaFreqs\n-- rFreqs\n-- (log maxScale)\n-- deltaLog\n-- monterCarloHistFunc =\n-- computeHistogramFromMonteCarloParallel\n-- filePath\n-- pointsGenerator\n-- histFunc\n-- addHistogramUnsafe\n-- hist <- runBatch numGens numTrails batchSize monterCarloHistFunc initHist\n-- return hist\n\n\n{-# INLINE runMonteCarloFourierCoefficientsSingleGPU #-}\nrunMonteCarloFourierCoefficientsSingleGPU ::\n Int\n -> Int\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> [Double]\n -> [Double]\n -> [Double]\n -> [Double]\n -> Double -> Double\n -> FilePath\n -> Histogram (Complex Double)\n -> IO (Histogram (Complex Double))\nrunMonteCarloFourierCoefficientsSingleGPU !deviceID !numGens !numTrails !batchSize !thetaSigma !scaleSigma !maxScale !tao !phiFreqs !rhoFreqs !thetaFreqs !rFreqs !deltaLog !initScale !filePath !initHist = do\n when\n (maxScale <= 1)\n (error $\n printf \"runMonteCarloFourierCoefficients error: maxScale(%f) <= 1\" maxScale)\n gen <- createSystemRandom\n initialise []\n dev <- device deviceID\n ctx <- CUDA.create dev []\n ptx <- createTargetFromContext ctx\n let !thetaDist = normalDistrE 0 thetaSigma\n !scaleDist = normalDistrE 0 scaleSigma\n -- !scaleDist = uniformDistrE (- (log maxScale)) (log maxScale)\n !poissonDist = poissonE 0\n !freqArr =\n computeFrequencyArray\n (L.map double2Float phiFreqs)\n (L.map double2Float rhoFreqs)\n (L.map double2Float thetaFreqs)\n (L.map double2Float rFreqs)\n pointsGenerator =\n generatePath\n thetaDist\n scaleDist\n poissonDist\n (maxScale ^ 2)\n maxScale\n tao\n initScale\n 1\n histFuncSingleGPU =\n computeFourierCoefficientsGPU\n phiFreqs\n rhoFreqs\n thetaFreqs\n rFreqs\n (use freqArr)\n (constant . double2Float $ maxScale)\n (constant . double2Float . log $ maxScale)\n ptx\n monterCarloHistFuncSingleGPU =\n computeHistogramFromMonteCarloParallelSingleGPU\n filePath\n pointsGenerator\n histFuncSingleGPU\n addHistogramUnsafe\n deviceID\n hist <-\n runBatch numGens numTrails batchSize monterCarloHistFuncSingleGPU initHist\n -- deepseq hist (destroy ctx)\n return hist\n\n-- {-# INLINE runMonteCarloFourierCoefficientsMultipleGPU #-}\n-- runMonteCarloFourierCoefficientsMultipleGPU ::\n-- [Int]\n-- -> Int\n-- -> Int\n-- -> Int\n-- -> Double\n-- -> Double\n-- -> Double\n-- -> Double\n-- -> [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> [Double]\n-- -> Double\n-- -> Double\n-- -> FilePath\n-- -> Histogram (Complex Double)\n-- -> IO (Histogram (Complex Double))\n-- runMonteCarloFourierCoefficientsMultipleGPU !deviceIDs !numGens !numTrails !batchSize !thetaSigma !scaleSigma !maxScale !tao !phiFreqs !rhoFreqs !thetaFreqs !rFreqs !deltaLog !initScale !filePath !initHist = do\n-- when\n-- (maxScale <= 1)\n-- (error $\n-- printf \"runMonteCarloFourierCoefficients error: maxScale(%f) <= 1\" maxScale)\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 !thetaDist = normalDistrE 0 thetaSigma\n-- !scaleDist = normalDistrE 0 scaleSigma\n-- !freqArr = computeFrequencyArray phiFreqs rhoFreqs thetaFreqs rFreqs\n-- pointsGenerator = generatePath thetaDist scaleDist maxScale tao initScale\n-- histFuncMultipleGPU =\n-- computeFourierCoefficientsGPU\n-- phiFreqs\n-- rhoFreqs\n-- thetaFreqs\n-- rFreqs\n-- (log maxScale)\n-- deltaLog\n-- (use freqArr)\n-- (constant maxScale)\n-- (constant (log maxScale))\n-- (constant (deltaLog :+ 0))\n-- monterCarloHistFuncMultipleGPU =\n-- computeHistogramFromMonteCarloParallelMultipleGPU\n-- filePath\n-- pointsGenerator\n-- histFuncMultipleGPU\n-- addHistogramUnsafe\n-- ptxs\n-- hist <-\n-- runBatch numGens numTrails batchSize monterCarloHistFuncMultipleGPU initHist\n-- deepseq hist (M.mapM destroy ctxs)\n-- return hist\n\n{-# INLINE runMonteCarloFourierCoefficientsGPU #-}\nrunMonteCarloFourierCoefficientsGPU ::\n [Int]\n -> Int\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> [Double]\n -> [Double]\n -> [Double]\n -> [Double]\n -> Double\n -> Double\n -> FilePath\n -> IO (Histogram (Complex Double))\nrunMonteCarloFourierCoefficientsGPU !deviceIDs !numGens !numTrails !batchSize !thetaSigma !scaleLambda !poissonLambda !sigma !tao !deltaT !phiFreqs !rhoFreqs !thetaFreqs !rFreqs !periodEnv !stdR2 !filePath = do\n when\n (periodEnv <= 1)\n (error $\n printf\n \"runMonteCarloFourierCoefficients error: periodEnv(%f) <= 1\"\n periodEnv)\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 !initHist =\n emptyHistogram\n [ L.length phiFreqs\n , L.length rhoFreqs\n , L.length thetaFreqs\n , L.length rFreqs\n ]\n 0\n !thetaDist = normalDistrE 0 (thetaSigma * sqrt deltaT)\n !scaleDist = normalDistrE 0 (scaleLambda * sqrt deltaT)\n !poissonDist = poissonE (poissonLambda / deltaT)\n !freqArr =\n computeFrequencyArray\n (L.map double2Float phiFreqs)\n (L.map double2Float rhoFreqs)\n (L.map double2Float thetaFreqs)\n (L.map double2Float rFreqs)\n !maxRho = sqrt periodEnv / 1 / sqrt 2\n !maxR = sqrt periodEnv / 1 / sqrt 2\n pointsGenerator =\n generatePath\n thetaDist\n scaleDist\n poissonDist\n maxRho\n maxR\n (tao / deltaT)\n deltaT\n stdR2\n -- pointsGenerator =\n -- generatePath'\n -- thetaSigma\n -- scaleDist\n -- poissonLambda\n -- maxRho\n -- maxR\n -- tao\n -- deltaT\n -- stdR2\n -- pointsGenerator =\n -- generatePath' thetaSigma scaleDist poissonLambda periodEnv (tao / deltaT) deltaT\n histFuncSingleGPU =\n computeFourierCoefficientsGPU\n phiFreqs\n rhoFreqs\n thetaFreqs\n rFreqs\n (use freqArr)\n (constant . double2Float $ sigma)\n (constant . double2Float $ log periodEnv)\n monterCarloHistFuncGPU =\n computeHistogramFromMonteCarloParallelMultipleGPU\n filePath\n pointsGenerator\n histFuncSingleGPU\n addHistogramUnsafe\n ptxs\n runBatch numGens numTrails batchSize monterCarloHistFuncGPU initHist\n\n{-# INLINE countR2S1 #-}\ncountR2S1 ::\n GenIO\n -> Double\n -> (Int, Int)\n -> (Int, Int)\n -> Int\n -> [DList Particle]\n -> IO (Histogram Double)\ncountR2S1 randomGen thetaSigma xRange@(!xMin, !xMax) yRange@(!yMin, !yMax) !numOrientations !xs = do\n let !deltaTheta = 2 * pi / (fromIntegral numOrientations)\n ys <-\n fmap\n (L.filter\n (\\((_, x, y), _) ->\n (inRange xRange x) && (inRange yRange y) && (x /= 0 || y /= 0)) .\n L.map\n (\\(Particle phi rho theta' _ _) ->\n let !x = rho * cos phi\n !y = rho * sin phi\n !theta =\n if theta' < 0\n then theta' + 2 * pi\n else theta'\n in ((floor $ theta / deltaTheta, round x, round y), 1)) .\n L.concat) .\n M.mapM\n (\\particle@(Particle phi rho theta r _) -> do\n let delta = 1\n n = Prelude.floor $ r / delta\n zs <-\n M.mapM\n (\\i -> do\n let thetaDist =\n normalDistr\n 0\n (thetaSigma * sqrt (delta * fromIntegral i / r))\n (Particle a b c d _) =\n FokkerPlanck.BrownianMotion.moveParticle\n 1\n (Particle\n phi\n rho\n theta\n (Prelude.fromIntegral i * delta)\n 1)\n deltaThetaDiffusion <- genContVar thetaDist randomGen\n return (Particle a b (c `thetaPlus` deltaThetaDiffusion) d 1))\n [1 .. n - 1]\n return .\n L.concatMap\n (\\(Particle phi' rho' theta' r' v) ->\n [ (Particle phi' rho' theta' r' v)\n , (Particle (-phi') rho' (-theta') r' v)\n ]) $\n (FokkerPlanck.BrownianMotion.moveParticle\n 1\n (Particle phi rho theta r 1)) :\n zs) .\n DL.toList . DL.concat $\n xs\n return .\n Histogram\n [(yMax - yMin + 1), (xMax - xMin + 1), numOrientations]\n (L.length ys) .\n toUnboxedVector .\n UA.accum (+) 0 ((0, xMin, yMin), (numOrientations - 1, xMax, yMax)) $\n ys\n\n{-# INLINE solveMonteCarloR2S1 #-}\nsolveMonteCarloR2S1 ::\n Int\n -> Int\n -> Int\n -> Int\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> FilePath\n -> IO (R.Array U DIM3 Double)\nsolveMonteCarloR2S1 numGens numTrails batchSize xLen yLen numOrientations thetaSigma tao r initSpeed histFilePath = do\n gen <- createSystemRandom\n let !xShift = div xLen 2\n xRange' =\n if odd xLen\n then (-xShift, xShift)\n else (-xShift, xShift - 1)\n !yShift = div yLen 2\n yRange' =\n if odd yLen\n then (-yShift, yShift)\n else (-yShift, yShift - 1)\n thetaDist = normalDistrE 0 thetaSigma\n scaleDist = normalDistrE 0 0\n poissonDist = poissonE 0\n pointsGenerator =\n generatePath\n thetaDist\n scaleDist\n poissonDist\n (r^2)\n r -- (sqrt . fromIntegral $ xLen ^ 2 + yLen ^ 2)\n tao\n initSpeed\n 1\n histFunc = countR2S1 gen thetaSigma xRange' yRange' numOrientations\n monterCarloHistFunc =\n computeHistogramFromMonteCarloParallel\n histFilePath\n pointsGenerator\n histFunc\n addHistogramUnsafe\n hist <-\n runBatch\n numGens\n numTrails\n batchSize\n monterCarloHistFunc\n (emptyHistogram [yLen, xLen, numOrientations] 0)\n return . getNormalizedHistogramArr $ hist\n", "meta": {"hexsha": "b8441bdd686422e85ce7678d740b66d833422f49", "size": 16196, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FokkerPlanck/MonteCarlo.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/MonteCarlo.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/MonteCarlo.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.0268199234, "max_line_length": 213, "alphanum_fraction": 0.5921215115, "num_tokens": 4436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.32470406930137713}} {"text": "{-# LANGUAGE TemplateHaskell\n , TupleSections\n , DeriveGeneric\n , DeriveAnyClass\n , OverloadedLists #-}\nmodule Physics.Collision where\n\nimport Numeric.LinearAlgebra (Vector, Matrix, (<>), scale, dot, cross, (#>))\nimport Control.Lens\nimport Numeric.LinearAlgebra.Data\nimport Data.Vector.Storable (init)\nimport GHC.Generics\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Storable as VS\nimport Data.Function (on)\n\nimport Control.DeepSeq\nimport Utils\nimport Prelude hiding (init)\n\ndata Contact = Contact { _contactPoint :: Vector Float\n , _contactNormal :: Vector Float\n , _penetration :: Float\n , _sign :: Float } deriving Show\n\nmakeLenses ''Contact\n\nmakeContactBasis cont =\n let ys = [0,1,0]\n y2 = [0,0,1]\n x = cont^.contactNormal\n zs = normalize $ cross x ys\n z = if VS.any isNaN zs\n then normalize $ cross x y2\n else zs\n y = normalize $ cross z x\n in fromRows [x,y,z]\n\ndata CollisionData = CollisionData { _contacts :: [Contact]\n , _left :: Int }\n\nmakeLenses ''CollisionData\n\ndata Primitive = Sphere { _radius :: Float\n , _primoffset :: Matrix Float }\n | Plane { _normal :: Vector Float\n , _planeoff :: Float }\n | Box { _points :: V.Vector (Vector Float)\n , _faces :: V.Vector Squad }\n deriving Show\n\ndata PrimitiveComputation = CSphere { _r :: Float\n , _poff :: Vector Float }\n | CPlane { _cnormal :: Vector Float\n , _cplaneoff :: Float}\n | CBox { _cpoints :: V.Vector (Vector Float)\n , _quads :: V.Vector Quad } deriving Show\n\ndata Quad = Quad { _qnorm :: Vector Float\n , _qoff :: Float} deriving Show\n\nquadToCPlane (Quad n o) = CPlane n o\n\ndata Squad = Squad { _snorm :: Vector Float\n , _spoint:: Vector Float } deriving Show\n\nsToQ t (Squad n p) = Quad newN o\n where\n newN = init . (t#>) . flip VS.snoc 0 $ n\n o = dot newN . init . (t#>) . flip VS.snoc 1 $ p\n\npreparePrimitive :: Matrix Float -> Primitive -> PrimitiveComputation\npreparePrimitive t (Sphere r p1) = CSphere r ppos\n where ppos = init . (!!3) . toColumns $ t <> p1\npreparePrimitive t (Box p q) = CBox (V.map adjust p) $ V.map (sToQ t) q\n where adjust = init . (t #>) . flip VS.snoc 1\npreparePrimitive _ (Plane n o) = CPlane n o\n\ntolerance = 0.05\n\nquadDepth (Quad n o) p =\n (dot n p - o, n)\n\nboxPtcoll (CBox _ qs) p cdata =\n let dots = V.map (flip quadDepth p) qs\n (d,n) = V.minimumBy (compare `on` fst) dots\n in if V.any ((>=0) . fst) dots\n then cdata\n else over contacts (Contact p n d 1:) cdata\n\nquadPenetration (Quad n o) = planePenetration (CPlane n o)\n\nplanePenetration (CPlane n o) p cdata =\n let vertDist = dot p n\n cPoint = p -- scale (vertDist - o) n + p\n contact = Contact cPoint n (o - vertDist) 1\n in if cdata^.left > 0 && vertDist <= o + tolerance\n then over contacts (contact:) . over left (subtract 1) $ cdata\n else cdata\n\n-- checkAxe :: Vector Float -> Vector Float -> V.Vector\ncheckAxe pos r ps ix =\n let vals = V.map (VS.!ix) ps\n in (pos VS.! ix + r) >= minimum vals &&\n (pos VS.! ix - r) <= maximum vals\n\ncheckConvexAxe ps1 ps2 ix =\n let vals1 = V.map (VS.! ix) ps1\n vals2 = V.map (VS.! ix) ps2\n in maximum vals1 >= minimum vals2 &&\n minimum vals1 <= maximum vals2\n\naxeList :: [Int]\naxeList = [0,1,2]\n\nseparatingAxes :: PrimitiveComputation -> PrimitiveComputation -> Bool\nseparatingAxes (CSphere r pos) (CBox ps _) = all (checkAxe pos r ps) axeList\nseparatingAxes (CBox ps _) (CSphere r pos) = all (checkAxe pos r ps) axeList\nseparatingAxes (CBox ps _) (CBox ps2 _) = all (checkConvexAxe ps ps2) axeList\n\ndetectCollision prim1 prim2 =\n collisionDetector prim1 prim2 (CollisionData [] 8)\n\nquadSphereCollision (CSphere r p) q@(Quad n o) =\n (dot n p - r - o, n)\n\nquadContact (CSphere r p) (dist, n) =\n let contactPos = p - scale (dist + r) n\n in Contact contactPos n (-dist) 1\n\ncollisionDetector (CSphere r1 pos1) (CSphere r2 pos2) cdata =\n let mid = pos1 - pos2\n midnorm = norm mid\n in if cdata^.left <= 0 || midnorm <= 0.0 || midnorm >= r1 + r2\n then cdata\n else let normal = scale (1/midnorm) mid\n contactPos = pos1 + scale 0.5 mid\n contactPen = r1 + r2 - midnorm\n contact = Contact contactPos normal contactPen 1\n in over contacts (contact:) . over left (subtract 1) $ cdata\ncollisionDetector p@(CPlane _ _) s@(CSphere _ _) cdata =\n set (contacts.traverse.sign) (-1) $\n collisionDetector s p cdata\ncollisionDetector (CSphere r pos1) (CPlane n p2) cdata =\n if cdata^.left <= 0 then cdata\n else let dist = dot n pos1 - r - p2\n in if dist >= 0\n then cdata\n else let contactPos = pos1 - scale (dist + r) n\n contact = Contact contactPos n (-dist) 1\n in over contacts (contact:) cdata\ncollisionDetector (CBox ps _) p@(CPlane _ _) cdata =\n V.foldr (planePenetration p) cdata ps\ncollisionDetector s@(CSphere _ _) b@(CBox _ _) cdata =\n set (contacts.traverse.sign) (-1) $\n collisionDetector b s cdata\ncollisionDetector (CBox _ q) s@(CSphere _ _) cdata =\n let cols = V.map (quadSphereCollision s) q\n best = V.maximumBy (compare `on` fst) cols\n in if V.any ((>=0) . fst) cols\n then cdata\n else over contacts (quadContact s best:) cdata\ncollisionDetector p@(CPlane _ _) b@(CBox _ _) cdata =\n set (contacts.traverse.sign) (-1) $\n collisionDetector b p cdata\ncollisionDetector b1@(CBox ps qs) b2@(CBox ps2 qs2) cdata =\n V.foldr (boxPtcoll b2) (V.foldr (boxPtcoll b1) cdata ps2) ps\ncollisionDetector _ _ cdata = cdata\n", "meta": {"hexsha": "a7c94388c13e2b3e6c4d0e5ada09155b3fa1b09b", "size": 5977, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Physics/Collision.hs", "max_stars_repo_name": "Antystenes/CPG", "max_stars_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Physics/Collision.hs", "max_issues_repo_name": "Antystenes/CPG", "max_issues_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Physics/Collision.hs", "max_forks_repo_name": "Antystenes/CPG", "max_forks_repo_head_hexsha": "9a9e669f30d6816735b5d004cd2ca32bcf2c32bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3668639053, "max_line_length": 80, "alphanum_fraction": 0.6011376945, "num_tokens": 1745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.3225211409730409}} {"text": "{-# language Rank2Types #-}\n{-# language ScopedTypeVariables #-}\n{-# language DataKinds #-}\n{-# language TypeOperators #-}\n{-# language TypeFamilies #-}\n{-# language FlexibleInstances #-}\n{-# language FlexibleContexts #-}\n{-# language MultiParamTypeClasses #-}\n{-# language PolyKinds #-}\n{-# language GADTs #-}\n{-# language ConstraintKinds #-}\n{-# language GeneralizedNewtypeDeriving #-}\n\nmodule Feldspar.Software.Verify.Primitive where\n\nimport Feldspar.Sugar\nimport Feldspar.Representation\nimport Feldspar.Software.Primitive\nimport Feldspar.Software.Expression\nimport Feldspar.Software.Representation hiding (Nil)\nimport Feldspar.Software.Verify.Command\nimport Feldspar.Verify.Arithmetic\n\nimport Feldspar.Verify.Monad (Verify)\nimport qualified Feldspar.Verify.FirstOrder as FO\nimport qualified Feldspar.Verify.Monad as V\nimport qualified Feldspar.Verify.SMT as SMT\nimport qualified Feldspar.Verify.Abstract as A\n\nimport Data.Struct\nimport qualified Data.Map.Strict as Map\n\nimport qualified Control.Monad.RWS.Strict as S\n\nimport qualified SimpleSMT as SMT hiding (not, declareFun)\n\nimport qualified Language.Embedded.Expression as Imp\nimport qualified Language.Embedded.Imperative.CMD as Imp\n\nimport qualified Data.Bits as Bits\nimport qualified Data.Complex as Complex\nimport Data.Constraint hiding (Sub)\nimport Data.Int\nimport Data.Word\nimport Data.Typeable\n\nimport Language.Syntactic\n\nimport GHC.Stack\n\n--------------------------------------------------------------------------------\n-- *\n--------------------------------------------------------------------------------\n\nnewtype Symbolic a = Symbolic { unSymbolic :: Rat }\n deriving (Eq, Ord, Show, V.TypedSExpr, V.SMTOrd)\n\ninstance V.Fresh (Symbolic a)\n where\n fresh = V.freshSExpr\n\nsymbCast :: Symbolic a -> Symbolic b\nsymbCast = Symbolic . unSymbolic\n\nsymbFun :: SymbParam a => String -> [Symbolic a] -> Symbolic a\nsymbFun name (args :: [Symbolic a]) = V.fromSMT $\n SMT.fun (symbType (undefined :: a) ++ \"-\" ++ name) (map V.toSMT args)\n\nfromComplexConstant :: (RealFrac a, SymbParam b) => Complex.Complex a -> Symbolic b\nfromComplexConstant c = symbFun \"complex\" [real, imag]\n where\n real = Symbolic $ fromRational $ toRational $ Complex.realPart c\n imag = Symbolic $ fromRational $ toRational $ Complex.imagPart c\n\n--------------------------------------------------------------------------------\n\ndata SymbFloat\ndata SymbDouble\ndata SymbComplexFloat\ndata SymbComplexDouble\n\nclass SymbParam a\n where\n symbType :: a -> String\n\ninstance SymbParam SymbFloat where symbType _ = \"float\"\ninstance SymbParam SymbDouble where symbType _ = \"double\"\ninstance SymbParam SymbComplexFloat where symbType _ = \"cfloat\"\ninstance SymbParam SymbComplexDouble where symbType _ = \"cdouble\"\n\ninstance SymbParam a => Num (Symbolic a)\n where\n fromInteger = Symbolic . fromInteger\n x + y = symbFun \"+\" [x, y]\n x - y = symbFun \"-\" [x, y]\n x * y = symbFun \"*\" [x, y]\n abs = smtAbs\n signum = smtSignum\n\ninstance SymbParam a => Fractional (Symbolic a) where\n fromRational = Symbolic . fromRational\n x / y = symbFun \"/\" [x, y]\n\ninstance SymbParam a => Floating (Symbolic a) where\n pi = fromRational (toRational pi)\n exp x = symbFun \"exp\" [x]\n log x = symbFun \"log\" [x]\n sqrt x = symbFun \"sqrt\" [x]\n x ** y = symbFun \"pow\" [x, y]\n sin x = symbFun \"sin\" [x]\n cos x = symbFun \"cos\" [x]\n tan x = symbFun \"tan\" [x]\n asin x = symbFun \"asin\" [x]\n acos x = symbFun \"acos\" [x]\n atan x = symbFun \"atan\" [x]\n sinh x = symbFun \"sinh\" [x]\n cosh x = symbFun \"cosh\" [x]\n tanh x = symbFun \"tanh\" [x]\n asinh x = symbFun \"asinh\" [x]\n acosh x = symbFun \"acosh\" [x]\n atanh x = symbFun \"atanh\" [x]\n\n--------------------------------------------------------------------------------\n\nclass Floating a => Complex a\n where\n type RealPart a\n complex :: RealPart a -> RealPart a -> a\n polar :: RealPart a -> RealPart a -> a\n real :: a -> RealPart a\n imag :: a -> RealPart a\n magnitude :: a -> RealPart a\n phase :: a -> RealPart a\n conjugate :: a -> a\n\ninstance Complex (V.SMTExpr Prim (Complex.Complex Float))\n where\n type RealPart (V.SMTExpr Prim (Complex.Complex Float)) = V.SMTExpr Prim Float\n complex (Float x) (Float y) = ComplexFloat (complex x y)\n polar (Float x) (Float y) = ComplexFloat (polar x y)\n real (ComplexFloat x) = Float (real x)\n imag (ComplexFloat x) = Float (imag x)\n magnitude (ComplexFloat x) = Float (magnitude x)\n phase (ComplexFloat x) = Float (phase x)\n conjugate (ComplexFloat x) = ComplexFloat (conjugate x)\n\ninstance Complex (V.SMTExpr Prim (Complex.Complex Double))\n where\n type RealPart (V.SMTExpr Prim (Complex.Complex Double)) = V.SMTExpr Prim Double\n complex (Double x) (Double y) = ComplexDouble (complex x y)\n polar (Double x) (Double y) = ComplexDouble (polar x y)\n real (ComplexDouble x) = Double (real x)\n imag (ComplexDouble x) = Double (imag x)\n magnitude (ComplexDouble x) = Double (magnitude x)\n phase (ComplexDouble x) = Double (phase x)\n conjugate (ComplexDouble x) = ComplexDouble (conjugate x)\n\nwitnessComplex :: (SoftwarePrimType a, SoftwarePrimType (Complex.Complex a)) =>\n Prim (Complex.Complex a) ->\n Dict ( Floating (V.SMTExpr Prim a)\n , Complex (V.SMTExpr Prim (Complex.Complex a))\n , RealPart (V.SMTExpr Prim (Complex.Complex a)) ~ V.SMTExpr Prim a)\nwitnessComplex (_ :: Prim (Complex.Complex a)) =\n case softwareRep :: SoftwarePrimTypeRep (Complex.Complex a) of\n ComplexFloatST -> Dict\n ComplexDoubleST -> Dict\n\nwitnessFractional :: (SoftwarePrimType a, Fractional a) =>\n Prim a ->\n Dict (Floating (V.SMTExpr Prim a))\nwitnessFractional (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of\n FloatST -> Dict\n DoubleST -> Dict\n ComplexFloatST -> Dict\n ComplexDoubleST -> Dict\n\nwitnessIntegral :: (SoftwarePrimType a, Integral a) =>\n Prim a ->\n Dict (Integral (V.SMTExpr Prim a), Bits (V.SMTExpr Prim a))\nwitnessIntegral (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of\n Int8ST -> Dict\n Int16ST -> Dict\n Int32ST -> Dict\n Int64ST -> Dict\n Word8ST -> Dict\n Word16ST -> Dict\n Word32ST -> Dict\n Word64ST -> Dict\n\nwitnessBits :: (SoftwarePrimType a, Bits.Bits a) =>\n Prim a ->\n Dict ( Num a\n , Integral (V.SMTExpr Prim a)\n , Bits (V.SMTExpr Prim a))\nwitnessBits (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of\n Int8ST -> Dict\n Int16ST -> Dict\n Int32ST -> Dict\n Int64ST -> Dict\n Word8ST -> Dict\n Word16ST -> Dict\n Word32ST -> Dict\n Word64ST -> Dict\n\n--------------------------------------------------------------------------------\n\ntoRat :: (SoftwarePrimType a, Fractional a) => V.SMTExpr Prim a -> Rat\ntoRat (x :: V.SMTExpr Prim a) = case softwareRep :: SoftwarePrimTypeRep a of\n FloatST -> let Float (Symbolic y) = x in y\n DoubleST -> let Double (Symbolic y) = x in y\n ComplexFloatST -> let ComplexFloat (Symbolic y) = x in y\n ComplexDoubleST -> let ComplexDouble (Symbolic y) = x in y\n\nfromRat :: forall a. (SoftwarePrimType a, Num a) => Rat -> V.SMTExpr Prim a\nfromRat x = case softwareRep :: SoftwarePrimTypeRep a of Int8ST -> Int8 (f2i x)\n where\n f2i :: forall s w. (Sign s, Width w) => Rat -> BV s w\n f2i (Rat x) = BV $ SMT.List [SMT.fam \"int2bv\" [width (undefined :: w)], SMT.fun \"to_int\" [x]]\n\ni2n :: forall a b.\n ( V.SMTEval Prim a, SoftwarePrimType a, Integral a\n , V.SMTEval Prim b, SoftwarePrimType b, Num b) =>\n V.SMTExpr Prim a ->\n V.SMTExpr Prim b\ni2n x = toBV x $ case softwareRep :: SoftwarePrimTypeRep b of\n Int8ST -> Int8 . i2i\n Int16ST -> Int16 . i2i\n Int32ST -> Int32 . i2i\n Int64ST -> Int64 . i2i\n Word8ST -> Word8 . i2i\n Word16ST -> Word16 . i2i\n Word32ST -> Word32 . i2i\n Word64ST -> Word64 . i2i\n FloatST -> Float . Symbolic . i2f\n DoubleST -> Double . Symbolic . i2f\n ComplexFloatST -> ComplexFloat . Symbolic . i2f\n ComplexDoubleST -> ComplexDouble . Symbolic . i2f\n where\n toBV :: forall a b. (V.SMTEval Prim a, SoftwarePrimType a, Integral a) =>\n V.SMTExpr Prim a -> (forall s w. (Sign s, Width w) => BV s w -> b) -> b\n toBV (x :: V.SMTExpr Prim a) k = case softwareRep :: SoftwarePrimTypeRep a of\n Int8ST -> let Int8 y = x in k y\n Int16ST -> let Int16 y = x in k y\n Int32ST -> let Int32 y = x in k y\n Int64ST -> let Int64 y = x in k y\n Word8ST -> let Word8 y = x in k y\n Word16ST -> let Word16 y = x in k y\n Word32ST -> let Word32 y = x in k y\n Word64ST -> let Word64 y = x in k y\n\n i2f :: (Sign s, Width w) => BV s w -> Rat\n i2f (BV x) = Rat (SMT.fun \"to_real\" [SMT.fun \"bv2int\" [x]])\n\n i2i :: forall s1 w1 s2 w2. (Sign s1, Width w1, Sign s2, Width w2) => BV s1 w1 -> BV s2 w2\n i2i x = case compare m n of\n LT | isSigned x -> V.fromSMT (SMT.signExtend (n-m) (V.toSMT x))\n | otherwise -> V.fromSMT (SMT.zeroExtend (n-m) (V.toSMT x))\n EQ -> V.fromSMT (V.toSMT x)\n GT -> V.fromSMT (SMT.extract (V.toSMT x) (n-1) 0)\n where\n m = width (undefined :: w1)\n n = width (undefined :: w2)\n\n--------------------------------------------------------------------------------\n\nclass SymbParam a => SymbComplex a\n where\n type SymbRealPart a\n\ninstance SymbComplex SymbComplexFloat\n where\n type SymbRealPart SymbComplexFloat = SymbFloat\n\ninstance SymbComplex SymbComplexDouble\n where\n type SymbRealPart SymbComplexDouble = SymbDouble\n\ninstance SymbComplex a => Complex (Symbolic a)\n where\n type RealPart (Symbolic a) = Symbolic (SymbRealPart a)\n complex x y = symbFun \"complex\" [symbCast x, symbCast y]\n polar x y = symbFun \"polar\" [symbCast x, symbCast y]\n real x = symbCast (symbFun \"real\" [x])\n imag x = symbCast (symbFun \"imag\" [x])\n magnitude x = symbCast (symbFun \"magnitude\" [x])\n phase x = symbCast (symbFun \"phase\" [x])\n conjugate x = symbFun \"conjugate\" [x]\n\n--------------------------------------------------------------------------------\n\ndeclareSymbFun :: SymbParam a => String -> a ->\n [SMT.SExpr] -> SMT.SExpr -> SMT.SMT ()\ndeclareSymbFun name (_ :: a) args res =\n S.void $ SMT.declareFun (symbType (undefined :: a) ++ \"-\" ++ name) args res\n\ndeclareSymbArith :: SymbParam a => a -> SMT.SMT ()\ndeclareSymbArith x = do\n declareSymbFun \"+\" x [SMT.tReal, SMT.tReal] SMT.tReal\n declareSymbFun \"-\" x [SMT.tReal, SMT.tReal] SMT.tReal\n declareSymbFun \"*\" x [SMT.tReal, SMT.tReal] SMT.tReal\n declareSymbFun \"/\" x [SMT.tReal, SMT.tReal] SMT.tReal\n declareSymbFun \"exp\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"log\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"sqrt\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"pow\" x [SMT.tReal, SMT.tReal] SMT.tReal\n declareSymbFun \"sin\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"cos\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"tan\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"asin\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"acos\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"atan\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"sinh\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"cosh\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"tanh\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"asinh\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"acosh\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"atanh\" x [SMT.tReal] SMT.tReal\n\ndeclareSymbComplex :: SymbParam a => a -> SMT.SMT ()\ndeclareSymbComplex x = do\n declareSymbArith x\n declareSymbFun \"complex\" x [SMT.tReal, SMT.tReal] SMT.tReal\n declareSymbFun \"polar\" x [SMT.tReal, SMT.tReal] SMT.tReal\n declareSymbFun \"real\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"imag\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"magnitude\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"phase\" x [SMT.tReal] SMT.tReal\n declareSymbFun \"conjugate\" x [SMT.tReal] SMT.tReal\n\ndeclareFeldsparGlobals :: SMT.SMT ()\ndeclareFeldsparGlobals = do\n declareSymbArith (undefined :: SymbFloat)\n declareSymbArith (undefined :: SymbDouble)\n declareSymbComplex (undefined :: SymbComplexFloat)\n declareSymbComplex (undefined :: SymbComplexDouble)\n SMT.declareFun \"skolem-int8\" [] (SMT.tBits 8)\n SMT.declareFun \"skolem-int16\" [] (SMT.tBits 16)\n SMT.declareFun \"skolem-int32\" [] (SMT.tBits 32)\n SMT.declareFun \"skolem-int64\" [] (SMT.tBits 64)\n SMT.declareFun \"skolem-word8\" [] (SMT.tBits 8)\n SMT.declareFun \"skolem-word16\" [] (SMT.tBits 16)\n SMT.declareFun \"skolem-word32\" [] (SMT.tBits 32)\n SMT.declareFun \"skolem-word64\" [] (SMT.tBits 64)\n return ()\n\ninstance FO.Substitute Prim\n where\n type SubstPred Prim = SoftwarePrimType\n subst sub (Prim exp) = Prim (everywhereUp f exp)\n where\n f :: ASTF SoftwarePrimDomain a -> ASTF SoftwarePrimDomain a\n f (Sym (FreeVar x :&: ty)) = case FO.lookupSubst sub (Imp.ValComp x) of\n Imp.ValComp y -> Sym (FreeVar y :&: ty)\n Imp.ValRun z -> Sym (Lit z :&: ty)\n f (Sym (ArrIx iarr :&: ty) :$ i) = Sym (ArrIx iarr' :&: ty) :$ i\n where iarr' = FO.lookupSubst sub iarr\n f x = x\n\ninstance FO.TypeablePred SoftwarePrimType\n where\n witnessTypeable Dict = Dict\n\n--------------------------------------------------------------------------------\n\ninstance V.SMTEval Prim Bool where\n fromConstant = Bool . SMT.bool\n witnessOrd _ = Dict\n\ninstance V.SMTEval Prim Int8 where\n fromConstant = Int8 . fromIntegral\n witnessNum _ = Dict\n witnessOrd _ = Dict\n skolemIndex = V.fromSMT (SMT.fun \"skolem-int8\" [])\n\ninstance V.SMTEval Prim Int16 where\n fromConstant = Int16 . fromIntegral\n witnessNum _ = Dict\n witnessOrd _ = Dict\n skolemIndex = V.fromSMT (SMT.fun \"skolem-int16\" [])\n\ninstance V.SMTEval Prim Int32 where\n fromConstant = Int32 . fromIntegral\n witnessNum _ = Dict\n witnessOrd _ = Dict\n skolemIndex = V.fromSMT (SMT.fun \"skolem-int32\" [])\n\ninstance V.SMTEval Prim Int64 where\n fromConstant = Int64 . fromIntegral\n witnessNum _ = Dict\n witnessOrd _ = Dict\n skolemIndex = V.fromSMT (SMT.fun \"skolem-int64\" [])\n\ninstance V.SMTEval Prim Word8 where\n fromConstant = Word8 . fromIntegral\n witnessNum _ = Dict\n witnessOrd _ = Dict\n skolemIndex = V.fromSMT (SMT.fun \"skolem-word8\" [])\n\ninstance V.SMTEval Prim Word16 where\n fromConstant = Word16 . fromIntegral\n witnessNum _ = Dict\n witnessOrd _ = Dict\n skolemIndex = V.fromSMT (SMT.fun \"skolem-word16\" [])\n\ninstance V.SMTEval Prim Word32 where\n fromConstant = Word32 . fromIntegral\n witnessNum _ = Dict\n witnessOrd _ = Dict\n skolemIndex = V.fromSMT (SMT.fun \"skolem-word32\" [])\n\ninstance V.SMTEval Prim Word64 where\n fromConstant = Word64 . fromIntegral\n witnessNum _ = Dict\n witnessOrd _ = Dict\n skolemIndex = V.fromSMT (SMT.fun \"skolem-word64\" [])\n\ninstance V.SMTEval Prim Float where\n fromConstant = Float . fromRational . toRational\n witnessOrd _ = Dict\n witnessNum _ = Dict\n\ninstance V.SMTEval Prim Double where\n fromConstant = Double . fromRational . toRational\n witnessOrd _ = Dict\n witnessNum _ = Dict\n\ninstance V.SMTEval Prim (Complex.Complex Float) where\n fromConstant = ComplexFloat . fromComplexConstant\n witnessNum _ = Dict\n\ninstance V.SMTEval Prim (Complex.Complex Double) where\n fromConstant = ComplexDouble . fromComplexConstant\n witnessNum _ = Dict\n\n--------------------------------------------------------------------------------\n\ninstance V.SMTEval1 Prim where\n type Pred Prim = SoftwarePrimType\n newtype SMTExpr Prim Bool = Bool SMT.SExpr\n deriving (Typeable)\n newtype SMTExpr Prim Float = Float (Symbolic SymbFloat)\n deriving (Typeable, Num, Fractional, Floating, V.SMTOrd, V.TypedSExpr)\n newtype SMTExpr Prim Double = Double (Symbolic SymbDouble)\n deriving (Typeable, Num, Fractional, Floating, V.SMTOrd, V.TypedSExpr)\n newtype SMTExpr Prim (Complex.Complex Float) =\n ComplexFloat (Symbolic SymbComplexFloat)\n deriving (Typeable, Num, Fractional, Floating, V.TypedSExpr)\n newtype SMTExpr Prim (Complex.Complex Double) =\n ComplexDouble (Symbolic SymbComplexDouble)\n deriving (Typeable, Num, Fractional, Floating, V.TypedSExpr)\n newtype SMTExpr Prim Int8 = Int8 (BV Signed W8)\n deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)\n newtype SMTExpr Prim Int16 = Int16 (BV Signed W16)\n deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)\n newtype SMTExpr Prim Int32 = Int32 (BV Signed W32)\n deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)\n newtype SMTExpr Prim Int64 = Int64 (BV Signed W64)\n deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)\n newtype SMTExpr Prim Word8 = Word8 (BV Unsigned W8)\n deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)\n newtype SMTExpr Prim Word16 = Word16 (BV Unsigned W16)\n deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)\n newtype SMTExpr Prim Word32 = Word32 (BV Unsigned W32)\n deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)\n newtype SMTExpr Prim Word64 = Word64 (BV Unsigned W64)\n deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)\n\n eval (Prim exp :: Prim a) =\n simpleMatch (\\(exp :&: ty) -> case softwarePrimWitType ty of\n Dict -> case V.witnessPred (undefined :: Prim a) of\n Dict -> verifyPrim exp) exp\n\n witnessPred (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of\n BoolST -> Dict\n Int8ST -> Dict\n Int16ST -> Dict\n Int32ST -> Dict\n Int64ST -> Dict\n Word8ST -> Dict\n Word16ST -> Dict\n Word32ST -> Dict\n Word64ST -> Dict\n FloatST -> Dict\n DoubleST -> Dict\n ComplexFloatST -> Dict\n ComplexDoubleST -> Dict\n\ninstance V.SMTOrd (V.SMTExpr Prim Bool) where\n Bool x .<. Bool y = SMT.not x SMT..&&. y\n Bool x .>. Bool y = x SMT..&&. SMT.not y\n Bool x .<=. Bool y = SMT.not x SMT..||. y\n Bool x .>=. Bool y = x SMT..||. SMT.not y\n\ninstance V.TypedSExpr (V.SMTExpr Prim Bool) where\n smtType _ = SMT.tBool\n toSMT (Bool x) = x\n fromSMT x = Bool x\n\n--------------------------------------------------------------------------------\n\nverifyPrim :: forall a .\n (SoftwarePrimType (DenResult a), V.SMTEval Prim (DenResult a), HasCallStack) =>\n SoftwarePrim a ->\n Args (AST SoftwarePrimDomain) a ->\n V.Verify (V.SMTExpr Prim (DenResult a))\nverifyPrim (FreeVar x) _ = peekValue x\nverifyPrim (Lit x) _ = return (V.fromConstant x)\nverifyPrim Add (x :* y :* Nil)\n | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =\n S.liftM2 (+) (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim Sub (x :* y :* Nil)\n | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =\n S.liftM2 (-) (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim Mul (x :* y :* Nil)\n | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =\n S.liftM2 (*) (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim Neg (x :* Nil)\n | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =\n fmap negate (V.eval (Prim x))\nverifyPrim Abs (x :* Nil)\n | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =\n fmap abs (V.eval (Prim x))\nverifyPrim Sign (x :* Nil)\n | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =\n fmap signum (V.eval (Prim x))\nverifyPrim Div (x :* y :* Nil)\n | Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =\n S.liftM2 div (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim Mod (x :* y :* Nil)\n | Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =\n S.liftM2 mod (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim Quot (x :* y :* Nil)\n | Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =\n S.liftM2 quot (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim Rem (x :* y :* Nil)\n | Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =\n S.liftM2 rem (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim FDiv (x :* y :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n S.liftM2 (/) (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim Pi Nil\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n return pi\nverifyPrim Exp (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap exp (V.eval (Prim x))\nverifyPrim Log (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap log (V.eval (Prim x))\nverifyPrim Sqrt (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap sqrt (V.eval (Prim x))\nverifyPrim Pow (x :* y :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n S.liftM2 (**) (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim Sin (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap sin (V.eval (Prim x))\nverifyPrim Cos (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap cos (V.eval (Prim x))\nverifyPrim Tan (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap tan (V.eval (Prim x))\nverifyPrim Asin (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap asin (V.eval (Prim x))\nverifyPrim Acos (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap acos (V.eval (Prim x))\nverifyPrim Atan (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap atan (V.eval (Prim x))\nverifyPrim Sinh (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap sinh (V.eval (Prim x))\nverifyPrim Cosh (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap cosh (V.eval (Prim x))\nverifyPrim Tanh (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap tanh (V.eval (Prim x))\nverifyPrim Asinh (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap asinh (V.eval (Prim x))\nverifyPrim Acosh (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap acosh (V.eval (Prim x))\nverifyPrim Atanh (x :* Nil)\n | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =\n fmap atanh (V.eval (Prim x))\nverifyPrim Complex (x :* y :* Nil)\n | Dict <- witnessComplex (undefined :: Prim (DenResult a)) =\n S.liftM2 complex (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim Polar (x :* y :* Nil)\n | Dict <- witnessComplex (undefined :: Prim (DenResult a)) =\n S.liftM2 polar (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim Real ((x :: ASTF SoftwarePrimDomain b) :* Nil)\n | Dict <- witnessComplex (undefined :: Prim b) =\n fmap real (V.eval (Prim x))\nverifyPrim Imag ((x :: ASTF SoftwarePrimDomain b) :* Nil)\n | Dict <- witnessComplex (undefined :: Prim b) =\n fmap imag (V.eval (Prim x))\nverifyPrim Magnitude ((x :: ASTF SoftwarePrimDomain b) :* Nil)\n | Dict <- witnessComplex (undefined :: Prim b) =\n fmap magnitude (V.eval (Prim x))\nverifyPrim Phase ((x :: ASTF SoftwarePrimDomain b) :* Nil)\n | Dict <- witnessComplex (undefined :: Prim b) =\n fmap phase (V.eval (Prim x))\nverifyPrim Conjugate ((x :: ASTF SoftwarePrimDomain b) :* Nil)\n | Dict <- witnessComplex (undefined :: Prim b) =\n fmap conjugate (V.eval (Prim x))\nverifyPrim I2N ((x :: ASTF SoftwarePrimDomain b) :* Nil)\n | Dict <- V.witnessPred (undefined :: Prim b),\n Dict <- V.witnessNum (undefined :: Prim b) = do\n fmap i2n (V.eval (Prim x))\nverifyPrim I2B ((x :: ASTF SoftwarePrimDomain b) :* Nil)\n | Dict <- V.witnessPred (undefined :: Prim b),\n Dict <- V.witnessNum (undefined :: Prim b) = do\n x <- V.eval (Prim x)\n return (V.fromSMT (SMT.not (x V..==. 0)))\nverifyPrim B2I (x :* Nil)\n | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) = do\n x <- V.eval (Prim x)\n return (V.smtIte (V.toSMT x) 1 0)\nverifyPrim Round ((x :: ASTF SoftwarePrimDomain b) :* Nil) = do\n x <- V.eval (Prim x)\n return (fromRat (toRat x))\nverifyPrim Not (x :* Nil) =\n fmap (V.fromSMT . SMT.not . V.toSMT) (V.eval (Prim x))\nverifyPrim And (x :* y :* Nil) = do\n x <- V.eval (Prim x)\n y <- V.eval (Prim y)\n return (V.fromSMT (V.toSMT x SMT..&&. V.toSMT y))\nverifyPrim Or (x :* y :* Nil) = do\n x <- V.eval (Prim x)\n y <- V.eval (Prim y)\n return (V.fromSMT (V.toSMT x SMT..||. V.toSMT y))\nverifyPrim Eq ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)\n | Dict <- V.witnessPred (undefined :: Prim b) =\n fmap V.fromSMT (S.liftM2 (V..==.) (V.eval (Prim x)) (V.eval (Prim y)))\nverifyPrim Neq ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)\n | Dict <- V.witnessPred (undefined :: Prim b) =\n fmap V.fromSMT (S.liftM2 (./=.) (V.eval (Prim x)) (V.eval (Prim y)))\n where\n x ./=. y = SMT.not (x V..==. y)\nverifyPrim Lt ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)\n | Dict <- V.witnessPred (undefined :: Prim b),\n Dict <- V.witnessOrd (undefined :: Prim b) =\n fmap V.fromSMT (S.liftM2 (V..<.) (V.eval (Prim x)) (V.eval (Prim y)))\nverifyPrim Gt ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)\n | Dict <- V.witnessPred (undefined :: Prim b),\n Dict <- V.witnessOrd (undefined :: Prim b) =\n fmap V.fromSMT (S.liftM2 (V..>.) (V.eval (Prim x)) (V.eval (Prim y)))\nverifyPrim Lte ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)\n | Dict <- V.witnessPred (undefined :: Prim b),\n Dict <- V.witnessOrd (undefined :: Prim b) =\n fmap V.fromSMT (S.liftM2 (V..<=.) (V.eval (Prim x)) (V.eval (Prim y)))\nverifyPrim Gte ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)\n | Dict <- V.witnessPred (undefined :: Prim b),\n Dict <- V.witnessOrd (undefined :: Prim b) =\n fmap V.fromSMT (S.liftM2 (V..>=.) (V.eval (Prim x)) (V.eval (Prim y)))\nverifyPrim BitAnd (x :* y :* Nil)\n | Dict <- witnessBits (undefined :: Prim (DenResult a)) =\n S.liftM2 (.&.) (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim BitOr (x :* y :* Nil)\n | Dict <- witnessBits (undefined :: Prim (DenResult a)) =\n S.liftM2 (.|.) (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim BitXor (x :* y :* Nil)\n | Dict <- witnessBits (undefined :: Prim (DenResult a)) =\n S.liftM2 xor (V.eval (Prim x)) (V.eval (Prim y))\nverifyPrim BitCompl (x :* Nil)\n | Dict <- witnessBits (undefined :: Prim (DenResult a)) =\n fmap complement (V.eval (Prim x))\nverifyPrim ShiftL (x :* (y :: ASTF SoftwarePrimDomain b) :* Nil)\n | Dict <- witnessBits (undefined :: Prim (DenResult a)),\n Dict <- V.witnessPred (undefined :: Prim b),\n Dict <- witnessIntegral (undefined :: Prim b) = do\n -- todo: should check for undefined behaviour\n x <- V.eval (Prim x)\n y <- V.eval (Prim y)\n return (shiftL x (i2n y))\nverifyPrim ShiftR (x :* (y :: ASTF SoftwarePrimDomain b) :* Nil)\n | Dict <- witnessBits (undefined :: Prim (DenResult a)),\n Dict <- V.witnessPred (undefined :: Prim b),\n Dict <- witnessIntegral (undefined :: Prim b) = do\n -- todo: should check for undefined behaviour\n x <- V.eval (Prim x)\n y <- V.eval (Prim y)\n return (shiftR x (i2n y))\nverifyPrim (ArrIx (Imp.IArrComp name :: Imp.IArr Index b)) (i :* Nil) = do\n i <- V.eval (Prim i)\n readArray name i\nverifyPrim Cond (cond :* x :* y :* Nil) =\n S.liftM3 V.smtIte\n (fmap V.toSMT (V.eval (Prim cond)))\n (V.eval (Prim x))\n (V.eval (Prim y))\nverifyPrim exp _ = error (\"Unimplemented: \" ++ show exp)\n\n--------------------------------------------------------------------------------\n", "meta": {"hexsha": "fecf2284ba30b8b1475ff476adc9bc7e0e07780e", "size": 27307, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Feldspar/Software/Verify/Primitive.hs", "max_stars_repo_name": "markus-git/co-feldspar", "max_stars_repo_head_hexsha": "580c693f0c80505ad879e4363c715464c5e04aab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-08-17T13:31:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T14:16:09.000Z", "max_issues_repo_path": "src/Feldspar/Software/Verify/Primitive.hs", "max_issues_repo_name": "markus-git/co-feldspar", "max_issues_repo_head_hexsha": "580c693f0c80505ad879e4363c715464c5e04aab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-05T23:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-12T17:10:33.000Z", "max_forks_repo_path": "src/Feldspar/Software/Verify/Primitive.hs", "max_forks_repo_name": "markus-git/co-feldspar", "max_forks_repo_head_hexsha": "580c693f0c80505ad879e4363c715464c5e04aab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-09-12T13:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-30T14:16:26.000Z", "avg_line_length": 38.8988603989, "max_line_length": 97, "alphanum_fraction": 0.6327681547, "num_tokens": 8589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3223680268951223}} {"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE QuasiQuotes #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n--{-# LANGUAGE MonomorphismRestriction #-}\nmodule Main where\n\nimport DataSources\nimport qualified Frames.Utils as FU\nimport qualified Frames.Folds as FF\nimport qualified Frames.KMeans as KM\nimport qualified Frames.Regression as FR\nimport qualified Frames.MaybeUtils as FM\nimport qualified Frames.VegaLite as FV\nimport qualified Frames.Transform as FT\nimport qualified Frames.Table as Table\nimport qualified Math.Rescale as MR\nimport qualified Frames.MapReduce as MR\n\nimport qualified Knit.Report as K\nimport qualified Knit.Effect.RandomFu as KR\nimport qualified Knit.Effect.Pandoc as K (newPandoc, NamedDoc (..))\nimport qualified Knit.Report.Other.Lucid as KL\n{-\nimport qualified Polysemy as PS\nimport qualified Knit.Effects.Logger as Log\nimport qualified Knit.Effects.PandocMonad as PM\nimport qualified Knit.Effects.Pandoc as PE\nimport Knit.Effects.RandomFu (Random, runRandomIOPureMT)\nimport Knit.Effects.Docs (toNamedDocListWithM)\n--import qualified Knit.Report.Blaze as RB\nimport qualified Knit.Report.Pandoc as RP\nimport qualified Knit.Report.Lucid as RL\n-}\n\nimport qualified Control.Foldl as FL\nimport Control.Monad.IO.Class (MonadIO, liftIO)\nimport Control.Monad (sequence)\nimport Control.Lens ((%~),(^.))\nimport Data.Bool (bool)\nimport qualified Data.Map as M\nimport Data.Maybe (catMaybes, fromJust, fromMaybe)\nimport Data.Monoid ((<>))\nimport qualified Data.Monoid as MO\nimport Data.Proxy (Proxy (..))\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\nimport qualified Data.Text.Lazy as TL\nimport qualified Data.Vector as V\nimport qualified Data.Vinyl as V\nimport qualified Data.Vinyl.Functor as V\nimport qualified Data.Vinyl.Class.Method as V\nimport qualified Data.Vinyl.TypeLevel as V\nimport Data.Vinyl.Lens (type (∈))\nimport Frames ((:.), (&:))\nimport qualified Frames as F\nimport qualified Frames.CSV as F\nimport qualified Frames.Melt as F\nimport qualified Frames.InCore as FI\nimport qualified Frames.TH as F\nimport qualified Graphics.Vega.VegaLite as GV\nimport qualified Pipes as P\nimport qualified Pipes.Prelude as P\nimport qualified Lucid as HL\nimport qualified Text.Blaze.Html.Renderer.Text as BH\nimport Data.Random.Source.PureMT as R\nimport Data.Random as R\nimport qualified System.Clock as C\nimport qualified Statistics.Types as ST\n-- stage restriction means this all has to be up top\nF.tableTypes' (F.rowGen fipsByCountyFP) { F.rowTypeName = \"FIPSByCountyRenamed\", F.columnNames = [\"fips\",\"County\",\"State\"]}\n\ntype CO_AnalysisVERA_Cols = [Year, State, TotalPop, TotalJailAdm, TotalJailPop, TotalPrisonAdm, TotalPrisonPop]\n \njustsFromRec :: V.RMap fs => F.Record fs -> F.Rec (Maybe :. F.ElField) fs\njustsFromRec = V.rmap (V.Compose . Just)\n\nrDiv :: (Real a, Real b, Fractional c) => a -> b -> c\nrDiv a b = realToFrac a/realToFrac b\n\ntype instance FI.VectorFor (Maybe a) = V.Vector\n\ntype DblX = \"X\" F.:-> Double\ntype DblY = \"Y\" F.:-> Double\n\ntemplateVars = M.fromList\n [\n (\"lang\", \"English\")\n , (\"author\", \"Adam Conner-Sax\")\n , (\"pagetitle\", \"Colorado Incarceration Data Analysis\")\n , (\"tufte\",\"True\")\n ]\n\nmain :: IO ()\nmain = do\n -- create streams which are filtered to CO\n let writeNamedHtml (K.NamedDoc n lt) = T.writeFile (T.unpack $ \"analysis/\" <> n <> \".html\") $ TL.toStrict lt\n writeAllHtml = fmap (const ()) . traverse writeNamedHtml\n pandocWriterConfig = K.PandocWriterConfig (Just \"pandoc-templates/minWithVega-pandoc.html\") templateVars K.mindocOptionsF\n startReal <- C.getTime C.Monotonic\n eitherDocs <- K.knitHtmls (Just \"colorado-analysis.Main\") K.logAll pandocWriterConfig $ KR.runRandomIOPureMT (pureMT 1) $ do\n K.logLE K.Info \"Creating data producers from CSV files\"\n let parserOptions = F.defaultParser { F.quotingMode = F.RFC4180Quoting ' ' }\n veraData :: F.MonadSafe m => P.Producer (FM.MaybeRow IncarcerationTrends) m ()\n veraData = F.readTableMaybeOpt F.defaultParser veraTrendsFP P.>-> P.filter (FU.filterOnMaybeField @State (==\"CO\"))\n povertyData :: F.MonadSafe m => P.Producer SAIPE m ()\n povertyData = F.readTableOpt parserOptions censusSAIPE_FP P.>-> P.filter (FU.filterOnField @Abbreviation (== \"CO\"))\n fipsByCountyData :: F.MonadSafe m => P.Producer FIPSByCountyRenamed m ()\n fipsByCountyData = F.readTableOpt parserOptions fipsByCountyFP P.>-> P.filter (FU.filterOnField @State (== \"CO\"))\n -- NB: This data has 2 rows per county, one for misdemeanors, one for felonies\n countyBondCO_Data :: F.MonadSafe m => P.Producer (FM.MaybeRow CountyBondCO) m ()\n countyBondCO_Data = F.readTableMaybeOpt parserOptions countyBondCO_FP\n countyDistrictCO_Data :: F.MonadSafe m => P.Producer CountyDistrictCO m ()\n countyDistrictCO_Data = F.readTableOpt parserOptions countyDistrictCrosswalkCO_FP\n -- This data has 3 rows per county and year, one for each type of crime (against persons, against property, against society)\n crimeStatsCO_Data :: F.MonadSafe m => P.Producer (FM.MaybeRow CrimeStatsCO) m ()\n crimeStatsCO_Data = F.readTableMaybeOpt parserOptions crimeStatsCO_FP\n -- load streams into memory for joins, subsetting as we go\n K.logLE K.Info \"loading producers into memory for joining\"\n fipsByCountyFrame <- liftIO $ F.inCoreAoS $ fipsByCountyData P.>-> P.map (F.rcast @[Fips,County]) -- get rid of state col\n povertyFrame <- liftIO $ F.inCoreAoS $ povertyData P.>-> P.map (F.rcast @[Fips, Year, MedianHI,MedianHIMOE,PovertyR])\n countyBondFrameM <- liftIO $ fmap F.boxedFrame $ F.runSafeEffect $ P.toListM countyBondCO_Data\n veraFrameM <- liftIO $ fmap F.boxedFrame $ F.runSafeEffect $ P.toListM $ veraData P.>-> P.map (F.rcast @[Fips,Year,TotalPop,Urbanicity,IndexCrime])\n countyDistrictFrame <- liftIO $F.inCoreAoS countyDistrictCO_Data\n K.logLE K.Diagnostic $ (T.pack $ show $ FL.fold FL.length fipsByCountyFrame) <> \" rows in fipsByCountyFrame.\"\n K.logLE K.Diagnostic $ (T.pack $ show $ FL.fold FL.length povertyFrame) <> \" rows in povertyFrame.\"\n K.logLE K.Diagnostic $ (T.pack $ show $ FL.fold FL.length countyBondFrameM) <> \" rows in countyBondFrameM.\"\n K.logLE K.Diagnostic $ (T.pack $ show $ FL.fold FL.length veraFrameM) <> \" rows in veraFrameM.\"\n K.logLE K.Diagnostic $ (T.pack $ show $ FL.fold FL.length countyDistrictFrame) <> \" rows in countyDistrictFrame.\"\n -- do joins\n K.logLE K.Info $ \"Doing initial the joins...\"\n let countyBondPlusFIPS = FM.leftJoinMaybe (Proxy @'[County]) countyBondFrameM (justsFromRec <$> fipsByCountyFrame)\n countyBondPlusFIPSAndDistrict = FM.leftJoinMaybe (Proxy @'[County]) (F.boxedFrame countyBondPlusFIPS) (justsFromRec <$> countyDistrictFrame)\n countyBondPlusFIPSAndSAIPE = FM.leftJoinMaybe (Proxy @[Fips, Year]) (F.boxedFrame countyBondPlusFIPSAndDistrict) (justsFromRec <$> povertyFrame)\n countyBondPlusFIPSAndSAIPEAndVera = FM.leftJoinMaybe (Proxy @[Fips, Year]) (F.boxedFrame countyBondPlusFIPSAndSAIPE) veraFrameM \n K.newPandoc \"moneyBondRateAndPovertyRate\" $ kmMoneyBondPctAnalysis countyBondPlusFIPSAndSAIPEAndVera\n K.newPandoc \"moneyBondRateAndCrimeRate\" $ bondVsCrimeAnalysis countyBondCO_Data crimeStatsCO_Data\n endReal <- liftIO $ C.getTime C.Monotonic\n let realTime = C.diffTimeSpec endReal startReal\n printTime (C.TimeSpec s ns) = (T.pack $ show $ realToFrac s + realToFrac ns/(10^9)) \n K.logLE K.Info $ \"Time (real): \" <> printTime realTime <> \"s\" \n return ()\n case eitherDocs of\n Right namedDocs -> writeAllHtml namedDocs\n Left err -> putStrLn $ \"pandoc error: \" ++ show err\n\n-- extra columns we will need\n-- CrimeRate is defined in DataSources since we use it in more places\ntype MoneyBondRate = \"money_bond_rate\" F.:-> Double\ntype PostedBondRate = \"posted_bond_rate\" F.:-> Double\ntype PostedBondPerCapita = \"posted_bond_per_capita\" F.:-> Double\ntype ReoffenseRate = \"reoffense_rate\" F.:-> Double\ntype PostedBondFreq = \"posted_bond_freq\" F.:-> Int\ntype CrimeRateError = \"crime_rate_error\" F.:-> Double\ntype CrimeRateFitted = \"crime_rate_fitted\" F.:-> Double\ntype CrimeRateFittedErr = \"crime_rate_fitted_err\" F.:-> Double\n\n\n-- functions to populate some of those columns from other columns\nmoneyBondRate r = let t = r ^. totalBondFreq in FT.recordSingleton @MoneyBondRate $ bool ((r ^. moneyBondFreq) `rDiv` t) 0 (t == 0) \npostedBondRate r = let t = r ^. totalBondFreq in FT.recordSingleton @PostedBondRate $ bool ((r ^. moneyPosted + r ^. prPosted) `rDiv` t) 0 (t == 0)\npostedBondPerCapita r = FT.recordSingleton @PostedBondPerCapita $ (r ^. moneyPosted + r ^. prPosted) `rDiv` (r ^. estPopulation)\ncRate r = FT.recordSingleton @CrimeRate $ (r ^. crimes) `rDiv` (r ^. estPopulation)\nreoffenseRate r = FT.recordSingleton @ReoffenseRate $ (r ^. moneyNewYes + r ^. prNewYes) `rDiv` (r ^. moneyPosted + r ^. prPosted) \npostedBondFreq r = FT.recordSingleton @PostedBondFreq $ (r ^. moneyPosted + r ^. prPosted)\n\n\nbondVsCrimeAnalysis :: forall effs. ( MonadIO (K.Semantic effs)\n , K.PandocEffects effs\n , K.Member K.ToPandoc effs\n , K.Member KR.Random effs)\n => P.Producer (FM.MaybeRow CountyBondCO) (F.SafeT IO) ()\n -> P.Producer (FM.MaybeRow CrimeStatsCO) (F.SafeT IO) ()\n -> K.Semantic effs ()\nbondVsCrimeAnalysis bondDataMaybeProducer crimeDataMaybeProducer = K.wrapPrefix \"BondRateVsCrimeRate\" $ do\n K.logLE K.Info \"Doing bond rate vs crime rate analysis...\"\n countyBondFrameM <- liftIO $ fmap F.boxedFrame $ F.runSafeT $ P.toListM bondDataMaybeProducer\n let blanksToZeroes :: F.Rec (Maybe :. F.ElField) '[Crimes,Offenses] -> F.Rec (Maybe :. F.ElField) '[Crimes,Offenses]\n blanksToZeroes = FM.fromMaybeMono 0\n -- turn Nothing into 0, sequence the Maybes out, use concat to \"fold\" over those maybes, removing any nothings\n crimeStatsList <- liftIO $ F.runSafeT $ P.toListM $ crimeDataMaybeProducer P.>-> P.map (F.recMaybe . (F.rsubset %~ blanksToZeroes)) P.>-> P.concat\n let sumCrimesFold = FF.sequenceEndoFolds $ FF.FoldEndo FL.sum V.:& FF.FoldEndo FL.sum V.:& FF.FoldEndo (fmap (fromMaybe 0) FL.last) V.:& V.RNil\n foldAllCrimes = MR.concatFold $ MR.hashableMapReduceFold MR.noUnpack (MR.assignKeysAndData @[County, Year] @[Crimes, Offenses, EstPopulation]) (MR.foldAndAddKey sumCrimesFold)\n mergedCrimeStatsFrame = FL.fold foldAllCrimes crimeStatsList\n unmergedCrimeStatsFrame = F.boxedFrame crimeStatsList\n foldAllBonds = MR.concatFold $ MR.hashableMapReduceFold\n (MR.unpackGoodRows @[County,Year,MoneyBondFreq,PrBondFreq,TotalBondFreq,MoneyPosted,PrPosted,MoneyNewYes,PrNewYes])\n (MR.splitOnKeys @[County,Year])\n (MR.foldAndAddKey $ FF.foldAllMonoid @MO.Sum)\n mergedBondDataFrame = FL.fold foldAllBonds countyBondFrameM\n countyBondAndCrimeMerged = F.leftJoin @[County,Year] mergedBondDataFrame mergedCrimeStatsFrame\n countyBondAndCrimeUnmerged = F.leftJoin @[County,Year] mergedBondDataFrame unmergedCrimeStatsFrame\n K.logLE K.Info \"Joined crime data and bond data\" \n K.logLE K.Diagnostic $ (T.pack $ show $ FL.fold FL.length crimeStatsList) <> \" rows in crimeStatsList (unmerged).\"\n K.logLE K.Diagnostic $ (T.pack $ show $ FL.fold FL.length mergedCrimeStatsFrame) <> \" rows in crimeStatsFrame(merged).\"\n let initialCentroidsF n = MR.functionToFoldM (KM.kMeansPPCentroids @DblX @DblY @EstPopulation KM.euclidSq n) \n kmReduce f k rows = sequence $ M.singleton k $ f 10 10 initialCentroidsF (KM.weighted2DRecord @DblX @DblY @EstPopulation) KM.euclidSq rows\n sunCrimeRateF = FL.premap (F.rgetField @CrimeRate) $ MR.scaleAndUnscale (MR.RescaleNormalize 1) (MR.RescaleNone) id\n sunMoneyBondRateF = FL.premap (F.rgetField @MoneyBondRate) $ MR.scaleAndUnscale (MR.RescaleNormalize 1) (MR.RescaleNone) id\n sunPostedBondRateF = FL.premap (F.rgetField @PostedBondRate) $ MR.scaleAndUnscale (MR.RescaleNormalize 1) MR.RescaleNone id \n sunReoffenseRateF = FL.premap (F.rgetField @ReoffenseRate) $ MR.scaleAndUnscale (MR.RescaleNormalize 1) MR.RescaleNone id\n mbrAndCr r = moneyBondRate r F.<+> cRate r \n pbrAndCr r = postedBondRate r F.<+> cRate r\n rorAndMbr r = reoffenseRate r F.<+> moneyBondRate r\n kmMergedCrimeRateVsMoneyBondRateByYear <- do\n K.logLE K.Info \"Doing weighted-KMeans on crime rate vs. money-bond rate (merged crime types).\"\n let unpack = fmap (FT.mutate mbrAndCr) (MR.unpackGoodRows @[Year,County,MoneyBondFreq,TotalBondFreq,Crimes,Offenses,EstPopulation])\n reduce :: _\n reduce = MR.ReduceM $ kmReduce (KM.kMeansOneWithClusters @MoneyBondRate @CrimeRate @EstPopulation sunMoneyBondRateF sunCrimeRateF)\n kmFoldM = MR.concatFoldM $ MR.hashableMapReduceFoldM (MR.generalizeUnpack unpack) (MR.generalizeAssign $ MR.assignKeys @'[Year]) reduce\n flip FL.foldM countyBondAndCrimeMerged $\n fmap (KM.clusteredRows @MoneyBondRate @CrimeRate @EstPopulation (F.rgetField @County)) $ kmFoldM\n kmCrimeRateVsMoneyBondRateByYearAndType <- do\n K.logLE K.Info \"Doing weighted-KMeans on crime rate vs. money-bond rate (separate crime types).\"\n let unpack = fmap (FT.mutate mbrAndCr) (MR.unpackGoodRows @[Year,County,CrimeAgainst,MoneyBondFreq,TotalBondFreq,Crimes,Offenses,EstPopulation])\n reduce :: _\n reduce = MR.ReduceM $ kmReduce (KM.kMeansOneWithClusters @MoneyBondRate @CrimeRate @EstPopulation sunMoneyBondRateF sunCrimeRateF)\n kmFoldM = MR.concatFoldM $ MR.hashableMapReduceFoldM (MR.generalizeUnpack unpack) (MR.generalizeAssign $ MR.assignKeys @'[Year, CrimeAgainst]) reduce \n flip FL.foldM countyBondAndCrimeUnmerged $\n fmap (KM.clusteredRows @MoneyBondRate @CrimeRate @EstPopulation (F.rgetField @County)) $ kmFoldM\n kmMergedCrimeRateVsPostedBondRateByYear <- do\n K.logLE K.Info \"Doing weighted-KMeans on crime rate vs. posted-bond rate (merged).\"\n let unpack = fmap (FT.mutate pbrAndCr) (MR.unpackGoodRows @[Year,County,TotalBondFreq,MoneyPosted,PrPosted,Crimes,Offenses,EstPopulation])\n reduce :: _ \n reduce = MR.ReduceM $ kmReduce (KM.kMeansOneWithClusters @PostedBondRate @CrimeRate @EstPopulation sunPostedBondRateF sunCrimeRateF)\n kmFoldM = MR.concatFoldM $ MR.hashableMapReduceFoldM (MR.generalizeUnpack unpack) (MR.generalizeAssign $ MR.assignKeys @'[Year]) reduce \n flip FL.foldM countyBondAndCrimeMerged $\n fmap (KM.clusteredRows @PostedBondRate @CrimeRate @EstPopulation (F.rgetField @County)) $ kmFoldM\n kmCrimeRateVsPostedBondRateByYearAndType <- do \n K.logLE K.Info \"Doing weighted-KMeans on crime rate vs. posted-bond rate (unmerged).\" \n let unpack = fmap (FT.mutate pbrAndCr) (MR.unpackGoodRows @[Year,County,CrimeAgainst,TotalBondFreq,MoneyPosted,PrPosted,Crimes,Offenses,EstPopulation])\n reduce :: _\n reduce = MR.ReduceM $ kmReduce (KM.kMeansOneWithClusters @PostedBondRate @CrimeRate @EstPopulation sunPostedBondRateF sunCrimeRateF)\n kmFoldM = MR.concatFoldM $ MR.hashableMapReduceFoldM (MR.generalizeUnpack unpack) (MR.generalizeAssign $ MR.assignKeys @'[Year,CrimeAgainst]) reduce \n flip FL.foldM countyBondAndCrimeUnmerged $\n fmap (KM.clusteredRows @PostedBondRate @CrimeRate @EstPopulation (F.rgetField @County)) $ kmFoldM\n kmReoffenseRateVsMergedMoneyBondRateByYear <- do\n K.logLE K.Info \"Doing weighted-KMeans on re-offense rate vs. money-bond rate (merged).\" \n let unpack = fmap (FT.mutate rorAndMbr) (MR.unpackGoodRows @[Year, County, MoneyNewYes, PrNewYes, MoneyPosted, PrPosted, TotalBondFreq, MoneyBondFreq, EstPopulation])\n reduce :: _\n reduce = MR.ReduceM $ kmReduce (KM.kMeansOneWithClusters @MoneyBondRate @ReoffenseRate @EstPopulation sunMoneyBondRateF sunReoffenseRateF)\n kmFoldM = MR.concatFoldM $ MR.hashableMapReduceFoldM (MR.generalizeUnpack unpack) (MR.generalizeAssign $ MR.assignKeys @'[Year]) reduce \n flip FL.foldM countyBondAndCrimeMerged $\n fmap (KM.clusteredRows @MoneyBondRate @ReoffenseRate @EstPopulation (F.rgetField @County)) $ kmFoldM\n -- regressions\n let rMut r = mbrAndCr r F.<+> postedBondFreq r F.<+> postedBondRate r F.<+> postedBondPerCapita r\n (rData, regressionRes, regressionResMany) <- do\n let regUnpack = fmap (FT.mutate rMut) $ (MR.unpackGoodRows @[Year,MoneyBondFreq,PrBondFreq,PrPosted,MoneyPosted,TotalBondFreq,Crimes,EstPopulation])\n-- regReduce :: Foldable f => (forall g. Foldable g => g (F.Record rs) -> PS.Semantic effs b) -> k -> f (F.Record rs) -> PS.Semantic effs (M.Map k b)\n\n regMR r = MR.concatFoldM $ MR.hashableMapReduceFoldM (MR.generalizeUnpack regUnpack) (MR.generalizeAssign $ MR.assignKeys @'[Year]) r --(MR.ReduceM $ regReduce r)\n dataMR = MR.unpackOnlyFoldM (MR.generalizeUnpack regUnpack)\n guess = [0,0] -- guess has one extra dimension for constant\n regressOneBM = MR.functionToFoldM $ return . FR.leastSquaresByMinimization @Crimes @'[EstPopulation, MoneyBondFreq] False guess\n regressOneOLS = MR.functionToFoldM $ FR.ordinaryLeastSquares @effs @Crimes @False @'[EstPopulation]\n regressOneWLS = MR.functionToFoldM $ FR.popWeightedLeastSquares @effs @CrimeRate @True @'[] @EstPopulation \n regressOneWLS2 = MR.functionToFoldM $ FR.varWeightedLeastSquares @effs @Crimes @False @'[EstPopulation, PostedBondFreq] @EstPopulation \n regressOneWTLS = MR.functionToFoldM $ FR.varWeightedTLS @effs @Crimes @False @'[EstPopulation, PostedBondFreq] @EstPopulation\n regReduceF r k = fmap (M.singleton k) r\n allMR = (,,,,,) <$> dataMR\n <*> (regMR $ MR.ReduceFoldM $ regReduceF regressOneBM)\n <*> (regMR $ MR.ReduceFoldM $ regReduceF regressOneOLS)\n <*> (regMR $ MR.ReduceFoldM $ regReduceF regressOneWLS)\n <*> (regMR $ MR.ReduceFoldM $ regReduceF regressOneWLS2)\n <*> (regMR $ MR.ReduceFoldM $ regReduceF regressOneWTLS) \n K.logLE K.Info \"Regressing Crime Rate on Money Bond Rate\"\n (rData, r1, r2,r3,r4,r5) <- FL.foldM allMR countyBondAndCrimeMerged\n-- K.logLE K.Info $ \"regression (by minimization) results: \" <> (T.pack $ show $ fmap (flip FR.prettyPrintRegressionResult 0.95) r1)\n K.logLE K.Info $ \"regression (by OLS) results: \" <> FR.prettyPrintRegressionResults FR.keyRecordText (M.toList r2) ST.cl95 FR.prettyPrintRegressionResult \"\\n\"\n K.logLE K.Info $ \"regression (rates by pop weighted LS) results: \" <> FR.prettyPrintRegressionResults FR.keyRecordText (M.toList r3) ST.cl95 FR.prettyPrintRegressionResult \"\\n\"\n K.logLE K.Info $ \"regression (counts by inv sqrt pop weighted LS) results: \" <> FR.prettyPrintRegressionResults FR.keyRecordText (M.toList r4) ST.cl95 FR.prettyPrintRegressionResult \"\\n\"\n K.logLE K.Info $ \"regression (counts by TLS) results: \" <> FR.prettyPrintRegressionResults FR.keyRecordText (M.toList r5) ST.cl95 FR.prettyPrintRegressionResult \"\\n\"\n let rData2016 = F.filterFrame ((== 2016) . F.rgetField @Year) $ F.toFrame rData\n regressionR = fromJust $ M.lookup (FT.recordSingleton @Year 2016) r4\n return $ (rData2016, regressionR, r4) \n-- K.log K.Info $ \"data=\\n\" <> Table.textTable rData\n \n K.logLE K.Info \"Creating Doc\"\n K.addLucid $ do\n HL.h1_ \"Colorado Money Bond Rate vs Crime rate\" \n KL.placeTextSection $ do\n HL.h2_ \"Colorado Bond Rates and Crime Rates (preliminary)\"\n HL.p_ [HL.class_ \"subtitle\"] \"Adam Conner-Sax\"\n HL.p_ \"Each county in Colorado issues money bonds and personal recognizance bonds. For each county I look at the % of money bonds out of all bonds issued and the crime rate. We have 3 years of data and there are 64 counties in Colorado (each with vastly different populations). So I've used a population-weighted k-means clustering technique (see notes below) to reduce the number of points to at most 10 per year. Each circle in the plot below represents one cluster of counties with similar money bond and poverty rates. The size of the circle represents the total population in the cluster.\"\n KL.placeVisualization \"crimeRateVsMoneyBondRateMerged\" $ cRVsMBRVL True kmMergedCrimeRateVsMoneyBondRateByYear \n HL.p_ \"Broken down by Colorado's crime categories:\"\n KL.placeVisualization \"crimeRateVsMoneyBondRateUnMerged\" $ cRVsMBRVL False kmCrimeRateVsMoneyBondRateByYearAndType\n KL.placeTextSection $ do\n HL.p_ \"Notes:\"\n HL.ul_ $ do\n HL.li_ $ do\n HL.span_ \"Money Bond Rate is (number of money bonds/total number of bonds). That data comes from \"\n HL.a_ [HL.href_ \"https://github.com/Data4Democracy/incarceration-trends/blob/master/Colorado_ACLU/4-money-bail-analysis/complete-county-bond.csv\"] \"complete-county-bond.csv\"\n HL.span_ \". NB: Bond rates are not broken down by crime type because they are not broken down in the data we have.\"\n HL.li_ $ do\n HL.span_ \"Crime Rate is crimes/estimated_population. Those numbers come from the Colorado crime statistics \"\n HL.a_ [HL.href_ \"https://coloradocrimestats.state.co.us/\"] \"web-site\"\n HL.span_ \". We also have some of that data in the \"\n HL.a_ [HL.href_ \"https://github.com/Data4Democracy/incarceration-trends/blob/master/Colorado_ACLU/4-money-bail-analysis/crime-rate-bycounty.csv\"] \"repo\"\n HL.span_ \", but only for 2016, so I re-downloaded it for this. Also, there are some crimes in that data that don't roll up to a particular county but instead are attributed to the Colorado Bureau of Investigation or the Colorado State Patrol. I've ignored those.\"\n KL.placeTextSection $ do\n HL.p_ \"Below I look at the percentage of all bonds which are \\\"posted\\\" (posting bond means paying the money bond or agreeing to the terms of the personal recognizance bond ?) rather than the % of money bonds. I use the same clustering technique.\"\n KL.placeVisualization \"crimeRateVsPostedBondRate\" $ cRVsPBRVL True kmMergedCrimeRateVsPostedBondRateByYear\n HL.p_ \"Broken down by Colorado's crime categories:\"\n KL.placeVisualization \"crimeRateVsPostedBondRateUnMerged\" $ cRVsPBRVL False kmCrimeRateVsPostedBondRateByYearAndType\n KL.placeTextSection $ do\n HL.p_ \"Notes:\"\n HL.ul_ $ do\n HL.li_ $ do\n HL.span_ \"Posted Bond Rate is [(number of posted money bonds + number of posted PR bonds)/total number of bonds] where that data comes from \"\n HL.a_ [HL.href_ \"https://github.com/Data4Democracy/incarceration-trends/blob/master/Colorado_ACLU/4-money-bail-analysis/complete-county-bond.csv\"] \"complete-county-bond.csv.\"\n HL.li_ $ do\n HL.span_ \"Crime Rate, as above, is crimes/estimated_population where those numbers come from the Colorado crime statistics \"\n HL.a_ [HL.href_ \"https://coloradocrimestats.state.co.us/\"] \"web-site.\"\n HL.p_ \"Below I look at the rate of re-offending among people out on bond, here considered in each county along with money-bond rate and clustered as above.\" \n KL.placeVisualization \"reoffenseRateVsMoneyBondRate\" $ rRVsMBRVL True kmReoffenseRateVsMergedMoneyBondRateByYear\n KL.placeTextSection $ do\n HL.p_ \"Notes:\"\n HL.ul_ $ do\n HL.li_ $ do\n HL.span_ \"Reoffense Rate is (number of new offenses for all bonds/total number of posted bonds) where that data comes from \"\n HL.a_ [HL.href_ \"https://github.com/Data4Democracy/incarceration-trends/blob/master/Colorado_ACLU/4-money-bail-analysis/complete-county-bond.csv\"] \"complete-county-bond.csv.\"\n\n KL.placeTextSection $ do\n HL.h2_ \"Regressions\"\n HL.p_ \"We can use linear regression to investigate the relationship between Crime Rate and the use of money and personal recognizance bonds. We begin by finding a best fit (using population-weighted least squares) to the model \"\n KL.latex_ \"$c_i = cr (p_{i}) + A (pb_{i}) + e_{i}$\" \n HL.p_ \"where, for each county (denoted by the subscipt i), c is the number of crimes, p is the population and pb is the number of posted bonds and e is an error term we seek to minimize. We look at the result for each of the years in the data:\"\n KL.placeVisualization \"regresssionCoeffs\" $ FV.regressionCoefficientPlotMany (T.pack . show . F.rgetField @Year) \"Regression Results (by year)\" [\" cr\",\"A\"] (M.toList (fmap FR.regressionResult regressionResMany)) ST.cl95\n HL.p_ \"We look at these regressions directly by overlaying this model on the data itself:\"\n-- H.placeVisualization \"regresssionScatter\" $ FV.scatterWithFit @PostedBondPerCapita @CrimeRate errF (FV.FitToPlot \"WLS regression\" fitF) \"test scatter with fit\" rData\n-- H.placeVisualization \"regresssionScatter\" $ FV.scatterWithFit @PostedBondPerCapita @CrimeRate errF (FV.FitToPlot \"WLS regression\" fitF) \"test scatter with fit\" rData\n KL.placeVisualization \"regresssionScatter\" $ FV.frameScatterWithFit \"test scatter with fit\" (Just \"WLS\") regressionRes ST.cl95 rData\n kMeansNotes\n-- liftIO $ T.writeFile \"analysis/moneyBondRateAndCrimeRate.html\" $ TL.toStrict $ htmlAsText\n\ncRVsMBRVL mergedOffenseAgainst dataRecords =\n let dat = FV.recordsToVLData (transformF @MoneyBondRate (*100) . transformF @CrimeRate (*100)) dataRecords\n ptEnc = GV.color [FV.mName @Year, GV.MmType GV.Nominal]\n . GV.size [FV.mName @EstPopulation, GV.MmType GV.Quantitative, GV.MLegend [GV.LTitle \"population\"]]\n in case mergedOffenseAgainst of\n True ->\n let vlF = FV.clustersWithClickIntoVL @MoneyBondRate @CrimeRate @KM.IsCentroid @KM.ClusterId @KM.MarkLabel @'[Year] \n in vlF \"Money Bond Rate (%, All Crimes)\" \"Crime Rate (%, All Crimes)\" \"Crime Rate vs Money Bond Rate\" ptEnc id id id dat\n False ->\n let ptEncFaceted = ptEnc\n . GV.row [FV.fName @CrimeAgainst, GV.FmType GV.Nominal,GV.FHeader [GV.HTitle \"Crime Against\"]]\n vlF = FV.clustersWithClickIntoVL @MoneyBondRate @CrimeRate @KM.IsCentroid @KM.ClusterId @KM.MarkLabel @[Year,CrimeAgainst]\n in vlF \"Money Bond Rate (%, All Crimes)\" \"Crime Rate (%)\" \"Crime Rate vs Money Bond Rate\" ptEncFaceted id id id dat\n\ncRVsPBRVL mergedOffenseAgainst dataRecords =\n let dat = FV.recordsToVLData (transformF @PostedBondRate (*100) . transformF @CrimeRate (*100)) dataRecords\n ptEnc = GV.color [FV.mName @Year, GV.MmType GV.Nominal]\n . GV.size [FV.mName @EstPopulation, GV.MmType GV.Quantitative, GV.MLegend [GV.LTitle \"population\"]]\n in case mergedOffenseAgainst of\n True ->\n let vlF = FV.clustersWithClickIntoVL @PostedBondRate @CrimeRate @KM.IsCentroid @KM.ClusterId @KM.MarkLabel @'[Year] \n in vlF \"Posted Bond Rate (%, All Crimes)\" \"Crime Rate (%, All Crimes)\" \"Crime Rate vs Posted Bond Rate\" ptEnc id id id dat\n False ->\n let ptEncFaceted = ptEnc\n . GV.row [FV.fName @CrimeAgainst, GV.FmType GV.Nominal,GV.FHeader [GV.HTitle \"Crime Against\"]]\n vlF = FV.clustersWithClickIntoVL @PostedBondRate @CrimeRate @KM.IsCentroid @KM.ClusterId @KM.MarkLabel @[Year,CrimeAgainst]\n in vlF \"Posted Bond Rate (%, All Crimes)\" \"Crime Rate (%)\" \"Crime Rate vs Posted Bond Rate\" ptEncFaceted id id id dat\n\nrRVsMBRVL mergedOffenseAgainst dataRecords =\n let dat = FV.recordsToVLData (transformF @MoneyBondRate (*100) . transformF @ReoffenseRate (*100)) dataRecords\n ptEnc = GV.color [FV.mName @Year, GV.MmType GV.Nominal]\n . GV.size [FV.mName @EstPopulation, GV.MmType GV.Quantitative, GV.MLegend [GV.LTitle \"population\"]]\n in case mergedOffenseAgainst of\n True ->\n let vlF = FV.clustersWithClickIntoVL @MoneyBondRate @ReoffenseRate @KM.IsCentroid @KM.ClusterId @KM.MarkLabel @'[Year] \n in vlF \"Money Bond Rate (%, All Crimes)\" \"Reoffense Rate (%, All Crimes)\" \"Reoffense Rate vs Money Bond Rate\" ptEnc id id id dat\n False ->\n let ptEncFaceted = ptEnc\n . GV.row [FV.fName @CrimeAgainst, GV.FmType GV.Nominal,GV.FHeader [GV.HTitle \"Crime Against\"]]\n vlF = FV.clustersWithClickIntoVL @MoneyBondRate @CrimeRate @KM.IsCentroid @KM.ClusterId @KM.MarkLabel @[Year,CrimeAgainst]\n in vlF \"Money Bond Rate (%, All Crimes)\" \"Reoffense Rate (%)\" \"Reoffense Rate vs Money Bond Rate\" ptEncFaceted id id id dat\n\n \n-- NB: The data has two rows for each county and year, one for misdemeanors and one for felonies.\n--type MoneyPct = \"moneyPct\" F.:-> Double --F.declareColumn \"moneyPct\" ''Double\nkmMoneyBondPctAnalysis :: _\nkmMoneyBondPctAnalysis joinedData = K.wrapPrefix \"MoneyBondVsPoverty\" $ do\n K.logLE K.Info \"Doing money bond % vs poverty rate analysis...\"\n let sunPovertyRF = FL.premap (F.rgetField @PovertyR) $ MR.scaleAndUnscale (MR.RescaleNormalize 1) MR.RescaleNone id\n sunMoneyBondRateF = FL.premap (F.rgetField @MoneyBondRate) $ MR.scaleAndUnscale (MR.RescaleNormalize 1) MR.RescaleNone id\n initialCentroids = KM.kMeansPPCentroids @DblX @DblY @TotalPop KM.euclidSq\n unpack = fmap (FT.mutate moneyBondRate) $ MR.unpackGoodRows @[Year,County,OffType,Urbanicity,PovertyR, MoneyBondFreq,TotalBondFreq,TotalPop]\n reduce :: _\n reduce = MR.ReduceM $ \\_ -> KM.kMeansOne @PovertyR @MoneyBondRate @TotalPop sunPovertyRF sunMoneyBondRateF 5 initialCentroids (KM.weighted2DRecord @DblX @DblY @TotalPop) KM.euclidSq\n toRec (x, y, z) = (x F.&: y F.&: z F.&: V.RNil) :: F.Record [PovertyR, MoneyBondRate, TotalPop]\n kmByYearF = MR.concatFoldM $ MR.hashableMapReduceFoldM\n (MR.generalizeUnpack unpack)\n (MR.generalizeAssign $ MR.assignKeysAndData @[Year, OffType] @[PovertyR, MoneyBondRate, TotalPop])\n (MR.makeRecsWithKeyM toRec reduce)\n kmByYearUrbF = MR.concatFoldM $ MR.hashableMapReduceFoldM\n (MR.generalizeUnpack unpack)\n (MR.generalizeAssign $ MR.assignKeysAndData @'[Year, OffType, Urbanicity] @[PovertyR, MoneyBondRate, TotalPop])\n (MR.makeRecsWithKeyM toRec reduce)\n (kmByYear, kmByYearUrb) <- FL.foldM ((,) <$> kmByYearF <*> kmByYearUrbF) joinedData\n{- (kmByYear, kmByYearUrb) <- FL.foldM ((,)\n <$> KM.kMeans @[Year, OffType] @PovertyR @MoneyBondRate @TotalPop sunPovertyRF sunMoneyBondRateF 5 (KM.kMeansPPCentroids KM.euclidSq) KM.euclidSq\n <*> KM.kMeans @[Year, OffType, Urbanicity] @PovertyR @MoneyBondRate @TotalPop sunPovertyRF sunMoneyBondRateF 5 (KM.kMeansPPCentroids KM.euclidSq) KM.euclidSq) kmData -}\n K.logLE K.Info \"Creating Doc\"\n K.addLucid $ do\n HL.h1_ \"Colorado Money Bonds and Poverty\" \n KL.placeTextSection $ do\n HL.h2_ \"Colorado Money Bond Rate and Poverty (preliminary)\"\n HL.p_ [HL.class_ \"subtitle\"] \"Adam Conner-Sax\"\n HL.p_ \"Colorado issues two types of bonds when releasing people from jail before trial. Sometimes people are released on a \\\"money bond\\\" and sometimes on a personal recognizance bond. We have county-level data of all bonds (?) issued in 2014, 2015 and 2016. Plotting it all is very noisy (since there are 64 counties in CO) so we use a population-weighted k-means clustering technique to combine similar counties into clusters. In the plots below, each circle represents one cluster of counties and the circle's size represents the total population of all the counties included in the cluster. We consider felonies and misdemeanors separately.\"\n KL.placeVisualization \"mBondsVspRateByYrFelonies\" $ moneyBondPctVsPovertyRateVL False kmByYear\n KL.placeTextSection $ HL.h3_ \"Broken down by \\\"urbanicity\\\":\"\n KL.placeVisualization \"mBondsVspRateByYrUrbFelonies\" $ moneyBondPctVsPovertyRateVL True kmByYearUrb\n KL.placeTextSection $ do\n HL.p_ \"Notes:\"\n HL.ul_ $ do\n HL.li_ \"Denver, the only urban county in CO, didn't report misdemeanors in this data, so the last plot is blank.\"\n HL.li_ $ do\n HL.span_ \"Money Bond Rate is (number of money bonds/total number of bonds). That data comes from \"\n HL.a_ [HL.href_ \"https://github.com/Data4Democracy/incarceration-trends/blob/master/Colorado_ACLU/4-money-bail-analysis/complete-county-bond.csv\"] \"complete-county-bond.csv.\"\n HL.li_ $ do\n HL.span_ \"Poverty Rate comes from the census and we have that data in \"\n HL.a_ [HL.href_ \"https://github.com/Data4Democracy/incarceration-trends/blob/master/Colorado_ACLU/4-money-bail-analysis/complete-county-bond-SAIPE.csv\"] \"complete-county-bond-SAIPE.csv\"\n HL.span_ \". That data originates from the \"\n HL.a_ [HL.href_ \"https://www.census.gov/programs-surveys/saipe.html\"] \"SAIPE website\"\n HL.span_ \" at the census bureau.\"\n HL.li_ $ do\n HL.span_ \"Urbanicity classification comes from the \"\n HL.a_ [HL.href_ \"https://www.vera.org/projects/incarceration-trends\"] \"VERA\"\n HL.span_ \" data. In the repo \"\n HL.a_ [HL.href_ \"https://github.com/Data4Democracy/incarceration-trends/blob/master/Colorado_ACLU/4-money-bail-analysis/county_bond_saipe_vera_data.csv\"] \"here.\"\n kMeansNotes\n-- liftIO $ T.writeFile \"analysis/moneyBondRateAndPovertyRate.html\" $ TL.toStrict $ htmlAsText\n\nmoneyBondPctVsPovertyRateVL facetByUrb dataRecords =\n let dat = FV.recordsToVLData (transformF @MoneyBondRate (*100)) dataRecords\n enc = GV.encoding\n . GV.position GV.X [FV.pName @PovertyR, GV.PmType GV.Quantitative, GV.PAxis [GV.AxTitle \"Poverty Rate (%)\"]]\n . GV.position GV.Y [FV.pName @MoneyBondRate, GV.PmType GV.Quantitative, GV.PAxis [GV.AxTitle \"% Money Bonds\"]]\n . GV.color [FV.mName @Year, GV.MmType GV.Nominal]\n . GV.size [FV.mName @TotalPop, GV.MmType GV.Quantitative, GV.MLegend [GV.LTitle \"population\"]]\n . GV.row [FV.fName @OffType, GV.FmType GV.Nominal, GV.FHeader [GV.HTitle \"Type of Offense\"]]\n . if facetByUrb then GV.column [FV.fName @Urbanicity, GV.FmType GV.Nominal] else id\n sizing = if facetByUrb\n then [GV.autosize [GV.AFit, GV.AResize]]\n else [GV.autosize [GV.AFit], GV.height 300, GV.width 700]\n vl = GV.toVegaLite $\n [ GV.description \"Vega-Lite Attempt\"\n , GV.title (\"% of money bonds (out of money and personal recognizance bonds) vs poverty rate in CO\")\n , GV.background \"white\"\n , GV.mark GV.Point []\n , enc []\n , dat] <> sizing\n in vl\n\nkMeansNotes = KL.placeTextSection $ do\n HL.h3_ \"Some notes on weighted k-means\"\n HL.ul_ $ do\n HL.li_ $ do\n HL.a_ [HL.href_ \"https://en.wikipedia.org/wiki/K-means_clustering\"] \"k-means\"\n HL.span_ \" works by choosing random starting locations for cluster centers, assigning each data-point to the nearest cluster center, moving the center of each cluster to the weighted average of the data-points assigned to the same cluster and then repeating until no data-points move to a new cluster.\"\n HL.li_ \"How do you define distance between points? Each axis has a different sort of data and it's not clear how to combine differences in each into a meanignful overall distance. Here, before we hand the data off to the k-means algorithm, we shift and rescale the data so that the set of points has mean 0 and std-deviation 1 in each variable. Then we use ordinary Euclidean distance, that is the sum of the squares of the differences in each coordinate. Before plotting, we reverse that scaling so that we can visualize the data in the original. This attempts to give the two variables equal weight in determining what \\\"nearby\\\" means for these data points.\"\n HL.li_ \"This clustering happens for each combination plotted.\"\n HL.li_ $ do\n HL.span_ \"k-means is sensitive to the choice of starting points. Here we use the \\\"k-means++\\\" method. This chooses one of the data points as a starting point. Then chooses among the remaining points in a way designed to make it likely that the initial centers are widely dispersed. See \"\n HL.a_ [HL.href_ \"https://en.wikipedia.org/wiki/K-means%2B%2B\"] \"here\"\n HL.span_ \" for more information. We repeat the k-means clustering with a few different starting centers chosen this way and choose the best clustering, in the sense of minimizing total weighted distance of all points from their cluster centers.\"\n\n\ntransformF :: forall x rs. (V.KnownField x, x ∈ rs) => (V.Snd x -> V.Snd x) -> F.Record rs -> F.Record rs\ntransformF f r = F.rputField @x (f $ F.rgetField @x r) r\n\n\n-- kmBondRatevsCrimeRateAnalysis countyBondPlusFIPSAndSAIPEAndVera\ntype IndexCrimeRate = \"index_crime_rate\" F.:-> Double\ntype TotalBondRate = \"total_bond_rate\" F.:-> Double\nindexCrimeRate r = FT.recordSingleton @IndexCrimeRate $ (r ^. indexCrime) `rDiv` (r ^. totalPop)\ntotalBondRate r = FT.recordSingleton @TotalBondRate $ (r ^. totalBondFreq) `rDiv` (r ^. totalPop) \nkmBondRatevsCrimeRateAnalysis joinedData = do\n let select = F.rcast @[Year,County,Urbanicity,TotalBondFreq,IndexCrime,TotalPop]\n mutation r = totalBondRate r F.<+> indexCrimeRate r\n mData = fmap (FT.mutate mutation) . catMaybes $ fmap (F.recMaybe . select) joinedData\n F.writeCSV \"data/raw_COCrimeRatevsBondRate.csv\" mData\n{- let dataCols = Proxy @[TotalBondRate, IndexCrimeRate, TotalPop]\n xScaling = FL.premap (F.rgetField @TotalBondRate &&& F.rgetField @TotalPop) $ MR.weightedScaleAndUnscale (MR.RescaleNormalize 1) MR.RescaleNone id\n yScaling = FL.premap (F.rgetField @IndexCrimeRate &&& F.rgetField @TotalPop) $ MR.weightedScaleAndUnscale (MR.RescaleNormalize 1) MR.RescaleNone id\n-}\n\n\n-- FM.writeCSV_Maybe \"data/countyBondPlusFIPS.csv\" countyBondPlusFIPS\n-- FM.writeCSV_Maybe \"data/countyBondPlusSAIPE.csv\" countyBondPlusFIPSAndSAIPE\n-- FM.writeCSV_Maybe \"data/countyBondPlus.csv\" countyBondPlusFIPSAndSAIPEAndVera\n-- coloradoRowCheck <- F.runSafeEffect $ FL.purely P.fold (goodDataByKey [F.pr1|Year|]) coloradoTrendsData\n-- putStrLn $ \"(CO rows, CO rows with all fields) = \" ++ show coloradoRowCheck\n\n\n\n", "meta": {"hexsha": "94c3550c7acfe8cf857b38407b0de6f9ff481d5b", "size": 39322, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "explore-data/colorado-analysis.hs", "max_stars_repo_name": "adamConnerSax/incarceration", "max_stars_repo_head_hexsha": "3bcd9826c6eb62fa3e9ea06136531ea6fa624e18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "explore-data/colorado-analysis.hs", "max_issues_repo_name": "adamConnerSax/incarceration", "max_issues_repo_head_hexsha": "3bcd9826c6eb62fa3e9ea06136531ea6fa624e18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "explore-data/colorado-analysis.hs", "max_forks_repo_name": "adamConnerSax/incarceration", "max_forks_repo_head_hexsha": "3bcd9826c6eb62fa3e9ea06136531ea6fa624e18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 76.6510721248, "max_line_length": 669, "alphanum_fraction": 0.7071105234, "num_tokens": 10803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.32165324685182645}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-|\nModule : Grenade.Layers.Crop\nDescription : Cropping layer\nCopyright : (c) Huw Campbell, 2016-2017\nLicense : BSD2\nStability : experimental\n-}\nmodule Grenade.Layers.Crop (\n Crop (..)\n ) where\n\nimport Data.Maybe\nimport Data.Proxy\nimport Data.Singletons.TypeLits\nimport GHC.TypeLits\n\nimport Grenade.Core\nimport Grenade.Layers.Internal.Pad\n\nimport Numeric.LinearAlgebra (konst, subMatrix, diagBlock)\nimport Numeric.LinearAlgebra.Static (extract, create)\n\n-- | A cropping layer for a neural network.\ndata Crop :: Nat\n -> Nat\n -> Nat\n -> Nat -> * where\n Crop :: Crop cropLeft cropTop cropRight cropBottom\n\ninstance Show (Crop cropLeft cropTop cropRight cropBottom) where\n show Crop = \"Crop\"\n\ninstance UpdateLayer (Crop l t r b) where\n type Gradient (Crop l t r b) = ()\n runUpdate _ x _ = x\n createRandom = return Crop\n\n-- | A two dimentional image can be cropped.\ninstance ( KnownNat cropLeft\n , KnownNat cropTop\n , KnownNat cropRight\n , KnownNat cropBottom\n , KnownNat inputRows\n , KnownNat inputColumns\n , KnownNat outputRows\n , KnownNat outputColumns\n , (outputRows + cropTop + cropBottom) ~ inputRows\n , (outputColumns + cropLeft + cropRight) ~ inputColumns\n ) => Layer (Crop cropLeft cropTop cropRight cropBottom) ('D2 inputRows inputColumns) ('D2 outputRows outputColumns) where\n type Tape (Crop cropLeft cropTop cropRight cropBottom) ('D2 inputRows inputColumns) ('D2 outputRows outputColumns) = ()\n runForwards Crop (S2D input) =\n let cropl = fromIntegral $ natVal (Proxy :: Proxy cropLeft)\n cropt = fromIntegral $ natVal (Proxy :: Proxy cropTop)\n nrows = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n ncols = fromIntegral $ natVal (Proxy :: Proxy outputColumns)\n m = extract input\n r = subMatrix (cropt, cropl) (nrows, ncols) m\n in ((), S2D . fromJust . create $ r)\n runBackwards _ _ (S2D dEdy) =\n let cropl = fromIntegral $ natVal (Proxy :: Proxy cropLeft)\n cropt = fromIntegral $ natVal (Proxy :: Proxy cropTop)\n cropr = fromIntegral $ natVal (Proxy :: Proxy cropRight)\n cropb = fromIntegral $ natVal (Proxy :: Proxy cropBottom)\n eo = extract dEdy\n vs = diagBlock [konst 0 (cropt,cropl), eo, konst 0 (cropb,cropr)]\n in ((), S2D . fromJust . create $ vs)\n\n\n-- | A two dimentional image can be cropped.\ninstance ( KnownNat cropLeft\n , KnownNat cropTop\n , KnownNat cropRight\n , KnownNat cropBottom\n , KnownNat inputRows\n , KnownNat inputColumns\n , KnownNat outputRows\n , KnownNat outputColumns\n , KnownNat channels\n , KnownNat (inputRows * channels)\n , KnownNat (outputRows * channels)\n , (outputRows + cropTop + cropBottom) ~ inputRows\n , (outputColumns + cropLeft + cropRight) ~ inputColumns\n ) => Layer (Crop cropLeft cropTop cropRight cropBottom) ('D3 inputRows inputColumns channels) ('D3 outputRows outputColumns channels) where\n type Tape (Crop cropLeft cropTop cropRight cropBottom) ('D3 inputRows inputColumns channels) ('D3 outputRows outputColumns channels) = ()\n runForwards Crop (S3D input) =\n let padl = fromIntegral $ natVal (Proxy :: Proxy cropLeft)\n padt = fromIntegral $ natVal (Proxy :: Proxy cropTop)\n padr = fromIntegral $ natVal (Proxy :: Proxy cropRight)\n padb = fromIntegral $ natVal (Proxy :: Proxy cropBottom)\n inr = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n inc = fromIntegral $ natVal (Proxy :: Proxy inputColumns)\n outr = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n outc = fromIntegral $ natVal (Proxy :: Proxy outputColumns)\n ch = fromIntegral $ natVal (Proxy :: Proxy channels)\n m = extract input\n cropped = crop ch padl padt padr padb outr outc inr inc m\n in ((), S3D . fromJust . create $ cropped)\n\n runBackwards Crop () (S3D gradient) =\n let padl = fromIntegral $ natVal (Proxy :: Proxy cropLeft)\n padt = fromIntegral $ natVal (Proxy :: Proxy cropTop)\n padr = fromIntegral $ natVal (Proxy :: Proxy cropRight)\n padb = fromIntegral $ natVal (Proxy :: Proxy cropBottom)\n inr = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n inc = fromIntegral $ natVal (Proxy :: Proxy inputColumns)\n outr = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n outc = fromIntegral $ natVal (Proxy :: Proxy outputColumns)\n ch = fromIntegral $ natVal (Proxy :: Proxy channels)\n m = extract gradient\n padded = pad ch padl padt padr padb outr outc inr inc m\n in ((), S3D . fromJust . create $ padded)\n", "meta": {"hexsha": "4b8b7597764a4176bfe09eaad9ca11961fe71db8", "size": 5109, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Crop.hs", "max_stars_repo_name": "sholland1/grenade", "max_stars_repo_head_hexsha": "b613502971fe43f4066d492912d45b57083dacd8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Grenade/Layers/Crop.hs", "max_issues_repo_name": "sholland1/grenade", "max_issues_repo_head_hexsha": "b613502971fe43f4066d492912d45b57083dacd8", "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/Crop.hs", "max_forks_repo_name": "sholland1/grenade", "max_forks_repo_head_hexsha": "b613502971fe43f4066d492912d45b57083dacd8", "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": 42.9327731092, "max_line_length": 148, "alphanum_fraction": 0.6359365825, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3214147800355006}} {"text": "-- This file is auto-generated. Do not edit directly.\n-- |\n-- Stability: Experimental\n--\n-- Generic interface to Blas using safe foreign calls. Refer to the GHC documentation\n-- for more information regarding appropriate use of safe and unsafe foreign calls.\n--\n-- The functions here are named in a similar fashion to the original Blas interface, with\n-- the type-dependent letter(s) removed. Some functions have been merged with\n-- others to allow the interface to work on both real and complex numbers. If you can't a\n-- particular function, try looking for its corresponding complex equivalent (e.g.\n-- @symv@ is a special case of 'hemv' applied to real numbers).\n--\n-- Note: although complex versions of @rot@ and @rotg@ exist in many implementations,\n-- they are not part of the official Blas standard and therefore not included here. If\n-- you /really/ need them, submit a ticket so we can try to come up with a solution.\n--\n-- The documentation here is still incomplete. Consult the\n-- for more\n-- information.\n--\n-- Notation:\n--\n-- * @⋅@ denotes dot product (without any conjugation).\n-- * @*@ denotes complex conjugation.\n-- * @⊤@ denotes transpose.\n-- * @†@ denotes conjugate transpose (Hermitian conjugate).\n--\n-- Conventions:\n--\n-- * All scalars are denoted with lowercase Greek letters\n-- * All vectors are denoted with lowercase Latin letters and are\n-- assumed to be column vectors (unless transposed).\n-- * All matrices are denoted with uppercase Latin letters.\n{-# LANGUAGE FlexibleInstances, TypeFamilies #-}\nmodule Blas.Generic.Safe (\n Numeric(..)\n , RealNumeric(..)\n , D.dsdot\n , S.sdsdot\n ) where\nimport Prelude (Floating, Double, Float, Int, IO)\nimport Data.Complex (Complex)\nimport Foreign (Ptr, Storable)\nimport Blas.Primitive.Types (Order, Transpose, Uplo, Diag, Side)\nimport qualified Blas.Specialized.Float.Safe as S\nimport qualified Blas.Specialized.Double.Safe as D\nimport qualified Blas.Specialized.ComplexFloat.Safe as C\nimport qualified Blas.Specialized.ComplexDouble.Safe as Z\n\n-- | Blas operations that are applicable to real and complex numbers.\n--\n-- Instances are defined for the 4 types supported by Blas: the single- and\n-- double-precision floating point types and their complex versions.\nclass (Floating a, Storable a) => Numeric a where\n\n -- | The corresponding real type of @a@.\n --\n -- In other words, @'RealType' ('Complex' a)@ is an alias for @a@. For everything\n -- else, @'RealType' a@ is simply @a@.\n type RealType a :: *\n -- | Swap two vectors:\n --\n -- > (x, y) ← (y, x)\n swap :: Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Multiply a vector by a scalar.\n --\n -- > x ← α x\n scal :: Int\n -> a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Copy a vector into another vector:\n --\n -- > y ← x\n copy :: Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Add a scalar-vector product to a vector.\n --\n -- > y ← α x + y\n axpy :: Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Calculate the bilinear dot product of two vectors:\n --\n -- > x ⋅ y ≡ ∑[i] x[i] y[i]\n dotu :: Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO a\n\n -- | Calculate the sesquilinear dot product of two vectors.\n --\n -- > x* ⋅ y ≡ ∑[i] x[i]* y[i]\n dotc :: Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO a\n\n -- | Calculate the Euclidean (L²) norm of a vector:\n --\n -- > ‖x‖₂ ≡ √(∑[i] x[i]²)\n nrm2 :: Int\n -> Ptr a\n -> Int\n -> IO (RealType a)\n\n -- | Calculate the Manhattan (L¹) norm, equal to the sum of the magnitudes of the elements:\n --\n -- > ‖x‖₁ = ∑[i] |x[i]|\n asum :: Int\n -> Ptr a\n -> Int\n -> IO (RealType a)\n\n -- | Calculate the index of the element with the maximum magnitude (absolute value).\n iamax :: Int\n -> Ptr a\n -> Int\n -> IO Int\n\n -- | Perform a general matrix-vector update.\n --\n -- > y ← α T(A) x + β y\n gemv :: Order\n -> Transpose\n -> Int\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a general banded matrix-vector update.\n --\n -- > y ← α T(A) x + β y\n gbmv :: Order\n -> Transpose\n -> Int\n -> Int\n -> Int\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a hermitian matrix-vector update.\n --\n -- > y ← α A x + β y\n hemv :: Order\n -> Uplo\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a hermitian banded matrix-vector update.\n --\n -- > y ← α A x + β y\n hbmv :: Order\n -> Uplo\n -> Int\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a hermitian packed matrix-vector update.\n --\n -- > y ← α A x + β y\n hpmv :: Order\n -> Uplo\n -> Int\n -> a\n -> Ptr a\n -> Ptr a\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Multiply a triangular matrix by a vector.\n --\n -- > x ← T(A) x\n trmv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Multiply a triangular banded matrix by a vector.\n --\n -- > x ← T(A) x\n tbmv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Multiply a triangular packed matrix by a vector.\n --\n -- > x ← T(A) x\n tpmv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Ptr a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Multiply an inverse triangular matrix by a vector.\n --\n -- > x ← T(A⁻¹) x\n trsv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Multiply an inverse triangular banded matrix by a vector.\n --\n -- > x ← T(A⁻¹) x\n tbsv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Multiply an inverse triangular packed matrix by a vector.\n --\n -- > x ← T(A⁻¹) x\n tpsv :: Order\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Ptr a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform an unconjugated rank-1 update of a general matrix.\n --\n -- > A ← α x y⊤ + A\n geru :: Order\n -> Int\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a conjugated rank-1 update of a general matrix.\n --\n -- > A ← α x y† + A\n gerc :: Order\n -> Int\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a rank-1 update of a Hermitian matrix.\n --\n -- > A ← α x y† + A\n her :: Order\n -> Uplo\n -> Int\n -> RealType a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a rank-1 update of a Hermitian packed matrix.\n --\n -- > A ← α x y† + A\n hpr :: Order\n -> Uplo\n -> Int\n -> RealType a\n -> Ptr a\n -> Int\n -> Ptr a\n -> IO ()\n\n -- | Perform a rank-2 update of a Hermitian matrix.\n --\n -- > A ← α x y† + y (α x)† + A\n her2 :: Order\n -> Uplo\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a rank-2 update of a Hermitian packed matrix.\n --\n -- > A ← α x y† + y (α x)† + A\n hpr2 :: Order\n -> Uplo\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> IO ()\n\n -- | Perform a general matrix-matrix update.\n --\n -- > C ← α T(A) U(B) + β C\n gemm :: Order -- ^ Layout of all the matrices.\n -> Transpose -- ^ The operation @T@ to be applied to @A@.\n -> Transpose -- ^ The operation @U@ to be applied to @B@.\n -> Int -- ^ Number of rows of @T(A)@ and @C@.\n -> Int -- ^ Number of columns of @U(B)@ and @C@.\n -> Int -- ^ Number of columns of @T(A)@ and number of rows of @U(B)@.\n -> a -- ^ Scaling factor @α@ of the product.\n -> Ptr a -- ^ Pointer to a matrix @A@.\n -> Int -- ^ Stride of the major dimension of @A@.\n -> Ptr a -- ^ Pointer to a matrix @B@.\n -> Int -- ^ Stride of the major dimension of @B@.\n -> a -- ^ Scaling factor @β@ of the original @C@.\n -> Ptr a -- ^ Pointer to a mutable matrix @C@.\n -> Int -- ^ Stride of the major dimension of @C@.\n -> IO ()\n\n -- | Perform a symmetric matrix-matrix update.\n --\n -- > C ← α A B + β C or C ← α B A + β C\n --\n -- where @A@ is symmetric. The matrix @A@ must be in an unpacked format, although the\n -- routine will only access half of it as specified by the @'Uplo'@ argument.\n symm :: Order -- ^ Layout of all the matrices.\n -> Side -- ^ Side that @A@ appears in the product.\n -> Uplo -- ^ The part of @A@ that is used.\n -> Int -- ^ Number of rows of @C@.\n -> Int -- ^ Number of columns of @C@.\n -> a -- ^ Scaling factor @α@ of the product.\n -> Ptr a -- ^ Pointer to a symmetric matrix @A@.\n -> Int -- ^ Stride of the major dimension of @A@.\n -> Ptr a -- ^ Pointer to a matrix @B@.\n -> Int -- ^ Stride of the major dimension of @B@.\n -> a -- ^ Scaling factor @α@ of the original @C@.\n -> Ptr a -- ^ Pointer to a mutable matrix @C@.\n -> Int -- ^ Stride of the major dimension of @C@.\n -> IO ()\n\n -- | Perform a Hermitian matrix-matrix update.\n --\n -- > C ← α A B + β C or C ← α B A + β C\n --\n -- where @A@ is Hermitian. The matrix @A@ must be in an unpacked format, although the\n -- routine will only access half of it as specified by the @'Uplo'@ argument.\n hemm :: Order -- ^ Layout of all the matrices.\n -> Side -- ^ Side that @A@ appears in the product.\n -> Uplo -- ^ The part of @A@ that is used.\n -> Int -- ^ Number of rows of @C@.\n -> Int -- ^ Number of columns of @C@.\n -> a -- ^ Scaling factor @α@ of the product.\n -> Ptr a -- ^ Pointer to a Hermitian matrix @A@.\n -> Int -- ^ Stride of the major dimension of @A@.\n -> Ptr a -- ^ Pointer to a matrix @B@.\n -> Int -- ^ Stride of the major dimension of @B@.\n -> a -- ^ Scaling factor @α@ of the original @C@.\n -> Ptr a -- ^ Pointer to a mutable matrix @C@.\n -> Int -- ^ Stride of the major dimension of @C@.\n -> IO ()\n\n -- | Perform a symmetric rank-k update.\n --\n -- > C ← α A A⊤ + β C or C ← α A⊤ A + β C\n syrk :: Order\n -> Uplo\n -> Transpose\n -> Int\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a Hermitian rank-k update.\n --\n -- > C ← α A A† + β C or C ← α A† A + β C\n herk :: Order\n -> Uplo\n -> Transpose\n -> Int\n -> Int\n -> RealType a\n -> Ptr a\n -> Int\n -> RealType a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a symmetric rank-2k update.\n --\n -- > C ← α A B⊤ + α* B A⊤ + β C or C ← α A⊤ B + α* B⊤ A + β C\n syr2k :: Order\n -> Uplo\n -> Transpose\n -> Int\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a Hermitian rank-2k update.\n --\n -- > C ← α A B† + α* B A† + β C or C ← α A† B + α* B† A + β C\n her2k :: Order\n -> Uplo\n -> Transpose\n -> Int\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> RealType a\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform a triangular matrix-matrix multiplication.\n --\n -- > B ← α T(A) B or B ← α B T(A)\n --\n -- where @A@ is triangular.\n trmm :: Order\n -> Side\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n -- | Perform an inverse triangular matrix-matrix multiplication.\n --\n -- > B ← α T(A⁻¹) B or B ← α B T(A⁻¹)\n --\n -- where @A@ is triangular.\n trsm :: Order\n -> Side\n -> Uplo\n -> Transpose\n -> Diag\n -> Int\n -> Int\n -> a\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> IO ()\n\n-- | Blas operations that are only applicable to real numbers.\nclass Numeric a => RealNumeric a where\n\n -- | Generate a Givens rotation. (Only available for real floating-point types.)\n rotg :: Ptr a\n -> Ptr a\n -> Ptr a\n -> Ptr a\n -> IO ()\n\n -- | Generate a modified Givens rotation. (Only available for real floating-point\n -- types.)\n rotmg :: Ptr a\n -> Ptr a\n -> Ptr a\n -> a\n -> Ptr a\n -> IO ()\n\n -- | Apply a Givens rotation. (Only available for real floating-point types.)\n rot :: Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> a\n -> a\n -> IO ()\n\n -- | Apply a modified Givens rotation. (Only available for real floating-point types.)\n rotm :: Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> Int\n -> Ptr a\n -> IO ()\n\ninstance Numeric Float where\n type RealType Float = Float\n swap = S.swap\n scal = S.scal\n copy = S.copy\n axpy = S.axpy\n dotu = S.dotu\n dotc = S.dotc\n nrm2 = S.nrm2\n asum = S.asum\n iamax = S.iamax\n gemv = S.gemv\n gbmv = S.gbmv\n hemv = S.hemv\n hbmv = S.hbmv\n hpmv = S.hpmv\n trmv = S.trmv\n tbmv = S.tbmv\n tpmv = S.tpmv\n trsv = S.trsv\n tbsv = S.tbsv\n tpsv = S.tpsv\n geru = S.geru\n gerc = S.gerc\n her = S.her\n hpr = S.hpr\n her2 = S.her2\n hpr2 = S.hpr2\n gemm = S.gemm\n symm = S.symm\n hemm = S.hemm\n syrk = S.syrk\n herk = S.herk\n syr2k = S.syr2k\n her2k = S.her2k\n trmm = S.trmm\n trsm = S.trsm\n\n\ninstance Numeric Double where\n type RealType Double = Double\n swap = D.swap\n scal = D.scal\n copy = D.copy\n axpy = D.axpy\n dotu = D.dotu\n dotc = D.dotc\n nrm2 = D.nrm2\n asum = D.asum\n iamax = D.iamax\n gemv = D.gemv\n gbmv = D.gbmv\n hemv = D.hemv\n hbmv = D.hbmv\n hpmv = D.hpmv\n trmv = D.trmv\n tbmv = D.tbmv\n tpmv = D.tpmv\n trsv = D.trsv\n tbsv = D.tbsv\n tpsv = D.tpsv\n geru = D.geru\n gerc = D.gerc\n her = D.her\n hpr = D.hpr\n her2 = D.her2\n hpr2 = D.hpr2\n gemm = D.gemm\n symm = D.symm\n hemm = D.hemm\n syrk = D.syrk\n herk = D.herk\n syr2k = D.syr2k\n her2k = D.her2k\n trmm = D.trmm\n trsm = D.trsm\n\n\ninstance Numeric (Complex Float) where\n type RealType (Complex Float) = Float\n swap = C.swap\n scal = C.scal\n copy = C.copy\n axpy = C.axpy\n dotu = C.dotu\n dotc = C.dotc\n nrm2 = C.nrm2\n asum = C.asum\n iamax = C.iamax\n gemv = C.gemv\n gbmv = C.gbmv\n hemv = C.hemv\n hbmv = C.hbmv\n hpmv = C.hpmv\n trmv = C.trmv\n tbmv = C.tbmv\n tpmv = C.tpmv\n trsv = C.trsv\n tbsv = C.tbsv\n tpsv = C.tpsv\n geru = C.geru\n gerc = C.gerc\n her = C.her\n hpr = C.hpr\n her2 = C.her2\n hpr2 = C.hpr2\n gemm = C.gemm\n symm = C.symm\n hemm = C.hemm\n syrk = C.syrk\n herk = C.herk\n syr2k = C.syr2k\n her2k = C.her2k\n trmm = C.trmm\n trsm = C.trsm\n\n\ninstance Numeric (Complex Double) where\n type RealType (Complex Double) = Double\n swap = Z.swap\n scal = Z.scal\n copy = Z.copy\n axpy = Z.axpy\n dotu = Z.dotu\n dotc = Z.dotc\n nrm2 = Z.nrm2\n asum = Z.asum\n iamax = Z.iamax\n gemv = Z.gemv\n gbmv = Z.gbmv\n hemv = Z.hemv\n hbmv = Z.hbmv\n hpmv = Z.hpmv\n trmv = Z.trmv\n tbmv = Z.tbmv\n tpmv = Z.tpmv\n trsv = Z.trsv\n tbsv = Z.tbsv\n tpsv = Z.tpsv\n geru = Z.geru\n gerc = Z.gerc\n her = Z.her\n hpr = Z.hpr\n her2 = Z.her2\n hpr2 = Z.hpr2\n gemm = Z.gemm\n symm = Z.symm\n hemm = Z.hemm\n syrk = Z.syrk\n herk = Z.herk\n syr2k = Z.syr2k\n her2k = Z.her2k\n trmm = Z.trmm\n trsm = Z.trsm\ninstance RealNumeric Float where\n rotg = S.rotg\n rotmg = S.rotmg\n rot = S.rot\n rotm = S.rotm\n\n\ninstance RealNumeric Double where\n rotg = D.rotg\n rotmg = D.rotmg\n rot = D.rot\n rotm = D.rotm\n", "meta": {"hexsha": "5b358652f4fdad66fb55475310dfa8368099ebdc", "size": 16785, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Blas/Generic/Safe.hs", "max_stars_repo_name": "Rufflewind/blas-hs", "max_stars_repo_head_hexsha": "59fdc1c48b19024f9bb6283b4ddc90fe45383937", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-01-20T04:34:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-09T12:09:06.000Z", "max_issues_repo_path": "src/Blas/Generic/Safe.hs", "max_issues_repo_name": "Rufflewind/blas-hs", "max_issues_repo_head_hexsha": "59fdc1c48b19024f9bb6283b4ddc90fe45383937", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-04-25T05:53:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-28T22:27:04.000Z", "max_forks_repo_path": "src/Blas/Generic/Safe.hs", "max_forks_repo_name": "Rufflewind/blas-hs", "max_forks_repo_head_hexsha": "59fdc1c48b19024f9bb6283b4ddc90fe45383937", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8839634941, "max_line_length": 93, "alphanum_fraction": 0.4893655049, "num_tokens": 5563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.320952427895305}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n\nmodule Main where\nimport qualified Data.Foldable as Foldable\n\n-- vector\nimport Data.Vector (Vector)\nimport qualified Data.Vector as Vector\n\n-- Matrix\nimport Data.Matrix (Matrix)\nimport qualified Data.Matrix as Matrix\n\n-- HMatrix\nimport qualified Numeric.LinearAlgebra.Data as HMatrix\nimport qualified Numeric.LinearAlgebra.HMatrix as HMatrix\n\n-- bytestring\nimport Data.ByteString.Lazy (ByteString)\nimport qualified Data.ByteString.Lazy as ByteString\n\n-- cassava\nimport Data.Csv\n ( DefaultOrdered(headerOrder)\n , FromField(parseField)\n , FromNamedRecord(parseNamedRecord)\n , Header\n , ToField(toField)\n , ToNamedRecord(toNamedRecord)\n , (.:)\n , (.=)\n )\nimport qualified Data.Csv as Cassava\n\n-- text\nimport Data.Text (Text)\nimport qualified Data.Text.Encoding as Text\n\n-- Exception\nimport Control.Exception\n\n-- base\nimport qualified Control.Monad as Monad\nimport qualified System.Exit as Exit\nimport qualified Debug.Trace as Trace\n\n\n\ndata ComponentData = \n ComponentData { \n componentType :: ComponentType,\n nodeK :: Int,\n nodeM :: Int,\n magnitude :: Double,\n param1 :: Double,\n param2 :: Double,\n plot :: Int\n }\n deriving (Eq, Show)\n\n\ndata SimulationData = \n SimulationData { \n nodes :: Int,\n voltageSources :: Int,\n stepSize :: Double,\n tmax :: Double\n }\n deriving (Eq, Show)\n\ndata ComponentType = Resistor | Capacitor | Inductor | EAC | EDC | Other Text deriving (Eq, Show)\ntype SimulationResults = (Vector Double, Matrix Double)\n\ninstance FromNamedRecord SimulationData where\n parseNamedRecord m =\n SimulationData\n <$> m .: \"Number of Nodes\"\n <*> m .: \"Number of Voltages Sources\"\n <*> m .: \"Step Size\"\n <*> m .: \"Maximum time for simulation\"\n\n\ninstance FromNamedRecord ComponentData where\n parseNamedRecord m =\n ComponentData\n <$> m .: \"Element Type\"\n <*> m .: \"Node K\"\n <*> m .: \"Node M\"\n <*> m .: \"Value\"\n <*> m .: \"Source param 1\"\n <*> m .: \"Source param 2\"\n <*> m .: \"Plot\"\n\ninstance FromField ComponentType where\n parseField \"R\" =\n pure Resistor\n\n parseField \"L\" =\n pure Inductor\n\n parseField \"C\" =\n pure Capacitor\n\n parseField \"EDC\" =\n pure EDC\n\n parseField \"EAC\" =\n pure EAC\n\n parseField otherType =\n Other <$> parseField otherType\n\n\ndecodeItems :: ByteString -> Either String (Vector ComponentData)\ndecodeItems =\n fmap snd . Cassava.decodeByName\n\ndecodeItemsFromFile :: FilePath -> IO (Either String (Vector ComponentData))\ndecodeItemsFromFile filePath =\n catchShowIO (ByteString.readFile filePath)\n >>= return . either Left decodeItems\n\ndecodeSimulation :: ByteString -> Either String (Vector SimulationData)\ndecodeSimulation =\n fmap snd . Cassava.decodeByName\n\ndecodeSimulationFromFile :: FilePath -> IO (Either String (Vector SimulationData))\ndecodeSimulationFromFile filePath =\n catchShowIO (ByteString.readFile filePath)\n >>= return . either Left decodeSimulation\n\ngetSingleSimulationLine :: Vector SimulationData -> SimulationData\ngetSingleSimulationLine = \n Vector.head \n\n\nnhComponents :: [ComponentData] -> [ComponentData]\nnhComponents =\n filter (\\r -> (componentType r == Capacitor) || (componentType r == Inductor))\n\nfilterEnergyStorageComponent :: Vector ComponentData -> Vector ComponentData\nfilterEnergyStorageComponent =\n Vector.filter (\\r -> (componentType r == Capacitor) || (componentType r == Inductor))\n\nnh :: Vector ComponentData -> Int\nnh components =\n length $ filterEnergyStorageComponent components\n \n-- filter ((== Zaal) . reviewLocation) reviews \n\nfilterSources :: Vector ComponentData -> Vector ComponentData\nfilterSources =\n Vector.filter (\\r -> (componentType r == EDC) || (componentType r == EAC))\n\ncondutance :: ComponentData -> Double -> Double\ncondutance component dt =\n case componentType component of\n Resistor -> 1.0 / (magnitude component)\n Capacitor -> (magnitude component) * 0.000001 * 2 / dt\n Inductor -> dt / (2 * 0.001 * (magnitude component))\n _ -> 0.0\n\ngkm :: Vector ComponentData -> Double -> Vector Double\ngkm components dt =\n Vector.map (\\c -> condutance c dt) components\n -- Matrix.colVector (Vector.map (\\c -> condutance c dt) components)\n -- Matrix.fromList (length components) 1 (Vector.toList (Vector.map (\\c -> condutance c dt) components))\n\nbuildCompactGMatrix :: Double -> [ComponentData] -> Matrix Double -> Matrix Double\nbuildCompactGMatrix dt [] buffer = buffer\nbuildCompactGMatrix dt (component:cs) buffer =\n case (nodeK component, nodeM component) of (0, m) -> buildCompactGMatrix dt cs (Matrix.setElem (Matrix.getElem m m buffer + condutance component dt) (m, m) buffer)\n (k, 0) -> buildCompactGMatrix dt cs (Matrix.setElem (Matrix.getElem k k buffer + condutance component dt) (k, k) buffer)\n (k, m) -> buildCompactGMatrix dt cs (Matrix.setElem (Matrix.getElem k k buffer + condutance component dt) (k, k) (Matrix.setElem (Matrix.getElem m m buffer + condutance component dt) (m, m) (Matrix.setElem (Matrix.getElem k m buffer - condutance component dt) (k, m) (Matrix.setElem (Matrix.getElem m k buffer - condutance component dt) (m, k) buffer))))\n (_, _) -> buildCompactGMatrix dt cs buffer\n\n\nbuildGMatrixFromVector :: SimulationData -> Vector ComponentData -> Matrix Double\nbuildGMatrixFromVector simulation components =\n buildCompactGMatrix (stepSize simulation) (Vector.toList components) (Matrix.zero (nodes simulation) (nodes simulation))\n\n\nbuildIhVector :: [ComponentData] -> Double -> Int -> [Double] -> [Double] -> Matrix Double -> Vector Double\nbuildIhVector [] _ _ _ ihnew _ = Vector.fromList ihnew\nbuildIhVector (component:cs) dt n (hold:ihold) ihnew vMatrix =\n case (componentType component, nodeK component, nodeM component) of (Inductor, 0, m) -> buildIhVector cs dt n ihold (ihnew ++ [(2*(condutance component dt)*(Matrix.getElem m n vMatrix) + hold)]) vMatrix\n (Inductor, k, 0) -> buildIhVector cs dt n ihold (ihnew ++ [(-2*(condutance component dt)*(Matrix.getElem k n vMatrix) + hold)]) vMatrix\n (Inductor, k, m) -> buildIhVector cs dt n ihold (ihnew ++ [(-2*(condutance component dt)*((Matrix.getElem k n vMatrix) - (Matrix.getElem m n vMatrix)) + hold)]) vMatrix\n (Capacitor, 0, m) -> buildIhVector cs dt n ihold (ihnew ++ [(-2*(condutance component dt)*(Matrix.getElem m n vMatrix) - hold)]) vMatrix\n (Capacitor, k, 0) -> buildIhVector cs dt n ihold (ihnew ++ [(2*(condutance component dt)*(Matrix.getElem k n vMatrix) - hold)]) vMatrix\n (Capacitor, k, m) -> buildIhVector cs dt n ihold (ihnew ++ [(2*(condutance component dt)*((Matrix.getElem k n vMatrix) - (Matrix.getElem m n vMatrix)) - hold)]) vMatrix\n (_, _, _) -> buildIhVector cs dt n ihold ihnew vMatrix\n\n\n\nbuildVBVector :: [ComponentData] -> Double -> [Double] -> Vector Double\nbuildVBVector [] _ buffer = Vector.fromList buffer\nbuildVBVector (c:components) time buffer =\n case (componentType c) of EDC -> buildVBVector components time ((magnitude c) : buffer)\n EAC -> buildVBVector components time (((magnitude c * cos (2 * pi * param2 c * time + (param1 c * (pi/180))))) : buffer)\n _ -> buildVBVector components time buffer\n\n\nbuildIVector :: [ComponentData] -> [Double] -> Vector Double -> Vector Double\nbuildIVector [] _ iVector = iVector\nbuildIVector (component:cs) (ihEl:ih) iVector =\n case (componentType component, nodeK component, nodeM component) of (Inductor, k, 0) -> buildIVector cs ih (iVector Vector.// [((k - 1), ((iVector Vector.! (k-1)) + ihEl))])\n (Inductor, 0, m) -> buildIVector cs ih (iVector Vector.// [((m - 1), ((iVector Vector.! (m-1)) - ihEl))])\n (Inductor, k, m) -> buildIVector cs ih (iVector Vector.// [((m - 1), ((iVector Vector.! (m-1)) - ihEl)), ((k-1), ((iVector Vector.! (k-1)) + ihEl))])\n (Capacitor, k, 0) -> buildIVector cs ih (iVector Vector.// [((k - 1), ((iVector Vector.! (k-1)) + ihEl))])\n (Capacitor, 0, m) -> buildIVector cs ih (iVector Vector.// [((m - 1), ((iVector Vector.! (m-1)) - ihEl))])\n (Capacitor, k, m) -> buildIVector cs ih (iVector Vector.// [((m - 1), ((iVector Vector.! (m-1)) - ihEl)), ((k-1), ((iVector Vector.! (k-1)) + ihEl))])\n (_, _, _) -> buildIVector cs ih iVector\n\n\nthtaControl :: Int -> Double -> Vector Double -> Vector Double -> SimulationData -> (Int, Vector Double, Double)\nthtaControl thtactl time ihnew ih simulation\n | thtactl <= 0 = (thtactl, ihnew, (stepSize simulation + time))\n | thtactl < 3 = (thtactl + 1, (Vector.map (\\i -> i/2) $ Vector.zipWith (+) ih ihnew), (time + (stepSize simulation/2)))\n | otherwise = (0, ihnew, (stepSize simulation + time))\n\nfromHMatrixTransformer :: HMatrix.Matrix Double -> Matrix Double\nfromHMatrixTransformer matrix =\n Matrix.fromLists $ HMatrix.toLists matrix\n\ntoHMatrixTransformer :: Matrix Double -> HMatrix.Matrix Double\ntoHMatrixTransformer matrix =\n HMatrix.fromLists $ Matrix.toLists matrix\n\nfromHMatrixVectorTransformer :: HMatrix.Vector Double -> Vector Double\nfromHMatrixVectorTransformer vec =\n Vector.fromList $ HMatrix.toList vec\n\ntoHMatrixVectorTransformer :: Vector Double -> HMatrix.Vector Double\ntoHMatrixVectorTransformer vec =\n HMatrix.fromList $ Vector.toList vec\n\nsolver :: HMatrix.Vector Double -> HMatrix.Matrix Double -> HMatrix.Matrix Double -> HMatrix.Matrix Double -> HMatrix.Matrix Double -> HMatrix.Vector Double -> SimulationData -> (Vector Double, Vector Double)\nsolver iVector gaa gab gba gbb vb simulation =\n let ia = HMatrix.subVector 0 ((nodes simulation) - (voltageSources simulation)) iVector\n rhsa = ia - (gab HMatrix.#> vb)\n va = gaa HMatrix.<\\> rhsa\n ib = (gba HMatrix.#> va) + (gbb HMatrix.#> vb)\n iVec = HMatrix.vjoin [ia, ib] \n vVec = HMatrix.vjoin [va, vb]\n in\n ((fromHMatrixVectorTransformer iVec), (fromHMatrixVectorTransformer vVec))\n \n\nthtaSimulationStep :: [ComponentData] -> Matrix Double -> SimulationData -> Int -> Int -> Double -> Vector Double -> Matrix Double -> Vector Double -> Vector Double -> SimulationResults\nthtaSimulationStep _ _ _ _ 1 _ _ vMatrix _ iVector = (iVector, vMatrix)\nthtaSimulationStep components condutances simulation thtactl n time ih vMatrix vbVector iVector =\n let (gaa, gab, gba, gbb) = Matrix.splitBlocks (nodes simulation - voltageSources simulation) (nodes simulation - voltageSources simulation) condutances\n ihBuffer = buildIhVector (nhComponents components) (stepSize simulation) n (Vector.toList ih) [] vMatrix\n (thta, ihThta, timeThta) = thtaControl thtactl time ihBuffer ih simulation\n vbVec = buildVBVector components timeThta []\n iVec = buildIVector (nhComponents components) (Vector.toList ihThta) (Vector.replicate (nodes simulation) 0)\n -- (iVecCalc, vVec) = Trace.trace (\"Solver = \\n\" ++ show (solver (toHMatrixVectorTransformer iVec) (toHMatrixTransformer gaa) (toHMatrixTransformer gab) (toHMatrixTransformer gba) (toHMatrixTransformer gbb) (toHMatrixVectorTransformer vbVec) simulation)) solver (toHMatrixVectorTransformer iVec) (toHMatrixTransformer gaa) (toHMatrixTransformer gab) (toHMatrixTransformer gba) (toHMatrixTransformer gbb) (toHMatrixVectorTransformer vbVec) simulation\n (iVecCalc, vVec) = solver (toHMatrixVectorTransformer iVec) (toHMatrixTransformer gaa) (toHMatrixTransformer gab) (toHMatrixTransformer gba) (toHMatrixTransformer gbb) (toHMatrixVectorTransformer vbVec) simulation\n vMatr = Matrix.mapCol (\\r _ -> vVec Vector.! (r - 1)) (n-1) vMatrix\n in\n thtaSimulationStep components condutances simulation thta (n-1) timeThta ihThta vMatr vbVec iVecCalc\n\n\nthtaSimulation :: Vector ComponentData -> SimulationData -> SimulationResults\nthtaSimulation components simulation = \n thtaSimulationStep (Vector.toList components) (buildGMatrixFromVector simulation components) simulation 1 (npoints simulation) 0.0 (Vector.replicate (nh components) 0) (Matrix.zero (nodes simulation) (npoints simulation)) (Vector.replicate (voltageSources simulation) 0) (Vector.replicate (nodes simulation) 0)\n\n\nnpoints :: SimulationData -> Int\nnpoints sim = \n round ((tmax sim)/(stepSize sim)) + 1\n\ncatchShowIO :: IO a -> IO (Either String a)\ncatchShowIO action =\n fmap Right action\n `catch` handleIOException\n where\n handleIOException :: IOException -> IO (Either String a)\n handleIOException =\n return . Left . show\n\nmain :: IO ()\nmain = do\n\n eitherSimulation <-\n fmap getSingleSimulationLine\n <$> decodeSimulationFromFile \"data/simulation.csv\"\n\n case eitherSimulation of\n Left reason ->\n Exit.die reason\n\n Right simulation -> do\n components_list <- decodeItemsFromFile \"data/components.csv\"\n case components_list of\n Left reason -> Exit.die reason\n Right components -> do\n let gmt = buildGMatrixFromVector simulation components\n putStr \"GMatrix: \\n\"\n print (gmt)\n let results = thtaSimulation components simulation\n putStr \"Simulation: \\n\"\n print (results)\n\n\n\n", "meta": {"hexsha": "599c427f5888917df994766a3d27814ddf095cb9", "size": 13907, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "hannelita/thtahs", "max_stars_repo_head_hexsha": "895339b836f1ed43b66c99b6208edf2be9ec858e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-27T02:04:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T20:54:11.000Z", "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "hannelita/thtahs", "max_issues_repo_head_hexsha": "895339b836f1ed43b66c99b6208edf2be9ec858e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2019-10-13T22:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-03T01:05:05.000Z", "max_forks_repo_path": "src/Main.hs", "max_forks_repo_name": "hannelita/thtahs", "max_forks_repo_head_hexsha": "895339b836f1ed43b66c99b6208edf2be9ec858e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-15T20:54:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T20:54:14.000Z", "avg_line_length": 45.0064724919, "max_line_length": 455, "alphanum_fraction": 0.6577982311, "num_tokens": 3475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.31905550784832976}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Data.Eigen.Matrix (\n -- * Matrix type\n -- | Matrix aliases follows Eigen naming convention\n Matrix(..),\n MatrixXf,\n MatrixXd,\n MatrixXcf,\n MatrixXcd,\n I.Elem,\n I.CComplex,\n valid,\n -- * Matrix conversions\n fromList,\n toList,\n fromFlatList,\n toFlatList,\n generate,\n -- * Standard matrices and special cases\n empty,\n null,\n square,\n zero,\n ones,\n identity,\n constant,\n random,\n -- * Accessing matrix data\n cols,\n rows,\n dims,\n (!),\n coeff,\n unsafeCoeff,\n col,\n row,\n block,\n topRows,\n bottomRows,\n leftCols,\n rightCols,\n -- * Matrix properties\n sum,\n prod,\n mean,\n minCoeff,\n maxCoeff,\n trace,\n norm,\n squaredNorm,\n blueNorm,\n hypotNorm,\n determinant,\n -- * Generic reductions\n fold,\n fold',\n ifold,\n ifold',\n fold1,\n fold1',\n -- * Boolean reductions\n all,\n any,\n count,\n -- * Basic matrix algebra\n add,\n sub,\n mul,\n -- * Mapping over elements\n map,\n imap,\n filter,\n ifilter,\n -- * Matrix transformations\n diagonal,\n transpose,\n inverse,\n adjoint,\n conjugate,\n normalize,\n modify,\n convert,\n TriangularMode(..),\n triangularView,\n lowerTriangle,\n upperTriangle,\n -- * Matrix serialization\n encode,\n decode,\n -- * Mutable matrices\n thaw,\n freeze,\n unsafeThaw,\n unsafeFreeze,\n -- * Raw pointers\n unsafeWith,\n) where\n\nimport qualified Prelude as P\nimport qualified Data.List as L\nimport Prelude hiding (null, sum, all, any, map, filter)\nimport Data.Tuple\nimport Data.Complex hiding (conjugate)\nimport Data.Binary hiding (encode, decode)\nimport qualified Data.Binary as B\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Storable\nimport Foreign.Marshal.Alloc\nimport Text.Printf\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.Primitive\n#if __GLASGOW_HASKELL__ >= 710\n#else\nimport Control.Applicative hiding (empty)\n#endif\nimport qualified Data.Vector.Storable as VS\nimport qualified Data.Vector.Storable.Mutable as VSM\nimport qualified Data.Eigen.Internal as I\nimport qualified Data.Eigen.Matrix.Mutable as M\nimport qualified Data.ByteString.Lazy as BSL\n\n-- | Matrix to be used in pure computations, uses column major memory layout, features copy-free FFI with C++ library.\n\ndata Matrix a b where\n Matrix :: I.Elem a b => !Int -> !Int -> !(VS.Vector b) -> Matrix a b\n\n-- | Alias for single precision matrix\ntype MatrixXf = Matrix Float CFloat\n-- | Alias for double precision matrix\ntype MatrixXd = Matrix Double CDouble\n-- | Alias for single previsiom matrix of complex numbers\ntype MatrixXcf = Matrix (Complex Float) (I.CComplex CFloat)\n-- | Alias for double prevision matrix of complex numbers\ntype MatrixXcd = Matrix (Complex Double) (I.CComplex CDouble)\n\n-- | Pretty prints the matrix\ninstance (I.Elem a b, Show a) => Show (Matrix a b) where\n show m@(Matrix rows cols _) = concat [\n \"Matrix \", show rows, \"x\", show cols,\n \"\\n\", L.intercalate \"\\n\" $ P.map (L.intercalate \"\\t\" . P.map show) $ toList m, \"\\n\"]\n\n\n-- | Basic matrix math exposed through Num instance: @(*)@, @(+)@, @(-)@, `fromInteger`, `signum`, `abs`, `negate`\ninstance I.Elem a b => Num (Matrix a b) where\n (*) = mul\n (+) = add\n (-) = sub\n fromInteger = constant 1 1 . fromInteger\n signum = map signum\n abs = map abs\n negate = map negate\n\n-- | Matrix binary serialization\ninstance I.Elem a b => Binary (Matrix a b) where\n put (Matrix rows cols vals) = do\n put $ I.magicCode (undefined :: b)\n put rows\n put cols\n put vals\n\n get = do\n get >>= (`when` fail \"wrong matrix type\") . (/= I.magicCode (undefined :: b))\n Matrix <$> get <*> get <*> get\n\n-- | Encode the matrix as a lazy byte string\nencode :: I.Elem a b => Matrix a b -> BSL.ByteString\nencode = B.encode\n\n-- | Decode matrix from the lazy byte string\ndecode :: I.Elem a b => BSL.ByteString -> Matrix a b\ndecode = B.decode\n\n-- | Empty 0x0 matrix\n{-# INLINE empty #-}\nempty :: I.Elem a b => Matrix a b\nempty = Matrix 0 0 VS.empty\n\n-- | Is matrix empty?\n{-# INLINE null #-}\nnull :: I.Elem a b => Matrix a b -> Bool\nnull (Matrix rows cols _) = rows == 0 && cols == 0\n\n-- | Is matrix square?\n{-# INLINE square #-}\nsquare :: I.Elem a b => Matrix a b -> Bool\nsquare (Matrix rows cols _) = rows == cols\n\n-- | Matrix where all coeffs are filled with given value\n{-# INLINE constant #-}\nconstant :: I.Elem a b => Int -> Int -> a -> Matrix a b\nconstant rows cols val = Matrix rows cols $ VS.replicate (rows * cols) (I.cast val)\n\n-- | Matrix where all coeff are 0\n{-# INLINE zero #-}\nzero :: I.Elem a b => Int -> Int -> Matrix a b\nzero rows cols = constant rows cols 0\n\n-- | Matrix where all coeff are 1\n{-# INLINE ones #-}\nones :: I.Elem a b => Int -> Int -> Matrix a b\nones rows cols = constant rows cols 1\n\n-- | The identity matrix (not necessarily square).\nidentity :: I.Elem a b => Int -> Int -> Matrix a b\nidentity rows cols = I.performIO $ do\n m <- M.new rows cols\n I.call $ M.unsafeWith m I.identity\n unsafeFreeze m\n\n-- | The random matrix of a given size\nrandom :: I.Elem a b => Int -> Int -> IO (Matrix a b)\nrandom rows cols = do\n m <- M.new rows cols\n I.call $ M.unsafeWith m I.random\n unsafeFreeze m\n\n-- | Number of rows for the matrix\n{-# INLINE rows #-}\nrows :: I.Elem a b => Matrix a b -> Int\nrows (Matrix rows _ _) = rows\n\n-- | Number of columns for the matrix\n{-# INLINE cols #-}\ncols :: I.Elem a b => Matrix a b -> Int\ncols (Matrix _ cols _) = cols\n\n-- | Mtrix size as (rows, cols) pair\n{-# INLINE dims #-}\ndims :: I.Elem a b => Matrix a b -> (Int, Int)\ndims (Matrix rows cols _) = (rows, cols)\n\n-- | Matrix coefficient at specific row and col\n{-# INLINE (!) #-}\n(!) :: I.Elem a b => Matrix a b -> (Int, Int) -> a\n(!) m (row,col) = coeff row col m\n\n-- | Matrix coefficient at specific row and col\n{-# INLINE coeff #-}\ncoeff :: I.Elem a b => Int -> Int -> Matrix a b -> a\ncoeff row col m@(Matrix rows cols _)\n | not (valid m) = error \"matrix is not valid\"\n | row < 0 || row >= rows = error $ printf \"Matrix.coeff: row %d is out of bounds [0..%d)\" row rows\n | col < 0 || col >= cols = error $ printf \"Matrix.coeff: col %d is out of bounds [0..%d)\" col cols\n | otherwise = unsafeCoeff row col m\n\n-- | Unsafe version of coeff function. No bounds check performed so SEGFAULT possible\n{-# INLINE unsafeCoeff #-}\nunsafeCoeff :: I.Elem a b => Int -> Int -> Matrix a b -> a\nunsafeCoeff row col (Matrix rows _ vals) = I.cast $ VS.unsafeIndex vals $ col * rows + row\n\n-- | List of coefficients for the given col\n{-# INLINE col #-}\ncol :: I.Elem a b => Int -> Matrix a b -> [a]\ncol c m@(Matrix rows _ _) = [coeff r c m | r <- [0..pred rows]]\n\n-- | List of coefficients for the given row\n{-# INLINE row #-}\nrow :: I.Elem a b => Int -> Matrix a b -> [a]\nrow r m@(Matrix _ cols _) = [coeff r c m | c <- [0..pred cols]]\n\n-- | Extract rectangular block from matrix defined by startRow startCol blockRows blockCols\nblock :: I.Elem a b => Int -> Int -> Int -> Int -> Matrix a b -> Matrix a b\nblock startRow startCol blockRows blockCols m =\n generate blockRows blockCols $ \\row col ->\n coeff (startRow + row) (startCol + col) m\n\n-- | Verify matrix dimensions and memory layout\n{-# INLINE valid #-}\nvalid :: I.Elem a b => Matrix a b -> Bool\nvalid (Matrix rows cols vals) = rows >= 0 && cols >= 0 && VS.length vals == rows * cols\n\n-- | The maximum coefficient of the matrix\n{-# INLINE maxCoeff #-}\nmaxCoeff :: (I.Elem a b, Ord a) => Matrix a b -> a\nmaxCoeff = fold1' max\n\n-- | The minimum coefficient of the matrix\n{-# INLINE minCoeff #-}\nminCoeff :: (I.Elem a b, Ord a) => Matrix a b -> a\nminCoeff = fold1' min\n\n-- | Top @N@ rows of matrix\n{-# INLINE topRows #-}\ntopRows :: I.Elem a b => Int -> Matrix a b -> Matrix a b\ntopRows n m@(Matrix _ cols _) = block 0 0 n cols m\n\n-- | Bottom @N@ rows of matrix\n{-# INLINE bottomRows #-}\nbottomRows :: I.Elem a b => Int -> Matrix a b -> Matrix a b\nbottomRows n m@(Matrix rows cols _) = block (rows - n) 0 n cols m\n\n-- | Left @N@ columns of matrix\n{-# INLINE leftCols #-}\nleftCols :: I.Elem a b => Int -> Matrix a b -> Matrix a b\nleftCols n m@(Matrix rows _ _) = block 0 0 rows n m\n\n-- | Right @N@ columns of matrix\n{-# INLINE rightCols #-}\nrightCols :: I.Elem a b => Int -> Matrix a b -> Matrix a b\nrightCols n m@(Matrix rows cols _) = block 0 (cols - n) rows n m\n\n-- | Construct matrix from a list of rows, column count is detected as maximum row length. Missing values are filled with 0\nfromList :: I.Elem a b => [[a]] -> Matrix a b\nfromList list = Matrix rows cols vals where\n rows = length list\n cols = L.foldl' max 0 $ P.map length list\n vals = VS.create $ do\n vm <- VSM.replicate (rows * cols) (I.cast (0 `asTypeOf` (head (head list))))\n forM_ (zip [0..] list) $ \\(row, vals) ->\n forM_ (zip [0..] vals) $ \\(col, val) ->\n VSM.write vm (col * rows + row) (I.cast val)\n return vm\n\n-- | Convert matrix to a list of rows\ntoList :: I.Elem a b => Matrix a b -> [[a]]\ntoList m@(Matrix rows cols vals)\n | not (valid m) = error \"matrix is not valid\"\n | otherwise = [[I.cast $ vals `VS.unsafeIndex` (col * rows + row) | col <- [0..pred cols]] | row <- [0..pred rows]]\n\n-- | Build matrix of given dimensions and values from given list split on rows. Invalid list length results in error.\nfromFlatList :: I.Elem a b => Int -> Int -> [a] -> Matrix a b\nfromFlatList rows cols list\n | not (rows * cols == (length list)) = error $ concat [\"cannot construct \", show rows, \"x\", show cols, \" matrix from \", show $ length list, \" values\"]\n | otherwise = Matrix rows cols vals where\n vals = VS.create $ do\n vm <- VSM.replicate (rows * cols) (I.cast (0 `asTypeOf` (head list)))\n forM_ (zip [(col * rows + row) | row <- [0..pred rows], col <- [0..pred cols]] list) $ \\(idx, val) ->\n VSM.write vm idx (I.cast val)\n return vm\n\n-- | Convert matrix to a list by concatenating rows\ntoFlatList :: I.Elem a b => Matrix a b -> [a]\ntoFlatList m@(Matrix rows cols vals)\n | not (valid m) = error \"matrix is not valid\"\n | otherwise = [I.cast $ vals `VS.unsafeIndex` (col * rows + row) | row <- [0..pred rows], col <- [0..pred cols]]\n\n-- | [generate rows cols (λ row col -> val)]\n--\n-- Create matrix using generator function @λ row col -> val@\n--\ngenerate :: I.Elem a b => Int -> Int -> (Int -> Int -> a) -> Matrix a b\ngenerate rows cols f = Matrix rows cols $ VS.create $ do\n vals <- VSM.new (rows * cols)\n forM_ [0..pred rows] $ \\row ->\n forM_ [0..pred cols] $ \\col ->\n VSM.write vals (col * rows + row) (I.cast $ f row col)\n return vals\n\n-- | The sum of all coefficients of the matrix\nsum :: I.Elem a b => Matrix a b -> a\nsum = _prop I.sum\n\n-- | The product of all coefficients of the matrix\nprod :: I.Elem a b => Matrix a b -> a\nprod = _prop I.prod\n\n-- | The mean of all coefficients of the matrix\nmean :: I.Elem a b => Matrix a b -> a\nmean = _prop I.mean\n\n-- | The trace of a matrix is the sum of the diagonal coefficients and can also be computed as sum (diagonal m)\ntrace :: I.Elem a b => Matrix a b -> a\ntrace = _prop I.trace\n\n-- | Applied to a predicate and a matrix, all determines if all elements of the matrix satisfies the predicate\nall :: I.Elem a b => (a -> Bool) -> Matrix a b -> Bool\nall f = VS.all (f . I.cast) . _vals\n\n-- | Applied to a predicate and a matrix, any determines if any element of the matrix satisfies the predicate\nany :: I.Elem a b => (a -> Bool) -> Matrix a b -> Bool\nany f = VS.any (f . I.cast) . _vals\n\n-- | Returns the number of coefficients in a given matrix that evaluate to true\ncount :: I.Elem a b => (a -> Bool) -> Matrix a b -> Int\ncount f = VS.foldl' (\\n x -> if f (I.cast x) then succ n else n) 0 . _vals\n\n{-| For vectors, the l2 norm, and for matrices the Frobenius norm.\n In both cases, it consists in the square root of the sum of the square of all the matrix entries.\n For vectors, this is also equals to the square root of the dot product of this with itself.\n-}\nnorm :: I.Elem a b => Matrix a b -> a\nnorm = _prop I.norm\n\n-- | For vectors, the squared l2 norm, and for matrices the Frobenius norm. In both cases, it consists in the sum of the square of all the matrix entries. For vectors, this is also equals to the dot product of this with itself.\nsquaredNorm :: I.Elem a b => Matrix a b -> a\nsquaredNorm = _prop I.squaredNorm\n\n-- | The l2 norm of the matrix using the Blue's algorithm. A Portable Fortran Program to Find the Euclidean Norm of a Vector, ACM TOMS, Vol 4, Issue 1, 1978.\nblueNorm :: I.Elem a b => Matrix a b -> a\nblueNorm = _prop I.blueNorm\n\n-- | The l2 norm of the matrix avoiding undeflow and overflow. This version use a concatenation of hypot calls, and it is very slow.\nhypotNorm :: I.Elem a b => Matrix a b -> a\nhypotNorm = _prop I.hypotNorm\n\n-- | The determinant of the matrix\ndeterminant :: I.Elem a b => Matrix a b -> a\ndeterminant m\n | square m = _prop I.determinant m\n | otherwise = error \"Matrix.determinant: non-square matrix\"\n\n-- | Adding two matrices by adding the corresponding entries together. You can use @(+)@ function as well.\nadd :: I.Elem a b => Matrix a b -> Matrix a b -> Matrix a b\nadd m1 m2\n | dims m1 == dims m2 = _binop const I.add m1 m2\n | otherwise = error \"Matrix.add: matrices should have the same size\"\n\n-- | Subtracting two matrices by subtracting the corresponding entries together. You can use @(-)@ function as well.\nsub :: I.Elem a b => Matrix a b -> Matrix a b -> Matrix a b\nsub m1 m2\n | dims m1 == dims m2 = _binop const I.sub m1 m2\n | otherwise = error \"Matrix.add: matrices should have the same size\"\n\n-- | Matrix multiplication. You can use @(*)@ function as well.\nmul :: I.Elem a b => Matrix a b -> Matrix a b -> Matrix a b\nmul m1 m2\n | cols m1 == rows m2 = _binop (\\(rows, _) (_, cols) -> (rows, cols)) I.mul m1 m2\n | otherwise = error \"Matrix.mul: number of columns for lhs matrix should be the same as number of rows for rhs matrix\"\n\n{- | Apply a given function to each element of the matrix.\n\nHere is an example how to implement scalar matrix multiplication:\n\n>>> let a = fromList [[1,2],[3,4]] :: MatrixXf\n\n>>> a\nMatrix 2x2\n1.0 2.0\n3.0 4.0\n\n>>> map (*10) a\nMatrix 2x2\n10.0 20.0\n30.0 40.0\n\n-}\nmap :: I.Elem a b => (a -> a) -> Matrix a b -> Matrix a b\nmap f (Matrix rows cols vals) = Matrix rows cols (VS.map (I.cast . f . I.cast) vals)\n\n{- | Apply a given function to each element of the matrix.\n\nHere is an example how upper triangular matrix can be implemented:\n\n>>> let a = fromList [[1,2,3],[4,5,6],[7,8,9]] :: MatrixXf\n\n>>> a\nMatrix 3x3\n1.0 2.0 3.0\n4.0 5.0 6.0\n7.0 8.0 9.0\n\n>>> imap (\\row col val -> if row <= col then val else 0) a\nMatrix 3x3\n1.0 2.0 3.0\n0.0 5.0 6.0\n0.0 0.0 9.0\n\n-}\n\nimap :: I.Elem a b => (Int -> Int -> a -> a) -> Matrix a b -> Matrix a b\nimap f (Matrix rows cols vals) = Matrix rows cols (VS.imap (\\n -> let (c, r) = divMod n rows in I.cast . f r c . I.cast) vals)\n\ndata TriangularMode\n -- | View matrix as a lower triangular matrix.\n = Lower\n -- | View matrix as an upper triangular matrix.\n | Upper\n -- | View matrix as a lower triangular matrix with zeros on the diagonal.\n | StrictlyLower\n -- | View matrix as an upper triangular matrix with zeros on the diagonal.\n | StrictlyUpper\n -- | View matrix as a lower triangular matrix with ones on the diagonal.\n | UnitLower\n -- | View matrix as an upper triangular matrix with ones on the diagonal.\n | UnitUpper deriving (Eq, Enum, Show, Read)\n\n-- | Triangular view extracted from the current matrix\ntriangularView :: I.Elem a b => TriangularMode -> Matrix a b -> Matrix a b\ntriangularView Lower = imap $ \\row col val -> case compare row col of { LT -> 0; _ -> val }\ntriangularView Upper = imap $ \\row col val -> case compare row col of { GT -> 0; _ -> val }\ntriangularView StrictlyLower = imap $ \\row col val -> case compare row col of { GT -> val; _ -> 0 }\ntriangularView StrictlyUpper = imap $ \\row col val -> case compare row col of { LT -> val; _ -> 0 }\ntriangularView UnitLower = imap $ \\row col val -> case compare row col of { GT -> val; LT -> 0; EQ -> 1 }\ntriangularView UnitUpper = imap $ \\row col val -> case compare row col of { LT -> val; GT -> 0; EQ -> 1 }\n\n-- | Lower trinagle of the matrix. Shortcut for @triangularView Lower@\nlowerTriangle :: I.Elem a b => Matrix a b -> Matrix a b\nlowerTriangle = triangularView Lower\n\n-- | Upper trinagle of the matrix. Shortcut for @triangularView Upper@\nupperTriangle :: I.Elem a b => Matrix a b -> Matrix a b\nupperTriangle = triangularView Upper\n\n-- | Filter elements in the matrix. Filtered elements will be replaced by 0\nfilter :: I.Elem a b => (a -> Bool) -> Matrix a b -> Matrix a b\nfilter f = map (\\x -> if f x then x else 0)\n\n-- | Filter elements in the matrix. Filtered elements will be replaced by 0\nifilter :: I.Elem a b => (Int -> Int -> a -> Bool) -> Matrix a b -> Matrix a b\nifilter f = imap (\\r c x -> if f r c x then x else 0)\n\n-- | Reduce matrix using user provided function applied to each element.\nfold :: I.Elem a b => (c -> a -> c) -> c -> Matrix a b -> c\nfold f a (Matrix _ _ vals) = VS.foldl (\\a x -> f a (I.cast x)) a vals\n\n-- | Reduce matrix using user provided function applied to each element. This is strict version of 'fold'\nfold' :: I.Elem a b => (c -> a -> c) -> c -> Matrix a b -> c\nfold' f a (Matrix _ _ vals) = VS.foldl' (\\a x -> f a (I.cast x)) a vals\n\n-- | Reduce matrix using user provided function applied to each element and it's index\nifold :: I.Elem a b => (Int -> Int -> c -> a -> c) -> c -> Matrix a b -> c\nifold f a (Matrix rows _ vals) = VS.ifoldl (\\a n x -> let (c,r) = divMod n rows in f r c a (I.cast x)) a vals\n\n-- | Reduce matrix using user provided function applied to each element and it's index. This is strict version of 'ifold'\nifold' :: I.Elem a b => (Int -> Int -> c -> a -> c) -> c -> Matrix a b -> c\nifold' f a (Matrix rows _ vals) = VS.ifoldl' (\\a n x -> let (c,r) = divMod n rows in f r c a (I.cast x)) a vals\n\n-- | Reduce matrix using user provided function applied to each element.\nfold1 :: I.Elem a b => (a -> a -> a) -> Matrix a b -> a\nfold1 f = foldl1 f . P.map I.cast . VS.toList . _vals\n\n-- | Reduce matrix using user provided function applied to each element. This is strict version of 'fold'\nfold1' :: I.Elem a b => (a -> a -> a) -> Matrix a b -> a\nfold1' f = L.foldl1' f . P.map I.cast . VS.toList . _vals\n\n-- | Diagonal of the matrix\ndiagonal :: I.Elem a b => Matrix a b -> Matrix a b\ndiagonal = _unop (\\(rows, cols) -> (min rows cols, 1)) I.diagonal\n\n{- | Inverse of the matrix\n\nFor small fixed sizes up to 4x4, this method uses cofactors. In the general case, this method uses PartialPivLU decomposition\n-}\ninverse :: I.Elem a b => Matrix a b -> Matrix a b\ninverse m\n | square m = _unop id I.inverse m\n | otherwise = error \"Matrix.inverse: non-square matrix\"\n\n-- | Adjoint of the matrix\nadjoint :: I.Elem a b => Matrix a b -> Matrix a b\nadjoint = _unop swap I.adjoint\n\n-- | Transpose of the matrix\ntranspose :: I.Elem a b => Matrix a b -> Matrix a b\ntranspose = _unop swap I.transpose\n\n-- | Conjugate of the matrix\nconjugate :: I.Elem a b => Matrix a b -> Matrix a b\nconjugate = _unop id I.conjugate\n\n-- | Nomalize the matrix by deviding it on its 'norm'\nnormalize :: I.Elem a b => Matrix a b -> Matrix a b\nnormalize (Matrix rows cols vals) = I.performIO $ do\n vals <- VS.thaw vals\n VSM.unsafeWith vals $ \\p ->\n I.call $ I.normalize p (I.cast rows) (I.cast cols)\n Matrix rows cols <$> VS.unsafeFreeze vals\n\n-- | Apply a destructive operation to a matrix. The operation will be performed in place if it is safe to do so and will modify a copy of the matrix otherwise.\nmodify :: I.Elem a b => (forall s. M.MMatrix a b s -> ST s ()) -> Matrix a b -> Matrix a b\nmodify f (Matrix rows cols vals) = Matrix rows cols (VS.modify (f . M.MMatrix rows cols) vals)\n\n-- | Convert matrix to different type using user provided element converter\nconvert :: (I.Elem a b, I.Elem c d) => (a -> c) -> Matrix a b -> Matrix c d\nconvert f (Matrix rows cols vals) = Matrix rows cols $ VS.map (I.cast . f . I.cast) vals\n\n-- | Yield an immutable copy of the mutable matrix\nfreeze :: I.Elem a b => PrimMonad m => M.MMatrix a b (PrimState m) -> m (Matrix a b)\nfreeze (M.MMatrix mrows mcols mvals) = VS.freeze mvals >>= return . Matrix mrows mcols\n\n-- | Yield a mutable copy of the immutable matrix\nthaw :: I.Elem a b => PrimMonad m => Matrix a b -> m (M.MMatrix a b (PrimState m))\nthaw (Matrix rows cols vals) = VS.thaw vals >>= return . M.MMatrix rows cols\n\n-- | Unsafe convert a mutable matrix to an immutable one without copying. The mutable matrix may not be used after this operation.\nunsafeFreeze :: I.Elem a b => PrimMonad m => M.MMatrix a b (PrimState m) -> m (Matrix a b)\nunsafeFreeze (M.MMatrix mrows mcols mvals) = VS.unsafeFreeze mvals >>= return . Matrix mrows mcols\n\n-- | Unsafely convert an immutable matrix to a mutable one without copying. The immutable matrix may not be used after this operation.\nunsafeThaw :: I.Elem a b => PrimMonad m => Matrix a b -> m (M.MMatrix a b (PrimState m))\nunsafeThaw (Matrix rows cols vals) = VS.unsafeThaw vals >>= return . M.MMatrix rows cols\n\n-- | Pass a pointer to the matrix's data to the IO action. The data may not be modified through the pointer.\nunsafeWith :: I.Elem a b => Matrix a b -> (Ptr b -> CInt -> CInt -> IO c) -> IO c\nunsafeWith m@(Matrix rows cols vals) f\n | not (valid m) = fail \"Matrix.unsafeWith: matrix layout is invalid\"\n | otherwise = VS.unsafeWith vals $ \\p -> f p (I.cast rows) (I.cast cols)\n\n{-# INLINE _prop #-}\n_prop :: I.Elem a b => (Ptr b -> Ptr b -> CInt -> CInt -> IO CString) -> Matrix a b -> a\n_prop f m = I.cast $ I.performIO $ alloca $ \\p -> do\n I.call $ unsafeWith m (f p)\n peek p\n\n{-# INLINE _binop #-}\n_binop :: I.Elem a b => ((Int, Int) -> (Int, Int) -> (Int, Int)) -> (Ptr b -> CInt -> CInt -> Ptr b -> CInt -> CInt -> Ptr b -> CInt -> CInt -> IO CString) -> Matrix a b -> Matrix a b -> Matrix a b\n_binop f g m1 m2 = I.performIO $ do\n m0 <- uncurry M.new $ f (dims m1) (dims m2)\n M.unsafeWith m0 $ \\vals0 rows0 cols0 ->\n unsafeWith m1 $ \\vals1 rows1 cols1 ->\n unsafeWith m2 $ \\vals2 rows2 cols2 ->\n I.call $ g\n vals0 rows0 cols0\n vals1 rows1 cols1\n vals2 rows2 cols2\n unsafeFreeze m0\n\n{-# INLINE _unop #-}\n_unop :: I.Elem a b => ((Int,Int) -> (Int,Int)) -> (Ptr b -> CInt -> CInt -> Ptr b -> CInt -> CInt -> IO CString) -> Matrix a b -> Matrix a b\n_unop f g m1 = I.performIO $ do\n m0 <- uncurry M.new $ f (dims m1)\n M.unsafeWith m0 $ \\vals0 rows0 cols0 ->\n unsafeWith m1 $ \\vals1 rows1 cols1 ->\n I.call $ g\n vals0 rows0 cols0\n vals1 rows1 cols1\n unsafeFreeze m0\n\n{-# INLINE _vals #-}\n_vals :: I.Elem a b => Matrix a b -> VS.Vector b\n_vals (Matrix _ _ vals) = vals\n", "meta": {"hexsha": "76c22d03b4ea80352e8427cb39b92acbd7aa22b2", "size": 23325, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Eigen/Matrix.hs", "max_stars_repo_name": "osidorkin/haskell-eigen", "max_stars_repo_head_hexsha": "2537faa99d3714d6a4c7621433f854e46f07f296", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2015-04-06T06:36:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T08:19:06.000Z", "max_issues_repo_path": "Data/Eigen/Matrix.hs", "max_issues_repo_name": "osidorkin/haskell-eigen", "max_issues_repo_head_hexsha": "2537faa99d3714d6a4c7621433f854e46f07f296", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2015-04-06T06:36:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-21T18:13:08.000Z", "max_forks_repo_path": "Data/Eigen/Matrix.hs", "max_forks_repo_name": "osidorkin/haskell-eigen", "max_forks_repo_head_hexsha": "2537faa99d3714d6a4c7621433f854e46f07f296", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-03-29T07:08:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-09T03:08:23.000Z", "avg_line_length": 36.9066455696, "max_line_length": 227, "alphanum_fraction": 0.6356698821, "num_tokens": 6753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5, "lm_q1q2_score": 0.31851539724019157}} {"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE UndecidableInstances #-}\nmodule Math.HiddenMarkovModel.Private where\n\nimport qualified Math.HiddenMarkovModel.Distribution as Distr\nimport qualified Math.HiddenMarkovModel.CSV as HMMCSV\nimport Math.HiddenMarkovModel.Distribution (State(State))\n\nimport qualified Numeric.LinearAlgebra.Algorithms as Algo\nimport qualified Numeric.LinearAlgebra.Util as LinAlg\nimport qualified Numeric.Container as NC\nimport qualified Data.Packed.Development as Dev\nimport qualified Data.Packed.Matrix as Matrix\nimport qualified Data.Packed.Vector as Vector\nimport Numeric.Container ((<>))\nimport Data.Packed.Matrix (Matrix)\nimport Data.Packed.Vector (Vector)\n\nimport Control.DeepSeq (NFData, rnf)\nimport Foreign.Storable (Storable)\n\nimport qualified Data.NonEmpty.Class as NonEmptyC\nimport qualified Data.NonEmpty as NonEmpty\nimport qualified Data.Semigroup as Sg\nimport qualified Data.List as List\nimport Data.Traversable (Traversable, mapAccumL)\nimport Data.Tuple.HT (mapPair, mapFst, mapSnd, swap)\n\n\n{- |\nA Hidden Markov model consists of a number of (hidden) states\nand a set of emissions.\nThere is a vector for the initial probability of each state\nand a matrix containing the probability for switching\nfrom one state to another one.\nThe 'distribution' field points to probability distributions\nthat associate every state with emissions of different probability.\nFamous distribution instances are discrete and Gaussian distributions.\nSee \"Math.HiddenMarkovModel.Distribution\" for details.\n\nThe transition matrix is transposed\nwith respect to popular HMM descriptions.\nBut I think this is the natural orientation, because this way\nyou can write \\\"transition matrix times probability column vector\\\".\n\nThe type has two type parameters,\nalthough the one for the distribution would be enough.\nHowever, replacing @prob@ by @Distr.Probability distr@\nwould prohibit the derived Show and Read instances.\n-}\ndata T distr prob =\n Cons {\n initial :: Vector prob,\n transition :: Matrix prob,\n distribution :: distr\n }\n deriving (Show, Read)\n\ninstance\n (NFData distr, NFData prob, Storable prob) =>\n NFData (T distr prob) where\n rnf hmm = rnf (initial hmm, transition hmm, distribution hmm)\n\n\nemission ::\n (Distr.EmissionProb distr,\n Distr.Probability distr ~ prob, Distr.Emission distr ~ emission) =>\n T distr prob -> emission -> Vector prob\nemission = Distr.emissionProb . distribution\n\n\nforward ::\n (Distr.EmissionProb distr,\n Distr.Probability distr ~ prob, Distr.Emission distr ~ emission,\n Traversable f) =>\n T distr prob -> NonEmpty.T f emission -> prob\nforward hmm = NC.sumElements . NonEmpty.last . alpha hmm\n\nalpha ::\n (Distr.EmissionProb distr,\n Distr.Probability distr ~ prob, Distr.Emission distr ~ emission,\n Traversable f) =>\n T distr prob ->\n NonEmpty.T f emission -> NonEmpty.T f (Vector prob)\nalpha hmm (NonEmpty.Cons x xs) =\n NonEmpty.scanl\n (\\alphai xi -> NC.mul (emission hmm xi) (transition hmm <> alphai))\n (NC.mul (emission hmm x) (initial hmm))\n xs\n\n\nbackward ::\n (Distr.EmissionProb distr,\n Distr.Probability distr ~ prob, Distr.Emission distr ~ emission,\n Traversable f) =>\n T distr prob -> NonEmpty.T f emission -> prob\nbackward hmm (NonEmpty.Cons x xs) =\n NC.sumElements $\n NC.mul (initial hmm) $\n NC.mul (emission hmm x) $\n NonEmpty.head $ beta hmm xs\n\nbeta ::\n (Distr.EmissionProb distr,\n Distr.Probability distr ~ prob, Distr.Emission distr ~ emission,\n Traversable f) =>\n T distr prob ->\n f emission -> NonEmpty.T f (Vector prob)\nbeta hmm =\n NonEmpty.scanr\n (\\xi betai -> NC.mul (emission hmm xi) betai <> transition hmm)\n (NC.constant 1 (NC.dim $ initial hmm))\n\n\nalphaBeta ::\n (Distr.EmissionProb distr,\n Distr.Probability distr ~ prob, Distr.Emission distr ~ emission,\n Traversable f) =>\n T distr prob ->\n NonEmpty.T f emission ->\n (prob, NonEmpty.T f (Vector prob), NonEmpty.T f (Vector prob))\nalphaBeta hmm xs =\n let alphas = alpha hmm xs\n betas = beta hmm $ NonEmpty.tail xs\n recipLikelihood = recip $ NC.sumElements $ NonEmpty.last alphas\n in (recipLikelihood, alphas, betas)\n\n\n\nxiFromAlphaBeta ::\n (Distr.EmissionProb distr,\n Distr.Probability distr ~ prob, Distr.Emission distr ~ emission) =>\n T distr prob -> prob ->\n NonEmpty.T [] emission ->\n NonEmpty.T [] (Vector prob) ->\n NonEmpty.T [] (Vector prob) ->\n [Matrix prob]\nxiFromAlphaBeta hmm recipLikelihood xs alphas betas =\n zipWith3\n (\\x alpha0 beta1 ->\n NC.scale recipLikelihood $\n NC.mul\n (NC.outer (NC.mul (emission hmm x) beta1) alpha0)\n (transition hmm))\n (NonEmpty.tail xs)\n (NonEmpty.init alphas)\n (NonEmpty.tail betas)\n\nzetaFromXi ::\n (NC.Product prob) => T distr prob -> [Matrix prob] -> [Vector prob]\nzetaFromXi hmm xis =\n map (NC.constant 1 (Matrix.rows $ transition hmm) <>) xis\n\nzetaFromAlphaBeta ::\n (NC.Container Vector prob) =>\n prob ->\n NonEmpty.T [] (Vector prob) ->\n NonEmpty.T [] (Vector prob) ->\n NonEmpty.T [] (Vector prob)\nzetaFromAlphaBeta recipLikelihood alphas betas =\n fmap (NC.scale recipLikelihood) $\n NonEmptyC.zipWith NC.mul alphas betas\n\n\n{- |\nIn constrast to Math.HiddenMarkovModel.reveal\nthis does not normalize the vector.\nThis is slightly simpler but for long sequences\nthe product of probabilities might be smaller\nthan the smallest representable number.\n-}\nreveal ::\n (Distr.EmissionProb distr,\n Distr.Probability distr ~ prob, Distr.Emission distr ~ emission,\n Traversable f) =>\n T distr prob -> NonEmpty.T f emission -> NonEmpty.T f State\nreveal hmm (NonEmpty.Cons x xs) =\n fmap State $\n uncurry (NonEmpty.scanr Dev.at') $\n mapFst NC.maxIndex $\n mapAccumL\n (\\alphai xi ->\n swap $ mapSnd (NC.mul (emission hmm xi)) $\n matrixMaxMul (transition hmm) alphai)\n (NC.mul (emission hmm x) (initial hmm)) xs\n\nmatrixMaxMul ::\n (NC.Container Vector a) =>\n Matrix a -> Vector a -> (Vector Int, Vector a)\nmatrixMaxMul m v =\n mapPair (Vector.fromList, Vector.fromList) $ unzip $\n map ((\\x -> (NC.maxIndex x, NC.maxElement x)) . NC.mul v) $\n Matrix.toRows m\n\n\n\n{- |\nA trained model is a temporary form of a Hidden Markov model\nthat we need during the training on multiple training sequences.\nIt allows to collect knowledge over many sequences with 'mergeTrained',\neven with mixed supervised and unsupervised training.\nYou finish the training by converting the trained model\nback to a plain modul using 'finishTraining'.\n\nYou can create a trained model in three ways:\n\n* supervised training using an emission sequence with associated states,\n\n* unsupervised training using an emission sequence and an existing Hidden Markov Model,\n\n* derive it from state sequence patterns, cf. \"Math.HiddenMarkovModel.Pattern\".\n-}\ndata Trained distr prob =\n Trained {\n trainedInitial :: Vector prob,\n trainedTransition :: Matrix prob,\n trainedDistribution :: distr\n }\n deriving (Show, Read)\n\ninstance\n (NFData distr, NFData prob, Storable prob) =>\n NFData (Trained distr prob) where\n rnf hmm =\n rnf (trainedInitial hmm, trainedTransition hmm, trainedDistribution hmm)\n\n\nsumTransitions ::\n (NC.Container Vector e) =>\n T distr e -> [Matrix e] -> Matrix e\nsumTransitions hmm =\n List.foldl' NC.add (NC.konst 0 $ LinAlg.size $ transition hmm)\n\n{- |\nBaum-Welch algorithm\n-}\ntrainUnsupervised ::\n (Distr.Estimate tdistr, Distr.Distribution tdistr ~ distr,\n Distr.Probability distr ~ prob, Distr.Emission distr ~ emission) =>\n T distr prob -> NonEmpty.T [] emission -> Trained tdistr prob\ntrainUnsupervised hmm xs =\n let (recipLikelihood, alphas, betas) = alphaBeta hmm xs\n zetas = zetaFromAlphaBeta recipLikelihood alphas betas\n\n in Trained {\n trainedInitial = NonEmpty.head zetas,\n trainedTransition =\n sumTransitions hmm $\n xiFromAlphaBeta hmm recipLikelihood xs alphas betas,\n trainedDistribution =\n Distr.accumulateEmissions $ map (zip (NonEmpty.flatten xs)) $\n List.transpose $ map Vector.toList $ NonEmpty.flatten zetas\n }\n\n\nmergeTrained ::\n (Distr.Estimate tdistr, Distr.Distribution tdistr ~ distr,\n Distr.Probability distr ~ prob) =>\n Trained tdistr prob -> Trained tdistr prob -> Trained tdistr prob\nmergeTrained hmm0 hmm1 =\n Trained {\n trainedInitial = NC.add (trainedInitial hmm0) (trainedInitial hmm1),\n trainedTransition =\n NC.add (trainedTransition hmm0) (trainedTransition hmm1),\n trainedDistribution =\n Distr.combine\n (trainedDistribution hmm0) (trainedDistribution hmm1)\n }\n\ninstance\n (Distr.Estimate tdistr, Distr.Distribution tdistr ~ distr,\n Distr.Probability distr ~ prob) =>\n Sg.Semigroup (Trained tdistr prob) where\n (<>) = mergeTrained\n\n\ntoCells ::\n (Distr.CSV distr, Algo.Field prob, Show prob) =>\n T distr prob -> [[String]]\ntoCells hmm =\n (HMMCSV.cellsFromVector $ initial hmm) :\n (HMMCSV.cellsFromMatrix $ transition hmm) ++\n [] :\n (Distr.toCells $ distribution hmm)\n\nparseCSV ::\n (Distr.CSV distr, Algo.Field prob, Read prob) =>\n HMMCSV.CSVParser (T distr prob)\nparseCSV = do\n v <- HMMCSV.parseNonEmptyVectorCells\n m <- HMMCSV.parseSquareMatrixCells $ Vector.dim v\n HMMCSV.skipEmptyRow\n distr <- Distr.parseCells $ Vector.dim v\n return $ Cons {\n initial = v,\n transition = m,\n distribution = distr\n }\n", "meta": {"hexsha": "6ce10e1b7467da03ca19aee547ee254e7b53e71a", "size": 9524, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/HiddenMarkovModel/Private.hs", "max_stars_repo_name": "rybern/hmm-hmatrix", "max_stars_repo_head_hexsha": "3f1c44aa630e0c7a662c1abe100ea8e783e3c44e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Math/HiddenMarkovModel/Private.hs", "max_issues_repo_name": "rybern/hmm-hmatrix", "max_issues_repo_head_hexsha": "3f1c44aa630e0c7a662c1abe100ea8e783e3c44e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/HiddenMarkovModel/Private.hs", "max_forks_repo_name": "rybern/hmm-hmatrix", "max_forks_repo_head_hexsha": "3f1c44aa630e0c7a662c1abe100ea8e783e3c44e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7466666667, "max_line_length": 87, "alphanum_fraction": 0.705900882, "num_tokens": 2401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.31623421443846256}} {"text": "-- |\n-- Module : Cartesian.Internal.Types\n-- Description :\n-- Copyright : (c) Jonatan H Sundqvist, 2015\n-- License : MIT\n-- Maintainer : Jonatan H Sundqvist\n-- Stability : experimental|stable\n-- Portability : POSIX (not sure)\n--\n\n-- Created October 31 2015\n\n-- TODO | - Use TemplateHaskell (?)\n-- - Strictness\n-- - Performance, inlining\n\n-- SPEC | -\n-- -\n\n\n\n------------------------------------------------------------------------------------------------------------------------------------------------------\n-- GHC Pragmas\n------------------------------------------------------------------------------------------------------------------------------------------------------\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleInstances #-}\n\n\n------------------------------------------------------------------------------------------------------------------------------------------------------\n-- API\n------------------------------------------------------------------------------------------------------------------------------------------------------\nmodule Cartesian.Internal.Types where\n\n\n\n------------------------------------------------------------------------------------------------------------------------------------------------------\n-- We'll need these\n------------------------------------------------------------------------------------------------------------------------------------------------------\nimport Control.Lens (Simple, Lens, lens)\n\nimport Data.Complex (Complex(..))\n\nimport Linear.V1\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\n\n\n\n------------------------------------------------------------------------------------------------------------------------------------------------------\n-- Types\n------------------------------------------------------------------------------------------------------------------------------------------------------\n\n-- Synonyms ------------------------------------------------------------------------------------------------------------------------------------------\n\n-- TODO: Add some aliased lenses for these aliased types (?)\n\n-- | A lens focusing on a single [vector-]component in a BoundingBox\ntype BoxLens v v' f f' = Lens (BoundingBox (v f)) (BoundingBox (v' f')) f f'\n\n\n-- | An axis represented as (begin, length)\ntype Axis a = (a, a)\n\n\n-- | A vector where each component represents a single axis (cf. 'Axis')\ntype Axes v a = v (Axis a)\n\n\n-- |\n-- type Domain\n\n\n-- |\n-- TODO: Rename (eg. 'Shape') (?)\ntype Polygon m v f = m (v f)\n\n\n-- | Coordinate system wrappers\nnewtype Normalised v = Normalised { absolute :: v } -- \nnewtype Absolute v = Absoloute { normalised :: v } -- \n\n-- Types ---------------------------------------------------------------------------------------------------------------------------------------------\n\n-- |\n-- TODO: Anchors (eg. C, N, S, E W and combinations thereof, perhaps represented as relative Vectors)\n-- TODO: Define some standard instances (eg. Functor, Applicative)\ndata BoundingBox v = BoundingBox { cornerOf :: v, sizeOf :: v } deriving (Show, Eq)\n\n\n-- |\n-- TODO: Use record (eg. from, to) (?)\ndata Line v = Line v v deriving (Show, Eq)\n\n\n-- |\ndata Linear f = Linear { interceptOf :: f, slopeOf :: f } deriving (Show, Eq)\n\n\n-- |\ndata Inclusivity r = Inclusive r | Exclusive r -- TODO: Rename (?)\ndata Interval r = Interval (Inclusivity r) (Inclusivity r)\n\n\n-- |\n-- TODO: Use existing type instead (?)\n-- data Side = SideLeft | SideRight | SideTop | SideBottom\n\n-- Classes -------------------------------------------------------------------------------------------------------------------------------------------\n\n-- TODO: How do you generate lenses for non-record types (?)\nclass HasX a f | a -> f where { x :: Simple Lens a f }\nclass HasY a f | a -> f where { y :: Simple Lens a f }\nclass HasZ a f | a -> f where { z :: Simple Lens a f }\n\n-- Instances -----------------------------------------------------------------------------------------------------------------------------------------\n\n\n-- TODO: Generate these instances with TemplateHaskell (?)\n\ninstance HasX (V1 f) f where\n x = lens (\\(V1 x') -> x') (\\_ x' -> V1 x')\n\n\ninstance HasX (V2 f) f where\n x = lens (\\(V2 x' _) -> x') (\\(V2 _ y') x' -> V2 x' y')\n\n\ninstance HasY (V2 f) f where\n y = lens (\\(V2 _ y') -> y') (\\(V2 x' _) y' -> V2 x' y')\n\n\ninstance HasX (V3 f) f where\n x = lens (\\(V3 x' _ _) -> x') (\\(V3 _ y' z') x' -> V3 x' y' z')\n\n\ninstance HasY (V3 f) f where\n y = lens (\\(V3 _ y' _) -> y') (\\(V3 x' _ z') y' -> V3 x' y' z')\n\n\ninstance HasZ (V3 f) f where\n z = lens (\\(V3 _ _ z') -> z') (\\(V3 x' y' _) z' -> V3 x' y' z')\n\n\ninstance HasX (V4 f) f where\n x = lens (\\(V4 x' _ _ _) -> x') (\\(V4 _ y' z' w') x' -> V4 x' y' z' w')\n\n\ninstance HasY (V4 f) f where\n y = lens (\\(V4 _ y' _ _) -> y') (\\(V4 x' _ z' w') y' -> V4 x' y' z' w')\n\n\ninstance HasZ (V4 f) f where\n z = lens (\\(V4 _ _ z' _) -> z') (\\(V4 x' y' _ w') z' -> V4 x' y' z' w')\n\n\ninstance HasX (Complex f) f where\n x = lens (\\(x':+_) -> x') (\\(_:+y') x' -> x':+y')\n\n\ninstance HasY (Complex f) f where\n y = lens (\\(_':+y') -> y') (\\(x':+_) y' -> x':+y')\n\n", "meta": {"hexsha": "d5debf4bc75ac8818ad4dd49c745d17d69e3719a", "size": 5270, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Cartesian/Internal/Types.hs", "max_stars_repo_name": "SwiftsNamesake/Cartesian", "max_stars_repo_head_hexsha": "42791378b1453b422692dd78e05977e5f8f577f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-01-05T13:11:24.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-05T13:11:24.000Z", "max_issues_repo_path": "src/Cartesian/Internal/Types.hs", "max_issues_repo_name": "SwiftsNamesake/Cartesian", "max_issues_repo_head_hexsha": "42791378b1453b422692dd78e05977e5f8f577f5", "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/Cartesian/Internal/Types.hs", "max_forks_repo_name": "SwiftsNamesake/Cartesian", "max_forks_repo_head_hexsha": "42791378b1453b422692dd78e05977e5f8f577f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-12T23:31:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-12T23:31:50.000Z", "avg_line_length": 31.5568862275, "max_line_length": 150, "alphanum_fraction": 0.3865275142, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.31415079150761527}} {"text": "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GADTs #-}\nmodule Grenade.Layers.Internal.Update (\n descendMatrix\n , descendVector\n , MatrixInputValues (..)\n , MatrixResult (..)\n , VectorInputValues (..)\n , VectorResult (..)\n ) where\n\nimport Data.Maybe (fromJust)\nimport qualified Data.Vector.Storable as U (unsafeFromForeignPtr0,\n unsafeToForeignPtr0)\nimport Foreign (mallocForeignPtrArray, withForeignPtr)\nimport Foreign.Ptr (Ptr)\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra (Vector, flatten)\nimport qualified Numeric.LinearAlgebra.Devel as U\nimport Numeric.LinearAlgebra.Static\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport Grenade.Core.Optimizer\nimport Grenade.Types\n\ndata MatrixInputValues rows columns\n = MatrixValuesSGD\n !(L rows columns) -- ^ current weights\n !(L rows columns) -- ^ gradients\n !(L rows columns) -- ^ last update (old momentum)\n | MatrixValuesAdam\n !Int -- ^ Step\n !(L rows columns) -- ^ current weights\n !(L rows columns) -- ^ gradients\n !(L rows columns) -- ^ current m\n !(L rows columns) -- ^ current v\n\n\ndata MatrixResult rows columns\n = MatrixResultSGD\n { matrixActivations :: !(L rows columns) -- ^ new activations (weights)\n , matrixMomentum :: !(L rows columns) -- ^ new momentum\n }\n | MatrixResultAdam\n { matrixActivations :: !(L rows columns) -- ^ new activations (weights)\n , matrixM :: !(L rows columns) -- ^ new m\n , matrixV :: !(L rows columns) -- ^ new v\n }\n\ndata VectorInputValues r\n = VectorValuesSGD\n !(R r) -- ^ current weights\n !(R r) -- ^ gradients\n !(R r) -- ^ last update (old momentum)\n | VectorValuesAdam\n !Int -- ^ Step\n !(R r) -- ^ current weights\n !(R r) -- ^ current gradients\n !(R r) -- ^ current m\n !(R r) -- ^ current v\n\ndata VectorResult r\n = VectorResultSGD\n { vectorBias :: !(R r) -- ^ new activations (bias)\n , vectorMomentum :: !(R r) -- ^ new momentum\n }\n | VectorResultAdam\n { vectorBias :: !(R r) -- ^ new activations (bias)\n , vectorM :: !(R r) -- ^ new m\n , vectorV :: !(R r) -- ^ new v\n }\n\ndescendMatrix :: (KnownNat rows, KnownNat columns) => Optimizer o -> MatrixInputValues rows columns -> MatrixResult rows columns\ndescendMatrix (OptSGD rate momentum regulariser) (MatrixValuesSGD weights gradient lastUpdate) =\n let (rows, cols) = size weights\n len = rows * cols\n -- Most gradients come in in ColumnMajor,\n -- so we'll transpose here before flattening them\n -- into a vector to prevent a copy.\n --\n -- This gives ~15% speed improvement for LSTMs.\n weights' = flatten . tr . extract $ weights\n gradient' = flatten . tr . extract $ gradient\n lastUpdate' = flatten . tr . extract $ lastUpdate\n (vw, vm) = descendUnsafeSGD len rate momentum regulariser weights' gradient' lastUpdate'\n\n -- Note that it's ColumnMajor, as we did a transpose before\n -- using the internal vectors.\n mw = U.matrixFromVector U.ColumnMajor rows cols vw\n mm = U.matrixFromVector U.ColumnMajor rows cols vm\n in MatrixResultSGD (fromJust . create $ mw) (fromJust . create $ mm)\ndescendMatrix (OptAdam alpha beta1 beta2 epsilon lambda) (MatrixValuesAdam step weights gradient m v) =\n let (rows, cols) = size weights\n len = rows * cols\n -- Most gradients come in in ColumnMajor,\n -- so we'll transpose here before flattening them\n -- into a vector to prevent a copy.\n --\n -- This gives ~15% speed improvement for LSTMs.\n weights' = flatten . tr . extract $ weights\n gradient' = flatten . tr . extract $ gradient\n m' = flatten . tr . extract $ m\n v' = flatten . tr . extract $ v\n (vw, vm, vv) = descendUnsafeAdam len step alpha beta1 beta2 epsilon lambda weights' gradient' m' v'\n\n -- Note that it's ColumnMajor, as we did a transpose before\n -- using the internal vectors.\n mw = U.matrixFromVector U.ColumnMajor rows cols vw\n mm = U.matrixFromVector U.ColumnMajor rows cols vm\n mv = U.matrixFromVector U.ColumnMajor rows cols vv\n in MatrixResultAdam (fromJust . create $ mw) (fromJust . create $ mm) (fromJust . create $ mv)\ndescendMatrix opt _ = error $ \"optimzer does not match to MatrixInputValues in implementation! Optimizer: \" ++ show opt\n\ndescendVector :: (KnownNat r) => Optimizer o -> VectorInputValues r -> VectorResult r\ndescendVector (OptSGD rate momentum regulariser) (VectorValuesSGD weights gradient lastUpdate) =\n let len = size weights\n weights' = extract weights\n gradient' = extract gradient\n lastUpdate' = extract lastUpdate\n (vw, vm) = descendUnsafeSGD len rate momentum regulariser weights' gradient' lastUpdate'\n in VectorResultSGD (fromJust $ create vw) (fromJust $ create vm)\ndescendVector (OptAdam alpha beta1 beta2 epsilon lambda) (VectorValuesAdam step weights gradient m v) =\n let len = size weights\n weights' = extract weights\n gradient' = extract gradient\n m' = extract m\n v' = extract v\n (vw, vm, vv) = descendUnsafeAdam len step alpha beta1 beta2 epsilon lambda weights' gradient' m' v'\n in VectorResultAdam (fromJust $ create vw) (fromJust $ create vm) (fromJust $ create vv)\ndescendVector opt _ = error $ \"optimzer does not match to VectorInputValues in implementation! Optimizer: \" ++ show opt\n\ndescendUnsafeSGD :: Int -> RealNum -> RealNum -> RealNum -> Vector RealNum -> Vector RealNum -> Vector RealNum -> (Vector RealNum, Vector RealNum)\ndescendUnsafeSGD len rate momentum regulariser weights gradient lastUpdate =\n unsafePerformIO $ do\n outWPtr <- mallocForeignPtrArray len\n outMPtr <- mallocForeignPtrArray len\n let (wPtr, _) = U.unsafeToForeignPtr0 weights\n let (gPtr, _) = U.unsafeToForeignPtr0 gradient\n let (lPtr, _) = U.unsafeToForeignPtr0 lastUpdate\n\n withForeignPtr wPtr $ \\wPtr' ->\n withForeignPtr gPtr $ \\gPtr' ->\n withForeignPtr lPtr $ \\lPtr' ->\n withForeignPtr outWPtr $ \\outWPtr' ->\n withForeignPtr outMPtr $ \\outMPtr' ->\n descend_sgd_cpu len rate momentum regulariser wPtr' gPtr' lPtr' outWPtr' outMPtr'\n\n return (U.unsafeFromForeignPtr0 outWPtr len, U.unsafeFromForeignPtr0 outMPtr len)\n\n\ndescendUnsafeAdam ::\n Int -- Len\n -> Int -- Step\n -> RealNum -- Alpha\n -> RealNum -- Beta1\n -> RealNum -- Beta2\n -> RealNum -- Epsilon\n -> RealNum -- Lambda\n -> Vector RealNum -- Weights\n -> Vector RealNum -- Gradient\n -> Vector RealNum -- M\n -> Vector RealNum -- V\n -> (Vector RealNum, Vector RealNum, Vector RealNum)\ndescendUnsafeAdam len step alpha beta1 beta2 epsilon lambda weights gradient m v =\n unsafePerformIO $ do\n outWPtr <- mallocForeignPtrArray len\n outMPtr <- mallocForeignPtrArray len\n outVPtr <- mallocForeignPtrArray len\n let (wPtr, _) = U.unsafeToForeignPtr0 weights\n let (gPtr, _) = U.unsafeToForeignPtr0 gradient\n let (mPtr, _) = U.unsafeToForeignPtr0 m\n let (vPtr, _) = U.unsafeToForeignPtr0 v\n withForeignPtr wPtr $ \\wPtr' ->\n withForeignPtr gPtr $ \\gPtr' ->\n withForeignPtr mPtr $ \\mPtr' ->\n withForeignPtr vPtr $ \\vPtr' ->\n withForeignPtr outWPtr $ \\outWPtr' ->\n withForeignPtr outMPtr $ \\outMPtr' ->\n withForeignPtr outVPtr $ \\outVPtr' -> descend_adam_cpu len step alpha beta1 beta2 epsilon lambda wPtr' gPtr' mPtr' vPtr' outWPtr' outMPtr' outVPtr'\n return (U.unsafeFromForeignPtr0 outWPtr len, U.unsafeFromForeignPtr0 outMPtr len, U.unsafeFromForeignPtr0 outVPtr len)\n\n\nforeign import ccall unsafe\n descend_sgd_cpu\n :: Int -> RealNum -> RealNum -> RealNum -> Ptr RealNum -> Ptr RealNum -> Ptr RealNum -> Ptr RealNum -> Ptr RealNum -> IO ()\n\nforeign import ccall unsafe\n descend_adam_cpu\n :: Int -> Int -> RealNum -> RealNum -> RealNum -> RealNum -> RealNum -> Ptr RealNum -> Ptr RealNum -> Ptr RealNum -> Ptr RealNum -> Ptr RealNum -> Ptr RealNum -> Ptr RealNum -> IO ()\n\n", "meta": {"hexsha": "fe4ff9efb24a339c80f3dcff65c93d73d8f65b68", "size": 8384, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Internal/Update.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/Internal/Update.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Internal/Update.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8952879581, "max_line_length": 188, "alphanum_fraction": 0.6371660305, "num_tokens": 2188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.31200914887759734}} {"text": "\n\nmodule Numerical.HBLAS.Lapack.FFI where\nimport Foreign.Ptr\nimport Foreign()\nimport Foreign.C.Types\nimport Data.Complex\nimport Data.Int\n\n\n\n{-\n\nstylenote: we will not use the LAPACKE_* operations, only the\nLAPACKE_*_work variants that require an explicitly provided work buffer.\n\nThis is to ensure that solver routine allocation behavior is transparent\n\n\n-}\n\n\n\n{-\nvoid LAPACK_dgesvx( char* fact, char* trans, lapack_int* n, lapack_int* nrhs,\n double* a, lapack_int* lda, double* af, lapack_int* ldaf,\n lapack_int* ipiv, char* equed, double* r, double* c,\n double* b, lapack_int* ldb, double* x, lapack_int* ldx,\n double* rcond, double* ferr, double* berr, double* work,\n lapack_int* iwork, lapack_int *info );\n\n\n\n-}\n\n\n{-\n fortran FFI conventions!\n-}\n\n--type Stride_C =\n\nnewtype Fact_C = Fact_C CChar\nnewtype Trans_C = Trans_C CChar\nnewtype Stride_C = Stride_C Int32\nnewtype Equilib_C = Equilib_C CChar\n\ntype Fun_FFI_GESVX el = Ptr Fact_C {- fact -}-> Ptr Trans_C {- trans -}\n -> Ptr Int32 {-n -}-> Ptr Int32 {- NRHS -}->\n Ptr el {- a -} -> Ptr Stride_C {- lda -} -> Ptr Double {- af -} -> Ptr Stride_C {- ldf-}->\n Ptr Int32 -> Ptr Equilib_C {- equed -} -> Ptr el {- r -} -> Ptr el ->\n Ptr el {- b -} -> Ptr Stride_C {- ld b -} -> Ptr el {- x -} -> Ptr Stride_C {- ldx -}->\n Ptr el {-rcond -}-> Ptr el {- ferr-} -> Ptr el {-berr-} -> Ptr el {-work-}->\n Ptr Int32 {-iwork -}-> Ptr Int32 {-info -} -> IO ()\n\n\n\n{-\n\nthe prefixes mean s=single,d=double,c=complex float,d=complex double\n\n\n\nfact will be a 1 character C string\neither\n \"F\", then the inputs af and ipiv already contain the permuted LU factorization\n (act as input rather than result params)\n \"E\", Matrix input A will be equilibriated if needed, then copied to AF and Factored\n \"N\", matrix input A will be copied to AF\n\n-}\n\n\n{-\nXgesvx is the s -sing\n\n\nim assuming for now that any real use of *gesvx routines, or any other\nn^3 complexity algs from LAPACK, are on inputs typically n>=15, which means > 1000 flops,\nwhich is > 1µs, and thus ok to\n-}\n\n--need to get around to wrapping these, but thats for another day\nforeign import ccall \"sgesvx_\" sgesvx :: Fun_FFI_GESVX Float\nforeign import ccall \"dgesvx_\" dgesvx :: Fun_FFI_GESVX Double\nforeign import ccall \"cgesvx_\" cgesvx :: Fun_FFI_GESVX (Complex Float)\nforeign import ccall \"zgesvx_\" zgesvx :: Fun_FFI_GESVX (Complex Double)\n\n\n\n--lapack_int ?syev_( char *jobz, char *uplo, lapack_int *n, ?* a, lapack_int * lda, ?* w );\n-- ? is Double or Float\n\nnewtype JobTy = JBT CChar\nnewtype UploTy = UPLT CChar\nnewtype Info = Info Int32\n\n--basic symmetric eigen value solvers\ntype SYEV_FUN_FFI elem = Ptr JobTy -> Ptr UploTy -> Ptr Int32 -> Ptr elem -> Ptr Int32 -> Ptr elem -> Ptr Info-> IO ()\nforeign import ccall \"ssyev_\" ssyev_ffi :: SYEV_FUN_FFI Float\nforeign import ccall \"dsyev_\" dsyev_ffi :: SYEV_FUN_FFI Double\n\n{-unsafe versions of lapack routines are meant to ONLY be used for workspace queries-}\nforeign import ccall unsafe \"ssyev_\" ssyev_ffi_unsafe :: SYEV_FUN_FFI Float\nforeign import ccall unsafe \"dsyev_\" dsyev_ffi_unsafe :: SYEV_FUN_FFI Double\n\n--lapack_int LAPACKE_gesv( int matrix_order, lapack_int n, lapack_int nrhs, * a, lapack_int lda, lapack_int* ipiv, * b, lapack_int ldb );\n--call sgesv( n, nrhs, a, lda, ipiv, b, ldb, info )\n\ntype GESV_FUN_FFI elem = Ptr Int32 {- n -} -> Ptr Int32 {- nrhs -} -> Ptr elem {- a -}\n -> Ptr Int32 {- lda -} -> Ptr Int32 {- permutation vector -}\n -> Ptr elem {- b -} -> Ptr Int32 {- ldb -} -> Ptr Info -> IO ()\n-- | basic Linear system solvers. they act inplace\nforeign import ccall \"sgesv_\" sgesv_ffi ::GESV_FUN_FFI Float\nforeign import ccall \"dgesv_\" dgesv_ffi :: GESV_FUN_FFI Double\nforeign import ccall \"cgesv_\" cgesv_ffi :: GESV_FUN_FFI (Complex Float)\nforeign import ccall \"zgesv_\" zgesv_ffi :: GESV_FUN_FFI (Complex Double)\n\n-- / not sure if linear solvers ever are run in < 1 microsecond size instances in practice\nforeign import ccall unsafe \"sgesv_\" sgesv_ffi_unsafe ::GESV_FUN_FFI Float\nforeign import ccall unsafe \"dgesv_\" dgesv_ffi_unsafe :: GESV_FUN_FFI Double\nforeign import ccall unsafe \"cgesv_\" cgesv_ffi_unsafe :: GESV_FUN_FFI (Complex Float)\nforeign import ccall unsafe \"zgesv_\" zgesv_ffi_unsafe :: GESV_FUN_FFI (Complex Double)\n\n{- only provide -}\n\n\n\n\n", "meta": {"hexsha": "c209bb5bf1989464dab67471e2aee39989222dcb", "size": 4441, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numerical/HBLAS/Lapack/FFI.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/Lapack/FFI.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/Lapack/FFI.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": 34.1615384615, "max_line_length": 160, "alphanum_fraction": 0.6827291151, "num_tokens": 1400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3113992901987279}} {"text": "{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Data.Matrix.Static.Internal\n ( c_dd_mul\n , c_ds_mul\n , c_sd_mul\n , c_ss_mul\n , c_ss_cmul\n , c_sd_plus\n , c_ss_plus\n , c_inverse\n , c_cholesky\n , c_eig\n , c_eigs\n , c_eigsh\n , c_seigs\n , c_seigsh\n , c_geigsh\n , c_bdcsvd\n\n , computationInfo\n ) where\n\nimport Data.Complex (Complex)\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\n\n-------------------------------------------------------------------------------\n-- Arithmetic\n-------------------------------------------------------------------------------\nforeign import ccall \"eigen_dd_mul\"\n c_dd_mul :: CInt\n -> Ptr a -> CInt -> CInt\n -> Ptr a -> CInt -> CInt\n -> Ptr a -> CInt -> CInt\n -> IO CString\n\nforeign import ccall \"eigen_ds_mul\"\n c_ds_mul :: CInt\n -> Ptr a -> CInt -> CInt\n -> Ptr a -> CInt -> CInt\n -> Ptr a -> Ptr CInt -> Ptr CInt -> CInt -> CInt -> CInt\n -> IO CString\n\nforeign import ccall \"eigen_sd_mul\"\n c_sd_mul :: CInt\n -> Ptr a -> CInt -> CInt\n -> Ptr a -> Ptr CInt -> Ptr CInt -> CInt -> CInt -> CInt\n -> Ptr a -> CInt -> CInt\n -> IO CString\n\nforeign import ccall \"eigen_sd_plus\"\n c_sd_plus :: CInt\n -> Ptr a -> CInt -> CInt\n -> Ptr a -> Ptr CInt -> Ptr CInt -> CInt -> CInt -> CInt\n -> Ptr a -> CInt -> CInt\n -> IO CString\n\nforeign import ccall \"eigen_ss_mul\"\n c_ss_mul :: CInt\n -> Ptr (Ptr a) -> Ptr CInt -> Ptr (Ptr CInt) -> CInt -> CInt -> Ptr CInt\n -> Ptr a -> Ptr CInt -> Ptr CInt -> CInt -> CInt -> CInt\n -> Ptr a -> Ptr CInt -> Ptr CInt -> CInt -> CInt -> CInt\n -> IO CString\n\nforeign import ccall \"eigen_ss_cmul\"\n c_ss_cmul :: CInt\n -> Ptr (Ptr a) -> Ptr CInt -> Ptr (Ptr CInt) -> CInt -> CInt -> Ptr CInt\n -> Ptr a -> Ptr CInt -> Ptr CInt -> CInt -> CInt -> CInt\n -> Ptr a -> Ptr CInt -> Ptr CInt -> CInt -> CInt -> CInt\n -> IO CString\n\nforeign import ccall \"eigen_ss_plus\"\n c_ss_plus :: CInt\n -> Ptr (Ptr a) -> Ptr CInt -> Ptr (Ptr CInt) -> CInt -> CInt -> Ptr CInt\n -> Ptr a -> Ptr CInt -> Ptr CInt -> CInt -> CInt -> CInt\n -> Ptr a -> Ptr CInt -> Ptr CInt -> CInt -> CInt -> CInt\n -> IO CString\n \nforeign import ccall \"eigen_inverse\"\n c_inverse :: CInt\n -> Ptr a -> CInt -> CInt\n -> Ptr a -> CInt -> CInt\n -> IO CString\n\nforeign import ccall \"eigen_cholesky\"\n c_cholesky :: CInt\n -> Ptr a -> Ptr a -> CInt -> IO CString\n\nforeign import ccall \"eigen_eig\"\n c_eig :: Ptr (Complex Double) -> Ptr (Complex Double)\n -> Ptr Double -> CInt -> IO CString\n\nforeign import ccall \"spectral_eigs\"\n c_eigs :: CInt -- ^ The number of eigenvectors to search\n -> Ptr (Complex Double) -- ^ \n -> Ptr (Complex Double) -- ^ \n -> Ptr Double -- ^ Input matrix\n -> CInt -- ^ Matrix size\n -> CInt -- ^ ncv\n -> CInt -- ^ max iterations\n -> Double -- ^ tolerance\n -> CInt\n -> Double\n -> CInt\n -> IO CInt\n\nforeign import ccall \"spectral_eigsh\"\n c_eigsh :: CInt\n -> Ptr Double -> Ptr Double\n -> Ptr Double -> CInt\n -> CInt -> CInt -> Double -> CInt -> Double -> CInt\n -> IO CInt\n\nforeign import ccall \"spectral_seigs\"\n c_seigs :: CInt\n -> Ptr (Complex Double) -> Ptr (Complex Double)\n -> Ptr Double -> Ptr CInt -> Ptr CInt -> CInt -> CInt\n -> CInt -> CInt -> Double -> CInt -> Double -> CInt\n -> IO CInt\n\nforeign import ccall \"spectral_seigsh\"\n c_seigsh :: CInt\n -> Ptr Double -> Ptr Double\n -> Ptr Double -> Ptr CInt -> Ptr CInt -> CInt -> CInt\n -> CInt -> CInt -> Double -> CInt -> Double -> CInt\n -> IO CInt\n\nforeign import ccall \"spectral_geigsh\"\n c_geigsh :: CInt\n -> Ptr Double -> Ptr Double\n -> Ptr Double -> CInt\n -> Ptr Double -> Ptr CInt -> Ptr CInt -> CInt\n -> CInt -> CInt -> Double -> CInt\n -> IO CInt\n\nforeign import ccall \"eigen_bdcsvd\"\n c_bdcsvd :: CInt -> Ptr a -> Ptr b -> Ptr a\n -> Ptr a -> CInt -> CInt -> IO CString\n\ncomputationInfo :: CInt -> Maybe String\ncomputationInfo 0 = Nothing\ncomputationInfo 1 = Just \"NOT_COMPUTED\"\ncomputationInfo 2 = Just \"NOT_CONVERGING\"\ncomputationInfo 3 = Just \"NUMERICAL_ISSUE\"\ncomputationInfo _ = Just \"UNKNOWN ERROR\"\n{-# INLINE computationInfo #-}", "meta": {"hexsha": "9895d391897669fc7303c0598f70263c6fcd82a6", "size": 4687, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Matrix/Static/Internal.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/Internal.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/Internal.hs", "max_forks_repo_name": "kaizhang/matrix-sized", "max_forks_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8843537415, "max_line_length": 82, "alphanum_fraction": 0.504587156, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.30772897890961803}} {"text": "-- This file is part of Quipper. Copyright (C) 2011-2016. Please see the\n-- file COPYRIGHT for a list of authors, copyright holders, licensing,\n-- and other details. All rights reserved.\n-- \n-- ======================================================================\n\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE FunctionalDependencies #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE TypeSynonymInstances #-}\r\n\r\n{-# OPTIONS -fcontext-stack=50 #-}\r\n\r\n-- | This module contains the Quipper implementation of the Quantum\r\n-- Linear Systems Algorithm.\r\n-- \r\n-- The algorithm estimates the radar cross section for a FEM\r\n-- scattering problem by using amplitude estimation to calculate\r\n-- probability amplitudes. \r\n-- \r\n-- The notations are based on the paper \r\n-- \r\n-- * B. D. Clader, B. C. Jacobs, C. R. Sprouse. Quantum algorithm to\r\n-- calculate electromagnetic scattering cross\r\n-- sections. .\r\nmodule Algorithms.QLS.QLS where\r\n\r\nimport Quipper\r\n\r\nimport QuipperLib.QFT\r\nimport QuipperLib.Arith\r\nimport QuipperLib.Decompose\r\n\r\nimport Data.Complex\r\nimport qualified Data.Map as Map\r\n\r\nimport qualified Algorithms.QLS.TemplateOracle as Template\r\nimport Algorithms.QLS.QDouble\r\nimport Algorithms.QLS.QSignedInt\r\nimport Algorithms.QLS.CircLiftingImport\r\nimport Algorithms.QLS.Utils\r\n\r\nimport Libraries.Auxiliary(boollist_of_int_bh)\r\n\r\n\r\n-- | The type of 'oracle_A' input arguments during runtime.\r\ntype OracleARunTime = Double -- ^Value resolution.\r\n -> Int -- ^Band.\r\n -> Bool -- ^Argflag.\r\n -> ([Qubit],[Qubit],[Qubit]) -- ^(x=index,y+node,z+value).\r\n -> Circ ([Qubit],[Qubit],[Qubit])\r\n\r\n-- | The type of 'oracle_b' and 'oracle_r' input arguments during runtime.\r\ntype OracleBRRunTime = Double -- ^Magnitude resolution.\r\n -> Double -- ^Phase resolution.\r\n -> ([Qubit],[Qubit],[Qubit]) -- ^(x=index,m+magnitude,p+phase).\r\n -> Circ ([Qubit],[Qubit],[Qubit])\r\n\r\n\r\n-- | A type to encapsulate all three oracles.\r\ndata Oracle = Oracle {\r\n oracle_A :: RunTimeParam -> OracleARunTime,\r\n oracle_b :: RunTimeParam -> OracleBRRunTime,\r\n oracle_r :: RunTimeParam -> OracleBRRunTime\r\n}\r\n\r\n\r\n-- | A set of oracles using only blackboxes.\r\ndummy_oracle :: Oracle\r\ndummy_oracle = Oracle {\r\n oracle_A = \\d r i b x -> named_gate \"Oracle A\" x,\r\n oracle_b = \\d1 d2 r x -> named_gate \"Oracle b\" x,\r\n oracle_r = \\d1 d2 r x -> named_gate \"Oracle r\" x\r\n}\r\n\r\n\r\n\r\n-- | A type to hold the runtime parameters.\r\ndata RunTimeParam = RT_param {\r\n k :: Double, -- ^ Wave number.\r\n theta :: Double, -- ^ Incident wave angle.\r\n phi :: Double, -- ^ Direction of desired far field radiation pattern.\r\n e0 :: Double, -- ^ Incident wave amplitude.\r\n lambda :: Double, -- ^ Wavelength.\r\n xlength :: Double, -- ^ /x/-length of square scattering region.\r\n ylength :: Double, -- ^ /y/-length of square scattering region.\r\n\r\n scatteringnodes :: [(Int,Int)], -- ^ Metallic region.\r\n \r\n nx :: Int,\r\n ny :: Int,\r\n lx :: Double,\r\n ly :: Double,\r\n\r\n kappa :: Double,\r\n epsilon :: Double,\r\n t0 :: Double,\r\n r :: Double,\r\n b_max :: Double,\r\n r_max :: Double,\r\n d :: Int,\r\n nb :: Int,\r\n p2 :: Double,\r\n n0 :: Int,\r\n n1 :: Int,\r\n n2 :: Int,\r\n n4 :: Int,\r\n\r\n -- argflags for oracle_A\r\n magnitudeArgflag :: Bool,\r\n phaseArgflag :: Bool\r\n} deriving (Show)\r\n\r\n\r\n-- | A convenient set of runtime parameters for testing. \r\ndummy_RT_param :: RunTimeParam\r\ndummy_RT_param = RT_param {\r\n\r\n k = 2.0*pi*1.0,\r\n theta = 0.0*pi/4.0,\r\n phi = 0.0,\r\n e0 = 1.0,\r\n lambda = (k dummy_RT_param)/(2.0*pi),\r\n xlength = 2.0*(lambda dummy_RT_param),\r\n ylength = 2.0*(lambda dummy_RT_param),\r\n \r\n scatteringnodes = \r\n let rt = dummy_RT_param in\r\n let xul = round((fromIntegral $ nx rt)/2)\r\n - round((xlength rt)/(2.0*(lx rt))) in -- Upper left x index\r\n let yul = round((fromIntegral $ ny rt)/2)\r\n - round((ylength rt)/(2.0*(ly rt))) in -- Upper left y index\r\n let xlr = round((fromIntegral $ nx rt)/2)\r\n + round((xlength rt)/(2.0*(lx rt))) in -- Lower right x index\r\n let ylr = round((fromIntegral $ ny rt)/2)\r\n + round((ylength rt)/(2.0*(ly rt))) in -- Lower right y in\r\n [(xul, yul), (xlr, ylr)],\r\n\r\n nx = 12885,\r\n ny = 12885,\r\n lx = 0.1,\r\n ly = 0.1,\r\n\r\n kappa = 1.0,\r\n epsilon = 1.0,\r\n t0 = 1.0,\r\n r = 1.0,\r\n b_max = 1.0,\r\n r_max = 1.0,\r\n d = 3,\r\n nb = 2,\r\n p2 = 3,\r\n n0 = 3, \r\n n1 = 3,\r\n n2 = 3,\r\n n4 = 3, \r\n\r\n -- argflags for oracle_A\r\n magnitudeArgflag = False,\r\n phaseArgflag = True\r\n}\r\n\r\n\r\n-- | A set of larger values, for testing scalability.\r\nlarge_RT_param :: RunTimeParam\r\nlarge_RT_param = RT_param {\r\n\r\n k = 2.0*pi*1.0,\r\n theta = 0.0*pi/4.0,\r\n phi = 0.0,\r\n e0 = 1.0,\r\n lambda = (k large_RT_param)/(2.0*pi),\r\n xlength = 2.0*(lambda large_RT_param),\r\n ylength = 2.0*(lambda large_RT_param),\r\n \r\n scatteringnodes = \r\n let rt = large_RT_param in\r\n let xul = round((fromIntegral $ nx rt)/2)\r\n - round((xlength rt)/(2.0*(lx rt))) in -- Upper left x index\r\n let yul = round((fromIntegral $ ny rt)/2)\r\n - round((ylength rt)/(2.0*(ly rt))) in -- Upper left y index\r\n let xlr = round((fromIntegral $ nx rt)/2)\r\n + round((xlength rt)/(2.0*(lx rt))) in -- Lower right x index\r\n let ylr = round((fromIntegral $ ny rt)/2)\r\n + round((ylength rt)/(2.0*(ly rt))) in -- Lower right y in\r\n [(xul, yul), (xlr, ylr)],\r\n\r\n nx = 12885,\r\n ny = 12885,\r\n lx = 0.1,\r\n ly = 0.1,\r\n\r\n kappa = 1e4,\r\n epsilon = 0.01,\r\n t0 = 7.0e6,\r\n r = 2.5e12,\r\n b_max = 5.0,\r\n r_max = 1.01,\r\n d = 7,\r\n nb = 9,\r\n p2 = ( 1.0 / (4-(4**(1/3))) ),\r\n n0 = 14,\r\n n1 = 24,\r\n n2 = 30,\r\n n4 = 65, \r\n\r\n -- argflags for oracle_A\r\n magnitudeArgflag = False,\r\n phaseArgflag = True\r\n}\r\n\r\n\r\n-- | A set of smaller values, for manageable yet meaningful output.\r\nsmall_RT_param :: RunTimeParam\r\nsmall_RT_param = RT_param {\r\n\r\n k = 2.0*pi*1.0,\r\n theta = 0.0*pi/4.0,\r\n phi = 0.0,\r\n e0 = 1.0,\r\n lambda = (k small_RT_param)/(2.0*pi),\r\n xlength = 2.0*(lambda small_RT_param),\r\n ylength = 2.0*(lambda small_RT_param),\r\n \r\n scatteringnodes = \r\n let xul = 2 in\r\n let yul = 2 in\r\n let xlr = 3 in\r\n let ylr = 3 in\r\n [(xul, yul), (xlr, ylr)],\r\n\r\n nx = 4,\r\n ny = 4,\r\n lx = 0.1,\r\n ly = 0.1,\r\n\r\n kappa = 1e4,\r\n epsilon = 0.01,\r\n t0 = 7.0e6,\r\n r = 2.5e12,\r\n b_max = 5.0,\r\n r_max = 1.01,\r\n d = 7,\r\n nb = 9,\r\n p2 = ( 1.0 / (4-(4**(1/3))) ),\r\n n0 = 14,\r\n n1 = 24,\r\n n2 = 6,\r\n n4 = 65, \r\n\r\n -- argflags for oracle_A\r\n magnitudeArgflag = False,\r\n phaseArgflag = True\r\n}\r\n\r\n\r\n\r\n-- | Apply an [exp −/iYt/] gate. The timestep /t/ is a parameter.\r\nexpYt :: Timestep -> Qubit -> Circ Qubit\r\nexpYt = named_rotation \"exp(-i%Y)\"\r\n\r\n\r\n-- | Apply an [exp −/iYt/] gate. The timestep /t/ is a parameter.\r\nexpYt_at :: Timestep -> Qubit -> Circ ()\r\nexpYt_at = named_rotation_at \"exp(-i%Y)\"\r\n\r\n\r\n-- | Read a list of bits and make it into a 'Double', by multiplying\r\n-- its integer value by the provided factor.\r\ndynamic_lift_double :: Double -> [Bit] -> Circ Double\r\ndynamic_lift_double factor cl = do\r\n cdiscard cl\r\n\r\n-- Implementation note: removed dynamic_lift as for now it breaks all\r\n-- output formats except ASCII.\r\n\r\n-- bl <- dynamic_lift cl\r\n let sign = 1 -- if (head $ reverse bl) then 1 else -1\r\n let unsigned_value = 1 -- integer_of_intm_unsigned $ \r\n -- intm_of_boollist_bh (tail $ reverse bl)\r\n return (sign * factor * (fromIntegral unsigned_value))\r\n\r\n\r\n-- | A black box gate to stand in as a replacement for QFT.\r\nqft_for_show :: [Qubit] -> Circ [Qubit]\r\nqft_for_show qs = named_gate \"QFT\" qs\r\n\r\n\r\n\r\n-- | Main function: for estimating the radar cross section for a FEM\r\n-- scattering problem. The problem can be reduced to the calculation\r\n-- of four angles: φ[sub /b/], φ[sub /bx/], φ[sub /r/1] and φ[sub /r/0].\r\nqlsa_FEM_main :: RunTimeParam -> Oracle -> Circ Double\r\nqlsa_FEM_main param oracle = do\r\n comment \"FEM_main\"\r\n phi_b <- qlsa_AmpEst_phi_b param oracle\r\n phi_bx <- qlsa_AmpEst_phi_bx param oracle\r\n phi_r1 <- qlsa_AmpEst_phi_bxr param oracle True\r\n phi_r0 <- qlsa_AmpEst_phi_bxr param oracle False\r\n let sigma = ((((fromIntegral $ nb param) ^ 2) * ((b_max param) ^ 2) * ((r_max param) ^ 2) * ((sin phi_b) ^ 2)) / ( 4 * pi))\r\n comment \"FEM_main\"\r\n return sigma\r\n\r\n\r\n\r\n\r\n-- * Amplitude Estimation Functions\r\n\r\n-- | Estimates φ[sub /b/], related to the probability of success for the\r\n-- preparation of the known state /b/, using amplitude amplification.\r\nqlsa_AmpEst_phi_b :: RunTimeParam -> Oracle -> Circ Double\r\nqlsa_AmpEst_phi_b param oracle = do\r\n g <- qinit $ replicate (n0 param) False\r\n with_ancilla_init (replicate (n2 param) False) $ \\x -> do\r\n label (g,x) (\"g\",\"x\")\r\n with_ancilla $ \\a -> do\r\n label (a) (\"anc. a\")\r\n with_ancilla $ \\b -> do\r\n label (b) (\"anc. b\")\r\n g <- map_hadamard g \r\n u_b (x,b) \r\n loop g u_g (x,b,a)\r\n return ()\r\n return ()\r\n g' <- qft_big_endian g -- QFT : Is it really big-endian?\r\n value_bits <- measure g'\r\n value_double <- dynamic_lift_double 1.0 value_bits\r\n return (pi * value_double / (2 ** (fromIntegral $ n0 param))) \r\n where\r\n loop :: [Qubit] -> (a -> Circ ()) -> a -> Circ ()\r\n loop [] f x = return ()\r\n loop (h:t) f x = do\r\n f x `controlled` h\r\n loop t f' x;\r\n where\r\n f' x = do f x; f x \r\n\r\n u_b :: ([Qubit],Qubit) -> Circ ()\r\n u_b xb = qlsa_StatePrep param xb (oracle_b oracle param) (1.0/(b_max param))\r\n\r\n\r\n u_g :: ([Qubit],Qubit,Qubit) -> Circ ()\r\n u_g (x,b,a) = do \r\n comment \"U_g starts\"\r\n gate_Z_at b\r\n -- For unitrary linear transformation, adjoint == inverse, hence reverse_...\r\n (reverse_generic_imp u_b) (x,b) \r\n qnot_at a `controlled` x .==. (map (\\x -> False) x)\r\n gate_X_at a\r\n gate_Z_at a\r\n gate_X_at a\r\n qnot_at a `controlled` x .==. (map (\\x -> False) x)\r\n u_b (x,b)\r\n comment \"U_g ends\"\r\n return ()\r\n\r\n \r\n \r\n-- | Testing function for 'qlsa_AmpEst_phi_b'.\r\ntest_qlsa_AmpEst_phi_b :: Bool -> IO ()\r\ntest_qlsa_AmpEst_phi_b dummyRTParamFlag = do\r\n let param = if dummyRTParamFlag then dummy_RT_param else large_RT_param \r\n print_simple GateCount (qlsa_AmpEst_phi_b param dummy_oracle)\r\n print_simple Preview (qlsa_AmpEst_phi_b param dummy_oracle)\r\n\r\n\r\n-- | Estimates φ[sub /bx/], related to the probability of success in\r\n-- computing solution value /x/.\r\nqlsa_AmpEst_phi_bx :: RunTimeParam -> Oracle -> Circ Double\r\nqlsa_AmpEst_phi_bx param oracle = do\r\n g <- qinit (take (n0 param) (repeat False))\r\n with_ancilla_init (take (n2 param) (repeat False)) $ \\x -> do\r\n with_ancilla $ \\a -> do \r\n with_ancilla $ \\b -> do\r\n with_ancilla $ \\s -> do\r\n g <- map_hadamard g \r\n u_bx (x,b,s)\r\n loop g u_g (x,b,s,a)\r\n return ()\r\n return () \r\n return ()\r\n g' <- qft_big_endian g -- QFT : Is it really big-endian?\r\n value_bits <- measure g'\r\n value_double <- dynamic_lift_double 1.0 value_bits\r\n return (pi * value_double / (2 ** (fromIntegral $ n0 param)))\r\n where\r\n loop :: [Qubit] -> (a -> Circ ()) -> a -> Circ ()\r\n loop [] f x = return ()\r\n loop (h:t) f x = do\r\n f x `controlled` h\r\n loop t f' x\r\n where\r\n f' x = do f x; f x\r\n \r\n u_bx :: ([Qubit],Qubit,Qubit) -> Circ ()\r\n u_bx (x,b,s) = do \r\n qlsa_StatePrep param (x,b) (oracle_b oracle param) (1.0/(b_max param)) \r\n qlsa_Solve_x param (x,s) oracle\r\n return ()\r\n\r\n u_g :: ([Qubit],Qubit,Qubit,Qubit) -> Circ ()\r\n u_g (x,b,s,a) = do --named_gate_at \"Ug_phi_bx\" (x,b,s,a)\r\n qnot_at a `controlled` b .&&. s\r\n gate_Z_at a\r\n qnot_at a `controlled` b .&&. s\r\n (reverse_generic_imp u_bx) (x,b,s)\r\n qnot_at a `controlled` [ q .==. 0 | q <- x ] .&&. b .==. 0 .&&. s .==. 0\r\n gate_X_at a\r\n gate_Z_at a\r\n gate_X_at a\r\n qnot_at a `controlled` [ q .==. 0 | q <- x ] .&&. b .==. 0 .&&. s .==. 0\r\n u_bx (x,b,s)\r\n return ()\r\n \r\n\r\n \r\n \r\n-- | Estimates φ[sub /r/0] and φ[sub /r/1] (depending on the boolean\r\n-- parameter), related to the overlap of the solution with the\r\n-- arbitrary state /r/.\r\nqlsa_AmpEst_phi_bxr :: RunTimeParam -> Oracle -> Bool -> Circ Double\r\nqlsa_AmpEst_phi_bxr param oracle target = do\r\n g <- qinit (take (n0 param) (repeat False))\r\n with_ancilla_init (take (n2 param) (repeat False)) $ \\x -> do\r\n with_ancilla_init (take (n2 param) (repeat False)) $ \\y -> do \r\n with_ancilla $ \\a -> do \r\n with_ancilla $ \\b -> do\r\n with_ancilla $ \\s -> do\r\n with_ancilla $ \\r -> do \r\n with_ancilla $ \\c -> do\r\n g <- map_hadamard g \r\n u_r (x,y,b,s,r,c)\r\n loop g u_g (x,y,b,s,r,c,a)\r\n return ()\r\n return ()\r\n return ()\r\n return ()\r\n return () \r\n g' <- qft_big_endian g -- QFT : Is it really big-endian?\r\n value_bits <- measure g'\r\n value_double <- dynamic_lift_double 1.0 value_bits\r\n return (pi * value_double / (2 ** (fromIntegral $ n0 param)))\r\n where\r\n loop :: [Qubit] -> (a -> Circ ()) -> a -> Circ ()\r\n loop [] f x = return ()\r\n loop (h:t) f x = do\r\n f x `controlled` h\r\n loop t f' x\r\n where\r\n f' x = do f x; f x\r\n \r\n u_r :: ([Qubit],[Qubit],Qubit,Qubit,Qubit,Qubit) -> Circ ()\r\n u_r (x,y,b,s,r,c) = do \r\n qlsa_Solve_xr param (x,y,b,s,r,c) oracle\r\n return ()\r\n\r\n u_g :: ([Qubit],[Qubit],Qubit,Qubit,Qubit,Qubit,Qubit) -> Circ ()\r\n u_g (x,y,b,s,r,c,a) = do --named_gate_at \"Ug_phi_bxr\" (x,y,b,s,r,c,a)\r\n qnot_at a `controlled` (b .==. 1 .&&. s .==. 1 .&&. r .==. 1 .&&. c .==. target)\r\n gate_Z_at a\r\n qnot_at a `controlled` (b .==. 1 .&&. s .==. 1 .&&. r .==. 1 .&&. c .==. target)\r\n (reverse_generic_imp u_r) (x,y,b,s,r,c)\r\n qnot_at a `controlled` [ q .==. 0 | q <- x ] .&&. [ q .==. 0 | q <- y ] .&&. b .==. 0 .&&. s .==. 0 .&&. r .==. 0 .&&. c .==. 0\r\n gate_X_at a\r\n gate_Z_at a\r\n gate_X_at a\r\n qnot_at a `controlled` [ q .==. 0 | q <- x ] .&&. [ q .==. 0 | q <- y ] .&&. b .==. 0 .&&. s .==. 0 .&&. r .==. 0 .&&. c .==. 0\r\n u_r (x,y,b,s,r,c)\r\n return ()\r\n\r\n\r\n-- * State Preparation.\r\n\r\n-- | Prepares a quantum state /x/, as specified by an oracle function,\r\n-- entangled with a single qubit flag /q/ marking the desired state.\r\nqlsa_StatePrep :: \r\n RunTimeParam\r\n -> ([Qubit], Qubit) -- x & qare handles to wires to be changed by StatePrep \r\n -> OracleBRRunTime -- Common type of (oracle_b oracle) and (oracle_r oracle), if oracle is typed Oracle\r\n -> Double\r\n -> Circ ()\r\nqlsa_StatePrep param (x, q) oracle phi0 = do\r\n _ <- (flip $ box (\"qlsa_StatePrep_\" ++ (show phi0))) (x,q) $ \\(x,q) -> do\r\n -- comment \"StatePrep starts\"\r\n label (x,q) (\"x\", \"q\")\r\n with_ancilla_list (n4 param) $ \\m -> do\r\n label (m) (\"anc. m\")\r\n with_ancilla_list (n4 param) $ \\p -> do\r\n label (p) (\"anc. p\")\r\n x <- map_hadamard x\r\n (x, m, p) <- oracle phi0 (epsilon param) (x, m, p)\r\n qlsa_ControlledPhase p (epsilon param) False\r\n qlsa_ControlledRotation (m, q) phi0 False\r\n (x, m, p) <- oracle phi0 (epsilon param) (x, m, p)\r\n return (x,q)\r\n -- comment \"StatePrep ends\"\r\n return ()\r\n\r\n\r\n-- | Testing function for 'qlsa_StatePrep'.\r\ntest_qlsa_StatePrep :: Bool -> IO ()\r\ntest_qlsa_StatePrep dummyRTParamFlag = do\r\n let param = if dummyRTParamFlag then dummy_RT_param else large_RT_param\r\n let oraclebRunTime = (oracle_b dummy_oracle param) \r\n let testCirc = do\r\n x <- qinit $ replicate (n2 param) False\r\n q <- qinit False\r\n qlsa_StatePrep param (x,q) oraclebRunTime 1.0\r\n print_simple GateCount testCirc\r\n print_simple Preview testCirc\r\n\r\n\r\n\r\n\r\n-- * Linear System Solver Functions\r\n\r\n-- | Implements the QLSA procedure to generate the solution state |/x/〉.\r\nqlsa_Solve_x :: RunTimeParam ->([Qubit],Qubit) -> Oracle -> Circ () \r\nqlsa_Solve_x param (x,s) oracle = do\r\n _ <- (flip $ box \"qlsa_Solve_x\") (x,s) $ \\(x,s) -> do\r\n with_ancilla_list (n1 param) $ \\t -> do \r\n with_ancilla_list (length t) $ \\f -> do \r\n let phi0 = 2 * pi / (2 ** (fromIntegral $ n1 param) - (epsilon param))\r\n t <- map_hadamard t\r\n u_hs (t,x)\r\n t <- qft_big_endian t\r\n integer_inverse (t,f) \r\n qlsa_ControlledRotation (f,s) phi0 False\r\n integer_inverse (t,f)\r\n (reverse_generic_endo qft_big_endian) t\r\n (reverse_generic_imp u_hs) (t,x)\r\n t <- map_hadamard t\r\n return() \r\n return ()\r\n return (x,s)\r\n return ()\r\n where\r\n u_hs :: ([Qubit],[Qubit]) -> Circ ()\r\n u_hs (t,x) = do \r\n qlsa_HamiltonianSimulation param (t,x) (oracle_A oracle param)\r\n return ()\r\n \r\n\r\n-- | Implementation of the integer division. The two registers are\r\n-- supposed to be of the same size and represent little-headian\r\n-- unsigned integers, i.e., the head of the list holds the least\r\n-- significant bit.\r\ninteger_inverse :: ([Qubit],[Qubit]) -> Circ ()\r\ninteger_inverse (t,f) = do\r\n _ <- (flip $ box \"integer_inverse\") (t,f) $ \\(t,f) -> do\r\n -- sanity check\r\n if (length t /= length f) \r\n then error \"integer_inverse: registers of distinct sizes\" \r\n else return ()\r\n -- initialize an unsigned integer to 2^(length t) - 1\r\n with_ancilla_init (map (\\_ -> True) t) $ \\num -> do\r\n -- perform the division (encapsulated in a subroutine)\r\n let d = classical_to_reversible $ \\(t,num) -> do\r\n let x = ((qdint_of_qulist_lh num),(qdint_of_qulist_lh t))\r\n (_,_,f') <- uncurry q_div_unsigned x\r\n return $ qulist_of_qdint_lh f'\r\n d ((t,num),f)\r\n return (t,f)\r\n return ()\r\n\r\n\r\n\r\n\r\n \r\n-- | Implements the complete QLSA procedure to find the\r\n-- solution state |/x/〉 and then implements the swap protocol\r\n-- required for estimation of 〈/x/|/r/〉.\r\nqlsa_Solve_xr :: RunTimeParam ->([Qubit],[Qubit],Qubit,Qubit,Qubit,Qubit) -> Oracle -> Circ () \r\n-- qlsa_Solve_xr param (x,y,b,s,r,c) oracle = named_gate_at \"Solve_xr\" (x,y,b,s,r,c)\r\nqlsa_Solve_xr param (x,y,b,s,r,c) oracle = do\r\n _ <- (flip $ box \"qlsa_Solve_xr\") (x,y,b,s,r,c) $ \\(x,y,b,s,r,c) -> do\r\n qlsa_StatePrep param (x,b) (oracle_b oracle param) (1.0/(b_max param)) \r\n qlsa_Solve_x param (x,s) oracle \r\n qlsa_StatePrep param (y,r) (oracle_r oracle param) (1.0/(r_max param)) \r\n hadamard_at c\r\n swap_at y x `controlled` c\r\n hadamard_at c\r\n return (x,y,b,s,r,c)\r\n return ()\r\n \r\n\r\n-- * Hamiltonian Simulation Functions.\r\n\r\n-- | Uses a quantum register |/t/〉 to control the\r\n-- implementation of the Suzuki method for simulating a Hamiltonian\r\n-- specified by an oracle function.\r\nqlsa_HamiltonianSimulation :: \r\n RunTimeParam \r\n -> ([Qubit], [Qubit])\r\n -> OracleARunTime \r\n -> Circ ()\r\nqlsa_HamiltonianSimulation param (t, x) oracleA = do\r\n _ <- (flip $ box \"qlsa_HamiltonianSimulation\") (t,x) $ \\(t,x) -> do\r\n -- Code the first line in a way that depends on the length of t rather \r\n -- explicitly on (n1 param) which is supposed to be the length of t\r\n -- Hence replaced the line below by the line after it.\r\n -- let denom = 2 * (r param) * (fromIntegral ((n1 param) - 1))\r\n let denom = 2 * (r param) * ( 2^((length t) - 1) )\r\n let t1 = (p2 param) * (t0 param) / denom\r\n let t2 = (1.0 - 4.0 * (p2 param)) * (t0 param) / denom\r\n (t,x) <- box_loopM \"TrotterLoop\" (round $ r param) (t,x) (hs_loop t1 t2)\r\n return (t,x)\r\n return ()\r\n where \r\n hs_loop :: Double -> Double -> ([Qubit], [Qubit]) -> Circ ([Qubit], [Qubit])\r\n hs_loop t1 t2 (t,x) = do \r\n u_z_at (t,x) t1\r\n u_z_at (t,x) t1\r\n u_z_at (t,x) t2\r\n u_z_at (t,x) t1\r\n u_z_at (t,x) t1\r\n return (t,x)\r\n\r\n u_z_at :: ([Qubit], [Qubit]) -> Double -> Circ ()\r\n u_z_at (t, x) timeStep = do\r\n for (nb param) 1 (-1) $ \\jj -> do\r\n qlsa_HsimKernel param (t, x) jj timeStep oracleA \r\n endfor\r\n for 1 (nb param) 1 $ \\jj -> do\r\n qlsa_HsimKernel param (t, x) jj timeStep oracleA \r\n endfor\r\n return ()\r\n\r\n-- | Testing function for 'qlsa_HamiltonianSimulation'.\r\ntest_qlsa_HamiltonianSimulation :: Bool -> IO ()\r\ntest_qlsa_HamiltonianSimulation dummyRTParamFlag = do\r\n let param = if dummyRTParamFlag then dummy_RT_param else large_RT_param\r\n let oracleARunTime = (oracle_A dummy_oracle param) \r\n let testCirc = do\r\n t <- qinit (take (n0 param) (repeat False))\r\n x <- qinit (take (n4 param) (repeat False))\r\n label(t,x) (\"t\", \"x\")\r\n qlsa_HamiltonianSimulation param (t,x) oracleARunTime\r\n print_simple GateCount testCirc\r\n-- print_simple Preview testCirc\r\n\r\n\r\n\r\n-- | Uses an oracle function and timestep control register (/t/) to\r\n-- apply 1-sparse Hamiltonian to the input state |/t/, /x/〉.\r\nqlsa_HsimKernel :: \r\n RunTimeParam\r\n -> ([Qubit], [Qubit]) \r\n -> Int \r\n -> Double \r\n -> OracleARunTime\r\n -> Circ ()\r\n-- qlsa_HsimKernel param tx band timeStep oracleA = named_gate_at \"HsimKernel\" tx\r\n\r\nqlsa_HsimKernel param (t, x) band timeStep oracleA = do\r\n _ <- (flip $ box (\"qlsa_HsimKernel\" ++ (show band) ++ (show timeStep))) (t,x) $ \\(t,x) -> do\r\n let phiP = (epsilon param)\r\n with_ancilla_list (n2 param) $ \\y -> do\r\n with_ancilla_list (n4 param) $ \\m -> do \r\n with_ancilla_list (n4 param) $ \\p -> do \r\n label (y,m,p) (\"y\",\"m\",\"p\")\r\n -- phases\r\n oracleA phiP band (phaseArgflag param) (x,y,p)\r\n qlsa_ControlledPhase p phiP False\r\n oracleA phiP band (phaseArgflag param) (x,y,p)\r\n -- magnitudes\r\n let phiMag = 2 ** (negate $ fromIntegral $ after_radix_length)\r\n oracleA phiMag band (magnitudeArgflag param) (x,y,m)\r\n for 0 ((length t) - 1) 1 $ \\ii -> do \r\n let phi_mt = timeStep * phiMag * (2^ii)\r\n qlsa_ApplyHmag param (x,y,m) phi_mt `controlled` (t !! ii)\r\n endfor\r\n oracleA phiMag band (magnitudeArgflag param) (x,y,m)\r\n -- phases again\r\n oracleA phiP band (phaseArgflag param) (x,y,p)\r\n qlsa_ControlledPhase p phiP True\r\n oracleA phiP band (phaseArgflag param) (x,y,p)\r\n return ()\r\n return ()\r\n return () \r\n return (t,x)\r\n return ()\r\n\r\n-- | Testing function for 'qlsa_HsimKernel'.\r\ntest_qlsa_HsimKernel :: Bool -> IO ()\r\ntest_qlsa_HsimKernel dummyRTParamFlag = do\r\n let param = if dummyRTParamFlag then dummy_RT_param else large_RT_param\r\n let oracleARunTime = (oracle_A dummy_oracle param) \r\n let testCirc = do\r\n t <- qinit (take (n0 param) (repeat False))\r\n x <- qinit (take (n4 param) (repeat False))\r\n label(t,x) (\"t\", \"x\")\r\n qlsa_HsimKernel param (t,x) 1 0.1 oracleARunTime\r\n print_simple GateCount testCirc\r\n-- print_simple Preview testCirc\r\n\r\n\r\n-- | Applies the magnitude component of coupling elements in a\r\n-- 1-sparse Hamiltonian.\r\nqlsa_ApplyHmag :: RunTimeParam -> ([Qubit], [Qubit], [Qubit]) -> Double -> Circ ()\r\nqlsa_ApplyHmag param (x,y,m) phi0 = do\r\n _ <- (flip $ box (\"qlsa_ApplyHmag \" ++ (show phi0))) (x,y,m) $ \\(x,y,m) -> do\r\n let (onOne, onZero) = (True, False)\r\n with_ancilla $ \\a -> do -- Assume initialized to False (0)\r\n label (a) (\"anc. a\")\r\n if (length x /= length y) \r\n then error \"qlsa_ApplyHmag: Input registers x and y have different lengths.\" \r\n else return ()\r\n let length_xy = length x\r\n for 0 (length_xy - 1) 1 $ \\ii -> do\r\n let (xi, yi) = (x !! ii, y !! ii)\r\n w (xi, yi)\r\n qnot_at a `controlled` (xi .==. onOne .&&. yi .==. onZero)\r\n endfor\r\n qlsa_ControlledPhase (m ++ [a]) phi0 False\r\n for (length_xy - 1) 0 (-1) $ \\ii -> do\r\n let (xi, yi) = (x !! ii, y !! ii)\r\n qnot_at a `controlled` (xi .==. onOne .&&. yi .==. onZero)\r\n w (xi, yi)\r\n endfor \r\n return ()\r\n return (x,y,m)\r\n return ()\r\n\r\n\r\n-- | Testing function for 'qlsa_ApplyHmag'.\r\ntest_qlsa_ApplyHmag :: Bool -> IO ()\r\ntest_qlsa_ApplyHmag dummyRTParamFlag = do\r\n let param = if dummyRTParamFlag then dummy_RT_param else large_RT_param\r\n let testCirc = do\r\n x <- qinit (take (n2 param) (repeat False))\r\n y <- qinit (take (n2 param) (repeat False))\r\n m <- qinit (take (n4 param) (repeat False))\r\n label(x,y,m) (\"x\", \"y\", \"m\")\r\n qlsa_ApplyHmag param (x,y,m) 0.1 \r\n print_simple GateCount testCirc\r\n print_simple Preview testCirc\r\n\r\n\r\n\r\n\r\n\r\n-- | Auxiliary function: the /W/-gate.\r\nw :: (Qubit, Qubit) -> Circ ()\r\n-- w xy = named_gate_at \"W\" xy\r\nw (xi,yi) = do\r\n _ <- box \"w\" (\\(xi, yi) -> do\r\n label (xi,yi) (\"x[i]\",\"y[i]\")\r\n gate_X_at xi `controlled` yi\r\n gate_X_at yi `controlled` xi\r\n hadamard_at yi `controlled` xi\r\n gate_X_at yi `controlled` xi\r\n gate_X_at xi `controlled` yi\r\n return (xi,yi)) (xi,yi)\r\n return ()\r\n\r\n-- | Testing function for 'w'.\r\ntest_w :: IO ()\r\ntest_w = do\r\n let testCirc = do\r\n xi <- qinit False \r\n yi <- qinit False\r\n w (xi, yi)\r\n print_simple GateCount testCirc\r\n print_simple Preview testCirc\r\n\r\n\r\n-- * Controlled Logic Operations\r\n\r\n\r\n-- | Applies a phase shift of φ\\/2 to the signed input register |φ〉.\r\n\r\n-- For c, bit locations are counted starting from 0 (least significant) to (length c - 2) (most significant)\r\n-- last c (or c !! (n-1)) is the sign bit\r\nqlsa_ControlledPhase :: [Qubit] -> Double -> Bool -> Circ ()\r\n-- qlsa_ControlledPhase c phi0 f = named_gate_at \"CPhase\" c\r\nqlsa_ControlledPhase c phi0 f = do\r\n _ <- (flip $ box (\"qlsa_ControlledPhase \" ++ (show phi0) ++ \" \" ++ (show f))) c $ \\c -> do\r\n with_ancilla $ \\a -> do -- ancilla is initialized to False\r\n if f then (qnot_at a) else return ()\r\n let signQubit = last c\r\n qnot_at a `controlled` signQubit\r\n for 0 (length c - 2) 1 $ \\ii -> do \r\n let theta = ( (2.0^(ii)) * phi0 / 2.0) -- Note the divide by 2\r\n -- The following three lines are equivalent\r\n expZt_at theta a `controlled` (c !! ii)\r\n -- a <- expZt theta a `controlled` (c !! ii); return ()\r\n -- qlsa_ControlledU (c !! ii, a) (expZt theta) False \r\n endfor\r\n qnot_at a `controlled` signQubit \r\n return c\r\n return ()\r\n\r\n\r\n-- | Applies a rotation of φ\\/2 to the signed input register |φ〉.\r\nqlsa_ControlledRotation :: ([Qubit], Qubit) -> Double -> Bool -> Circ ()\r\n-- qlsa_ControlledRotation ct phi0 f = named_gate_at \"CRotate\" ct\r\nqlsa_ControlledRotation (c, t) phi0 f = do\r\n _ <- (flip $ box (\"qlsa_ControlledRotation \" ++ (show phi0) ++ \" \" ++ (show f))) (c,t) $ \\(c,t) -> do\r\n if f then (qnot_at t) else return ()\r\n let signQubit = last c\r\n qnot_at t `controlled` signQubit\r\n for 0 (length c - 2) 1 $ \\ii -> do\r\n let theta = (2.0^(ii)) * phi0 / 2.0\r\n expYt_at theta t `controlled` (c !! ii)\r\n endfor\r\n qnot_at t `controlled` signQubit\r\n if f then (qnot_at t) else return ()\r\n return (c,t)\r\n return ()\r\n\r\n\r\n----------------------------------------------------------------------\r\n-- * Oracles\r\n\r\n-- | Map a 'QDouble' into an integer, understood as being scaled by\r\n-- the given factor. Take the factor and the size of the output\r\n-- register as parameter.\r\nmake_factor_rep :: Double -> Int -> QDouble -> Circ [Qubit]\r\nmake_factor_rep factor size p = do\r\n -- number of high bits of p\r\n let p_int_size = (xdouble_length p) - (xdouble_exponent p)\r\n -- get the required number of bits for doing the encoding\r\n let auxsize = max (size - 1) p_int_size\r\n -- do the operation:\r\n -- (1) build a QDouble from the factor: need (size-1) bits of integer part\r\n qfactor <- qinit $ fdouble_of_double (xdouble_exponent p) \r\n (auxsize + xdouble_exponent p) factor\r\n -- (2) scale p\r\n p_large <- qdouble_pad_to_extent (auxsize,- (xdouble_exponent p)) p\r\n -- (3) divide p by factor\r\n qreal_multiples <- unpack template_symb_slash_ p_large qfactor\r\n -- (4) get the floor of the result\r\n q_floor <- template_floor\r\n qmultiples <- q_floor qreal_multiples\r\n -- (5) set them in the right format (it has size elements)\r\n let (SInt tp bp) = qmultiples\r\n let new_p = (take (size - 1) $ reverse tp) ++ [bp]\r\n return new_p\r\n\r\n\r\n\r\n-- | Implements the oracle for the arbitrary state |/r/〉, using the\r\n-- Template Haskell implementation of 'calcRweights'.\r\ninline_oracle_r :: RunTimeParam -> Double -> Double -> ([Qubit],[Qubit],[Qubit]) -> Circ ([Qubit],[Qubit],[Qubit])\r\ninline_oracle_r rt factor_m factor_p = box (\"Or \" ++ (show factor_m) ++ \" \" ++ (show factor_p)) $ decompose_generic Toffoli $ \\(x',m',p') ->\r\n with_ancilla_init (fromIntegral $ nx rt :: FSignedInt) $ \\qnx -> \r\n with_ancilla_init (fromIntegral $ ny rt :: FSignedInt) $ \\qny -> \r\n with_ancilla_init (fdouble $ lx rt) $ \\qlx ->\r\n with_ancilla_init (fdouble $ ly rt) $ \\qly ->\r\n with_ancilla_init (fdouble $ k rt) $ \\qk ->\r\n with_ancilla_init (fdouble $ theta rt) $ \\qtheta ->\r\n with_ancilla_init (fdouble $ phi rt) $ \\qphi -> \r\n -- the x register is smaller than the size of a QSInt,\r\n -- and x is an unsigned integer: make up a positive\r\n -- sign and a pad\r\n \r\n with_ancilla_init False $ \\bx -> do\r\n with_ancilla_init (replicate (fixed_int_register_length - (n2 rt)) \r\n False) $ \\pad_x -> do\r\n \r\n let x = SInt (pad_x ++ (reverse x')) bx\r\n let f = classical_to_reversible $ \r\n \\(x,nx,ny,lx,ly,k,theta,phi) -> do \r\n (m,p) <- unpack Template.template_calcRweights \r\n x nx ny lx ly k theta phi\r\n new_p <- make_factor_rep factor_p (n4 rt) p\r\n new_m <- make_factor_rep factor_m (n4 rt) m\r\n return (new_m, new_p)\r\n f ((x,qnx,qny,qlx,qly,qk,qtheta,qphi),(m',p'))\r\n return (x',m',p')\r\n\r\n\r\n\r\n\r\n\r\n-- | Implements the oracle for the known state |/b/〉, using the\r\n-- Template Haskell implementation of 'getKnownWeights'.\r\ninline_oracle_b :: RunTimeParam -> Double -> Double -> ([Qubit],[Qubit],[Qubit]) -> Circ ([Qubit],[Qubit],[Qubit])\r\ninline_oracle_b rt factor_m factor_p = box (\"Ob \" ++ (show factor_m) ++ \" \" ++ (show factor_p)) $ decompose_generic Toffoli $ \\(x',m',p') -> \r\n -- Make ancillas for constant values\r\n \r\n with_ancilla_init (listpair_fmap fromIntegral $ scatteringnodes rt :: [(FDouble,FDouble)]) $ \\qscatteringnodes ->\r\n with_ancilla_init (fromIntegral $ ny rt :: FSignedInt) $ \\qny -> \r\n with_ancilla_init (fdouble $ lx rt) $ \\qlx ->\r\n with_ancilla_init (fdouble $ ly rt) $ \\qly ->\r\n with_ancilla_init (fdouble $ k rt) $ \\qk ->\r\n with_ancilla_init (fdouble $ theta rt) $ \\qtheta ->\r\n with_ancilla_init (fdouble $ e0 rt) $ \\qe0 ->\r\n with_ancilla_init (fromIntegral $ nx rt :: FSignedInt) $ \\qnx -> do\r\n\r\n -- the x register is smaller than the size of a QSInt,\r\n -- and x is an unsigned integer: make up a positive\r\n -- sign and a pad\r\n \r\n with_ancilla_init False $ \\bx -> do\r\n with_ancilla_init (replicate (fixed_int_register_length - (n2 rt)) \r\n False) $ \\pad_x -> do\r\n \r\n let x = SInt (pad_x ++ (reverse x')) bx\r\n \r\n let f = classical_to_reversible $ \r\n \\(y,nx,ny,scatteringnodes,lx,ly,k,theta,e0) -> do\r\n -- get some QSInt and QDouble\r\n (m,p) <- unpack Template.template_getKnownWeights \r\n y nx ny scatteringnodes lx ly k theta e0 7\r\n new_p <- make_factor_rep factor_p (n4 rt) p\r\n new_m <- make_factor_rep factor_m (n4 rt) m\r\n \r\n return (new_m, new_p)\r\n \r\n f ((x,qnx,qny,qscatteringnodes,qlx,qly,qk,qtheta,qe0),(m',p'))\r\n return (x',m',p')\r\n\r\n\r\n-- | Implementation of the oracle calculating the matrix /A/\r\n-- corresponding to the discretization of the scattering problem,\r\n-- using the Template Haskell implementation of\r\n-- 'getNodeValuesMoreOutputs'.\r\ninline_oracle_A :: RunTimeParam -> Double -> Int -> Bool -> ([Qubit],[Qubit],[Qubit]) -> Circ ([Qubit],[Qubit],[Qubit])\r\ninline_oracle_A rt factor band argflag = box (\"OA \" ++ (show band) ++ \" \" ++ (show argflag)) $ decompose_generic Toffoli $ \\(x',y',p') -> do\r\n\r\n let argflag' = if argflag then PTrue else PFalse\r\n \r\n -- Make ancillas for constant values\r\n \r\n with_ancilla_init (listpair_fmap fromIntegral $ scatteringnodes rt :: [(FDouble, FDouble)]) $ \\qscatteringnodes -> \r\n with_ancilla_init (fromIntegral $ ny rt :: FSignedInt) $ \\qny -> \r\n with_ancilla_init (fromRational $ toRational $ lx rt) $ \\qlx ->\r\n with_ancilla_init (fromRational $ toRational $ ly rt) $ \\qly ->\r\n with_ancilla_init (fromRational $ toRational $ k rt) $ \\qk ->\r\n with_ancilla_init (fromIntegral $ nx rt :: FSignedInt) $ \\qnx -> do\r\n\r\n -- the x register is smaller than the size of a QSInt,\r\n -- and x is an unsigned integer: make up a positive\r\n -- sign and a pad\r\n \r\n with_ancilla_init False $ \\bx -> do\r\n with_ancilla_init (replicate (fixed_int_register_length - (n2 rt))\r\n False) $ \\pad_x -> do\r\n \r\n let x = SInt (pad_x ++ (reverse x')) bx\r\n \r\n let f = classical_to_reversible $ \r\n \\(v,nx,ny,scatteringnodes,lx,ly,k) -> do\r\n -- get some QSInt and QDouble\r\n (y,p) <- unpack Template.template_getNodeValuesMoreOutputs\r\n v band nx ny scatteringnodes lx ly k argflag' 7\r\n \r\n new_p <- make_factor_rep factor (n4 rt) p \r\n \r\n -- set y in the correct format (it has n2 elements)\r\n -- we can assume that the sign is positive.\r\n -- we also assume that n2 < size of QSInt register\r\n let (SInt ty _) = y\r\n let new_y = (take (n2 rt) $ reverse ty)\r\n \r\n -- return the values in the right format.\r\n return (new_y,new_p)\r\n \r\n f ((x,qnx,qny,qscatteringnodes,qlx,qly,qk),(y',p'))\r\n \r\n return (x',y',p')\r\n \r\n\r\n-- | Encapsulate the inline oracles in Template Haskell into an object\r\n-- of type 'Oracle'.\r\ninline_oracle :: Oracle\r\ninline_oracle = Oracle {\r\n oracle_A = inline_oracle_A,\r\n oracle_b = inline_oracle_b,\r\n oracle_r = inline_oracle_r\r\n}\r\n", "meta": {"hexsha": "31937d630e85d9586a21d297c7fb1b29e03b2acf", "size": 36919, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Algorithms/QLS/QLS.hs", "max_stars_repo_name": "silky/quipper", "max_stars_repo_head_hexsha": "1ef6d031984923d8b7ded1c14f05db0995791633", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-07-28T07:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T02:51:59.000Z", "max_issues_repo_path": "Algorithms/QLS/QLS.hs", "max_issues_repo_name": "qbit-/quipper", "max_issues_repo_head_hexsha": "5adba47b53c50e348517a0b30637b8b959a40c0d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-11-15T04:27:40.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-28T09:17:08.000Z", "max_forks_repo_path": "Algorithms/QLS/QLS.hs", "max_forks_repo_name": "qbit-/quipper", "max_forks_repo_head_hexsha": "5adba47b53c50e348517a0b30637b8b959a40c0d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-12-31T21:26:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T13:10:17.000Z", "avg_line_length": 37.9045174538, "max_line_length": 142, "alphanum_fraction": 0.5430807985, "num_tokens": 10634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.3077011622540461}} {"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE QuasiQuotes #-}\n\nmodule Layers\n ( ForwardLayer(..)\n , OutputLayer(..)\n , ForwardNN(..)\n , BackwardLayer(..)\n , BackputLayer(..)\n , BackwardNN(..)\n , TrainBatch(..)\n , NElement(..)\n , (<~)\n , (~>)\n , forward\n , output\n , backward\n , backput\n , learnForward\n , learnBackward\n , learn\n , learnAll\n , predict\n , evaluate\n ) where\n\nimport Control.Arrow\nimport Control.Lens hiding ((<~))\nimport Data.String.Interpolate as S (i)\nimport Debug.Trace\nimport Numeric\nimport Numeric.LinearAlgebra\nimport Synapse\n\ntype Weight a = Matrix a\n\ntype Bias a = Vector a\n\ntype SignalX a = Matrix a\n\ntype SignalY a = Matrix a\n\ntype Diff a = Matrix a\n\ntype TeacherBatch a = Matrix a\n\ntype InputBatch a = Matrix a\n\nnewtype TrainBatch a =\n TrainBatch (TeacherBatch a, InputBatch a)\n deriving (Show)\n\ndata ForwardLayer a\n = AffineForward (Weight a) (Bias a)\n | SigmoidForward\n | ReLUForward\n | JoinedForwardLayer (ForwardLayer a) (ForwardLayer a)\n deriving (Show)\n\ninstance (Numeric a, Eq a) => Eq (ForwardLayer a) where\n AffineForward w b == AffineForward w' b' = w == w' && b == b'\n SigmoidForward == SigmoidForward = True\n ReLUForward == ReLUForward = True\n JoinedForwardLayer a b == JoinedForwardLayer a' b' = a == a' && b == b'\n _ == _ = False\n\ninfixl 4 ~>\n\n(~>) :: ForwardLayer a -> ForwardLayer a -> ForwardLayer a\na ~> (JoinedForwardLayer x y) = (a ~> x) ~> y\na ~> b = JoinedForwardLayer a b\n\ndata OutputLayer a =\n SoftmaxWithCrossForward\n deriving (Show)\n\ndata ForwardNN a =\n ForwardNN (ForwardLayer a) (OutputLayer a)\n deriving (Show)\n\ndata BackwardLayer a\n = AffineBackward (Weight a) (Bias a) (SignalX a)\n | SigmoidBackward (SignalY a)\n | ReLUBackward (SignalX a)\n | JoinedBackwardLayer (BackwardLayer a) (BackwardLayer a)\n deriving (Show)\n\ninstance (Numeric a, Eq a) => Eq (BackwardLayer a) where\n AffineBackward w b d == AffineBackward w' b' d' =\n w == w' && b == b' && d == d'\n SigmoidBackward y == SigmoidBackward y' = y == y'\n ReLUBackward x == ReLUBackward x' = x == x'\n JoinedBackwardLayer a b == JoinedBackwardLayer a' b' = a == a' && b == b'\n _ == _ = False\n\ninfixr 4 <~\n\n(<~) :: BackwardLayer a -> BackwardLayer a -> BackwardLayer a\n(JoinedBackwardLayer x y) <~ b = x <~ (y <~ b)\na <~ b = JoinedBackwardLayer a b\n\ndata BackputLayer a =\n SoftmaxWithCrossBackward (TeacherBatch a) (SignalY a)\n\ndata BackwardNN a =\n BackwardNN (BackwardLayer a) (BackputLayer a)\n\ntype NElement a = (Ord a, Floating a, Numeric a, Num (Vector a), Show a)\n\nforward ::\n NElement a => ForwardLayer a -> SignalX a -> (BackwardLayer a, SignalY a)\nforward (AffineForward w b) x = (AffineBackward w b x, affinem w b x)\nforward SigmoidForward x = (SigmoidBackward y, y)\n where\n y = sigmoidm x\nforward ReLUForward x = (ReLUBackward x, relum x)\nforward (JoinedForwardLayer a b) x0 = (a' <~ b', x2)\n where\n (a', x1) = forward a x0\n (b', x2) = forward b x1\n\nbackward ::\n NElement a => a -> BackwardLayer a -> Diff a -> (ForwardLayer a, Diff a)\nbackward rate (AffineBackward w b x) d =\n (AffineForward (w - scale rate w') (b - scale rate b'), x')\n where\n (x', w', b') = affinemBackward w x d\nbackward _ (SigmoidBackward y) d = (SigmoidForward, sigmoidBackward y d)\nbackward _ (ReLUBackward x) d = (ReLUForward, relumBackward x d)\nbackward r (JoinedBackwardLayer a b) d0 = (a' ~> b', d2)\n where\n (b', d1) = backward r b d0\n (a', d2) = backward r a d1\n\noutput ::\n NElement a\n => OutputLayer a\n -> TeacherBatch a\n -> SignalY a\n -> (BackputLayer a, a)\noutput SoftmaxWithCrossForward t y = (SoftmaxWithCrossBackward t y', loss)\n where\n (y', loss) = softmaxWithCross t y\n\nbackput :: NElement a => BackputLayer a -> (OutputLayer a, Diff a)\nbackput (SoftmaxWithCrossBackward t y) =\n (SoftmaxWithCrossForward, softmaxWithCrossBackward t y)\n\nlearnForward :: NElement a => ForwardNN a -> TrainBatch a -> (BackwardNN a, a)\nlearnForward (ForwardNN layers loss) (TrainBatch (t, x)) =\n result `seq` (BackwardNN layers' loss', result)\n where\n (layers', y) = forward layers x\n (loss', result) = output loss t y\n\nlearnBackward :: NElement a => a -> BackwardNN a -> ForwardNN a\nlearnBackward rate (BackwardNN layers loss) = ForwardNN layers' loss'\n where\n (loss', d) = backput loss\n (layers', _) = backward rate layers d\n\nlearn :: NElement a => a -> ForwardNN a -> TrainBatch a -> (ForwardNN a, a)\nlearn rate a = first (learnBackward rate) . learnForward a\n\nlearnAll ::\n NElement a => a -> ForwardNN a -> [TrainBatch a] -> (ForwardNN a, [a])\nlearnAll rate origin batches = ls `seq` (nn, ls)\n where\n (nn, ls) = foldr f (origin, []) batches\n f batch (a, ls) = ls `seq` second (~: ls) $ learn rate a batch\n x ~: xs = trace [i|[#{length xs + 1}/#{n}] #{show x}|] (x : xs)\n n = length batches\n\npredict :: NElement a => ForwardLayer a -> Vector a -> Int\npredict layers = maxIndex . flatten . snd . forward layers . asRow\n\nevaluate :: NElement a => ForwardLayer a -> [(Int, Vector a)] -> Double\nevaluate layers samples = fromIntegral nOk / fromIntegral (length samples)\n where\n nOk = length $ filter (uncurry (==)) results\n results = map (second $ predict layers) samples\n", "meta": {"hexsha": "d94cc7661d2cf4784c0aca3cc7707f36829b361c", "size": 5309, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Layers.hs", "max_stars_repo_name": "sawatani/simple_mnist", "max_stars_repo_head_hexsha": "3aa8f9ccaa9a3a58fed123a81e24ce7feab3e977", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Layers.hs", "max_issues_repo_name": "sawatani/simple_mnist", "max_issues_repo_head_hexsha": "3aa8f9ccaa9a3a58fed123a81e24ce7feab3e977", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Layers.hs", "max_forks_repo_name": "sawatani/simple_mnist", "max_forks_repo_head_hexsha": "3aa8f9ccaa9a3a58fed123a81e24ce7feab3e977", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0109289617, "max_line_length": 78, "alphanum_fraction": 0.649086457, "num_tokens": 1645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.3075730011937148}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport qualified Data.Text.IO as T\nimport qualified Data.Text as T\nimport Data.Text (Text)\nimport Data.Text.Encoding (encodeUtf8)\n\nimport qualified Data.ByteString.Lazy as B\nimport Data.ByteString.Lazy (ByteString)\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Vector as V\nimport Data.Vector (Vector)\nimport Data.Csv\nimport Data.Monoid\n\nimport Parser\nimport Type\n\nimport Control.Monad\nimport Control.Monad.Primitive\nimport System.Random.MWC\nimport Statistics.Distribution\nimport Statistics.Distribution.Laplace\n\ntype County a = Map Text a\ntype District a = Map Text (County a)\ntype FlatDistrict a = Map Text a\n\niteration :: Int\niteration = 1000\n\nmain :: IO ()\nmain = do\n raw <- B.readFile \"asset/sim_2.csv\"\n case parse raw of\n Left err -> putStrLn err\n Right rows -> do\n let nation = buildUp rows\n calculateNation nation\n calculateCounty nation\n calculateDistrict nation\n\ncalculateNation :: District (Vector Row) -> IO ()\ncalculateNation nation = do\n putStrLn \"全國平均就醫距離\"\n let header = V.fromList [encodeUtf8 \"全國\"] :: Vector Name\n let result = [NationResult (nationAvg nation)]\n B.writeFile \"result/original/nationwide.csv\" (encodeByName header result)\n\n putStrLn \"全國平均就醫距離 (added noise)\"\n forM_ [-9 .. 5] $ \\level -> do\n results <- replicateM iteration (nationAddNoise level nation)\n B.writeFile (\"result/pertubated/nationwide/2^\" <> show level <> \".csv\") (encodeByName header results)\n--\ncalculateCounty :: District (Vector Row) -> IO ()\ncalculateCounty nation = do\n putStrLn \"各縣市平均就醫距離\"\n let header = V.fromList (map encodeUtf8 (Map.keys nation)) :: Vector Name\n let avgs = fmap countyAvg nation\n let result = [CountyResult avgs]\n B.writeFile \"result/original/countywide.csv\" (encodeByName header result)\n\n withSystemRandom . asGenIO $ \\gen -> do\n putStrLn \"各縣市平均就醫距離 (added noise)\"\n forM_ [-4 .. 10] $ \\level -> do\n results <- replicateM iteration (countyAddNoise level nation gen)\n B.writeFile (\"result/pertubated/countywide/2^\" <> show level <> \".csv\") (encodeByName header results)\n\ncalculateDistrict :: District (Vector Row) -> IO ()\ncalculateDistrict nation = do\n let flattened = flatten nation\n putStrLn \"各鄉鎮市區的平均就醫距離\"\n let header = V.fromList $ map encodeUtf8 $ Map.keys flattened\n let result = [DistrictResult (flatten $ fmap (fmap districtAvg) nation)]\n B.writeFile \"result/original/districtwide.csv\" (encodeByName header result)\n\n putStrLn \"各鄉鎮市區的平均就醫距離 (added noise)\"\n\n withSystemRandom . asGenIO $ \\gen -> do\n forM_ [5 .. 20] $ \\level -> do\n results <- replicateM iteration (districtAddNoise level flattened gen)\n B.writeFile (\"result/pertubated/districtwide/2^\" <> show level <> \".csv\") (encodeByName header results)\n\n\nnationAddNoise :: Int -> District (Vector Row) -> IO NationResult\nnationAddNoise level nation = do\n let avg = nationAvg nation\n pertubated <- addNoise scale avg\n return (NationResult pertubated)\n where\n size = Map.foldl (\\s elem -> s + (Map.foldl (\\s vec -> s + V.length vec) 0 elem)) 0 nation\n eps = 2.0 ^^ level\n scale = 400000.0 / (fromIntegral size * eps)\n -- pertubated <- addNoise' scale (replicate iteration (nationwideAvg mapping))\n\ncountyAddNoise :: Int -> District (Vector Row) -> Gen (PrimState IO) -> IO CountyResult\ncountyAddNoise level nation gen = do\n pertubated <- mapM (\\county -> do\n let avg = countyAvg county\n noise <- genContVar (laplace 0 (scale county)) gen\n return (avg + noise)) nation\n return (CountyResult pertubated)\n\n where\n countySize = Map.foldl (\\s vec -> s + V.length vec) 0\n eps = 2.0 ^^ level\n scale county = 400000.0 / (fromIntegral (countySize county) * eps)\n\ndistrictAddNoise :: Int -> FlatDistrict (Vector Row) -> Gen (PrimState IO) -> IO DistrictResult\ndistrictAddNoise level flattened gen = do\n pertubated <- mapM (\\district -> do\n let avg = districtAvg district\n noise <- genContVar (laplace 0 (scale district)) gen\n return (avg + noise)) flattened\n return (DistrictResult pertubated)\n\n where\n districtSize = V.length -- Map.foldl (\\s vec -> s + V.length vec) 0\n eps = 2.0 ^^ level\n scale district = 400000.0 / (fromIntegral (districtSize district) * eps)\n\n\n\n\ndata NationResult = NationResult Double deriving (Show)\ndata CountyResult = CountyResult (County Double) deriving (Show)\ndata DistrictResult = DistrictResult (FlatDistrict Double) deriving (Show)\n\ninstance ToNamedRecord NationResult where\n toNamedRecord (NationResult value) = namedRecord\n [ (encodeUtf8 \"全國\") .= value ]\n\ninstance ToNamedRecord CountyResult where\n toNamedRecord (CountyResult value)\n = namedRecord (map (\\(key, val) -> (encodeUtf8 key) .= val) (Map.assocs value))\n\nflatten :: District a -> FlatDistrict a\nflatten = Map.fromList . concat . map fuseName . Map.assocs\n where\n fuseName :: (Text, County a) -> [(Text, a)]\n fuseName (countyName, county) = map (\\(districtName, distrct) -> (countyName <> districtName, distrct)) (Map.assocs county)\n\n\ninstance ToNamedRecord DistrictResult where\n toNamedRecord (DistrictResult nation)\n = namedRecord\n $ Map.elems\n $ Map.mapWithKey (\\name value -> encodeUtf8 name .= value)\n $ nation\n\ndistrictAvg :: Vector Row -> Double\ndistrictAvg = average . V.toList . fmap distance\n\ncountyAvg :: County (Vector Row) -> Double\ncountyAvg = average . concat . Map.elems . fmap (V.toList . fmap distance)\n -- average . Map.elems . fmap districtAvg\n -- Map.foldl (\\ acc distrct -> acc + districtAvg distrct) 0.0\n\nnationAvg :: District (Vector Row) -> Double\nnationAvg = average . concat . Map.elems . fmap (concat . Map.elems . fmap (V.toList . fmap distance))\n\nbuildUp :: Vector Row -> District (Vector Row)\nbuildUp = foldl insertCounty Map.empty\n where\n\n districtSingleton :: Row -> County (Vector Row)\n districtSingleton row = Map.singleton (snd (key row)) (V.singleton row)\n\n insertCounty :: District (Vector Row) -> Row -> District (Vector Row)\n insertCounty m row = Map.insertWith\n (insertDistrict row)\n (fst (key row)) -- key for TierCounty\n (districtSingleton row) -- key for TierCounty (which is TierDistrict)\n m\n\n insertDistrict :: Row -> County (Vector Row) -> County (Vector Row) -> County (Vector Row)\n insertDistrict row _ old = Map.insertWith\n (V.++)\n (snd (key row)) -- key for TierDistrict\n (V.singleton row) -- value for TierDistrict\n old\n\n key :: Row -> (Text, Text)\n key = T.splitAt 3 . townshipName . township . from\n\n townshipName :: Township -> Text\n townshipName (Township name _) = name\n\n\n--------------------------------------------------------------------------------\n-- Queries\n--------------------------------------------------------------------------------\n\naverage :: [Double] -> Double\naverage vec = sum vec / fromIntegral (length vec)\n\ndistance :: Row -> Double\ndistance row = sqrt ((fromX - toX) * (fromX - toX) + (fromY - toY) * (fromY - toY))\n where\n (fromX, fromY) = coord (from row)\n (toX , toY ) = coord (to row)\n\n--------------------------------------------------------------------------------\n-- Noise\n--------------------------------------------------------------------------------\n\nsampleLaplace :: Double -> IO Double\nsampleLaplace scale = withSystemRandom . asGenST $ genContVar (laplace 0 scale)\n\naddNoise :: Double -> Double -> IO Double\naddNoise scale x = do\n noise <- sampleLaplace scale\n return (x + noise)\n\n-- -- 研究問題\n--\n-- -- 1. 各鄉鎮市區的平均就醫距離\n-- -- 2. 各縣市的平均就醫距離\n-- -- 3. 全國的平均就醫距離\n--\n-- -- 距離上限: 400 公里\n", "meta": {"hexsha": "e868ab7344dba2352daf0c1c5ac321de3a343d0a", "size": 8159, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "banacorn/dp-trial", "max_stars_repo_head_hexsha": "bc4126f19e2aa25cb4d028a2cef3ad524a84c9ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-29T11:05:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-29T11:05:45.000Z", "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "banacorn/dp-trial", "max_issues_repo_head_hexsha": "bc4126f19e2aa25cb4d028a2cef3ad524a84c9ca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "banacorn/dp-trial", "max_forks_repo_head_hexsha": "bc4126f19e2aa25cb4d028a2cef3ad524a84c9ca", "max_forks_repo_licenses": ["BSD-3-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.2622222222, "max_line_length": 131, "alphanum_fraction": 0.6179678882, "num_tokens": 2119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.30629762558877877}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE DefaultSignatures #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PatternGuards #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances #-}\n-----------------------------------------------------------------------------\n-- |\n-- Copyright : (c) Edward Kmett 2010-2021\n-- License : BSD3\n-- Maintainer : ekmett@gmail.com\n-- Stability : experimental\n-- Portability : GHC only\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.AD.Mode\n (\n -- * AD modes\n Mode(..)\n , pattern KnownZero\n , pattern Auto\n ) where\n\nimport Numeric.Natural\nimport Data.Complex\nimport Data.Int\nimport Data.Ratio\nimport Data.Word\n\ninfixr 7 *^\ninfixl 7 ^*\ninfixr 7 ^/\n\nclass (Num t, Num (Scalar t)) => Mode t where\n type Scalar t\n type Scalar t = t\n\n -- | allowed to return False for items with a zero derivative, but we'll give more NaNs than strictly necessary\n isKnownConstant :: t -> Bool\n isKnownConstant _ = False\n\n asKnownConstant :: t -> Maybe (Scalar t)\n asKnownConstant _ = Nothing\n\n -- | allowed to return False for zero, but we give more NaN's than strictly necessary\n isKnownZero :: t -> Bool\n isKnownZero _ = False\n\n -- | Embed a constant\n auto :: Scalar t -> t\n default auto :: (Scalar t ~ t) => Scalar t -> t\n auto = id\n\n -- | Scalar-vector multiplication\n (*^) :: Scalar t -> t -> t\n a *^ b = auto a * b\n\n -- | Vector-scalar multiplication\n (^*) :: t -> Scalar t -> t\n a ^* b = a * auto b\n\n -- | Scalar division\n (^/) :: Fractional (Scalar t) => t -> Scalar t -> t\n a ^/ b = a ^* recip b\n\n -- |\n -- @'zero' = 'lift' 0@\n zero :: t\n zero = auto 0\n\npattern KnownZero :: Mode s => s\npattern KnownZero <- (isKnownZero -> True) where\n KnownZero = zero\n\npattern Auto :: Mode s => Scalar s -> s\npattern Auto n <- (asKnownConstant -> Just n) where\n Auto n = auto n\n\ninstance Mode Double where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Float where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Int where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Integer where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Int8 where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Int16 where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Int32 where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Int64 where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Natural where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Word where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Word8 where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Word16 where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Word32 where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Mode Word64 where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance RealFloat a => Mode (Complex a) where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n\ninstance Integral a => Mode (Ratio a) where\n isKnownConstant _ = True\n asKnownConstant = Just\n isKnownZero x = 0 == x\n (^/) = (/)\n", "meta": {"hexsha": "e9cb89693412931873fd4e5f7c741ef425fd5f40", "size": 4030, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/AD/Mode.hs", "max_stars_repo_name": "msakai/ad", "max_stars_repo_head_hexsha": "85aee3c6b4b621bab24c4379a88da1b5f0494d97", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 286, "max_stars_repo_stars_event_min_datetime": "2015-01-13T12:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T19:11:54.000Z", "max_issues_repo_path": "src/Numeric/AD/Mode.hs", "max_issues_repo_name": "msakai/ad", "max_issues_repo_head_hexsha": "85aee3c6b4b621bab24c4379a88da1b5f0494d97", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2015-03-15T02:22:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-19T18:26:25.000Z", "max_forks_repo_path": "src/Numeric/AD/Mode.hs", "max_forks_repo_name": "msakai/ad", "max_forks_repo_head_hexsha": "85aee3c6b4b621bab24c4379a88da1b5f0494d97", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2015-01-22T12:26:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T09:28:35.000Z", "avg_line_length": 22.2651933702, "max_line_length": 113, "alphanum_fraction": 0.6146401985, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5, "lm_q1q2_score": 0.30569098664707556}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-|\nModule : Grenade.Layers.Relu\nDescription : Rectifying linear unit layer\nCopyright : (c) Huw Campbell, 2016-2017\nLicense : BSD2\nStability : experimental\n-}\nmodule Grenade.Layers.Relu (\n Relu (..)\n ) where\n\nimport Data.Serialize\n\nimport GHC.TypeLits\nimport Grenade.Core\n\nimport qualified Numeric.LinearAlgebra.Static as LAS\n\n-- | A rectifying linear unit.\n-- A layer which can act between any shape of the same dimension, acting as a\n-- diode on every neuron individually.\ndata Relu = Relu\n deriving Show\n\ninstance UpdateLayer Relu where\n type Gradient Relu = ()\n runUpdate _ _ _ = Relu\n createRandom = return Relu\n\ninstance Serialize Relu where\n put _ = return ()\n get = return Relu\n\ninstance ( KnownNat i) => Layer Relu ('D1 i) ('D1 i) where\n type Tape Relu ('D1 i) ('D1 i) = S ('D1 i)\n\n runForwards _ (S1D y) = (S1D y, S1D (relu y))\n where\n relu = LAS.dvmap (\\a -> if a <= 0 then 0 else a)\n runBackwards _ (S1D y) (S1D dEdy) = ((), S1D (relu' y * dEdy))\n where\n relu' = LAS.dvmap (\\a -> if a <= 0 then 0 else 1)\n\ninstance (KnownNat i, KnownNat j) => Layer Relu ('D2 i j) ('D2 i j) where\n type Tape Relu ('D2 i j) ('D2 i j) = S ('D2 i j)\n\n runForwards _ (S2D y) = (S2D y, S2D (relu y))\n where\n relu = LAS.dmmap (\\a -> if a <= 0 then 0 else a)\n runBackwards _ (S2D y) (S2D dEdy) = ((), S2D (relu' y * dEdy))\n where\n relu' = LAS.dmmap (\\a -> if a <= 0 then 0 else 1)\n\ninstance (KnownNat i, KnownNat j, KnownNat k) => Layer Relu ('D3 i j k) ('D3 i j k) where\n\n type Tape Relu ('D3 i j k) ('D3 i j k) = S ('D3 i j k)\n\n runForwards _ (S3D y) = (S3D y, S3D (relu y))\n where\n relu = LAS.dmmap (\\a -> if a <= 0 then 0 else a)\n runBackwards _ (S3D y) (S3D dEdy) = ((), S3D (relu' y * dEdy))\n where\n relu' = LAS.dmmap (\\a -> if a <= 0 then 0 else 1)\n", "meta": {"hexsha": "3db4670fe4ba86b7f04d4ce4b256e821f0f42b6b", "size": 2014, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Relu.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1527, "max_stars_repo_stars_event_min_datetime": "2016-06-23T13:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T05:22:00.000Z", "max_issues_repo_path": "src/Grenade/Layers/Relu.hs", "max_issues_repo_name": "Alien-Inc/grenade", "max_issues_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 69, "max_issues_repo_issues_event_min_datetime": "2016-06-27T22:16:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-20T17:50:09.000Z", "max_forks_repo_path": "src/Grenade/Layers/Relu.hs", "max_forks_repo_name": "Alien-Inc/grenade", "max_forks_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2016-06-28T02:24:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:17:29.000Z", "avg_line_length": 29.6176470588, "max_line_length": 89, "alphanum_fraction": 0.5988083416, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.30531400561872174}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeFamilyDependencies #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE GADTs #-}\n{-# OPTIONS_GHC -Wwarn #-}\nmodule Language.Test where\n\nimport Control.Arrow\nimport Data.Complex\nimport Data.Proxy\nimport Type.Reflection\n\nimport GHC.TypeLits\n\ndata INat = Z | S INat\n\ndata family Sing :: k -> *\n\ndata instance Sing (n :: INat) where\n SZ :: Sing 'Z\n SS :: Sing n -> Sing ('S n)\n\nclass IsSing a where sing :: Sing a\ninstance IsSing 'Z where sing = SZ\ninstance IsSing n => IsSing ('S n) where sing = SS sing\ntype SINat (n :: INat) = Sing n\n\nnewtype Unit a = MkUnit () deriving Show\n\nunit :: Unit a\nunit = MkUnit ()\n\ntype family Prod (n :: INat) (a :: *) = r | r -> n a where\n Prod 'Z a = Unit a\n Prod ('S n) a = (a, Prod n a)\n\nfmapP' :: SINat n -> (a -> b) -> Prod n a -> Prod n b\nfmapP' SZ _ = const unit\nfmapP' (SS m) f = f{- ALLOCATE HERE -} *** fmapP' m f\n\nfmapPIx :: SINat n -> (Int -> a -> b) -> Int -> Prod n a -> Prod n b\nfmapPIx SZ _ _ = const unit\nfmapPIx (SS m) f k = f k *** fmapPIx m f (k+1)\n\nfmapP :: IsSing n => (a -> b) -> Prod n a -> Prod n b\nfmapP = fmapP' sing\n\ntype family Div2 (n :: INat) where\n Div2 'Z = 'Z\n Div2 ('S 'Z) = 'Z\n Div2 ('S ('S n)) = 'S (Div2 n)\n\ndiv2 :: SINat n -> SINat (Div2 n)\ndiv2 SZ = SZ\ndiv2 (SS SZ) = SZ\ndiv2 (SS (SS n)) = SS (div2 n)\n\nassocL :: (a, (b, c)) -> ((a, b), c)\nassocL (x, (y, z)) = ((x, y), z)\n\nred :: SINat n -> ((a, a) -> a) -> Prod n a -> Prod (Div2 n) a\nred SZ _ = id\nred (SS SZ) _ = snd\nred (SS (SS n)) f = assocL >>> f{- ALLOCATE HERE -} *** red n f\n\nfold :: SINat n -> ((a, a) -> a) -> a -> Prod n a -> a\nfold SZ _ z = const z\nfold (SS SZ) _ _ = fst\nfold n f z = red n f >>> fold (div2 n) f z\n\nreduce :: (IsSing n, Monoid a) => Prod n a -> a\nreduce = fold sing (uncurry mappend) mempty\n\ndata Fin (m :: INat) where\n FZ :: Fin ('S m)\n FS :: Fin m -> Fin ('S m)\n\ndata Le (n :: INat) (m :: INat) where\n LZ :: Le 'Z m\n LS :: Le n m -> Le ('S n) ('S m)\n\nclass (IsSing n, IsSing m) => IsLe (n :: INat) (m :: INat) where\n le :: Sing n -> Le n m\ninstance IsSing n => IsLe 'Z n where\n le SZ = LZ\ninstance IsLe n m => IsLe ('S n) ('S m) where\n le (SS n) = LS (le n)\n\nget' :: Le n m -> Prod ('S m) a -> a\nget' LZ = fst\nget' (LS n) = snd >>> get' n\n\nget :: IsLe n m => SINat n -> Prod ('S m) a -> a\nget n = get' (le n)\n\nzw' :: forall a b c (n :: INat). SINat n -> ((a, b) -> c) -> (Prod n a, Prod n b) -> Prod n c\nzw' SZ _ = const unit\nzw' (SS m) f = swap >>> f *** zw' m f\n\ntoNum :: forall (k :: INat) a. Num a => SINat k -> a\ntoNum SZ = 0\ntoNum (SS sm) = 1 + toNum sm\n\nexpn :: Float -> Float -> Complex Float -> Complex Float\nexpn n k c = cis (-2 * pi * k / n) * c {- multiply exponential -}\n\nadd :: (Complex Float, Complex Float) -> Complex Float\nadd = uncurry (+)\n\nsub :: (Complex Float, Complex Float) -> Complex Float\nsub = uncurry (-)\n\ntype family Add (n :: INat) (m :: INat) where\n Add 'Z n = n\n Add ('S n) m = 'S (Add n m)\n\naddn :: SINat n -> SINat m -> SINat (Add n m)\naddn SZ n = n\naddn (SS n) m = SS (addn n m)\n\ntype family Mul (n :: INat) (m :: INat) where\n Mul 'Z n = 'Z\n Mul ('S n) m = Add m (Mul n m)\n\nmul :: SINat n -> SINat m -> SINat (Mul n m)\nmul SZ _ = SZ\nmul (SS n) m = addn m (mul n m)\n\ntype family Pow2 (n :: INat) where\n Pow2 'Z = 'S 'Z\n Pow2 ('S n) = Add (Pow2 n) (Pow2 n)\n\npow2 :: SINat n -> SINat (Pow2 n)\npow2 SZ = SS SZ\npow2 (SS n) = addn (pow2 n) (pow2 n)\n\n-- Hack: proper way would be to traverse 'n' and 'm', but it is quite inefficient\n\nszr :: SINat n -> Add n 'Z :~: n\nszr SZ = Refl\nszr (SS n) = case szr n of\n Refl -> Refl\n\nssr :: SINat n -> SINat m -> Add n ('S m) :~: 'S (Add n m)\nssr SZ _ = Refl\nssr (SS n) m = case ssr n m of\n Refl -> Refl\n\naddComm :: SINat n -> SINat m -> Add n m :~: Add m n\naddComm SZ m = case szr m of Refl -> Refl -- unsafeCoerce Refl\naddComm (SS n) m = case (addComm n m, ssr m n) of\n (Refl, Refl) -> Refl\n\n--deinterleave\nsplit :: forall a (n :: INat). SINat n -> Prod (Add n n) a -> (Prod n a, Prod n a)\nsplit SZ = id &&& id\nsplit (SS n) =\n case addComm n (SS n) of\n Refl -> assocL >>> id *** split n >>> swap\n\nassocR :: ((a, b), c) -> (a, (b, c))\nassocR ((a, b), c) = (a, (b, c))\n\ncat :: SINat n -> (Prod n a, Prod m a) -> Prod (Add n m) a\ncat SZ = snd\ncat (SS x) = assocR >>> id *** cat x\n\nfromINat :: forall a n. Num a => SINat n -> a\nfromINat SZ = 0\nfromINat (SS x) = 1 + fromINat x\n\nfromTo :: forall a n. Num a => SINat n -> Prod n a\nfromTo = go 0\n\ngo :: forall a n. Num a => a -> SINat n -> Prod n a\ngo _ SZ = unit\ngo n (SS m) = (n, go (1 + n) m)\n\ndft :: SINat n -> Prod (Pow2 n) (Complex Float) -> Prod (Pow2 n) (Complex Float)\ndft SZ = id\ndft (SS x)\n = split p2x >>>\n dft x {-EVENS-} *** dft x {-ODDS-} >>>\n id *** fmapPIx p2x (expn p2sx . fromIntegral) 0 {- Multiply by exponential -} >>>\n zw' p2x add {- Left side -} &&& zw' p2x sub {- right side -} >>>\n cat p2x\n where\n p2x = pow2 x\n p2sx :: Float\n p2sx = fromIntegral $ ((2 ^ (fromINat (SS x) :: Integer)) :: Integer)\n\n--------------------------------------------------------------------------------\n-- FFT BELOW -------------------------------------------------------------------\n\n-- PRIM FUNCTIONS --------------------------------------------------------------\n\n-- baseFFT is one of your PRIM funcs: you can copy from some online FFT implementation: e.g. Rosetta Code\n\nbaseFFT :: RealFloat a => [Complex a] -> [Complex a]\nbaseFFT [] = []\nbaseFFT [x] = [x]\nbaseFFT xs = zipWith (+) ys ts ++ zipWith (-) ys ts\n where n = length xs\n ys = baseFFT evens\n zs = baseFFT odds\n (evens, odds) = splitList xs\n ts = zipWith (\\z k -> (exp' k n) * z) zs [0::Integer ..]\n\nexp' :: (Floating a1, Integral a2, Integral a3) => a2 -> a3 -> Complex a1\nexp' k n = cis $ -2 * pi * (fromIntegral k) / (fromIntegral n)\n\nsplitList :: [a] -> ([a], [a])\nsplitList [] = ([], [])\nsplitList [x] = ([x], [])\nsplitList (x:y:xs) = (x:xt, y:yt) where (xt, yt) = splitList xs\n\naddPadding :: Num a => SINat n -> [a] -> [a]\naddPadding sz l = l ++ replicate (padding $ length l) 0\n where\n padding k = 2 ^ (max ((fromINat sz) :: Integer) (ceiling (logBase 2 $ fromIntegral k :: Double))) - k\n\nconcatenate :: ([a], [a]) -> [a]\nconcatenate = uncurry (++)\n\n{- Below should be your prim functions -}\nmulExp :: (RealFloat a1, Integral a3) =>\n a3 -> Int -> [Complex a1] -> [Complex a1]\nmulExp p2sx i l = zipWith (\\k z -> exp' k (p2sx * fromIntegral len) * z) [i * len ..] l\n where\n len = length l\naddc :: ([Complex Float], [Complex Float]) -> [Complex Float]\naddc = uncurry $ zipWith (+)\nsubc :: ([Complex Float], [Complex Float]) -> [Complex Float]\nsubc = uncurry $ zipWith (-)\n\n-- END PRIM FUNCTIONS ----------------------------------------------------------\n\n-- ARROW DEFINITIONS -----------------------------------------------------------\n--- Should not change, except types\n\ntype family Tree (n :: INat) (a :: *) where\n Tree 'Z a = a\n Tree ('S n) a = (Tree n a, Tree n a)\n\nsplitL :: SINat m -> [Complex Float] -> Tree m [Complex Float]\nsplitL SZ = id\nsplitL (SS n) = splitList >>> splitL n *** splitL n\n\nmerge :: forall (n :: INat). SINat n -> Tree n [Complex Float] -> [Complex Float]\nmerge SZ = id {- same: just concatenate all using a Prim -}\nmerge (SS n) = merge n *** merge n >>> concatenate\n\nfmapTIx :: SINat n -> ((Int, [Complex Float]) -> [Complex Float]) -> Int -> Tree n [Complex Float] -> Tree n [Complex Float]\nfmapTIx SZ f k = (\\v -> f (k, v))\nfmapTIx (SS x) f k = fmapTIx x f k *** fmapTIx x f (k + (2 ^ (fromINat x :: Integer)))\n\nswap :: ((a,b), (c, d)) -> ((a, c), (b, d))\nswap = ((fst >>> fst) &&& (snd >>> fst)) &&&\n ((fst >>> snd) &&& (snd >>> snd))\n\nzwT :: SINat n -> (([Complex Float],[Complex Float]) -> [Complex Float])\n -> (Tree n [Complex Float], Tree n [Complex Float]) -> Tree n [Complex Float]\nzwT SZ f = f\nzwT (SS x) f = swap >>> zwT x f *** zwT x f\n\nfft :: SINat n -> Tree n [Complex Float] -> Tree n [Complex Float]\nfft SZ = baseFFT\nfft (SS x)\n = fft x {-EVENS-} *** fft x {-ODDS-} >>>\n id *** fmapTIx x (uncurry $ mulExp p2sx) 0 {- Multiply by exponential -} >>>\n zwT x addc {- Left side -} &&& zwT x subc {- right side -}\n where\n p2sx :: Integer\n p2sx = 2 ^ (fromINat (SS x) :: Integer)\n\nfastFourierR :: forall (n :: INat). SINat n -> [Complex Float] -> [Complex Float]\nfastFourierR cores = addPadding cores >>> splitL cores >>> fft cores >>> merge cores\n\n---------------------------------------------------------------------------------\n-- UTILITY FUNCTIONS\n\nfastFourier :: forall n. (KnownNat n, IsSing (FromNat n))\n => [Complex Float] -> [Complex Float]\nfastFourier = fastFourierR (sing :: SINat (FromNat n))\n\nfft8core :: [Complex Float] -> [Complex Float]\nfft8core = fastFourier @3\nfft16core :: [Complex Float] -> [Complex Float]\nfft16core = fastFourier @4\n\ntype family ToNat (i :: INat) :: Nat where\n ToNat 'Z = 0\n ToNat ('S n) = 1 + ToNat n\n\ntype family FromNat (i :: Nat) :: INat where\n FromNat 0 = 'Z\n FromNat n = 'S (FromNat (n-1))\n\n\n\nfmapT :: SINat n -> (a -> b) -> Tree n a -> Tree n b\nfmapT SZ f = f\nfmapT (SS x) f = fmapT x f *** fmapT x f\n\n\ndata SDict a where\n SDict :: Show a => SDict a\n\ngetDict :: Show a => SINat n -> Proxy a -> SDict (Tree n a)\ngetDict SZ _ = SDict\ngetDict (SS n) p = case getDict n p of\n SDict -> SDict\n\ntest :: SINat n -> Tree n Int -> String\ntest n = case getDict n (Proxy :: Proxy Int) of\n SDict -> show\n\ntest2 :: Show (Tree n Int) => SINat n -> Tree n Int -> Bool\ntest2 _ _ = False\n\ntest3 :: SINat n -> Tree n Int -> Bool\ntest3 n t = case getDict n (Proxy :: Proxy Int) of\n SDict -> test2 n t\n", "meta": {"hexsha": "899d9d6303908b10dee4286f2afd711bb11f9521", "size": 10077, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Language/Test.hs", "max_stars_repo_name": "session-arr/session-arr", "max_stars_repo_head_hexsha": "5dbde7e18176c493767f9c84d8d900f7a5637c66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Language/Test.hs", "max_issues_repo_name": "session-arr/session-arr", "max_issues_repo_head_hexsha": "5dbde7e18176c493767f9c84d8d900f7a5637c66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-07T16:57:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-15T07:58:54.000Z", "max_forks_repo_path": "src/Language/Test.hs", "max_forks_repo_name": "dcastrop/SAlg", "max_forks_repo_head_hexsha": "cfe0fade336b6e34b79eeb5eecc653c9a6926b87", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-18T11:16:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T11:16:16.000Z", "avg_line_length": 30.0805970149, "max_line_length": 124, "alphanum_fraction": 0.5438126427, "num_tokens": 3442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.304706914625794}} {"text": "{-# OPTIONS_GHC -Wall #-}\n\n{-# LANGUAGE QuasiQuotes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.Sundials.CVode.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--\n-- \n--\n-- A simple example:\n--\n-- <>\n--\n-- @\n-- import Numeric.Sundials.CVode.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-----------------------------------------------------------------------------\nmodule Numeric.Sundials.CVode.ODE ( odeSolve\n , odeSolveV\n , odeSolveVWith\n , odeSolveVWith'\n , odeSolveRootVWith'\n , ODEMethod(..)\n , StepControl(..)\n , SolverResult(..)\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)\n\nimport qualified Data.Vector.Storable as V\n\nimport Data.Coerce (coerce)\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport Numeric.LinearAlgebra.Devel (createVector)\n\nimport Numeric.LinearAlgebra.HMatrix (Vector, Matrix, toList, rows,\n cols, toLists, size, reshape)\n\nimport Numeric.Sundials.Arkode (cV_ADAMS, cV_BDF,\n getDataFromContents, putDataInContents,\n vectorToC, cV_SUCCESS, cV_ROOT_RETURN)\nimport qualified Numeric.Sundials.Arkode as T\nimport Numeric.Sundials.ODEOpts (ODEOpts(..), Jacobian, SundialsDiagnostics(..))\n\n\nC.context (C.baseCtx <> C.vecCtx <> C.funCtx <> T.sunCtx)\n\nC.include \"\"\nC.include \"\"\nC.include \"\"\nC.include \"\" -- prototypes for CVODE 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 CVDls 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 = ADAMS\n | BDF\n\ngetMethod :: ODEMethod -> Int\ngetMethod (ADAMS) = cV_ADAMS\ngetMethod (BDF) = cV_BDF\n\ngetJacobian :: ODEMethod -> Maybe Jacobian\ngetJacobian _ = Nothing\n\n-- | A version of 'odeSolveVWith' with reasonable default step control.\nodeSolveV\n :: ODEMethod\n -> Maybe Double -- ^ 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\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 BDF (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, 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 -> (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 , relTol = error \"relTol\"\n , absTols = error \"absTol\"\n , initStep = error \"initStep\"\n , maxFail = 10\n }\n\nodeSolveVWith' ::\n ODEOpts\n -> ODEMethod\n -> StepControl\n -> Maybe Double -- ^ 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 -> (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 =\n 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 x y f _ptr = do\n -- Convert the pointer we get from C (y) to a vector, and then\n -- apply the user-supplied function.\n fImm <- fun x <$> getDataFromContents dim y\n -- Fill in the provided pointer with the resulting vector.\n putDataInContents fImm dim f\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 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.CVode.ODE: Jacobian not defined\"\n Just jacI -> do j <- jacI t <$> getDataFromContents dim 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\n SUNMatrix A = NULL; /* empty matrix for linear solver */\n SUNLinearSolver LS = NULL; /* empty linear solver object */\n void *cvode_mem = NULL; /* empty CVODE memory structure */\n realtype t;\n long int nst, nfe, nsetups, nje, nfeLS, nni, ncfn, netf, nge;\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 cvode_mem = CVodeCreate($(int method), CV_NEWTON);\n if (check_flag((void *)cvode_mem, \"CVodeCreate\", 0)) return(1);\n\n /* Call CVodeInit to initialize the integrator memory and specify the\n * user's right hand side function in y'=f(t,y), the inital time T0, and\n * the initial dependent variable vector y. */\n flag = CVodeInit(cvode_mem, $fun:(int (* funIO) (double t, SunVector y[], SunVector dydt[], void * params)), T0, y);\n if (check_flag(&flag, \"CVodeInit\", 1)) return(1);\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 flag = CVodeSetMinStep(cvode_mem, $(double minStep_));\n if (check_flag(&flag, \"CVodeSetMinStep\", 1)) return 1;\n flag = CVodeSetMaxNumSteps(cvode_mem, $(long int maxNumSteps_));\n if (check_flag(&flag, \"CVodeSetMaxNumSteps\", 1)) return 1;\n flag = CVodeSetMaxErrTestFails(cvode_mem, $(int maxErrTestFails));\n if (check_flag(&flag, \"CVodeSetMaxErrTestFails\", 1)) return 1;\n\n /* Call CVodeSVtolerances to specify the scalar relative tolerance\n * and vector absolute tolerances */\n flag = CVodeSVtolerances(cvode_mem, $(double rTol), tv);\n if (check_flag(&flag, \"CVodeSVtolerances\", 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 = CVDlsSetLinearSolver(cvode_mem, LS, A);\n if (check_flag(&flag, \"CVDlsSetLinearSolver\", 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 = CVodeSetInitStep(cvode_mem, $(double ss));\n if (check_flag(&flag, \"CVodeSetInitStep\", 1)) return 1;\n }\n\n /* Set the Jacobian if there is one */\n if ($(int isJac)) {\n flag = CVDlsSetJacFn(cvode_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, \"CVDlsSetJacFn\", 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 /* Main time-stepping loop: calls CVode to perform the integration */\n /* Stops when the final time has been reached */\n for (i = 1; i < $(int nTs); i++) {\n\n flag = CVode(cvode_mem, ($vec-ptr:(double *ts))[i], y, &t, CV_NORMAL); /* call integrator */\n if (check_flag(&flag, \"CVode 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 = CVodeGetNumSteps(cvode_mem, &nst);\n check_flag(&flag, \"CVodeGetNumSteps\", 1);\n ($vec-ptr:(long int *diagMut))[0] = nst;\n\n /* FIXME */\n ($vec-ptr:(long int *diagMut))[1] = 0;\n\n flag = CVodeGetNumRhsEvals(cvode_mem, &nfe);\n check_flag(&flag, \"CVodeGetNumRhsEvals\", 1);\n ($vec-ptr:(long int *diagMut))[2] = nfe;\n /* FIXME */\n ($vec-ptr:(long int *diagMut))[3] = 0;\n\n flag = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups);\n check_flag(&flag, \"CVodeGetNumLinSolvSetups\", 1);\n ($vec-ptr:(long int *diagMut))[4] = nsetups;\n\n flag = CVodeGetNumErrTestFails(cvode_mem, &netf);\n check_flag(&flag, \"CVodeGetNumErrTestFails\", 1);\n ($vec-ptr:(long int *diagMut))[5] = netf;\n\n flag = CVodeGetNumNonlinSolvIters(cvode_mem, &nni);\n check_flag(&flag, \"CVodeGetNumNonlinSolvIters\", 1);\n ($vec-ptr:(long int *diagMut))[6] = nni;\n\n flag = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);\n check_flag(&flag, \"CVodeGetNumNonlinSolvConvFails\", 1);\n ($vec-ptr:(long int *diagMut))[7] = ncfn;\n\n flag = CVDlsGetNumJacEvals(cvode_mem, &nje);\n check_flag(&flag, \"CVDlsGetNumJacEvals\", 1);\n ($vec-ptr:(long int *diagMut))[8] = ncfn;\n\n flag = CVDlsGetNumRhsEvals(cvode_mem, &nfeLS);\n check_flag(&flag, \"CVDlsGetNumRhsEvals\", 1);\n ($vec-ptr:(long int *diagMut))[9] = ncfn;\n\n /* Clean up and return */\n\n N_VDestroy(y); /* Free y vector */\n N_VDestroy(tv); /* Free tv vector */\n CVodeFree(&cvode_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\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 -> CInt -- ^ FIXME\n -> (CDouble -> V.Vector CDouble -> V.Vector CDouble) -- ^ FIXME\n -> V.Vector CDouble -- ^ Desired solution times\n -> SolverResult V.Vector V.Vector CInt CDouble\nsolveOdeC' maxErrTestFails maxNumSteps_ minStep_ method initStepSize\n jacH (aTols, rTol) fun f0 nr g ts =\n 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.\n -- 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 -- Convert the pointer we get from C (y) to a vector, and then\n -- apply the user-supplied function.\n fImm <- fun t <$> getDataFromContents dim y\n -- Fill in the provided pointer with the resulting vector.\n putDataInContents fImm dim f\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 let nrPre = fromIntegral nr\n gResults :: V.Vector CInt <- createVector nrPre\n gResMut <- V.thaw gResults\n tRoot :: V.Vector CDouble <- createVector 1\n tRootMut <- V.thaw tRoot\n\n let gIO :: CDouble -> Ptr T.SunVector -> Ptr CDouble -> Ptr () -> IO CInt\n gIO x y f _ptr = do\n -- Convert the pointer we get from C (y) to a vector, and then\n -- apply the user-supplied function.\n gImm <- g x <$> getDataFromContents dim y\n -- Fill in the provided pointer with the resulting vector.\n vectorToC gImm nrPre f\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 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.CVode.ODE: Jacobian not defined\"\n Just jacI -> do j <- jacI t <$> getDataFromContents dim 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 flagr; /* root finding flag */\n\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\n SUNMatrix A = NULL; /* empty matrix for linear solver */\n SUNLinearSolver LS = NULL; /* empty linear solver object */\n void *cvode_mem = NULL; /* empty CVODE memory structure */\n realtype t;\n long int nst, nfe, nsetups, nje, nfeLS, nni, ncfn, netf, nge;\n\n realtype tout;\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 cvode_mem = CVodeCreate($(int method), CV_NEWTON);\n if (check_flag((void *)cvode_mem, \"CVodeCreate\", 0)) return(1);\n\n /* Call CVodeInit to initialize the integrator memory and specify the\n * user's right hand side function in y'=f(t,y), the inital time T0, and\n * the initial dependent variable vector y. */\n flag = CVodeInit(cvode_mem, $fun:(int (* funIO) (double t, SunVector y[], SunVector dydt[], void * params)), T0, y);\n if (check_flag(&flag, \"CVodeInit\", 1)) return(1);\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 flag = CVodeSetMinStep(cvode_mem, $(double minStep_));\n if (check_flag(&flag, \"CVodeSetMinStep\", 1)) return 1;\n flag = CVodeSetMaxNumSteps(cvode_mem, $(long int maxNumSteps_));\n if (check_flag(&flag, \"CVodeSetMaxNumSteps\", 1)) return 1;\n flag = CVodeSetMaxErrTestFails(cvode_mem, $(int maxErrTestFails));\n if (check_flag(&flag, \"CVodeSetMaxErrTestFails\", 1)) return 1;\n\n /* Call CVodeSVtolerances to specify the scalar relative tolerance\n * and vector absolute tolerances */\n flag = CVodeSVtolerances(cvode_mem, $(double rTol), tv);\n if (check_flag(&flag, \"CVodeSVtolerances\", 1)) return(1);\n\n /* Call CVodeRootInit to specify the root function g with nr components */\n flag = CVodeRootInit(cvode_mem, $(int nr), $fun:(int (* gIO) (double t, SunVector y[], double gout[], void * params)));\n\n if (check_flag(&flag, \"CVodeRootInit\", 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 = CVDlsSetLinearSolver(cvode_mem, LS, A);\n if (check_flag(&flag, \"CVDlsSetLinearSolver\", 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 = CVodeSetInitStep(cvode_mem, $(double ss));\n if (check_flag(&flag, \"CVodeSetInitStep\", 1)) return 1;\n }\n\n /* Set the Jacobian if there is one */\n if ($(int isJac)) {\n flag = CVDlsSetJacFn(cvode_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, \"CVDlsSetJacFn\", 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 /* Main time-stepping loop: calls CVode to perform the integration */\n /* Stops when the final time has been reached */\n for (i = 1; i < $(int nTs); i++) {\n\n flag = CVode(cvode_mem, ($vec-ptr:(double *ts))[i], y, &t, CV_NORMAL); /* call integrator */\n if (check_flag(&flag, \"CVode 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 if (flag == CV_ROOT_RETURN) {\n flagr = CVodeGetRootInfo(cvode_mem, ($vec-ptr:(int *gResMut)));\n if (check_flag(&flagr, \"CVodeGetRootInfo\", 1)) return(1);\n ($vec-ptr:(double *tRootMut))[0] = t;\n flagr = flag;\n break;\n }\n }\n\n /* Get some final statistics on how the solve progressed */\n\n flag = CVodeGetNumSteps(cvode_mem, &nst);\n check_flag(&flag, \"CVodeGetNumSteps\", 1);\n ($vec-ptr:(long int *diagMut))[0] = nst;\n\n /* FIXME */\n ($vec-ptr:(long int *diagMut))[1] = 0;\n\n flag = CVodeGetNumRhsEvals(cvode_mem, &nfe);\n check_flag(&flag, \"CVodeGetNumRhsEvals\", 1);\n ($vec-ptr:(long int *diagMut))[2] = nfe;\n /* FIXME */\n ($vec-ptr:(long int *diagMut))[3] = 0;\n\n flag = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups);\n check_flag(&flag, \"CVodeGetNumLinSolvSetups\", 1);\n ($vec-ptr:(long int *diagMut))[4] = nsetups;\n\n flag = CVodeGetNumErrTestFails(cvode_mem, &netf);\n check_flag(&flag, \"CVodeGetNumErrTestFails\", 1);\n ($vec-ptr:(long int *diagMut))[5] = netf;\n\n flag = CVodeGetNumNonlinSolvIters(cvode_mem, &nni);\n check_flag(&flag, \"CVodeGetNumNonlinSolvIters\", 1);\n ($vec-ptr:(long int *diagMut))[6] = nni;\n\n flag = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);\n check_flag(&flag, \"CVodeGetNumNonlinSolvConvFails\", 1);\n ($vec-ptr:(long int *diagMut))[7] = ncfn;\n\n flag = CVDlsGetNumJacEvals(cvode_mem, &nje);\n check_flag(&flag, \"CVDlsGetNumJacEvals\", 1);\n ($vec-ptr:(long int *diagMut))[8] = ncfn;\n\n flag = CVDlsGetNumRhsEvals(cvode_mem, &nfeLS);\n check_flag(&flag, \"CVDlsGetNumRhsEvals\", 1);\n ($vec-ptr:(long int *diagMut))[9] = ncfn;\n\n /* Clean up and return */\n\n N_VDestroy(y); /* Free y vector */\n N_VDestroy(tv); /* Free tv vector */\n CVodeFree(&cvode_mem); /* Free integrator memory */\n SUNLinSolFree(LS); /* Free linear solver */\n SUNMatDestroy(A); /* Free A matrix */\n\n if (flag == CV_SUCCESS && flagr == CV_ROOT_RETURN) {\n return CV_ROOT_RETURN;\n }\n else {\n return flag;\n }\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 t <- V.freeze tRootMut\n rs <- V.freeze gResMut\n let f r | r == cV_SUCCESS = SolverSuccess m d\n | r == cV_ROOT_RETURN = SolverRoot (t V.!0) rs m d\n | otherwise = SolverError m res\n return $ f $ fromIntegral res\n\ndata SolverResult f g a b =\n SolverError (f b) a -- ^ Partial results and error code\n | SolverSuccess (f b) SundialsDiagnostics -- ^ Results and diagnostics\n | SolverRoot b (g a) (f b) SundialsDiagnostics -- ^ Time at which the root was found, the root itself and the\n -- results and diagnostics. NB the final result will be at the time\n -- at which the root was found not as specified by the times given\n -- to the solver.\n deriving Show\n\nodeSolveRootVWith' ::\n ODEOpts\n -> ODEMethod\n -> StepControl\n -> Maybe Double -- ^ 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 -> (Double -> V.Vector Double -> V.Vector Double) -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> V.Vector Double -- ^ Initial conditions\n -> Int -- ^ Dimension of the range of the roots function\n -> (Double -> V.Vector Double -> V.Vector Double) -- ^ Roots function\n -> V.Vector Double -- ^ Desired solution times\n -> SolverResult Matrix Vector Int Double\nodeSolveRootVWith' opts method control initStepSize f y0 is gg 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) (fromIntegral is) (coerce gg) (coerce tt) of\n SolverError v c -> SolverError (reshape l (coerce v)) (fromIntegral c)\n SolverSuccess v d -> SolverSuccess (reshape l (coerce v)) d\n SolverRoot t rs v d -> SolverRoot (coerce t) (V.map fromIntegral rs) (reshape l (coerce v)) d\n where\n l = size y0\n scise (X aTol rTol) = coerce (V.replicate l aTol, rTol)\n scise (X' aTol rTol) = coerce (V.replicate l aTol, rTol)\n scise (XX' aTol rTol yScale _yDotScale) = coerce (V.replicate l aTol, yScale * rTol)\n -- FIXME; Should we check that the length of ss is correct?\n scise (ScXX' aTol rTol yScale _yDotScale ss) = coerce (V.map (* aTol) ss, yScale * rTol)\n jacH = fmap (\\g t v -> matrixToSunMatrix $ g (coerce t) (coerce v)) $\n getJacobian method\n matrixToSunMatrix m = T.SunMatrix { T.rows = nr, T.cols = nc, T.vals = vs }\n where\n nr = fromIntegral $ rows m\n nc = fromIntegral $ cols m\n -- FIXME: efficiency\n vs = V.fromList $ map coerce $ concat $ toLists m\n\n-- | 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": "5fd306ef5f911b96c6cf05ec323ea2f266e3bbca", "size": 40124, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Sundials/CVode/ODE.hs", "max_stars_repo_name": "steinitznavican/hmatrix-sundials", "max_stars_repo_head_hexsha": "2f2a0722926522861928a5531a88bdac1dfe9c9a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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/CVode/ODE.hs", "max_issues_repo_name": "steinitznavican/hmatrix-sundials", "max_issues_repo_head_hexsha": "2f2a0722926522861928a5531a88bdac1dfe9c9a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/CVode/ODE.hs", "max_forks_repo_name": "steinitznavican/hmatrix-sundials", "max_forks_repo_head_hexsha": "2f2a0722926522861928a5531a88bdac1dfe9c9a", "max_forks_repo_licenses": ["BSD-3-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.5977301387, "max_line_length": 310, "alphanum_fraction": 0.5003239956, "num_tokens": 9882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3033028244009829}} {"text": "{-# LANGUAGE DataKinds #-}\nmodule CannyEdgeIllusoryContour where\n\nimport Control.Monad as M\nimport Control.Monad.IO.Class\nimport Data.Array.Repa as R\nimport Data.Array.Unboxed as AU\nimport Data.Binary\nimport Data.ByteString as BS\nimport Data.Complex\nimport Data.List as L\nimport DFT.Plan\nimport FokkerPlanck.DomainChange\nimport FokkerPlanck.MonteCarlo\nimport FokkerPlanck.Pinwheel\nimport GHC.Word\nimport Image.IO\nimport Image.Transform\nimport Linear.V2\nimport OpenCV as CV hiding (Z)\nimport STC\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Text.Printf\nimport Types\nimport Utils.Array\nimport Utils.Parallel hiding ((.|))\nimport Utils.Time\n\n\nmain = do\n args <- getArgs\n let (numPointStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:taoStr:numTrailStr:maxTrailStr:theta0FreqsStr:thetaFreqsStr:scale0FreqsStr:scaleFreqsStr:histFileName:histFileNameEndPoint:numIterationStr:numIterationEndPointStr:writeSourceFlagStr:cutoffRadiusEndPointStr:cutoffRadiusStr:reversalFactorStr:inputImgPath:threshold1Str:threshold2Str:writeSegmentsFlagStr:writeEndPointFlagStr:minSegLenStr:useFFTWWisdomFlagStr:fftwWisdomFileName:numThreadStr:_) =\n args\n numPoint = read numPointStr :: Int\n numOrientation = read numOrientationStr :: Int\n numScale = read numScaleStr :: Int\n thetaSigma = read thetaSigmaStr :: Double\n scaleSigma = read scaleSigmaStr :: Double\n maxScale = read maxScaleStr :: Double\n tao = read taoStr :: Double\n numTrail = read numTrailStr :: Int\n maxTrail = read maxTrailStr :: Int\n theta0Freq = read theta0FreqsStr :: Double\n theta0Freqs = [-theta0Freq .. theta0Freq]\n thetaFreq = read thetaFreqsStr :: Double\n thetaFreqs = [-thetaFreq .. thetaFreq]\n scale0Freq = read scale0FreqsStr :: Double\n scaleFreq = read scaleFreqsStr :: Double\n scale0Freqs = [-scale0Freq .. scale0Freq]\n scaleFreqs = [-scaleFreq .. scaleFreq]\n numIteration = read numIterationStr :: Int\n numIterationEndPoint = read numIterationEndPointStr :: Int\n writeSourceFlag = read writeSourceFlagStr :: Bool\n cutoffRadiusEndPoint = read cutoffRadiusEndPointStr :: Int\n cutoffRadius = read cutoffRadiusStr :: Int\n reversalFactor = read reversalFactorStr :: Double\n threshold1 = read threshold1Str :: Double\n threshold2 = read threshold2Str :: Double\n minSegLen = read minSegLenStr :: Int\n writeSegmentsFlag = read writeSegmentsFlagStr :: Bool\n writeEndPointFlag = read writeEndPointFlagStr :: Bool\n minimumPixelDist = 1 :: Int\n useFFTWWisdomFlag = read useFFTWWisdomFlagStr :: Bool\n numThread = read numThreadStr :: Int\n folderPath = \"output/test/CannyEdgeIllusoryContour\"\n histFilePath = folderPath histFileName\n histFilePathEndPoint = folderPath histFileNameEndPoint\n edgeFilePath = folderPath (takeBaseName inputImgPath L.++ \"_edge.png\")\n segmentsFilePath =\n folderPath (takeBaseName inputImgPath L.++ \"_segments.dat\")\n endPointFilePath =\n folderPath \n (printf\n \"%s_EndPoint_%d_%d_%d_%d_%.2f_%f.dat\"\n (takeBaseName inputImgPath)\n (numPoint * minimumPixelDist)\n (round thetaFreq :: Int)\n (round tao :: Int)\n cutoffRadiusEndPoint\n thetaSigma\n reversalFactor)\n fftwWisdomFilePath = folderPath fftwWisdomFileName\n createDirectoryIfMissing True folderPath\n copyFile inputImgPath (folderPath takeFileName inputImgPath)\n -- Find edges using Canny dege detector (Opencv)\n img <-\n (exceptError . coerceMat . imdecode ImreadUnchanged) <$>\n BS.readFile inputImgPath :: IO (Mat ('S '[ 'D, 'D]) 'D ('S GHC.Word.Word8))\n let [cols, rows] = miShape . matInfo $ img\n n = numPoint - cutoffRadiusEndPoint - 1 -- make sure that there is a zero wrap\n (w, h) =\n if rows > cols\n then ( n\n , round $ fromIntegral cols * fromIntegral n / fromIntegral rows)\n else ( round $ fromIntegral rows * fromIntegral n / fromIntegral cols\n , n)\n resizedImg =\n exceptError .\n resize\n (ResizeAbs . toSize $ V2 (fromIntegral w) (fromIntegral h))\n InterCubic $\n img\n edge =\n exceptError . canny threshold1 threshold2 (Just 3) CannyNormL2 $\n resizedImg\n edgeRepa =\n pad [numPoint, numPoint, 1] 0 .\n normalizeValueRange (0, 1) . R.map fromIntegral . toRepa $\n edge\n plotImageRepa edgeFilePath . ImageRepa 8 . computeS $ edgeRepa\n edgeRepa <- (\\(ImageRepa _ img) -> img) <$> readImageRepa edgeFilePath False\n doesEndPointFileExist <- doesFileExist endPointFilePath\n endPointArray <-\n if doesEndPointFileExist && (not writeEndPointFlag)\n then do\n printCurrentTime \"Read endpoint from file.\"\n readRepaArray endPointFilePath\n else do\n printCurrentTime \"Start computing endpoint...\"\n -- find segments for normalization:\n -- two adjacent non-zero-valued points are connected\n patchNormMethod <-\n if writeSegmentsFlag\n then do\n printCurrentTime \"Start computing segments...\"\n let nonzerorPoints =\n createIndex2D .\n L.map fst . L.filter (\\(_, v) -> v /= 0) . AU.assocs $\n (AU.listArray ((0, 0), (numPoint - 1, numPoint - 1)) .\n R.toList $\n edgeRepa :: AU.Array (Int, Int) Double)\n segments =\n L.map\n (L.map\n (\\(a, b) ->\n (a * minimumPixelDist, b * minimumPixelDist))) .\n L.filter (\\xs -> L.length xs >= minSegLen) .\n pointCluster\n (connectionMatrixP\n (ParallelParams numThread 1)\n 1\n nonzerorPoints) $\n nonzerorPoints\n encodeFile segmentsFilePath segments\n removePathForcibly (folderPath \"segments\")\n createDirectoryIfMissing True (folderPath \"segments\")\n M.zipWithM_\n (\\i ->\n plotImageRepa\n (folderPath \"segments\" (printf \"Cluster%03d.png\" i)) .\n ImageRepa 8)\n [1 :: Int ..] .\n cluster2Array\n (numPoint * minimumPixelDist)\n (numPoint * minimumPixelDist) $\n segments\n printCurrentTime \"Done computing segments.\"\n return . PowerMethodConnection $ segments\n else do\n printCurrentTime \"Read segments from files.\"\n PowerMethodConnection <$> decodeFile segmentsFilePath\n -- Compute the Green's function\n let numPointEndPoint = minimumPixelDist * numPoint\n maxScaleEndPoint = 1.00000000001\n flag <- doesFileExist histFilePathEndPoint\n radialArr <-\n if flag\n then do\n printCurrentTime \"Read endpoint filter histogram from files.\"\n R.map magnitude . getNormalizedHistogramArr <$>\n decodeFile histFilePathEndPoint\n else do\n printCurrentTime\n \"Couldn't find a Green's function data. Start simulation...\"\n solveMonteCarloR2Z2T0S0Radial\n numThread\n numTrail\n maxTrail\n numPointEndPoint\n numPointEndPoint\n thetaSigma\n 0.0\n maxScaleEndPoint\n tao\n theta0Freqs\n thetaFreqs\n [0]\n [0]\n histFilePathEndPoint\n (emptyHistogram\n [ (round . sqrt . fromIntegral $\n 2 * (div numPointEndPoint 2) ^ 2)\n , 1\n , L.length theta0Freqs\n , 1\n , L.length thetaFreqs\n ]\n 0)\n arrR2Z2T0S0 <-\n computeUnboxedP $\n computeR2Z2T0S0ArrayRadial\n (pinwheelHollowNonzeronCenter 12)\n (cutoff cutoffRadiusEndPoint radialArr)\n numPointEndPoint\n numPointEndPoint\n 1\n maxScaleEndPoint\n thetaFreqs\n [0]\n theta0Freqs\n [0]\n plan <-\n makeR2Z2T0S0Plan\n emptyPlan\n useFFTWWisdomFlag\n fftwWisdomFilePath\n arrR2Z2T0S0\n -- Compute initial eigenvector and bias\n -- increase the distance between pixels to aovid aliasing\n let resizedEdgeRepa =\n R.traverse\n edgeRepa\n (const (Z :. numPointEndPoint :. numPointEndPoint)) $ \\f (Z :. i :. j) ->\n if mod i minimumPixelDist == 0 && mod j minimumPixelDist == 0\n then f (Z :. (0 :: Int) :. (div i minimumPixelDist) :.\n (div j minimumPixelDist))\n else 0\n bias =\n computeBiasR2T0S0FromRepa\n numPointEndPoint\n numPointEndPoint\n (L.length theta0Freqs)\n 1\n resizedEdgeRepa\n eigenVec =\n computeInitialEigenVectorR2T0S0FromRepa\n numPointEndPoint\n numPointEndPoint\n (L.length theta0Freqs)\n 1\n (L.length thetaFreqs)\n 1\n resizedEdgeRepa\n plotImageRepa\n (folderPath takeBaseName inputImgPath L.++ \"_resizedEdge.png\") .\n ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n resizedEdgeRepa\n endPointSource <-\n computeS . R.zipWith (*) bias <$>\n powerMethodR2Z2T0S0Reversal\n plan\n folderPath\n numPointEndPoint\n numPointEndPoint\n numOrientation\n thetaFreqs\n theta0Freqs\n 1\n [0]\n [0]\n 0\n arrR2Z2T0S0\n patchNormMethod\n numIterationEndPoint\n writeSourceFlag\n (printf\n \"_%d_%d_%d_%d_%.2f_%f_%s_EndPoint\"\n (numPoint * minimumPixelDist)\n (round thetaFreq :: Int)\n (round tao :: Int)\n cutoffRadiusEndPoint\n thetaSigma\n reversalFactor\n (takeBaseName inputImgPath))\n 0.5\n reversalFactor\n bias\n eigenVec\n writeRepaArray endPointFilePath endPointSource\n return endPointSource\n print \"done\"\n\n", "meta": {"hexsha": "318aaae84c5b0b3907ad86ade96b626727cef255", "size": 11206, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/CannyEdgeIllusoryContour/CannyEdgeIllusoryContour.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/CannyEdgeIllusoryContour/CannyEdgeIllusoryContour.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/CannyEdgeIllusoryContour/CannyEdgeIllusoryContour.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.3192982456, "max_line_length": 482, "alphanum_fraction": 0.5592539711, "num_tokens": 2579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.3014743871616994}}